story 2-10-security-schemes-secrets: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
f5f40cb167
commit
ecfb4e788f
45 files changed
+6025
-829
No files matched your search
@@ -1,9 +1,10 @@
|
||||
mod legacy_auth;
|
||||
mod plan_apply;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope, ImportPlan,
|
||||
ImportPlanId,
|
||||
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope,
|
||||
ImportOperationDraft, ImportPlan, ImportPlanId,
|
||||
};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -577,6 +578,8 @@ async fn apply_import_job_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
legacy_auth::verify_legacy_import_auth(tx, request.workspace_id, request.operations).await?;
|
||||
|
||||
let mut result = ImportJobApplyResult {
|
||||
application_key: request.application_key.to_owned(),
|
||||
skipped: request.pre_skipped.to_vec(),
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
use super::*;
|
||||
|
||||
/// Legacy Apply has no plan-time auth snapshot, but it still must not create
|
||||
/// operations from a stale or cross-workspace profile reference. Lock and
|
||||
/// validate every referenced profile and its secret rows before inserting
|
||||
/// any operation; ImportPlan Apply performs the stricter snapshot comparison.
|
||||
pub(super) async fn verify_legacy_import_auth(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operations: &[ImportOperationDraft],
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut profiles = std::collections::BTreeMap::<String, Vec<String>>::new();
|
||||
let mut profile_snapshots = std::collections::BTreeMap::<String, (String, Value)>::new();
|
||||
for draft in operations {
|
||||
if let Some(profile_id) = draft.operation.execution_config.auth_profile_ref.as_ref() {
|
||||
profiles.entry(profile_id.as_str().to_owned()).or_default();
|
||||
}
|
||||
}
|
||||
if profiles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let unavailable = |id: &str| RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id: id.to_owned(),
|
||||
};
|
||||
let profile_ids: Vec<String> = profiles.keys().cloned().collect();
|
||||
for profile_id in &profile_ids {
|
||||
let row = sqlx::query(
|
||||
"select id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(profile_id))?;
|
||||
let profile_id_value = row.try_get::<String, _>("id")?;
|
||||
let profile_kind = row.try_get::<String, _>("kind")?;
|
||||
let config_json = row.try_get::<Value, _>("config_json")?;
|
||||
let profile = build_auth_profile(
|
||||
profile_id_value,
|
||||
workspace_id.as_str().to_owned(),
|
||||
row.try_get::<String, _>("name")?,
|
||||
profile_kind.clone(),
|
||||
config_json.clone(),
|
||||
row.try_get::<OffsetDateTime, _>("created_at")?,
|
||||
row.try_get::<OffsetDateTime, _>("updated_at")?,
|
||||
)
|
||||
.map_err(|_| unavailable(profile_id))?;
|
||||
if profile.kind != profile.config.kind() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
let mut secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret| secret.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
secret_ids.sort();
|
||||
secret_ids.dedup();
|
||||
profiles.insert(profile_id.clone(), secret_ids);
|
||||
profile_snapshots.insert(row.try_get::<String, _>("id")?, (profile_kind, config_json));
|
||||
}
|
||||
|
||||
let secret_ids: std::collections::BTreeSet<String> =
|
||||
profiles.values().flatten().cloned().collect();
|
||||
for secret_id in secret_ids {
|
||||
let owner = profiles
|
||||
.iter()
|
||||
.find_map(|(profile_id, ids)| ids.contains(&secret_id).then_some(profile_id.as_str()))
|
||||
.unwrap_or_default();
|
||||
let row = sqlx::query(
|
||||
"select status, current_version
|
||||
from secrets
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&secret_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(owner))?;
|
||||
let status: String = row.try_get("status")?;
|
||||
let version: i32 = row.try_get("current_version")?;
|
||||
let version_present = sqlx::query_scalar::<_, bool>(
|
||||
"select exists(select 1 from secret_versions where secret_id = $1 and version = $2)",
|
||||
)
|
||||
.bind(&secret_id)
|
||||
.bind(version)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if status != "active" || !version_present {
|
||||
return Err(unavailable(owner));
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the established secret-then-profile lock order. The profile may
|
||||
// have changed while secret rows were locked; compare its live config and
|
||||
// secret set with the initial read before Apply mutates any operation.
|
||||
for profile_id in profile_ids {
|
||||
let row = sqlx::query(
|
||||
"select id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or_else(|| unavailable(&profile_id))?;
|
||||
let kind: String = row.try_get("kind")?;
|
||||
let config: Value = row.try_get("config_json")?;
|
||||
let Some((expected_kind, expected_config)) = profile_snapshots.get(&profile_id) else {
|
||||
return Err(unavailable(&profile_id));
|
||||
};
|
||||
if &kind != expected_kind || &config != expected_config {
|
||||
return Err(unavailable(&profile_id));
|
||||
}
|
||||
let profile = build_auth_profile(
|
||||
row.try_get::<String, _>("id")?,
|
||||
workspace_id.as_str().to_owned(),
|
||||
row.try_get::<String, _>("name")?,
|
||||
kind,
|
||||
config,
|
||||
row.try_get::<OffsetDateTime, _>("created_at")?,
|
||||
row.try_get::<OffsetDateTime, _>("updated_at")?,
|
||||
)
|
||||
.map_err(|_| unavailable(&profile_id))?;
|
||||
let mut live_secret_ids = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|secret| secret.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
live_secret_ids.sort();
|
||||
live_secret_ids.dedup();
|
||||
if profiles.get(&profile_id) != Some(&live_secret_ids) {
|
||||
return Err(unavailable(&profile_id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -60,6 +60,18 @@ pub(super) struct StoredPlanCandidate {
|
||||
/// ids/status/versions.
|
||||
#[serde(default)]
|
||||
pub(crate) auth_snapshot: Option<StoredAuthSnapshot>,
|
||||
/// Source-derived selected scheme requirement. Apply checks the live
|
||||
/// profile against this independently of the captured profile snapshot,
|
||||
/// closing a profile-change race between compatibility lookup and capture.
|
||||
#[serde(default)]
|
||||
pub(crate) auth_requirement: Option<StoredAuthRequirement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq, Eq)]
|
||||
pub(super) struct StoredAuthRequirement {
|
||||
pub(crate) kind: String,
|
||||
#[serde(default)]
|
||||
pub(crate) parameter_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Plan-time snapshot of one auth profile's redacted metadata.
|
||||
@@ -391,6 +403,24 @@ pub(super) fn read_and_validate_plan_material(
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
match (&candidate.auth_requirement, &auth_ref, actionable) {
|
||||
(Some(requirement), Some(_), true)
|
||||
if requirement.kind == "unconstrained"
|
||||
&& requirement.parameter_name.is_none()
|
||||
&& decision.action == "new_version" => {}
|
||||
(Some(requirement), Some(_), true)
|
||||
if matches!(requirement.kind.as_str(), "bearer" | "basic")
|
||||
&& requirement.parameter_name.is_none()
|
||||
|| matches!(
|
||||
requirement.kind.as_str(),
|
||||
"api_key_header" | "api_key_query"
|
||||
) && requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| !name.is_empty() && name.len() <= 256) => {}
|
||||
(None, None, _) | (None, Some(_), false) => {}
|
||||
_ => return Err(corrupt()),
|
||||
}
|
||||
match decision.action.as_str() {
|
||||
"create" => {
|
||||
if target.is_some()
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(super) async fn lock_and_verify_auth(
|
||||
workspace_id: &WorkspaceId,
|
||||
candidates: &[StoredPlanCandidate],
|
||||
) -> Result<(), RegistryError> {
|
||||
use material::StoredAuthSnapshot;
|
||||
use material::{StoredAuthRequirement, StoredAuthSnapshot};
|
||||
|
||||
let unavailable = |auth_profile_id: &str| RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id: auth_profile_id.to_owned(),
|
||||
@@ -79,6 +79,7 @@ pub(super) async fn lock_and_verify_auth(
|
||||
// snapshot; a disagreement means the profile drifted during CreatePlan
|
||||
// and the whole apply must be re-previewed before any mutation.
|
||||
let mut snapshots: BTreeMap<String, &StoredAuthSnapshot> = BTreeMap::new();
|
||||
let mut requirements: BTreeMap<String, Vec<&StoredAuthRequirement>> = BTreeMap::new();
|
||||
{
|
||||
use std::collections::btree_map::Entry;
|
||||
for candidate in candidates {
|
||||
@@ -95,6 +96,14 @@ pub(super) async fn lock_and_verify_auth(
|
||||
.auth_snapshot
|
||||
.as_ref()
|
||||
.ok_or_else(|| unavailable(ref_id.as_str()))?;
|
||||
let requirement = candidate
|
||||
.auth_requirement
|
||||
.as_ref()
|
||||
.ok_or_else(|| unavailable(ref_id.as_str()))?;
|
||||
requirements
|
||||
.entry(ref_id.as_str().to_owned())
|
||||
.or_default()
|
||||
.push(requirement);
|
||||
match snapshots.entry(ref_id.as_str().to_owned()) {
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(snapshot);
|
||||
@@ -132,6 +141,13 @@ pub(super) async fn lock_and_verify_auth(
|
||||
if profile.kind != profile.config.kind() {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
if requirements.get(profile_id).is_none_or(|expected| {
|
||||
expected
|
||||
.iter()
|
||||
.any(|requirement| !auth_config_satisfies_requirement(&profile.config, requirement))
|
||||
}) {
|
||||
return Err(unavailable(profile_id));
|
||||
}
|
||||
// Drift since the plan was confirmed (config, name, kind or
|
||||
// updated_at) means the re-preview contract: typed conflict, no
|
||||
// mutation.
|
||||
@@ -263,3 +279,57 @@ pub(super) async fn lock_and_verify_auth(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn auth_config_satisfies_requirement(
|
||||
config: &crank_core::AuthConfig,
|
||||
requirement: &material::StoredAuthRequirement,
|
||||
) -> bool {
|
||||
use crank_core::AuthConfig;
|
||||
match (config, requirement.kind.as_str()) {
|
||||
(_, "unconstrained") => requirement.parameter_name.is_none(),
|
||||
(AuthConfig::Bearer(_), "bearer") | (AuthConfig::Basic(_), "basic") => {
|
||||
requirement.parameter_name.is_none()
|
||||
}
|
||||
(AuthConfig::ApiKeyHeader(config), "api_key_header") => requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| config.header_name.eq_ignore_ascii_case(name)),
|
||||
(AuthConfig::ApiKeyQuery(config), "api_key_query") => requirement
|
||||
.parameter_name
|
||||
.as_deref()
|
||||
.is_some_and(|name| config.param_name == name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::auth_config_satisfies_requirement;
|
||||
use crate::postgres::import_job::plan_apply::material::StoredAuthRequirement;
|
||||
use crank_core::{ApiKeyHeaderAuthConfig, AuthConfig, SecretId};
|
||||
|
||||
#[test]
|
||||
fn source_selected_header_name_is_rechecked_against_live_profile_config() {
|
||||
let source_requirement = StoredAuthRequirement {
|
||||
kind: "api_key_header".to_owned(),
|
||||
parameter_name: Some("X-A".to_owned()),
|
||||
};
|
||||
let compatible = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "x-a".to_owned(),
|
||||
secret_id: SecretId::new("secret_a"),
|
||||
});
|
||||
let changed_after_resolution = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-B".to_owned(),
|
||||
secret_id: SecretId::new("secret_a"),
|
||||
});
|
||||
|
||||
assert!(auth_config_satisfies_requirement(
|
||||
&compatible,
|
||||
&source_requirement
|
||||
));
|
||||
assert!(!auth_config_satisfies_requirement(
|
||||
&changed_after_resolution,
|
||||
&source_requirement
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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(®istry, workspace_tag).await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&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(®istry, &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(®istry, &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(®istry, &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(®istry, &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(®istry, &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;
|
||||
}
|
||||
Reference in new issue
Block a user