Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
a539935
fix(forge): only receive-pack registers as a writer, not a dumb-proto…
tonibergholm-codento Nov 20, 2026
64a6db8
fix(forge): bound the wait for a password-verification slot, answer 503
tonibergholm-codento Nov 20, 2026
7bdcfd0
fix(forge): read SC_FORGE_MERGE_PAUSE_MS in debug builds only
tonibergholm-codento Nov 20, 2026
745293f
fix(forge): parse ip:port forwarded-for entries and stop the walk at …
tonibergholm-codento Nov 20, 2026
fdd3f8f
style(forge): cargo fmt the password gate refusal
tonibergholm-codento Nov 20, 2026
0447152
fix(forge): a private organization the caller cannot see answers like…
tonibergholm-codento Nov 20, 2026
f08ebe6
feat(forge): admin user create and change-password take --password-st…
tonibergholm-codento Nov 20, 2026
70feee2
docs(threat-model): record the forge hardening decisions
tonibergholm-codento Nov 20, 2026
1541769
test(forge): record the private-organization departures with ignore_body
tonibergholm-codento Nov 20, 2026
b5841d4
fix(forge): refund the exact reservation; resolve the client once fro…
tonibergholm-codento Nov 20, 2026
713389d
fix(forge): decide the hidden-organization 404 from the paginated lis…
tonibergholm-codento Nov 20, 2026
4b47f63
test(forge): pin the missing-organization error shape and an absent c…
tonibergholm-codento Nov 20, 2026
a12ae81
test(forge): compare exact-body departures with the strict comparator
tonibergholm-codento Nov 20, 2026
392f210
test(forge): generate the stdin test passwords
tonibergholm-codento Nov 20, 2026
5598738
Merge branch 'main' into fix/forge-hardening
tonibergholm-codento Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/forge/conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,13 @@ success, ...), as well as every deliberate sc-forge difference.
override is refused (`applied to a different exchange`) when the exchange actually produced differs,
including for `skip`.
- `expect` keys depend on `kind`: http `status`, `message_contains`, `fields`, `ignore_fields`,
`ignore_headers`, `ignore_body`, `skip`; git `ok`, `message_contains`, `skip`; note `value`, `skip`.
`ignore_headers`, `ignore_body`, `body`, `absent_headers`, `skip`; git `ok`, `message_contains`, `skip`; note `value`, `skip`.
A key that does not apply to the entry's kind is a load error. The keys: `status` (number or list), `message_contains`, `ok` (git), `value` (note; works for
`strict=False` notes too), `fields` (pin body values by dotted path, `$len` pins an array length),
`ignore_fields` (dotted paths left out of the body comparison), `ignore_headers` (recorded headers left out),
`ignore_body` (no body comparison at all) and `skip` (only when unavoidable; say why in `reason`).
`ignore_body` (no body comparison at all), `body` (the exact JSON object the departed answer must have: the same
keys, every value compared, URLs included; use it with `ignore_body` to pin a changed error shape instead of
dropping the check), `absent_headers` (headers that must not be present on the departed answer) and `skip` (only when unavoidable; say why in `reason`).
- A departure replaces only what it names. Whatever it sets (`status`, `fields`, `message_contains`, ...), the
recorded headers (minus `ignore_headers`) and every JSON field not in `ignore_fields` or `fields` are still
compared, and a top-level error `message` is checked by `message_contains` instead of the recorded text.
Expand Down
59 changes: 58 additions & 1 deletion crates/forge/conformance/departures.json
Original file line number Diff line number Diff line change
Expand Up @@ -1748,11 +1748,26 @@
"kind": "http",
"match": "GET /api/v1/orgs/acme/repos",
"expect": {
"status": 404,
"message_contains": [
"getorgbyname"
],
"ignore_body": true,
"ignore_headers": [
"x-total-count"
],
"body": {
"errors": [
"user redirect does not exist [name: acme]"
],
"message": "GetOrgByName",
"url": "<base>/api/swagger"
},
"absent_headers": [
"x-total-count"
]
},
"reason": "Gitea leaks all 11 organization repositories in X-Total-Count even when the body is access-filtered. The complete body stays compared; e2e_repos::listings_are_filtered_by_access_with_visible_counts checks visible-count filtering for a read collaborator and an outsider."
"reason": "sc-forge answers a caller who cannot see a private organization and can read nothing in it like a missing organization (404 GetOrgByName); Gitea answers 200 with an empty list [ignore_body: the recorded 200 body has another shape than the departed answer; `body` pins the missing-organization error, `absent_headers` that no count leaks]. K#56 (a collaborator) still lists what it can read."
},
{
"scenario": "K",
Expand All @@ -1765,5 +1780,47 @@
]
},
"reason": "Gitea leaks all 11 organization repositories in X-Total-Count even when the body is access-filtered. The complete body stays compared; e2e_repos::listings_are_filtered_by_access_with_visible_counts checks visible-count filtering for a read collaborator and an outsider."
},
{
"scenario": "B",
"exchange": 32,
"kind": "http",
"match": "GET /api/v1/orgs/acme",
"expect": {
"status": 404,
"message_contains": [
"getorgbyname"
],
"ignore_body": true,
"body": {
"errors": [
"user redirect does not exist [name: acme]"
],
"message": "GetOrgByName",
"url": "<base>/api/swagger"
}
},
"reason": "sc-forge answers a private organization the caller cannot see exactly like a missing one (404 GetOrgByName); Gitea's 'HasOrgOrUserVisible' tells the two apart [ignore_body: the recorded `errors` is null; `body` pins the missing-organization error shape and URL]"
},
{
"scenario": "K",
"exchange": 54,
"kind": "http",
"match": "GET /api/v1/orgs/acme",
"expect": {
"status": 404,
"message_contains": [
"getorgbyname"
],
"ignore_body": true,
"body": {
"errors": [
"user redirect does not exist [name: acme]"
],
"message": "GetOrgByName",
"url": "<base>/api/swagger"
}
},
"reason": "sc-forge answers a private organization the caller cannot see exactly like a missing one (404 GetOrgByName); Gitea's 'HasOrgOrUserVisible' tells the two apart [ignore_body: the recorded `errors` is null; `body` pins the missing-organization error shape and URL]"
}
]
29 changes: 28 additions & 1 deletion crates/forge/conformance/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,8 @@ def dep_indexes(spec, expected):


