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
@@ -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
|
||||
));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user