mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 12:39:42 +02:00
fix(docker): gate gh/az seeding on its switch; no shared git sign-in for non-admin clones
Addresses the review on #472. - CRED_STORES: `.config/gh` and `.azure` now carry `enabledByEnv` (CODEMAN_AGENT_IMAGE_INSTALL_GH / _AZ), and resolveDockerCredentialArtifacts skips a store unless that variable is exactly `1`, read at container create. A host that merely has ~/.config/gh/hosts.yml or a plaintext MSAL cache no longer copies them into every case container. Tests: the default environment seeds neither even with the files present, and each store follows only its own switch. - Multi-user mode: a non-admin's Clone Repo clone and preflight run with `git -c credential.helper=` (GIT_NO_CREDENTIAL_HELPERS, placed before the subcommand), so the server account's helpers are never lent to them. Verified against a real private repo that it also clears the URL-scoped credential.<url>.helper entries, and that public clones still work. Tests: the argv in test/git-clone.test.ts, and the route decision (non-admin cleared; admin and single-user kept) in test/routes/case-clone-credential-helpers.test.ts. - Docs: recreate the case container to pick up seeds (docker/README.md, Docker-Cases wiki, docker-cases.md); the multi-user behaviour in docker/README.md and security-architecture.md; "functionally unchanged" instead of "unchanged" for an image built with both switches off (server.Dockerfile comment, README, changeset). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0167CiuzLrmjYWxwKp3rMWjw
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5cf5a45438
commit
02e40f506b
@@ -2,4 +2,4 @@
|
||||
"aicodeman": minor
|
||||
---
|
||||
|
||||
Docker images: optional GitHub CLI and Azure CLI for private GitHub and Azure DevOps repositories. Both are opt-in and off by default. Build the server image with `CODEMAN_INSTALL_GH=1` / `CODEMAN_INSTALL_AZ=1` (under `build: args:` in `docker/docker-compose.override.yml`) to add `gh` and/or `az` with the `azure-devops` extension, plus system Git credential helpers that route github.com through `gh auth git-credential` and dev.azure.com / *.visualstudio.com through a new `az`-backed helper (`docker/git-credential-azure-cli`, which also honours `AZURE_DEVOPS_EXT_PAT`). Sign the CLIs in once from a shell session and Add Case → Clone Repo can clone private repositories; until then a private clone still fails fast with an authentication error. The Docker-case agent image takes the same switches from `CODEMAN_AGENT_IMAGE_INSTALL_GH` / `_AZ` (the `environment:` of the override file, or in front of `build-agent-image.mjs`), and a seeded Docker case now also copies the `gh` sign-in (`~/.config/gh/hosts.yml`, `config.yml`) and the `az` sign-in files from `~/.azure` into its container, read-only and per file like the other CLIs. The Clone Repo authentication error now says how to sign the server's git in instead of claiming private repositories cannot be cloned. This changes `server.Dockerfile`, so Compose deployments need a `Start-Codeman.sh` rebuild rather than an in-app update; with neither switch set the rebuilt image is unchanged.
|
||||
Docker images: optional GitHub CLI and Azure CLI for private GitHub and Azure DevOps repositories. Both are opt-in and off by default. Build the server image with `CODEMAN_INSTALL_GH=1` / `CODEMAN_INSTALL_AZ=1` (under `build: args:` in `docker/docker-compose.override.yml`) to add `gh` and/or `az` with the `azure-devops` extension, plus system Git credential helpers that route github.com through `gh auth git-credential` and dev.azure.com / *.visualstudio.com through a new `az`-backed helper (`docker/git-credential-azure-cli`, which also honours `AZURE_DEVOPS_EXT_PAT`). Sign the CLIs in once from a shell session and Add Case → Clone Repo can clone private repositories; until then a private clone still fails fast with an authentication error. The Docker-case agent image takes the same switches from `CODEMAN_AGENT_IMAGE_INSTALL_GH` / `_AZ` (the `environment:` of the override file, or in front of `build-agent-image.mjs`), and, only with those switches on, a seeded Docker case also copies the `gh` sign-in (`~/.config/gh/hosts.yml`, `config.yml`) and the `az` sign-in files from `~/.azure` into newly created case containers, read-only and per file like the other CLIs. In multi-user mode, Clone Repo runs a non-admin's clone and preflight with git's credential helpers cleared, so the server account's sign-in is never lent to them. The Clone Repo authentication error now says how to sign the server's git in instead of claiming private repositories cannot be cloned. This changes `server.Dockerfile`, so Compose deployments need a `Start-Codeman.sh` rebuild rather than an in-app update; with neither switch set the rebuilt image is functionally unchanged.
|
||||
|
||||
+4
-2
@@ -66,7 +66,7 @@ The `build: args:` pair controls the Codeman server image. The `environment:` pa
|
||||
|
||||
They are not `.env` settings: turning a CLI on is a per-host choice, which is what the override file is for, and a new `.env.example` key makes the in-app updater refuse to update every existing installation until its `.env` gains the key.
|
||||
|
||||
The Azure CLI is the large one, about 600 MB of the roughly 670 MB the pair adds. A CLI left off leaves nothing behind: no apt repository, no package, no `azure-devops` extension and no credential-helper entry, so git for that host behaves exactly as it does without this feature.
|
||||
The Azure CLI is the large one, about 600 MB of the roughly 670 MB the pair adds. A CLI left off leaves nothing functional behind: no apt repository, no package, no `azure-devops` extension and no credential-helper entry, so git for that host behaves exactly as it does without this feature. With both off the image is functionally unchanged; it still carries the `AZURE_EXTENSION_DIR` variable, an empty extensions directory and one small layer that copies and then removes the helper script.
|
||||
|
||||
### Signing in
|
||||
|
||||
@@ -86,9 +86,11 @@ az login --use-device-code # then: az devops configure --defaults organizati
|
||||
|
||||
After that, **Add Case → Clone Repo** accepts private `https://` URLs on those hosts, and `git clone` works from any session. Until a CLI is signed in its helper prints nothing, so a private clone fails immediately with the usual authentication error rather than waiting on a prompt.
|
||||
|
||||
**Multi-user mode:** every Codeman user's git runs as the same server account, so these sign-ins would otherwise be shared. Clone Repo therefore runs a **non-admin**'s clone and preflight with every git credential helper cleared (`git -c credential.helper=`): a non-admin can clone public repositories and anything their own SSH setup allows, but not a private https repository through the admin's `gh`/`az` sign-in. Admins, and single-user mode, keep the helpers. A non-admin's own agent sessions still run as that same account; see `docs/security-architecture.md`, multi-user mode.
|
||||
|
||||
Azure DevOps is authenticated with an Entra ID access token that the helper requests from `az` for each Git operation, so nothing is written to disk beyond `az`'s own sign-in. An account that has to use a personal access token can set `AZURE_DEVOPS_EXT_PAT` for the container instead (for example under `environment:` in `docker-compose.override.yml`); the helper prefers it when present. SSH remotes are unaffected by any of this and keep using the account's own keys.
|
||||
|
||||
In a Docker case built with the CLIs on, a case with credential seeding on copies these sign-ins into its container at launch (`~/.config/gh/hosts.yml` and `config.yml`, plus the sign-in files from `~/.azure`). A case container created before you signed in only picks them up once it is recreated.
|
||||
Docker cases copy these sign-ins into a case container only when the matching agent-image switch is on (`CODEMAN_AGENT_IMAGE_INSTALL_GH=1` for `~/.config/gh/hosts.yml` and `config.yml`, `CODEMAN_AGENT_IMAGE_INSTALL_AZ=1` for the sign-in files from `~/.azure`) and the case has credential seeding on. With a switch off they are never copied, even when the files exist, because a GitHub token or an Azure refresh token is usable by anything in the container. The copies are made when the container is **created**, so an existing case container never picks them up: after turning a switch on, signing in, or rebuilding the agent image, **recreate the case container** (remove it; the next session in that case creates a fresh one).
|
||||
|
||||
The GitHub agent skill for `gh` installs into the runtime account's home in the same session:
|
||||
|
||||
|
||||
@@ -76,12 +76,14 @@ COPY --from=docker:29-cli \
|
||||
# user signs in to here is what authenticates, and nothing when they have not
|
||||
# (the clone then fails fast with AUTH_REQUIRED, exactly as before).
|
||||
#
|
||||
# Each is OPT-IN and OFF by default: the image is unchanged unless the build
|
||||
# gets CODEMAN_INSTALL_GH=1 and/or CODEMAN_INSTALL_AZ=1, which a deployment sets
|
||||
# under `build: args:` in docker-compose.override.yml (docker/README.md,
|
||||
# "Private repositories"). Off means nothing at all: no apt repository, no
|
||||
# package, no extension and no credential-helper entry. The Azure CLI is the
|
||||
# heavy one (~600 MB, mostly its bundled Python). The base docker-compose.yaml
|
||||
# Each is OPT-IN and OFF by default: the image is functionally unchanged
|
||||
# unless the build gets CODEMAN_INSTALL_GH=1 and/or CODEMAN_INSTALL_AZ=1, which
|
||||
# a deployment sets under `build: args:` in docker-compose.override.yml
|
||||
# (docker/README.md, "Private repositories"). Off installs no apt repository,
|
||||
# package, extension or credential-helper entry; all that remains is the
|
||||
# AZURE_EXTENSION_DIR variable, its empty directory and one layer that copies
|
||||
# and then removes the helper script. The Azure CLI is the heavy one (~600 MB,
|
||||
# mostly its bundled Python). The base docker-compose.yaml
|
||||
# and .env deliberately do not carry them: turning a CLI on is a per-host
|
||||
# choice, which is what the override file is for, and a new .env.example key
|
||||
# would make the self-updater refuse existing installs until their .env gained
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -81,7 +81,7 @@ Antigravity (`agy`) and Grok (`grok`) are the two CLIs not installed from npm (G
|
||||
|
||||
Pi's credentials are seeded per-FILE rather than as a whole directory (`auth.json`, `settings.json`, `trust.json`, `models.json`, `models-store.json` out of `~/.pi/agent`), because that directory also holds `sessions/`, `extensions/`, `skills/` and the installed package trees — gigabytes on an active host. Consequence: in-container pi sessions are invisible host-side, so `pi -c` inside a Docker case only sees that container's own history. See [`pi-integration.md`](./pi-integration.md). Grok is seeded per-file for the same reason (`auth.json`, `config.toml`, `pager.toml` out of `~/.grok`, which also holds `sessions/`, `memory/` and the ~160MB binary under `downloads/`), with the same consequence for `grok -c`. See [`grok-integration.md`](./grok-integration.md). OMP is the one CLI in this family where `sessions/` is the EXCEPTION rather than the rule: `~/.omp/agent/{config.yml,mcp.json,models.yml,settings.yml}` are seeded per-file (the dir also holds SQLite caches and `terminal-sessions/`), but `~/.omp/agent/sessions/` is shared RW like codex's, not seeded, because Codeman reads it host-side for history recovery and `--resume` pinning. See [`omp-integration.md`](./omp-integration.md).
|
||||
|
||||
The image can also carry the GitHub CLI (`gh`) and the Azure CLI (`az` + the `azure-devops` extension, in `AZURE_EXTENSION_DIR=/opt/az-extensions` so it stays out of the seeded HOME), wired into the system git config as credential helpers for github.com and dev.azure.com / *.visualstudio.com, exactly as in `docker/server.Dockerfile`. Their sign-ins are seeded per-FILE like pi's: `~/.config/gh/{hosts.yml,config.yml}` and `~/.azure/{azureProfile.json,msal_token_cache.json,service_principal_entries.json,clouds.config,config}`, never `~/.azure`'s logs, command index or extensions. A token kept in a desktop keyring, or in the encrypted MSAL cache az uses on Windows/macOS, is not in those files and does not carry. None of the three is version-pinned; the `--no-cache` rebuild recommended above is also what refreshes them. Both CLIs are opt-in and OFF by default: `CODEMAN_AGENT_IMAGE_INSTALL_GH=1` / `CODEMAN_AGENT_IMAGE_INSTALL_AZ=1` in the environment of `scripts/build-agent-image.mjs`, or of the Codeman server for its own auto-build (in the Compose deployment, `environment:` in `docker-compose.override.yml`), become the `CODEMAN_INSTALL_GH` / `CODEMAN_INSTALL_AZ` build args and put that CLI, its extension and its helper entry into the image. Unset passes nothing, so a default build's argv is unchanged and the image has neither. A left-out CLI's sign-in files are still seeded if they exist on the host; they are inert without it.
|
||||
The image can also carry the GitHub CLI (`gh`) and the Azure CLI (`az` + the `azure-devops` extension, in `AZURE_EXTENSION_DIR=/opt/az-extensions` so it stays out of the seeded HOME), wired into the system git config as credential helpers for github.com and dev.azure.com / *.visualstudio.com, exactly as in `docker/server.Dockerfile`. Their sign-ins are seeded per-FILE like pi's: `~/.config/gh/{hosts.yml,config.yml}` and `~/.azure/{azureProfile.json,msal_token_cache.json,service_principal_entries.json,clouds.config,config}`, never `~/.azure`'s logs, command index or extensions. A token kept in a desktop keyring, or in the encrypted MSAL cache az uses on Windows/macOS, is not in those files and does not carry. None of the three is version-pinned; the `--no-cache` rebuild recommended above is also what refreshes them. Both CLIs are opt-in and OFF by default: `CODEMAN_AGENT_IMAGE_INSTALL_GH=1` / `CODEMAN_AGENT_IMAGE_INSTALL_AZ=1` in the environment of `scripts/build-agent-image.mjs`, or of the Codeman server for its own auto-build (in the Compose deployment, `environment:` in `docker-compose.override.yml`), become the `CODEMAN_INSTALL_GH` / `CODEMAN_INSTALL_AZ` build args and put that CLI, its extension and its helper entry into the image. Unset passes nothing, so a default build's argv is unchanged and the image has neither. The sign-in seeds follow the same switches, read when a case container is created: `.config/gh` only with `CODEMAN_AGENT_IMAGE_INSTALL_GH=1`, `.azure` only with `CODEMAN_AGENT_IMAGE_INSTALL_AZ=1` (`enabledByEnv` in `CRED_STORES`), never merely because the files exist. Seeds are create-time mounts and deliberately not part of the config hash (hashing them would trip the drift gate for every case), so an existing case container picks them up only when it is recreated.
|
||||
|
||||
## Quickest path: one-click "Run in Docker"
|
||||
|
||||
|
||||
@@ -497,7 +497,7 @@ production layout (`~/.codeman`, `-L codeman`, port 3000).
|
||||
Docker cases (1.4.0) run a session inside a per‑case container instead of on the host. The security posture:
|
||||
|
||||
- **Hardened create flags, always** — `--cap-drop ALL`, `--security-opt no-new-privileges`, `--pids-limit` (fork‑bomb guard), `--memory` == `--memory-swap` (a real OOM cap), `--init`, and non‑root: `--user <hostUid>:0` on Linux (host uid → workspace files stay host‑owned; GID 0 keeps `$HOME` writable), `--userns=keep-id` on rootless Podman. **Never** `--privileged`, and **never** the docker socket — the pure builder in `docker-hosts.ts` cannot emit them and the schema cannot represent them.
|
||||
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — `~/.config/{gcloud,opencode}`, five seeded files from `~/.pi/agent`, three from `~/.grok`, `~/.config/gh/{hosts.yml,config.yml}` and the sign-in files from `~/.azure`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
|
||||
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — `~/.config/{gcloud,opencode}`, five seeded files from `~/.pi/agent`, three from `~/.grok`, and, only when their opt-in switches `CODEMAN_AGENT_IMAGE_INSTALL_GH` / `_AZ` are `1`, `~/.config/gh/{hosts.yml,config.yml}` and the sign-in files from `~/.azure`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
|
||||
- **Blast radius — accept it explicitly** — the convenient profile mounts an arbitrary host workspace RW plus the host credential dirs RW into a network‑enabled container, so container‑run agent code can read/modify those host trees and reach the network at once. Still a net improvement over today's on‑host `--dangerously-skip-permissions` execution; use the sealed profile for genuinely untrusted work.
|
||||
- **Import is untrusted‑bundle‑safe** — `/api/docker-cases/import` validates the manifest + per‑member SHA‑256 before extraction, rejects absolute / `..` tar members (traversal guard), and re‑tags the loaded image into a quarantined namespace so it can never overwrite `codeman/agent:base` or a pre‑existing tag.
|
||||
- **Host guard & the bridge‑hooks listener** — in‑container hook callbacks carry `Host: host.docker.internal` / `host.containers.internal`; both are on the always‑on host‑header allowlist (`DOCKER_HOST_GATEWAY_ALIASES`) and resolve to the host only from inside a container netns, so they are not a browser DNS‑rebinding surface. On a loopback‑only server, in‑container hooks are opt‑in via `CODEMAN_DOCKER_BRIDGE_HOOKS=1`, which binds a SECOND listener on the docker bridge gateway serving **only** the hook endpoints (every other path → `403`) into the same hook‑secret‑gated pipeline. The bridge is host‑internal (containers + host), not the LAN, so it does not widen network exposure; the hook secret is bind‑mounted read‑only and referenced by path.
|
||||
@@ -516,6 +516,7 @@ Full feature guide: [`docker-cases.md`](docker-cases.md).
|
||||
- **Auth is a parallel branch** (`middleware/auth.ts`) that leaves the single‑user path untouched: per‑user scrypt verify (`timingSafeEqual`, timing‑equalized against user enumeration), identity‑carrying cookies, a per‑username failure bucket (a botnet can't brute one account across IPs; one NATed user can't lock out the rest), and a `mustChangePassword` lockbox. The hook‑secret loopback bypass, host guard, and Origin/CSRF guard are unchanged (hooks authenticate the INSTANCE, not a user).
|
||||
- **Ownership is enforced server‑side only** and fails closed: `req.authUser` (a synthetic admin in single‑user), `findSessionOrFail` returns NOT_FOUND (never 403) for a foreign session, list/SSE/WS/file‑preview/search all filter by `session.owner`, and SSE routing defaults session‑scoped events to their owner (unresolved owner → withheld). The load‑bearing rule is **non‑admin `workingDir` confinement**: a non‑admin's session/one‑shot working dir must realpath‑resolve inside `~/codeman-users/<name>/cases`, checked BEFORE any disk write.
|
||||
- **Privileged actions are a one‑bit grant** (`canBypassPermissions`, default off): only granted users (and admins) get `--dangerously-skip-permissions` (others are silently downgraded to `--permission-mode auto`), shell‑mode sessions, cron `launchCommand`, and other CLIs' bypass flags. Machine‑level resources (remote/Docker host definitions, tunnel, self‑update, settings writes) are admin‑only.
|
||||
- **Clone Repo does not lend the server's git sign-in to non-admins.** A clone writes only inside the caller's own case space, so it is not admin-gated, but the server account's git credential helpers (the Docker image's opt-in `gh`/`az` helpers, or any `gh auth setup-git`) are shared by every user. A non-admin's clone and preflight therefore run with `git -c credential.helper=`, which empties the helper list including the URL-scoped entries (`cloneWithoutCredentialHelpers` in `case-routes.ts`, argv pinned in `test/git-clone.test.ts`). This closes the Clone Repo path only: the account's SSH keys still apply to an `ssh://` URL, and a non-admin's agent sessions run as the same account, consistent with the first bullet above.
|
||||
- **Admin actions are audited** append‑only to `~/.codeman/admin-audit.jsonl` (acting admin, action, target, IP). Passwords set by an admin create/reset are one‑time (returned once, force change). Under Basic auth, `logout` only truly ends QR‑issued sessions — to lock someone out, disable the account or reset the password (a proper login form is a deferred Phase 6).
|
||||
|
||||
---
|
||||
|
||||
@@ -120,17 +120,20 @@ Codeman reads it host-side for history and resume.
|
||||
|
||||
**Git hosts.** The agent image can also include the GitHub CLI (`gh`) and the Azure CLI (`az`,
|
||||
with the `azure-devops` extension), off by default, and its git then uses them as credential
|
||||
helpers for github.com and Azure DevOps. Their sign-ins are seeded like everything else, file by file:
|
||||
`~/.config/gh/hosts.yml` and `config.yml`, and the sign-in files from `~/.azure` (not its
|
||||
logs or extensions). So once `gh auth login` / `az login` have been run where Codeman runs,
|
||||
agents in a Docker case can clone and push private repos on those hosts. Two limits:
|
||||
helpers for github.com and Azure DevOps. When the matching switch is on, their sign-ins are
|
||||
seeded like everything else, file by file: `~/.config/gh/hosts.yml` and `config.yml`, and the
|
||||
sign-in files from `~/.azure` (not its logs or extensions). With a switch off they are never
|
||||
copied in, even if the files exist. So once a switch is on and `gh auth login` / `az login`
|
||||
have been run where Codeman runs, agents in a Docker case can clone and push private repos on
|
||||
those hosts. Two limits:
|
||||
|
||||
- A token held in a desktop keyring or an encrypted token cache (Windows, macOS) is not
|
||||
inside those files and does not carry in. Sign in inside the container instead. The Docker
|
||||
server image and a headless Linux host keep it in the files, so they carry.
|
||||
- The copy happens only when the file is not already in the container, so a sign-in made
|
||||
after a case container was created reaches that container only once it is recreated
|
||||
(or once you sign in inside it).
|
||||
- The sign-ins are mounted when a case container is **created**, so an existing container
|
||||
never picks them up. After turning a switch on, signing in, or rebuilding the agent image,
|
||||
**recreate the case container**: remove it, and the next session in that case creates a
|
||||
fresh one. (Or sign in inside the existing container instead.)
|
||||
|
||||
This hands a GitHub token and an Azure sign-in to every agent in a seeded Docker case, the
|
||||
same trust you already give it with Claude, Codex or gcloud. Turn seeding off for a case that
|
||||
|
||||
+22
-6
@@ -812,6 +812,14 @@ interface CredStorePolicy {
|
||||
seedFiles?: string[];
|
||||
/** Seed the WHOLE dir (RO mount → cp -a) — for stores with no shared/host-read state. */
|
||||
seedWhole?: boolean;
|
||||
/**
|
||||
* Seed this store ONLY when this environment variable is exactly `1`, read when
|
||||
* the container is created. For credentials that belong to an opt-in tool rather
|
||||
* than to an agent CLI every case already trusts: they are not inert just because
|
||||
* the image lacks the tool (a gh `hosts.yml` token or an Azure refresh token is
|
||||
* usable by anything in the container, and the agent in it is prompt-injectable).
|
||||
*/
|
||||
enabledByEnv?: string;
|
||||
}
|
||||
|
||||
const CRED_STORES: CredStorePolicy[] = [
|
||||
@@ -857,18 +865,22 @@ const CRED_STORES: CredStorePolicy[] = [
|
||||
{ rel: '.config/gcloud', seedWhole: true },
|
||||
{ rel: '.config/opencode', seedWhole: true },
|
||||
// GitHub CLI: `hosts.yml` holds the token wherever no system keyring exists (the
|
||||
// Docker server image, a headless Linux host), `config.yml` the preferences. The
|
||||
// agent image routes github.com git credentials through `gh`, so this seed is what
|
||||
// lets an agent clone/push a private repo. A token that lives in a desktop keyring
|
||||
// is not in `hosts.yml` and does not carry in; sign `gh` in inside the container.
|
||||
{ rel: '.config/gh', seedFiles: ['hosts.yml', 'config.yml'] },
|
||||
// Docker server image, a headless Linux host), `config.yml` the preferences. An
|
||||
// agent image built with CODEMAN_INSTALL_GH=1 routes github.com git credentials
|
||||
// through `gh`, so this seed is what lets an agent clone/push a private repo. A
|
||||
// token that lives in a desktop keyring is not in `hosts.yml` and does not carry
|
||||
// in; sign `gh` in inside the container. OPT-IN: seeded only when the same switch
|
||||
// that builds gh into the agent image is on, never merely because the file exists.
|
||||
{ rel: '.config/gh', seedFiles: ['hosts.yml', 'config.yml'], enabledByEnv: 'CODEMAN_AGENT_IMAGE_INSTALL_GH' },
|
||||
// Azure CLI: only the sign-in state. `~/.azure` also accumulates `logs/`,
|
||||
// `commands/`, telemetry and (on a bare host) `cliextensions/`, none of which is
|
||||
// needed to authenticate; the agent image carries its own extensions outside HOME.
|
||||
// `msal_token_cache.json` is plaintext only on Linux (Windows/macOS encrypt it), so
|
||||
// this carries a sign-in from the Docker server image or a Linux host.
|
||||
// OPT-IN like gh: the MSAL cache holds refresh tokens for the whole Azure account.
|
||||
{
|
||||
rel: '.azure',
|
||||
enabledByEnv: 'CODEMAN_AGENT_IMAGE_INSTALL_AZ',
|
||||
seedFiles: [
|
||||
'azureProfile.json',
|
||||
'msal_token_cache.json',
|
||||
@@ -901,10 +913,14 @@ const CRED_STORES: CredStorePolicy[] = [
|
||||
* session state back into the host). Every path is existsSync-gated (on most hosts
|
||||
* only a subset exists). Pure-ish IO (no writes; just existence checks + mount specs).
|
||||
*/
|
||||
export function resolveDockerCredentialArtifacts(home: string = homedir()): DockerClaudeArtifacts {
|
||||
export function resolveDockerCredentialArtifacts(
|
||||
home: string = homedir(),
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): DockerClaudeArtifacts {
|
||||
const mounts: DockerMount[] = [];
|
||||
const seedCopies: DockerSeedCopy[] = [];
|
||||
for (const store of CRED_STORES) {
|
||||
if (store.enabledByEnv && env[store.enabledByEnv] !== '1') continue;
|
||||
const hostBase = join(home, store.rel);
|
||||
if (!existsSync(hostBase)) continue;
|
||||
const containerBase = `${CONTAINER_HOME}/${store.rel}`;
|
||||
|
||||
+29
-5
@@ -195,6 +195,8 @@ export interface CloneOptions {
|
||||
/** `--depth 1`: history-less but much faster on large repos. */
|
||||
shallow?: boolean;
|
||||
timeoutMs?: number;
|
||||
/** Clear every git credential helper for this run (see `GIT_NO_CREDENTIAL_HELPERS`). */
|
||||
withoutCredentialHelpers?: boolean;
|
||||
}
|
||||
|
||||
export type CloneResult = { ok: true; stderr: string } | { ok: false; failure: GitFailure };
|
||||
@@ -436,12 +438,27 @@ export function isSafeGitRef(ref: string): boolean {
|
||||
|
||||
// ─── Pure: argv + env ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Global git options that empty the credential-helper list for one run.
|
||||
*
|
||||
* Every Codeman user in multi-user mode runs git as the SAME OS account, so a
|
||||
* helper that account has (the Docker image's opt-in `gh`/`az` helpers, or a
|
||||
* user's own `gh auth setup-git`) would read private repositories on the
|
||||
* signed-in admin's behalf for anyone who can reach Clone Repo. An empty
|
||||
* `credential.helper` resets the helper list, and a command-line `-c` is read
|
||||
* last, so it also drops the URL-scoped `credential.<url>.helper` entries the
|
||||
* image configures (verified against a real private repo: refs with the helper,
|
||||
* `could not read Username` with it cleared). Public repositories are
|
||||
* unaffected. It must precede the subcommand.
|
||||
*/
|
||||
export const GIT_NO_CREDENTIAL_HELPERS: readonly string[] = ['-c', 'credential.helper='];
|
||||
|
||||
/**
|
||||
* argv for the clone. `--` separates flags from operands so neither the
|
||||
* repository nor the destination can ever be read as an option.
|
||||
*/
|
||||
export function buildCloneArgs(opts: CloneOptions): string[] {
|
||||
const args = ['clone'];
|
||||
const args = [...(opts.withoutCredentialHelpers ? GIT_NO_CREDENTIAL_HELPERS : []), 'clone'];
|
||||
// `--single-branch` is what makes "just this tag/branch" cheap on a big repo.
|
||||
if (opts.ref) args.push('--single-branch', '--branch', opts.ref);
|
||||
if (opts.shallow) args.push('--depth', '1');
|
||||
@@ -450,8 +467,14 @@ export function buildCloneArgs(opts: CloneOptions): string[] {
|
||||
}
|
||||
|
||||
/** argv for the preflight. `--symref` is what reveals the remote's default branch. */
|
||||
export function buildLsRemoteArgs(repository: string): string[] {
|
||||
return ['ls-remote', '--symref', '--', repository];
|
||||
export function buildLsRemoteArgs(repository: string, opts: { withoutCredentialHelpers?: boolean } = {}): string[] {
|
||||
return [
|
||||
...(opts.withoutCredentialHelpers ? GIT_NO_CREDENTIAL_HELPERS : []),
|
||||
'ls-remote',
|
||||
'--symref',
|
||||
'--',
|
||||
repository,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -790,7 +813,8 @@ export function isGitAvailable(): boolean {
|
||||
*/
|
||||
export async function probeGitRemote(
|
||||
repository: string,
|
||||
timeoutMs = GIT_LS_REMOTE_TIMEOUT_MS
|
||||
timeoutMs = GIT_LS_REMOTE_TIMEOUT_MS,
|
||||
opts: { withoutCredentialHelpers?: boolean } = {}
|
||||
): Promise<GitRemoteProbe> {
|
||||
if (!isGitAvailable()) {
|
||||
return {
|
||||
@@ -800,7 +824,7 @@ export async function probeGitRemote(
|
||||
failure: classifyGitFailure('', false, 'ENOENT: git not found'),
|
||||
};
|
||||
}
|
||||
const run = await runGit(buildLsRemoteArgs(repository), timeoutMs, MAX_LS_REMOTE_BYTES);
|
||||
const run = await runGit(buildLsRemoteArgs(repository, opts), timeoutMs, MAX_LS_REMOTE_BYTES);
|
||||
if (run.code !== 0 || run.spawnError) {
|
||||
return {
|
||||
reachable: false,
|
||||
|
||||
@@ -128,6 +128,18 @@ const APP_VERSION = (() => {
|
||||
const LOCAL_CLONE_ADMIN_ONLY =
|
||||
'Cloning from a local path is admin-only in multi-user mode. Use a repository URL instead.';
|
||||
|
||||
/**
|
||||
* Whether a clone or preflight must run with git's credential helpers cleared:
|
||||
* a non-admin in multi-user mode. Every user's git runs as the one server
|
||||
* account, so its helpers (the Docker image's opt-in `gh`/`az` ones, or any
|
||||
* `gh auth setup-git`) would otherwise read a private repository with the
|
||||
* signed-in admin's credentials, the same boundary the local-transport rule
|
||||
* above guards. Admins and single-user mode keep the account's own helpers.
|
||||
*/
|
||||
export function cloneWithoutCredentialHelpers(req: FastifyRequest): boolean {
|
||||
return isMultiUserMode() && !isAdmin(req);
|
||||
}
|
||||
|
||||
/**
|
||||
* The one line of git's stderr worth appending to an error message.
|
||||
*
|
||||
@@ -475,7 +487,9 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
if (!isGitAvailable()) {
|
||||
return { success: true, data: { parse: parsed, gitAvailable: false } };
|
||||
}
|
||||
const remote = await probeGitRemote(parsed.repository);
|
||||
const remote = await probeGitRemote(parsed.repository, undefined, {
|
||||
withoutCredentialHelpers: cloneWithoutCredentialHelpers(req),
|
||||
});
|
||||
return { success: true, data: { parse: parsed, remote, gitAvailable: true } };
|
||||
}
|
||||
);
|
||||
@@ -491,8 +505,10 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
* request died mid-clone still sees the case appear over SSE when git finishes.
|
||||
*
|
||||
* Deliberately NOT admin-gated in multi-user mode: unlike `/api/cases/link`,
|
||||
* this writes only inside the caller's own `resolveCasesDir`. The one exception
|
||||
* is a `local`-transport source, which would read through that boundary.
|
||||
* this writes only inside the caller's own `resolveCasesDir`. Two things would
|
||||
* otherwise read through that boundary: a `local`-transport source (refused for
|
||||
* non-admins) and the server account's git credential helpers, which every user
|
||||
* shares (cleared for non-admins, see `cloneWithoutCredentialHelpers`).
|
||||
*
|
||||
* Repository contents win over scaffolding: an existing CLAUDE.md is left
|
||||
* alone, and hooks are MERGED into whatever `.claude/settings.local.json` the
|
||||
@@ -562,6 +578,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
const clone = await cloneRepository({
|
||||
repository: parsed.repository,
|
||||
destination: casePath,
|
||||
withoutCredentialHelpers: cloneWithoutCredentialHelpers(req),
|
||||
...(ref ? { ref } : {}),
|
||||
...(shallow ? { shallow: true } : {}),
|
||||
});
|
||||
|
||||
@@ -351,6 +351,40 @@ describe('resolveDockerCredentialArtifacts (isolated codex/gemini/gcloud/opencod
|
||||
expect(mounts.filter((m) => m.readonly && m.dst.includes('cred-seeds')).length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
/** Host files for both opt-in stores, present whether or not the switches are on. */
|
||||
function writeGhAzHostFiles(): void {
|
||||
mkdirSync(join(home, '.config', 'gh'), { recursive: true });
|
||||
writeFileSync(join(home, '.config', 'gh', 'hosts.yml'), '');
|
||||
writeFileSync(join(home, '.config', 'gh', 'config.yml'), '');
|
||||
mkdirSync(join(home, '.azure'), { recursive: true });
|
||||
writeFileSync(join(home, '.azure', 'azureProfile.json'), '{}');
|
||||
writeFileSync(join(home, '.azure', 'msal_token_cache.json'), '{}');
|
||||
}
|
||||
const isGhOrAz = (p: string) => /\.azure|\.config[\\/]gh/.test(p);
|
||||
|
||||
it('gh + az: the DEFAULT environment seeds neither, even when the host files exist', () => {
|
||||
writeGhAzHostFiles();
|
||||
for (const env of [{}, { CODEMAN_AGENT_IMAGE_INSTALL_GH: '0', CODEMAN_AGENT_IMAGE_INSTALL_AZ: '' }]) {
|
||||
const { mounts, seedCopies } = resolveDockerCredentialArtifacts(home, env);
|
||||
expect(mounts.filter((m) => isGhOrAz(m.src))).toEqual([]);
|
||||
expect(seedCopies.filter((s) => isGhOrAz(s.to))).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it('gh + az: each store follows ONLY its own switch, and only the exact value 1', () => {
|
||||
writeGhAzHostFiles();
|
||||
const dests = (env: NodeJS.ProcessEnv) => resolveDockerCredentialArtifacts(home, env).seedCopies.map((s) => s.to);
|
||||
const ghOnly = dests({ CODEMAN_AGENT_IMAGE_INSTALL_GH: '1' });
|
||||
expect(ghOnly).toContain('/home/agent/.config/gh/hosts.yml');
|
||||
expect(ghOnly.some((d) => d.includes('.azure'))).toBe(false);
|
||||
const azOnly = dests({ CODEMAN_AGENT_IMAGE_INSTALL_AZ: '1' });
|
||||
expect(azOnly).toContain('/home/agent/.azure/msal_token_cache.json');
|
||||
expect(azOnly.some((d) => d.includes('.config/gh'))).toBe(false);
|
||||
expect(
|
||||
dests({ CODEMAN_AGENT_IMAGE_INSTALL_GH: 'true', CODEMAN_AGENT_IMAGE_INSTALL_AZ: 'yes' }).some(isGhOrAz)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('gh + az: seed only the sign-in files, never logs/extensions/caches', () => {
|
||||
mkdirSync(join(home, '.config', 'gh'), { recursive: true });
|
||||
writeFileSync(join(home, '.config', 'gh', 'hosts.yml'), '');
|
||||
@@ -361,7 +395,10 @@ describe('resolveDockerCredentialArtifacts (isolated codex/gemini/gcloud/opencod
|
||||
writeFileSync(join(home, '.azure', 'msal_token_cache.json'), '{}');
|
||||
writeFileSync(join(home, '.azure', 'config'), '');
|
||||
|
||||
const { mounts, seedCopies } = resolveDockerCredentialArtifacts(home);
|
||||
const { mounts, seedCopies } = resolveDockerCredentialArtifacts(home, {
|
||||
CODEMAN_AGENT_IMAGE_INSTALL_GH: '1',
|
||||
CODEMAN_AGENT_IMAGE_INSTALL_AZ: '1',
|
||||
});
|
||||
const dests = seedCopies.map((s) => s.to);
|
||||
expect(dests).toContain('/home/agent/.config/gh/hosts.yml');
|
||||
expect(dests).toContain('/home/agent/.config/gh/config.yml');
|
||||
|
||||
@@ -201,6 +201,25 @@ describe('buildCloneArgs / buildLsRemoteArgs', () => {
|
||||
'd',
|
||||
]);
|
||||
});
|
||||
|
||||
it('clears every credential helper, BEFORE the subcommand, only when asked', () => {
|
||||
// Multi-user non-admin clones must not borrow the server account's git sign-in.
|
||||
// `-c` is a global option: after `clone` git would read it as an unknown flag.
|
||||
expect(
|
||||
buildCloneArgs({ repository: 'https://example.com/r.git', destination: 'd', withoutCredentialHelpers: true })
|
||||
).toEqual(['-c', 'credential.helper=', 'clone', '--', 'https://example.com/r.git', 'd']);
|
||||
expect(buildLsRemoteArgs('https://example.com/r.git', { withoutCredentialHelpers: true })).toEqual([
|
||||
'-c',
|
||||
'credential.helper=',
|
||||
'ls-remote',
|
||||
'--symref',
|
||||
'--',
|
||||
'https://example.com/r.git',
|
||||
]);
|
||||
// Absent or false leaves the argv exactly as it was before the option existed.
|
||||
expect(buildCloneArgs({ repository: 'r', destination: 'd', withoutCredentialHelpers: false })[0]).toBe('clone');
|
||||
expect(buildLsRemoteArgs('r', {})[0]).toBe('ls-remote');
|
||||
});
|
||||
});
|
||||
|
||||
describe('gitNonInteractiveEnv', () => {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* @fileoverview Clone Repo must not lend the server account's git sign-in to
|
||||
* non-admins in multi-user mode (PR #472 review).
|
||||
*
|
||||
* Every Codeman user's git runs as the one server account, so a credential
|
||||
* helper that account has (the Docker image's opt-in `gh`/`az` helpers, or any
|
||||
* `gh auth setup-git`) would otherwise clone a PRIVATE repository with the
|
||||
* signed-in admin's credentials into a non-admin's case space, the same
|
||||
* boundary the local-transport rule guards. These tests pin the ROUTE decision:
|
||||
* who gets `withoutCredentialHelpers`. The argv it becomes is pinned in
|
||||
* `test/git-clone.test.ts`, and the real-git clone path in
|
||||
* `case-clone-routes.test.ts`.
|
||||
*
|
||||
* Only the two network calls are mocked, so no git runs and nothing leaves the
|
||||
* machine; everything else in `git-clone.ts` (URL parsing included) is real.
|
||||
*
|
||||
* Port: N/A (app.inject).
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
|
||||
|
||||
const calls = vi.hoisted(() => ({
|
||||
probe: [] as Array<{ repository: string; opts: unknown }>,
|
||||
clone: [] as Array<Record<string, unknown>>,
|
||||
}));
|
||||
|
||||
vi.mock('../../src/git-clone.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/git-clone.js')>();
|
||||
return {
|
||||
...actual,
|
||||
isGitAvailable: () => true,
|
||||
probeGitRemote: async (repository: string, _timeoutMs?: number, opts?: unknown) => {
|
||||
calls.probe.push({ repository, opts });
|
||||
return { reachable: false, branches: [], tags: [] };
|
||||
},
|
||||
cloneRepository: async (opts: Record<string, unknown>) => {
|
||||
calls.clone.push(opts);
|
||||
return { ok: false, failure: { code: 'AUTH_REQUIRED', message: 'needs auth', stderr: '' } };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const REPO = 'https://github.com/example/private-repo.git';
|
||||
|
||||
type Who = { username: string; role: 'admin' | 'user' } | undefined;
|
||||
|
||||
async function run(who: Who, multiUser: boolean): Promise<{ probe: unknown; clone: unknown }> {
|
||||
const prev = process.env.CODEMAN_MULTIUSER;
|
||||
if (multiUser) process.env.CODEMAN_MULTIUSER = '1';
|
||||
else delete process.env.CODEMAN_MULTIUSER;
|
||||
try {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes, who ? { authUser: who } : undefined);
|
||||
await app.inject({ method: 'POST', url: '/api/cases/clone-preflight', payload: { repository: REPO } });
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/cases/clone',
|
||||
payload: { name: `cred-${Math.random().toString(36).slice(2, 10)}`, repository: REPO },
|
||||
});
|
||||
await app.close();
|
||||
expect(calls.probe, 'the preflight never reached probeGitRemote').toHaveLength(1);
|
||||
expect(calls.clone, 'the clone never reached cloneRepository').toHaveLength(1);
|
||||
return {
|
||||
probe: (calls.probe[0].opts as { withoutCredentialHelpers?: boolean } | undefined)?.withoutCredentialHelpers,
|
||||
clone: calls.clone[0].withoutCredentialHelpers,
|
||||
};
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.CODEMAN_MULTIUSER;
|
||||
else process.env.CODEMAN_MULTIUSER = prev;
|
||||
}
|
||||
}
|
||||
|
||||
describe('Clone Repo credential helpers by caller', () => {
|
||||
beforeEach(() => {
|
||||
calls.probe.length = 0;
|
||||
calls.clone.length = 0;
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('clears them for a NON-ADMIN in multi-user mode (preflight AND clone)', async () => {
|
||||
expect(await run({ username: 'mallory', role: 'user' }, true)).toEqual({ probe: true, clone: true });
|
||||
});
|
||||
|
||||
it('keeps them for an admin in multi-user mode', async () => {
|
||||
expect(await run({ username: 'root', role: 'admin' }, true)).toEqual({ probe: false, clone: false });
|
||||
});
|
||||
|
||||
it('keeps them in single-user mode, where the sole user owns the account', async () => {
|
||||
expect(await run(undefined, false)).toEqual({ probe: false, clone: false });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user