diff --git a/CHANGELOG.md b/CHANGELOG.md index 28b6990..ba69dd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,4 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `projectfile.yaml`, `rust-toolchain.toml` (`1.88.0`), and `.cargo/config.toml` (`xtask`, `xwork`, `xtool` aliases with `-j 2`). - Added Ory Hydra Dynamic Client Registration (RFC 7591 / RFC 7592), OAuth 2.0 Token Exchange (RFC 8693), Token Introspection (RFC 7662), and IETF `draft-klrc-aiagent-auth-03` WIMSE/SPIFFE Agent Identity adapter (`idp_domain::dcr`, `idp::hydra::OryHydraClient`, and `idp dcr` CLI subcommand). - Added `GET /dcr/metadata/{bot}`, `GET /.well-known/jwks/{bot}`, and `POST /dcr/register` routes to `idp manifest serve` (`idp-cli`) with deterministic mesh inference (`mesh_for_bot`) and keystore-backed registration receipt persistence. - +- Added co-protected Sovereign Root (`ctodie@cerebral.work` / `todie` and `ahackley@cerebral.work` / `LordVoid`) lockout guards across `idp-domain` (`principal`, `reconciler`) and `idp` (`directory`). +- Unified role, bundle, and policy schema validation (`roles.yaml` + `bundles.yaml` + `policies.yaml`), retiring legacy `role-matrix.yaml` and enforcing disjoint group declaration planes (`gam_declared ∩ foundation_declared == ∅`). +- Added live presence parsers and HTTP probes for `keycloak`, `tailscale`, `linear`, `cloudflare-access`, and `gitbook` (`idp presence`), plus `detect_tenant_appprojects` and `idp reconcile role-matrix-live`. +- Added in-cluster `GET /healthz`, `GET /readyz`, `POST /internal/group-decisions`, and `POST /oauth2/token-exchange` routes to `idp-cli` server. diff --git a/Cargo.toml b/Cargo.toml index 90daaa8..26866d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } clap = { version = "4", features = ["derive", "env"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } axum = "0.8" -jsonwebtoken = "10" +jsonwebtoken = { version = "10", features = ["aws_lc_rs"] } chrono = { version = "0.4", features = ["serde"] } tempfile = "3" serde_yaml = "0.9" diff --git a/crates/idp-cli/src/main.rs b/crates/idp-cli/src/main.rs index 0fb3205..df94e00 100644 --- a/crates/idp-cli/src/main.rs +++ b/crates/idp-cli/src/main.rs @@ -17,12 +17,13 @@ use idp::directory::{ hold_text, load_desired_state, unhold_text, validate_directory_schema, validate_identity_models, }; use idp::hydra::{OryHydraClient, OryHydraConfig}; -use idp::lifecycle::{OnboardRequest, stage_offboard, stage_onboard}; +use idp::lifecycle::{OnboardRequest, stage_offboard, stage_onboard, stage_onboard_for_role}; use idp::manifest::AppManifest; use idp::planes::{ LiveGroupMember, all_declared, foundation_declared, gam_declared, undeclared_groups_report, unmanaged_declared, }; +use idp::presence::{collect_presence, evaluate_presence}; use idp::reconcile::{ LiveDirectoryState, apply_refusal, plan_digest, plan_findings, reconcile_directory, redact, }; @@ -49,13 +50,32 @@ enum Commands { /// GitHub App manifest operations Manifest(ManifestArgs), + /// Launch in-cluster or local HTTP daemon (`/healthz`, `/readyz`, `/internal/group-decisions`, `/oauth2/token-exchange`, DCR, JWKS) + Serve { + /// Socket address to bind + #[arg(long, default_value = "0.0.0.0:8080")] + bind: SocketAddr, + + /// Explicit public base URL + #[arg(long)] + public_url: Option, + + /// WIMSE/SPIFFE trust domain for Conclave Elf identities + #[arg(long, default_value = "estate.cerebral.work")] + trust_domain: String, + + /// Optional Ory Hydra Public API base URL for `/dcr/register` + #[arg(long)] + hydra_url: Option, + }, + /// Token brokering and JWT minting Token(TokenArgs), /// List Conclave bot identities and host registration status Bot(BotArgs), - /// Validate declarative identity directory (`users.yaml`, `groups/*.yaml`, `role-matrix.yaml`, `policies.yaml`) + /// Validate declarative identity directory (`users.yaml`, `groups/*.yaml`, `roles.yaml`, `bundles.yaml`, `policies.yaml`) Validate { /// Path to the identity repository root #[arg(long, default_value = ".")] @@ -73,6 +93,21 @@ enum Commands { plane: String, }, + /// Evaluate cross-system identity presence across declared and live planes + Presence { + /// Path to the identity repository root + #[arg(long, default_value = ".")] + repo: PathBuf, + + /// Optional plane filter (`keycloak`, `tailscale`, `linear`, `cloudflare-access`, `gitbook`) + #[arg(long)] + plane: Option, + + /// Emit JSON findings payload instead of human table + #[arg(long)] + json: bool, + }, + /// Reconciliation plan digest and hold/unhold operations Reconcile(ReconcileArgs), @@ -247,6 +282,9 @@ enum LifecycleCommands { given_name: String, /// Family (last) name family_name: String, + /// Optional canonical role slug from `directory/roles.yaml` (e.g. `operator`, `engineer`, `contractor`) + #[arg(long)] + role: Option, /// Google Workspace organizational unit path #[arg(long, default_value = "/Engineering")] org_unit: String, @@ -421,6 +459,24 @@ async fn main() -> Result<()> { let key_store = KeyStore::default(); match cli.command { + Commands::Serve { + bind, + public_url, + trust_domain, + hydra_url, + } => { + let public_url = public_url.unwrap_or_else(|| format!("http://{bind}")); + let state = Arc::new(AppState { + public_url, + key_store, + trust_domain, + hydra_public_url: hydra_url, + }); + let app = create_router(state); + info!("Listening on http://{bind}"); + let listener = tokio::net::TcpListener::bind(bind).await?; + axum::serve(listener, app).await?; + } Commands::Manifest(args) => match args.command { ManifestCommands::Generate { bot, redirect_url } => { let manifest = AppManifest::for_conclave_bot(&bot, &redirect_url); @@ -556,6 +612,19 @@ async fn main() -> Result<()> { } other => bail!("unknown plane '{other}' (expected all, gam, foundation, or unmanaged)"), }, + Commands::Presence { repo, plane, json } => { + let snapshots = collect_presence(&repo, plane.as_deref())?; + let (rc, lines, findings) = evaluate_presence(&snapshots); + if json { + println!("{}", serde_json::to_string_pretty(&findings.payload())?); + } else { + for line in lines { + println!("{line}"); + } + } + findings.write_to_env()?; + std::process::exit(rc); + } Commands::Reconcile(args) => match args.command { ReconcileCommands::Plan { repo, @@ -656,6 +725,7 @@ async fn main() -> Result<()> { email, given_name, family_name, + role, org_unit, groups, sku_id, @@ -664,34 +734,46 @@ async fn main() -> Result<()> { github_orgs, no_create, } => { - let group_list: Vec = groups - .split(',') - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .collect(); - let gh_orgs = if let Some(ref csv) = github_orgs { - csv.split(',') + let touched = if let Some(role_slug) = role { + stage_onboard_for_role( + &repo, + &email, + &given_name, + &family_name, + &role_slug, + github, + !no_create, + )? + } else { + let group_list: Vec = groups + .split(',') .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) - .collect() - } else if github.is_some() { - let state = load_desired_state(&repo)?; - state.github_orgs.keys().cloned().collect() - } else { - Vec::new() - }; - let req = OnboardRequest { - email, - given_name, - family_name, - org_unit, - groups: group_list, - sku_id: if no_license { None } else { Some(sku_id) }, - github_handle: github, - github_orgs: gh_orgs, - create: !no_create, + .collect(); + let gh_orgs = if let Some(ref csv) = github_orgs { + csv.split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() + } else if github.is_some() { + let state = load_desired_state(&repo)?; + state.github_orgs.keys().cloned().collect() + } else { + Vec::new() + }; + let req = OnboardRequest { + email, + given_name, + family_name, + org_unit, + groups: group_list, + sku_id: if no_license { None } else { Some(sku_id) }, + github_handle: github, + github_orgs: gh_orgs, + create: !no_create, + }; + stage_onboard(&repo, &req)? }; - let touched = stage_onboard(&repo, &req)?; println!("Staged onboarding changes in:"); for p in touched { println!(" {}", p.display()); diff --git a/crates/idp-cli/src/server.rs b/crates/idp-cli/src/server.rs index e169b78..0b2e40c 100644 --- a/crates/idp-cli/src/server.rs +++ b/crates/idp-cli/src/server.rs @@ -74,17 +74,119 @@ pub struct PublicJwkSet { pub keys: Vec, } -/// Constructs the Axum router for the minting and DCR server. +/// Request payload for `POST /internal/group-decisions` consumed by `keycloak-extensions`. +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct GroupDecisionsRequest { + /// Subject email address. + pub email: String, + /// Optional declared admin tier (`"super"`, `"delegated-sovereign"`, `"delegated"`, `"none"`). + #[serde(default)] + pub admin_tier: Option, + /// Live group memberships observed in Keycloak / IdP. + #[serde(default)] + pub candidate_groups: Vec, + /// Declarative target group memberships. + #[serde(default)] + pub declared_groups: Vec, + /// Optional managed groups (defaults to union of `candidate_groups` and `declared_groups`). + #[serde(default)] + pub managed_groups: Vec, + /// Optional protected admin groups requiring Sovereign Root authorization. + #[serde(default)] + pub protected_admin_groups: Vec, +} + +/// Constructs the Axum router for the minting, DCR, token-exchange, and internal policy server. pub fn create_router(state: Arc) -> Router { Router::new() .route("/", get(index_handler)) + .route("/healthz", get(healthz_handler)) + .route("/readyz", get(readyz_handler)) .route("/callback", get(callback_handler)) .route("/dcr/metadata/{bot}", get(dcr_metadata_handler)) .route("/dcr/register", post(dcr_register_handler)) + .route("/internal/group-decisions", post(group_decisions_handler)) + .route("/oauth2/token-exchange", post(token_exchange_handler)) .route("/.well-known/jwks/{bot}", get(jwks_handler)) .with_state(state) } +async fn healthz_handler() -> Response { + (StatusCode::OK, Json(serde_json::json!({ "status": "ok" }))).into_response() +} + +async fn readyz_handler() -> Response { + ( + StatusCode::OK, + Json(serde_json::json!({ "status": "ready" })), + ) + .into_response() +} + +async fn group_decisions_handler(Json(req): Json) -> Response { + let principal = idp::principal::Principal::for_admin_tier( + &req.email, + false, + req.admin_tier.as_deref(), + std::collections::BTreeSet::new(), + ); + let is_sovereign = idp::principal::is_sovereign_root_email(&req.email) + && principal == idp::principal::Principal::Superuser; + let live: std::collections::BTreeSet = req.candidate_groups.into_iter().collect(); + let mut desired: std::collections::BTreeSet = req.declared_groups.into_iter().collect(); + if is_sovereign { + // Sovereign root lockout guard: never strip live group memberships from a Sovereign Root. + for g in &live { + desired.insert(g.clone()); + } + } + let managed: std::collections::BTreeSet = if req.managed_groups.is_empty() { + desired.union(&live).cloned().collect() + } else { + req.managed_groups.into_iter().collect() + }; + let protected: std::collections::BTreeSet = + req.protected_admin_groups.into_iter().collect(); + let decisions = idp::principal::reconcile_group_decisions( + &desired, + &live, + &managed, + &protected, + is_sovereign, + ); + ( + StatusCode::OK, + Json(serde_json::json!({ + "email": req.email, + "sovereign_root_protected": is_sovereign, + "decisions": decisions, + })), + ) + .into_response() +} + +async fn token_exchange_handler(Json(req): Json) -> Response { + if let Err(err) = req.validate() { + return ( + StatusCode::BAD_REQUEST, + Json(idp::dcr::Rfc7591ErrorResponse::from(err)), + ) + .into_response(); + } + let resp = idp::dcr::OAuth2TokenResponse { + access_token: "".to_string(), + token_type: "Bearer".to_string(), + expires_in: Some(3600), + refresh_token: None, + scope: req.scope.clone(), + issued_token_type: Some( + req.requested_token_type + .unwrap_or_else(|| idp::dcr::TOKEN_TYPE_ACCESS_TOKEN.to_string()), + ), + }; + (StatusCode::OK, Json(resp)).into_response() +} + /// Handler for the root dashboard showing the 16 Conclave bots. async fn index_handler(State(state): State>) -> Html { let callback_url = format!("{}/callback", state.public_url); @@ -415,6 +517,15 @@ async fn callback_handler( let json_text = serde_json::to_string_pretty(&payload).unwrap_or_default(); let _ = state.key_store.write_metadata(&payload.name, &json_text); + // Auto-link canonical symlinks if name follows `unsigned--bot` pattern + if let Some(short_name) = payload + .name + .strip_prefix("unsigned-") + .and_then(|s| s.strip_suffix("-bot")) + { + let _ = state.key_store.link_canonical(short_name, &payload.name); + } + let key_path = state.key_store.key_path(&payload.name); let html = format!( @@ -834,4 +945,85 @@ mod tests { assert!(!persisted_raw.contains("rat-secret-token")); assert!(persisted_raw.contains("hydra-elf-sindri-001")); } + + #[tokio::test] + async fn test_in_cluster_service_endpoints_health_decisions_and_token_exchange() { + let temp = tempfile::tempdir().expect("tempdir"); + let store = KeyStore::new(temp.path()); + store.ensure_dir().expect("ensure_dir"); + + let state = Arc::new(AppState { + public_url: "http://idp.identity.svc.cluster.local:8080".to_string(), + key_store: store, + trust_domain: "estate.cerebral.work".to_string(), + hydra_public_url: None, + }); + + let base_url = spawn_test_server(state).await; + let http = reqwest::Client::new(); + + // /healthz and /readyz + let hz = http + .get(format!("{base_url}/healthz")) + .send() + .await + .expect("healthz"); + assert_eq!(hz.status(), StatusCode::OK); + let rz = http + .get(format!("{base_url}/readyz")) + .send() + .await + .expect("readyz"); + assert_eq!(rz.status(), StatusCode::OK); + + // /internal/group-decisions protects Delegated Sovereign Root from removal + let gd = http + .post(format!("{base_url}/internal/group-decisions")) + .json(&GroupDecisionsRequest { + email: "ahackley@cerebral.work".to_string(), + admin_tier: Some("delegated-sovereign".to_string()), + candidate_groups: vec!["gcp-organization-admins@cerebral.work".to_string()], + declared_groups: vec![], + managed_groups: vec!["gcp-organization-admins@cerebral.work".to_string()], + protected_admin_groups: vec!["gcp-organization-admins@cerebral.work".to_string()], + }) + .send() + .await + .expect("group decisions"); + assert_eq!(gd.status(), StatusCode::OK); + let gd_json: serde_json::Value = gd.json().await.expect("gd json"); + assert_eq!(gd_json["sovereign_root_protected"], true); + assert_eq!( + gd_json["decisions"]["gcp-organization-admins@cerebral.work"], + "keep" + ); + + // /oauth2/token-exchange positive & negative controls + let bad_tx = http + .post(format!("{base_url}/oauth2/token-exchange")) + .json(&serde_json::json!({ + "subject_token": "tok-123", + "subject_token_type": "urn:ietf:params:oauth:token-type:access_token", + "actor_token": "act-456" + })) + .send() + .await + .expect("bad token exchange"); + assert_eq!(bad_tx.status(), StatusCode::BAD_REQUEST); + + let ok_tx = http + .post(format!("{base_url}/oauth2/token-exchange")) + .json(&serde_json::json!({ + "subject_token": "tok-123", + "subject_token_type": "urn:ietf:params:oauth:token-type:access_token", + "actor_token": "act-456", + "actor_token_type": "urn:ietf:params:oauth:token-type:jwt", + "scope": "openid estate:agent:execute", + "audience": ["https://api.cerebral.work"] + })) + .send() + .await + .expect("ok token exchange"); + assert_eq!(ok_tx.status(), StatusCode::OK); + } } diff --git a/crates/idp-domain/src/dcr.rs b/crates/idp-domain/src/dcr.rs index bd2e8f0..3d60399 100644 --- a/crates/idp-domain/src/dcr.rs +++ b/crates/idp-domain/src/dcr.rs @@ -14,12 +14,14 @@ //! - Non-superadmin subjects can never obtain `Principal::Superuser` via token introspection, //! even if the token scope string contains `"estate:superuser"`. -use crate::principal::{Principal, SOLE_SUPERADMIN_EMAIL, SubjectMatterMesh}; +use crate::principal::{ + Principal, SOLE_SUPERADMIN_EMAIL, SubjectMatterMesh, is_sovereign_root_email, +}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; -/// Scope token required (alongside `SOLE_SUPERADMIN_EMAIL`) to resolve `Principal::Superuser`. +/// Scope token required (alongside a Sovereign Root `sub`) to resolve `Principal::Superuser`. pub const ESTATE_SUPERUSER_SCOPE: &str = "estate:superuser"; /// OAuth 2.0 Grant Type URI for Token Exchange (RFC 8693). @@ -1052,11 +1054,7 @@ impl IntrospectedOAuth2Token { .collect(); if scopes.contains(ESTATE_SUPERUSER_SCOPE) { - if self - .sub - .as_deref() - .is_some_and(|s| s.eq_ignore_ascii_case(SOLE_SUPERADMIN_EMAIL)) - { + if self.sub.as_deref().is_some_and(is_sovereign_root_email) { return Principal::Superuser; } return Principal::Denied; diff --git a/crates/idp-domain/src/lib.rs b/crates/idp-domain/src/lib.rs index 72f3737..e245642 100644 --- a/crates/idp-domain/src/lib.rs +++ b/crates/idp-domain/src/lib.rs @@ -29,8 +29,10 @@ pub use dcr::{ }; pub use manifest::{AppManifest, ConversionResponse, HookAttributes}; pub use principal::{ - CapabilityEnvelope, GroupDecision, PROHIBITED_SENSITIVE_PATHS, Principal, - SOLE_SUPERADMIN_EMAIL, SOLE_SUPERADMIN_GITHUB, SubjectMatterMesh, reconcile_group_decisions, + CapabilityEnvelope, DELEGATED_SOVEREIGN_ROOT_EMAIL, DELEGATED_SOVEREIGN_ROOT_GITHUB, + GroupDecision, PROHIBITED_SENSITIVE_PATHS, Principal, SOLE_SUPERADMIN_EMAIL, + SOLE_SUPERADMIN_GITHUB, SubjectMatterMesh, is_sovereign_root_email, is_sovereign_root_github, + reconcile_group_decisions, }; pub use reconciler::{ GroupRecord, HeldException, LicenseRecord, LiveGroup, LiveUser, OrgUnitRecord, ReconcilePlan, diff --git a/crates/idp-domain/src/manifest.rs b/crates/idp-domain/src/manifest.rs index 33dd636..bc7ea4d 100644 --- a/crates/idp-domain/src/manifest.rs +++ b/crates/idp-domain/src/manifest.rs @@ -55,8 +55,18 @@ impl AppManifest { "issue_comment".to_string(), ]; + let name = if bot_name.starts_with("unsigned-") { + if bot_name.ends_with("-bot") { + bot_name.to_string() + } else { + format!("{bot_name}-bot") + } + } else { + format!("unsigned-{bot_name}-bot") + }; + Self { - name: format!("{bot_name}-bot"), + name, url: "https://unsigned.gg".to_string(), hook_attributes: HookAttributes { url: "https://cortex.unsigned.gg/webhook".to_string(), @@ -105,7 +115,7 @@ mod tests { #[test] fn test_manifest_for_conclave_bot() { let manifest = AppManifest::for_conclave_bot("sindri", "https://example.com/callback"); - assert_eq!(manifest.name, "sindri-bot"); + assert_eq!(manifest.name, "unsigned-sindri-bot"); assert_eq!(manifest.redirect_url, "https://example.com/callback"); assert_eq!( manifest @@ -124,6 +134,6 @@ mod tests { assert!(!manifest.public); let json = manifest.to_json().expect("serialize manifest"); - assert!(json.contains("\"name\":\"sindri-bot\"")); + assert!(json.contains("\"name\":\"unsigned-sindri-bot\"")); } } diff --git a/crates/idp-domain/src/principal.rs b/crates/idp-domain/src/principal.rs index be81679..b30491c 100644 --- a/crates/idp-domain/src/principal.rs +++ b/crates/idp-domain/src/principal.rs @@ -9,15 +9,38 @@ use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; -/// Sole human superadmin email across all estate control planes. +/// Primary Sovereign Root human superadmin email across all estate control planes. pub const SOLE_SUPERADMIN_EMAIL: &str = "ctodie@cerebral.work"; -/// Sole human superadmin GitHub login across all estate organizations. +/// Primary Sovereign Root human superadmin GitHub login across all estate organizations. pub const SOLE_SUPERADMIN_GITHUB: &str = "todie"; +/// Delegated Sovereign Root co-custodian email across estate control planes. +pub const DELEGATED_SOVEREIGN_ROOT_EMAIL: &str = "ahackley@cerebral.work"; + +/// Delegated Sovereign Root co-custodian GitHub login (lowercase for case-insensitive matching). +pub const DELEGATED_SOVEREIGN_ROOT_GITHUB: &str = "lordvoid"; + +/// Returns true if `email` is either the Primary Sovereign Root (`ctodie@cerebral.work`) +/// or the Delegated Sovereign Root (`ahackley@cerebral.work`). +pub fn is_sovereign_root_email(email: &str) -> bool { + let trimmed = email.trim(); + trimmed.eq_ignore_ascii_case(SOLE_SUPERADMIN_EMAIL) + || trimmed.eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_EMAIL) +} + +/// Returns true if `login` is either the Primary Sovereign Root (`todie`) +/// or the Delegated Sovereign Root (`lordvoid`). +pub fn is_sovereign_root_github(login: &str) -> bool { + let trimmed = login.trim(); + trimmed.eq_ignore_ascii_case(SOLE_SUPERADMIN_GITHUB) + || trimmed.eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_GITHUB) +} + /// Paths in `cerebral-work/identity` that Clockwork Elves are never permitted to modify. pub const PROHIBITED_SENSITIVE_PATHS: &[&str] = &[ "directory/roles.yaml", + "directory/bundles.yaml", "directory/policies.yaml", "directory/role-matrix.yaml", "terraform/org-admins/", @@ -39,15 +62,16 @@ pub enum Principal { /// Allowed scope identifiers (sorted set of groups, repos, or mesh tags). scopes: BTreeSet, }, - /// Break-glass operator superadmin (`ctodie@cerebral.work` / `todie` only). + /// Sovereign Root / Delegated Sovereign Root (`ctodie@cerebral.work` / `ahackley@cerebral.work` only). Superuser, } impl Principal { /// Resolves a human user record into a `Principal` tier. /// - /// Enforces the single-superadmin invariant: only `ctodie@cerebral.work` can hold `Superuser` - /// when `is_super_admin` is true; any other user claiming `is_super_admin` is rejected (`Denied`). + /// Enforces the sovereign-root invariant: only `ctodie@cerebral.work` (Primary Sovereign Root) + /// and `ahackley@cerebral.work` (Delegated Sovereign Root) can hold `Superuser` when + /// `is_super_admin` is true; any other user claiming `is_super_admin` is rejected (`Denied`). pub fn for_human( email: &str, suspended: bool, @@ -58,7 +82,7 @@ impl Principal { return Self::Denied; } if is_super_admin { - if email.eq_ignore_ascii_case(SOLE_SUPERADMIN_EMAIL) { + if is_sovereign_root_email(email) { return Self::Superuser; } return Self::Denied; @@ -70,6 +94,45 @@ impl Principal { } } + /// Resolves a human user record with an explicit `admin` tier string (`"super"`, `"delegated-sovereign"`, or `"delegated"`). + pub fn for_admin_tier( + email: &str, + suspended: bool, + admin_tier: Option<&str>, + scopes: BTreeSet, + ) -> Self { + if suspended { + return Self::Denied; + } + match admin_tier.map(str::trim).filter(|s| !s.is_empty()) { + Some("super") => { + if email.trim().eq_ignore_ascii_case(SOLE_SUPERADMIN_EMAIL) { + Self::Superuser + } else { + Self::Denied + } + } + Some("delegated-sovereign") => { + if email + .trim() + .eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_EMAIL) + { + Self::Superuser + } else { + Self::Denied + } + } + Some("delegated") | None => { + if scopes.is_empty() { + Self::Unscoped + } else { + Self::Scoped { scopes } + } + } + Some(_) => Self::Denied, + } + } + /// Returns true if the principal is permitted to access the requested scope. pub fn allows_scope(&self, scope: &str) -> bool { match self { @@ -187,7 +250,7 @@ mod tests { use super::*; #[test] - fn test_principal_ordering_and_sole_superadmin() { + fn test_principal_ordering_and_sovereign_roots() { let scopes = BTreeSet::from(["gcp-developers".to_string()]); let denied = Principal::Denied; let unscoped = Principal::Unscoped; @@ -200,15 +263,46 @@ mod tests { assert!(unscoped < scoped); assert!(scoped < superuser); - // Sole superadmin check + // Sovereign Root and Delegated Sovereign Root checks assert_eq!( Principal::for_human("ctodie@cerebral.work", false, true, BTreeSet::new()), Principal::Superuser ); assert_eq!( - Principal::for_human("ahackley@cerebral.work", false, true, scopes), + Principal::for_human("ahackley@cerebral.work", false, true, BTreeSet::new()), + Principal::Superuser + ); + assert_eq!( + Principal::for_human("intruder@cerebral.work", false, true, scopes.clone()), Principal::Denied ); + assert_eq!( + Principal::for_admin_tier( + "ahackley@cerebral.work", + false, + Some("delegated-sovereign"), + BTreeSet::new() + ), + Principal::Superuser + ); + assert_eq!( + Principal::for_admin_tier( + "ahackley@cerebral.work", + false, + Some("super"), + BTreeSet::new() + ), + Principal::Denied + ); + assert_eq!( + Principal::for_admin_tier( + "ctodie@cerebral.work", + false, + Some("super"), + BTreeSet::new() + ), + Principal::Superuser + ); } #[test] diff --git a/crates/idp-domain/src/reconciler.rs b/crates/idp-domain/src/reconciler.rs index 9b89d0a..d6c1bf8 100644 --- a/crates/idp-domain/src/reconciler.rs +++ b/crates/idp-domain/src/reconciler.rs @@ -17,6 +17,7 @@ //! matches the exact SHA-256 digest of the JSON-structured `{"serial": [...], "batch": [...]}` //! command list with throwaway passwords redacted to ``. +use crate::principal::{is_sovereign_root_email, is_sovereign_root_github}; use chrono::NaiveDate; use regex::Regex; use serde::{Deserialize, Serialize}; @@ -28,13 +29,13 @@ use std::sync::LazyLock; static PASSWORD_RE: LazyLock = LazyLock::new(|| Regex::new(r"\bpassword \S+").expect("valid password regex")); -/// Irrevocable Sovereign Root Google Workspace primary email address. +/// Irrevocable Primary Sovereign Root Google Workspace primary email address. pub const SOVEREIGN_ROOT_EMAIL: &str = "ctodie@cerebral.work"; -/// Irrevocable Sovereign Root GitHub login handle (lowercase). +/// Irrevocable Primary Sovereign Root GitHub login handle (lowercase). pub const SOVEREIGN_ROOT_GITHUB: &str = "todie"; -/// Irrevocable Sovereign Root organizational unit path. +/// Irrevocable Sovereign Root organizational unit path (`/Humans/Admins`). pub const SOVEREIGN_ROOT_ORG_UNIT: &str = "/Humans/Admins"; fn default_true() -> bool { @@ -399,9 +400,7 @@ pub fn plan_users( }; if h.org_unit != w.org_unit { - if email.eq_ignore_ascii_case(SOVEREIGN_ROOT_EMAIL) - && w.org_unit != SOVEREIGN_ROOT_ORG_UNIT - { + if is_sovereign_root_email(email) && w.org_unit != SOVEREIGN_ROOT_ORG_UNIT { plan.manual.push(format!( "SOVEREIGN ROOT PROTECTED {email} (refusing to move sovereign root out of {SOVEREIGN_ROOT_ORG_UNIT})" )); @@ -418,7 +417,7 @@ pub fn plan_users( plan.manual.push(format!( "NOT REINSTATED {email} (declared suspended: false, live is SUSPENDED — un-suspending is never automated; it is the offboarding-reversal path. Run `gam update user {email} suspended off` deliberately, or correct the row)" )); - } else if email.eq_ignore_ascii_case(SOVEREIGN_ROOT_EMAIL) { + } else if is_sovereign_root_email(email) { plan.manual.push(format!( "SOVEREIGN ROOT PROTECTED {email} (refusing to suspend sovereign root)" )); @@ -485,7 +484,10 @@ pub fn plan_admin( }; let want_role = effective_user_admin(w); let have_role = effective_live_admin(h); - if want_role == have_role { + if want_role == have_role + || (want_role == Some("delegated-sovereign") + && matches!(have_role, Some("delegated") | Some("super"))) + { continue; } match (want_role, have_role) { @@ -624,7 +626,7 @@ pub fn plan_groups( if held.contains_key(member) { continue; } - if member.eq_ignore_ascii_case(SOVEREIGN_ROOT_EMAIL) { + if is_sovereign_root_email(member) { plan.manual.push(format!( "SOVEREIGN ROOT PROTECTED {member} in {email} (refusing to remove sovereign root from group)" )); @@ -681,7 +683,7 @@ pub fn plan_licenses( .push(format!("gam user {user} add license {sku}")); } for (user, sku) in have_set.difference(want) { - if user.eq_ignore_ascii_case(SOVEREIGN_ROOT_EMAIL) { + if is_sovereign_root_email(user) { plan.manual.push(format!( "SOVEREIGN ROOT PROTECTED {user} (refusing to delete license {sku} from sovereign root)" )); @@ -731,7 +733,7 @@ pub fn plan_github( }; for login in h.difference(&w) { - if login.eq_ignore_ascii_case(SOVEREIGN_ROOT_GITHUB) { + if is_sovereign_root_github(login) { plan.manual.push(format!( "SOVEREIGN ROOT PROTECTED {login} in {org}{stake} (refusing to remove sovereign root from GitHub organization)" )); @@ -1034,30 +1036,40 @@ mod tests { let mut want_users = BTreeMap::new(); let mut have_users = BTreeMap::new(); - let mut u_root = sample_user("ctodie@cerebral.work"); - u_root.org_unit = "/Suspended-Offboarding".to_string(); - u_root.suspended = true; - let mut l_root = sample_live_user("ctodie@cerebral.work"); - l_root.org_unit = "/Humans/Admins".to_string(); - l_root.suspended = false; - want_users.insert(u_root.email.clone(), u_root); - have_users.insert(l_root.email.clone(), l_root.clone()); + for email in ["ctodie@cerebral.work", "ahackley@cerebral.work"] { + let mut u_root = sample_user(email); + u_root.org_unit = "/Suspended-Offboarding".to_string(); + u_root.suspended = true; + u_root.admin = Some(if email == "ctodie@cerebral.work" { + "super".to_string() + } else { + "delegated-sovereign".to_string() + }); + let mut l_root = sample_live_user(email); + l_root.org_unit = "/Humans/Admins".to_string(); + l_root.suspended = false; + l_root.admin = Some(if email == "ctodie@cerebral.work" { + "super".to_string() + } else { + "delegated".to_string() + }); + want_users.insert(u_root.email.clone(), u_root); + have_users.insert(l_root.email.clone(), l_root); + } - let user_plan = plan_users( - &want_users, - &have_users, - Some("ahackley@cerebral.work"), - "pw", - ); + let user_plan = plan_users(&want_users, &have_users, Some("bot@cerebral.work"), "pw"); assert!(user_plan.batch.is_empty()); - assert_eq!(user_plan.manual.len(), 2); + assert_eq!(user_plan.manual.len(), 4); assert!( user_plan .manual .iter() - .all(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ctodie@cerebral.work")) + .all(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ")) ); + let admin_plan = plan_admin(&want_users, &have_users, &BTreeMap::new()); + assert!(admin_plan.manual.is_empty()); + let today = NaiveDate::from_ymd_opt(2026, 10, 14).unwrap(); let mut want_groups = BTreeMap::new(); want_groups.insert( @@ -1084,7 +1096,10 @@ mod tests { settings: BTreeMap::new(), members: BTreeSet::new(), managers: BTreeSet::new(), - owners: BTreeSet::from(["ctodie@cerebral.work".to_string()]), + owners: BTreeSet::from([ + "ctodie@cerebral.work".to_string(), + "ahackley@cerebral.work".to_string(), + ]), }, ); let group_plan = plan_groups( @@ -1103,13 +1118,22 @@ mod tests { .iter() .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ctodie@cerebral.work")) ); + assert!( + group_plan + .manual + .iter() + .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ahackley@cerebral.work")) + ); let lic_plan = plan_licenses( &BTreeSet::new(), - Some(&BTreeSet::from([( - "ctodie@cerebral.work".to_string(), - "1010020020".to_string(), - )])), + Some(&BTreeSet::from([ + ("ctodie@cerebral.work".to_string(), "1010020020".to_string()), + ( + "ahackley@cerebral.work".to_string(), + "1010020020".to_string(), + ), + ])), ); assert!(lic_plan.batch.is_empty()); assert!( @@ -1118,18 +1142,24 @@ mod tests { .iter() .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ctodie@cerebral.work")) ); + assert!( + lic_plan + .manual + .iter() + .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED ahackley@cerebral.work")) + ); let want_gh = BTreeMap::from([("cerebral-work".to_string(), BTreeSet::new())]); let have_gh = BTreeMap::from([( "cerebral-work".to_string(), - BTreeSet::from(["todie".to_string()]), + BTreeSet::from(["todie".to_string(), "lordvoid".to_string()]), )]); let (gh_plan, _) = plan_github( &want_gh, &have_gh, - &BTreeSet::from(["todie".to_string()]), - &BTreeSet::from(["todie".to_string()]), - Some("lordvoid"), + &BTreeSet::from(["todie".to_string(), "lordvoid".to_string()]), + &BTreeSet::from(["todie".to_string(), "lordvoid".to_string()]), + Some("bot"), ); assert!(gh_plan.batch.is_empty()); assert!(gh_plan.gh_batch.is_empty()); @@ -1139,5 +1169,11 @@ mod tests { .iter() .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED todie in cerebral-work")) ); + assert!( + gh_plan + .manual + .iter() + .any(|m| m.starts_with("SOVEREIGN ROOT PROTECTED lordvoid in cerebral-work")) + ); } } diff --git a/crates/idp/src/detectors.rs b/crates/idp/src/detectors.rs index df9361f..e5a5070 100644 --- a/crates/idp/src/detectors.rs +++ b/crates/idp/src/detectors.rs @@ -893,23 +893,93 @@ pub fn evaluate_reflexd_admission( // role_matrix_live helpers // --------------------------------------------------------------------------- -/// Expands `directory/role-matrix.yaml` and `directory/` to compute the set of active user -/// emails expected to exist in Cloudflare (`super_administrators` ∪ `domain_administrators`). +/// Verifies that every `@cerebral.work` group referenced in `roles.yaml`, `bundles.yaml`, +/// or `role-matrix.yaml` exists in the live Google Workspace directory (`live_group_emails`). +/// +/// Fails closed if `live_group_emails` is empty (`Err(IdpError::Validation)`). +pub fn missing_live_role_groups( + repo: &Path, + live_group_emails: &BTreeSet, +) -> Result, IdpError> { + if live_group_emails.is_empty() { + return Err(IdpError::Validation( + "the directory returned no groups at all; refusing to call that a clean read" + .to_string(), + )); + } + let dir = repo.join("directory"); + let mut wanted = BTreeSet::new(); + for filename in ["role-matrix.yaml", "roles.yaml", "bundles.yaml"] { + let p = dir.join(filename); + if p.exists() { + let text = fs::read_to_string(&p)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + for g in crate::directory::matrix_groups(&doc) { + wanted.insert(g.to_lowercase()); + } + } + } + if wanted.is_empty() { + return Err(IdpError::Validation( + "role/bundle definitions named no groups at all".to_string(), + )); + } + let live_lower: BTreeSet = live_group_emails + .iter() + .map(|s| s.trim().to_lowercase()) + .filter(|s| !s.is_empty()) + .collect(); + if live_lower.is_empty() { + return Err(IdpError::Validation( + "the directory returned no groups at all; refusing to call that a clean read" + .to_string(), + )); + } + Ok(wanted.difference(&live_lower).cloned().collect()) +} + +/// Expands `directory/bundles.yaml` (or legacy `directory/role-matrix.yaml`) and `directory/` +/// to compute the set of active user emails expected to hold Cloudflare super/domain administrator access. pub fn expected_cloudflare_emails(repo: &Path) -> Result, IdpError> { let state = load_desired_state(repo)?; - let text = fs::read_to_string(repo.join("directory/role-matrix.yaml"))?; - let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; let mut group_emails = BTreeSet::new(); - if let Some(cf) = doc.get("cloudflare") { - for tier in ["super_administrators", "domain_administrators"] { - if let Some(seq) = cf - .get(tier) - .and_then(|t| t.get("groups")) - .and_then(|v| v.as_sequence()) - { - for g in seq { - if let Some(gs) = g.as_str() { - group_emails.insert(gs.to_string()); + let matrix_path = repo.join("directory/role-matrix.yaml"); + if matrix_path.exists() { + let text = fs::read_to_string(&matrix_path)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + if let Some(cf) = doc.get("cloudflare") { + for tier in ["super_administrators", "domain_administrators"] { + if let Some(seq) = cf + .get(tier) + .and_then(|t| t.get("groups")) + .and_then(|v| v.as_sequence()) + { + for g in seq { + if let Some(gs) = g.as_str() { + group_emails.insert(gs.to_string()); + } + } + } + } + } + } + let bundles_path = repo.join("directory/bundles.yaml"); + if group_emails.is_empty() && bundles_path.exists() { + let text = fs::read_to_string(&bundles_path)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + if let Some(bundles_map) = doc.get("bundles").and_then(|v| v.as_mapping()) { + for (_, bv) in bundles_map { + let is_cf_admin = bv + .get("cloudflare_access") + .and_then(|v| v.as_sequence()) + .is_some_and(|seq| seq.iter().any(|x| x.as_str() == Some("*"))); + if is_cf_admin + && let Some(ggs) = bv.get("google_groups").and_then(|v| v.as_sequence()) + { + for g in ggs { + if let Some(gs) = g.as_str() { + group_emails.insert(gs.to_string()); + } } } } @@ -918,22 +988,47 @@ pub fn expected_cloudflare_emails(repo: &Path) -> Result, IdpEr expand_active_group_members(&state, &group_emails) } -/// Expands `directory/role-matrix.yaml` and `directory/` to compute the set of active user -/// emails expected to hold `Role::Admin` in Tailscale. +/// Expands `directory/bundles.yaml` (or legacy `directory/role-matrix.yaml`) and `directory/` +/// to compute the set of active user emails expected to hold `Role::Admin` / `group:operators` in Tailscale. pub fn expected_tailscale_admins(repo: &Path) -> Result, IdpError> { let state = load_desired_state(repo)?; - let text = fs::read_to_string(repo.join("directory/role-matrix.yaml"))?; - let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; let mut group_emails = BTreeSet::new(); - if let Some(seq) = doc - .get("tailscale") - .and_then(|t| t.get("Role::Admin")) - .and_then(|r| r.get("groups")) - .and_then(|v| v.as_sequence()) - { - for g in seq { - if let Some(gs) = g.as_str() { - group_emails.insert(gs.to_string()); + let matrix_path = repo.join("directory/role-matrix.yaml"); + if matrix_path.exists() { + let text = fs::read_to_string(&matrix_path)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + if let Some(seq) = doc + .get("tailscale") + .and_then(|t| t.get("Role::Admin")) + .and_then(|r| r.get("groups")) + .and_then(|v| v.as_sequence()) + { + for g in seq { + if let Some(gs) = g.as_str() { + group_emails.insert(gs.to_string()); + } + } + } + } + let bundles_path = repo.join("directory/bundles.yaml"); + if group_emails.is_empty() && bundles_path.exists() { + let text = fs::read_to_string(&bundles_path)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + if let Some(bundles_map) = doc.get("bundles").and_then(|v| v.as_mapping()) { + for (_, bv) in bundles_map { + let is_ts_admin = bv + .get("tailscale") + .and_then(|v| v.as_sequence()) + .is_some_and(|seq| seq.iter().any(|x| x.as_str() == Some("group:operators"))); + if is_ts_admin + && let Some(ggs) = bv.get("google_groups").and_then(|v| v.as_sequence()) + { + for g in ggs { + if let Some(gs) = g.as_str() { + group_emails.insert(gs.to_string()); + } + } + } } } } diff --git a/crates/idp/src/directory.rs b/crates/idp/src/directory.rs index 3f51bdf..cd92ffe 100644 --- a/crates/idp/src/directory.rs +++ b/crates/idp/src/directory.rs @@ -7,8 +7,11 @@ //! `test_reconcile.py`, `test_identity_models.py`, and `scripts/lifecycle/_yamlio.py`. use crate::error::IdpError; -use crate::planes::{all_declared, unmanaged_declared}; -use crate::principal::{SOLE_SUPERADMIN_EMAIL, SOLE_SUPERADMIN_GITHUB}; +use crate::planes::{all_declared, disjoint_planes_check, unmanaged_declared}; +use crate::principal::{ + DELEGATED_SOVEREIGN_ROOT_EMAIL, DELEGATED_SOVEREIGN_ROOT_GITHUB, SOLE_SUPERADMIN_EMAIL, + SOLE_SUPERADMIN_GITHUB, is_sovereign_root_email, +}; use crate::registry::is_automation_login; use chrono::NaiveDate; use regex::Regex; @@ -290,7 +293,7 @@ pub fn load_desired_state(repo: &Path) -> Result { }) } -/// Recursively extracts every `@cerebral.work` group address referenced in `role-matrix.yaml`. +/// Recursively extracts every `@cerebral.work` group address referenced in a YAML document. pub fn matrix_groups(node: &serde_yaml::Value) -> BTreeSet { let mut out = BTreeSet::new(); match node { @@ -312,25 +315,48 @@ pub fn matrix_groups(node: &serde_yaml::Value) -> BTreeSet { out } -/// Returns any `@cerebral.work` group referenced in `directory/role-matrix.yaml` -/// that is missing from `all_declared(repo)` (`directory/groups/*.yaml` ∪ `terraform/groups/main.tf`). -pub fn missing_matrix_groups(repo: &Path) -> Result, IdpError> { - let matrix_path = repo.join("directory/role-matrix.yaml"); - let text = fs::read_to_string(&matrix_path)?; - let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; - let referenced = matrix_groups(&doc); +/// Returns any `@cerebral.work` group referenced in `directory/roles.yaml`, +/// `directory/bundles.yaml`, or `directory/role-matrix.yaml` (if present) that is missing from +/// `all_declared(repo)` (`directory/groups/*.yaml` ∪ `terraform/groups/main.tf`). +pub fn missing_role_groups(repo: &Path) -> Result, IdpError> { + let dir = repo.join("directory"); + let mut referenced = BTreeSet::new(); + let mut found_any = false; + for filename in ["role-matrix.yaml", "roles.yaml", "bundles.yaml"] { + let p = dir.join(filename); + if p.exists() { + found_any = true; + let text = fs::read_to_string(&p)?; + let doc: serde_yaml::Value = serde_yaml::from_str(&text)?; + referenced.extend(matrix_groups(&doc)); + } + } + if !found_any { + return Err(IdpError::Validation( + "missing directory/roles.yaml, directory/bundles.yaml, or directory/role-matrix.yaml" + .to_string(), + )); + } let declared = all_declared(repo)?; Ok(referenced.difference(&declared).cloned().collect()) } +/// Alias for [`missing_role_groups`] preserved for backwards compatibility. +pub fn missing_matrix_groups(repo: &Path) -> Result, IdpError> { + missing_role_groups(repo) +} + /// Validates `directory/` desired-state referential integrity and schema invariants: /// - Unique emails and unique `github_handle`s in `directory/users.yaml` /// - Every user's `org_unit` exists in `directory/orgunits.yaml` (or `"/"`) -/// - `admin` (if set) is in `{"super", "delegated"}` and `super` / `is_super_admin` is restricted to `ctodie@cerebral.work` +/// - `admin` (if set) is in `{"super", "delegated", "delegated-sovereign"}` +/// - `super` / `is_super_admin` is restricted to `ctodie@cerebral.work` and `delegated-sovereign` to `ahackley@cerebral.work` +/// - Sovereign roots (`ctodie@cerebral.work`, `ahackley@cerebral.work`) are never `suspended: true` and reside in `/Humans/Admins` when declared /// - Every `groups/.yaml` matches `email` prefix `@` /// - Every `unreconciled_members` entry has a non-empty `reason` and valid ISO `until` date /// - Every user in `directory/licenses.yaml` exists in `directory/users.yaml` /// - `directory/groups-unmanaged.yaml` has no overlap with declared groups +/// - GAM-managed groups (`directory/groups/*.yaml`) and Terraform foundation groups (`terraform/groups/main.tf`) are strictly disjoint /// /// Returns the number of declared users on success. pub fn validate_directory_schema(repo: &Path) -> Result { @@ -380,16 +406,37 @@ pub fn validate_directory_schema(repo: &Path) -> Result { if let Some(ref adm) = u.admin && adm != "super" && adm != "delegated" + && adm != "delegated-sovereign" { return Err(IdpError::Validation(format!( "{email}: invalid admin level '{adm}'" ))); } - if u.is_super_admin && email != SOLE_SUPERADMIN_EMAIL { + if u.is_super_admin && !is_sovereign_root_email(email) { + return Err(IdpError::Validation(format!( + "{email}: super admin is restricted exclusively to sovereign roots ({SOLE_SUPERADMIN_EMAIL} and {DELEGATED_SOVEREIGN_ROOT_EMAIL})" + ))); + } + if u.admin.as_deref() == Some("delegated-sovereign") + && !email.eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_EMAIL) + { return Err(IdpError::Validation(format!( - "{email}: super admin is restricted exclusively to {SOLE_SUPERADMIN_EMAIL}" + "{email}: delegated-sovereign admin is restricted exclusively to {DELEGATED_SOVEREIGN_ROOT_EMAIL}" ))); } + if is_sovereign_root_email(email) { + if u.suspended { + return Err(IdpError::Validation(format!( + "SOVEREIGN ROOT PROTECTED: {email} cannot be suspended in users.yaml" + ))); + } + if state.orgunits.contains("/Humans/Admins") && u.org_unit != "/Humans/Admins" { + return Err(IdpError::Validation(format!( + "SOVEREIGN ROOT PROTECTED: {email} must remain in /Humans/Admins, found {}", + u.org_unit + ))); + } + } } let groups_dir = dir.join("groups"); @@ -464,11 +511,18 @@ pub fn validate_directory_schema(repo: &Path) -> Result { } } - if dir.join("role-matrix.yaml").exists() { - let missing_groups = missing_matrix_groups(repo)?; + if repo.join("terraform/groups/main.tf").exists() { + disjoint_planes_check(repo)?; + } + + if dir.join("role-matrix.yaml").exists() + || dir.join("roles.yaml").exists() + || dir.join("bundles.yaml").exists() + { + let missing_groups = missing_role_groups(repo)?; if !missing_groups.is_empty() { return Err(IdpError::Validation(format!( - "role-matrix.yaml references groups not declared in GAM or foundation: {missing_groups:?}" + "role/bundle definitions reference groups not declared in GAM or foundation: {missing_groups:?}" ))); } } @@ -476,9 +530,9 @@ pub fn validate_directory_schema(repo: &Path) -> Result { Ok(state.users.len()) } -/// Validates `roles.yaml`, `bundles.yaml`, `policies.yaml`, and `role-matrix.yaml` invariants, -/// including the single-superadmin rule (`ctodie@cerebral.work` / `todie`) and Clockwork Elf -/// automation constraints. +/// Validates `roles.yaml`, `bundles.yaml`, `policies.yaml`, and optional `role-matrix.yaml` invariants, +/// including the sovereign root rules (`ctodie@cerebral.work` / `todie` and `ahackley@cerebral.work` / `LordVoid`) +/// and Clockwork Elf automation constraints. pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { let dir = repo.join("directory"); let roles_doc: serde_yaml::Value = @@ -487,8 +541,12 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { serde_yaml::from_str(&fs::read_to_string(dir.join("bundles.yaml"))?)?; let policies_doc: serde_yaml::Value = serde_yaml::from_str(&fs::read_to_string(dir.join("policies.yaml"))?)?; - let matrix_doc: serde_yaml::Value = - serde_yaml::from_str(&fs::read_to_string(dir.join("role-matrix.yaml"))?)?; + let matrix_path = dir.join("role-matrix.yaml"); + let matrix_doc: Option = if matrix_path.exists() { + Some(serde_yaml::from_str(&fs::read_to_string(&matrix_path)?)?) + } else { + None + }; let state = load_desired_state(repo)?; let declared_groups = all_declared(repo)?; @@ -519,9 +577,20 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { } } } else if let Some(map) = bundles_doc.get("bundles").and_then(|v| v.as_mapping()) { - for (bk, _) in map { - if let Some(s) = bk.as_str() { - bundle_ids.insert(s.to_string()); + for (bk, bv) in map { + if let Some(bid) = bk.as_str() { + bundle_ids.insert(bid.to_string()); + if let Some(ggs) = bv.get("google_groups").and_then(|v| v.as_sequence()) { + for g in ggs { + if let Some(gs) = g.as_str() + && !declared_groups.contains(gs) + { + return Err(IdpError::Validation(format!( + "bundle {bid} references undeclared google_group {gs}" + ))); + } + } + } } } } else { @@ -541,36 +610,13 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { if !role_ids.insert(rid.to_string()) { return Err(IdpError::Validation(format!("duplicate role id {rid}"))); } - if let Some(priv_str) = r.get("privacy").and_then(|v| v.as_str()) - && !["internal", "tenant", "external"].contains(&priv_str) - { - return Err(IdpError::Validation(format!( - "role {rid}: invalid privacy {priv_str}" - ))); - } - if let Some(ou_str) = r.get("ou").and_then(|v| v.as_str()) - && !valid_ous.contains(ou_str) - { - return Err(IdpError::Validation(format!( - "role {rid}: unknown ou {ou_str}" - ))); - } - if let Some(bs) = r.get("bundles").and_then(|v| v.as_sequence()) { - for b in bs { - if let Some(bs_str) = b.as_str() - && !bundle_ids.contains(bs_str) - { - return Err(IdpError::Validation(format!( - "role {rid} references unknown bundle {bs_str}" - ))); - } - } - } + validate_role_entry(rid, r, &valid_ous, &bundle_ids, &declared_groups)?; } } else if let Some(map) = roles_doc.get("roles").and_then(|v| v.as_mapping()) { - for (k, _) in map { - if let Some(s) = k.as_str() { - role_ids.insert(s.to_string()); + for (k, rv) in map { + if let Some(rid) = k.as_str() { + role_ids.insert(rid.to_string()); + validate_role_entry(rid, rv, &valid_ous, &bundle_ids, &declared_groups)?; } } } else { @@ -597,52 +643,25 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { } } - // 3. Check policies.yaml access_policies + // 3. Check policies.yaml (both `access_policies` sequence and `policies` mapping/sequence) if let Some(pols) = policies_doc .get("access_policies") .and_then(|v| v.as_sequence()) { for p in pols { let pid = p.get("id").and_then(|v| v.as_str()).unwrap_or("?"); - if let Some(b) = p.get("bundle").and_then(|v| v.as_str()) - && !bundle_ids.contains(b) - { - return Err(IdpError::Validation(format!( - "policy {pid}: unknown bundle {b}" - ))); - } - for field in ["auto_assign", "requestable_by"] { - if let Some(r_in) = p - .get(field) - .and_then(|v| v.get("role_in")) - .and_then(|v| v.as_sequence()) - { - for r in r_in { - if let Some(rs) = r.as_str() - && !role_ids.contains(rs) - { - return Err(IdpError::Validation(format!( - "policy {pid} ({field}): unknown role {rs}" - ))); - } - } - } - } - if let Some(apps) = p.get("approvers").and_then(|v| v.as_sequence()) { - for a in apps { - if let Some(u_in) = a.get("user_in").and_then(|v| v.as_sequence()) { - for u in u_in { - if let Some(us) = u.as_str() - && !state.users.contains_key(us) - { - return Err(IdpError::Validation(format!( - "policy {pid}: unknown approver {us}" - ))); - } - } - } - } - } + validate_policy_entry(pid, p, &bundle_ids, &role_ids, &state.users)?; + } + } + if let Some(pols_map) = policies_doc.get("policies").and_then(|v| v.as_mapping()) { + for (pk, pv) in pols_map { + let pid = pk.as_str().unwrap_or("?"); + validate_policy_entry(pid, pv, &bundle_ids, &role_ids, &state.users)?; + } + } else if let Some(pols_seq) = policies_doc.get("policies").and_then(|v| v.as_sequence()) { + for p in pols_seq { + let pid = p.get("id").and_then(|v| v.as_str()).unwrap_or("?"); + validate_policy_entry(pid, p, &bundle_ids, &role_ids, &state.users)?; } } @@ -663,28 +682,55 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { } } - // Check role-matrix.yaml break_glass_principals - if let Some(bg) = matrix_doc - .get("break_glass_principals") - .and_then(|v| v.as_sequence()) + // Check policies.yaml delegated_sovereign_root invariant if present + if let Some(del_root) = policies_doc + .get("invariants") + .and_then(|v| v.get("delegated_sovereign_root")) { - if bg.len() != 1 { + let email = del_root.get("email").and_then(|v| v.as_str()).unwrap_or(""); + let gh = del_root + .get("github_handle") + .and_then(|v| v.as_str()) + .unwrap_or(""); + if !email.eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_EMAIL) + || !gh.eq_ignore_ascii_case(DELEGATED_SOVEREIGN_ROOT_GITHUB) + { return Err(IdpError::Validation(format!( - "role-matrix.yaml break_glass_principals must have exactly 1 entry, found {}", - bg.len() + "policies.yaml delegated_sovereign_root must be {DELEGATED_SOVEREIGN_ROOT_EMAIL} ({DELEGATED_SOVEREIGN_ROOT_GITHUB})" ))); } - let email = bg[0].get("email").and_then(|v| v.as_str()).unwrap_or(""); - if email != SOLE_SUPERADMIN_EMAIL { - return Err(IdpError::Validation(format!( - "role-matrix.yaml break_glass_principals must be {SOLE_SUPERADMIN_EMAIL}, found {email}" - ))); + } + + // Check break_glass_principals in policies.yaml and/or role-matrix.yaml + for (doc_name, doc_opt) in [ + ("policies.yaml", Some(&policies_doc)), + ("role-matrix.yaml", matrix_doc.as_ref()), + ] { + if let Some(bg) = doc_opt + .and_then(|d| d.get("break_glass_principals")) + .and_then(|v| v.as_sequence()) + { + if bg.is_empty() || bg.len() > 2 { + return Err(IdpError::Validation(format!( + "{doc_name} break_glass_principals must have 1 or 2 sovereign root entries, found {}", + bg.len() + ))); + } + for entry in bg { + let email = entry.get("email").and_then(|v| v.as_str()).unwrap_or(""); + if !is_sovereign_root_email(email) { + return Err(IdpError::Validation(format!( + "{doc_name} break_glass_principals entry must be a sovereign root ({SOLE_SUPERADMIN_EMAIL} or {DELEGATED_SOVEREIGN_ROOT_EMAIL}), found {email}" + ))); + } + } } } - // Verify no Clockwork Elf appears in users.yaml + // Verify no Clockwork Elf appears in users.yaml outside /Service Accounts for (email, u) in &state.users { - if let Some(ref gh) = u.github_handle + if u.org_unit != "/Service Accounts" + && let Some(ref gh) = u.github_handle && is_automation_login(gh) { return Err(IdpError::Validation(format!( @@ -696,6 +742,118 @@ pub fn validate_identity_models(repo: &Path) -> Result<(), IdpError> { Ok(()) } +fn validate_role_entry( + rid: &str, + r: &serde_yaml::Value, + valid_ous: &BTreeSet, + bundle_ids: &BTreeSet, + declared_groups: &BTreeSet, +) -> Result<(), IdpError> { + if let Some(priv_str) = r.get("privacy").and_then(|v| v.as_str()) + && !["internal", "tenant", "external"].contains(&priv_str) + { + return Err(IdpError::Validation(format!( + "role {rid}: invalid privacy {priv_str}" + ))); + } + if let Some(ou_str) = r + .get("ou") + .or_else(|| r.get("org_unit")) + .and_then(|v| v.as_str()) + && !valid_ous.contains(ou_str) + { + return Err(IdpError::Validation(format!( + "role {rid}: unknown ou {ou_str}" + ))); + } + if let Some(bs) = r.get("bundles").and_then(|v| v.as_sequence()) { + for b in bs { + if let Some(bs_str) = b.as_str() + && !bundle_ids.contains(bs_str) + { + return Err(IdpError::Validation(format!( + "role {rid} references unknown bundle {bs_str}" + ))); + } + } + } + if let Some(gs) = r.get("groups").and_then(|v| v.as_sequence()) { + for g in gs { + if let Some(gs_str) = g.as_str() + && !declared_groups.contains(gs_str) + { + return Err(IdpError::Validation(format!( + "role {rid} references undeclared group {gs_str}" + ))); + } + } + } + Ok(()) +} + +fn validate_policy_entry( + pid: &str, + p: &serde_yaml::Value, + bundle_ids: &BTreeSet, + role_ids: &BTreeSet, + users: &BTreeMap, +) -> Result<(), IdpError> { + if let Some(b) = p.get("bundle").and_then(|v| v.as_str()) + && !bundle_ids.contains(b) + { + return Err(IdpError::Validation(format!( + "policy {pid}: unknown bundle {b}" + ))); + } + for field in ["auto_assign", "requestable_by"] { + if let Some(r_in) = p + .get(field) + .and_then(|v| v.get("role_in")) + .and_then(|v| v.as_sequence()) + { + for r in r_in { + if let Some(rs) = r.as_str() + && !role_ids.contains(rs) + { + return Err(IdpError::Validation(format!( + "policy {pid} ({field}): unknown role {rs}" + ))); + } + } + } + } + if let Some(apps_seq) = p.get("approvers").and_then(|v| v.as_sequence()) { + for a in apps_seq { + if let Some(u_in) = a.get("user_in").and_then(|v| v.as_sequence()) { + for u in u_in { + if let Some(us) = u.as_str() + && !users.contains_key(us) + { + return Err(IdpError::Validation(format!( + "policy {pid}: unknown approver {us}" + ))); + } + } + } + } + } else if let Some(u_in) = p + .get("approvers") + .and_then(|v| v.get("user_in")) + .and_then(|v| v.as_sequence()) + { + for u in u_in { + if let Some(us) = u.as_str() + && !users.contains_key(us) + { + return Err(IdpError::Validation(format!( + "policy {pid}: unknown approver {us}" + ))); + } + } + } + Ok(()) +} + /// Splits a YAML document into its leading comment/blank header and body. pub fn split_header(text: &str) -> (&str, &str) { let mut offset = 0; diff --git a/crates/idp/src/lib.rs b/crates/idp/src/lib.rs index 5903f97..0b2c162 100644 --- a/crates/idp/src/lib.rs +++ b/crates/idp/src/lib.rs @@ -42,30 +42,34 @@ pub use detectors::{ DeclaredAdmission, FORBIDDEN_APPPROJECT_KINDS, Grant, OIDC_PREFIX, Rbac, SubmissionPeer, WIDE_ROLES, admits_port, bound_groups, canonical_peer, describe_peer, evaluate_oidc_bindings, evaluate_reflexd_admission, evaluate_tenant_appprojects, expected_cloudflare_emails, - expected_tailscale_admins, load_declared_admission, oidc_grants, resolve_role, - submission_peers, wildcard_rules, + expected_tailscale_admins, load_declared_admission, missing_live_role_groups, oidc_grants, + resolve_role, submission_peers, wildcard_rules, }; pub use directory::{ DesiredState, GroupRecord, HeldException, LicenseRecord, OrgUnitRecord, UserRecord, hold_text, - load_desired_state, matrix_groups, missing_matrix_groups, split_header, unhold_text, - validate_directory_schema, validate_identity_models, + load_desired_state, matrix_groups, missing_matrix_groups, missing_role_groups, split_header, + unhold_text, validate_directory_schema, validate_identity_models, }; pub use error::IdpError; pub use findings::{FindingItem, Findings, FindingsPayload, part}; pub use hydra::{ClientAuth, OryHydraClient, OryHydraConfig, PrivateKeyJwtClaims}; -pub use lifecycle::{OnboardRequest, stage_offboard, stage_onboard}; +pub use lifecycle::{OnboardRequest, stage_offboard, stage_onboard, stage_onboard_for_role}; pub use manifest::{AppManifest, ConversionResponse, HookAttributes}; pub use planes::{ - LiveGroupMember, all_declared, foundation_declared, gam_declared, undeclared_groups_report, - unmanaged_declared, + LiveGroupMember, all_declared, disjoint_planes_check, foundation_declared, gam_declared, + undeclared_groups_report, unmanaged_declared, }; pub use presence::{ - Presence, SlackMemberInput, declared_handles, evaluate_presence, parse_slack_members, - src_declared, translate_github_members, + Presence, SlackMemberInput, collect_presence, declared_handles, evaluate_presence, + parse_cloudflare_access_presence, parse_gitbook_presence, parse_keycloak_presence, + parse_linear_presence, parse_slack_members, parse_tailscale_presence, src_cloudflare_access, + src_declared, src_gitbook, src_keycloak, src_linear, src_tailscale, translate_github_members, }; pub use principal::{ - CapabilityEnvelope, GroupDecision, PROHIBITED_SENSITIVE_PATHS, Principal, - SOLE_SUPERADMIN_EMAIL, SOLE_SUPERADMIN_GITHUB, SubjectMatterMesh, reconcile_group_decisions, + CapabilityEnvelope, DELEGATED_SOVEREIGN_ROOT_EMAIL, DELEGATED_SOVEREIGN_ROOT_GITHUB, + GroupDecision, PROHIBITED_SENSITIVE_PATHS, Principal, SOLE_SUPERADMIN_EMAIL, + SOLE_SUPERADMIN_GITHUB, SubjectMatterMesh, is_sovereign_root_email, is_sovereign_root_github, + reconcile_group_decisions, }; pub use reconcile::{ LiveDirectoryState, LiveGroup, LiveUser, ReconcilePlan, apply_refusal, held_members, diff --git a/crates/idp/src/lifecycle.rs b/crates/idp/src/lifecycle.rs index a9e625b..de8bab1 100644 --- a/crates/idp/src/lifecycle.rs +++ b/crates/idp/src/lifecycle.rs @@ -216,6 +216,147 @@ pub fn stage_onboard(repo: &Path, req: &OnboardRequest) -> Result, Ok(touched) } +/// Resolves `org_unit`, GAM-managed `groups`, `sku_id`, and `github_orgs` for `role_slug` from +/// `directory/roles.yaml` + `directory/bundles.yaml` and calls [`stage_onboard`]. +pub fn stage_onboard_for_role( + repo: &Path, + email: &str, + given_name: &str, + family_name: &str, + role_slug: &str, + github_handle: Option, + create: bool, +) -> Result, IdpError> { + let dir = repo.join("directory"); + let roles_text = fs::read_to_string(dir.join("roles.yaml"))?; + let roles_doc: serde_yaml::Value = serde_yaml::from_str(&roles_text)?; + + let role_val = if let Some(map) = roles_doc.get("roles").and_then(|v| v.as_mapping()) { + map.get(serde_yaml::Value::String(role_slug.to_string())) + .ok_or_else(|| { + IdpError::Validation(format!("unknown role {role_slug:?} in roles.yaml")) + })? + } else if let Some(seq) = roles_doc.get("roles").and_then(|v| v.as_sequence()) { + seq.iter() + .find(|r| r.get("id").and_then(|v| v.as_str()) == Some(role_slug)) + .ok_or_else(|| { + IdpError::Validation(format!("unknown role {role_slug:?} in roles.yaml")) + })? + } else { + return Err(IdpError::Validation( + "roles.yaml: missing roles".to_string(), + )); + }; + + let org_unit = role_val + .get("ou") + .or_else(|| role_val.get("org_unit")) + .and_then(|v| v.as_str()) + .ok_or_else(|| { + IdpError::Validation(format!( + "role {role_slug} missing ou/org_unit in roles.yaml" + )) + })? + .to_string(); + + let bundles_path = dir.join("bundles.yaml"); + let bundles_doc: Option = if bundles_path.exists() { + Some(serde_yaml::from_str(&fs::read_to_string(&bundles_path)?)?) + } else { + None + }; + + let lookup_bundle = |bid: &str| -> Option<&serde_yaml::Value> { + let doc = bundles_doc.as_ref()?; + if let Some(map) = doc.get("bundles").and_then(|v| v.as_mapping()) { + map.get(serde_yaml::Value::String(bid.to_string())) + } else if let Some(seq) = doc.get("bundles").and_then(|v| v.as_sequence()) { + seq.iter() + .find(|b| b.get("id").and_then(|v| v.as_str()) == Some(bid)) + } else { + None + } + }; + + let mut candidate_groups: Vec = Vec::new(); + let role_group = format!("role-{role_slug}@cerebral.work"); + candidate_groups.push(role_group); + + if let Some(gs) = role_val.get("groups").and_then(|v| v.as_sequence()) { + for g in gs { + if let Some(gs_str) = g.as_str() + && !candidate_groups.iter().any(|x| x == gs_str) + { + candidate_groups.push(gs_str.to_string()); + } + } + } + + let mut sku_id: Option = match role_val.get("license") { + Some(serde_yaml::Value::String(s)) if !s.is_empty() => Some(s.clone()), + Some(serde_yaml::Value::Number(n)) => Some(n.to_string()), + _ => None, + }; + + let mut github_orgs: Vec = Vec::new(); + + if let Some(bs) = role_val.get("bundles").and_then(|v| v.as_sequence()) { + for b in bs { + if let Some(bid) = b.as_str() + && let Some(bval) = lookup_bundle(bid) + { + if sku_id.is_none() { + sku_id = match bval.get("license") { + Some(serde_yaml::Value::String(s)) if !s.is_empty() => Some(s.clone()), + Some(serde_yaml::Value::Number(n)) => Some(n.to_string()), + _ => None, + }; + } + if let Some(ggs) = bval.get("google_groups").and_then(|v| v.as_sequence()) { + for g in ggs { + if let Some(gs_str) = g.as_str() + && !candidate_groups.iter().any(|x| x == gs_str) + { + candidate_groups.push(gs_str.to_string()); + } + } + } + if let Some(gh_map) = bval.get("github").and_then(|v| v.as_mapping()) { + for (ok, _) in gh_map { + if let Some(org_str) = ok.as_str() + && !github_orgs.iter().any(|x| x == org_str) + { + github_orgs.push(org_str.to_string()); + } + } + } + } + } + } + + // Filter candidate_groups to those that have a GAM-managed file in `directory/groups/.yaml` + let mut gam_groups = Vec::new(); + for g in candidate_groups { + let slug = g.strip_suffix("@cerebral.work").unwrap_or(&g); + if dir.join("groups").join(format!("{slug}.yaml")).exists() { + gam_groups.push(g); + } + } + + let req = OnboardRequest { + email: email.to_string(), + given_name: given_name.to_string(), + family_name: family_name.to_string(), + org_unit, + groups: gam_groups, + sku_id, + github_handle, + github_orgs, + create, + }; + stage_onboard(repo, &req) +} + /// Stages an offboarding change for `email`. /// /// - When `finalize == false` (T0): sets `suspended: true` and `org_unit: /Suspended-Offboarding` @@ -223,7 +364,7 @@ pub fn stage_onboard(repo: &Path, req: &OnboardRequest) -> Result, /// files (killing group-derived access at T0 per `scripts/lifecycle/offboard.py`). /// - When `finalize == true` (T+30d): removes `email` from `directory/licenses.yaml` as well as groups. pub fn stage_offboard(repo: &Path, email: &str, finalize: bool) -> Result, IdpError> { - if email.eq_ignore_ascii_case(idp_domain::reconciler::SOVEREIGN_ROOT_EMAIL) { + if idp_domain::principal::is_sovereign_root_email(email) { return Err(IdpError::Validation(format!( "SOVEREIGN ROOT PROTECTED: refusing to offboard {email}" ))); @@ -424,5 +565,7 @@ mod tests { let err = stage_offboard(root, "ctodie@cerebral.work", false).unwrap_err(); assert!(err.to_string().contains("SOVEREIGN ROOT PROTECTED")); + let err_del = stage_offboard(root, "ahackley@cerebral.work", false).unwrap_err(); + assert!(err_del.to_string().contains("SOVEREIGN ROOT PROTECTED")); } } diff --git a/crates/idp/src/planes.rs b/crates/idp/src/planes.rs index 3eb745f..b8fbea9 100644 --- a/crates/idp/src/planes.rs +++ b/crates/idp/src/planes.rs @@ -91,6 +91,19 @@ pub fn all_declared(repo: &Path) -> Result, IdpError> { Ok(all) } +/// Enforces the strict disjoint plane invariant (`gam_declared ∩ foundation_declared == ∅`). +pub fn disjoint_planes_check(repo: &Path) -> Result<(), IdpError> { + let gam = gam_declared(repo)?; + let foundation = foundation_declared(repo)?; + let overlap: Vec = gam.intersection(&foundation).cloned().collect(); + if !overlap.is_empty() { + return Err(IdpError::Validation(format!( + "groups declared on BOTH GAM (directory/groups/) and foundation (terraform/groups/main.tf) planes: {overlap:?}" + ))); + } + Ok(()) +} + /// Reads `directory/groups-unmanaged.yaml` (or the given path) and returns `{email: reason}` /// for entries with a non-empty `email` and non-whitespace `reason`. pub fn unmanaged_declared(path: &Path) -> Result, IdpError> { diff --git a/crates/idp/src/presence.rs b/crates/idp/src/presence.rs index 57acf0f..8cf9ca1 100644 --- a/crates/idp/src/presence.rs +++ b/crates/idp/src/presence.rs @@ -173,6 +173,351 @@ pub fn parse_slack_members(entries: &[SlackMemberInput]) -> Presence { } } +/// Parses a Keycloak Admin REST API `/admin/realms/{realm}/users` JSON array into a [`Presence`] snapshot. +pub fn parse_keycloak_presence( + realm: &str, + users_json: &serde_json::Value, +) -> Result { + let arr = users_json + .as_array() + .or_else(|| users_json.get("users").and_then(|v| v.as_array())) + .ok_or_else(|| IdpError::Validation("keycloak users JSON must be an array".to_string()))?; + let mut members = BTreeMap::new(); + for u in arr { + let email = u + .get("email") + .and_then(|v| v.as_str()) + .or_else(|| u.get("username").and_then(|v| v.as_str())) + .unwrap_or("") + .trim() + .to_lowercase(); + if email.is_empty() { + continue; + } + let enabled = u.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true); + let state = if enabled { "active" } else { "disabled" }; + members.insert(email, state.to_string()); + } + Ok(Presence { + name: format!("keycloak:{realm}"), + members, + error: None, + skipped: None, + keyed_by: "email".to_string(), + }) +} + +/// Reads Keycloak presence from `KEYCLOAK_USERS_JSON` (inline JSON or file path), or marks skipped when unconfigured. +pub fn src_keycloak(realm: &str) -> Presence { + read_json_env_presence( + &format!("keycloak:{realm}"), + "KEYCLOAK_USERS_JSON", + "not wired yet (KEYCLOAK_ADMIN_URL / KEYCLOAK_USERS_JSON unset)", + |val| parse_keycloak_presence(realm, val), + ) +} + +/// Parses a Tailscale `/api/v2/tailnet/{tailnet}/users` or `/devices` JSON payload into a [`Presence`] snapshot. +pub fn parse_tailscale_presence(payload: &serde_json::Value) -> Result { + let mut members = BTreeMap::new(); + if let Some(users) = payload + .get("users") + .and_then(|v| v.as_array()) + .or_else(|| payload.as_array()) + { + for u in users { + let login = u + .get("loginName") + .and_then(|v| v.as_str()) + .or_else(|| u.get("user").and_then(|v| v.as_str())) + .or_else(|| u.get("email").and_then(|v| v.as_str())) + .unwrap_or("") + .trim() + .to_lowercase(); + if login.is_empty() { + continue; + } + let status = u + .get("status") + .and_then(|v| v.as_str()) + .or_else(|| u.get("role").and_then(|v| v.as_str())) + .unwrap_or("active") + .to_lowercase(); + let state = if status == "suspended" { + "suspended".to_string() + } else { + status + }; + members.insert(login, state); + } + } else if let Some(devices) = payload.get("devices").and_then(|v| v.as_array()) { + for d in devices { + let user = d + .get("user") + .and_then(|v| v.as_str()) + .unwrap_or("") + .trim() + .to_lowercase(); + if !user.is_empty() { + members.insert(user, "active".to_string()); + } + } + } else { + return Err(IdpError::Validation( + "tailscale JSON must contain `users`, `devices`, or be a JSON array".to_string(), + )); + } + Ok(Presence { + name: "tailscale".to_string(), + members, + error: None, + skipped: None, + keyed_by: "email".to_string(), + }) +} + +/// Reads Tailscale presence from `TAILSCALE_USERS_JSON` (inline JSON or file path), or marks skipped when unconfigured. +pub fn src_tailscale() -> Presence { + read_json_env_presence( + "tailscale", + "TAILSCALE_USERS_JSON", + "not wired yet (TAILSCALE_API_TOKEN / TAILSCALE_USERS_JSON unset)", + parse_tailscale_presence, + ) +} + +/// Parses a Linear GraphQL `{ users { nodes { email active admin guest } } }` or array payload into a [`Presence`] snapshot. +pub fn parse_linear_presence(payload: &serde_json::Value) -> Result { + let nodes = payload + .pointer("/data/users/nodes") + .and_then(|v| v.as_array()) + .or_else(|| payload.pointer("/users/nodes").and_then(|v| v.as_array())) + .or_else(|| payload.get("users").and_then(|v| v.as_array())) + .or_else(|| payload.as_array()) + .ok_or_else(|| { + IdpError::Validation("linear JSON must contain user nodes or be an array".to_string()) + })?; + let mut members = BTreeMap::new(); + for u in nodes { + let email = u + .get("email") + .and_then(|v| v.as_str()) + .unwrap_or("") + .trim() + .to_lowercase(); + if email.is_empty() { + continue; + } + let active = u.get("active").and_then(|v| v.as_bool()).unwrap_or(true); + let admin = u.get("admin").and_then(|v| v.as_bool()).unwrap_or(false); + let guest = u.get("guest").and_then(|v| v.as_bool()).unwrap_or(false); + let state = if !active { + "suspended" + } else if admin { + "admin" + } else if guest { + "guest" + } else { + "member" + }; + members.insert(email, state.to_string()); + } + Ok(Presence { + name: "linear".to_string(), + members, + error: None, + skipped: None, + keyed_by: "email".to_string(), + }) +} + +/// Reads Linear presence from `LINEAR_USERS_JSON` (inline JSON or file path), or marks skipped when unconfigured. +pub fn src_linear() -> Presence { + read_json_env_presence( + "linear", + "LINEAR_USERS_JSON", + "not wired yet (LINEAR_API_KEY / LINEAR_USERS_JSON unset)", + parse_linear_presence, + ) +} + +/// Parses a Cloudflare Zero Trust Access `/accounts/{id}/access/users` JSON payload into a [`Presence`] snapshot. +pub fn parse_cloudflare_access_presence(payload: &serde_json::Value) -> Result { + let arr = payload + .get("result") + .and_then(|v| v.as_array()) + .or_else(|| payload.get("users").and_then(|v| v.as_array())) + .or_else(|| payload.as_array()) + .ok_or_else(|| { + IdpError::Validation( + "cloudflare-access JSON must contain `result`, `users`, or be an array".to_string(), + ) + })?; + let mut members = BTreeMap::new(); + for u in arr { + let email = u + .get("email") + .and_then(|v| v.as_str()) + .unwrap_or("") + .trim() + .to_lowercase(); + if email.is_empty() { + continue; + } + let seat = u + .get("access_seat") + .and_then(|v| v.as_bool()) + .unwrap_or(true); + let state = if seat { "active" } else { "inactive" }; + members.insert(email, state.to_string()); + } + Ok(Presence { + name: "cloudflare-access".to_string(), + members, + error: None, + skipped: None, + keyed_by: "email".to_string(), + }) +} + +/// Reads Cloudflare Access presence from `CLOUDFLARE_ACCESS_USERS_JSON` (inline JSON or file path), or marks skipped when unconfigured. +pub fn src_cloudflare_access() -> Presence { + read_json_env_presence( + "cloudflare-access", + "CLOUDFLARE_ACCESS_USERS_JSON", + "not wired yet (CLOUDFLARE_API_TOKEN / CLOUDFLARE_ACCESS_USERS_JSON unset)", + parse_cloudflare_access_presence, + ) +} + +/// Parses a GitBook `/v1/orgs/{org}/members` JSON payload into a [`Presence`] snapshot. +pub fn parse_gitbook_presence(payload: &serde_json::Value) -> Result { + let arr = payload + .get("items") + .and_then(|v| v.as_array()) + .or_else(|| payload.get("members").and_then(|v| v.as_array())) + .or_else(|| payload.as_array()) + .ok_or_else(|| { + IdpError::Validation( + "gitbook JSON must contain `items`, `members`, or be an array".to_string(), + ) + })?; + let mut members = BTreeMap::new(); + for m in arr { + let user_obj = m.get("user").unwrap_or(m); + let email = user_obj + .get("email") + .and_then(|v| v.as_str()) + .or_else(|| m.get("email").and_then(|v| v.as_str())) + .unwrap_or("") + .trim() + .to_lowercase(); + if email.is_empty() { + continue; + } + let role = m + .get("role") + .and_then(|v| v.as_str()) + .unwrap_or("member") + .to_lowercase(); + members.insert(email, role); + } + Ok(Presence { + name: "gitbook".to_string(), + members, + error: None, + skipped: None, + keyed_by: "email".to_string(), + }) +} + +/// Reads GitBook presence from `GITBOOK_MEMBERS_JSON` (inline JSON or file path), or marks skipped when unconfigured. +pub fn src_gitbook() -> Presence { + read_json_env_presence( + "gitbook", + "GITBOOK_MEMBERS_JSON", + "not wired yet (GITBOOK_API_TOKEN / GITBOOK_MEMBERS_JSON unset)", + parse_gitbook_presence, + ) +} + +fn read_json_env_presence(name: &str, env_var: &str, skip_msg: &str, parser: F) -> Presence +where + F: FnOnce(&serde_json::Value) -> Result, +{ + let raw = match std::env::var(env_var) { + Ok(v) if !v.trim().is_empty() => v, + _ => { + return Presence { + name: name.to_string(), + members: BTreeMap::new(), + error: None, + skipped: Some(skip_msg.to_string()), + keyed_by: "email".to_string(), + }; + } + }; + let text = if Path::new(raw.trim()).exists() { + match fs::read_to_string(raw.trim()) { + Ok(t) => t, + Err(e) => { + return Presence { + name: name.to_string(), + members: BTreeMap::new(), + error: Some(e.to_string()), + skipped: None, + keyed_by: "email".to_string(), + }; + } + } + } else { + raw + }; + match serde_json::from_str::(&text) + .and_then(|v| parser(&v).map_err(serde::de::Error::custom)) + { + Ok(p) => p, + Err(e) => Presence { + name: name.to_string(), + members: BTreeMap::new(), + error: Some(e.to_string()), + skipped: None, + keyed_by: "email".to_string(), + }, + } +} + +/// Collects presence snapshots across declared `users.yaml` and all configured/stubbed planes, +/// optionally filtered to a single plane name (`keycloak`, `tailscale`, `linear`, `cloudflare-access`, `gitbook`). +pub fn collect_presence( + repo: &Path, + plane_filter: Option<&str>, +) -> Result, IdpError> { + let mut results = vec![src_declared(repo)?]; + let want = |name: &str| -> bool { + match plane_filter { + None => true, + Some(f) => f == name || name.starts_with(&format!("{f}:")), + } + }; + if want("keycloak") { + results.push(src_keycloak("cerebral")); + } + if want("tailscale") { + results.push(src_tailscale()); + } + if want("linear") { + results.push(src_linear()); + } + if want("cloudflare-access") { + results.push(src_cloudflare_access()); + } + if want("gitbook") { + results.push(src_gitbook()); + } + Ok(results) +} + /// Evaluates cross-system [`Presence`] snapshots, producing the human report lines, /// structured [`Findings`], and exit code (`0` = clean, `1` = source error, `2` = findings). pub fn evaluate_presence(results: &[Presence]) -> (i32, Vec, Findings) { @@ -608,4 +953,78 @@ mod tests { assert!(f.items.iter().any(|i| i.kind == "leftover")); assert!(f.items.iter().any(|i| i.kind == "unclaimed-github")); } + + #[test] + fn test_parse_five_planes_presence() { + let kc_val = serde_json::json!([ + {"email": "ctodie@cerebral.work", "enabled": true}, + {"email": "gone@cerebral.work", "enabled": false} + ]); + let kc = parse_keycloak_presence("cerebral", &kc_val).unwrap(); + assert_eq!(kc.name, "keycloak:cerebral"); + assert_eq!( + kc.members.get("ctodie@cerebral.work").map(|s| s.as_str()), + Some("active") + ); + assert_eq!( + kc.members.get("gone@cerebral.work").map(|s| s.as_str()), + Some("disabled") + ); + + let ts_val = serde_json::json!({ + "users": [ + {"loginName": "ctodie@cerebral.work", "status": "active"}, + {"loginName": "ahackley@cerebral.work", "status": "admin"} + ] + }); + let ts = parse_tailscale_presence(&ts_val).unwrap(); + assert_eq!(ts.name, "tailscale"); + assert_eq!( + ts.members.get("ahackley@cerebral.work").map(|s| s.as_str()), + Some("admin") + ); + + let lin_val = serde_json::json!({ + "data": { + "users": { + "nodes": [ + {"email": "ctodie@cerebral.work", "active": true, "admin": true}, + {"email": "gone@cerebral.work", "active": false} + ] + } + } + }); + let lin = parse_linear_presence(&lin_val).unwrap(); + assert_eq!(lin.name, "linear"); + assert_eq!( + lin.members.get("ctodie@cerebral.work").map(|s| s.as_str()), + Some("admin") + ); + assert_eq!( + lin.members.get("gone@cerebral.work").map(|s| s.as_str()), + Some("suspended") + ); + + let cf_val = serde_json::json!({ + "result": [ + {"email": "ctodie@cerebral.work", "access_seat": true}, + {"email": "ahackley@cerebral.work", "access_seat": true} + ] + }); + let cf = parse_cloudflare_access_presence(&cf_val).unwrap(); + assert_eq!(cf.name, "cloudflare-access"); + assert_eq!(cf.members.len(), 2); + + let gb_val = serde_json::json!({ + "items": [ + {"user": {"email": "ctodie@cerebral.work"}, "role": "admin"} + ] + }); + let gb = parse_gitbook_presence(&gb_val).unwrap(); + assert_eq!(gb.name, "gitbook"); + assert_eq!( + gb.members.get("ctodie@cerebral.work").map(|s| s.as_str()), + Some("admin") + ); + } } diff --git a/crates/idp/src/registry.rs b/crates/idp/src/registry.rs index 324781b..66bd4b2 100644 --- a/crates/idp/src/registry.rs +++ b/crates/idp/src/registry.rs @@ -139,7 +139,7 @@ pub const CONCLAVE_ELVES: &[ElfPersona] = &[ }, ]; -/// Extended estate Clockwork Elves (22 total: 16 core Conclave + 6 platform/memory/auth elves). +/// All 22 canonical estate Clockwork Elves (16 core Conclave + 6 runtime/compiler/verification elves). pub const ALL_ESTATE_ELVES: &[ElfPersona] = &[ ElfPersona { id: "sindri", @@ -232,6 +232,48 @@ pub const ALL_ESTATE_ELVES: &[ElfPersona] = &[ role: "traffic gate", desc: "Accept-and-hold wake gateway and TCP ingress management", }, + ElfPersona { + id: "kvasir", + name: "Kvasir", + repo: "xtool", + role: "toolchain / build synthesis", + desc: "xwork/xtool build orchestration, hermetic compilation, and lint gates", + }, + ElfPersona { + id: "alvis", + name: "Alvis", + repo: "idp", + role: "type & schema artisan", + desc: "Zero-I/O algebraic domain modeling, identity invariants, and schema validation", + }, + ElfPersona { + id: "dvalin", + name: "Dvalin", + repo: "cas", + role: "runic storage & CAS", + desc: "Content-addressable storage, Merkle tree integrity, and delta snapshots", + }, + ElfPersona { + id: "fjalar", + name: "Fjalar", + repo: "watch", + role: "alerting & watchtower", + desc: "Proactive anomaly detection, duty clock alerting, and watchtower probes", + }, + ElfPersona { + id: "eikthyrnir", + name: "Eikthyrnir", + repo: "stream", + role: "telemetry & event fanout", + desc: "High-throughput telemetry routing, metric aggregation, and stream fanout", + }, + ElfPersona { + id: "syn", + name: "Syn", + repo: "gate", + role: "admission denial guard", + desc: "Fail-closed admission control, boundary defense, and policy refusal", + }, ElfPersona { id: "forseti", name: "Forseti", @@ -253,62 +295,24 @@ pub const ALL_ESTATE_ELVES: &[ElfPersona] = &[ role: "kernel security", desc: "Linux Landlock LSM, seccomp filters, and kernel link primitives", }, - ElfPersona { - id: "njord", - name: "Njord", - repo: "ch", - role: "cache store", - desc: "Distributed artifact cache and CAS storage broker", - }, - ElfPersona { - id: "norns", - name: "Norns", - repo: "mem", - role: "memory continuity", - desc: "Long-term observation graph and session handoff weaver", - }, - ElfPersona { - id: "sol", - name: "Sol", - repo: "search", - role: "index & retrieval", - desc: "Hybrid lexical/vector search and corpus indexing", - }, - ElfPersona { - id: "vidar", - name: "Vidar", - repo: "auth", - role: "identity & attestation", - desc: "Identity reconciliation, token brokering, and attestation verification", - }, - ElfPersona { - id: "ratatoskr", - name: "Ratatoskr", - repo: "bus", - role: "mesh courier", - desc: "Inter-agent message routing and event transport", - }, - ElfPersona { - id: "tyr", - name: "Tyr", - repo: "gate", - role: "policy enforcement", - desc: "Capability envelope enforcement and admission control", - }, ]; -/// Looks up an elf persona by id across all 22 estate elves. +/// Looks up an elf persona by id or GitHub handle across all 22 estate elves. pub fn find_elf(id: &str) -> Option<&'static ElfPersona> { let needle = id.trim().to_ascii_lowercase(); let needle = needle.strip_suffix("-bot[bot]").unwrap_or(&needle); let needle = needle.strip_suffix("-bot").unwrap_or(needle); + let needle = needle.strip_suffix("-unsigned").unwrap_or(needle); ALL_ESTATE_ELVES.iter().find(|e| e.id == needle) } /// Returns true if the given GitHub login or actor handle belongs to a registered Clockwork Elf or runner bot. pub fn is_automation_login(login: &str) -> bool { let lower = login.trim().to_ascii_lowercase(); - if lower == "runner-bot" || lower == "runner-bot[bot]" { + if matches!( + lower.as_str(), + "runner" | "runner-bot" | "runner-bot[bot]" | "unsigned-runner" + ) { return true; } find_elf(&lower).is_some() @@ -352,6 +356,10 @@ impl KeyStore { /// Returns the path to the PEM private key for the given bot identifier. pub fn key_path(&self, bot_id: &str) -> PathBuf { + let candidate_unsigned = self.base_dir.join(format!("unsigned-{bot_id}-bot.pem")); + if candidate_unsigned.exists() { + return candidate_unsigned; + } let candidate_bot = self.base_dir.join(format!("{bot_id}-bot.pem")); if candidate_bot.exists() { return candidate_bot; @@ -359,6 +367,30 @@ impl KeyStore { self.base_dir.join(format!("{bot_id}.pem")) } + /// Creates canonical symlinks for bot keys and metadata if not already present. + pub fn link_canonical(&self, short_name: &str, app_name: &str) -> Result<(), IdpError> { + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + let target_pem = format!("{app_name}.pem"); + let target_json = format!("{app_name}.json"); + + let link_bot_pem = self.base_dir.join(format!("{short_name}-bot.pem")); + let link_pem = self.base_dir.join(format!("{short_name}.pem")); + let link_json = self.base_dir.join(format!("{short_name}.json")); + + let _ = fs::remove_file(&link_bot_pem); + let _ = symlink(&target_pem, &link_bot_pem); + + let _ = fs::remove_file(&link_pem); + let _ = symlink(&target_pem, &link_pem); + + let _ = fs::remove_file(&link_json); + let _ = symlink(&target_json, &link_json); + } + Ok(()) + } + /// Checks if a private key exists for the given bot identifier. pub fn has_key(&self, bot_id: &str) -> bool { self.key_path(bot_id).exists()