EXPECT_KEYS = {
"http": {"status", "message_contains", "fields", "ignore_fields", "ignore_headers", "ignore_body", "skip"},
"http": {"status", "message_contains", "fields", "ignore_fields", "ignore_headers", "ignore_body", "body",
"absent_headers", "skip"},
"git": {"ok", "message_contains", "skip"},
"note": {"value", "value_prefix", "skip"},
}
Expand Down Expand Up @@ -490,6 +491,18 @@ def apply_override(exp, act, ov, bij, match=None):
got = len(body) if k == "$len" and isinstance(body, list) else dget(body, k)
if got != v:
d.append(("fail", f"unexpected: {k} {v!r} expected, got {got!r}"))
# `body`: the exact JSON object the departed answer must have (same keys, by value, URLs included);
# `absent_headers`: recorded headers that must not appear on it
if "body" in e:
ab = act.get("body")
if not isinstance(ab, dict) or set(ab) != set(e["body"]):
d.append(("fail", f"unexpected: body keys {sorted(e['body'])} expected, got "
f"{sorted(ab) if isinstance(ab, dict) else type(ab).__name__}"))
elif not eq_val(e["body"], ab, bij):
d.append(("fail", f"unexpected: body {e['body']!r} expected, got {ab!r}"))
for h in e.get("absent_headers", []):
if h in act.get("headers", {}):
d.append(("fail", f"unexpected: header {h} must be absent, got {act['headers'][h]!r}"))
pins = list((e.get("fields") or {}))
status_ok = sts is None or act["status"] in sts
if status_ok:
Expand Down Expand Up @@ -1205,6 +1218,20 @@ def compare_pr(act):
for key, value in (("mergeable", False), ("html_url", "<base>/acme/wrong/pulls/1")):
wrong = dict(pr, body=dict(pr["body"], **{key: value}))
assert any(lv == "fail" and key in text for lv, text in compare_pr(wrong)), f"wrong {key} must fail"
# a departure's `body` pins an error shape and URL, `absent_headers` a header that must not appear
miss = {"errors": ["user redirect does not exist [name: acme]"], "message": "GetOrgByName", "url": "<base>/api/swagger"}
rec = {"kind": "http", "method": "GET", "path": "/api/v1/orgs/acme", "status": 200, "headers": {"x-total-count": "1"},
"body": []}
ov = {"kind": "http", "match": None, "expect": {"status": 404, "message_contains": ["getorgbyname"],
"ignore_body": True, "ignore_headers": ["x-total-count"], "body": miss, "absent_headers": ["x-total-count"]}}
base = {"kind": "http", "method": "GET", "path": "/api/v1/orgs/acme", "status": 404, "headers": {}, "body": miss}
def departed(act):
return [t for lv, t in apply_override(rec, act, ov, Bij()) if lv == "fail"]
assert not departed(base), "the pinned missing-organization answer is honoured"
assert departed(dict(base, body=dict(miss, url="<base>/api/other"))), "a changed URL must fail"
assert departed(dict(base, body=dict(miss, errors=None))), "a changed errors list must fail"
assert departed(dict(base, body=dict(miss, extra=1))), "an extra key must fail"
assert departed(dict(base, headers={"x-total-count": "0"})), "a count header must fail"
bad = []
for d in sorted(os.listdir(a.fixtures_root)):
full = os.path.join(a.fixtures_root, d)
Expand Down
6 changes: 4 additions & 2 deletions crates/forge/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,9 @@ pub fn get_org(ctx: &mut Ctx) -> Resp {
};
match org_visible(ctx, &org) {
Ok(true) => Resp::json(200, &org_json(&ctx.app.base, &org)),
Ok(false) => not_found(&ctx.app.base, "HasOrgOrUserVisible", None),
// Not Gitea's `HasOrgOrUserVisible`: that text tells a private organization from a missing
// one (recorded departure).
Ok(false) => no_such_org(ctx, &name),
Err(e) => ctx.app.internal(&e),
}
}
Expand Down Expand Up @@ -326,7 +328,7 @@ pub fn org_permissions(ctx: &mut Ctx) -> Resp {
// hidden like on `GET /users/{u}`.
match org_visible(ctx, &org) {
Ok(true) => {}
Ok(false) => return not_found(&ctx.app.base, "HasOrgOrUserVisible", None),
Ok(false) => return no_such_org(ctx, &oname),
Err(e) => return ctx.app.internal(&e),
}
let full = match store::is_org_owner(ctx.conn, org.id, subject.id) {
Expand Down
23 changes: 18 additions & 5 deletions crates/forge/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ pub fn by_token(app: &App, conn: &Connection, cred: &Cred, now: i64) -> Result<A
}
}

