test/docs(ownership): §7 apply_ownership journey + design/CLAUDE updates

End-to-end coverage of the M1 ownership claim through the real CLI + server:
claim-on-first-apply + owner column, idempotent re-apply by the owner, a
second project refused (409, naming the owner), --takeover by an admin,
app-inheritance from the nearest claimed ancestor (owning project ok; foreign
or absent project refused), and the capability gate — a member with only an
editor GROUP role can reconcile but is refused --takeover (needs group-admin),
with ownership unchanged after the failed takeover.

- tests/apply_ownership.rs (registered in cli.rs); a grant_group_membership
  helper in tests/common/member.rs (group-level, mirroring the app one).
- design doc §7 gains an M1-shipped status note; CLAUDE.md records §7 M1 and
  re-points 'Next' at M2 (attach ceiling) + M3 (blast-radius / pic projects ls).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-06 20:49:31 +02:00
parent b33c87e5c4
commit 5bd72956b1
5 changed files with 257 additions and 1 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,216 @@
//! §7 multi-repo ownership — the claim, end to end via `pic`.
//!
//! A `[project]` claims a group node on first apply; the SAME project re-applies
//! freely; a DIFFERENT project applying to that node is refused (409) unless it
//! `--takeover`s (which requires group-admin). An app inherits ownership from
//! its nearest claimed ancestor group. `pic groups ls` shows the owning
//! project's slug. The pure claim policy is unit-tested in manager-core; this
//! journey pins the wire + CLI + authz interaction.
use std::fs;
use std::path::Path;
use tempfile::TempDir;
use crate::common;
use crate::common::cleanup::{AppGuard, GroupGuard, ScriptGuard};
fn manifest_dir() -> TempDir {
let dir = TempDir::new().expect("tempdir");
fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir");
fs::write(
dir.path().join("scripts/shared.rhai"),
r#"log::info("shared"); "ok""#,
)
.unwrap();
dir
}
/// A `[project]` + `[group]` manifest (with one group script) in `dir`.
fn write_group_manifest(dir: &Path, project: &str, group: &str) {
let m = format!(
"[project]\nslug = \"{project}\"\nname = \"Proj\"\n\n\
[group]\nslug = \"{group}\"\nname = \"Grp\"\n\n\
[[scripts]]\nname = \"shared\"\nfile = \"scripts/shared.rhai\"\n"
);
fs::write(dir.join("picloud.toml"), m).unwrap();
}
fn group_script_id(env: &common::TestEnv, group: &str) -> String {
let ls = common::pic_as(env)
.args(["scripts", "ls", "--group", group])
.output()
.expect("scripts ls");
let table = String::from_utf8(ls.stdout).unwrap();
table
.lines()
.map(common::cells)
.find(|c| c.get(2) == Some(&"shared"))
.and_then(|c| c.first().map(|s| (*s).to_string()))
.unwrap_or_else(|| panic!("group script not found:\n{table}"))
}
/// The `owner` cell (index 3: slug, name, parent, OWNER, created_at) for
/// `group` in `pic groups ls`.
fn owner_cell(env: &common::TestEnv, group: &str) -> String {
let ls = common::pic_as(env)
.args(["groups", "ls"])
.output()
.expect("groups ls");
let table = String::from_utf8(ls.stdout).unwrap();
table
.lines()
.map(common::cells)
.find(|c| c.first() == Some(&group))
.and_then(|c| c.get(3).map(|s| (*s).to_string()))
.unwrap_or_else(|| panic!("group `{group}` not in groups ls:\n{table}"))
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn claim_conflict_takeover_and_app_inheritance() {
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let group = common::unique_slug("own-grp");
let proj_a = common::unique_slug("plat");
let proj_b = common::unique_slug("teamb");
// The group must pre-exist (groups pre-exist; the manifest owns content).
let _g = GroupGuard::new(&env.url, &env.token, &group);
common::pic_as(&env)
.args(["groups", "create", &group])
.assert()
.success();
// (1) First apply by project A CLAIMS the group.
let dir_a = manifest_dir();
write_group_manifest(dir_a.path(), &proj_a, &group);
common::pic_as(&env)
.args(["apply", "--file"])
.arg(dir_a.path().join("picloud.toml"))
.assert()
.success();
let _gs = ScriptGuard::new(&env.url, &env.token, &group_script_id(&env, &group));
assert_eq!(
owner_cell(&env, &group),
proj_a,
"the owner column must show the claiming project"
);
// (2) The SAME project re-applies with no conflict (idempotent).
common::pic_as(&env)
.args(["apply", "--file"])
.arg(dir_a.path().join("picloud.toml"))
.assert()
.success();
// (3) A DIFFERENT project applying to the owned group is refused (409),
// naming the current owner.
let dir_b = manifest_dir();
write_group_manifest(dir_b.path(), &proj_b, &group);
let out = common::pic_as(&env)
.args(["apply", "--file"])
.arg(dir_b.path().join("picloud.toml"))
.output()
.expect("apply B");
assert!(!out.status.success(), "a second project must be refused");
let err = String::from_utf8_lossy(&out.stderr).to_lowercase();
assert!(
err.contains("owned by project") && err.contains(&proj_a),
"the conflict must name the owner `{proj_a}`:\n{err}"
);
// (4) --takeover (admin holds group-admin implicitly) reassigns to B.
common::pic_as(&env)
.args(["apply", "--file"])
.arg(dir_b.path().join("picloud.toml"))
.arg("--takeover")
.assert()
.success();
assert_eq!(
owner_cell(&env, &group),
proj_b,
"takeover must reassign the owner"
);
// (5) An app under the claimed group INHERITS ownership: the owning project
// applies fine; a foreign or absent project is refused.
let app = common::unique_slug("own-app");
let _a = AppGuard::new(&env.url, &env.token, &app);
common::pic_as(&env)
.args(["apps", "create", &app, "--group", &group])
.assert()
.success();
let app_dir = manifest_dir();
let app_manifest = |proj: Option<&str>| -> String {
let head = proj
.map(|p| format!("[project]\nslug = \"{p}\"\n\n"))
.unwrap_or_default();
format!("{head}[app]\nslug = \"{app}\"\nname = \"App\"\n")
};
// Project B owns the group → ok.
fs::write(
app_dir.path().join("picloud.toml"),
app_manifest(Some(&proj_b)),
)
.unwrap();
common::pic_as(&env)
.args(["apply", "--file"])
.arg(app_dir.path().join("picloud.toml"))
.assert()
.success();
// Project A no longer owns the group → refused.
fs::write(
app_dir.path().join("picloud.toml"),
app_manifest(Some(&proj_a)),
)
.unwrap();
let out = common::pic_as(&env)
.args(["apply", "--file"])
.arg(app_dir.path().join("picloud.toml"))
.output()
.expect("apply app A");
assert!(
!out.status.success(),
"an app under a claimed group must match its owner"
);
// No [project] under a claimed subtree → refused.
fs::write(app_dir.path().join("picloud.toml"), app_manifest(None)).unwrap();
let out = common::pic_as(&env)
.args(["apply", "--file"])
.arg(app_dir.path().join("picloud.toml"))
.output()
.expect("apply app none");
assert!(
!out.status.success(),
"a no-project app under a claimed subtree is refused"
);
// (6) --takeover is capability-gated: a member with only EDITOR on the group
// can reconcile it but must NOT be able to take it over (needs group-admin).
let mem = common::member::member_user(fx, &common::unique_slug("own-mem"));
common::member::grant_group_membership(fx, &group, &mem.id, "editor");
let menv = common::custom_env(&env.url, &mem.token);
common::seed_credentials(&menv, &mem.username);
let proj_c = common::unique_slug("teamc");
let dir_c = manifest_dir();
write_group_manifest(dir_c.path(), &proj_c, &group);
let out = common::pic_as(&menv)
.args(["apply", "--file"])
.arg(dir_c.path().join("picloud.toml"))
.arg("--takeover")
.output()
.expect("member takeover");
assert!(
!out.status.success(),
"a member without group-admin must not be able to --takeover"
);
// The owner is unchanged — the failed takeover rolled back.
assert_eq!(
owner_cell(&env, &group),
proj_b,
"a refused takeover must not change ownership"
);
}

View File

@@ -16,6 +16,7 @@ mod common;
mod admins; mod admins;
mod api_keys; mod api_keys;
mod apply; mod apply;
mod apply_ownership;
mod apps; mod apps;
mod auth; mod auth;
mod collections; mod collections;

View File

@@ -78,6 +78,29 @@ pub fn grant_membership(fx: &Fixture, app_slug: &str, user_id: &str, role: &str)
); );
} }
/// `POST /api/v1/admin/groups/{slug}/members` — grant `role` to `user_id` on a
/// GROUP (hierarchy-aware). §7 takeover tests use this to give a member an
/// `editor` group role — enough to reconcile a group node, but NOT to
/// `--takeover` (which needs `GroupAdmin`).
pub fn grant_group_membership(fx: &Fixture, group_slug: &str, user_id: &str, role: &str) {
let client = reqwest::blocking::Client::new();
let resp = client
.post(format!(
"{}/api/v1/admin/groups/{}/members",
fx.url, group_slug
))
.bearer_auth(&fx.admin_token)
.json(&json!({ "user_id": user_id, "role": role }))
.send()
.expect("grant group membership");
assert!(
resp.status().is_success(),
"grant group membership failed: {} {}",
resp.status(),
resp.text().unwrap_or_default(),
);
}
/// `PATCH /api/v1/admin/apps/{slug}/members/{user_id}` — promote/demote. /// `PATCH /api/v1/admin/apps/{slug}/members/{user_id}` — promote/demote.
pub fn update_membership(fx: &Fixture, app_slug: &str, user_id: &str, role: &str) { pub fn update_membership(fx: &Fixture, app_slug: &str, user_id: &str, role: &str) {
let client = reqwest::blocking::Client::new(); let client = reqwest::blocking::Client::new();

View File

@@ -764,6 +764,22 @@ non-orphaning:
**Corollary:** don't co-own a node — split config downward. Shared config lives *higher* (owned by a **Corollary:** don't co-own a node — split config downward. Shared config lives *higher* (owned by a
platform/shared repo attaching at root); team-specific bits go into subgroups each team owns. platform/shared repo attaching at root); team-specific bits go into subgroups each team owns.
**Status — M1 shipped (the ownership claim).** The `owner_project` seam (0047) is now live, backed by a
first-class `projects` table (`0066`, UUID pk + unique slug; `owner_project` FKs it `ON DELETE SET NULL`).
A `[project]` block (slug + optional name) in the repo's root manifest declares identity; the first apply
with a new slug registers the project and **claims** each group node it touches. The claim is a gate run
inside the apply transaction, under the per-node advisory lock, *before* the diff — so a conflict
short-circuits with a 409 before any write. Pure policy (`decide_group_claim` / `decide_app_owner` in
`apply_service`): unclaimed→claim, owner→no-op, foreign→conflict unless `--takeover` (which additionally
requires `GroupAdmin` — ownership ⟂ RBAC), no-project-into-a-claimed-subtree→conflict. Apps carry no
`owner_project`; an app inherits ownership from its **nearest claimed ancestor group** (the ancestor walk
is the boundary), and an unclaimed subtree stays open (backward-compatible — nothing changes until a repo
first declares `[project]`). Visibility: `pic groups ls` shows an `owner` column; `--takeover` on `pic
apply`. Pinned by `apply_service` unit tests + the `apply_ownership` journey. **Deferred:** point 2's
attach-point *ceiling* (M2 — `[project] parent_group`), and the plan-time cross-repo blast-radius preview +
`pic projects ls` (M3). The **structural-divergence** detection of §6 and declarative group create/reparent
(lifting "groups pre-exist") remain later work.
--- ---
## 8. Diagrams ## 8. Diagrams