Files
crank/crates/crank-registry/tests/integration/import_plan/apply/auth.rs
T

762 lines
25 KiB
Rust

//! 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, ApiKeyQueryAuthConfig, AuthConfig, AuthKind, AuthProfile,
BasicAuthConfig, 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>,
) -> Value {
let operation = auth_operation("op_apply_auth");
let mut candidate = json!({
"key": "auth",
"name": operation.name,
"state": "actionable",
"decision": { "action": "create" },
"auth_requirement": { "kind": "api_key_header", "parameter_name": "X-Apply-Key" },
"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]
})
}
fn typed_auth_plan_payload(
plan_id: &str,
job_id: &str,
fingerprint: &Value,
auth_profile_id: &str,
requirement_kind: &str,
parameter_name: Option<&str>,
snapshot: Value,
) -> Value {
let mut operation = plan_operation("op_typed_auth");
operation.execution_config.auth_profile_ref = Some(auth_profile_id.into());
let mut requirement = json!({ "kind": requirement_kind });
if let Some(parameter_name) = parameter_name {
requirement["parameter_name"] = json!(parameter_name);
}
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": ["typed"], "selected": ["typed"], "excluded": []
},
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
"candidates": [{
"key": "typed",
"name": operation.name,
"state": "actionable",
"decision": { "action": "create" },
"auth_requirement": requirement,
"operation": operation,
"auth_snapshot": snapshot
}]
})
}
async fn typed_auth_base(
database: &TestDatabase,
workspace_tag: &str,
profile_id: &str,
config: AuthConfig,
) -> (
PostgresRegistry,
WorkspaceId,
ImportJobId,
Value,
AuthProfile,
Value,
) {
let registry = database.registry().await;
registry
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
epoch: 1,
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
observed_at: &ts(),
})
.await
.unwrap();
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, workspace_tag).await;
let job = create_pending_openapi_job(
&registry,
&ws,
&format!("job_typed_auth_{workspace_tag}"),
now,
now + Duration::hours(1),
)
.await;
activate_source(&database.raw_pool().await, &ws, now).await;
let mut secrets = Vec::new();
for (index, secret_id) in config.secret_ids().into_iter().enumerate() {
let secret = Secret {
id: secret_id.clone(),
workspace_id: ws.clone(),
name: format!("Typed auth secret {index}"),
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();
secrets.push(secret);
}
let profile = AuthProfile {
id: profile_id.into(),
workspace_id: ws.clone(),
name: "Typed auth profile".to_owned(),
kind: config.kind(),
config,
created_at: ts(),
updated_at: ts(),
};
registry
.save_auth_profile(SaveAuthProfileRequest {
workspace_id: &ws,
profile: &profile,
})
.await
.unwrap();
let snapshot = 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": secrets.iter().map(|secret| json!({
"id": secret.id.as_str(),
"status": secret.status,
"current_version": secret.current_version,
"updated_at": secret.updated_at.format(&Rfc3339).unwrap()
})).collect::<Vec<_>>()
});
(registry, ws, job, fingerprint(), profile, snapshot)
}
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(&registry, workspace_tag).await;
let job = create_pending_openapi_job(
&registry,
&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(&registry, &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(&registry, &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(&registry, &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(&registry, &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;
}
#[tokio::test]
async fn apply_rechecks_live_profile_against_source_requirement_even_when_snapshot_matches() {
let database = TestDatabase::new().await;
let (registry, raw_pool, ws, job, fp, _snapshot_a) =
auth_base(&database, "a_source_requirement").await;
// Reproduce the race: source compatibility was resolved while the
// profile used X-Apply-Key, then the profile changed before the later
// snapshot capture, so the stored snapshot itself accurately says X-B.
sqlx::query(
"update auth_profiles
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-B\"'),
updated_at = now()
where workspace_id = $1 and id = $2",
)
.bind(ws.as_str())
.bind("auth_apply")
.execute(&raw_pool)
.await
.unwrap();
let profile = capture_profile_fixture(&registry, &ws).await;
let secret = registry
.get_secret(&ws, &SecretId::new("sec_apply"))
.await
.unwrap()
.unwrap()
.secret;
let snapshot_b = capture_snapshot(&profile, &secret);
assert_eq!(snapshot_b["config"]["api_key_header"]["header_name"], "X-B");
// The source-derived requirement remains X-Apply-Key even though the
// plan-time snapshot now matches the live X-B profile exactly.
let payload = auth_plan_payload("plan_auth_source_req", job.as_str(), &fp, Some(snapshot_b));
let (plan, digest) =
store_plan(&registry, &ws, &job, "plan_auth_source_req", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_auth_source_req",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await;
assert!(matches!(
result,
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
if auth_profile_id == "auth_apply"
));
assert!(
registry
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
.await
.unwrap()
.is_none()
);
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(&registry, &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(&registry, &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(&registry, &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(&registry, &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;
}
#[tokio::test]
async fn apply_accepts_basic_auth_with_matching_snapshot_and_source_requirement() {
let database = TestDatabase::new().await;
let profile_id = "auth_basic_apply";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_basic_ok",
profile_id,
AuthConfig::Basic(BasicAuthConfig {
username_secret_id: SecretId::new("sec_basic_user"),
password_secret_id: SecretId::new("sec_basic_password"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_basic_ok",
job.as_str(),
&fp,
profile_id,
"basic",
None,
snapshot,
);
let (plan, digest) = store_plan(&registry, &ws, &job, "plan_basic_ok", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_basic_ok",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await
.unwrap();
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.created, 1);
let summary = registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.unwrap();
assert_eq!(summary.current_draft_version, 1);
database.cleanup().await;
}
#[tokio::test]
async fn apply_accepts_query_key_with_matching_snapshot_and_source_requirement() {
let database = TestDatabase::new().await;
let profile_id = "auth_query_apply";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_query_ok",
profile_id,
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new("sec_query_key"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_query_ok",
job.as_str(),
&fp,
profile_id,
"api_key_query",
Some("access_token"),
snapshot,
);
let (plan, digest) = store_plan(&registry, &ws, &job, "plan_query_ok", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_query_ok",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await
.unwrap();
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.created, 1);
let summary = registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.unwrap();
assert_eq!(summary.current_draft_version, 1);
database.cleanup().await;
}
#[tokio::test]
async fn apply_rejects_query_key_source_mismatch_with_matching_live_snapshot() {
let database = TestDatabase::new().await;
let profile_id = "auth_query_mismatch";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_query_mismatch",
profile_id,
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new("sec_query_mismatch"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_query_mismatch",
job.as_str(),
&fp,
profile_id,
"api_key_query",
Some("other_token"),
snapshot,
);
let (plan, digest) =
store_plan(&registry, &ws, &job, "plan_query_mismatch", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_query_mismatch",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await;
assert!(matches!(
result,
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
if auth_profile_id == profile_id
));
assert!(
registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.is_none(),
"query source mismatch must fail before creating an operation"
);
database.cleanup().await;
}