Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,56 @@ rogitproxy serves an HTTP status page on port 80 (tsnet) showing the
requesting user's granted repos and usage examples. It also serves
`/debug/` via tsweb.Debugger (metrics, pprof, etc.).

## Read-only GitHub API proxy

When GitHub App auth is enabled, rogitproxy also proxies read-only GitHub
API requests with no client credentials, so sandboxed tools can read PRs,
issues, comments, reviews, checks, commit statuses, and GitHub Actions runs
and logs for the repos they have `pull` grants on. URLs are laid out like
GitHub Enterprise Server:

REST: http://rogitproxy.your-tailnet.ts.net/api/v3/repos/org/repo/...
GraphQL: http://rogitproxy.your-tailnet.ts.net/api/graphql

Both are served over plain HTTP on port 80 and over HTTPS on port 443 using
the tailnet's TLS certificate (no MITM or custom root certs needed).

Safety is layered:

* Each upstream request uses a GitHub App installation token downscoped to
read-only permissions (`actions`, `checks`, `contents`, `issues`,
`metadata`, `pull_requests`, `statuses`) and to the requested repo (REST)
or the caller's granted repos in one org (GraphQL).
* REST: only `GET` and `HEAD` under `/api/v3/repos/{owner}/{repo}/`, which
requires a `pull` grant on that repo.
* GraphQL: only `query` operations; mutations and subscriptions are rejected.
The token's org is taken from the `owner` variable if present.
* Client `Authorization` and `Cookie` headers are dropped. Redirects (e.g.
Actions log downloads) are followed server-side without the token.
* `https://api.github.com/` URLs in JSON bodies and `Link` headers are
rewritten to point back at the proxy, so pagination works.

The GitHub App must have been granted the read permissions above, and each
org installation must accept them.

### Clients

The gh CLI only speaks HTTPS to Enterprise hosts. Point it at the proxy
(gh requires a token to be set, but its value is ignored):

export GH_HOST=rogitproxy.your-tailnet.ts.net GH_ENTERPRISE_TOKEN=unused
gh pr checks 123
gh run view 456 --log-failed

Inside a checkout cloned from `git://rogitproxy.your-tailnet.ts.net/...`,
gh detects the repo from the remote. Elsewhere, pass
`-R rogitproxy.your-tailnet.ts.net/org/repo` or set `GH_REPO`.

For go-github, use
`github.NewClient(nil).WithEnterpriseURLs("http://rogitproxy.your-tailnet.ts.net/api/v3/", "")`.
For curl and scripts, swap `https://api.github.com` for
`http://rogitproxy.your-tailnet.ts.net/api/v3`.

## Only read-only operations

Only `git-upload-pack` (the read-only git protocol command) is permitted.
Expand Down
107 changes: 105 additions & 2 deletions github.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import (
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"

"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/google/go-github/v84/github"
"github.com/tailscale/setec/client/setec"
)

