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

+20
View File
@@ -542,6 +542,23 @@ pub struct OpenApiImportPreviewResponse {
pub job_id: String,
pub expires_at: String,
pub preview: crank_import::rest::ImportPreview,
#[serde(default)]
pub security_profile_choices: Vec<OpenApiImportSecurityProfileChoice>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportSecurityProfileChoice {
pub operation_key: String,
pub alternative_index: usize,
pub schemes: Vec<String>,
pub profiles: Vec<OpenApiImportAuthProfileChoice>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportAuthProfileChoice {
pub id: String,
pub name: String,
pub kind: crank_core::AuthKind,
}
#[derive(Clone, Debug, Deserialize)]
@@ -610,6 +627,8 @@ pub struct OpenApiImportPlanDecision {
pub confirmed_name: Option<String>,
#[serde(default)]
pub auth_profile_id: Option<String>,
#[serde(default)]
pub security_alternative_index: Option<usize>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -629,6 +648,7 @@ pub struct OpenApiImportPlanCandidateView {
pub target_operation_id: Option<String>,
pub confirmed_name: Option<String>,
pub auth_profile_id: Option<String>,
pub security_alternative_index: Option<usize>,
pub reason: Option<String>,
}
+130 -17
View File
@@ -3,11 +3,11 @@ use std::collections::{BTreeMap, BTreeSet};
use crank_artifacts::{ArtifactError, MAX_ARTIFACT_BYTES};
use crank_core::{
AuthProfileId, ExecutionConfig, OperationId, OperationSecurityLevel, OperationStatus, Protocol,
ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
SecretStatus, ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
};
use crank_import::rest::{
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, NORMALIZER_VERSION,
PROJECTION_VERSION, operation_draft_from_candidate,
PROJECTION_VERSION, operation_draft_from_candidate, validate_document_source_safe,
};
use crank_registry::{
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
@@ -24,12 +24,12 @@ use tracing::{info, instrument};
use crate::{
error::ApiError,
service::{
AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
AdminService, OpenApiImportAuthProfileChoice, OpenApiImportCreatePayload,
OpenApiImportCreateResponse, OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
OpenApiImportPlanCandidateView, OpenApiImportPlanCounts, OpenApiImportPlanCreatePayload,
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision, OpenApiImportPreviewResponse,
OpenApiImportSkippedOperation, OpenApiUpload, OpenApiUploadLocale, OperationPayload,
new_prefixed_id,
OpenApiImportSecurityProfileChoice, OpenApiImportSkippedOperation, OpenApiUpload,
OpenApiUploadLocale, OperationPayload, new_prefixed_id,
},
};
@@ -71,20 +71,52 @@ impl AdminService {
validate_openapi_upload(&upload)?;
let OpenApiUpload {
bytes,
bytes: raw_bytes,
mime_type,
locale,
} = upload;
let store = self.artifact_store.clone();
let artifact = tokio::task::spawn_blocking(move || store.put_registered(&bytes))
.await
.map_err(|_| ApiError::openapi_upload(locale, "storage_unavailable"))?
.map_err(|error| artifact_error(locale, error))?;
let raw_document = std::str::from_utf8(&raw_bytes)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_utf8"))?;
validate_document_source_safe(raw_document, &self.external_reference_normalization)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?;
let now = OffsetDateTime::now_utc();
let mut dependencies = self
.materialize_external_reference_snapshots(workspace_id, &raw_bytes, now)
.await;
if dependencies.unsafe_source {
return Err(ApiError::openapi_upload(locale, "invalid_document"));
}
let source_digest =
crank_import::rest::SourceDigest::parse(format!("{:x}", Sha256::digest(&raw_bytes)))
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?;
if crank_import::rest::validate_resolved_bundle_source_safe(
raw_document,
source_digest,
&dependencies.snapshots,
&self.external_reference_normalization,
)
.is_err()
{
dependencies.detach_all().await;
return Err(ApiError::openapi_upload(locale, "invalid_document"));
}
let bytes = raw_bytes;
let store = self.artifact_store.clone();
let artifact_result = tokio::task::spawn_blocking(move || store.put_registered(&bytes))
.await
.map_err(|_| ApiError::openapi_upload(locale, "storage_unavailable"))
.and_then(|result| result.map_err(|error| artifact_error(locale, error)));
let artifact = match artifact_result {
Ok(artifact) => artifact,
Err(error) => {
dependencies.detach_all().await;
return Err(error);
}
};
let expires_at = now + Duration::hours(IMPORT_JOB_TTL_HOURS);
let job_id = ImportJobId::new(new_prefixed_id("imp"));
let source_id = ArtifactSourceId::new(new_prefixed_id("src_openapi"));
let source = self
let source_result = self
.registry
.create_artifact_source(CreateArtifactSourceRequest {
workspace_id,
@@ -94,7 +126,14 @@ impl AdminService {
sensitivity: ArtifactSourceSensitivity::Internal,
created_at: now,
})
.await?;
.await;
let source = match source_result {
Ok(source) => source,
Err(error) => {
dependencies.detach_all().await;
return Err(ApiError::from(error));
}
};
let mut detach_guard = SourceDetachGuard::new(
self.registry.clone(),
workspace_id.clone(),
@@ -120,9 +159,6 @@ impl AdminService {
detach_guard.detach_now().await;
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let mut dependencies = self
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
.await;
let parsed = match parse_verified_preview(
verified.bytes,
artifact.artifact_ref().digest_hex().to_owned(),
@@ -197,15 +233,92 @@ impl AdminService {
dependencies.disarm();
detach_guard.disarm();
let security_profile_choices = self
.security_profile_choices(workspace_id, &parsed.preview)
.await?;
Ok(OpenApiImportPreviewResponse {
job_id: job_id.as_str().to_owned(),
expires_at: expires_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
preview: parsed.preview,
security_profile_choices,
})
}
async fn security_profile_choices(
&self,
workspace_id: &WorkspaceId,
preview: &crank_import::rest::ImportPreview,
) -> Result<Vec<OpenApiImportSecurityProfileChoice>, ApiError> {
let profiles = self.registry.list_auth_profiles(workspace_id).await?;
let mut available = Vec::new();
for profile in profiles {
if profile.kind != profile.config.kind() {
continue;
}
let mut usable = true;
for secret_id in profile.config.secret_ids() {
let Some(secret) = self.registry.get_secret(workspace_id, secret_id).await? else {
usable = false;
break;
};
if secret.secret.status != SecretStatus::Active
|| self
.registry
.get_current_secret_version(workspace_id, secret_id)
.await?
.is_none()
{
usable = false;
break;
}
}
if usable {
available.push(profile);
}
}
let mut choices = Vec::new();
for operation in preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
{
for (alternative_index, alternative) in operation
.security_requirements
.alternatives
.iter()
.enumerate()
{
if !alternative.supported || alternative.schemes.len() != 1 {
continue;
}
let Some(scheme) = operation.security_schemes.get(&alternative.schemes[0]) else {
continue;
};
let profiles = available
.iter()
.filter(|profile| {
import_plan::auth_config_matches_scheme(&profile.config, scheme)
})
.map(|profile| OpenApiImportAuthProfileChoice {
id: profile.id.as_str().to_owned(),
name: profile.name.clone(),
kind: profile.kind,
})
.collect::<Vec<_>>();
choices.push(OpenApiImportSecurityProfileChoice {
operation_key: operation.key.clone(),
alternative_index,
schemes: alternative.schemes.clone(),
profiles,
});
}
}
Ok(choices)
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
pub async fn create_openapi_import(
&self,
@@ -7,6 +7,13 @@ pub(super) struct MaterializedDependencies {
envelopes: Vec<ImportJobSourceEnvelope>,
canonical_uris: Vec<String>,
guards: Vec<SourceDetachGuard>,
pub(super) unsafe_source: bool,
}
struct StagedDependency {
canonical_uri: String,
bytes: Vec<u8>,
document: String,
}
pub(super) struct ImportReplayContext<'a> {
@@ -24,6 +31,7 @@ impl MaterializedDependencies {
envelopes: Vec::new(),
canonical_uris: Vec::new(),
guards: Vec::new(),
unsafe_source: false,
}
}
@@ -176,8 +184,8 @@ impl AdminService {
}
}
let mut seen = BTreeSet::new();
let mut result = MaterializedDependencies::empty();
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
let mut staged = Vec::<StagedDependency>::new();
let mut staged_documents = vec![primary.to_owned()];
while let Some((canonical_uri, depth)) = queue.pop_front() {
if !seen.insert(canonical_uri.clone())
|| depth > self.external_reference_normalization.max_reference_depth
@@ -194,32 +202,77 @@ impl AdminService {
materialization_failure(
"fetch",
external_fetch_error_code(&error),
result.snapshots.len(),
staged.len(),
);
continue;
}
};
let Ok(document) = std::str::from_utf8(&bytes).map(str::to_owned) else {
materialization_failure(
"dependency_decode",
"invalid_utf8",
result.snapshots.len(),
);
materialization_failure("dependency_decode", "invalid_utf8", staged.len());
continue;
};
let Ok(references) = crank_import::rest::external_reference_uris(
&document,
&self.external_reference_normalization,
) else {
materialization_failure(
"dependency_scan",
"invalid_document",
result.snapshots.len(),
);
materialization_failure("dependency_scan", "invalid_document", staged.len());
continue;
};
staged_documents.push(document.clone());
staged.push(StagedDependency {
canonical_uri: canonical_uri.clone(),
bytes,
document,
});
for reference in references {
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
{
queue.push_back((uri, depth.saturating_add(1)));
}
}
}
let staged_snapshots = staged
.iter()
.filter_map(|dependency| {
let digest = format!("{:x}", Sha256::digest(&dependency.bytes));
let digest = crank_import::rest::SourceDigest::parse(digest).ok()?;
Some(crank_import::rest::ExternalDocumentSnapshot {
canonical_uri: dependency.canonical_uri.clone(),
digest,
document: dependency.document.clone(),
})
})
.collect::<Vec<_>>();
let primary_digest =
crank_import::rest::SourceDigest::parse(format!("{:x}", Sha256::digest(primary_bytes)))
.expect("SHA-256 digest is valid");
let raw_bundle_is_unsafe = crank_import::rest::validate_document_bundle_source_safe(
&staged_documents
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
&self.external_reference_normalization,
)
.is_err();
let resolved_bundle_is_unsafe = crank_import::rest::validate_resolved_bundle_source_safe(
primary,
primary_digest,
&staged_snapshots,
&self.external_reference_normalization,
)
.is_err();
if raw_bundle_is_unsafe || resolved_bundle_is_unsafe {
materialization_failure("dependency_redaction", "invalid_document", staged.len());
let mut rejected = MaterializedDependencies::empty();
rejected.unsafe_source = true;
return rejected;
}
let mut result = MaterializedDependencies::empty();
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
for dependency in staged {
let store = self.artifact_store.clone();
let artifact_bytes = bytes.clone();
let artifact_bytes = dependency.bytes.clone();
let Ok(Ok(artifact)) =
tokio::task::spawn_blocking(move || store.put_registered(&artifact_bytes)).await
else {
@@ -295,31 +348,22 @@ impl AdminService {
dependency_by_digest.insert(digest_key, index);
index
};
let dependency = &result.envelopes[envelope_index];
let snapshot_digest = match crank_import::rest::SourceDigest::parse(
dependency.digest.digest_hex().to_owned(),
) {
Ok(digest) => digest,
Err(_) => {
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
continue;
}
let dependency_envelope = &result.envelopes[envelope_index];
let Ok(snapshot_digest) = crank_import::rest::SourceDigest::parse(
dependency_envelope.digest.digest_hex().to_owned(),
) else {
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
continue;
};
result
.snapshots
.push(crank_import::rest::ExternalDocumentSnapshot {
canonical_uri: canonical_uri.clone(),
canonical_uri: dependency.canonical_uri.clone(),
digest: snapshot_digest,
document,
document: dependency.document,
});
materialized_count.store(result.snapshots.len(), std::sync::atomic::Ordering::Relaxed);
result.canonical_uris.push(canonical_uri.clone());
for reference in references {
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
{
queue.push_back((uri, depth.saturating_add(1)));
}
}
result.canonical_uris.push(dependency.canonical_uri);
}
// Registry ownership is one envelope per immutable digest, while the
// resolver may map several canonical URIs to that same snapshot. Keep
@@ -1,4 +1,6 @@
use super::*;
use crank_core::AuthConfig;
use crank_import::rest::SecurityRequirementsSource as SecuritySource;
impl AdminService {
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
@@ -204,6 +206,7 @@ impl AdminService {
target_operation_id: candidate.target_operation_id.clone(),
confirmed_name: candidate.confirmed_name.clone(),
auth_profile_id: candidate.auth_profile_id.clone(),
security_alternative_index: candidate.security_alternative_index,
reason: candidate.reason.clone(),
})
.collect();
@@ -220,6 +223,7 @@ impl AdminService {
target_operation_id: None,
confirmed_name: None,
auth_profile_id: None,
security_alternative_index: None,
reason: Some("not_selected".to_owned()),
}
}));
@@ -257,9 +261,12 @@ impl AdminService {
decision.and_then(|decision| decision.target_operation_id.clone());
let confirmed_name = decision.and_then(|decision| decision.confirmed_name.clone());
let auth_profile_id = decision.and_then(|decision| decision.auth_profile_id.clone());
let requested_security_alternative =
decision.and_then(|decision| decision.security_alternative_index);
let mut blocker_reason = blocker_reason;
let candidate_name = candidate.draft.name.clone();
let blocked = blocker_reason.is_some();
let mut blocked = blocker_reason.is_some();
// Explicit skip/new_version targets are always resolved in the
// workspace: an unknown target, a name mismatch, or an incompatible
@@ -353,6 +360,8 @@ impl AdminService {
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index: requested_security_alternative,
auth_requirement: None,
auth_snapshot: None,
target: None,
operation: None,
@@ -368,17 +377,17 @@ impl AdminService {
));
}
}
// The final server-authored auth profile reference: the explicit
// decision, or the target's reference inherited for an actionable
// new_version. Only the reference (never a secret value) is stored.
// Use an explicit decision or inherit the target reference for new_version.
let mut auth_profile_ref = auth_profile_id
.as_deref()
.map(|id| AuthProfileId::new(id.to_owned()));
let mut inherited_auth_profile = false;
if let Some(summary) = target_summary.as_ref()
&& !blocked
&& action == "new_version"
&& auth_profile_ref.is_none()
&& (candidate.security_requirements.source == SecuritySource::None
|| !candidate.security_requirements.alternatives.is_empty())
{
let record = self
.registry
@@ -386,8 +395,65 @@ impl AdminService {
.await?
.ok_or_else(|| ApiError::internal("current operation version is unavailable"))?;
auth_profile_ref = record.snapshot.execution_config.auth_profile_ref;
inherited_auth_profile = auth_profile_ref.is_some();
}
let auth_profile_id = auth_profile_ref.as_ref().map(|id| id.as_str().to_owned());
let inherited_unconstrained_auth = inherited_auth_profile
&& action == "new_version"
&& candidate.security_requirements.source
== crank_import::rest::SecurityRequirementsSource::None
&& candidate.security_requirements.alternatives.is_empty()
&& requested_security_alternative.is_none();
let security_alternative_index = if blocked {
requested_security_alternative
} else if inherited_unconstrained_auth {
None
} else {
resolve_security_binding(
self,
workspace_id,
candidate,
auth_profile_ref.as_ref(),
requested_security_alternative,
&mut blocker_reason,
)
.await?
};
blocked = blocker_reason.is_some();
let auth_requirement = if !blocked && inherited_unconstrained_auth {
Some(json!({ "kind": "unconstrained" }))
} else if !blocked && auth_profile_ref.is_some() {
security_alternative_index
.and_then(|index| candidate.security_requirements.alternatives.get(index))
.and_then(|alternative| {
(alternative.schemes.len() == 1).then(|| &alternative.schemes[0])
})
.and_then(|scheme_name| candidate.security_schemes.get(scheme_name))
.and_then(|scheme| match &scheme.kind {
crank_import::rest::NormalizedSecuritySchemeKind::Http { scheme, .. } => {
match scheme.to_ascii_lowercase().as_str() {
"bearer" => Some(json!({ "kind": "bearer" })),
"basic" => Some(json!({ "kind": "basic" })),
_ => None,
}
}
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
location: crank_import::rest::SecurityParameterLocation::Header,
parameter_name,
..
} => {
Some(json!({ "kind": "api_key_header", "parameter_name": parameter_name }))
}
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
location: crank_import::rest::SecurityParameterLocation::Query,
parameter_name,
..
} => Some(json!({ "kind": "api_key_query", "parameter_name": parameter_name })),
_ => None,
})
} else {
None
};
if blocked {
return Ok(PlannedCandidate {
@@ -399,6 +465,8 @@ impl AdminService {
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement,
auth_snapshot: None,
target,
operation: None,
@@ -415,6 +483,8 @@ impl AdminService {
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement: None,
auth_snapshot: None,
target,
operation: None,
@@ -479,6 +549,8 @@ impl AdminService {
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement,
auth_snapshot,
target,
operation: Some(operation),
@@ -492,7 +564,12 @@ impl AdminService {
workspace_id: &WorkspaceId,
profile_id: &AuthProfileId,
) -> Result<Value, ApiError> {
let unavailable = || import_plan_repreview_error("import_plan_auth_unavailable");
let unavailable = || {
ApiError::unprocessable_with_context(
"The selected authentication profile is unavailable for this import.",
json!({ "error_code": "import_plan_auth_unavailable" }),
)
};
let profile = self
.registry
.get_auth_profile(workspace_id, profile_id)
@@ -543,6 +620,8 @@ struct PlannedCandidate {
target_operation_id: Option<String>,
confirmed_name: Option<String>,
auth_profile_id: Option<String>,
security_alternative_index: Option<usize>,
auth_requirement: Option<Value>,
auth_snapshot: Option<Value>,
target: Option<Value>,
operation: Option<RegistryOperation>,
@@ -705,6 +784,12 @@ fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(),
{
return invalid("decision auth_profile_id is empty or too long");
}
if decision
.security_alternative_index
.is_some_and(|index| index > MAX_IMPORT_PLAN_KEYS)
{
return invalid("decision security_alternative_index is too large");
}
match decision.action.as_str() {
"create" => {
if decision.target_operation_id.is_some() || decision.confirmed_name.is_some() {
@@ -714,8 +799,8 @@ fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(),
}
}
"skip" => {
if decision.auth_profile_id.is_some() {
return invalid("auth_profile_id is not allowed for action skip");
if decision.auth_profile_id.is_some() || decision.security_alternative_index.is_some() {
return invalid("security binding is not allowed for action skip");
}
if decision.target_operation_id.is_none() {
return invalid("action skip requires the exact target_operation_id");
@@ -745,6 +830,138 @@ fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(),
Ok(())
}
async fn resolve_security_binding(
service: &AdminService,
workspace_id: &WorkspaceId,
candidate: &ImportOperationCandidate,
profile_ref: Option<&AuthProfileId>,
requested_index: Option<usize>,
blocker_reason: &mut Option<String>,
) -> Result<Option<usize>, ApiError> {
let alternatives = &candidate.security_requirements.alternatives;
if alternatives.is_empty() {
if profile_ref.is_some() || requested_index.is_some() {
return Err(ApiError::validation_with_context(
"security binding was supplied for an operation with no security requirement",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
return Ok(None);
}
let public_index = alternatives
.iter()
.position(|alternative| alternative.supported && alternative.schemes.is_empty());
let compatible = if let Some(profile_ref) = profile_ref {
let profile = service
.registry
.get_auth_profile(workspace_id, profile_ref)
.await?
.ok_or_else(|| {
ApiError::unprocessable_with_context(
"selected Auth Profile is unavailable in this workspace",
json!({ "error_code": "import_plan_auth_unavailable" }),
)
})?;
let compatible = alternatives
.iter()
.enumerate()
.filter(|(_, alternative)| {
alternative.supported
&& alternative.schemes.len() == 1
&& candidate
.security_schemes
.get(&alternative.schemes[0])
.is_some_and(|scheme| auth_config_matches_scheme(&profile.config, scheme))
})
.map(|(index, _)| index)
.collect::<Vec<_>>();
Some((profile, compatible))
} else {
None
};
if let Some((_, compatible_indices)) = compatible.as_ref() {
let selected = match requested_index {
Some(index) if compatible_indices.contains(&index) => index,
Some(_) => {
return Err(ApiError::validation_with_context(
"selected Auth Profile is incompatible with the selected security alternative",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
None if compatible_indices.len() == 1 => compatible_indices[0],
None if compatible_indices.is_empty() => {
return Err(ApiError::validation_with_context(
"selected Auth Profile is incompatible with the source security schemes",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
None => {
return Err(ApiError::validation_with_context(
"security_alternative_index is required when a profile matches multiple alternatives",
json!({ "operation_key": candidate.key, "error_code": "import_plan_security_alternative_required" }),
));
}
};
return Ok(Some(selected));
}
if let Some(index) = requested_index {
if alternatives
.get(index)
.is_none_or(|alternative| !alternative.supported)
{
return Err(ApiError::validation_with_context(
"selected security alternative is unsupported",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
if alternatives[index].schemes.is_empty() {
return Ok(Some(index));
}
}
if let Some(public_index) = public_index
&& requested_index.is_none()
{
return Ok(Some(public_index));
}
*blocker_reason = Some("auth_profile_required".to_owned());
Ok(requested_index)
}
pub(super) fn auth_config_matches_scheme(
config: &AuthConfig,
scheme: &crank_import::rest::NormalizedSecurityScheme,
) -> bool {
use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
match (&scheme.kind, config) {
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Bearer(_)) => {
scheme.eq_ignore_ascii_case("bearer")
}
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Basic(_)) => {
scheme.eq_ignore_ascii_case("basic")
}
(
NormalizedSecuritySchemeKind::ApiKey {
location: SecurityParameterLocation::Header,
parameter_name,
..
},
AuthConfig::ApiKeyHeader(config),
) => parameter_name.eq_ignore_ascii_case(&config.header_name),
(
NormalizedSecuritySchemeKind::ApiKey {
location: SecurityParameterLocation::Query,
parameter_name,
..
},
AuthConfig::ApiKeyQuery(config),
) => parameter_name == &config.param_name,
_ => false,
}
}
/// Serializes one planned candidate into the versioned plan payload: the
/// redacted decision, the bounded rejection reason (if any), the exact
/// authorized target with expected state and, for mutating actions, the full
@@ -759,6 +976,7 @@ fn plan_candidate_payload(candidate: &PlannedCandidate) -> Result<Value, ApiErro
"target_operation_id": candidate.target_operation_id,
"confirmed_name": candidate.confirmed_name,
"auth_profile_id": candidate.auth_profile_id,
"security_alternative_index": candidate.security_alternative_index,
},
});
if let Some(reason) = &candidate.reason {
@@ -770,6 +988,9 @@ fn plan_candidate_payload(candidate: &PlannedCandidate) -> Result<Value, ApiErro
if let Some(auth_snapshot) = &candidate.auth_snapshot {
object["auth_snapshot"] = auth_snapshot.clone();
}
if let Some(auth_requirement) = &candidate.auth_requirement {
object["auth_requirement"] = auth_requirement.clone();
}
if let Some(operation) = &candidate.operation {
let value = serde_json::to_value(operation)
.map_err(|error| ApiError::internal(error.to_string()))?;
@@ -203,10 +203,12 @@ fn import_replay_contract(
return Ok(ImportReplayContract::Current);
}
// Historical preview payloads are replayed as their persisted projection.
// They must never be parsed again with the current v4 semantics.
// They must never be parsed again with current normalization semantics.
if !matches!(
(normalizer, projection),
("normalized-ir-v2", "preview-v2") | ("normalized-ir-v3", "preview-v3")
("normalized-ir-v2", "preview-v2")
| ("normalized-ir-v3", "preview-v3")
| ("normalized-ir-v4", "preview-v4")
) {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
@@ -385,6 +387,14 @@ pub(super) fn preview_has_blocker(
.iter()
.flat_map(|group| group.operations.iter())
.filter(|operation| selected_operation_keys.contains(&operation.key))
.flat_map(|operation| operation.findings.iter())
.any(|finding| finding.severity == ImportFindingSeverity::Error)
.any(|operation| {
operation
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|| (!operation.security_requirements.alternatives.is_empty()
&& !operation.security_requirements.alternatives.iter().any(
|alternative| alternative.supported && alternative.schemes.is_empty(),
))
})
}