/// How long a password check waits for an Argon2 slot before the forge answers 503.
const VERIFY_WAIT: std::time::Duration = std::time::Duration::from_secs(2);

/// Resolve the user's password (`Basic login:password`). Every failure answers
/// the same text, runs one full Argon2 verification (against a dummy hash for
/// an unknown login), is counted for backoff, and is delayed.
Expand All @@ -139,28 +142,38 @@ pub fn by_password(app: &App, conn: &Connection, req: &Req, cred: &Cred) -> Resu
)
.with("www-authenticate", "Basic realm=\"sc-forge\"".into()));
};
if !app.backoff.begin(req.source) {
let Some(slot) = app.backoff.begin(req.source) else {
return Err(error(
&app.base,
429,
"too many failed password attempts from this address",
)
.with("retry-after", "60".into()));
}
};
let found = match store::find_by_login(conn, login) {
Ok(u) => u.filter(|u| !u.is_org),
Err(e) => {
app.backoff.cancel(req.source);
app.backoff.cancel(&slot);
return Err(app.internal(&e));
}
};
let ok = {
let _slot = app.gate.acquire();
// Bounded: an unbounded wait would pin a blocking-pool thread per queued login.
let Some(_permit) = app.gate.acquire_timeout(VERIFY_WAIT) else {
// Our own load says nothing about the credential: give the reservation back.
app.backoff.cancel(&slot);
return Err(error(
&app.base,
503,
"too many password checks in flight, try again",
)
.with("retry-after", "5".into()));
};
verify_password(pass, found.as_ref().map(|u| u.password_hash.as_str()))
};
match (ok, found) {
(true, Some(user)) => {
app.backoff.success(login, req.source);
app.backoff.success(login, &slot);
if user.must_change_password {
return Err(error(
&app.base,
Expand Down
21 changes: 19 additions & 2 deletions crates/forge/src/cgi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,12 @@ fn environment(l: &Launch, marker: &std::path::Path) -> Vec<(String, String)> {
env
}

/// Only a receive-pack run is a writer. A dumb-protocol GET has no service and needs only Read, so
/// counting it would let a slow read-only client stall `PATCH default_branch` and lock cleanup.
fn registers_as_writer(service: Option<Service>) -> bool {
service == Some(Service::Receive)
}

fn launch(l: Launch) -> Result<Started, LaunchError> {
let repo_id = l.plan.access.repo.id;
let cfg = l.app.transports.cfg.clone();
Expand All @@ -520,8 +526,7 @@ fn launch(l: Launch) -> Result<Started, LaunchError> {
.registry
.register(
repo_id,
// Only a fetch is known to write no lock and no quarantine directory.
l.plan.service != Some(Service::Upload),
registers_as_writer(l.plan.service),
|| matches!(repos::find_by_id(&conn, repo_id), Ok(Some(r)) if r.state == "live"),
)
.ok_or_else(|| {
Expand Down Expand Up @@ -1051,3 +1056,15 @@ pub async fn handle(app: Arc<App>, req: Req, body: Incoming, path: GitPath) -> R
pub fn answer(r: crate::http::Resp) -> Response<RespBody> {
buffered(r)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn only_receive_pack_registers_as_a_writer() {
assert!(registers_as_writer(Some(Service::Receive)));
assert!(!registers_as_writer(Some(Service::Upload)));
assert!(!registers_as_writer(None), "a dumb GET is a reader");
}
}
44 changes: 42 additions & 2 deletions crates/forge/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use clap::{Args, Parser, Subcommand};
use scl_forge::limits::{Cidr, Proxies};
use scl_forge::server::{bind_gate, make_app, serve, Limits};
use scl_forge::{admin, db};
use std::io::BufRead;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
Expand Down Expand Up @@ -148,8 +149,16 @@ enum UserCmd {
Create {
#[arg(long)]
username: String,
/// Visible in the process list and shell history; prefer `--password-stdin`.
#[arg(
long,
required_unless_present = "password_stdin",
conflicts_with = "password_stdin"
)]
password: Option<String>,
/// Read the password from one line of standard input.
#[arg(long)]
password: String,
password_stdin: bool,
#[arg(long)]
email: String,
#[arg(long)]
Expand All @@ -163,8 +172,16 @@ enum UserCmd {
ChangePassword {
#[arg(long)]
username: String,
/// Visible in the process list and shell history; prefer `--password-stdin`.
#[arg(
long,
required_unless_present = "password_stdin",
conflicts_with = "password_stdin"
)]
password: Option<String>,
/// Read the password from one line of standard input.
#[arg(long)]
password: String,
password_stdin: bool,
#[arg(long, num_args = 0..=1, default_missing_value = "true", default_value = "true", action = clap::ArgAction::Set)]
must_change_password: bool,
#[arg(long)]
Expand Down Expand Up @@ -218,19 +235,40 @@ pub fn run() -> Result<()> {
}
}

/// The password from `--password`, or one line of stdin for `--password-stdin` (the trailing
/// newline is stripped; an empty line is refused).
fn password_arg(arg: Option<String>, from_stdin: bool) -> Result<String> {
if !from_stdin {
return arg.context("--password or --password-stdin is required");
}
let mut line = String::new();
std::io::stdin()
.lock()
.read_line(&mut line)
.context("read the password from stdin")?;
let pw = line.strip_suffix('\n').unwrap_or(&line);
let pw = pw.strip_suffix('\r').unwrap_or(pw);
if pw.is_empty() {
bail!("the password read from stdin is empty");
}
Ok(pw.to_string())
}

fn run_admin(cmd: AdminCmd) -> Result<()> {
match cmd {
AdminCmd::User {
cmd:
UserCmd::Create {
username,
password,
password_stdin,
email,
admin: a,
must_change_password,
data_dir,
},
} => {
let password = password_arg(password, password_stdin)?;
admin::user_create(
&data_dir,
&username,
Expand All @@ -246,10 +284,12 @@ fn run_admin(cmd: AdminCmd) -> Result<()> {
UserCmd::ChangePassword {
username,
password,
password_stdin,
must_change_password,
data_dir,
},
} => {
let password = password_arg(password, password_stdin)?;
admin::user_change_password(&data_dir, &username, &password, must_change_password)?;
println!("{username}'s password has been successfully updated!");
}
Expand Down
Loading
Loading