Expand Down Expand Up @@ -52,6 +54,8 @@ func GitHubAppTransport(ctx context.Context, setecURL string, setecDo func(*http
base: http.DefaultTransport,
appsTr: appsTr,
orgTr: make(map[string]*ghinstallation.Transport),
orgID: make(map[string]int64),
scoped: make(map[string]*ghinstallation.Transport),
}

return mt, nil
Expand All @@ -65,8 +69,10 @@ type multiOrgTransport struct {
base http.RoundTripper
appsTr *ghinstallation.AppsTransport

mu sync.RWMutex
orgTr map[string]*ghinstallation.Transport // lowercase org -> transport
mu sync.RWMutex
orgTr map[string]*ghinstallation.Transport // lowercase org -> transport
orgID map[string]int64 // lowercase org -> installation ID
scoped map[string]*ghinstallation.Transport // scopedKey -> read-only scoped transport
}

func (t *multiOrgTransport) RoundTrip(req *http.Request) (*http.Response, error) {
Expand Down Expand Up @@ -119,6 +125,7 @@ func (t *multiOrgTransport) transportForOrg(ctx context.Context, org string) (*g
}
itr = ghinstallation.NewFromAppsTransport(t.appsTr, installID)
t.mu.Lock()
t.orgID[org] = installID
// Only set if we didn't lose the race
if existing, ok := t.orgTr[org]; !ok {
t.orgTr[org] = itr
Expand All @@ -129,6 +136,101 @@ func (t *multiOrgTransport) transportForOrg(ctx context.Context, org string) (*g
return itr, nil
}

// installationIDForOrg returns the GitHub App installation ID for the
// given lowercase org, discovering it via the GitHub API on cache miss.
func (t *multiOrgTransport) installationIDForOrg(ctx context.Context, org string) (int64, error) {
t.mu.RLock()
id, ok := t.orgID[org]
t.mu.RUnlock()
if ok {
return id, nil
}
id, err := t.findInstallationForOrg(ctx, org)
if err != nil {
return 0, err
}
t.mu.Lock()
t.orgID[org] = id
t.mu.Unlock()
return id, nil
}

// apiReadPermissions are the read-only permissions requested for
// downscoped installation tokens used by the GitHub API proxy. They
// cover what a read-only collaborator can see on the website: code,
// Actions runs and logs, checks, commit statuses, issues, and pull
// requests (including comments and reviews).
//
// The GitHub App itself must have been granted at least these
// permissions, or token creation fails.
func apiReadPermissions() *github.InstallationPermissions {
read := github.Ptr("read")
return &github.InstallationPermissions{
Actions: read,
Checks: read,
Contents: read,
Issues: read,
Metadata: read,
PullRequests: read,
Statuses: read,
}
}

// scopedToken returns a GitHub App installation token for the given
// lowercase org that has only read-only permissions (see
// apiReadPermissions) and, if repos is non-empty, can only access the
// named repos (bare repo names without the org prefix).
//
// Tokens are cached and refreshed by ghinstallation per distinct
// (installation, repo set) pair.
func (t *multiOrgTransport) scopedToken(ctx context.Context, org string, repos []string) (string, error) {
installID, err := t.installationIDForOrg(ctx, org)
if err != nil {
return "", err
}
repos = normalizeRepoNames(repos)
key := scopedKey(installID, repos)

t.mu.RLock()
itr, ok := t.scoped[key]
t.mu.RUnlock()
if !ok {
itr = ghinstallation.NewFromAppsTransport(t.appsTr, installID)
itr.InstallationTokenOptions = &github.InstallationTokenOptions{
Repositories: repos,
Permissions: apiReadPermissions(),
}
t.mu.Lock()
if existing, ok := t.scoped[key]; ok {
itr = existing
} else {
t.scoped[key] = itr
}
t.mu.Unlock()
}
return itr.Token(ctx)
}

// normalizeRepoNames returns a sorted, deduplicated, lowercased copy
// of repos.
func normalizeRepoNames(repos []string) []string {
if len(repos) == 0 {
return nil
}
ret := make([]string, len(repos))
for i, r := range repos {
ret[i] = strings.ToLower(r)
}
slices.Sort(ret)
return slices.Compact(ret)
}

// scopedKey returns the scoped token cache key for the given
// installation ID and normalized repo names.
func scopedKey(installID int64, repos []string) string {
return fmt.Sprintf("%d:%s", installID, strings.Join(repos, ","))
}

// findInstallationForOrg calls GET /orgs/{org}/installation using the
// App JWT to discover the installation ID for the given org.
func (t *multiOrgTransport) findInstallationForOrg(ctx context.Context, org string) (int64, error) {
Expand Down Expand Up @@ -203,6 +305,7 @@ func (t *multiOrgTransport) discoverAllInstallations(ctx context.Context) (int,

t.mu.Lock()
t.orgTr[org] = itr
t.orgID[org] = inst.ID
t.mu.Unlock()
}
return len(installations), nil
Expand Down
11 changes: 11 additions & 0 deletions github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,14 @@ func TestOrgFromPath(t *testing.T) {
}
}
}

func TestScopedKey(t *testing.T) {
a := scopedKey(42, normalizeRepoNames([]string{"Corp", "tailscale", "corp"}))
b := scopedKey(42, normalizeRepoNames([]string{"tailscale", "corp"}))
if a != b || a != "42:corp,tailscale" {
t.Errorf("keys = %q, %q; want both %q", a, b, "42:corp,tailscale")
}
if got := scopedKey(42, normalizeRepoNames(nil)); got != "42:" {
t.Errorf("unscoped key = %q; want %q", got, "42:")
}
}
Loading
Loading