fix(project-tool): close M5+M3 review findings (authz + data-loss + None-path)

A fresh two-lens end-to-end review (security + correctness) of the committed
M5/M3 diff surfaced four real defects; all fixed here with regressions.

- HIGH (M5 authz bypass) — `enforce_env_approval` resolved a group node with a
  bare `get_by_slug` and SKIPPED the GroupAdmin gate on miss. A node addressed
  by the group's UUID (which the apply still resolves) let a group EDITOR apply
  to a confirm-required env without admin. Now resolves UUID-or-slug and fails
  closed, mirroring authz_tree / prepare_tree. Raw-wire regression added.

- FIX-FIRST (M3 correctness) — the legacy `project_key=None` path was not inert:
  the conflict loop pushed a conflict for any owned group (`Some(oid) != None`),
  so a keyless/direct-API tree apply touching an already-claimed group was
  spuriously 409'd. Ownership classification is now gated on a key being present
  (the discriminator is key-present, not project-persisted, so a first-ever
  keyed apply still sees an already-owned group as a conflict). Regression added.

- FIX-FIRST (M3 data-loss) — the structural-prune guard checked collection
  MARKERS (`group_collections`) but data outlives its marker: un-declaring a
  `collections=[...]` entry drops the marker while the kv/docs/files/queue rows
  survive until group delete. A dropped-then-pruned group would silently CASCADE
  that orphaned data. The guard now EXISTS-checks the actual data tables
  (group_kv_entries/docs/files/queue_messages) plus secrets + markers.

- MEDIUM (audit) — group ownership takeover (and claim) now emit a
  tracing::info! audit line with the actor + ousted owner, matching the M5
  gated-env audit. Previously only a report counter.

Also: documented WHY `pic plan --dir` mints the project key (a rare write for a
read-only command) — plan and apply must present the same key or the ownership
token folds diverge and trip a spurious StateMoved.

Re-verified: 411 manager-core lib tests; 28 CLI journeys (incl. 2 new
regressions: uuid-slug admin gate, keyless legacy apply); workspace clippy
-D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-05 20:45:23 +02:00
parent 5c33b7490b
commit 4c68d2fa33
6 changed files with 222 additions and 68 deletions

View File

@@ -165,3 +165,76 @@ fn approving_a_gated_apply_requires_admin() {
"approval denial should be an authz error:\n{err}"
);
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn gated_group_node_admin_gate_is_not_bypassable_by_uuid_slug() {
// Regression (§4.2): `enforce_env_approval` must resolve a group node by
// UUID-or-slug and FAIL CLOSED — a bare `get_by_slug` skipped the GroupAdmin
// gate when the node addressed the group by its UUID (which the apply still
// resolves), letting a group EDITOR apply to a confirm-required env without
// admin. We drive the raw `/tree/apply` wire directly (the CLI only ever
// sends slugs) with the group node's UUID as its slug.
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let group = common::unique_slug("appr3-g");
let _g = GroupGuard::new(&env.url, &env.token, &group);
common::pic_as(&env)
.args(["groups", "create", &group])
.assert()
.success();
// Resolve the group's UUID.
let http = reqwest::blocking::Client::new();
let detail: serde_json::Value = http
.get(format!("{}/api/v1/admin/groups/{}", env.url, group))
.bearer_auth(&env.token)
.send()
.expect("get group")
.json()
.expect("group json");
let group_uuid = detail["id"].as_str().expect("group id").to_string();
// A group `editor` — write caps, but NOT GroupAdmin.
let m = member::member_user(fx, &common::unique_username("appr3"));
common::pic_as(&env)
.args([
"groups", "members", "add", &group, &m.id, "--role", "editor",
])
.assert()
.success();
// A gated bundle whose single group node is addressed by UUID. A `vars`
// entry makes the node non-empty (and exercises the editor's write cap).
let body = serde_json::json!({
"bundle": {
"nodes": [{
"kind": "group",
"slug": group_uuid,
"bundle": { "vars": { "region": "eu" } }
}],
"project": { "environments": [{ "name": "production", "confirm": true }] }
},
"prune": false,
"env": "production",
"approved_envs": ["production"],
"allow_takeover": false,
});
let resp = http
.post(format!("{}/api/v1/admin/tree/apply", env.url))
.bearer_auth(&m.token)
.json(&body)
.send()
.expect("tree apply");
assert_eq!(
resp.status().as_u16(),
403,
"a group editor must be 403'd approving a gated apply even when the node \
is addressed by UUID (got {}: {})",
resp.status(),
resp.text().unwrap_or_default()
);
}

View File

@@ -286,3 +286,47 @@ fn prune_refuses_to_cascade_a_groups_shared_data() {
"a group owning shared collections must NOT be pruned"
);
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn legacy_apply_without_project_key_ignores_ownership() {
// Regression (§7): a tree apply with NO project key (legacy / direct-API
// caller) must skip ALL ownership — no conflicts, no claims. A bug gated the
// conflict classification on `our_project_id` (None for a keyless caller),
// so ANY already-owned declared group was spuriously rejected. Drive the raw
// wire without `project_key` (the CLI always sends one).
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let slug = common::unique_slug("own-legacy");
let _g = GroupGuard::new(&env.url, &env.token, &slug);
create_group(&env, &slug, None);
// Repo A claims the group (a normal CLI apply — sends a project key).
let repo_a = group_dir(&slug, "");
assert!(
apply(&env, repo_a.path(), &[]).status.success(),
"claim apply should succeed"
);
// A keyless raw apply of the same (now-owned) group must NOT 409 — ownership
// is simply not evaluated without a project key.
let http = reqwest::blocking::Client::new();
let body = serde_json::json!({
"bundle": { "nodes": [{ "kind": "group", "slug": slug, "bundle": {} }] },
"prune": false,
});
let resp = http
.post(format!("{}/api/v1/admin/tree/apply", env.url))
.bearer_auth(&env.token)
.json(&body)
.send()
.expect("tree apply");
assert!(
resp.status().is_success(),
"a keyless (legacy) apply must ignore ownership, not conflict (got {}: {})",
resp.status(),
resp.text().unwrap_or_default()
);
}