//! Auth profile/secret revalidation with plan-time snapshots: matching //! snapshot applies; config drift, secret rotation/revocation and missing //! snapshots conflict with zero mutation. use super::*; use crank_core::{ ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, Secret, SecretId, SecretKind, SecretStatus, }; use crank_registry::MASTER_KEY_CIPHER_CONTRACT; use crank_registry::{ CreateSecretRequest, MasterKeyIdentityCandidate, PostgresRegistry, SaveAuthProfileRequest, }; use time::format_description::well_known::Rfc3339; fn ts() -> OffsetDateTime { OffsetDateTime::parse("2026-03-25T12:00:00Z", &Rfc3339).unwrap() } /// Creates a master key epoch, one active secret and an ApiKeyHeader profile /// for it; returns the secret id. async fn create_auth_fixture(registry: &PostgresRegistry, workspace_id: &WorkspaceId) -> SecretId { registry .verify_or_register_master_key_identity(MasterKeyIdentityCandidate { epoch: 1, fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", cipher_contract: MASTER_KEY_CIPHER_CONTRACT, observed_at: &ts(), }) .await .unwrap(); let secret_id = SecretId::new("sec_apply"); let secret = Secret { id: secret_id.clone(), workspace_id: workspace_id.clone(), name: "Apply secret".to_owned(), kind: SecretKind::Token, status: SecretStatus::Active, current_version: 1, created_at: ts(), updated_at: ts(), last_used_at: None, }; registry .create_secret(CreateSecretRequest { secret: &secret, ciphertext: "ciphertext", key_version: "v1", master_key_epoch: 1, created_by: None, }) .await .unwrap(); let profile = AuthProfile { id: "auth_apply".into(), workspace_id: workspace_id.clone(), name: "Apply key".to_owned(), kind: AuthKind::ApiKeyHeader, config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig { header_name: "X-Apply-Key".to_owned(), secret_id: secret_id.clone(), }), created_at: ts(), updated_at: ts(), }; registry .save_auth_profile(SaveAuthProfileRequest { workspace_id, profile: &profile, }) .await .unwrap(); secret_id } fn auth_operation(id: &str) -> RegistryOperation { let mut operation = plan_operation(id); operation.execution_config.auth_profile_ref = Some("auth_apply".into()); operation } /// The plan-time snapshot an Admin CreatePlan captures for this profile + /// secret (metadata only, never credential bytes). fn capture_snapshot(profile: &AuthProfile, secret: &crank_core::Secret) -> Value { json!({ "profile_id": profile.id.as_str(), "name": profile.name, "kind": profile.kind, "config": profile.config, "updated_at": profile.updated_at.format(&Rfc3339).unwrap(), "secrets": [{ "id": secret.id.as_str(), "status": secret.status, "current_version": secret.current_version, "updated_at": secret.updated_at.format(&Rfc3339).unwrap() }] }) } fn auth_plan_payload( plan_id: &str, job_id: &str, fingerprint: &Value, snapshot: Option, ) -> Value { let operation = auth_operation("op_apply_auth"); let mut candidate = json!({ "key": "auth", "name": operation.name, "state": "actionable", "decision": { "action": "create" }, "operation": operation }); if let Some(snapshot) = snapshot { candidate["auth_snapshot"] = snapshot; } json!({ "schema_version": "import-plan-v1", "plan_reference": plan_id, "job_id": job_id, "fingerprint": fingerprint, "source": { "source_id": SOURCE_ID, "digest": source_ref() }, "dependencies": [], "selection": { "mode": "full", "all": ["auth"], "selected": ["auth"], "excluded": [] }, "counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 }, "candidates": [candidate] }) } async fn auth_base( database: &TestDatabase, workspace_tag: &str, ) -> ( PostgresRegistry, PgPool, WorkspaceId, ImportJobId, Value, Value, ) { let registry = database.registry().await; let raw_pool = database.raw_pool().await; let now = OffsetDateTime::now_utc(); let ws = create_workspace(®istry, workspace_tag).await; let job = create_pending_openapi_job( ®istry, &ws, &format!("job_apply_auth_{workspace_tag}"), now, now + Duration::hours(1), ) .await; activate_source(&raw_pool, &ws, now).await; let secret_id = create_auth_fixture(®istry, &ws).await; let profile = registry .get_auth_profile(&ws, &crank_core::AuthProfileId::new("auth_apply")) .await .unwrap() .unwrap(); let secret = registry .get_secret(&ws, &secret_id) .await .unwrap() .unwrap() .secret; let fp = fingerprint(); ( registry, raw_pool, ws, job, fp, capture_snapshot(&profile, &secret), ) } #[tokio::test] async fn apply_accepts_matching_auth_snapshot() { let database = TestDatabase::new().await; let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_ok").await; let payload = auth_plan_payload("plan_auth_ok", job.as_str(), &fp, Some(snapshot)); let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_ok", &fp, payload).await; let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap(); let request = ApplyImportPlanRequest { workspace_id: &ws, plan_id: &plan, plan_digest: &digest, idempotency_key: "idem_auth_ok", verified_fingerprint: &fp, applied_at: &applied_at, }; let result = registry.apply_import_plan(&request).await.unwrap(); assert!(!result.replayed); assert_eq!(result.report.status, ImportPlanApplyStatus::Applied); assert_eq!(result.report.counts.created, 1); let summary = registry .get_operation_summary(&ws, &OperationId::new("op_apply_auth")) .await .unwrap() .unwrap(); assert_eq!(summary.current_draft_version, 1); let stored = result.report; drop(stored); database.cleanup().await; } #[tokio::test] async fn apply_rejects_auth_profile_config_drift() { let database = TestDatabase::new().await; let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_drift").await; let payload = auth_plan_payload("plan_auth_drift", job.as_str(), &fp, Some(snapshot)); let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_drift", &fp, payload).await; // After the plan was captured, the profile's config drifted. let drifted = AuthProfile { name: "Drifted key".to_owned(), config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig { header_name: "X-Other-Key".to_owned(), secret_id: SecretId::new("sec_apply"), }), updated_at: OffsetDateTime::now_utc(), ..capture_profile_fixture(®istry, &ws).await }; registry .save_auth_profile(SaveAuthProfileRequest { workspace_id: &ws, profile: &drifted, }) .await .unwrap(); let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap(); let request = ApplyImportPlanRequest { workspace_id: &ws, plan_id: &plan, plan_digest: &digest, idempotency_key: "idem_auth_drift", verified_fingerprint: &fp, applied_at: &applied_at, }; assert!( matches!( registry .apply_import_plan(&request) .await, Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id }) if auth_profile_id == "auth_apply" ), "a config drift must be a typed re-preview conflict" ); assert!( registry .get_operation_summary(&ws, &OperationId::new("op_apply_auth")) .await .unwrap() .is_none(), "zero mutation on auth drift" ); database.cleanup().await; } async fn capture_profile_fixture(registry: &PostgresRegistry, ws: &WorkspaceId) -> AuthProfile { registry .get_auth_profile(ws, &crank_core::AuthProfileId::new("auth_apply")) .await .unwrap() .unwrap() } #[tokio::test] async fn apply_rejects_secret_rotation_or_revocation() { let database = TestDatabase::new().await; let (registry, raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_rotate").await; let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap(); // Rotated secret: same id, new current version. let payload = auth_plan_payload("plan_auth_rot", job.as_str(), &fp, Some(snapshot.clone())); let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_rot", &fp, payload).await; let now = OffsetDateTime::now_utc(); registry .rotate_secret(crank_registry::RotateSecretRequest { workspace_id: &ws, secret_id: &SecretId::new("sec_apply"), ciphertext: "new-ciphertext", key_version: "v2", master_key_epoch: 1, created_at: &now, updated_at: &now, created_by: None, }) .await .unwrap(); assert!( matches!( registry .apply_import_plan(&ApplyImportPlanRequest { workspace_id: &ws, plan_id: &plan, plan_digest: &digest, idempotency_key: "idem_auth_rot", verified_fingerprint: &fp, applied_at: &applied_at, }) .await, Err(RegistryError::ImportPlanAuthUnavailable { .. }) ), "a rotated secret must be a typed re-preview conflict" ); // Revoked/disabled secret: same id, changed status. let payload = auth_plan_payload("plan_auth_dis", job.as_str(), &fp, Some(snapshot)); let (dis_plan, dis_digest) = store_plan(®istry, &ws, &job, "plan_auth_dis", &fp, payload).await; sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2") .bind(ws.as_str()) .bind("sec_apply") .execute(&raw_pool) .await .unwrap(); assert!( matches!( registry .apply_import_plan(&ApplyImportPlanRequest { workspace_id: &ws, plan_id: &dis_plan, plan_digest: &dis_digest, idempotency_key: "idem_auth_dis", verified_fingerprint: &fp, applied_at: &applied_at, }) .await, Err(RegistryError::ImportPlanAuthUnavailable { .. }) ), "a revoked secret must be a typed re-preview conflict" ); assert!( registry .get_operation_summary(&ws, &OperationId::new("op_apply_auth")) .await .unwrap() .is_none(), "zero mutation on secret drift" ); database.cleanup().await; } #[tokio::test] async fn apply_rejects_auth_candidates_missing_or_mismatched_snapshot() { let database = TestDatabase::new().await; let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_missing").await; // Actionable + auth ref but NO snapshot -> unavailable (re-preview). let payload = auth_plan_payload("plan_auth_mis", job.as_str(), &fp, None); let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_mis", &fp, payload).await; let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap(); assert!( matches!( registry .apply_import_plan(&ApplyImportPlanRequest { workspace_id: &ws, plan_id: &plan, plan_digest: &digest, idempotency_key: "idem_auth_mis", verified_fingerprint: &fp, applied_at: &applied_at, }) .await, Err(RegistryError::ImportPlanAuthUnavailable { .. }) ), "an auth-bound candidate without a snapshot must re-preview" ); // Snapshot on a candidate WITHOUT an auth ref -> corrupt plan. let unauth_operation = plan_operation("op_apply_noauth"); let payload = json!({ "schema_version": "import-plan-v1", "plan_reference": "plan_auth_corrupt", "job_id": job.as_str(), "fingerprint": fp, "source": { "source_id": SOURCE_ID, "digest": source_ref() }, "dependencies": [], "selection": { "mode": "full", "all": ["na"], "selected": ["na"], "excluded": [] }, "counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 }, "candidates": [{ "key": "na", "name": unauth_operation.name, "state": "actionable", "decision": { "action": "create" }, "operation": unauth_operation, "auth_snapshot": snapshot }] }); let (c_plan, c_digest) = store_plan(®istry, &ws, &job, "plan_auth_corrupt", &fp, payload).await; assert!( matches!( registry .apply_import_plan(&ApplyImportPlanRequest { workspace_id: &ws, plan_id: &c_plan, plan_digest: &c_digest, idempotency_key: "idem_auth_corrupt", verified_fingerprint: &fp, applied_at: &applied_at, }) .await, Err(RegistryError::ImportPlanPayloadCorrupt { .. }) ), "a no-ref candidate must not carry an auth snapshot" ); database.cleanup().await; }