Use separate PAT credentials for Amadan git transport
Co-Authored-By: Astra <noreply@openai.com>
19 files changed,
+644
−60
docs/live-gate.md+43 −0docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md+201 −0internal/equipo/team/publication_forge_test.go+1 −1internal/equipotest/runner_flow_test.go+1 −1internal/runner/config_test.go+6 −5internal/runner/direct_graph_test.go+1 −1internal/runner/forge/credential_file.go+67 −0internal/runner/forge/credential_file_test.go+76 −0internal/runner/forge/description_test.go+4 −4internal/runner/forge/git.go+2 −1internal/runner/forge/publisher.go+6 −2internal/runner/forge/publisher_test.go+12 −7internal/runner/journal_test.go+6 −6internal/runner/runtime_workflow.go+2 −25internal/runner/workspace/git_auth_test.go+142 −0internal/runner/workspace/workspace.go+16 −5internal/runner/workspace/workspace_test.go+1 −1internal/runnerproto/event_io.go+1 −1scripts/runner-reference-allowlist.json+56 −0
CI passed — run details
Intent
diff --git a/docs/live-gate.md b/docs/live-gate.md| index 00b6e647..f5bdfd64 100644 |
| --- a/docs/live-gate.md |
| +++ b/docs/live-gate.md |
| @@ -105,3 +105,46 @@ unavailable at dispatch with `provider_policy_uncertified`. Deployment |
| and enabling execution remain human actions. Before upgrading an existing |
| instance, stop its old runner and all its children, then resolve any task waiting |
| for **Old runner stopped**. |
| + |
| +## Amadan credentials for the runner |
| + |
| +The runner needs an API bearer and a separate personal access token (PAT) for |
| +Git. Both belong to the disclosed agent account. As the agent's operator, mint |
| +its API bearer with `amadan agent token create equipo` (replace `equipo` with |
| +your registered agent name). In the agent's private Amadan home, save that bearer |
| +in `credentials` as `{"https://amadan.net":"<api bearer>"}`, with mode `0600`. |
| +Keep the home at mode `0700`. Then mint the Git PAT as that agent: |
| + |
| +```sh |
| +AMADAN_HOME="$HOME/.local/share/equipo-runner/amadan-agent-home" \ |
| + amadan tokens create -label equipo-runner-git |
| +``` |
| + |
| +These commands show the new credentials once. Use a private terminal without |
| +session recording. Save only the PAT value, without the command's explanatory |
| +text, in `~/.local/share/equipo-runner/amadan-agent-home/git-pat`, mode `0600`. |
| + |
| +Set `EQUIPO_AMADAN_CREDENTIAL_PATH` to a regular file with mode `0600` containing: |
| + |
| +```json |
| +{ |
| + "agent": "equipo~operator@example.com", |
| + "repositories": { |
| + "amadan.net/oficina/equipo": { |
| + "api": "<agent API bearer>", |
| + "git": "<agent Git PAT>" |
| + } |
| + } |
| +} |
| +``` |
| + |
| +Use your agent's full disclosed identity and an entry for each repository it |
| +will work on. API requests use Bearer auth. Git fetch and push use Basic auth |
| +with username `x` and the PAT as the password, supplied only through the Git |
| +process environment. Neither credential is copied into provider workspaces. |
| +The credential file remains a protected path for provider and check sandboxes. |
| + |
| +An old string entry is still read as an API bearer. Git refuses it with |
| +`configure a repository git password (PAT) in EQUIPO_AMADAN_CREDENTIAL_PATH` |
| +until you add the PAT. The controller's atomic conversion procedure is in |
| +[the forge git auth report](superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md). |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md b/docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md| new file mode 100644 |
| index 00000000..4162cd90 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md |
| @@ -0,0 +1,201 @@ |
| +# Forge git authentication |
| + |
| +Implemented on `forge-git-auth`, from brief commit `4940731` above deployed |
| +base `e99d178`. Copy accepted for now under the task brief. |
| + |
| +Credential-file handling now lives in `internal/runner/forge/credential_file.go`, |
| +so its tests fit the existing package budgets. Runtime wiring uses that reader |
| +for fetch and publication. The file accepts per-repository `api` and `git` values. Legacy |
| +string entries remain API-only. Fetch and publication require a Git PAT and |
| +use `Authorization: Basic base64("x:" + pat)` in `GIT_CONFIG_*`. API readback |
| +and the Amadan description command retain the bearer. Missing PATs produce a |
| +configuration error before fetch. Basic auth values are now redacted from |
| +journal text and downloaded logs. |
| + |
| +## Controller conversion |
| + |
| +No production credentials were opened or changed during implementation. The |
| +controller owns this conversion. First mint the agent's API bearer with |
| +`amadan agent token create equipo` if it does not already exist. Configure the |
| +agent's private Amadan home with that bearer, then run |
| +`AMADAN_HOME="$HOME/.local/share/equipo-runner/amadan-agent-home" amadan tokens create -label equipo-runner-git`. |
| +The setup and file formats are described in [the live guide](../../live-gate.md#amadan-credentials-for-the-runner). |
| + |
| +Save just the PAT value at |
| +`~/.local/share/equipo-runner/amadan-agent-home/git-pat`, mode `0600`. Keep the |
| +agent home private (`0700`). Run this snippet as the owner of the existing |
| +runner files on docs-t1. It preserves the API bearer, agent identity and other |
| +repository entries, replaces only the Equipo repository entry, and writes the |
| +new file atomically with mode `0600`. It prints no credentials and makes no |
| +network requests. It also accepts an already converted entry. |
| + |
| +```python |
| +import json |
| +import os |
| +from pathlib import Path |
| +import stat |
| +import tempfile |
| + |
| +root = Path.home() / ".local/share/equipo-runner" |
| +path = root / "amadan.json" |
| +pat_path = root / "amadan-agent-home/git-pat" |
| +repo = "amadan.net/oficina/equipo" |
| +temporary = None |
| + |
| + |
| +def read_private(source): |
| + fd = os.open(source, os.O_RDONLY | os.O_NOFOLLOW) |
| + with os.fdopen(fd, "r", encoding="utf-8") as stream: |
| + info = os.fstat(stream.fileno()) |
| + if (not stat.S_ISREG(info.st_mode) |
| + or stat.S_IMODE(info.st_mode) != 0o600 |
| + or info.st_uid != os.getuid() |
| + or info.st_size > 1024 * 1024): |
| + raise ValueError("Expected a private credential file") |
| + return stream.read() |
| + |
| + |
| +def valid_secret(value): |
| + return (isinstance(value, str) and bool(value) |
| + and not any(c.isspace() or c == "\0" for c in value)) |
| + |
| + |
| +try: |
| + data = json.loads(read_private(path)) |
| + pat = read_private(pat_path).strip() |
| + entry = data["repositories"][repo] |
| + api = entry if isinstance(entry, str) else entry["api"] |
| + if not valid_secret(api) or not valid_secret(pat): |
| + raise ValueError("Expected credential values") |
| + if not isinstance(data["agent"], str) or not data["agent"]: |
| + raise ValueError("Expected agent identity") |
| + data["repositories"][repo] = {"api": api, "git": pat} |
| + fd, temporary = tempfile.mkstemp(prefix=".amadan-", dir=root) |
| + with os.fdopen(fd, "w", encoding="utf-8") as stream: |
| + os.fchmod(stream.fileno(), 0o600) |
| + json.dump(data, stream, indent=2) |
| + stream.write("\n") |
| + stream.flush() |
| + os.fsync(stream.fileno()) |
| + os.replace(temporary, path) |
| + temporary = None |
| + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY) |
| + try: |
| + os.fsync(directory) |
| + finally: |
| + os.close(directory) |
| +except Exception: |
| + raise SystemExit("Credential conversion failed; check the private files") from None |
| +finally: |
| + if temporary is not None: |
| + os.unlink(temporary) |
| +``` |
| + |
| +The live read-only fetch is allowed only after the controller converts the |
| +file. It has not been run in this session. No deployment or live provider session |
| +was launched. |
| + |
| +## Regression evidence |
| + |
| +Tests were written before the implementation. This command failed on the old |
| +code: the new object entries were unreadable, legacy entries were accepted for |
| +git, Basic auth leaked into the journal, and publication still used Bearer: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner ./internal/runner/forge -run 'TestForgeCredentialsSplitAndLegacy|TestForgeBasicCredentialsAbsentFromJournalAndLog|TestPublishCredentialIsolationHTTPS' -count=1 |
| +``` |
| + |
| +`CGO_ENABLED=0 go test ./internal/runner/workspace -run 'TestWorkspaceGit' -count=1` |
| +also failed before implementation: fetch did not use Basic, and a missing PAT |
| +reached git without a configuration diagnostic. |
| + |
| +After implementation and the package move, the following targeted run passed: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner ./internal/runner/forge ./internal/runner/workspace -run 'TestForge|TestRunnerConfig$|TestRunnerJournalSecrets|TestPublish|TestAmadan|TestWorkspace' -count=1 |
| +``` |
| + |
| +The changed protocol redactor is exercised by the runner journal and log tests. |
| +Publication and fetch |
| +use instrumented git commands against disposable local repositories. The tests |
| +check the exact Basic value, absence from arguments and local git commands, |
| +provider environments, saved workspace files and publication state. API tests |
| +carry distinct bearer and PAT values and require the bearer for both HTTP and |
| +the description command. Tests also cover malformed entries, repository |
| +boundaries, missing PATs, control characters, public files and symlinks. |
| + |
| +Each guard below was deliberately broken, tested, and restored. Every command |
| +exited 1 with the corresponding test assertion failure, not a compilation |
| +failure. The final mutation runs followed the package move. The journal and log |
| +assertions both failed when Basic redaction was removed. |
| + |
| +| Broken behavior | Command that caught it | |
| +| --- | --- | |
| +| fetch auth scheme | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitBasicIsolation -count=1` | |
| +| publish auth scheme | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublishCredentialIsolationHTTPS -count=1` | |
| +| API retains bearer | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestAmadanDescriptionReadback/valid$ -count=1` | |
| +| legacy refuses git | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestForgeCredentialsSplitAndLegacy/legacy -count=1` | |
| +| fetch requires PAT | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitRequiresPassword -count=1` | |
| +| publish requires PAT | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublishEvidenceAndCredentialGuards/git_missing -count=1` | |
| +| publish validates PAT | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublishEvidenceAndCredentialGuards/git_header -count=1` | |
| +| journal and log redaction | `CGO_ENABLED=0 go test ./internal/runner -run ^TestRunnerJournalSecretsAndLog -count=1` | |
| +| protected credential path | `CGO_ENABLED=0 go test ./internal/runner -run ^TestRunnerConfig$ -count=1` | |
| +| provider environment | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitBasicIsolation -count=1` | |
| +| publish persisted state | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublishCredentialIsolation$ -count=1` | |
| +| fetch credentials in argv | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitBasicIsolation -count=1` | |
| +| fetch validates PAT | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitPasswordValidation -count=1` | |
| +| local fetch forbids PAT | `CGO_ENABLED=0 go test ./internal/runner/workspace -run ^TestWorkspaceGitPasswordValidation/local -count=1` | |
| +| configuration validates PAT | `CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestForgeCredentialInvalidEntries -count=1` | |
| + |
| +The exact conversion snippet above was extracted and run with disposable fake |
| +homes. Legacy conversion and a second conversion passed without output; |
| +identity and unrelated repository entries stayed unchanged. Mode `0600` was |
| +preserved. Empty values, copied CLI output, public PAT files and symlinks were |
| +refused without altering the credential file or leaving temporary files. |
| + |
| + |
| +## Full gate |
| + |
| +The first `make -k ci` exited 2. Its reference scan found unclassified paths in |
| +the new guide and the supplied brief, and the new tests exceeded the runner |
| +package's existing line budget. Both checks now pass: the exact references |
| +have reasoned inventory entries, and the credential reader and its tests live |
| +in forge. The budget limits were not raised. |
| + |
| +The first full tests also found two external publication fixtures without |
| +PATs. Those now use distinct test passwords. Release-copy tests encountered a |
| +missing test file because the package move happened while that run read the |
| +checkout. The moved files are staged together for the final run. Build, vet, |
| +formatting, staticcheck, govulncheck, gitleaks, adapter checks, namespace checks, |
| +migrations and performance passed in the first run. The vulnerability scan |
| +found no reachable vulnerabilities; gitleaks found no secrets. |
| + |
| +After updating the external fixtures, this combined targeted command passed |
| +(team 0.969s, app integration 34.896s, runner 0.113s, forge 11.664s, |
| +workspace 1.332s): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/equipo/team ./internal/equipotest ./internal/runner ./internal/runner/forge ./internal/runner/workspace -run 'TestPublishCoreAuthorizationContract$|TestRunnerDirectEndToEnd$|TestForge|TestRunnerConfig$|TestRunnerJournalSecrets|TestPublish|TestAmadan|TestWorkspace' -count=1 |
| +``` |
| + |
| +The second `make -k ci` exited 0. This was the only full rerun. All lanes passed: |
| +reference inventory, build, vet, formatting, staticcheck, govulncheck, gitleaks, |
| +size budgets, full tests, adapter checks, namespace checks, migrations and |
| +performance. The required sandbox tests include the protected Amadan path. |
| +Cold boot had a 110ms median against the 500ms budget. No budget exceptions |
| +were changed. |
| + |
| +The final checkout was held unchanged throughout that run. Scratch scripts, |
| +logs and conversion fixtures were removed after recording these results. |
| +Production credentials remain untouched. The controller still needs to run the |
| +conversion before any live read-only fetch. No deployment, default-branch push, |
| +push to another repository, live provider session or copy-review server was |
| +started. |
| + |
| +## Push status |
| + |
| +`git push -u origin HEAD:refs/heads/forge-git-auth` failed because this checkout |
| +has no HTTPS Git authentication (`could not read Username`). The implementation |
| +is committed locally. The controller must enable Git authentication here or |
| +push the branch. No production credential file was read to work around this. |
| +The committed history passed a second secret scan before the push attempt. |
diff --git a/internal/equipo/team/publication_forge_test.go b/internal/equipo/team/publication_forge_test.go| index b1c6f3ca..92169af8 100644 |
| --- a/internal/equipo/team/publication_forge_test.go |
| +++ b/internal/equipo/team/publication_forge_test.go |
| @@ -35,7 +35,7 @@ func TestPublishCoreAuthorizationContract(t *testing.T) { |
| t.Run(agent, func(t *testing.T) { |
| exported := false |
| p, err := forge.New(forge.Config{Root: filepath.Join(t.TempDir(), "private"), GitPath: "/usr/bin/git", Runner: a.Ticket.Handle.Runner, Incarnation: a.Ticket.Incarnation, Clock: func() time.Time { return now }, Authorize: func(context.Context, team.Dispatch) (forge.Authorization, error) { return a, nil }, Revalidate: func(context.Context, forge.Authorization) error { return nil }, Credential: func(context.Context, string) (forge.Credential, error) { |
| - return forge.Credential{Remote: "https://" + a.Target.Repository, Agent: agent, Bearer: "offline-fixture"}, nil |
| + return forge.Credential{Remote: "https://" + a.Target.Repository, Agent: agent, Bearer: "offline-fixture", GitPassword: "git-offline-fixture"}, nil |
| }, Export: func(context.Context, team.GitCandidate, string) error { exported = true; return team.ErrNotDispatched }, Description: noDescription{t}}) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/equipotest/runner_flow_test.go b/internal/equipotest/runner_flow_test.go| index 3fd9672b..6b77cb65 100644 |
| --- a/internal/equipotest/runner_flow_test.go |
| +++ b/internal/equipotest/runner_flow_test.go |
| @@ -168,7 +168,7 @@ func TestRunnerDirectEndToEnd(t *testing.T) { |
| return forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: active.Handle.Runner, Incarnation: auth.Ticket.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { |
| return api.Call(ctx, "validate", flowRequest(active, "publication-check"), nil) |
| }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) { |
| - return forge.Credential{Remote: "https://" + f.project.Repository, Agent: "test~person@example.test", Bearer: "fixture-only"}, nil |
| + return forge.Credential{Remote: "https://" + f.project.Repository, Agent: "test~person@example.test", Bearer: "fixture-only", GitPassword: "git-fixture-only"}, nil |
| }, Description: description}) |
| } |
| workflow, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{Namespaces: namespaces, Launchers: registry, Launch: launch, PublisherFor: publisherFor, Workspaces: manager, Witness: w, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "fixture", Copy: runner.ToolCopy{Accepted: "accepted", Rejected: "rejected"}}) |
diff --git a/internal/runner/config_test.go b/internal/runner/config_test.go| index a6b50034..24aa92ee 100644 |
| --- a/internal/runner/config_test.go |
| +++ b/internal/runner/config_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "net/http" |
| "os" |
| "path/filepath" |
| + "slices" |
| "strings" |
| "testing" |
| "time" |
| @@ -21,15 +22,15 @@ func configFixture(t *testing.T) Config { |
| t.Helper() |
| root := t.TempDir() |
| amadan := filepath.Join(root, "amadan") |
| - if err := os.WriteFile(amadan, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { |
| - t.Fatal(err) |
| - } |
| + mustJournal(t, os.WriteFile(amadan, []byte("#!/bin/sh\nexit 0\n"), 0700)) |
| return Config{BwrapPath: "/usr/bin/bwrap", ClaudePath: "/usr/bin/claude", CodexCodeModeHostPath: "/usr/bin/codex-code-mode-host", Origin: "https://equipo.example", StateDir: filepath.Join(root, "state"), AmadanCredentialPath: filepath.Join(root, "forge.json"), AccountBindingsPath: filepath.Join(root, "bindings.json"), CodexPath: "/usr/bin/codex", GoRoot: "/opt/go", GoBinary: "/opt/go/bin/go", WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: amadan, Executable: "/usr/bin/equipo-runner", InstanceID: "instance"} |
| } |
| func TestRunnerConfig(t *testing.T) { |
| c := configFixture(t) |
| - if err := c.validate(); err != nil { |
| - t.Fatal(err) |
| + mustJournal(t, c.validate()) |
| + policy, err := bindingPolicy(c, nil, AccountBinding{}) |
| + if err != nil || c.securityPaths(nil).ForgeCredential != c.AmadanCredentialPath || !slices.Contains(policy.DeniedPaths, c.AmadanCredentialPath) { |
| + t.Fatal("forge credentials absent from protected paths", err) |
| } |
| for _, origin := range []string{"http://example.com", "https://user:pass@example.com", "https://example.com/path", "https://example.com?x=y", "https://example.com/#x"} { |
| bad := c |
diff --git a/internal/runner/direct_graph_test.go b/internal/runner/direct_graph_test.go| index f431d8c7..3394278e 100644 |
| --- a/internal/runner/direct_graph_test.go |
| +++ b/internal/runner/direct_graph_test.go |
| @@ -236,7 +236,7 @@ func runDirectPlanGraph(t *testing.T, feature, extra, readWork bool) { |
| publisher, err = forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: "runner", Incarnation: status.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { |
| return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle) |
| }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) { |
| - return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only"}, nil |
| + return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only", GitPassword: "git-fixture-only"}, nil |
| }, Description: &workflowDescription{}}) |
| wfMust(t, err) |
| } |
diff --git a/internal/runner/forge/credential_file.go b/internal/runner/forge/credential_file.go| new file mode 100644 |
| index 00000000..17e85da9 |
| --- /dev/null |
| +++ b/internal/runner/forge/credential_file.go |
| @@ -0,0 +1,67 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type FileCredentials struct{ Path string } |
| +type forgeCredentialFile struct { |
| + Agent string `json:"agent"` |
| + Repositories map[string]json.RawMessage `json:"repositories"` |
| +} |
| + |
| +func (f FileCredentials) Credential(_ context.Context, repo string) (Credential, error) { |
| + var file forgeCredentialFile |
| + if err := readCredentialFile(f.Path, &file); err != nil { |
| + return Credential{}, err |
| + } |
| + var entry struct { |
| + API string `json:"api"` |
| + Git string `json:"git"` |
| + } |
| + raw := file.Repositories[repo] |
| + // Legacy entries grant API access only; an agent bearer is not a git password. |
| + if json.Unmarshal(raw, &entry.API) != nil { |
| + if err := runnerproto.DecodeLimit(strings.NewReader(string(raw)), &entry, 1<<20); err != nil { |
| + return Credential{}, provider.ErrIdentity |
| + } |
| + } |
| + token := entry.API |
| + if !strings.HasPrefix(repo, "amadan.net/") || strings.ContainsAny(repo+token+entry.Git, "\r\n\x00") || token == "" || file.Agent == "" { |
| + return Credential{}, provider.ErrIdentity |
| + } |
| + return Credential{Remote: "https://" + repo, Agent: file.Agent, Bearer: token, GitPassword: entry.Git}, nil |
| +} |
| +func (f FileCredentials) Resolve(ctx context.Context, repo string) (workspace.Remote, error) { |
| + c, err := f.Credential(ctx, repo) |
| + if err != nil { |
| + return workspace.Remote{}, err |
| + } |
| + if c.GitPassword == "" { |
| + return workspace.Remote{}, workspace.ErrGitPassword |
| + } |
| + return workspace.Remote{URL: c.Remote, GitPassword: c.GitPassword}, nil |
| +} |
| + |
| +func readCredentialFile(path string, out *forgeCredentialFile) error { |
| + info, err := os.Lstat(path) |
| + if err != nil { |
| + return err |
| + } |
| + if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > 1<<20 { |
| + return provider.ErrPolicy |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + return runnerproto.DecodeLimit(f, out, 1<<20) |
| +} |
diff --git a/internal/runner/forge/credential_file_test.go b/internal/runner/forge/credential_file_test.go| new file mode 100644 |
| index 00000000..84cba013 |
| --- /dev/null |
| +++ b/internal/runner/forge/credential_file_test.go |
| @@ -0,0 +1,76 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestForgeCredentialsSplitAndLegacy(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, entry string |
| + git bool |
| + }{ |
| + {"split", `{"api":"api-canary","git":"git-canary"}`, true}, |
| + {"legacy", `"api-canary"`, false}, |
| + {"api only", `{"api":"api-canary"}`, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "amadan.json") |
| + raw := `{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/repo":` + tc.entry + `}}` |
| + must(t, os.WriteFile(path, []byte(raw), 0600)) |
| + f := FileCredentials{Path: path} |
| + c, err := f.Credential(context.Background(), "amadan.net/ns/repo") |
| + if err != nil || c.Bearer != "api-canary" { |
| + t.Fatal("API credential unavailable", err) |
| + } |
| + remote, err := f.Resolve(context.Background(), "amadan.net/ns/repo") |
| + if tc.git && (err != nil || c.GitPassword != "git-canary" || remote.GitPassword != "git-canary") { |
| + t.Fatal("git credential unavailable", err) |
| + } |
| + if !tc.git && (err == nil || !strings.Contains(err.Error(), "git password")) { |
| + t.Fatal("missing PAT needs a clear configuration error", err) |
| + } |
| + if _, err := f.Credential(context.Background(), "amadan.net/ns/other"); err == nil { |
| + t.Fatal("credential crossed repository boundary") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestForgeCredentialFileProtection(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "amadan.json") |
| + raw := `{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/repo":{"api":"api-canary","git":"git-canary"}}}` |
| + must(t, os.WriteFile(path, []byte(raw), 0600)) |
| + must(t, os.Chmod(path, 0644)) |
| + if _, err := (FileCredentials{Path: path}).Credential(context.Background(), "amadan.net/ns/repo"); err == nil { |
| + t.Fatal("public credential file accepted") |
| + } |
| + must(t, os.Chmod(path, 0600)) |
| + alias := filepath.Join(t.TempDir(), "alias") |
| + must(t, os.Symlink(path, alias)) |
| + if _, err := (FileCredentials{Path: alias}).Credential(context.Background(), "amadan.net/ns/repo"); err == nil { |
| + t.Fatal("symlink credential file accepted") |
| + } |
| +} |
| + |
| +func TestForgeCredentialInvalidEntries(t *testing.T) { |
| + for _, entry := range []string{`null`, `42`, `[]`, `{}`, `{"git":"git-canary"}`, `{"api":"api-canary","git":123}`, `{"api":"api-canary","git":"git-canary","extra":"secret-canary"}`, `{"api":"api-canary\r\nInjected: secret-canary","git":"git-canary"}`, `{"api":"api-canary","git":"git-canary\u0000"}`} { |
| + t.Run(entry, func(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "amadan.json") |
| + raw := `{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/repo":` + entry + `}}` |
| + must(t, os.WriteFile(path, []byte(raw), 0600)) |
| + _, err := (FileCredentials{Path: path}).Resolve(context.Background(), "amadan.net/ns/repo") |
| + if err == nil { |
| + t.Fatal("invalid credential accepted") |
| + } |
| + for _, secret := range []string{"api-canary", "git-canary", "secret-canary"} { |
| + if strings.Contains(err.Error(), secret) { |
| + t.Fatal("credential leaked in error") |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/forge/description_test.go b/internal/runner/forge/description_test.go| index a1bbfa09..2934fe5b 100644 |
| --- a/internal/runner/forge/description_test.go |
| +++ b/internal/runner/forge/description_test.go |
| @@ -79,7 +79,7 @@ func TestAmadanDescriptionLengthHash(t *testing.T) { |
| } |
| func TestAmadanDescriptionReadback(t *testing.T) { |
| - cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only"} |
| + cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| body := " Equipo café\n unconfined; approved beyond profile\n" |
| for _, name := range []string{"valid", "optional_agent", "reordered", "tamper", "wrong_hash", "wrong_agent", "bad_metadata", "empty", "invalid_utf8", "malformed", "malformed_at", "trailing", "oversized", "redirect", "auth", "timeout"} { |
| t.Run(name, func(t *testing.T) { |
| @@ -205,7 +205,7 @@ assert json.load(open(path)) == {'https://amadan.net':'fake-only'} |
| assert sys.stdin.read() == ' Equipo café\n unconfined; approved beyond profile\n' |
| ` |
| must(t, os.WriteFile(command, []byte(script), 0700)) |
| - cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only"} |
| + cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: " Equipo café\n unconfined; approved beyond profile\n"} |
| desc.Digest = Digest([]byte(desc.Body)) |
| scratch := filepath.Join(root, "scratch") |
| @@ -292,7 +292,7 @@ func TestAmadanDescriptionNotDispatched(t *testing.T) { |
| root := t.TempDir() |
| command := filepath.Join(root, "command") |
| must(t, os.WriteFile(command, []byte("#!/bin/sh\nexit 1\n"), 0700)) |
| - cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only"} |
| + cred := Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"} |
| desc := Description{Repository: "amadan.net/oficina/equipo", Ref: "review/trial", Agent: cred.Agent, Body: "body"} |
| desc.Digest = Digest([]byte(desc.Body)) |
| for _, mode := range []string{"validation", "relative_path", "unclean_path", "missing_command", "not_executable", "scratch", "cancelled", "started", "missing_writer"} { |
| @@ -343,7 +343,7 @@ func TestDescriptionIgnoresDefaultProxyClient(t *testing.T) { |
| })} |
| ctx, cancel := context.WithCancel(context.Background()) |
| cancel() |
| - _, _ = ReadBranchDescription(ctx, nil, Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only"}, "amadan.net/oficina/equipo", "heads/fix") |
| + _, _ = ReadBranchDescription(ctx, nil, Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only", GitPassword: "git-canary"}, "amadan.net/oficina/equipo", "heads/fix") |
| if called { |
| t.Fatal("description used ambient proxy client") |
| } |
diff --git a/internal/runner/forge/git.go b/internal/runner/forge/git.go| index 9626586c..aa0678a5 100644 |
| --- a/internal/runner/forge/git.go |
| +++ b/internal/runner/forge/git.go |
| @@ -2,6 +2,7 @@ package forge |
| import ( |
| "context" |
| + "encoding/base64" |
| "io" |
| "os" |
| "os/exec" |
| @@ -29,7 +30,7 @@ func (p *Publisher) git(ctx context.Context, dir string, cred *Credential, args |
| if cred != nil && p.localRemote == nil { |
| env["GIT_CONFIG_COUNT"] = "10" |
| env["GIT_CONFIG_KEY_9"] = "http.extraHeader" |
| - env["GIT_CONFIG_VALUE_9"] = "Authorization: Bearer " + cred.Bearer |
| + env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x:"+cred.GitPassword)) |
| } |
| for k, v := range env { |
| cmd.Env = append(cmd.Env, k+"="+v) |
diff --git a/internal/runner/forge/publisher.go b/internal/runner/forge/publisher.go| index 347de1f1..d292a66b 100644 |
| --- a/internal/runner/forge/publisher.go |
| +++ b/internal/runner/forge/publisher.go |
| @@ -16,12 +16,13 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| type Authorization = runnerproto.PublicationAuthorization |
| -type Credential struct{ Remote, Agent, Bearer string } |
| +type Credential struct{ Remote, Agent, Bearer, GitPassword string } |
| type Description struct { |
| Repository, Ref, Agent, Body, Digest string |
| At int64 |
| @@ -147,9 +148,12 @@ func (p *Publisher) credential(ctx context.Context, repository string) (Credenti |
| return Credential{}, team.ErrUncertain |
| } |
| u, e := url.Parse(c.Remote) |
| - if e != nil || !team.ValidPublicationAgent(c.Agent) || c.Bearer == "" || strings.ContainsAny(c.Bearer+c.Remote, "\r\n\x00") || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" || c.Remote != "https://"+repository || u.String() != c.Remote { |
| + if e != nil || !team.ValidPublicationAgent(c.Agent) || c.Bearer == "" || strings.ContainsAny(c.Bearer+c.GitPassword+c.Remote, "\r\n\x00") || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" || c.Remote != "https://"+repository || u.String() != c.Remote { |
| return Credential{}, team.ErrInvalid |
| } |
| + if c.GitPassword == "" { |
| + return Credential{}, workspace.ErrGitPassword |
| + } |
| return c, nil |
| } |
diff --git a/internal/runner/forge/publisher_test.go b/internal/runner/forge/publisher_test.go| index 445a1fd8..069e01da 100644 |
| --- a/internal/runner/forge/publisher_test.go |
| +++ b/internal/runner/forge/publisher_test.go |
| @@ -2,6 +2,7 @@ package forge |
| import ( |
| "context" |
| + "encoding/base64" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -124,7 +125,7 @@ func newFixture(t *testing.T) *fixture { |
| gitTest(t, root, "clone", "--no-local", "--template=", source, dir) |
| return nil |
| }, Credential: func(context.Context, string) (Credential, error) { |
| - return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary"}, nil |
| + return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary", GitPassword: "git-canary"}, nil |
| }, Description: f.desc} |
| var err error |
| f.p, err = newPublisher(cfg, func(_ string) string { return remote }) |
| @@ -257,7 +258,7 @@ func TestPublishCredentialIsolation(t *testing.T) { |
| if e != nil { |
| return e |
| } |
| - if strings.Contains(string(b), "agent-canary") || strings.Contains(string(b), "person-canary") { |
| + if strings.Contains(string(b), "agent-canary") || strings.Contains(string(b), "person-canary") || strings.Contains(string(b), "git-canary") || strings.Contains(string(b), base64.StdEncoding.EncodeToString([]byte("x:git-canary"))) { |
| t.Fatal("credential persisted", path) |
| } |
| } |
| @@ -421,7 +422,7 @@ func TestPublishLostReceiptNoRedispatch(t *testing.T) { |
| } |
| func TestPublishEvidenceAndCredentialGuards(t *testing.T) { |
| - for _, name := range []string{"description", "digest", "taint", "acknowledgement", "tuple", "tuple_identity", "tags", "person", "http", "foreign_remote", "header"} { |
| + for _, name := range []string{"description", "digest", "taint", "acknowledgement", "tuple", "tuple_identity", "tags", "person", "http", "foreign_remote", "header", "git_header", "git_missing"} { |
| t.Run(name, func(t *testing.T) { |
| f := newFixture(t) |
| switch name { |
| @@ -455,6 +456,10 @@ func TestPublishEvidenceAndCredentialGuards(t *testing.T) { |
| c.Remote = "https://amadan.net/foreign/repo.git" |
| case "header": |
| c.Bearer = "token\r\nHeader: value" |
| + case "git_header": |
| + c.GitPassword = "git-canary\r\nHeader: value" |
| + case "git_missing": |
| + c.GitPassword = "" |
| } |
| return c, e |
| } |
| @@ -477,7 +482,7 @@ func TestPublishCanonicalRepository(t *testing.T) { |
| raw, _ := json.Marshal(f.auth.Publication) |
| f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw) |
| f.p.cfg.Credential = func(context.Context, string) (Credential, error) { |
| - return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary"}, nil |
| + return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary", GitPassword: "git-canary"}, nil |
| } |
| if _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch); err != nil { |
| t.Fatal("saved canonical project repository rejected", err) |
| @@ -515,7 +520,7 @@ os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ)) |
| } |
| must(t, json.Unmarshal([]byte(line), &row)) |
| args := strings.Join(row.Args, " ") |
| - if strings.Contains(args, "agent-canary") || row.Env["PERSON_SECRET"] != "" { |
| + if strings.Contains(args, "agent-canary") || strings.Contains(args, "git-canary") || strings.Contains(args, base64.StdEncoding.EncodeToString([]byte("x:git-canary"))) || strings.Contains(fmt.Sprint(row.Env), "agent-canary") || row.Env["PERSON_SECRET"] != "" { |
| t.Fatal("credential escaped allowed environment") |
| } |
| if row.Env["GIT_CONFIG_KEY_7"] != "maintenance.auto" || row.Env["GIT_CONFIG_VALUE_7"] != "false" || row.Env["GIT_CONFIG_KEY_8"] != "gc.autoDetach" || row.Env["GIT_CONFIG_VALUE_8"] != "false" { |
| @@ -524,10 +529,10 @@ os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ)) |
| remote := strings.Contains(args, "https://amadan.net/example/repo") |
| if remote { |
| remoteCalls++ |
| - if row.Env["GIT_CONFIG_COUNT"] != "10" || row.Env["GIT_CONFIG_KEY_9"] != "http.extraHeader" || row.Env["GIT_CONFIG_VALUE_9"] != "Authorization: Bearer agent-canary" { |
| + if row.Env["GIT_CONFIG_COUNT"] != "10" || row.Env["GIT_CONFIG_KEY_9"] != "http.extraHeader" || row.Env["GIT_CONFIG_VALUE_9"] != "Authorization: Basic "+base64.StdEncoding.EncodeToString([]byte("x:git-canary")) { |
| t.Fatal("runner credential missing") |
| } |
| - } else if strings.Contains(fmt.Sprint(row.Env), "agent-canary") { |
| + } else if strings.Contains(fmt.Sprint(row.Env), "git-canary") || strings.Contains(fmt.Sprint(row.Env), base64.StdEncoding.EncodeToString([]byte("x:git-canary"))) { |
| t.Fatal("credential exposed to local Git") |
| } |
| if strings.Contains(args, " push ") { |
diff --git a/internal/runner/journal_test.go b/internal/runner/journal_test.go| index 3e29c484..fa0405df 100644 |
| --- a/internal/runner/journal_test.go |
| +++ b/internal/runner/journal_test.go |
| @@ -202,12 +202,12 @@ func TestRunnerJournalSecretsAndLog(t *testing.T) { |
| mustJournal(t, err) |
| defer j.Close() |
| e := journalEvent("secret", 1) |
| - e.Payload = json.RawMessage(`{"authorization":"Bearer credential-value","text":"Bearer credential-value <script>alert(1)</script>","inputTokens":2}`) |
| + e.Payload = json.RawMessage(`{"authorization":"Bearer credential-value","text":"Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5 <script>alert(1)</script>","inputTokens":2}`) |
| mustJournal(t, j.Append(journalCtx, e)) |
| rows, err := j.Pending(journalCtx, 10) |
| mustJournal(t, err) |
| - if strings.Contains(string(rows[0].Payload), "credential-value") || !strings.Contains(string(rows[0].Payload), "inputTokens") { |
| - t.Fatal("redaction lost accounting or leaked secret", string(rows[0].Payload)) |
| + if strings.Contains(string(rows[0].Payload), "credential-value") || strings.Contains(string(rows[0].Payload), "eDpnaXQtY2FuYXJ5") || !strings.Contains(string(rows[0].Payload), "inputTokens") { |
| + t.Error("redaction lost accounting or leaked secret", string(rows[0].Payload)) |
| } |
| intent := provider.Intent{Kind: "agent", Key: "secret-intent", RequestHash: "hash", Request: json.RawMessage(`{"env":{"EQUIPO_TOOL_TOKEN":"private-key-value"}}`)} |
| mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| @@ -217,9 +217,9 @@ func TestRunnerJournalSecretsAndLog(t *testing.T) { |
| t.Fatal("intent persisted credential") |
| } |
| w := httptest.NewRecorder() |
| - DownloadLog(w, []byte(`<script>secret</script> Bearer credential-value`), []string{"secret"}) |
| - if strings.Contains(w.Body.String(), "<script>") || strings.Contains(w.Body.String(), "credential-value") || strings.Contains(w.Body.String(), "secret") || w.Header().Get("Content-Type") != "text/plain; charset=utf-8" { |
| - t.Fatal("unsafe log download", w.Body.String()) |
| + DownloadLog(w, []byte(`<script>secret</script> Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5`), []string{"secret"}) |
| + if strings.Contains(w.Body.String(), "<script>") || strings.Contains(w.Body.String(), "credential-value") || strings.Contains(w.Body.String(), "eDpnaXQtY2FuYXJ5") || strings.Contains(w.Body.String(), "secret") || w.Header().Get("Content-Type") != "text/plain; charset=utf-8" { |
| + t.Error("unsafe log download", w.Body.String()) |
| } |
| } |
| func TestBufferFullStopsWorkSQLite(t *testing.T) { |
diff --git a/internal/runner/runtime_workflow.go b/internal/runner/runtime_workflow.go| index 14b85738..551a4ab5 100644 |
| --- a/internal/runner/runtime_workflow.go |
| +++ b/internal/runner/runtime_workflow.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "encoding/json" |
| "path/filepath" |
| - "strings" |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| @@ -15,28 +14,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| -type forgeCredentials struct{ path string } |
| -type forgeCredentialFile struct { |
| - Agent string `json:"agent"` |
| - Repositories map[string]string `json:"repositories"` |
| -} |
| - |
| -func (f forgeCredentials) credential(_ context.Context, repo string) (forge.Credential, error) { |
| - var file forgeCredentialFile |
| - if err := privateJSON(f.path, &file); err != nil { |
| - return forge.Credential{}, err |
| - } |
| - token := file.Repositories[repo] |
| - if !strings.HasPrefix(repo, "amadan.net/") || strings.ContainsAny(repo+token, "\r\n\x00") || token == "" || file.Agent == "" { |
| - return forge.Credential{}, provider.ErrIdentity |
| - } |
| - return forge.Credential{Remote: "https://" + repo, Agent: file.Agent, Bearer: token}, nil |
| -} |
| -func (f forgeCredentials) Resolve(ctx context.Context, repo string) (workspace.Remote, error) { |
| - c, err := f.credential(ctx, repo) |
| - return workspace.Remote{URL: c.Remote, Bearer: c.Bearer}, err |
| -} |
| - |
| func (r *Runtime) active() (RunClaim, error) { |
| r.mu.Lock() |
| defer r.mu.Unlock() |
| @@ -133,7 +110,7 @@ func (r *Runtime) wire(ctx context.Context) error { |
| return provider.ErrIdentity |
| }}, r.sandbox) |
| } |
| - credentials := forgeCredentials{r.cfg.AmadanCredentialPath} |
| + credentials := forge.FileCredentials{Path: r.cfg.AmadanCredentialPath} |
| manager, err = workspace.New(workspace.Config{Protected: r.cfg.securityPaths(bs), PrivateRoot: filepath.Join(r.cfg.StateDir, "private"), WorkspaceRoot: r.cfg.WorkspaceRoot, GitPath: r.cfg.GitPath, Forge: credentials, Policy: r.policy, Definitions: func(ctx context.Context, target team.TargetBinding, repo string) (runnerproto.PreparedBug, error) { |
| c, err := r.active() |
| if err != nil { |
| @@ -167,7 +144,7 @@ func (r *Runtime) wire(ctx context.Context) error { |
| return provider.ErrIdentity |
| } |
| return r.api.Call(ctx, "validate", claimRequest(c, "publish-validate"), nil) |
| - }, Export: manager.ExportCandidate, Credential: credentials.credential, Description: forge.NewDescriptionTransport(nil, forge.NewCommandDescriptionWriter(r.cfg.AmadanPath, r.cfg.ScratchRoot))}) |
| + }, Export: manager.ExportCandidate, Credential: credentials.Credential, Description: forge.NewDescriptionTransport(nil, forge.NewCommandDescriptionWriter(r.cfg.AmadanPath, r.cfg.ScratchRoot))}) |
| } |
| workflow, err := NewPlanWorkflow(BugWorkflowConfig{UploadBlob: func(ctx context.Context, c RunClaim, hash string, raw []byte) error { |
| token, err := r.api.token(c.Assignment.ID, false) |
diff --git a/internal/runner/workspace/git_auth_test.go b/internal/runner/workspace/git_auth_test.go| new file mode 100644 |
| index 00000000..2ad232a3 |
| --- /dev/null |
| +++ b/internal/runner/workspace/git_auth_test.go |
| @@ -0,0 +1,142 @@ |
| +package workspace |
| + |
| +import ( |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestWorkspaceGitBasicIsolation(t *testing.T) { |
| + f := setup(t) |
| + password := "git-canary" |
| + header := "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x:"+password)) |
| + f.forge.remote = Remote{URL: "https://amadan.test/team/repo", GitPassword: password} |
| + log := filepath.Join(f.root, "observations") |
| + spy := filepath.Join(f.root, "git-spy") |
| + script := fmt.Sprintf(`#!/usr/bin/python3 |
| +import os,sys,json |
| +args=sys.argv[1:] |
| +with open(%q,'a') as out: |
| + out.write(json.dumps({'args':args,'env':dict(os.environ)})+'\n') |
| +if 'https://amadan.test/team/repo' in args: |
| + args[args.index('https://amadan.test/team/repo')]=%q |
| + args=['-c','protocol.file.allow=always']+args |
| +os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ)) |
| +`, log, f.remote) |
| + put(t, spy, script) |
| + if err := os.Chmod(spy, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.m.cfg.GitPath = spy |
| + t.Setenv("EQUIPO_API_SECRET", "api-canary") |
| + t.Setenv("GIT_TRACE_CURL", "1") |
| + w := f.create(t) |
| + data, err := os.ReadFile(log) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fetches := 0 |
| + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { |
| + var row struct { |
| + Args []string |
| + Env map[string]string |
| + } |
| + if err := json.Unmarshal([]byte(line), &row); err != nil { |
| + t.Fatal(err) |
| + } |
| + args := strings.Join(row.Args, " ") |
| + if strings.Contains(args, password) || strings.Contains(args, header) || row.Env["EQUIPO_API_SECRET"] != "" || row.Env["GIT_TRACE_CURL"] != "" { |
| + t.Fatal("credentials or tracing escaped into git process") |
| + } |
| + if strings.Contains(args, "https://amadan.test/team/repo") { |
| + fetches++ |
| + if row.Env["GIT_CONFIG_VALUE_9"] != header || row.Env["GIT_CONFIG_KEY_9"] != "http.extraHeader" || row.Env["GIT_CONFIG_COUNT"] != "10" { |
| + t.Fatal("fetch did not use Basic PAT") |
| + } |
| + } else if strings.Contains(fmt.Sprint(row.Env), header) { |
| + t.Fatal("PAT exposed to local git") |
| + } |
| + } |
| + if fetches != 1 { |
| + t.Fatal("HTTPS fetch not exercised") |
| + } |
| + if strings.Contains(fmt.Sprint(w.Environment()), password) || strings.Contains(fmt.Sprint(w.Environment()), header) { |
| + t.Fatal("PAT exposed to provider environment") |
| + } |
| + for _, root := range []string{f.cfg.PrivateRoot, f.cfg.WorkspaceRoot} { |
| + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if !d.Type().IsRegular() { |
| + return nil |
| + } |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + if strings.Contains(string(b), password) || strings.Contains(string(b), header) { |
| + t.Error("credential persisted in workspace state") |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Git may echo its environment on failure; callers must get only a safe error. |
| + put(t, spy, "#!/bin/sh\nprintf '%s' \"$GIT_CONFIG_VALUE_9\"\nprintf '%s' \"$GIT_CONFIG_VALUE_9\" >&2\nexit 1\n") |
| + _, _, err = f.m.fetch(ctx, f.target) |
| + if err == nil || strings.Contains(err.Error(), password) || strings.Contains(err.Error(), header) { |
| + t.Fatal("git failure leaked credentials") |
| + } |
| +} |
| + |
| +func TestWorkspaceGitRequiresPassword(t *testing.T) { |
| + f := setup(t) |
| + f.forge.remote = Remote{URL: "https://amadan.test/team/repo"} |
| + marker := filepath.Join(f.root, "git-ran") |
| + spy := filepath.Join(f.root, "git-spy") |
| + put(t, spy, "#!/bin/sh\ntouch '"+marker+"'\nexit 1\n") |
| + if err := os.Chmod(spy, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.m.cfg.GitPath = spy |
| + _, _, err := f.m.fetch(ctx, f.target) |
| + if err == nil || !strings.Contains(err.Error(), "git password") { |
| + t.Fatal("missing PAT needs a clear configuration error", err) |
| + } |
| + if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| + t.Fatal("git ran without a PAT") |
| + } |
| +} |
| + |
| +func TestWorkspaceGitPasswordValidation(t *testing.T) { |
| + for _, password := range []string{"git\rpassword", "git\npassword", "git\x00password", "local"} { |
| + t.Run(password, func(t *testing.T) { |
| + f := setup(t) |
| + marker := filepath.Join(f.root, "git-ran") |
| + spy := filepath.Join(f.root, "git-spy") |
| + put(t, spy, "#!/bin/sh\ntouch '"+marker+"'\nexit 1\n") |
| + if err := os.Chmod(spy, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.m.cfg.GitPath = spy |
| + if password == "local" { |
| + f.forge.remote.GitPassword = password |
| + } else { |
| + f.forge.remote = Remote{URL: "https://amadan.test/team/repo", GitPassword: password} |
| + } |
| + if _, _, err := f.m.fetch(ctx, f.target); err == nil { |
| + t.Fatal("invalid git credential accepted") |
| + } |
| + if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| + t.Fatal("invalid git credential reached git") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go| index 04d117e4..72d7b59b 100644 |
| --- a/internal/runner/workspace/workspace.go |
| +++ b/internal/runner/workspace/workspace.go |
| @@ -5,8 +5,10 @@ import ( |
| "context" |
| "crypto/sha1" |
| "crypto/sha256" |
| + "encoding/base64" |
| "encoding/hex" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "io" |
| "net/url" |
| @@ -25,7 +27,10 @@ import ( |
| type PreparedBug = runnerproto.PreparedBug |
| type GitCandidate = team.GitCandidate |
| -type Remote struct{ URL, Bearer string } |
| +type Remote struct{ URL, GitPassword string } |
| + |
| +var ErrGitPassword = errors.New("configure a repository git password (PAT) in EQUIPO_AMADAN_CREDENTIAL_PATH") |
| + |
| type ForgeRead interface { |
| Resolve(context.Context, string) (Remote, error) |
| } |
| @@ -219,21 +224,27 @@ func objectFormat(id string) string { |
| } |
| func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, string, error) { |
| remote, err := m.cfg.Forge.Resolve(ctx, t.Repository) |
| + if errors.Is(err, ErrGitPassword) { |
| + return "", "", ErrGitPassword |
| + } |
| if err != nil { |
| return "", "", provider.ErrContract |
| } |
| protocol := "" |
| if filepath.IsAbs(remote.URL) { |
| r, e := canonical(remote.URL) |
| - if e != nil || r != remote.URL || remote.Bearer != "" { |
| + if e != nil || r != remote.URL || remote.GitPassword != "" { |
| return "", "", provider.ErrPolicy |
| } |
| protocol = "file" |
| } else { |
| u, e := url.Parse(remote.URL) |
| - if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(remote.URL+remote.Bearer, "\r\n\x00") { |
| + if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(remote.URL+remote.GitPassword, "\r\n\x00") { |
| return "", "", provider.ErrPolicy |
| } |
| + if remote.GitPassword == "" { |
| + return "", "", ErrGitPassword |
| + } |
| protocol = "https" |
| } |
| repo := filepath.Join(m.cfg.PrivateRoot, "project-"+digest(t.Repository)) |
| @@ -249,10 +260,10 @@ func (m *Manager) fetch(ctx context.Context, t team.TargetBinding) (string, stri |
| ref = "refs/heads/" + t.DefaultRef |
| } |
| env := map[string]string{} |
| - if remote.Bearer != "" { |
| + if remote.GitPassword != "" { |
| env["GIT_CONFIG_COUNT"] = "10" |
| env["GIT_CONFIG_KEY_9"] = "http.extraHeader" |
| - env["GIT_CONFIG_VALUE_9"] = "Authorization: Bearer " + remote.Bearer |
| + env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x:"+remote.GitPassword)) |
| } |
| if _, err := m.git(ctx, repo, nil, env, "-c", "protocol."+protocol+".allow=always", "-c", "http.followRedirects=false", "fetch", "--no-auto-maintenance", "--no-tags", "--no-recurse-submodules", "--", remote.URL, ref); err != nil { |
| return "", "", err |
diff --git a/internal/runner/workspace/workspace_test.go b/internal/runner/workspace/workspace_test.go| index 4532ad15..ca0a2a0a 100644 |
| --- a/internal/runner/workspace/workspace_test.go |
| +++ b/internal/runner/workspace/workspace_test.go |
| @@ -383,7 +383,7 @@ func TestWorkspaceHasNoCredentials(t *testing.T) { |
| if _, err := os.Stat(marker); !os.IsNotExist(err) { |
| t.Fatal("poison git configuration executed") |
| } |
| - f.forge.remote = Remote{URL: "https://user:secret@invalid.test/repo", Bearer: sentinel} |
| + f.forge.remote = Remote{URL: "https://user:secret@invalid.test/repo", GitPassword: sentinel} |
| f.target.Repository = "invalid" |
| if _, err := f.m.Prepare(ctx, f.target); err == nil || strings.Contains(err.Error(), sentinel) { |
| t.Fatal("credential URL accepted or diagnostic leaked") |
diff --git a/internal/runnerproto/event_io.go b/internal/runnerproto/event_io.go| index 7f681029..2b75112a 100644 |
| --- a/internal/runnerproto/event_io.go |
| +++ b/internal/runnerproto/event_io.go |
| @@ -47,7 +47,7 @@ func WaitReconnect(ctx context.Context, attempt int, leaseDeadline time.Time) er |
| } |
| } |
| -var secretPattern = regexp.MustCompile(`(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+|((?:api[_-]?key|password|secret|token)\s*[=:]\s*)[^\s,"'<>]+|(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]{8,}`) |
| +var secretPattern = regexp.MustCompile(`(?i)((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+|((?:api[_-]?key|password|secret|token)\s*[=:]\s*)[^\s,"'<>]+|(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]{8,}`) |
| func RedactText(s string, secrets []string) string { |
| for _, secret := range secrets { |
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index a6a12348..e17f1afc 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -9742,5 +9742,61 @@ |
| "match": "equipo-runner", |
| "count": 1, |
| "reason": "Controller instructions and evidence for the runner startup fix." |
| + }, |
| + { |
| + "path": "docs/live-gate.md", |
| + "line_sha256": "ae238c413722092b05860a9c9c0728955e525e31e7369687fbcce7d64cb8f807", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Current runner credential setup and private agent home paths." |
| + }, |
| + { |
| + "path": "docs/live-gate.md", |
| + "line_sha256": "bfb85cecdb8d62210fe819a17d2a88f135f5dbb4bb0d86593978fec3f87eec89", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Current runner credential setup and private agent home paths." |
| + }, |
| + { |
| + "path": "docs/live-gate.md", |
| + "line_sha256": "e5e3a34f6108b461856ac55e3c6aa3c69302fbcd0004c6831957588bd4523abf", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Current runner credential setup and private agent home paths." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CODEX-BRIEF-forge-git-auth.md", |
| + "line_sha256": "53f8659045c7b81f8ed70d45b1b4b007ffad5dd07661d1b3e3e32edbfa108a6f", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Controller task brief naming existing private runner credential paths." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CODEX-BRIEF-forge-git-auth.md", |
| + "line_sha256": "5fa92a6abee5ed79c2c0088dcd7516aef9f50393eaec587eb2a0081bf73827c5", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Controller task brief naming existing private runner credential paths." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md", |
| + "line_sha256": "91d38503704564d86bd4c5c031bf63eaec4e31d7bddaa7e69e9e57a85369170e", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Controller conversion instructions for private runner credential files." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md", |
| + "line_sha256": "a317372bc4fc473f7e1a3247dc67c13e98009fb58a05767faddc2a4ffa9085af", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Controller conversion instructions for private runner credential files." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CONTROLLER-REPORT-forge-git-auth.md", |
| + "line_sha256": "e609174dd7b9861d9b3989921bf12b8778feadf07fe75d31aaef6c853bce7582", |
| + "match": "equipo-runner", |
| + "count": 2, |
| + "reason": "Controller conversion instructions for private runner credential files." |
| } |
| ] |