diff --git a/docs/cli/run.md b/docs/cli/run.md index d5d3644e10..0bfbef15a9 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -532,6 +532,16 @@ The run stops before setup when: For the exact errors and fixes, see [Self-Hosted GitLab Instances](../guides/getting-started/configuring-gitlab.md#self-hosted-gitlab-instances). For the credential contract, see [GitLab Role-Credential Contract](../contributing/gitlab-role-credentials.md). +## GitHub servers other than github.com + +When `GITHUB_SERVER_URL` names a GitHub server other than github.com, such as GitHub Enterprise Server or a GitHub-compatible API, `fullsend run` points the sandbox's GitHub access at that server. The Actions runner sets `GITHUB_SERVER_URL` for every job, so no configuration is required. On github.com or when the variable is unset, nothing changes. + +- **Provider profiles.** Every imported provider profile that issues `GH_TOKEN` also gets an endpoint for the server's host and port. Each one is cloned from one of the profile's `api.github.com` or `github.com` endpoints, keeping its protocol, access and enforcement. GraphQL moves to `/api/graphql`, where GitHub Enterprise Server serves it. The clones leave out the github.com endpoint's `ports` and `allowed_ips`. If `api.github.com` and `github.com` specify different access for the same protocol and path, the clone takes the read-only one. Endpoints the profile already names for the server are not added again, and source files are never modified. As with GitLab, the run stops if an imported provider profile uses YAML merge keys, alias keys, duplicate keys or more than one document. +- **Sandbox `.env`.** The runner writes `GH_HOST` (the server's host, plus `:port` when it is not 443) and `GH_ENTERPRISE_TOKEN="${GH_TOKEN}"`. On such a host, `gh` reads its token from `GH_ENTERPRISE_TOKEN`, not `GH_TOKEN`. `GH_ENTERPRISE_TOKEN` holds the same OpenShell placeholder as `GH_TOKEN`, so the real token still never enters the sandbox. Both are runner-owned, so `env.sandbox` cannot override them. +- **OIDC.** The gateway and OpenAI WIF routes also accept the server's own host and port as the Actions token service (`ACTIONS_ID_TOKEN_REQUEST_URL`). An inference gateway reached this way must trust that server's OIDC issuer. + +The server URL follows the rule the GitHub API client uses: `https`, no userinfo, path, query or fragment. A URL that breaks this rule leaves the run on github.com. GHE.com (`*.ghe.com`) is not bound: `gh` calls `api.` there and reads `GH_TOKEN`. + ## GitHub Packages credentials On GitHub Actions, `fullsend run` copies the pre-mint `GH_TOKEN` (the job's workflow token) to diff --git a/docs/normative/sandbox-env/v1/env-references.schema.json b/docs/normative/sandbox-env/v1/env-references.schema.json index fafa20e109..c2f10f3929 100644 --- a/docs/normative/sandbox-env/v1/env-references.schema.json +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -280,6 +280,14 @@ "const": "FULLSEND_TRACE_ID", "description": "trace-ID injection succeeds; the run warns and continues when it fails" }, + { + "const": "GH_ENTERPRISE_TOKEN", + "description": "GITHUB_SERVER_URL points to a GitHub server other than github.com; it carries the same GH_TOKEN placeholder, since gh reads only GH_ENTERPRISE_TOKEN on such a host" + }, + { + "const": "GH_HOST", + "description": "GITHUB_SERVER_URL points to a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API)" + }, { "const": "TIRITH_FAIL_ON", "description": "security.sandbox_hooks.tirith.fail_on is set; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode" diff --git a/internal/cli/env_manifest_collector_test.go b/internal/cli/env_manifest_collector_test.go index bc28de3ddf..6f6a2cb9ca 100644 --- a/internal/cli/env_manifest_collector_test.go +++ b/internal/cli/env_manifest_collector_test.go @@ -62,6 +62,8 @@ var sandboxEnvGates = map[string]string{ "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)", "FULLSEND_FETCH_TOKEN": "the runtime fetch service is enabled (ADR 0038)", "FULLSEND_TRACE_ID": "trace-ID injection succeeds; the run warns and continues when it fails", + "GH_ENTERPRISE_TOKEN": "GITHUB_SERVER_URL points to a GitHub server other than github.com; it carries the same GH_TOKEN placeholder, since gh reads only GH_ENTERPRISE_TOKEN on such a host", + "GH_HOST": "GITHUB_SERVER_URL points to a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API)", "TIRITH_FAIL_ON": "security.sandbox_hooks.tirith.fail_on is set; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", "TIRITH_REQUIRED": "Tirith scanning is required (security.sandbox_hooks.tirith.enabled, default true); only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", "FULLSEND_EGRESS_ALLOWLIST": "an SSRF egress allowlist is configured, including the auto-merged forge egress entry; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", @@ -108,6 +110,8 @@ func TestEnvManifestCollector(t *testing.T) { "FULLSEND_SLUG", "FULLSEND_TIMEOUT_MINUTES", "FULLSEND_TRACE_ID", + "GH_ENTERPRISE_TOKEN", + "GH_HOST", "TIRITH_FAIL_ON", "TIRITH_REQUIRED", "TRACEPARENT", @@ -483,7 +487,12 @@ func bootstrapEnvExportKeys(t *testing.T, gated bool) map[string]bool { captureDir := envManifestCaptureDir(envManifestOpenshell(t)) h := &harness.Harness{Role: envManifestAgentName} var fetch []fetchServiceEnv + // GH_HOST is gated on the run's GitHub server, read from the host + // environment; pin it so the manifest does not depend on where the + // tests run. + t.Setenv("GITHUB_SERVER_URL", "") if gated { + t.Setenv("GITHUB_SERVER_URL", "https://ghes.example.com") schemaFile := filepath.Join(t.TempDir(), "output-schema.json") require.NoError(t, os.WriteFile(schemaFile, []byte(`{"type":"object"}`), 0o644)) h.Slug = envManifestAgentName + "-slug" diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go new file mode 100644 index 0000000000..f75601c926 --- /dev/null +++ b/internal/cli/github_profile.go @@ -0,0 +1,277 @@ +package cli + +import ( + "bytes" + "fmt" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/resolve" +) + +// githubTokenEnvVar is the credential the stock GitHub providers +// (fullsend-github, fullsend-github-ro, the agents' github-code) hand to the +// sandbox as an OpenShell placeholder. +const githubTokenEnvVar = "GH_TOKEN" + +// githubPublicHosts are the github.com API and web hosts the stock GitHub +// profiles name. A configured GitHub host other than github.com gets an +// endpoint cloned from each of these. +var githubPublicHosts = map[string]bool{"api.github.com": true, "github.com": true} + +// githubForgeHostPort returns the host and port of the GitHub server this run +// is configured for (GITHUB_SERVER_URL), or ("", "") when the run is on +// github.com. The URL must pass config.GitHubServerBaseURL, the rule the API +// client and the allowlist use, so the profiles and gh never name a server the +// rest of the run does not: an http, userinfo, path or query URL leaves the +// run on github.com here too. GHE.com (*.ghe.com) is left alone as well: gh +// calls api. there and reads GH_TOKEN, which this binding does not model. +func githubForgeHostPort(getenv func(string) string) (host string, port int) { + base := config.GitHubServerBaseURL(getenv("GITHUB_SERVER_URL")) + if base == "" { + return "", 0 + } + // GitHubServerBaseURL returns "https://" + a host that url.Parse + // already accepted, so this parse cannot fail. + u, _ := url.Parse(base) + h := u.Hostname() + if h == "ghe.com" || strings.HasSuffix(h, ".ghe.com") { + return "", 0 + } + port = 443 + if p, err := strconv.Atoi(u.Port()); err == nil { + port = p + } + return h, port +} + +// githubForgeSandboxEnvLines returns the sandbox .env lines that point gh at +// a GitHub server other than github.com: GH_HOST names it, and +// GH_ENTERPRISE_TOKEN carries the same value as GH_TOKEN, because gh reads +// only GH_ENTERPRISE_TOKEN for a host other than github.com. In the sandbox +// GH_TOKEN is an OpenShell placeholder, and the proxy substitutes a +// placeholder by value wherever it appears in a request to an endpoint of the +// profile that issued it, so the copy needs no credential of its own and the +// real token never enters the sandbox. No lines on github.com. +func githubForgeSandboxEnvLines(getenv func(string) string) []string { + host, port := githubForgeHostPort(getenv) + if host == "" { + return nil + } + if err := validateForgeDestination(host, port); err != nil { + return nil + } + // gh takes GH_HOST as an authority: an IPv6 literal needs its brackets, + // with or without a port. + ghHost := host + if port != 443 { + ghHost = net.JoinHostPort(host, strconv.Itoa(port)) + } else if strings.Contains(host, ":") { + ghHost = "[" + host + "]" + } + // A plain export in the form the runtime .env loader expands + // (internal/runtime/env_data.go takes $NAME and ${NAME}, not ${NAME:-x}) + // and the env manifest collector reads. An unset GH_TOKEN leaves + // GH_ENTERPRISE_TOKEN empty, which gh treats as unset. + return []string{ + fmt.Sprintf("export GH_HOST='%s'", ghHost), + `export GH_ENTERPRISE_TOKEN="${GH_TOKEN}"`, + } +} + +// bindGitHubForgeHost returns profiles with the configured GitHub server +// (a GitHub Enterprise Server or another GitHub-compatible API) added to +// every profile that issues the GH_TOKEN credential, the GitHub analogue of +// bindGitLabForgeHost. +// +// OpenShell resolves a credential placeholder only at the endpoints of the +// profile that issued it, and the stock GitHub profiles name only +// api.github.com and github.com, so on any other host the sandbox's gh +// calls were denied. For each of the profile's github.com endpoints, an +// endpoint for host:port is added with the same protocol, access level and +// enforcement. A GraphQL endpoint's path /graphql becomes /api/graphql, where +// GitHub Enterprise Server serves GraphQL; the REST API needs no path, since +// it sits under /api/v3 on the same host. Profiles that already name host:port, +// that do not issue GH_TOKEN, or that name no github.com endpoint are +// returned unchanged, and source files are never modified. host == "" +// (github.com) returns profiles unchanged. The returned cleanup is never nil. +func bindGitHubForgeHost(profiles []resolve.ResolvedProfile, host string, port int) ([]resolve.ResolvedProfile, func(), error) { + noop := func() {} + if host == "" { + return profiles, noop, nil + } + if err := validateForgeDestination(host, port); err != nil { + return nil, noop, err + } + var tmpDir string + cleanup := func() { + if tmpDir != "" { + os.RemoveAll(tmpDir) + } + } + out := make([]resolve.ResolvedProfile, len(profiles)) + copy(out, profiles) + for i, rp := range out { + data, err := os.ReadFile(rp.LocalPath) + if err != nil { + cleanup() + return nil, noop, fmt.Errorf("reading profile %q: %w", rp.ID, err) + } + patched, changed, err := addGitHubForgeEndpoints(data, host, port) + if err != nil { + cleanup() + return nil, noop, fmt.Errorf("adding GitHub server to profile %q: %w", rp.ID, err) + } + if !changed { + continue + } + if tmpDir == "" { + if tmpDir, err = os.MkdirTemp("", "fullsend-github-bound-profile-*"); err != nil { + return nil, noop, fmt.Errorf("creating temp dir for GitHub profiles: %w", err) + } + } + path := filepath.Join(tmpDir, fmt.Sprintf("%d.yaml", i)) + if err := os.WriteFile(path, patched, 0o644); err != nil { + cleanup() + return nil, noop, fmt.Errorf("writing profile %q: %w", rp.ID, err) + } + out[i].LocalPath = path + } + return out, cleanup, nil +} + +// bindGitHubForgeHostBytes applies bindGitHubForgeHost to one profile held in +// memory (an embedded scaffold profile). It returns data unchanged on +// github.com and for a profile it leaves alone. +func bindGitHubForgeHostBytes(data []byte, getenv func(string) string) ([]byte, error) { + host, port := githubForgeHostPort(getenv) + if host == "" { + return data, nil + } + if err := validateForgeDestination(host, port); err != nil { + return nil, err + } + patched, _, err := addGitHubForgeEndpoints(data, host, port) + return patched, err +} + +// addGitHubForgeEndpoints adds host:port endpoints, cloned from the +// github.com endpoints of a profile that issues GH_TOKEN. A clone keeps the +// template's protocol, path, access and enforcement; its ports and +// allowed_ips are dropped, since they describe github.com, not this server. +// A clone whose protocol and path the profile already names for host:port is +// skipped. When api.github.com and github.com give the same protocol and path +// different policies, the read-only one wins. It reports changed == false, +// with the input returned as is, when the profile does not issue GH_TOKEN, +// names no github.com endpoint, or already names every clone. +func addGitHubForgeEndpoints(data []byte, host string, port int) ([]byte, bool, error) { + // One document only, as the GitLab binding requires: yaml.Unmarshal + // would read the first and drop the rest on rewrite. + doc, err := parseSingleProfileDocument(data) + if err != nil { + return nil, false, err + } + if doc == nil || doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { + return data, false, nil + } + root := doc.Content[0] + // profileIssuesCredential and yamlMappingValue read literal keys, so a + // merge key could hide GH_TOKEN or an endpoint's host. Refuse those + // shapes, as the GitLab binding does, rather than leave the profile + // silently unbound while GH_HOST points gh at the server. + if err := checkProfileKeys(root); err != nil { + return nil, false, err + } + if !profileIssuesCredential(root, githubTokenEnvVar) { + return data, false, nil + } + rawEndpoints := yamlMappingValue(root, "endpoints") + endpoints := resolveYAMLAlias(rawEndpoints) + if endpoints == nil || endpoints.Kind != yaml.SequenceNode { + return data, false, nil + } + portStr := strconv.Itoa(port) + endpointKey := func(ep *yaml.Node) string { + return scalarValue(yamlMappingValue(ep, "protocol")) + " " + scalarValue(yamlMappingValue(ep, "path")) + } + var templates []*yaml.Node + present := map[string]bool{} + for _, ep := range endpoints.Content { + ep = resolveYAMLAlias(ep) + if ep == nil || ep.Kind != yaml.MappingNode { + continue + } + h := strings.ToLower(scalarValue(yamlMappingValue(ep, "host"))) + if h == "" { + continue + } + if h == strings.ToLower(host) && scalarValue(yamlMappingValue(ep, "port")) == portStr { + present[endpointKey(ep)] = true + continue + } + if githubPublicHosts[h] { + templates = append(templates, ep) + } + } + // api.github.com and github.com collapse onto one host: one clone per + // protocol and path, the read-only one when their access differs. + var clones []*yaml.Node + byKey := map[string]int{} + for _, t := range templates { + ep := cloneYAMLNode(t) + setYAMLMappingScalar(ep, "host", host, "!!str") + setYAMLMappingScalar(ep, "port", portStr, "!!int") + deleteYAMLMappingKey(ep, "ports") + deleteYAMLMappingKey(ep, "allowed_ips") + if scalarValue(yamlMappingValue(ep, "path")) == "/graphql" { + setYAMLMappingScalar(ep, "path", "/api/graphql", "!!str") + } + key := endpointKey(ep) + if present[key] { + continue + } + if i, ok := byKey[key]; ok { + if scalarValue(yamlMappingValue(ep, "access")) == "read-only" { + clones[i] = ep + } + continue + } + byKey[key] = len(clones) + clones = append(clones, ep) + } + if len(clones) == 0 { + return data, false, nil + } + if rawEndpoints != endpoints { + // endpoints is an alias: appending to the anchored sequence would + // also change every other node that references it. + endpoints = cloneYAMLNode(endpoints) + setYAMLMappingNode(root, "endpoints", endpoints) + } + endpoints.Content = append(endpoints.Content, clones...) + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(doc); err != nil { + return nil, false, fmt.Errorf("marshaling profile YAML: %w", err) + } + if err := enc.Close(); err != nil { + return nil, false, fmt.Errorf("closing YAML encoder: %w", err) + } + return buf.Bytes(), true, nil +} + +func scalarValue(n *yaml.Node) string { + n = resolveYAMLAlias(n) + if n == nil || n.Kind != yaml.ScalarNode { + return "" + } + return n.Value +} diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go new file mode 100644 index 0000000000..9a234ef8b6 --- /dev/null +++ b/internal/cli/github_profile_test.go @@ -0,0 +1,422 @@ +package cli + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/resolve" + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/scaffold" +) + +func envOf(m map[string]string) func(string) string { + return func(k string) string { return m[k] } +} + +func TestGitHubForgeHostPort(t *testing.T) { + cases := []struct { + server, host string + port int + }{ + {"", "", 0}, + {"https://github.com", "", 0}, + {"https://GitHub.com/", "", 0}, + {"https://ghes.example.com", "ghes.example.com", 443}, + {"https://ghemu.localhost:443", "ghemu.localhost", 443}, + {"https://ghes.example.com:8443/", "ghes.example.com", 8443}, + {"http://127.0.0.1:18600", "", 0}, + {"http://ghes.internal", "", 0}, + {"https://user@ghes.example.com", "", 0}, + {"https://ghes.example.com/sub", "", 0}, + {"https://acme.ghe.com", "", 0}, + {"::not a url", "", 0}, + } + for _, c := range cases { + host, port := githubForgeHostPort(envOf(map[string]string{"GITHUB_SERVER_URL": c.server})) + assert.Equal(t, c.host, host, c.server) + assert.Equal(t, c.port, port, c.server) + } +} + +type testEndpoint struct { + Host string `yaml:"host"` + Port int `yaml:"port"` + Protocol string `yaml:"protocol"` + Access string `yaml:"access"` + Path string `yaml:"path"` +} + +func endpointsOf(t *testing.T, data []byte) []testEndpoint { + t.Helper() + var doc struct { + Endpoints []testEndpoint `yaml:"endpoints"` + } + require.NoError(t, yaml.Unmarshal(data, &doc)) + return doc.Endpoints +} + +func TestAddGitHubForgeEndpointsToTheReadOnlyProfile(t *testing.T) { + data, err := scaffold.FullsendRepoFile("profiles/fullsend-github-ro.yaml") + require.NoError(t, err) + + patched, changed, err := addGitHubForgeEndpoints(data, "ghemu.localhost", 443) + require.NoError(t, err) + require.True(t, changed) + + var added []testEndpoint + for _, ep := range endpointsOf(t, patched) { + if ep.Host == "ghemu.localhost" { + added = append(added, ep) + } + } + // api.github.com and github.com collapse onto one host: one REST + // endpoint, plus GraphQL at GitHub Enterprise Server's path. + assert.ElementsMatch(t, []testEndpoint{ + {Host: "ghemu.localhost", Port: 443, Protocol: "rest", Access: "read-only"}, + {Host: "ghemu.localhost", Port: 443, Protocol: "graphql", Access: "read-only", Path: "/api/graphql"}, + }, added) + // The github.com endpoints stay as they were. + assert.Len(t, endpointsOf(t, patched), len(endpointsOf(t, data))+2) + + again, changedAgain, err := addGitHubForgeEndpoints(patched, "ghemu.localhost", 443) + require.NoError(t, err) + assert.False(t, changedAgain, "a profile that already names the server is unchanged") + assert.Equal(t, patched, again) +} + +func TestAddGitHubForgeEndpointsKeepsThePort(t *testing.T) { + data, err := scaffold.FullsendRepoFile("profiles/fullsend-github.yaml") + require.NoError(t, err) + patched, changed, err := addGitHubForgeEndpoints(data, "ghes.example.com", 8443) + require.NoError(t, err) + require.True(t, changed) + var ports []int + for _, ep := range endpointsOf(t, patched) { + if ep.Host == "ghes.example.com" { + ports = append(ports, ep.Port) + } + } + assert.Equal(t, []int{8443}, ports) +} + +func TestAddGitHubForgeEndpointsLeavesOtherProfilesAlone(t *testing.T) { + other := []byte(`id: other +credentials: + - name: key + env_vars: [OTHER_TOKEN] +endpoints: + - host: api.github.com + port: 443 + protocol: rest +`) + out, changed, err := addGitHubForgeEndpoints(other, "ghes.example.com", 443) + require.NoError(t, err) + assert.False(t, changed, "a profile that does not issue GH_TOKEN is unchanged") + assert.Equal(t, other, out) + + noGitHub := []byte(`id: nogh +credentials: + - name: t + env_vars: [GH_TOKEN] +endpoints: + - host: registry.example.com + port: 443 + protocol: rest +`) + out, changed, err = addGitHubForgeEndpoints(noGitHub, "ghes.example.com", 443) + require.NoError(t, err) + assert.False(t, changed, "a GH_TOKEN profile with no github.com endpoint is unchanged") + assert.Equal(t, noGitHub, out) +} + +func TestBindGitHubForgeHost(t *testing.T) { + data, err := scaffold.FullsendRepoFile("profiles/fullsend-github-ro.yaml") + require.NoError(t, err) + src := filepath.Join(t.TempDir(), "fullsend-github-ro.yaml") + require.NoError(t, os.WriteFile(src, data, 0o644)) + in := []resolve.ResolvedProfile{{ID: "fullsend-github-ro", LocalPath: src}} + + same, cleanup, err := bindGitHubForgeHost(in, "", 0) + require.NoError(t, err) + cleanup() + assert.Equal(t, in, same, "github.com changes nothing") + + out, cleanup, err := bindGitHubForgeHost(in, "ghemu.localhost", 443) + require.NoError(t, err) + defer cleanup() + require.NotEqual(t, src, out[0].LocalPath, "the source file is never modified") + unchanged, err := os.ReadFile(src) + require.NoError(t, err) + assert.Equal(t, data, unchanged) + bound, err := os.ReadFile(out[0].LocalPath) + require.NoError(t, err) + assert.Contains(t, string(bound), "ghemu.localhost") + + _, _, err = bindGitHubForgeHost(in, "*.example.com", 443) + assert.Error(t, err, "a wildcard host is refused before any profile is bound") +} + +func TestBindGitHubForgeHostBytes(t *testing.T) { + data, err := scaffold.FullsendRepoFile("profiles/fullsend-github-ro.yaml") + require.NoError(t, err) + + out, err := bindGitHubForgeHostBytes(data, envOf(map[string]string{"GITHUB_SERVER_URL": "https://github.com"})) + require.NoError(t, err) + assert.Equal(t, data, out) + + out, err = bindGitHubForgeHostBytes(data, envOf(map[string]string{"GITHUB_SERVER_URL": "https://ghemu.localhost"})) + require.NoError(t, err) + assert.Contains(t, string(out), "/api/graphql") +} + +func TestGitHubForgeSandboxEnvLines(t *testing.T) { + assert.Nil(t, githubForgeSandboxEnvLines(envOf(nil))) + assert.Nil(t, githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://github.com"}))) + + assert.Equal(t, []string{ + "export GH_HOST='ghemu.localhost'", + `export GH_ENTERPRISE_TOKEN="${GH_TOKEN}"`, + }, githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://ghemu.localhost:443"}))) + + // An IPv6 literal keeps its brackets, with and without a port. + lines6 := githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://[2001:db8::1]"})) + require.NotEmpty(t, lines6) + assert.Equal(t, "export GH_HOST='[2001:db8::1]'", lines6[0]) + lines6 = githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://[2001:db8::1]:8443"})) + require.NotEmpty(t, lines6) + assert.Equal(t, "export GH_HOST='[2001:db8::1]:8443'", lines6[0]) + + lines := githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://ghes.example.com:8443"})) + require.NotEmpty(t, lines) + assert.Equal(t, "export GH_HOST='ghes.example.com:8443'", lines[0]) + + assert.Nil(t, githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://bad'host.example"})), + "a host that is not a concrete hostname gets no lines") +} + +func TestAddGitHubForgeEndpointsDropsGitHubComPortsAndAddresses(t *testing.T) { + in := []byte(`id: custom +credentials: + - name: t + env_vars: [GH_TOKEN] +endpoints: + - host: api.github.com + port: 443 + ports: [443, 8443] + allowed_ips: [140.82.112.0/20] + protocol: rest + access: read-only +`) + out, changed, err := addGitHubForgeEndpoints(in, "ghes.example.com", 443) + require.NoError(t, err) + require.True(t, changed) + var doc struct { + Endpoints []map[string]any `yaml:"endpoints"` + } + require.NoError(t, yaml.Unmarshal(out, &doc)) + require.Len(t, doc.Endpoints, 2) + clone := doc.Endpoints[1] + assert.Equal(t, "ghes.example.com", clone["host"]) + assert.NotContains(t, clone, "ports", "github.com's extra ports must not reach the server") + assert.NotContains(t, clone, "allowed_ips", "github.com's addresses must not restrict the server") + assert.Contains(t, doc.Endpoints[0], "allowed_ips", "the github.com endpoint itself is unchanged") +} + +func TestAddGitHubForgeEndpointsAddsOnlyWhatIsMissing(t *testing.T) { + in := []byte(`id: partial +credentials: + - name: t + env_vars: [GH_TOKEN] +endpoints: + - host: api.github.com + port: 443 + protocol: rest + access: read-only + - host: api.github.com + port: 443 + protocol: graphql + path: /graphql + access: read-only + - host: ghes.example.com + port: 443 + protocol: rest + access: read-only +`) + out, changed, err := addGitHubForgeEndpoints(in, "ghes.example.com", 443) + require.NoError(t, err) + require.True(t, changed, "the missing GraphQL endpoint is added although REST is already there") + var added []testEndpoint + for _, ep := range endpointsOf(t, out) { + if ep.Host == "ghes.example.com" { + added = append(added, ep) + } + } + assert.ElementsMatch(t, []testEndpoint{ + {Host: "ghes.example.com", Port: 443, Protocol: "rest", Access: "read-only"}, + {Host: "ghes.example.com", Port: 443, Protocol: "graphql", Access: "read-only", Path: "/api/graphql"}, + }, added) +} + +func TestAddGitHubForgeEndpointsPrefersReadOnlyAndResolvesAliases(t *testing.T) { + in := []byte(`id: mixed +credentials: + - name: t + env_vars: [GH_TOKEN] +api: &api api.github.com +endpoints: + - host: *api + port: 443 + protocol: rest + access: read-write + - host: github.com + port: 443 + protocol: rest + access: read-only +`) + out, changed, err := addGitHubForgeEndpoints(in, "ghes.example.com", 443) + require.NoError(t, err) + require.True(t, changed, "an aliased api.github.com host is still a template") + var added []testEndpoint + for _, ep := range endpointsOf(t, out) { + if ep.Host == "ghes.example.com" { + added = append(added, ep) + } + } + assert.Equal(t, []testEndpoint{{Host: "ghes.example.com", Port: 443, Protocol: "rest", Access: "read-only"}}, added, + "two github.com policies for one protocol and path collapse to the read-only one") +} + +func TestBindGitHubForgeHostErrors(t *testing.T) { + _, cleanup, err := bindGitHubForgeHost([]resolve.ResolvedProfile{{ID: "gone", LocalPath: filepath.Join(t.TempDir(), "missing.yaml")}}, "ghes.example.com", 443) + cleanup() + assert.ErrorContains(t, err, `reading profile "gone"`) + + bad := filepath.Join(t.TempDir(), "bad.yaml") + require.NoError(t, os.WriteFile(bad, []byte("endpoints: [\n"), 0o644)) + _, cleanup, err = bindGitHubForgeHost([]resolve.ResolvedProfile{{ID: "bad", LocalPath: bad}}, "ghes.example.com", 443) + cleanup() + assert.ErrorContains(t, err, `adding GitHub server to profile "bad"`) + + _, err = bindGitHubForgeHostBytes([]byte("id: x\n"), envOf(map[string]string{"GITHUB_SERVER_URL": "https://bad'host.example"})) + assert.Error(t, err, "a server host that is not a concrete hostname is refused") +} + +func TestAddGitHubForgeEndpointsOddShapes(t *testing.T) { + _, _, err := addGitHubForgeEndpoints([]byte("endpoints: [\n"), "ghes.example.com", 443) + assert.ErrorContains(t, err, "parsing profile YAML") + + for name, in := range map[string]string{ + "not a mapping": "- a\n- b\n", + "endpoints not a list": "credentials: [{name: t, env_vars: [GH_TOKEN]}]\nendpoints: {host: api.github.com}\n", + "entries without hosts": "credentials: [{name: t, env_vars: [GH_TOKEN]}]\nendpoints: [plain, {port: 443}]\n", + } { + out, changed, err := addGitHubForgeEndpoints([]byte(in), "ghes.example.com", 443) + require.NoError(t, err, name) + assert.False(t, changed, name) + assert.Equal(t, in, string(out), name) + } +} + +func TestAddGitHubForgeEndpointsCopiesAnAliasedEndpointList(t *testing.T) { + in := []byte(`id: aliased +credentials: + - name: t + env_vars: [GH_TOKEN] +shared: &eps + - host: api.github.com + port: 443 + protocol: rest +endpoints: *eps +`) + out, changed, err := addGitHubForgeEndpoints(in, "ghes.example.com", 443) + require.NoError(t, err) + require.True(t, changed) + var doc struct { + Shared []testEndpoint `yaml:"shared"` + Endpoints []testEndpoint `yaml:"endpoints"` + } + require.NoError(t, yaml.Unmarshal(out, &doc)) + assert.Len(t, doc.Shared, 1, "the anchored list itself is not changed") + assert.Len(t, doc.Endpoints, 2) +} + +func TestBindGitHubForgeHostSkipsProfilesItLeavesAlone(t *testing.T) { + dir := t.TempDir() + other := filepath.Join(dir, "other.yaml") + require.NoError(t, os.WriteFile(other, []byte("id: other\ncredentials: [{name: k, env_vars: [OTHER_TOKEN]}]\nendpoints: [{host: api.github.com, port: 443, protocol: rest}]\n"), 0o644)) + out, cleanup, err := bindGitHubForgeHost([]resolve.ResolvedProfile{{ID: "other", LocalPath: other}}, "ghes.example.com", 443) + defer cleanup() + require.NoError(t, err) + assert.Equal(t, other, out[0].LocalPath, "an unchanged profile keeps its source file") +} + +// The lines go through the runtime .env loader the agent launch and the +// in-sandbox probes use, not a shell source: a line it rejects is dropped. +func TestGitHubForgeSandboxEnvLinesThroughTheRuntimeLoader(t *testing.T) { + envFile := filepath.Join(t.TempDir(), ".env") + lines := githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://ghes.example.com:8443"})) + require.NoError(t, os.WriteFile(envFile, []byte(strings.Join(lines, "\n")+"\n"), 0o600)) + for name, tc := range map[string]struct { + env []string + want string + }{ + "placeholder": {[]string{"GH_TOKEN=openshell:resolve:env:GH_TOKEN"}, "ghes.example.com:8443|openshell:resolve:env:GH_TOKEN"}, + "unset": {nil, "ghes.example.com:8443|"}, + } { + cmd := exec.Command("/bin/sh", "-c", agentruntime.EnvDataLoad(envFile)+` && printf '%s|%s' "$GH_HOST" "$GH_ENTERPRISE_TOKEN"`) + cmd.Env = append([]string{"PATH=" + os.Getenv("PATH"), "HOME=/home/agent"}, tc.env...) + var stderr strings.Builder + cmd.Stderr = &stderr + out, err := cmd.Output() + require.NoError(t, err, "%s: %s", name, stderr.String()) + assert.Equal(t, tc.want, string(out), name) + assert.NotContains(t, stderr.String(), "ignored", "%s: the loader dropped a line", name) + } +} + +func TestAddGitHubForgeEndpointsRefusesMergeKeys(t *testing.T) { + for name, in := range map[string]string{ + "merged credential": `id: merged +base: &cred {name: t, env_vars: [GH_TOKEN]} +credentials: + - <<: *cred +endpoints: + - host: api.github.com + port: 443 + protocol: rest +`, + "merged endpoint host": `id: merged +credentials: + - name: t + env_vars: [GH_TOKEN] +gh: &gh {host: api.github.com, port: 443} +endpoints: + - <<: *gh + protocol: rest +`, + } { + _, _, err := addGitHubForgeEndpoints([]byte(in), "ghes.example.com", 443) + assert.Error(t, err, name) + } +} + +func TestAddGitHubForgeEndpointsRefusesASecondDocument(t *testing.T) { + for name, in := range map[string]string{ + "profile that needs cloning": "id: a\ncredentials: [{name: t, env_vars: [GH_TOKEN]}]\nendpoints: [{host: api.github.com, port: 443, protocol: rest}]\n---\nid: b\n", + "profile left unchanged": "id: a\ncredentials: [{name: k, env_vars: [OTHER]}]\n---\nid: b\n", + } { + _, _, err := addGitHubForgeEndpoints([]byte(in), "ghes.example.com", 443) + assert.ErrorContains(t, err, "more than one YAML document", name) + } + out, changed, err := addGitHubForgeEndpoints([]byte(""), "ghes.example.com", 443) + require.NoError(t, err) + assert.False(t, changed) + assert.Empty(t, out) +} diff --git a/internal/cli/gitlab_profile.go b/internal/cli/gitlab_profile.go index 47db2f8012..87d18cf3e6 100644 --- a/internal/cli/gitlab_profile.go +++ b/internal/cli/gitlab_profile.go @@ -254,19 +254,19 @@ func bindGitLabCredentialToForgeHost(profiles []resolve.ResolvedProfile, host, p // and dots, and the port must be in 1-65535. func validateForgeDestination(host string, port int) error { if port < 1 || port > 65535 { - return fmt.Errorf("GitLab port %d is out of range 1-65535", port) + return fmt.Errorf("forge port %d is out of range 1-65535", port) } if net.ParseIP(host) != nil { return nil } if strings.HasPrefix(host, ".") || strings.Contains(host, "..") { - return fmt.Errorf("GitLab forge host %q is not a concrete hostname", host) + return fmt.Errorf("forge host %q is not a concrete hostname", host) } for _, r := range host { ok := r == '-' || r == '_' || r == '.' || (r >= '0' && r <= '9') || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') if !ok { - return fmt.Errorf("GitLab forge host %q is not a concrete hostname (wildcards and special characters are not allowed)", host) + return fmt.Errorf("forge host %q is not a concrete hostname (wildcards and special characters are not allowed)", host) } } return nil diff --git a/internal/cli/run.go b/internal/cli/run.go index e3ba55d7bf..07f7a9845a 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1672,6 +1672,17 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } defer cleanupBound() result.Profiles = boundProfiles + } else if ghHost, ghPort := githubForgeHostPort(os.Getenv); ghHost != "" { + // The same for a GitHub server other than github.com: the stock + // GitHub profiles' GH_TOKEN placeholder resolves only at + // api.github.com and github.com. + boundProfiles, cleanupBound, err := bindGitHubForgeHost(result.Profiles, ghHost, ghPort) + if err != nil { + printer.StepFail("Failed to add the GitHub server to provider profiles") + return fmt.Errorf("binding GitHub server to provider profiles: %w", err) + } + defer cleanupBound() + result.Profiles = boundProfiles } if intErr := checkProviderProfileIntegrity(result.Providers, result.Profiles); intErr != nil { @@ -4085,6 +4096,11 @@ func harnessEnvLines(h *harness.Harness) []string { // entry, the same ordering rule as iteration.env below. lines = append(lines, runnerPathRestoreLine()) + // On a GitHub server other than github.com, gh needs GH_HOST and reads + // its token from GH_ENTERPRISE_TOKEN. Runner-owned, after the harness + // entries, so env.sandbox cannot point gh at another host. + lines = append(lines, githubForgeSandboxEnvLines(os.Getenv)...) + // Runner-owned budget, deadline, and TRACEPARENT come after every // harness-controlled entry so none of them can shadow the values (#7042). return append(lines, iterationEnvSourceLine()) diff --git a/internal/cli/run_openai.go b/internal/cli/run_openai.go index 3021e6f183..08a3c00e28 100644 --- a/internal/cli/run_openai.go +++ b/internal/cli/run_openai.go @@ -675,6 +675,12 @@ func ensureEmbeddedProfile(ctx context.Context, profileID string, printer *ui.Pr if err != nil { return fmt.Errorf("provider profile %q is not shipped by this fullsend build: %w", profileID, err) } + // On a GitHub server other than github.com, the GitHub profiles also + // name that server (bindGitHubForgeHost); others are unchanged. + data, err = bindGitHubForgeHostBytes(data, os.Getenv) + if err != nil { + return fmt.Errorf("adding the GitHub server to provider profile %q: %w", profileID, err) + } return importProfileBytes(ctx, profileID, data, printer) } diff --git a/internal/inference/actionsoidc/actionsoidc.go b/internal/inference/actionsoidc/actionsoidc.go index 1b59a029d7..888ff01e15 100644 --- a/internal/inference/actionsoidc/actionsoidc.go +++ b/internal/inference/actionsoidc/actionsoidc.go @@ -20,8 +20,11 @@ import ( "net" "net/http" "net/url" + "os" "strings" "time" + + "github.com/fullsend-ai/fullsend/internal/config" ) const ( @@ -33,8 +36,9 @@ const ( // HTTPTimeout is the per-request timeout of the default client. HTTPTimeout = 30 * time.Second - // oidcHostSuffix is where GitHub serves ACTIONS_ID_TOKEN_REQUEST_URL - // (github.com only; GHES is not supported by fullsend). + // oidcHostSuffix is where github.com serves ACTIONS_ID_TOKEN_REQUEST_URL. + // On another GitHub server the token service is that server itself + // (see RequireGitHubOIDCHost). oidcHostSuffix = ".actions.githubusercontent.com" ) @@ -173,7 +177,17 @@ func RequireSecureURL(what, raw string) error { // GitHub's Actions token service (loopback is allowed for tests). The URL // is runner-injected and deny-listed, so this is defence in depth against a // rewritten runner environment, not SSRF hardening. +// +// On a GitHub server other than github.com (GitHub Enterprise Server, or a +// GitHub-compatible API) the Actions token service is that server itself, +// so the host GITHUB_SERVER_URL names is accepted too. The runner sets +// GITHUB_SERVER_URL beside the request URL. github.com itself is never +// accepted as a token service. func RequireGitHubOIDCHost(raw string) error { + return requireGitHubOIDCHost(raw, os.Getenv) +} + +func requireGitHubOIDCHost(raw string, getenv func(string) string) error { u, err := url.Parse(raw) if err != nil { return fmt.Errorf("parsing OIDC request URL: %w", err) @@ -182,9 +196,38 @@ func RequireGitHubOIDCHost(raw string) error { if isLoopback(host) || strings.HasSuffix(host, oidcHostSuffix) { return nil } + if server, port := configuredGitHubServer(getenv); server != "" && host == server && urlPort(u) == port { + return nil + } return fmt.Errorf("OIDC request URL host %q is not GitHub's Actions token service (*%s)", u.Hostname(), oidcHostSuffix) } +// configuredGitHubServer returns the host and port of the GitHub server +// GITHUB_SERVER_URL names, or ("", "") when it is unset, github.com, or not +// a URL config.GitHubServerBaseURL accepts (https, no userinfo, path or +// query), the same rule the rest of the run uses for the server. +func configuredGitHubServer(getenv func(string) string) (host, port string) { + base := config.GitHubServerBaseURL(getenv("GITHUB_SERVER_URL")) + if base == "" { + return "", "" + } + // GitHubServerBaseURL returns "https://" + a host that url.Parse + // already accepted, so this parse cannot fail. + u, _ := url.Parse(base) + return strings.ToLower(u.Hostname()), urlPort(u) +} + +// urlPort returns u's port, or the scheme's default when it names none. +func urlPort(u *url.URL) string { + if p := u.Port(); p != "" { + return p + } + if strings.EqualFold(u.Scheme, "http") { + return "80" + } + return "443" +} + func isLoopback(host string) bool { if host == "localhost" { return true diff --git a/internal/inference/actionsoidc/server_host_test.go b/internal/inference/actionsoidc/server_host_test.go new file mode 100644 index 0000000000..36227a7350 --- /dev/null +++ b/internal/inference/actionsoidc/server_host_test.go @@ -0,0 +1,57 @@ +package actionsoidc + +import "testing" + +func envWith(server string) func(string) string { + return func(k string) string { + if k == "GITHUB_SERVER_URL" { + return server + } + return "" + } +} + +func TestRequireGitHubOIDCHostAcceptsTheConfiguredServer(t *testing.T) { + cases := []struct{ server, oidcURL string }{ + {"https://ghes.example.com", "https://ghes.example.com/_services/token?api-version=2.0"}, + {"https://GHES.example.com/", "https://ghes.example.com/_services/token"}, + {"https://ghemu.localhost:443", "https://ghemu.localhost:443/actions/oidc/token"}, + {"https://ghemu.localhost", "https://ghemu.localhost/actions/oidc/token"}, + } + for _, c := range cases { + if err := requireGitHubOIDCHost(c.oidcURL, envWith(c.server)); err != nil { + t.Errorf("GITHUB_SERVER_URL=%q refused %q: %v", c.server, c.oidcURL, err) + } + } +} + +func TestRequireGitHubOIDCHostRefusesOtherHosts(t *testing.T) { + if err := requireGitHubOIDCHost("https://elsewhere.example/token", envWith("https://ghes.example.com")); err == nil { + t.Error("a host other than the configured server was accepted") + } + if err := requireGitHubOIDCHost("https://ghes.example.com.evil.test/token", envWith("https://ghes.example.com")); err == nil { + t.Error("a look-alike host was accepted") + } + if err := requireGitHubOIDCHost("http://ghes.example.com/token", envWith("https://ghes.example.com")); err == nil { + t.Error("the configured server on port 80 was accepted for an https server URL") + } + if err := requireGitHubOIDCHost("https://ghes.example.com:8443/token", envWith("https://ghes.example.com")); err == nil { + t.Error("another port on the configured server was accepted") + } + for _, server := range []string{"http://ghes.example.com", "https://user@ghes.example.com", "https://ghes.example.com/sub"} { + if err := requireGitHubOIDCHost("https://ghes.example.com/token", envWith(server)); err == nil { + t.Errorf("GITHUB_SERVER_URL=%q is not a valid server URL but its host was accepted", server) + } + } +} + +func TestRequireGitHubOIDCHostOnGitHubCom(t *testing.T) { + for _, server := range []string{"", "https://github.com", "https://GitHub.com/"} { + if err := requireGitHubOIDCHost("https://github.com/token", envWith(server)); err == nil { + t.Errorf("GITHUB_SERVER_URL=%q accepted github.com itself as a token service", server) + } + if err := requireGitHubOIDCHost("https://pipelines.actions.githubusercontent.com/abc/token", envWith(server)); err != nil { + t.Errorf("GITHUB_SERVER_URL=%q refused GitHub's token service: %v", server, err) + } + } +}