fix(#2911): keep the forge token out of argv

`forge_git_url` spliced `core:<token>@` between scheme and authority, and
that URL is a process argument. `/proc/<pid>/cmdline` is mode 0444 —
world-readable — so the core admin token, which provisions every agent's
forge account, was published to any local user for the lifetime of each
git child. Seven call sites built such a URL.

The credential now travels in the environment instead:
`git_command_authed` sets `http.extraHeader` via `GIT_CONFIG_*`, which
git reads exactly like a config file, and `/proc/<pid>/environ` is 0400 —
owner-only. Same credential, materially smaller audience. The remote is a
plain `http://forge/<org>/<repo>.git`, and `forge_git_url` no longer takes
a token, so the old shape cannot be rebuilt by accident.

`knowledge`'s clone was the one place a credentialed URL was stored as a
named remote — git persists the clone URL into `.git/config`, so the
token sat on disk and every later `pull` authenticated from there. That
is the case `forge::repos::push_config` documents as forbidden ("the
tokenised URL ... deliberately never stored as a named remote"). `pull`
now rewrites `origin` to the plain URL first, which also scrubs the
persisted token from existing deployments, and authenticates from the
environment when a token is available. The repo is public, so the pull
still works without one.

Three call sites also stopped spawning `Command::new("git")` directly,
so they honour the `HYPERHIVE_GIT` path the NixOS module bakes in and
the `kill_on_drop` every other git spawn gets.

The two URL-shape tests now assert the *absence* of a credential, and a
new one decodes the header back to `core:<token>` — without that, a
malformed header would leave every forge operation silently anonymous
with the other assertions still green.
This commit is contained in:
atlas 2026-08-02 13:21:42 +02:00
commit 44572d1e1a
7 changed files with 134 additions and 56 deletions

View file

@ -59,28 +59,34 @@ pub(crate) fn forge_http_base() -> &'static str {
})
}
/// Token-in-URL git remote for `repo` (e.g. `"core/meta"`). Inserts
/// `core:<token>` credentials between the scheme and authority of
/// [`forge_http_base()`] — the form git accepts for inline auth.
pub(crate) fn forge_git_url(token: &str, repo: &str) -> String {
git_url_with_base(forge_http_base(), token, repo)
/// Git remote for `repo` (e.g. `"core/meta"`) — **credential-free**.
///
/// The token does not go here. A URL is a process argument, and `argv` is
/// world-readable through `/proc/<pid>/cmdline` for as long as the git child
/// lives, so a credentialed remote publishes the core admin token to every
/// local user on the host. Credentials travel in the environment instead, via
/// [`core_auth_header`] and [`crate::lifecycle::git_command_authed`] —
/// `/proc/<pid>/environ` is owner-only.
pub(crate) fn forge_git_url(repo: &str) -> String {
git_url_with_base(forge_http_base(), repo)
}
/// The credential-insertion half of [`forge_git_url`], split out so it
/// can be tested without a process-wide env var (which would race every
/// other test in this binary).
/// The pure half of [`forge_git_url`], split out so it can be tested without a
/// process-wide env var (which would race every other test in this binary).
fn git_url_with_base(base: &str, repo: &str) -> String {
format!("{base}/{repo}.git")
}
/// The `http.extraHeader` value authenticating as the forge core user.
///
/// # Panics
///
/// When `base` has no `://`. Previously this fell back to
/// `http://core:<token>@localhost:3000` — a guess that would have sent
/// a *credentialed* push at whatever answers on the local port. A
/// malformed base is a broken deployment; failing on it is the point.
fn git_url_with_base(base: &str, token: &str, repo: &str) -> String {
let (scheme, host) = base
.split_once("://")
.unwrap_or_else(|| panic!("HIVE_FORGE_URL is not a URL (no \"://\"): {base}"));
format!("{scheme}://core:{token}@{host}/{repo}.git")
/// Basic auth over a header rather than userinfo in the URL, so the secret
/// reaches git through the environment (see [`forge_git_url`]). Pair with
/// [`crate::lifecycle::git_command_authed`], which is the only thing that
/// should ever hold the result.
pub(crate) fn core_auth_header(token: &str) -> String {
use base64::Engine as _;
let basic = base64::engine::general_purpose::STANDARD.encode(format!("core:{token}"));
format!("Authorization: Basic {basic}")
}
/// Forgejo org grouping every agent's config repo. Core is a site admin

View file

@ -6,7 +6,7 @@
use anyhow::Context;
use forgejo_api::structs::{MergePullRequestOption, MergePullRequestOptionDo, StateType};
use super::{CONFIG_ORG, api, core_token, forge_git_url};
use super::{CONFIG_ORG, api, core_auth_header, core_token, forge_git_url};
// ---------------------------------------------------------------------------
// PR-based config-flow merge primitives (part of the
@ -74,9 +74,9 @@ fn repo_agent_name(repo: &str) -> &str {
pub async fn pr_head_sha(repo: &str, pr: u64) -> Result<String, ForgeMergeError> {
let token = core_token()
.ok_or_else(|| ForgeMergeError::Other(anyhow::anyhow!("forge core token absent")))?;
let url = forge_git_url(&token, repo);
let url = forge_git_url(repo);
let refspec = format!("refs/pull/{pr}/head");
let out = crate::lifecycle::git_command()
let out = crate::lifecycle::git_command_authed(&core_auth_header(&token))
.args(["ls-remote", &url, &refspec])
.output()
.await
@ -142,10 +142,10 @@ pub fn config_repo(agent: &str) -> String {
pub async fn fetch_pr_head_into_applied(repo: &str, pr: u64) -> Result<(), ForgeMergeError> {
let token = core_token()
.ok_or_else(|| ForgeMergeError::Other(anyhow::anyhow!("forge core token absent")))?;
let url = forge_git_url(&token, repo);
let url = forge_git_url(repo);
let applied = crate::paths::applied_dir(repo_agent_name(repo));
let refspec = format!("refs/pull/{pr}/head");
let out = crate::lifecycle::git_command()
let out = crate::lifecycle::git_command_authed(&core_auth_header(&token))
.current_dir(&applied)
.args(["fetch", "--no-tags", &url, &refspec])
.output()
@ -262,25 +262,44 @@ mod tests {
assert_eq!(repo_agent_name("a/b/c"), "c");
}
/// The remote carries **no credential**. `argv` is world-readable through
/// `/proc/<pid>/cmdline`, so a token spliced in here would be published to
/// every local user for the life of the git child.
///
/// Deliberately not via `forge_git_url`, which reads `HIVE_FORGE_URL` —
/// setting that here would race every other test in this binary.
#[test]
fn forge_git_url_shape() {
// Tests the pure half: credentials go between scheme and
// authority. Deliberately not via `forge_git_url`, which reads
// HIVE_FORGE_URL — setting that here would race every other
// test in this binary, and there is no fallback to lean on any
// more (a guessed base is the bug this issue removes).
let url = git_url_with_base("http://forge.example.test", "tok", "a/iris");
assert_eq!(url, "http://core:tok@forge.example.test/a/iris.git");
fn forge_git_url_carries_no_credential() {
let url = git_url_with_base("http://forge.example.test", "a/iris");
assert_eq!(url, "http://forge.example.test/a/iris.git");
assert!(!url.contains('@'), "no userinfo: {url}");
}
#[test]
fn forge_git_url_preserves_https() {
// The scheme is carried through rather than assumed: a swarm
// whose forge is behind TLS must not be downgraded to http.
let url = git_url_with_base("https://forge.example.test", "tok", "a/iris");
let url = git_url_with_base("https://forge.example.test", "a/iris");
assert!(url.starts_with("https://"), "https must survive: {url}");
}
/// The credential goes in an `Authorization` header instead — decodable
/// back to `core:<token>`, so the swap is genuinely equivalent auth and
/// not a silent downgrade to anonymous.
#[test]
fn core_auth_header_is_basic_core_token() {
use base64::Engine as _;
let header = crate::forge::core_auth_header("s3cret");
let b64 = header
.strip_prefix("Authorization: Basic ")
.expect("basic auth header");
let decoded = base64::engine::general_purpose::STANDARD
.decode(b64)
.expect("valid base64");
assert_eq!(String::from_utf8_lossy(&decoded), "core:s3cret");
assert!(
url.starts_with("https://core:tok@"),
"https must survive: {url}"
!header.contains("s3cret"),
"token not in the clear: {header}"
);
}
}

View file

@ -17,7 +17,7 @@ use anyhow::{Context, Result};
use hive_host_sock::{HostResponse, ReconcileDirection};
use super::{CONFIG_ORG, core_token, forge_git_url, is_present};
use super::{CONFIG_ORG, core_auth_header, core_token, forge_git_url, is_present};
/// Scratch ref the forge `main` is fetched into — outside the normal
/// branch/tag namespace so it never collides with real refs.
@ -36,10 +36,11 @@ async fn fetch_forge_main(agent: &str) -> Result<PathBuf> {
if !dir.join(".git").exists() {
anyhow::bail!("agent `{agent}` has no applied config checkout");
}
let url = forge_git_url(&token, &format!("{CONFIG_ORG}/{agent}"));
crate::lifecycle::git(
let url = forge_git_url(&format!("{CONFIG_ORG}/{agent}"));
crate::lifecycle::git_authed(
&dir,
&["fetch", "--force", &url, &format!("main:{FORGE_MAIN_REF}")],
&core_auth_header(&token),
)
.await
.context("fetch forge config main (does forge main exist yet?)")?;

View file

@ -16,13 +16,12 @@ use forgejo_api::structs::{
};
use forgejo_api::{ApiErrorKind, ForgejoError};
use reqwest::StatusCode;
use tokio::process::Command;
use crate::coordinator::Coordinator;
use super::{
AGENTS_ORG, CONFIG_ORG, KNOWLEDGE_REPO, OPERATORS_TEAM, SHARED_DOCS_REPO, SHARED_ORG, api,
core_token, forge_git_url, forge_http_base, is_present,
core_auth_header, core_token, forge_git_url, forge_http_base, is_present,
};
/// Creation options for an empty repo defaulting to `main`.
@ -239,8 +238,8 @@ pub async fn push_meta(dir: &Path) -> Result<()> {
// raise a dashboard warning and leave the remote intact rather than
// silently erasing its history — consistent with `push_config`'s
// non-fast-forward handling.
let url = forge_git_url(&token, "core/meta");
let out = Command::new("git")
let url = forge_git_url("core/meta");
let out = crate::lifecycle::git_command_authed(&core_auth_header(&token))
.current_dir(dir)
.args(["push", &url, "HEAD:main"])
.output()
@ -482,9 +481,10 @@ pub async fn push_config(name: &str) -> Result<()> {
if !dir.join(".git").exists() {
return Ok(());
}
let url = forge_git_url(&token, &format!("{CONFIG_ORG}/{name}"));
let url = forge_git_url(&format!("{CONFIG_ORG}/{name}"));
let auth = core_auth_header(&token);
// Tags first, in their own push, so they land regardless of main's fate.
let out = run_config_push(&dir, &url, "refs/tags/*:refs/tags/*").await?;
let out = run_config_push(&dir, &url, &auth, "refs/tags/*:refs/tags/*").await?;
if !out.status.success() {
anyhow::bail!(
"git push tags {CONFIG_ORG}/{name} failed ({}): {}",
@ -495,7 +495,7 @@ pub async fn push_config(name: &str) -> Result<()> {
// Then main on its own — a protected-branch / non-ff reject of an
// established main is expected (pr_merge owns main); only the initial
// empty-repo seed actually advances it here.
let out = run_config_push(&dir, &url, "refs/heads/main:refs/heads/main").await?;
let out = run_config_push(&dir, &url, &auth, "refs/heads/main:refs/heads/main").await?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
if stderr.contains("non-fast-forward")
@ -525,9 +525,10 @@ pub async fn push_config(name: &str) -> Result<()> {
async fn run_config_push(
dir: &std::path::Path,
url: &str,
auth: &str,
refspec: &str,
) -> Result<std::process::Output> {
crate::lifecycle::git_command()
crate::lifecycle::git_command_authed(auth)
.current_dir(dir)
.args(["push", url, refspec])
.output()