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

@@ -1658,12 +1658,26 @@ impl ApplyService {
crate::group_repo::set_group_owner_tx(&mut tx, *gid, pid)
.await
.map_err(map_group_err)?;
// Audit (§7.4): seizing another project's group is at
// least as sensitive as the M5 gated-env override — record
// the actor + the ousted owner.
tracing::info!(
user_id = ?actor,
group = %slug,
prev_owner_key = %okey,
"apply: group ownership TAKEN OVER (audit)"
);
report.groups_taken_over += 1;
}
None => {
crate::group_repo::set_group_owner_tx(&mut tx, *gid, pid)
.await
.map_err(map_group_err)?;
tracing::info!(
user_id = ?actor,
group = %slug,
"apply: group ownership CLAIMED (audit)"
);
report.groups_claimed += 1;
}
}
@@ -2005,57 +2019,63 @@ impl ApplyService {
token_parts.push(format!("proj|{}", envs.join(",")));
}
// Ownership (§7, M3): resolve this repo's project, then classify each
// declared group node as ours / unclaimed / owned-by-another. Folding
// the owner key into the token means a claim or takeover by a different
// repo between plan and apply trips StateMoved. (Every group node on the
// tree-apply path pre-exists — `resolve_group` errors otherwise — so
// there is no to-create node to skip, unlike a create-capable engine.)
let our_project_id = match project_key {
Some(k) => crate::group_repo::get_project_id_by_key(&self.pool, k)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?,
None => None,
};
// Ownership (§7, M3): classify each declared group node as ours /
// unclaimed / owned-by-another, and fold the owner key into the token so
// a claim or takeover by a different repo between plan and apply trips
// StateMoved. Gated on `project_key.is_some()` — a legacy caller with NO
// project key skips ALL ownership (no conflicts, no prune, no owner token
// fold), matching the "optional for legacy callers" contract. Note the
// discriminator is a *key present*, NOT a *persisted project*: a
// first-ever apply has a key but no `projects` row yet (our_project_id ==
// None), and MUST still see an already-owned group as a conflict. (Every
// group node pre-exists — `resolve_group` errors otherwise.)
let mut existing_group_nodes: Vec<(GroupId, String)> = Vec::new();
let mut declared_group_slugs: HashSet<String> = HashSet::new();
let mut conflicts: Vec<OwnershipConflict> = Vec::new();
for n in &bundle.nodes {
if n.kind != NodeKind::Group {
continue;
}
let lc = n.slug.to_lowercase();
declared_group_slugs.insert(lc.clone());
let gid = group_id_by_slug[&lc];
existing_group_nodes.push((gid, n.slug.clone()));
let owner = crate::group_repo::get_group_owner(&self.pool, gid)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?;
match &owner {
Some((_, key)) => token_parts.push(format!("own|{lc}|{key}")),
None => token_parts.push(format!("own|{lc}|none")),
}
if let Some((oid, okey)) = owner {
if Some(oid) != our_project_id {
conflicts.push(OwnershipConflict {
slug: n.slug.clone(),
owner_key: okey,
});
let mut prune_candidates: Vec<(GroupId, String)> = Vec::new();
if project_key.is_some() {
let our_project_id = match project_key {
Some(k) => crate::group_repo::get_project_id_by_key(&self.pool, k)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?,
None => None,
};
let mut declared_group_slugs: HashSet<String> = HashSet::new();
for n in &bundle.nodes {
if n.kind != NodeKind::Group {
continue;
}
let lc = n.slug.to_lowercase();
declared_group_slugs.insert(lc.clone());
let gid = group_id_by_slug[&lc];
existing_group_nodes.push((gid, n.slug.clone()));
let owner = crate::group_repo::get_group_owner(&self.pool, gid)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?;
match &owner {
Some((_, key)) => token_parts.push(format!("own|{lc}|{key}")),
None => token_parts.push(format!("own|{lc}|none")),
}
if let Some((oid, okey)) = owner {
if Some(oid) != our_project_id {
conflicts.push(OwnershipConflict {
slug: n.slug.clone(),
owner_key: okey,
});
}
}
}
}
// Structural-prune candidates: groups THIS project owns that the
// manifest omits. Computed read-only here (so `plan` can list them);
// `apply --prune` re-derives the set in-tx and deletes leaf-first.
let mut prune_candidates: Vec<(GroupId, String)> = Vec::new();
if let Some(pid) = our_project_id {
for (gid, slug) in crate::group_repo::list_owned_groups(&self.pool, pid)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?
{
if !declared_group_slugs.contains(&slug.to_lowercase()) {
prune_candidates.push((gid, slug));
// Structural-prune candidates: groups THIS project owns that the
// manifest omits. Computed read-only here (so `plan` can list them);
// `apply --prune` re-derives the set in-tx and deletes leaf-first.
if let Some(pid) = our_project_id {
for (gid, slug) in crate::group_repo::list_owned_groups(&self.pool, pid)
.await
.map_err(|e| ApplyError::Backend(e.to_string()))?
{
if !declared_group_slugs.contains(&slug.to_lowercase()) {
prune_candidates.push((gid, slug));
}
}
}
}