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()))] pub async fn create_openapi_import_plan( &self, workspace_id: &WorkspaceId, job_id: &ImportJobId, payload: OpenApiImportPlanCreatePayload, ) -> Result { self.ensure_workspace_exists(workspace_id).await?; let now = OffsetDateTime::now_utc(); let job = self .registry .get_import_job(workspace_id, job_id) .await? .ok_or_else(|| { ApiError::not_found_with_context( "import job was not found", json!({ "job_id": job_id.as_str() }), ) })?; if job.kind != ImportJobKind::OpenApi { return Err(ApiError::validation("import job kind is not openapi")); } if job.expires_at <= now { return Err(ApiError::validation("import preview has expired")); } if job.status != ImportJobStatus::Pending { return Err(import_plan_repreview_error("import_plan_job_terminal")); } if payload.decisions.len() > MAX_IMPORT_PLAN_KEYS { return Err(ApiError::validation( "too many decision blocks for this import plan", )); } if payload.server_url.as_deref().is_some_and(|server_url| { server_url.is_empty() || server_url.len() > MAX_IMPORT_PLAN_SERVER_URL_BYTES }) { return Err(ApiError::validation_with_context( "server_url is empty or too long", json!({ "error_code": "import_plan_invalid_input" }), )); } // The plan is anchored to the verified job snapshots. A stale or // corrupt preview is reported as bounded re-preview guidance and // never mutates the job: other stored plans may still reference the // same job and its replay must remain readable. let resolved = self .resolve_verified_openapi_preview(workspace_id, &job, OpenApiUploadLocale::En) .await .map_err(|resolution| match resolution { ImportPreviewResolution::Fatal(error_code, _) => { import_plan_repreview_error(error_code) } ImportPreviewResolution::NonFatal(error) => error, })?; let preview = &resolved.preview; // Stored external dependency snapshots are re-verified for every // replay variant (including historically persisted ones) without a // network fetch: detached or altered snapshots are re-preview // material and no plan is created. self.read_import_job_dependencies( workspace_id, &job.preview_payload, OpenApiUploadLocale::En, ) .await .map_err(|_| import_plan_repreview_error("import_dependency_verification_failed"))?; let candidates: BTreeMap = preview .groups .iter() .flat_map(|group| group.operations.iter()) .map(|operation| (operation.key.clone(), operation)) .collect(); let all_set: BTreeSet = candidates.keys().cloned().collect(); let selected = resolve_plan_selection( &payload.selection_mode, &payload.selected_operation_keys, &all_set, )?; if selected.len() > MAX_IMPORT_PLAN_KEYS || all_set.len() - selected.len() > MAX_IMPORT_PLAN_KEYS { return Err(ApiError::validation_with_context( "too many candidates for an import plan", json!({ "error_code": "import_plan_invalid_input" }), )); } let selected_keys: Vec = selected.iter().cloned().collect(); let excluded: Vec = all_set .iter() .filter(|key| !selected.contains(*key)) .cloned() .collect(); let decisions = validate_plan_decisions(&payload.decisions, &selected)?; let global_blocker = preview .findings .iter() .find(|finding| { finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none() }) .map(|finding| finding.code.clone()); let mut planned = Vec::with_capacity(selected_keys.len()); for key in &selected_keys { let Some(candidate) = candidates.get(key) else { unreachable!("selection is validated against the candidate set"); }; let blocker = global_blocker.clone().or_else(|| { candidate .findings .iter() .find(|finding| finding.severity == ImportFindingSeverity::Error) .map(|finding| finding.code.clone()) }); let candidate_plan = self .plan_import_candidate( workspace_id, payload.server_url.as_deref(), key, candidate, decisions.get(key).copied(), blocker, ) .await?; planned.push(candidate_plan); } let counts = OpenApiImportPlanCounts { selected: planned.len(), excluded: excluded.len(), actionable: planned .iter() .filter(|candidate| !candidate.blocked) .count(), blocked: planned.iter().filter(|candidate| candidate.blocked).count(), }; // Server-authored immutable plan. Client-supplied candidate material, // digests or payload fields are not read: every value below derives // from the verified job preview and the revalidated decisions. let all_keys: Vec = all_set.iter().cloned().collect(); let plan_counts_value = json!({ "selected": counts.selected, "excluded": counts.excluded, "actionable": counts.actionable, "blocked": counts.blocked, }); let plan_reference = new_prefixed_id("plan"); let plan_payload = json!({ "schema_version": "import-plan-v1", "plan_reference": plan_reference, "job_id": job_id.as_str(), "server_url": payload.server_url, "source": { "source_id": resolved.source.source_id.as_str(), "digest": resolved.source.digest.as_str(), }, "dependencies": job.preview_payload.get("dependencies").cloned().unwrap_or(json!([])), "fingerprint": resolved.fingerprint, "selection": { "mode": payload.selection_mode, "all": all_keys, "selected": selected_keys, "excluded": excluded, }, "counts": plan_counts_value, "candidates": planned.iter().map(plan_candidate_payload).collect::, _>>()?, }); let plan_reference_id = ImportPlanId::new(&plan_reference); let created = self .registry .create_import_plan(CreateImportPlanRequest { id: &plan_reference_id, workspace_id, job_id, payload: &plan_payload, created_at: &now, expires_at: &job.expires_at, }) .await .map_err(ApiError::from)?; let mut candidate_views: Vec = planned .iter() .map(|candidate| OpenApiImportPlanCandidateView { key: candidate.key.clone(), name: candidate.name.clone(), state: if candidate.blocked { "blocked" } else { "actionable" } .to_owned(), action: Some(candidate.action.clone()), 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(); candidate_views.extend(excluded.iter().map(|key| { let name = candidates .get(key) .map(|candidate| candidate.draft.name.clone()) .unwrap_or_default(); OpenApiImportPlanCandidateView { key: key.clone(), name, state: "excluded".to_owned(), action: None, target_operation_id: None, confirmed_name: None, auth_profile_id: None, security_alternative_index: None, reason: Some("not_selected".to_owned()), } })); Ok(OpenApiImportPlanCreateResponse { plan_reference: created.id.as_str().to_owned(), plan_digest: created.digest, expires_at: created .expires_at .format(&Rfc3339) .map_err(|error| ApiError::internal(error.to_string()))?, selection_mode: payload.selection_mode, counts, candidates: candidate_views, }) } /// Materializes one selected candidate of the plan: the confirmed /// decision, the exact authorized target with its expected state and the /// full Draft snapshot (create/rename/new_version) or the bounded /// redacted rejection reason (blocked). async fn plan_import_candidate( &self, workspace_id: &WorkspaceId, server_url: Option<&str>, key: &str, candidate: &ImportOperationCandidate, decision: Option<&OpenApiImportPlanDecision>, blocker_reason: Option, ) -> Result { let action = decision .map(|decision| decision.action.as_str()) .unwrap_or("create"); let target_operation_id = 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 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 // protocol is a request error even when the candidate is already // blocked. let mut target = None; let mut target_summary = None; let mut next_version: Option = None; if matches!(action, "skip" | "new_version") { let target_id = target_operation_id .as_ref() .expect("target_operation_id is validated for skip/new_version") .clone(); let target_operation = OperationId::new(target_id.clone()); let summary = self .registry .get_operation_summary(workspace_id, &target_operation) .await? .ok_or_else(|| { ApiError::validation_with_context( "decision target operation was not found in this workspace", json!({ "target_operation_id": target_id, "error_code": "import_plan_target_invalid" }), ) })?; if summary.name != candidate_name { return Err(ApiError::validation_with_context( "decision target does not match the candidate name in this workspace", json!({ "target_operation_id": target_id, "error_code": "import_plan_target_invalid" }), )); } if action == "new_version" && (summary.protocol != Protocol::Rest || summary.status == OperationStatus::Archived) { return Err(ApiError::validation_with_context( "new_version target must be an active REST operation", json!({ "target_operation_id": target_id, "error_code": "import_plan_target_invalid" }), )); } target = Some(json!({ "operation_id": target_id, "name": summary.name, "expected_state": { "status": serde_json::to_value(summary.status) .map_err(|error| ApiError::internal(error.to_string()))?, "current_draft_version": summary.current_draft_version, "latest_published_version": summary.latest_published_version, }, })); if action == "new_version" { let version = summary .current_draft_version .checked_add(1) .filter(|value| i32::try_from(*value).is_ok()) .ok_or_else(|| { ApiError::conflict_with_context( "operation revision limit reached", json!({ "error_code": "operation_revision_exhausted" }), ) })?; next_version = Some(version); } target_summary = Some(summary); } // create/rename must land on a name that is free now; the server // never auto-selects a replacement when the confirmed name is taken. if !blocked && matches!(action, "create" | "rename") { let final_name = confirmed_name.as_deref().unwrap_or(candidate_name.as_str()); if self .find_operation_by_name(workspace_id, final_name) .await? .is_some() { if action == "create" && decision.is_none() { return Ok(PlannedCandidate { key: key.to_owned(), name: candidate_name, blocked: true, reason: Some("operation_name_conflict".to_owned()), action: action.to_owned(), target_operation_id, confirmed_name, auth_profile_id, security_alternative_index: requested_security_alternative, auth_requirement: None, auth_snapshot: None, target: None, operation: None, }); } return Err(ApiError::conflict_with_context( format!("operation with name {final_name} already exists"), json!({ "name": final_name, "error_code": "import_plan_name_conflict", "recovery": "confirm_skip_rename_or_new_version" }), )); } } // 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 .get_operation_version(workspace_id, &summary.id, summary.current_draft_version) .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 { key: key.to_owned(), name: candidate_name, blocked: true, reason: blocker_reason, action: action.to_owned(), target_operation_id, confirmed_name, auth_profile_id, security_alternative_index, auth_requirement, auth_snapshot: None, target, operation: None, }); } if action == "skip" { return Ok(PlannedCandidate { key: key.to_owned(), name: candidate_name, blocked: false, reason: None, action: action.to_owned(), target_operation_id, confirmed_name, auth_profile_id, security_alternative_index, auth_requirement: None, auth_snapshot: None, target, operation: None, }); } let mut draft = operation_draft_from_candidate(candidate, server_url); if action == "rename" { draft.name = confirmed_name .clone() .expect("rename decisions carry the exact confirmed_name"); } attach_import_findings(&mut draft, candidate); let operation = self.new_operation_snapshot(OperationPayload { name: draft.name.clone(), display_name: draft.display_name.clone(), category: draft.category, protocol: Protocol::Rest, security_level: OperationSecurityLevel::Standard, target: crank_core::Target::Rest(draft.target), input_schema: draft.input_schema, output_schema: draft.output_schema, input_mapping: draft.input_mapping, output_mapping: draft.output_mapping, execution_config: ExecutionConfig { timeout_ms: 10_000, retry_policy: None, response_cache: None, idempotency: None, safety: None, approval_policy: None, auth_profile_ref, headers: BTreeMap::new(), }, tool_description: draft.tool_description, wizard_state: draft.wizard_state, })?; // The same workspace/auth secret validator the operation creation // path uses: the referenced profile and its active secret refs must // resolve in this workspace before the plan is accepted. self.validate_registry_operation_in_workspace(workspace_id, &operation) .await?; let mut operation = operation; if action == "new_version" { let target_id = target_operation_id .clone() .expect("new_version decisions carry target_operation_id"); operation.id = OperationId::new(target_id); operation.version = next_version.expect("new_version computes the next Draft version"); } let auth_snapshot = match operation.execution_config.auth_profile_ref.as_ref() { Some(profile_id) => Some(self.import_auth_snapshot(workspace_id, profile_id).await?), None => None, }; Ok(PlannedCandidate { key: key.to_owned(), name: draft.name, blocked: false, reason: None, action: action.to_owned(), target_operation_id, confirmed_name, auth_profile_id, security_alternative_index, auth_requirement, auth_snapshot, target, operation: Some(operation), }) } /// Captures only profile configuration and secret metadata. Credential /// values never enter the plan; Apply compares this snapshot under locks. async fn import_auth_snapshot( &self, workspace_id: &WorkspaceId, profile_id: &AuthProfileId, ) -> Result { 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) .await? .ok_or_else(unavailable)?; let mut secret_ids: Vec = profile .config .secret_ids() .into_iter() .map(|id| id.as_str().to_owned()) .collect(); secret_ids.sort(); secret_ids.dedup(); let mut secrets = Vec::with_capacity(secret_ids.len()); for id in secret_ids { let secret = self .registry .get_secret(workspace_id, &crank_core::SecretId::new(id.clone())) .await? .ok_or_else(unavailable)? .secret; secrets.push(json!({ "id": id, "status": secret.status, "current_version": secret.current_version, "updated_at": secret.updated_at.format(&Rfc3339) .map_err(|error| ApiError::internal(error.to_string()))?, })); } Ok(json!({ "profile_id": profile_id.as_str(), "name": profile.name, "kind": profile.kind, "config": profile.config, "updated_at": profile.updated_at.format(&Rfc3339) .map_err(|error| ApiError::internal(error.to_string()))?, "secrets": secrets, })) } } struct PlannedCandidate { key: String, name: String, blocked: bool, reason: Option, action: String, target_operation_id: Option, confirmed_name: Option, auth_profile_id: Option, security_alternative_index: Option, auth_requirement: Option, auth_snapshot: Option, target: Option, operation: Option, } pub(super) fn import_plan_repreview_error(error_code: &'static str) -> ApiError { ApiError::conflict_with_context( "import plan revalidation failed; create a fresh preview", json!({ "error_code": error_code, "recovery": "repreview_required", "repreview_required": true }), ) } /// Closes the selection against the current preview: `full` keeps every /// candidate (an explicit list must equal the whole candidate set), `partial` /// requires a non-empty exact subset. Unknown or duplicate keys are rejected /// before any plan material exists. fn resolve_plan_selection( selection_mode: &str, requested: &[String], all: &BTreeSet, ) -> Result, ApiError> { if !matches!(selection_mode, "full" | "partial") { return Err(ApiError::validation_with_context( "selection_mode must be full or partial", json!({ "error_code": "import_plan_invalid_input" }), )); } if requested.len() > MAX_IMPORT_PLAN_KEYS { return Err(ApiError::validation_with_context( "too many selected_operation_keys for this import plan", json!({ "error_code": "import_plan_invalid_input" }), )); } for key in requested { if key.is_empty() || key.len() > MAX_IMPORT_PLAN_KEY_BYTES { return Err(ApiError::validation_with_context( "selected_operation_keys entries are empty or too long", json!({ "error_code": "import_plan_invalid_input" }), )); } } let requested_set: BTreeSet<&String> = requested.iter().collect(); if requested_set.len() != requested.len() { return Err(ApiError::validation_with_context( "selected_operation_keys contains duplicates", json!({ "error_code": "import_plan_invalid_input" }), )); } let all_set: BTreeSet<&String> = all.iter().collect(); match selection_mode { "full" => { if !requested_set.is_empty() && requested_set != all_set { return Err(ApiError::validation_with_context( "full selection covers the entire candidate set; selected_operation_keys does not match the preview", json!({ "error_code": "import_plan_selection_mismatch" }), )); } Ok(all.clone()) } _ => { if requested_set.is_empty() { return Err(ApiError::validation_with_context( "partial selection requires at least one selected_operation_key", json!({ "error_code": "import_plan_invalid_input" }), )); } if !requested_set.is_subset(&all_set) { return Err(ApiError::validation_with_context( "selected_operation_keys reference operations absent from the preview", json!({ "error_code": "import_plan_unknown_operation_key" }), )); } Ok(requested.iter().cloned().collect()) } } } /// Binds decisions to selected candidates with action-specific field rules: /// unknown/duplicate keys, foreign fields and oversized references are /// rejected before the plan is materialized. fn validate_plan_decisions<'input>( decisions: &'input [OpenApiImportPlanDecision], selected: &BTreeSet, ) -> Result, ApiError> { let invalid = |context: Value| { Err(ApiError::validation_with_context( "import plan decision is invalid", context, )) }; let mut mapping = BTreeMap::new(); for decision in decisions { if decision.operation_key.is_empty() || decision.operation_key.len() > MAX_IMPORT_PLAN_KEY_BYTES { return invalid(json!({ "operation_key": decision.operation_key, "error_code": "import_plan_invalid_input" })); } if !matches!( decision.action.as_str(), "create" | "skip" | "rename" | "new_version" ) { return invalid(json!({ "operation_key": decision.operation_key, "error_code": "import_plan_invalid_input" })); } validate_decision_fields(decision)?; if !selected.contains(&decision.operation_key) { return invalid(json!({ "operation_key": decision.operation_key, "error_code": "import_plan_decision_unselected" })); } if mapping .insert(decision.operation_key.clone(), decision) .is_some() { return invalid(json!({ "operation_key": decision.operation_key, "error_code": "import_plan_invalid_input" })); } } Ok(mapping) } fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(), ApiError> { let context = json!({ "operation_key": decision.operation_key, "error_code": "import_plan_invalid_input" }); let invalid = |message: &str| -> Result<(), ApiError> { Err(ApiError::validation_with_context(message, context.clone())) }; if decision .target_operation_id .as_deref() .is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES) { return invalid("decision target_operation_id is empty or too long"); } if decision .confirmed_name .as_deref() .is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_NAME_BYTES) { return invalid("decision confirmed_name is empty or too long"); } if decision .auth_profile_id .as_deref() .is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES) { 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() { return invalid( "target_operation_id and confirmed_name are not allowed for action create", ); } } "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"); } if decision.confirmed_name.is_some() { return invalid("confirmed_name is not allowed for action skip"); } } "rename" => { if decision.target_operation_id.is_some() { return invalid("target_operation_id is not allowed for action rename"); } if decision.confirmed_name.is_none() { return invalid("action rename requires the exact confirmed_name"); } } "new_version" => { if decision.target_operation_id.is_none() { return invalid("action new_version requires the exact target_operation_id"); } if decision.confirmed_name.is_some() { return invalid("confirmed_name is not allowed for action new_version"); } } _ => unreachable!("decision action is validated before the field rules"), } Ok(()) } async fn resolve_security_binding( service: &AdminService, workspace_id: &WorkspaceId, candidate: &ImportOperationCandidate, profile_ref: Option<&AuthProfileId>, requested_index: Option, blocker_reason: &mut Option, ) -> Result, 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::>(); 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 /// server-authored Draft snapshot. fn plan_candidate_payload(candidate: &PlannedCandidate) -> Result { let mut object = json!({ "key": candidate.key, "name": candidate.name, "state": if candidate.blocked { "blocked" } else { "actionable" }, "decision": { "action": candidate.action, "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 { object["reason"] = json!(reason); } if let Some(target) = &candidate.target { object["target"] = target.clone(); } 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()))?; object["operation"] = value; } Ok(object) }