From 8b6b44f752a30b87fea3f7c1dec9aad72c859f5a Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Sat, 14 Nov 2026 16:28:56 -0500 Subject: [PATCH 1/9] feat(run): bind the GitHub provider profiles to a GitHub server other than github.com On a GitHub Enterprise Server (or another GitHub-compatible API) the sandbox's gh calls were denied: OpenShell resolves the GH_TOKEN placeholder only at the endpoints of the profile that issued it, and the stock GitHub profiles name only api.github.com and github.com. gh also needs GH_HOST for such a server, and reads its token from GH_ENTERPRISE_TOKEN there, never from GH_TOKEN. When GITHUB_SERVER_URL names a host other than github.com: - every profile that issues GH_TOKEN, resolved or embedded, gets an endpoint for that host and port cloned from each of its github.com endpoints (same protocol, access and enforcement; GraphQL at /api/graphql), the GitHub analogue of bindGitLabForgeHost (#8683); - the sandbox .env gets runner-owned GH_HOST and a GH_ENTERPRISE_TOKEN that copies the GH_TOKEN placeholder. The proxy substitutes a placeholder by value, so the copy authenticates without a credential of its own, and the real token never enters the sandbox. Nothing changes on github.com. validateForgeDestination's messages no longer name GitLab, since both forges use it. Checked with OpenShell 0.1.4 against a TLS GitHub emulator: with GH_HOST only, gh gets 401; with GH_ENTERPRISE_TOKEN copied from the placeholder, gh api /user answers. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/github_profile.go | 255 ++++++++++++++++++++++++++++ internal/cli/github_profile_test.go | 187 ++++++++++++++++++++ internal/cli/gitlab_profile.go | 6 +- internal/cli/run.go | 16 ++ internal/cli/run_openai.go | 6 + 5 files changed, 467 insertions(+), 3 deletions(-) create mode 100644 internal/cli/github_profile.go create mode 100644 internal/cli/github_profile_test.go diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go new file mode 100644 index 0000000000..4ae27a9e51 --- /dev/null +++ b/internal/cli/github_profile.go @@ -0,0 +1,255 @@ +package cli + +import ( + "bytes" + "fmt" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + + "gopkg.in/yaml.v3" + + "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 ("", "") on github.com or when it +// is unset or unparsable. A URL without a port gets the scheme's default. +func githubForgeHostPort(getenv func(string) string) (host, port string) { + raw := strings.TrimSpace(getenv("GITHUB_SERVER_URL")) + if raw == "" { + return "", "" + } + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" { + return "", "" + } + h := strings.ToLower(u.Hostname()) + if h == "github.com" { + return "", "" + } + p := u.Port() + if p == "" { + if u.Scheme == "http" { + p = "80" + } else { + p = "443" + } + } + return h, p +} + +// 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, mustAtoi(port)); err != nil { + return nil + } + ghHost := host + if port != "443" { + ghHost = host + ":" + port + } + return []string{ + fmt.Sprintf("export GH_HOST='%s'", ghHost), + `if [ -n "${GH_TOKEN:-}" ]; then export GH_ENTERPRISE_TOKEN="$GH_TOKEN"; fi`, + } +} + +func mustAtoi(s string) int { + n, err := strconv.Atoi(s) + if err != nil { + return -1 + } + return n +} + +// 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, port string) ([]resolve.ResolvedProfile, func(), error) { + noop := func() {} + if host == "" { + return profiles, noop, nil + } + portNum, err := strconv.Atoi(port) + if err != nil { + return nil, noop, fmt.Errorf("GitHub server port %q is not a valid integer", port) + } + if err := validateForgeDestination(host, portNum); 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, portNum) + 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 + } + portNum, err := strconv.Atoi(port) + if err != nil { + return nil, fmt.Errorf("GitHub server port %q is not a valid integer", port) + } + if err := validateForgeDestination(host, portNum); err != nil { + return nil, err + } + patched, _, err := addGitHubForgeEndpoints(data, host, portNum) + return patched, err +} + +// addGitHubForgeEndpoints adds host:port endpoints, cloned from the +// github.com endpoints of a profile that issues GH_TOKEN. 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 host:port. +func addGitHubForgeEndpoints(data []byte, host string, port int) ([]byte, bool, error) { + var doc yaml.Node + if err := yaml.Unmarshal(data, &doc); err != nil { + return nil, false, fmt.Errorf("parsing profile YAML: %w", err) + } + if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { + return data, false, nil + } + root := doc.Content[0] + 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) + var templates []*yaml.Node + for _, ep := range endpoints.Content { + ep = resolveYAMLAlias(ep) + if ep == nil || ep.Kind != yaml.MappingNode { + continue + } + h, p := yamlMappingValue(ep, "host"), yamlMappingValue(ep, "port") + if h == nil { + continue + } + if strings.EqualFold(h.Value, host) && p != nil && p.Value == portStr { + return data, false, nil + } + if githubPublicHosts[strings.ToLower(h.Value)] { + templates = append(templates, ep) + } + } + if len(templates) == 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) + } + seen := map[string]bool{} + for _, t := range templates { + ep := cloneYAMLNode(t) + setYAMLMappingScalar(ep, "host", host, "!!str") + setYAMLMappingScalar(ep, "port", portStr, "!!int") + if path := yamlMappingValue(ep, "path"); path != nil && path.Value == "/graphql" { + setYAMLMappingScalar(ep, "path", "/api/graphql", "!!str") + } + // api.github.com and github.com collapse onto one host: keep one + // endpoint per protocol and path. + key := scalarValue(yamlMappingValue(ep, "protocol")) + " " + scalarValue(yamlMappingValue(ep, "path")) + if seen[key] { + continue + } + seen[key] = true + endpoints.Content = append(endpoints.Content, ep) + } + 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..100a4ea785 --- /dev/null +++ b/internal/cli/github_profile_test.go @@ -0,0 +1,187 @@ +package cli + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/resolve" + "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, port string + }{ + {"", "", ""}, + {"https://github.com", "", ""}, + {"https://GitHub.com/", "", ""}, + {"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", "127.0.0.1", "18600"}, + {"http://ghes.internal", "ghes.internal", "80"}, + {"::not a url", "", ""}, + } + 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, "", "") + 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'", + `if [ -n "${GH_TOKEN:-}" ]; then export GH_ENTERPRISE_TOKEN="$GH_TOKEN"; fi`, + }, githubForgeSandboxEnvLines(envOf(map[string]string{"GITHUB_SERVER_URL": "https://ghemu.localhost:443"}))) + + 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") +} 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) } From 7914db9b54a5c9b3c066f43f168c0db00bd46664 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Sat, 14 Nov 2026 17:22:54 -0500 Subject: [PATCH 2/9] fix(inference): accept the configured GitHub server as the OIDC host On a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API such as an emulator) the runner's Actions token service is that server itself, so RequireGitHubOIDCHost refused the runner-injected ACTIONS_ID_TOKEN_REQUEST_URL and the gateway and OpenAI WIF routes could not fetch an assertion. Also accept the host GITHUB_SERVER_URL names when it is not github.com. github.com itself is still never a token service, and any other host is still refused. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/inference/actionsoidc/actionsoidc.go | 32 +++++++++++++ .../inference/actionsoidc/server_host_test.go | 46 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 internal/inference/actionsoidc/server_host_test.go diff --git a/internal/inference/actionsoidc/actionsoidc.go b/internal/inference/actionsoidc/actionsoidc.go index 1b59a029d7..30bd197a90 100644 --- a/internal/inference/actionsoidc/actionsoidc.go +++ b/internal/inference/actionsoidc/actionsoidc.go @@ -20,6 +20,7 @@ import ( "net" "net/http" "net/url" + "os" "strings" "time" ) @@ -173,7 +174,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 +193,30 @@ func RequireGitHubOIDCHost(raw string) error { if isLoopback(host) || strings.HasSuffix(host, oidcHostSuffix) { return nil } + if server := configuredGitHubServerHost(getenv); server != "" && host == server { + return nil + } return fmt.Errorf("OIDC request URL host %q is not GitHub's Actions token service (*%s)", u.Hostname(), oidcHostSuffix) } +// configuredGitHubServerHost returns the host GITHUB_SERVER_URL names, or "" +// when it is unset, unparsable, or github.com. +func configuredGitHubServerHost(getenv func(string) string) string { + raw := strings.TrimSpace(getenv("GITHUB_SERVER_URL")) + if raw == "" { + return "" + } + u, err := url.Parse(raw) + if err != nil { + return "" + } + host := strings.ToLower(u.Hostname()) + if host == "" || host == "github.com" { + return "" + } + return host +} + 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..3705c6369c --- /dev/null +++ b/internal/inference/actionsoidc/server_host_test.go @@ -0,0 +1,46 @@ +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") + } +} + +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) + } + } +} From 14fd789335c23b86c97c73a67b20f6a0ea247fa3 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 12:23:39 -0500 Subject: [PATCH 3/9] fix(run): take the GitHub server from the rule the API client uses The profile binding, GH_HOST and the OIDC host check parsed GITHUB_SERVER_URL on their own. They accepted http, userinfo and a path, which config.GitHubServerBaseURL rejects, so for such a URL the profiles and gh named the server while the rest of the run stayed on github.com. An http server URL also bound port 80, where the proxy would put the real token in a plain-text request. All three now use config.GitHubServerBaseURL. The OIDC check also compares the port. GHE.com (*.ghe.com) is left unbound: gh calls api. there and reads GH_TOKEN, which this binding does not model. GH_HOST depends on the host environment, so the sandbox env manifest collector pins GITHUB_SERVER_URL and lists GH_HOST as a gated export; the env reference schema is regenerated. Assisted-by: Claude Signed-off-by: Wayne Sun --- .../sandbox-env/v1/env-references.schema.json | 4 ++ internal/cli/env_manifest_collector_test.go | 7 ++++ internal/cli/github_profile.go | 25 +++++------ internal/cli/github_profile_test.go | 7 +++- internal/inference/actionsoidc/actionsoidc.go | 41 ++++++++++++------- .../inference/actionsoidc/server_host_test.go | 8 ++++ 6 files changed, 63 insertions(+), 29 deletions(-) diff --git a/docs/normative/sandbox-env/v1/env-references.schema.json b/docs/normative/sandbox-env/v1/env-references.schema.json index fafa20e109..099442b56d 100644 --- a/docs/normative/sandbox-env/v1/env-references.schema.json +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -280,6 +280,10 @@ "const": "FULLSEND_TRACE_ID", "description": "trace-ID injection succeeds; the run warns and continues when it fails" }, + { + "const": "GH_HOST", + "description": "GITHUB_SERVER_URL points to a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API); GH_ENTERPRISE_TOKEN then gets the GH_TOKEN placeholder" + }, { "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..45ff355ed8 100644 --- a/internal/cli/env_manifest_collector_test.go +++ b/internal/cli/env_manifest_collector_test.go @@ -62,6 +62,7 @@ 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_HOST": "GITHUB_SERVER_URL points to a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API); GH_ENTERPRISE_TOKEN then gets the GH_TOKEN placeholder", "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 +109,7 @@ func TestEnvManifestCollector(t *testing.T) { "FULLSEND_SLUG", "FULLSEND_TIMEOUT_MINUTES", "FULLSEND_TRACE_ID", + "GH_HOST", "TIRITH_FAIL_ON", "TIRITH_REQUIRED", "TRACEPARENT", @@ -483,7 +485,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 index 4ae27a9e51..35ba65be26 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -11,6 +11,7 @@ import ( "gopkg.in/yaml.v3" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/resolve" ) @@ -25,28 +26,28 @@ const githubTokenEnvVar = "GH_TOKEN" 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 ("", "") on github.com or when it -// is unset or unparsable. A URL without a port gets the scheme's default. +// 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, port string) { - raw := strings.TrimSpace(getenv("GITHUB_SERVER_URL")) - if raw == "" { + base := config.GitHubServerBaseURL(getenv("GITHUB_SERVER_URL")) + if base == "" { return "", "" } - u, err := url.Parse(raw) + u, err := url.Parse(base) if err != nil || u.Hostname() == "" { return "", "" } - h := strings.ToLower(u.Hostname()) - if h == "github.com" { + h := u.Hostname() + if h == "ghe.com" || strings.HasSuffix(h, ".ghe.com") { return "", "" } p := u.Port() if p == "" { - if u.Scheme == "http" { - p = "80" - } else { - p = "443" - } + p = "443" } return h, p } diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index 100a4ea785..61e33c183e 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -27,8 +27,11 @@ func TestGitHubForgeHostPort(t *testing.T) { {"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", "127.0.0.1", "18600"}, - {"http://ghes.internal", "ghes.internal", "80"}, + {"http://127.0.0.1:18600", "", ""}, + {"http://ghes.internal", "", ""}, + {"https://user@ghes.example.com", "", ""}, + {"https://ghes.example.com/sub", "", ""}, + {"https://acme.ghe.com", "", ""}, {"::not a url", "", ""}, } for _, c := range cases { diff --git a/internal/inference/actionsoidc/actionsoidc.go b/internal/inference/actionsoidc/actionsoidc.go index 30bd197a90..528127452a 100644 --- a/internal/inference/actionsoidc/actionsoidc.go +++ b/internal/inference/actionsoidc/actionsoidc.go @@ -23,6 +23,8 @@ import ( "os" "strings" "time" + + "github.com/fullsend-ai/fullsend/internal/config" ) const ( @@ -193,28 +195,37 @@ func requireGitHubOIDCHost(raw string, getenv func(string) string) error { if isLoopback(host) || strings.HasSuffix(host, oidcHostSuffix) { return nil } - if server := configuredGitHubServerHost(getenv); server != "" && host == server { + 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) } -// configuredGitHubServerHost returns the host GITHUB_SERVER_URL names, or "" -// when it is unset, unparsable, or github.com. -func configuredGitHubServerHost(getenv func(string) string) string { - raw := strings.TrimSpace(getenv("GITHUB_SERVER_URL")) - if raw == "" { - return "" - } - u, err := url.Parse(raw) - if err != nil { - return "" +// 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 "", "" + } + u, err := url.Parse(base) + if err != nil || u.Hostname() == "" { + return "", "" + } + 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 } - host := strings.ToLower(u.Hostname()) - if host == "" || host == "github.com" { - return "" + if strings.EqualFold(u.Scheme, "http") { + return "80" } - return host + return "443" } func isLoopback(host string) bool { diff --git a/internal/inference/actionsoidc/server_host_test.go b/internal/inference/actionsoidc/server_host_test.go index 3705c6369c..4eee3aab2c 100644 --- a/internal/inference/actionsoidc/server_host_test.go +++ b/internal/inference/actionsoidc/server_host_test.go @@ -32,6 +32,14 @@ func TestRequireGitHubOIDCHostRefusesOtherHosts(t *testing.T) { 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("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) { From b0772dad10142e0700035245f30cad21c9dd5510 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 12:44:56 -0500 Subject: [PATCH 4/9] fix(run): plain GH_ENTERPRISE_TOKEN export and narrower endpoint clones Review follow-ups for the GitHub server binding: - GH_ENTERPRISE_TOKEN is a plain export of the GH_TOKEN placeholder, not a conditional, so readers of the sandbox .env that take only assignments and exports, the env manifest collector among them, see it. gh treats an empty value as unset. The manifest lists it as a gated export and the env reference schema is regenerated. - GH_HOST keeps the brackets of an IPv6 literal, with or without a port. - A clone drops the github.com endpoint's ports and allowed_ips, which describe github.com, not the configured server. - Only the endpoints the profile does not already name for the server are added, so an existing REST endpoint no longer blocks the GraphQL one. - Host and port are read through alias resolution, and when api.github.com and github.com give one protocol and path different access, the read-only policy wins. - The oidcHostSuffix comment no longer says GHES is unsupported. Assisted-by: Claude Signed-off-by: Wayne Sun --- .../sandbox-env/v1/env-references.schema.json | 6 +- internal/cli/env_manifest_collector_test.go | 4 +- internal/cli/github_profile.go | 96 ++++++++++------- internal/cli/github_profile_test.go | 102 +++++++++++++++++- internal/inference/actionsoidc/actionsoidc.go | 5 +- 5 files changed, 172 insertions(+), 41 deletions(-) diff --git a/docs/normative/sandbox-env/v1/env-references.schema.json b/docs/normative/sandbox-env/v1/env-references.schema.json index 099442b56d..c2f10f3929 100644 --- a/docs/normative/sandbox-env/v1/env-references.schema.json +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -280,9 +280,13 @@ "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); GH_ENTERPRISE_TOKEN then gets the GH_TOKEN placeholder" + "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", diff --git a/internal/cli/env_manifest_collector_test.go b/internal/cli/env_manifest_collector_test.go index 45ff355ed8..6f6a2cb9ca 100644 --- a/internal/cli/env_manifest_collector_test.go +++ b/internal/cli/env_manifest_collector_test.go @@ -62,7 +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_HOST": "GITHUB_SERVER_URL points to a GitHub server other than github.com (GitHub Enterprise Server or a GitHub-compatible API); GH_ENTERPRISE_TOKEN then gets the GH_TOKEN placeholder", + "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", @@ -109,6 +110,7 @@ func TestEnvManifestCollector(t *testing.T) { "FULLSEND_SLUG", "FULLSEND_TIMEOUT_MINUTES", "FULLSEND_TRACE_ID", + "GH_ENTERPRISE_TOKEN", "GH_HOST", "TIRITH_FAIL_ON", "TIRITH_REQUIRED", diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go index 35ba65be26..93782dc9c7 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "fmt" + "net" "net/url" "os" "path/filepath" @@ -65,27 +66,30 @@ func githubForgeSandboxEnvLines(getenv func(string) string) []string { if host == "" { return nil } - if err := validateForgeDestination(host, mustAtoi(port)); err != nil { + portNum, err := strconv.Atoi(port) + if err != nil { + return nil + } + if err := validateForgeDestination(host, portNum); 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 = host + ":" + port + ghHost = net.JoinHostPort(host, port) + } else if strings.Contains(host, ":") { + ghHost = "[" + host + "]" } + // A plain export, not a conditional: the sandbox .env loader and the + // env manifest collector read assignments and exports only. An empty + // GH_TOKEN leaves GH_ENTERPRISE_TOKEN empty, which gh treats as unset. return []string{ fmt.Sprintf("export GH_HOST='%s'", ghHost), - `if [ -n "${GH_TOKEN:-}" ]; then export GH_ENTERPRISE_TOKEN="$GH_TOKEN"; fi`, + `export GH_ENTERPRISE_TOKEN="${GH_TOKEN:-}"`, } } -func mustAtoi(s string) int { - n, err := strconv.Atoi(s) - if err != nil { - return -1 - } - return n -} - // 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 @@ -171,9 +175,14 @@ func bindGitHubForgeHostBytes(data []byte, getenv func(string) string) ([]byte, } // addGitHubForgeEndpoints adds host:port endpoints, cloned from the -// github.com endpoints of a profile that issues GH_TOKEN. 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 host:port. +// 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) { var doc yaml.Node if err := yaml.Unmarshal(data, &doc); err != nil { @@ -192,49 +201,64 @@ func addGitHubForgeEndpoints(data []byte, host string, port int) ([]byte, bool, 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, p := yamlMappingValue(ep, "host"), yamlMappingValue(ep, "port") - if h == nil { + h := strings.ToLower(scalarValue(yamlMappingValue(ep, "host"))) + if h == "" { continue } - if strings.EqualFold(h.Value, host) && p != nil && p.Value == portStr { - return data, false, nil + if h == strings.ToLower(host) && scalarValue(yamlMappingValue(ep, "port")) == portStr { + present[endpointKey(ep)] = true + continue } - if githubPublicHosts[strings.ToLower(h.Value)] { + if githubPublicHosts[h] { templates = append(templates, ep) } } - if len(templates) == 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) - } - seen := map[string]bool{} + // 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") - if path := yamlMappingValue(ep, "path"); path != nil && path.Value == "/graphql" { + deleteYAMLMappingKey(ep, "ports") + deleteYAMLMappingKey(ep, "allowed_ips") + if scalarValue(yamlMappingValue(ep, "path")) == "/graphql" { setYAMLMappingScalar(ep, "path", "/api/graphql", "!!str") } - // api.github.com and github.com collapse onto one host: keep one - // endpoint per protocol and path. - key := scalarValue(yamlMappingValue(ep, "protocol")) + " " + scalarValue(yamlMappingValue(ep, "path")) - if seen[key] { + key := endpointKey(ep) + if present[key] { continue } - seen[key] = true - endpoints.Content = append(endpoints.Content, ep) + 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) diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index 61e33c183e..4c87eec009 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -178,9 +178,17 @@ func TestGitHubForgeSandboxEnvLines(t *testing.T) { assert.Equal(t, []string{ "export GH_HOST='ghemu.localhost'", - `if [ -n "${GH_TOKEN:-}" ]; then export GH_ENTERPRISE_TOKEN="$GH_TOKEN"; fi`, + `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]) @@ -188,3 +196,95 @@ func TestGitHubForgeSandboxEnvLines(t *testing.T) { 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") +} diff --git a/internal/inference/actionsoidc/actionsoidc.go b/internal/inference/actionsoidc/actionsoidc.go index 528127452a..545a35c865 100644 --- a/internal/inference/actionsoidc/actionsoidc.go +++ b/internal/inference/actionsoidc/actionsoidc.go @@ -36,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" ) From 16e14d0378ea1756a27ff7495ece108ac199200b Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 13:12:47 -0500 Subject: [PATCH 5/9] test(run): cover the GitHub server binding's error paths Pass the server port as an int from githubForgeHostPort, which drops the Atoi error paths that could not fail, and test the profile read, parse, destination and alias cases, plus an http OIDC URL on the server host. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/github_profile.go | 49 ++++------ internal/cli/github_profile_test.go | 97 ++++++++++++++++--- internal/inference/actionsoidc/actionsoidc.go | 7 +- .../inference/actionsoidc/server_host_test.go | 3 + 4 files changed, 105 insertions(+), 51 deletions(-) diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go index 93782dc9c7..59e847a608 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -33,24 +33,23 @@ var githubPublicHosts = map[string]bool{"api.github.com": true, "github.com": tr // 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, port string) { +func githubForgeHostPort(getenv func(string) string) (host string, port int) { base := config.GitHubServerBaseURL(getenv("GITHUB_SERVER_URL")) if base == "" { - return "", "" - } - u, err := url.Parse(base) - if err != nil || u.Hostname() == "" { - return "", "" + 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 "", "" + return "", 0 } - p := u.Port() - if p == "" { - p = "443" + port = 443 + if p, err := strconv.Atoi(u.Port()); err == nil { + port = p } - return h, p + return h, port } // githubForgeSandboxEnvLines returns the sandbox .env lines that point gh at @@ -66,18 +65,14 @@ func githubForgeSandboxEnvLines(getenv func(string) string) []string { if host == "" { return nil } - portNum, err := strconv.Atoi(port) - if err != nil { - return nil - } - if err := validateForgeDestination(host, portNum); err != 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, port) + if port != 443 { + ghHost = net.JoinHostPort(host, strconv.Itoa(port)) } else if strings.Contains(host, ":") { ghHost = "[" + host + "]" } @@ -106,16 +101,12 @@ func githubForgeSandboxEnvLines(getenv func(string) string) []string { // 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, port string) ([]resolve.ResolvedProfile, func(), error) { +func bindGitHubForgeHost(profiles []resolve.ResolvedProfile, host string, port int) ([]resolve.ResolvedProfile, func(), error) { noop := func() {} if host == "" { return profiles, noop, nil } - portNum, err := strconv.Atoi(port) - if err != nil { - return nil, noop, fmt.Errorf("GitHub server port %q is not a valid integer", port) - } - if err := validateForgeDestination(host, portNum); err != nil { + if err := validateForgeDestination(host, port); err != nil { return nil, noop, err } var tmpDir string @@ -132,7 +123,7 @@ func bindGitHubForgeHost(profiles []resolve.ResolvedProfile, host, port string) cleanup() return nil, noop, fmt.Errorf("reading profile %q: %w", rp.ID, err) } - patched, changed, err := addGitHubForgeEndpoints(data, host, portNum) + 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) @@ -163,14 +154,10 @@ func bindGitHubForgeHostBytes(data []byte, getenv func(string) string) ([]byte, if host == "" { return data, nil } - portNum, err := strconv.Atoi(port) - if err != nil { - return nil, fmt.Errorf("GitHub server port %q is not a valid integer", port) - } - if err := validateForgeDestination(host, portNum); err != nil { + if err := validateForgeDestination(host, port); err != nil { return nil, err } - patched, _, err := addGitHubForgeEndpoints(data, host, portNum) + patched, _, err := addGitHubForgeEndpoints(data, host, port) return patched, err } diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index 4c87eec009..3e1577be36 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -19,20 +19,21 @@ func envOf(m map[string]string) func(string) string { func TestGitHubForgeHostPort(t *testing.T) { cases := []struct { - server, host, port string + server, host string + port int }{ - {"", "", ""}, - {"https://github.com", "", ""}, - {"https://GitHub.com/", "", ""}, - {"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", "", ""}, - {"http://ghes.internal", "", ""}, - {"https://user@ghes.example.com", "", ""}, - {"https://ghes.example.com/sub", "", ""}, - {"https://acme.ghe.com", "", ""}, - {"::not a url", "", ""}, + {"", "", 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})) @@ -139,12 +140,12 @@ func TestBindGitHubForgeHost(t *testing.T) { require.NoError(t, os.WriteFile(src, data, 0o644)) in := []resolve.ResolvedProfile{{ID: "fullsend-github-ro", LocalPath: src}} - same, cleanup, err := bindGitHubForgeHost(in, "", "") + 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") + 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") @@ -155,7 +156,7 @@ func TestBindGitHubForgeHost(t *testing.T) { require.NoError(t, err) assert.Contains(t, string(bound), "ghemu.localhost") - _, _, err = bindGitHubForgeHost(in, "*.example.com", "443") + _, _, err = bindGitHubForgeHost(in, "*.example.com", 443) assert.Error(t, err, "a wildcard host is refused before any profile is bound") } @@ -288,3 +289,67 @@ endpoints: 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") +} diff --git a/internal/inference/actionsoidc/actionsoidc.go b/internal/inference/actionsoidc/actionsoidc.go index 545a35c865..888ff01e15 100644 --- a/internal/inference/actionsoidc/actionsoidc.go +++ b/internal/inference/actionsoidc/actionsoidc.go @@ -211,10 +211,9 @@ func configuredGitHubServer(getenv func(string) string) (host, port string) { if base == "" { return "", "" } - u, err := url.Parse(base) - if err != nil || u.Hostname() == "" { - 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) } diff --git a/internal/inference/actionsoidc/server_host_test.go b/internal/inference/actionsoidc/server_host_test.go index 4eee3aab2c..36227a7350 100644 --- a/internal/inference/actionsoidc/server_host_test.go +++ b/internal/inference/actionsoidc/server_host_test.go @@ -32,6 +32,9 @@ func TestRequireGitHubOIDCHostRefusesOtherHosts(t *testing.T) { 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") } From c1fc4148d3cfe2d0d5befdf934505019e2181070 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 14:05:49 -0500 Subject: [PATCH 6/9] fix(run): write GH_ENTERPRISE_TOKEN in a form the .env loader expands The runtime .env loader (internal/runtime/env_data.go) takes $NAME and ${NAME} but rejects ${NAME:-default}, so the copy of the GH_TOKEN placeholder was dropped at launch and gh on the configured server ran unauthenticated. Use ${GH_TOKEN}, which the loader expands to an empty string when unset, and test the lines through the loader itself. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/github_profile.go | 9 +++++---- internal/cli/github_profile_test.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go index 59e847a608..8f12815962 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -76,12 +76,13 @@ func githubForgeSandboxEnvLines(getenv func(string) string) []string { } else if strings.Contains(host, ":") { ghHost = "[" + host + "]" } - // A plain export, not a conditional: the sandbox .env loader and the - // env manifest collector read assignments and exports only. An empty - // GH_TOKEN leaves GH_ENTERPRISE_TOKEN empty, which gh treats as unset. + // 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:-}"`, + `export GH_ENTERPRISE_TOKEN="${GH_TOKEN}"`, } } diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index 3e1577be36..4ee8f61531 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -2,7 +2,9 @@ package cli import ( "os" + "os/exec" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -10,6 +12,7 @@ import ( "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" ) @@ -179,7 +182,7 @@ func TestGitHubForgeSandboxEnvLines(t *testing.T) { assert.Equal(t, []string{ "export GH_HOST='ghemu.localhost'", - `export GH_ENTERPRISE_TOKEN="${GH_TOKEN:-}"`, + `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. @@ -353,3 +356,27 @@ func TestBindGitHubForgeHostSkipsProfilesItLeavesAlone(t *testing.T) { 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) + } +} From dd4c9ce91e44125fae103e099759504223a36fc4 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 15:59:40 -0500 Subject: [PATCH 7/9] docs(run): document the GitHub server binding for GITHUB_SERVER_URL Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/cli/run.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/cli/run.md b/docs/cli/run.md index d5d3644e10..43243a8476 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. +- **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 From f0405f2b990a6bbfc113fe82f6858ed28f4536b4 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 16:51:04 -0500 Subject: [PATCH 8/9] fix(run): refuse merge keys in profiles bound to a GitHub server addGitHubForgeEndpoints reads literal keys, so a merge key could hide GH_TOKEN or an endpoint's host and leave the profile unbound while GH_HOST pointed gh at the server. Run checkProfileKeys first, as the GitLab binding does. Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/cli/run.md | 2 +- internal/cli/github_profile.go | 7 +++++++ internal/cli/github_profile_test.go | 26 ++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 43243a8476..0bfbef15a9 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -536,7 +536,7 @@ For the exact errors and fixes, see [Self-Hosted GitLab Instances](../guides/get 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. +- **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. diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go index 8f12815962..817f3f0388 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -180,6 +180,13 @@ func addGitHubForgeEndpoints(data []byte, host string, port int) ([]byte, bool, 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 } diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index 4ee8f61531..ded43c91aa 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -380,3 +380,29 @@ func TestGitHubForgeSandboxEnvLinesThroughTheRuntimeLoader(t *testing.T) { 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) + } +} From c2d251aa83e356d430e1648126451dbd19347c5d Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Tue, 17 Nov 2026 17:36:24 -0500 Subject: [PATCH 9/9] fix(run): refuse a second YAML document in a GitHub-bound profile Parse with parseSingleProfileDocument, as the GitLab binding does: yaml.Unmarshal read only the first document, so a rewrite dropped the rest. This also makes the run.md sentence on refused profile shapes hold for the GitHub binding. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/github_profile.go | 12 +++++++----- internal/cli/github_profile_test.go | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/internal/cli/github_profile.go b/internal/cli/github_profile.go index 817f3f0388..f75601c926 100644 --- a/internal/cli/github_profile.go +++ b/internal/cli/github_profile.go @@ -172,11 +172,13 @@ func bindGitHubForgeHostBytes(data []byte, getenv func(string) string) ([]byte, // 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) { - var doc yaml.Node - if err := yaml.Unmarshal(data, &doc); err != nil { - return nil, false, fmt.Errorf("parsing profile YAML: %w", err) + // 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.Kind != yaml.DocumentNode || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { + 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] @@ -257,7 +259,7 @@ func addGitHubForgeEndpoints(data []byte, host string, port int) ([]byte, bool, var buf bytes.Buffer enc := yaml.NewEncoder(&buf) enc.SetIndent(2) - if err := enc.Encode(&doc); err != nil { + if err := enc.Encode(doc); err != nil { return nil, false, fmt.Errorf("marshaling profile YAML: %w", err) } if err := enc.Close(); err != nil { diff --git a/internal/cli/github_profile_test.go b/internal/cli/github_profile_test.go index ded43c91aa..9a234ef8b6 100644 --- a/internal/cli/github_profile_test.go +++ b/internal/cli/github_profile_test.go @@ -406,3 +406,17 @@ endpoints: 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) +}