# 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.
