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(),
))
})
}
@@ -14,6 +14,115 @@ mod http_contract;
mod import_plan_apply;
mod import_plan_create;
#[tokio::test]
#[serial]
async fn upload_rejects_credential_literals_before_persisting_source_artifacts() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_storage_redaction");
let service = test_service(
registry.clone(),
storage_root,
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Redaction persistence","version":"1"},
"servers":[{"url":"https://bare-canary@api.example.test/v1?api_key=query-canary"}],
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
"paths":{"/private":{"get":{
"operationId":"privateOperation",
"parameters":[{"name":"X-Api-Key","in":"header","example":"opaque-canary-42"}],
"responses":{"200":{"description":"ok"}},
"x-client-secret":true
}}}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.expect_err("credential-bearing uploads must be rejected before persistence");
let rendered_error = format!("{error:?}");
assert!(
rendered_error.contains("invalid_document"),
"unexpected typed error: {rendered_error}"
);
for canary in ["bare-canary", "query-canary", "opaque-canary-42"] {
assert!(
!rendered_error.contains(canary),
"API error leaked {canary}"
);
}
let source_count: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(source_count, 0, "unsafe upload created an artifact source");
}
#[tokio::test]
#[serial]
async fn legacy_apply_rejects_required_auth_without_binding_before_creating_draft() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_unresolved_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Required auth","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer"}}},
"security":[{"bearer":[]}],
"paths":{"/secure":{"get":{"operationId":"secureOperation","responses":{"200":{"description":"ok"}}}}}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /secure".to_owned()],
server_url: None,
conflict_mode: "rename".to_owned(),
},
)
.await;
let error = result.expect_err("legacy apply cannot bypass unresolved required auth");
assert!(format!("{error:?}").contains("invalid_document"));
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let job = registry
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Failed);
}
const OPENAPI3: &str = r#"
openapi: 3.0.3
info:
@@ -80,11 +189,11 @@ async fn previews_openapi_and_creates_draft_operations() {
assert_eq!(preview_job.status, ImportJobStatus::Pending);
assert_eq!(
preview_job.preview_payload["normalization"]["normalizer_version"],
"normalized-ir-v4"
crank_import::rest::NORMALIZER_VERSION
);
assert_eq!(
preview_job.preview_payload["normalization"]["projection_version"],
"preview-v4"
crank_import::rest::PROJECTION_VERSION
);
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
@@ -1,11 +1,15 @@
use super::super::common::test_service_with_external_references;
use super::*;
use axum::{Router, routing::get};
use sha2::{Digest, Sha256};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет Line truncated
#[tokio::test]
#[serial]
async fn external_relative_chain_survives_reversed_builder_order_and_apply_never_refetches() {
@@ -35,7 +39,7 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
@@ -105,6 +109,7 @@ paths:
)
.await
.unwrap();
server.abort();
assert_eq!(applied.created.len(), 1);
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let active_sources: i64 = sqlx::query_scalar(
@@ -117,6 +122,115 @@ paths:
assert_eq!(active_sources, 0);
}
#[tokio::test]
#[serial]
async fn external_secret_document_is_rejected_before_blob_registration() {
let external_document = "Item: { type: object, x-api-key: external-secret-canary-42, properties: { id: { type: string } } }";
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/schemas.yaml",
get(move || {
let fetch_count = Arc::clone(&fetch_count);
async move {
fetch_count.fetch_add(1, Ordering::SeqCst);
external_document
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_secret_rejected");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let error = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: Safe primary with unsafe external }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }} }} }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect_err("unsafe external bundle must be rejected before source persistence");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(!rendered_error.contains("external-secret-canary-42"));
// The raw dependency's content-addressed path must not exist even as an
// unregistered blob, and no other stored file may contain its literal.
let external_digest = format!("{:x}", Sha256::digest(external_document.as_bytes()));
let external_blob = storage_root
.join("sha256")
.join(&external_digest[..2])
.join(&external_digest);
assert!(
!external_blob.exists(),
"secret-bearing external response was written to the artifact store"
);
assert!(!storage_contains_literal(
&storage_root,
b"external-secret-canary-42"
));
let dependency_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(dependency_sources, 0);
let active_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(active_sources, 0);
}
fn storage_contains_literal(root: &std::path::Path, literal: &[u8]) -> bool {
std::fs::read_dir(root).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_contains_literal(&path, literal)
} else {
std::fs::read(path)
.unwrap()
.windows(literal.len())
.any(|window| window == literal)
}
})
}
#[tokio::test]
#[serial]
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
@@ -316,7 +430,7 @@ async fn external_materialization_uses_one_wall_clock_timeout_and_cleans_cancell
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let timeout_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
@@ -368,6 +482,7 @@ paths:
)
.await
.unwrap();
timeout_server.abort();
assert!(started.elapsed() < std::time::Duration::from_millis(800));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let job = registry
@@ -403,7 +518,10 @@ paths:
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(detached_dependencies, 1);
assert_eq!(
detached_dependencies, 0,
"staged dependencies must not be persisted before the fetch chain completes"
);
}
#[tokio::test]
@@ -606,3 +724,90 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
}
#[tokio::test]
#[serial]
async fn exact_v4_security_contract_replays_its_persisted_security_classification() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v4_security_compatibility"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Historical security","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"basic":{"type":"http","scheme":"basic"}}},
"security":[{"basic":[]}],
"paths":{
"/secure":{"get":{"operationId":"secure","responses":{"200":{"description":"ok"}}}},
"/public":{"get":{"operationId":"public","security":[],"responses":{"200":{"description":"ok"}}}}
}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
// Keep the genuine baseline-v4 normalization/projection, preview and digest intact.
// Only bind its source envelope to this test's newly registered immutable source blob.
let mut payload: serde_json::Value =
serde_json::from_str(BASELINE_V4_SECURITY_PREVIEW_PAYLOAD).unwrap();
assert_eq!(
payload.pointer("/source/digest"),
job.preview_payload.pointer("/source/digest"),
"baseline fixture must refer to the exact uploaded source bytes",
);
payload["source"]["source_id"] = job.preview_payload["source"]["source_id"].clone();
assert_eq!(
payload["normalization"]["normalizer_version"],
"normalized-ir-v4"
);
assert_eq!(payload["normalization"]["projection_version"], "preview-v4");
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /secure".to_owned()],
server_url: Some("https://api.example.test".to_owned()),
conflict_mode: "skip".to_owned(),
},
)
.await;
let error =
result.expect_err("historical v4 security blocker must refuse the selected candidate");
assert!(
format!("{error:?}").contains("invalid_document"),
"v4 contract was rejected before candidate validation: {error:?}"
);
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
mod security_bundle;
@@ -0,0 +1,413 @@
use super::*;
// --- Referenced security credentials RED regressions ---
// These tests prove that credential literals hidden behind local/external $ref
// security scheme + parameter splits are rejected before artifact persistence.
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_ref_with_parameter_default_canary_rejected() {
let canary = b"local-ref-canary-001-Zx9qK";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ref_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: r##"{
"openapi":"3.1.0",
"info":{"title":"Local ref scheme","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"},
"x-key":{"type":"string","default":"local-ref-canary-001-Zx9qK"},
"components":{
"securitySchemes":{"custom":{"$ref":"#/x-scheme"}}
},
"security":[{"custom":[]}],
"paths":{
"/test":{"get":{
"operationId":"test", "security":[{"custom":[]}],
"parameters":[{"name":"X-Custom","in":"header","schema":{"$ref":"#/x-key"}}],
"responses":{"200":{"description":"ok"}}
}}
}
}"##
.as_bytes()
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
// Canary must NOT appear in the API response (error or preview).
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe local ref bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
// Canary must NOT be persisted to artifact storage.
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from referenced local scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn encoded_access_token_fragment_is_rejected_before_persistence() {
let canary = b"fragment-ingress-canary-004-Qm7vN";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_encoded_fragment_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br##"{
"openapi":"3.1.0",
"info":{"title":"Encoded fragment credential","version":"1"},
"servers":[{"url":"https://api.example.test/v1#%61%63%63%65%73%73%5F%74%6F%6B%65%6E=fragment-ingress-canary-004-Qm7vN"}],
"paths":{"/health":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"##
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.expect_err("encoded access_token fragment must be rejected at ingress");
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(rendered_error.len() <= 512, "error must remain bounded");
assert!(!rendered_error.contains("fragment-ingress-canary-004-Qm7vN"));
assert!(!rendered_error.contains("%61%63%63%65%73%73%5F%74%6F%6B%65%6E"));
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
assert!(!storage_contains_literal(&storage_root, canary));
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_external_scheme_ref_local_parameter_default_canary_rejected()
{
let canary = b"split-ext-canary-002-Yw8pJ";
// External document defines the apiKey security scheme with header X-Custom.
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.to_owned()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_ext_scheme_ref_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary references the external scheme; contains a local parameter
// with name X-Custom and schema.default = canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Ext scheme ref","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"$ref":"{origin}/scheme.yaml#/x-scheme"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"type":"string","default":"{canary}"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
canary = std::str::from_utf8(canary).unwrap(),
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external scheme must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external scheme bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from split external scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_external_parameter_default_canary_rejected() {
let canary = b"split-local-canary-003-Xv7oI";
// External document defines a parameter schema whose default is the canary.
let external_doc = format!(
r#"{{"x-key":{{"type":"string","default":"{canary}"}}}}"#,
canary = std::str::from_utf8(canary).unwrap(),
);
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/key.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.clone()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ext_param_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary declares the scheme directly (no $ref); parameter schema is
// an external $ref whose resolved default would be the canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Local scheme ext param","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"type":"apiKey","in":"header","name":"X-Custom"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"$ref":"{origin}/key.yaml#/x-key"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external parameter must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external parameter bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from external referenced parameter persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn safe_external_security_scheme_and_parameter_are_preserved() {
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let count = Arc::clone(&fetch_count);
async move {
count.fetch_add(1, Ordering::SeqCst);
external_doc
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_safe_external_security_ref");
let service = test_service_with_external_references(
registry.clone(),
storage_root,
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"openapi: 3.1.0
info: {{ title: Safe external scheme, version: '1' }}
servers: [{{ url: https://api.example.test }}]
components:
securitySchemes:
custom: {{ $ref: '{origin}/scheme.yaml#/x-scheme' }}
security: [{{ custom: [] }}]
paths:
/test:
get:
operationId: safeExternalSecurity
security: [{{ custom: [] }}]
parameters:
- name: X-Custom
in: header
schema: {{ type: string }}
- name: locale
in: query
schema: {{ type: string, default: en }}
responses:
'200': {{ description: ok }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect("safe referenced schemes and parameters remain importable");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let operation = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|operation| operation.key == "GET /test")
.expect("operation preview is preserved");
assert!(matches!(
&operation.security_schemes["custom"].kind,
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
parameter_name,
location: crank_import::rest::SecurityParameterLocation::Header,
..
} if parameter_name == "X-Custom"
));
let input_schema = serde_json::to_value(&operation.draft.input_schema).unwrap();
assert_eq!(
input_schema.pointer("/fields/locale/default_value"),
Some(&serde_json::json!("en")),
"benign locale default must remain visible in the preview"
);
let job = registry
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
job.preview_payload["dependency_snapshots"]
.as_array()
.unwrap()
.len(),
1
);
}
async fn assert_rejected_bundle_unpersisted(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
storage_root: &std::path::Path,
) {
let sources: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
let jobs: i64 = sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(sources, 0, "rejected bundle registered a source");
assert_eq!(jobs, 0, "rejected bundle created an import job");
assert!(
!storage_has_files(storage_root),
"rejected bundle stored artifact bytes"
);
}
fn storage_has_files(path: &std::path::Path) -> bool {
std::fs::read_dir(path).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_has_files(&path)
} else {
true
}
})
}
@@ -58,6 +58,26 @@ paths:
responses: { '200': { description: ok } }
"#;
const OPENAPI_TWO_APIKEY_OPERATIONS: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
security: [{ apiKey: [] }]
paths:
/alpha: { get: { operationId: alpha, responses: { '200': { description: ok } } } }
/beta: { get: { operationId: beta, responses: { '200': { description: ok } } } }
"#;
const OPENAPI_SINGLE_APIKEY_OPERATION: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
paths:
/alpha: { get: { operationId: alpha, security: [{ apiKey: [] }], responses: { '200': { description: ok } } } }
"#;
const OPENAPI_WITH_BLOCKER: &str = r#"
openapi: 3.0.3
info: { title: Blocked full Apply test }
@@ -593,7 +613,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
let redacted_plan = create_plan(
&client,
&base_url,
OPENAPI_TWO_OPERATIONS,
OPENAPI_TWO_APIKEY_OPERATIONS,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /beta"],
@@ -619,7 +639,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
OPENAPI_SINGLE_APIKEY_OPERATION,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
@@ -657,7 +677,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
&OPENAPI_SINGLE_APIKEY_OPERATION.replace("X-Api-Key", "X-Changed-Key"),
json!({
"selection_mode": "full",
"selected_operation_keys": [],
@@ -695,6 +715,128 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
assert_eq!(after["items"][0]["name"], "beta");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn profiles_sharing_active_secret_are_selectable_and_both_block_after_disable() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("import_plan_shared_auth_secret"),
))
.await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "shared-import-auth-token",
"kind": "token",
"value": { "token": "shared-import-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let secret_id = secret["id"].as_str().unwrap();
let make_profile = |name: &str| {
client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": name,
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret_id
}}
}))
};
let first: Value = make_profile("shared-auth-a")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let second: Value = make_profile("shared-auth-b")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let document = r#"{
"openapi":"3.0.3",
"info":{"title":"Shared profile test","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
"paths":{
"/a":{"get":{"operationId":"sharedA","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}},
"/b":{"get":{"operationId":"sharedB","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}}
}
}"#;
let plan = create_plan(
&client,
&base_url,
document,
json!({
"selection_mode":"full",
"selected_operation_keys":[],
"decisions":[
{"operation_key":"GET /a","action":"create","auth_profile_id":first["id"]},
{"operation_key":"GET /b","action":"create","auth_profile_id":second["id"]}
]
}),
)
.await;
let (status, report) = apply_plan(&client, &base_url, &plan, "shared-secret-active").await;
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
let first_id = first["id"].as_str().unwrap();
let second_id = second["id"].as_str().unwrap();
let disabled_document = document
.replace("sharedA", "sharedAAfterDisable")
.replace("sharedB", "sharedBAfterDisable");
let mut disabled_plans = Vec::new();
for (key, profile_id) in [("GET /a", first_id), ("GET /b", second_id)] {
disabled_plans.push((
key,
create_plan(
&client,
&base_url,
&disabled_document,
json!({
"selection_mode":"partial",
"selected_operation_keys":[key],
"decisions":[{"operation_key":key,"action":"create","auth_profile_id":profile_id}]
}),
)
.await,
));
}
sqlx::query("update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2")
.bind("ws_default")
.bind(secret_id)
.execute(registry.pool())
.await
.unwrap();
for (key, plan) in disabled_plans {
let (status, error) = apply_plan(
&client,
&base_url,
&plan,
&format!("shared-secret-disabled-{key}"),
)
.await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
@@ -844,3 +986,4 @@ async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
}
mod corpus_hostile;
mod security_source;
@@ -45,16 +45,13 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
);
assert_eq!(operation_list(&client, &base_url).await, before);
let secret = std::fs::read_to_string(root.join("hostile-secret.json")).unwrap();
let secret_plan = create_plan(&client, &base_url, &secret, full_plan()).await;
let exposed = format!("{}{}", secret_plan.preview, secret_plan.body);
assert!(
!exposed.contains("sk_test_corpus_secret_canary"),
"secret canary leaked into plan evidence"
);
assert_eq!(operation_list(&client, &base_url).await, before);
for file in ["hostile-malformed.json", "hostile-oversized.json"] {
// Credential-bearing sources are rejected before their original bytes
// can enter artifact storage, rather than producing a persisted plan.
for file in [
"hostile-secret.json",
"hostile-malformed.json",
"hostile-oversized.json",
] {
let source = std::fs::read(root.join(file)).unwrap();
let started = std::time::Instant::now();
let upload = reqwest::multipart::Part::bytes(source)
@@ -90,7 +87,7 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
// Real HTTP preview+plan: a root security requirement combined with an
// explicit empty operation override must leave the public operation
// actionable and block only the inherited one. No Apply mutation follows.
// actionable and leave the inherited one unresolved without a profile.
let mixed_security: Value = serde_json::json!({
"openapi": "3.0.3",
"info": { "title": "Mixed security plan probe", "version": "1" },
@@ -149,8 +146,8 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
);
assert_eq!(
secured["reason"].as_str(),
Some("unsupported_security_requirement"),
"secured candidate must expose the exact security blocker: {}",
Some("auth_profile_required"),
"secured candidate must expose its unresolved binding: {}",
security_plan.body
);
assert_eq!(
@@ -264,7 +261,7 @@ async fn p0_api_malformed_local_security_is_atomic_across_openapi_versions() {
.find(|item| item["key"] == "GET /public")
.unwrap();
assert_eq!(bad["state"], "blocked", "{version}: {}", plan.body);
assert_eq!(bad["reason"], "unsupported_security_requirement");
assert_eq!(bad["reason"], "invalid_security_requirements");
assert_eq!(public["state"], "actionable", "{version}: {}", plan.body);
assert!(public["reason"].is_null());
@@ -0,0 +1,184 @@
use super::*;
const SECURITY_SOURCE_A: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Api-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
const SECURITY_SOURCE_B: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Rotated-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn changed_security_scheme_invalidates_old_plan_before_draft_creation() {
let registry = test_registry().await;
let storage_root = test_storage_root("import_plan_security_source_change");
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "security-source-test-secret",
"kind": "token",
"value": { "token": "source-change-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let profile_response = client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": "security-source-test-profile",
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret["id"]
}}
}))
.send()
.await
.unwrap();
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
let profile: Value = profile_response.json().await.unwrap();
let plan = create_plan(
&client,
&base_url,
SECURITY_SOURCE_A,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /secure",
"action": "create",
"auth_profile_id": profile["id"]
}]
}),
)
.await;
assert_eq!(plan.body["candidates"][0]["auth_profile_id"], profile["id"]);
assert_eq!(plan.body["candidates"][0]["security_alternative_index"], 0);
let stored_plan = registry
.get_import_plan(
&crank_core::WorkspaceId::new("ws_default"),
&plan.reference.clone().into(),
)
.await
.unwrap()
.unwrap();
assert_eq!(
stored_plan.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
profile["id"],
"the old plan must persist its explicit profile binding"
);
assert_eq!(
stored_plan.payload["candidates"][0]["auth_requirement"]["parameter_name"],
"X-Api-Key"
);
// Register a second immutable source with only the security parameter
// changed. Its own upload/preview proves these are valid changed bytes,
// rather than corruption of the first content-addressed artifact.
let source_b_upload = reqwest::multipart::Part::bytes(SECURITY_SOURCE_B.as_bytes().to_vec())
.file_name("security-b.yaml")
.mime_str("application/yaml")
.unwrap();
let source_b_response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", source_b_upload))
.send()
.await
.unwrap();
assert_eq!(source_b_response.status(), reqwest::StatusCode::OK);
let source_b_preview: Value = source_b_response.json().await.unwrap();
assert_eq!(
source_b_preview["preview"]["groups"][0]["operations"][0]["security_schemes"]["apiKey"]["kind"]
["parameter_name"],
"X-Rotated-Key"
);
let workspace_id = crank_core::WorkspaceId::new("ws_default");
let original_job_id: crank_registry::ImportJobId =
plan.preview["job_id"].as_str().unwrap().into();
let changed_job_id: crank_registry::ImportJobId =
source_b_preview["job_id"].as_str().unwrap().into();
let original_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
let changed_job = registry
.get_import_job(&workspace_id, &changed_job_id)
.await
.unwrap()
.unwrap();
assert_ne!(
original_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"],
"the changed scheme must come from a different verified source artifact"
);
assert_eq!(
stored_plan.payload["source"]["digest"], original_job.preview_payload["source"]["digest"],
"the plan must remain anchored to source A"
);
// Simulate the existing new-source/re-preview condition on the anchored
// pending job while retaining its original plan. The replacement is a
// separately registered and digest-verified B snapshot; Apply must
// compare the newly derived fingerprint with the old plan fingerprint.
sqlx::query("update import_jobs set preview_payload = $3 where id = $1 and workspace_id = $2")
.bind(original_job_id.as_str())
.bind(workspace_id.as_str())
.bind(&changed_job.preview_payload)
.execute(registry.pool())
.await
.unwrap();
let replaced_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
assert_eq!(
replaced_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"]
);
let (status, error) = apply_plan(&client, &base_url, &plan, "security-source-changed").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"], "import_plan_fingerprint_stale",
"the old plan must require re-preview after source security changes"
);
assert_eq!(error["error"]["context"]["repreview_required"], true);
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
}
@@ -1,5 +1,21 @@
use super::*;
pub(crate) const OPENAPI_SINGLE_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Import security, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation() {
@@ -636,167 +652,6 @@ async fn exact_skip_rename_and_new_version_decisions_are_saved_verbatim() {
assert!(candidate.get("operation").is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn auth_profile_references_are_validated_stored_and_inherited() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret_token = "plan-secret-canary-2-13";
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-auth-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": secret_token }),
},
None,
)
.await
.unwrap();
let auth_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-auth-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile.id.as_str()),
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str()
);
// Only the reference survives: no secret material anywhere in the plan.
assert!(!stored.payload.to_string().contains(secret_token));
assert_eq!(
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
Some(auth_profile.id.as_str())
);
// An unknown profile reference fails closed in the workspace scope check.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"create",
None,
None,
Some("auth_missing_profile"),
)],
),
)
.await
.expect_err("an unknown auth profile reference must be rejected");
assert_error_code(&error, "operation_auth_profile_invalid");
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
// `new_version` without an explicit choice inherits the target's ref.
let existing = service
.create_operation(&workspace_id, {
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
payload.execution_config.auth_profile_ref =
Some(AuthProfileId::new(auth_profile.id.as_str()));
payload
})
.await
.expect("an existing operation with the candidate name");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["decision"]["auth_profile_id"],
auth_profile.id.as_str(),
"the inherited target reference is reflected in the candidate summary"
);
assert_eq!(
candidate["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str(),
"the inherited target reference must be retained in the snapshot"
);
assert!(!stored.payload.to_string().contains(secret_token));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn stale_or_terminal_jobs_preview_again_without_mutating_the_job() {
@@ -109,6 +109,7 @@ fn decision(
target_operation_id: target.map(ToOwned::to_owned),
confirmed_name: name.map(ToOwned::to_owned),
auth_profile_id: auth.map(ToOwned::to_owned),
security_alternative_index: None,
}
}
@@ -160,4 +161,7 @@ fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
}
mod creation;
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
mod security_availability;
mod security_binding;
mod validation;
@@ -0,0 +1,292 @@
use super::*;
const OPENAPI_SECURITY_BINDING: &str = r#"
openapi: 3.0.3
info: { title: Security binding availability, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
fn security_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: OPENAPI_SECURITY_BINDING.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn binding_decision(auth_profile_id: &str) -> OpenApiImportPlanDecision {
let mut binding = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile_id),
);
binding.security_alternative_index = Some(0);
binding
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn security_binding_refuses_foreign_and_unavailable_auth_material_before_draft() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_plan_security_availability"),
test_auth_settings(),
test_secret_crypto(),
);
let primary = WorkspaceId::new("ws_default");
let foreign = WorkspaceId::new("ws_security_foreign");
let created_at = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign.clone(),
slug: "ws-security-foreign".to_owned(),
display_name: "Foreign security workspace".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at,
updated_at: created_at,
},
})
.await
.unwrap();
let foreign_canary = "foreign-security-profile-canary";
let foreign_secret = service
.create_secret(
&foreign,
None,
SecretPayload {
name: "foreign-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": foreign_canary }),
},
None,
)
.await
.unwrap();
let foreign_profile = service
.create_auth_profile(
&foreign,
AuthProfilePayload {
name: "foreign-security-profile-name".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(foreign_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
// A foreign profile is absent from the current workspace's advertised
// choices and submission fails with a generic workspace-safe error.
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
let preview_text = serde_json::to_string(&preview).unwrap();
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!preview_text.contains(private_value),
"foreign profile metadata appeared in preview choices"
);
}
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != foreign_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let foreign_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(foreign_profile.id.as_str())],
),
)
.await
.expect_err("a profile from another workspace must not bind");
assert_error_code(&foreign_error, "import_plan_auth_unavailable");
let foreign_error_text = format!("{foreign_error:?}");
assert_http_status(foreign_error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!foreign_error_text.contains(private_value),
"foreign profile or secret metadata leaked: {foreign_error_text}"
);
}
// A previously valid local profile whose Secret is disabled is removed
// from choices and cannot be used in a newly confirmed ImportPlan.
let disabled_canary = "disabled-security-secret-canary";
let disabled_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "disabled-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": disabled_canary }),
},
None,
)
.await
.unwrap();
let disabled_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "disabled-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(disabled_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query(
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
)
.bind(primary.as_str())
.bind(disabled_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != disabled_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let disabled_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(disabled_profile.id.as_str())],
),
)
.await
.expect_err("a disabled linked Secret must reject the profile binding");
assert_error_code(&disabled_error, "secret_not_active");
let disabled_error_text = format!("{disabled_error:?}");
assert!(!disabled_error_text.contains(disabled_canary));
// A profile whose active Secret has no stored current version is equally
// unavailable. Direct SQL models the broken persisted reference while
// retaining the real Admin preview and plan validation paths.
let missing_version_canary = "missing-version-security-canary";
let missing_version_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "missing-version-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": missing_version_canary }),
},
None,
)
.await
.unwrap();
let missing_version_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "missing-version-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(missing_version_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query("delete from secret_versions where secret_id = $1 and version = 1")
.bind(missing_version_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != missing_version_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let missing_version_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(missing_version_profile.id.as_str())],
),
)
.await
.expect_err("a Secret without a current version must reject the profile binding");
assert_error_code(&missing_version_error, "operation_auth_profile_invalid");
let missing_version_error_text = format!("{missing_version_error:?}");
for private_value in [
missing_version_profile.id.as_str(),
missing_version_profile.name.as_str(),
missing_version_secret.id.as_str(),
missing_version_canary,
] {
assert!(
!missing_version_error_text.contains(private_value),
"missing-version Secret metadata leaked: {missing_version_error_text}"
);
}
assert!(
service.list_operations(&primary).await.unwrap().is_empty(),
"no unavailable profile binding may create a Draft"
);
}
@@ -0,0 +1,732 @@
use super::*;
const OPENAPI_SINGLE_PUBLIC: &str = r#"
openapi: 3.0.3
info: { title: Public import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
responses: { '200': { description: ok } }
"#;
const OPENAPI_SINGLE_EXPLICIT_NO_AUTH: &str = r#"
openapi: 3.0.3
info: { title: Explicit no auth import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
security: []
responses: { '200': { description: ok } }
"#;
const OPENAPI_BASIC_AND_QUERY_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Basic and query import, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Basic: { type: http, scheme: basic }
QueryKey: { type: apiKey, in: query, name: access_token }
paths:
/v2/basic:
get:
operationId: basicRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
/v2/query:
get:
operationId: queryRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn auth_profile_references_are_validated_stored_and_inherited() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret_token = "plan-secret-canary-2-13";
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-auth-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": secret_token }),
},
None,
)
.await
.unwrap();
let auth_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-auth-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let bearer_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-bearer-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "bearer-choice-canary" }),
},
None,
)
.await
.unwrap();
let bearer_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(bearer_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let selectable = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 0)
.expect("preview must expose choices for supported security alternatives");
assert!(selectable.profiles.iter().any(|choice| {
choice.id == auth_profile.id.as_str() && choice.kind == AuthKind::ApiKeyHeader
}));
assert!(
selectable
.profiles
.iter()
.all(|choice| { choice.id != bearer_profile.id.as_str() })
);
let bearer_choice = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 1)
.expect("preview must expose profile choices for the second OR alternative");
assert!(bearer_choice.profiles.iter().any(|choice| {
choice.id == bearer_profile.id.as_str() && choice.kind == AuthKind::Bearer
}));
assert!(
bearer_choice
.profiles
.iter()
.all(|choice| { choice.id != auth_profile.id.as_str() })
);
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut auth_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile.id.as_str()),
);
auth_decision.security_alternative_index = Some(0);
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![auth_decision]),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str()
);
assert_eq!(
stored.payload["candidates"][0]["decision"]["security_alternative_index"],
0
);
// Only the reference survives: no secret material anywhere in the plan.
assert!(!stored.payload.to_string().contains(secret_token));
assert_eq!(
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
Some(auth_profile.id.as_str())
);
let mut bearer_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(bearer_profile.id.as_str()),
);
bearer_decision.security_alternative_index = Some(1);
let bearer_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![bearer_decision]),
)
.await
.unwrap();
let stored_bearer = registry
.get_import_plan(&workspace_id, &bearer_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored_bearer.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
bearer_profile.id.as_str()
);
assert_eq!(
stored_bearer.payload["candidates"][0]["decision"]["security_alternative_index"],
1
);
assert!(
!stored_bearer
.payload
.to_string()
.contains("bearer-choice-canary")
);
// An unknown profile reference fails closed in the workspace scope check.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"create",
None,
None,
Some("auth_missing_profile"),
)],
),
)
.await
.expect_err("an unknown auth profile reference must be rejected");
assert_error_code(&error, "import_plan_auth_unavailable");
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
// `new_version` without an explicit choice inherits the target's ref.
let existing = service
.create_operation(&workspace_id, {
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
payload.execution_config.auth_profile_ref =
Some(AuthProfileId::new(auth_profile.id.as_str()));
payload
})
.await
.expect("an existing operation with the candidate name");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["decision"]["auth_profile_id"],
auth_profile.id.as_str(),
"the inherited target reference is reflected in the candidate summary"
);
assert_eq!(
candidate["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str(),
"the inherited target reference must be retained in the snapshot"
);
assert!(!stored.payload.to_string().contains(secret_token));
let public_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_PUBLIC))
.await
.unwrap();
let public_job_id: ImportJobId = public_preview.job_id.as_str().into();
let public_plan = service
.create_openapi_import_plan(
&workspace_id,
&public_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("a no-security source may inherit the target's existing profile");
let public_stored = registry
.get_import_plan(&workspace_id, &public_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
public_stored.payload["candidates"][0]["auth_requirement"]["kind"], "unconstrained",
"no source security declaration is represented explicitly for transactional Apply"
);
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(public_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: public_plan.plan_digest.clone(),
idempotency_key: "new-version-inherited-public".to_owned(),
},
)
.await
.expect("Apply must retain profile and Secret transactional validation");
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
assert_eq!(
report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(report.outcomes[0].version, Some(2));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 2);
let explicit_no_auth_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_EXPLICIT_NO_AUTH))
.await
.unwrap();
let explicit_no_auth_job_id: ImportJobId = explicit_no_auth_preview.job_id.as_str().into();
let incompatible_profile_decision = decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
Some(auth_profile.id.as_str()),
);
let error = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload("full", vec![], vec![incompatible_profile_decision]),
)
.await
.expect_err("explicit Auth Profile stays incompatible with security: []");
assert_error_code(&error, "import_plan_auth_incompatible");
let explicit_no_auth_plan = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("an explicit empty security requirement clears inherited auth");
let no_auth_stored = registry
.get_import_plan(
&workspace_id,
&explicit_no_auth_plan.plan_reference.as_str().into(),
)
.await
.unwrap()
.unwrap();
assert!(no_auth_stored.payload["candidates"][0]["operation"]["execution_config"]
["auth_profile_ref"]
.is_null());
let no_auth_report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(explicit_no_auth_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: explicit_no_auth_plan.plan_digest.clone(),
idempotency_key: "new-version-explicit-no-auth".to_owned(),
},
)
.await
.expect("explicit no-auth new_version applies without inherited credentials");
assert_eq!(
no_auth_report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(no_auth_report.outcomes[0].version, Some(3));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 3);
let operation_id = OperationId::new(existing.operation_id.clone());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 3)
.await
.unwrap()
.unwrap();
assert!(version.snapshot.execution_config.auth_profile_ref.is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_apply() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_basic_query_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let username_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-username".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-user" }),
},
None,
)
.await
.unwrap();
let password_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-password".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-password-canary" }),
},
None,
)
.await
.unwrap();
let basic_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "basic-profile".to_owned(),
kind: AuthKind::Basic,
config: AuthConfig::Basic(crank_core::BasicAuthConfig {
username_secret_id: SecretId::new(username_secret.id.as_str()),
password_secret_id: SecretId::new(password_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let query_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "query-key".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "query-key-canary" }),
},
None,
)
.await
.unwrap();
let query_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "query-profile".to_owned(),
kind: AuthKind::ApiKeyQuery,
config: AuthConfig::ApiKeyQuery(crank_core::ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new(query_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let incompatible_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "incompatible-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "incompatible-canary" }),
},
None,
)
.await
.unwrap();
let incompatible_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "incompatible-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(incompatible_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
.await
.unwrap();
for operation_key in ["GET /v2/basic", "GET /v2/query"] {
let basic_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 0)
.expect("Basic alternative must be represented in preview");
assert!(basic_alternative.profiles.iter().any(|choice| {
choice.id == basic_profile.id.as_str() && choice.kind == AuthKind::Basic
}));
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != query_profile.id.as_str())
);
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
let query_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 1)
.expect("query alternative must be represented in preview");
assert!(query_alternative.profiles.iter().any(|choice| {
choice.id == query_profile.id.as_str() && choice.kind == AuthKind::ApiKeyQuery
}));
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != basic_profile.id.as_str())
);
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
}
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut basic_decision = decision(
"GET /v2/basic",
"create",
None,
None,
Some(basic_profile.id.as_str()),
);
basic_decision.security_alternative_index = Some(0);
let basic_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/basic".to_owned()],
vec![basic_decision],
),
)
.await
.unwrap();
assert_eq!(basic_plan.counts.actionable, 1);
let basic_candidate = basic_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/basic")
.unwrap();
assert_eq!(
basic_candidate.auth_profile_id.as_deref(),
Some(basic_profile.id.as_str())
);
let mut query_decision = decision(
"GET /v2/query",
"create",
None,
None,
Some(query_profile.id.as_str()),
);
query_decision.security_alternative_index = Some(1);
let query_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision],
),
)
.await
.unwrap();
assert_eq!(query_plan.counts.actionable, 1);
let query_candidate = query_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/query")
.unwrap();
assert_eq!(
query_candidate.auth_profile_id.as_deref(),
Some(query_profile.id.as_str())
);
for (plan, expected_profile, idempotency_key) in [
(
&basic_plan,
basic_profile.id.as_str(),
"apply-basic-profile",
),
(
&query_plan,
query_profile.id.as_str(),
"apply-query-profile",
),
] {
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest.clone(),
idempotency_key: idempotency_key.to_owned(),
},
)
.await
.unwrap();
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
let operation_id = OperationId::new(report.outcomes[0].operation_id.clone().unwrap());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 1)
.await
.unwrap()
.unwrap();
assert_eq!(
version
.snapshot
.execution_config
.auth_profile_ref
.as_ref()
.map(|profile_id| profile_id.as_str()),
Some(expected_profile)
);
}
let basic_stored = registry
.get_import_plan(&workspace_id, &basic_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!basic_stored
.payload
.to_string()
.contains("plan-password-canary")
);
let query_stored = registry
.get_import_plan(&workspace_id, &query_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!query_stored
.payload
.to_string()
.contains("query-key-canary")
);
}