story 2-10-security-schemes-secrets: implemented and reviewed via bmad-loop

This commit is contained in:
bsodfather committed 2026-10-03 00:09:08 +03:00
1 parent f5f40cb167
commit ecfb4e788f
45 files changed
+6025 -829

No files matched your search

@@ -5,8 +5,8 @@
use super::*;
use crank_core::{
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, Secret, SecretId, SecretKind,
SecretStatus,
ApiKeyHeaderAuthConfig, ApiKeyQueryAuthConfig, AuthConfig, AuthKind, AuthProfile,
BasicAuthConfig, Secret, SecretId, SecretKind, SecretStatus,
};
use crank_registry::MASTER_KEY_CIPHER_CONTRACT;
use crank_registry::{
@@ -110,6 +110,7 @@ fn auth_plan_payload(
"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 {
@@ -133,6 +134,136 @@ fn auth_plan_payload(
})
}
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,
@@ -268,6 +399,67 @@ async fn apply_rejects_auth_profile_config_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"))
@@ -421,3 +613,149 @@ async fn apply_rejects_auth_candidates_missing_or_mismatched_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;
}