feat(import): bind OpenAPI security schemes safely
This commit is contained in:
1 parent
c562d5368d
commit
41a0e46110
38 files changed
+4651
-590
No files matched your search
@@ -542,17 +542,48 @@ pub struct OpenApiImportPreviewResponse {
|
||||
pub job_id: String,
|
||||
pub expires_at: String,
|
||||
pub preview: crank_import::rest::ImportPreview,
|
||||
/// Compatible Auth Profiles visible to the current workspace, grouped by
|
||||
/// operation and security alternative. Profile credentials are never
|
||||
/// included.
|
||||
pub auth_profile_choices: Vec<OpenApiAuthProfileChoice>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiAuthProfileChoice {
|
||||
pub operation_key: String,
|
||||
pub alternative_index: usize,
|
||||
pub scheme_names: Vec<String>,
|
||||
pub supported: bool,
|
||||
pub profiles: Vec<OpenApiAuthProfileOption>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiAuthProfileOption {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: AuthKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct OpenApiImportCreatePayload {
|
||||
pub selected_operation_keys: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub auth_mappings: Vec<OpenApiAuthMapping>,
|
||||
#[serde(default)]
|
||||
pub server_url: Option<String>,
|
||||
#[serde(default = "default_openapi_conflict_mode")]
|
||||
pub conflict_mode: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct OpenApiAuthMapping {
|
||||
pub operation_key: String,
|
||||
pub alternative_index: usize,
|
||||
/// `None` is an explicit unresolved mapping. It is never actionable for a
|
||||
/// required authentication alternative.
|
||||
pub auth_profile_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiImportCreateResponse {
|
||||
pub created: Vec<OpenApiImportCreatedOperation>,
|
||||
|
||||
@@ -135,6 +135,41 @@ impl ApiError {
|
||||
"OpenAPI document is invalid or unsupported"
|
||||
}
|
||||
}
|
||||
(_, "literal_credentials_rejected") => {
|
||||
if russian {
|
||||
"документ OpenAPI содержит literal credential и отклонён"
|
||||
} else {
|
||||
"OpenAPI document contains literal credential material and was rejected"
|
||||
}
|
||||
}
|
||||
(_, "auth_mapping_required") => {
|
||||
if russian {
|
||||
"для требования аутентификации выберите доступный профиль"
|
||||
} else {
|
||||
"an available Auth Profile mapping is required for this authentication requirement"
|
||||
}
|
||||
}
|
||||
(_, "auth_mapping_unsupported") => {
|
||||
if russian {
|
||||
"это требование аутентификации не поддерживается импортом"
|
||||
} else {
|
||||
"this authentication requirement is not supported by import"
|
||||
}
|
||||
}
|
||||
(_, "auth_mapping_invalid") => {
|
||||
if russian {
|
||||
"привязка аутентификации в запросе импорта некорректна"
|
||||
} else {
|
||||
"OpenAPI import authentication mapping is invalid"
|
||||
}
|
||||
}
|
||||
(_, "auth_binding_unavailable") => {
|
||||
if russian {
|
||||
"выбранный профиль аутентификации недоступен для этого импорта"
|
||||
} else {
|
||||
"selected Auth Profile is unavailable for this import"
|
||||
}
|
||||
}
|
||||
(_, "no_methods") => {
|
||||
if russian {
|
||||
"документ OpenAPI не содержит поддерживаемых методов"
|
||||
@@ -195,6 +230,18 @@ impl ApiError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn openapi_auth_binding_unavailable(locale: OpenApiUploadLocale) -> Self {
|
||||
let message = if locale == OpenApiUploadLocale::Ru {
|
||||
"выбранный профиль аутентификации недоступен для этого импорта"
|
||||
} else {
|
||||
"selected Auth Profile is unavailable for this import"
|
||||
};
|
||||
Self::unprocessable_with_context(
|
||||
message,
|
||||
json!({ "error_code": "openapi_auth_binding_unavailable" }),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn rate_limited_with_context(message: impl Into<String>, context: Value) -> Self {
|
||||
Self::RateLimited {
|
||||
message: message.into(),
|
||||
@@ -675,6 +722,10 @@ impl From<RegistryError> for ApiError {
|
||||
"value": value,
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportAuthBindingUnavailable => Self::unprocessable_with_context(
|
||||
"selected Auth Profile is unavailable for this import",
|
||||
json!({ "error_code": "openapi_auth_binding_unavailable" }),
|
||||
),
|
||||
RegistryError::YamlImportJobNotFound { job_id } => Self::validation_with_context(
|
||||
format!("yaml import job {job_id} was not found"),
|
||||
json!({ "job_id": job_id }),
|
||||
|
||||
@@ -12,8 +12,8 @@ use crank_import::rest::{
|
||||
use crank_registry::{
|
||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
|
||||
ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind, ImportJobSourceEnvelope,
|
||||
ImportJobStatus, ImportOperationDraft, RegistryError,
|
||||
ImportAuthRequirement, ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, RegistryError,
|
||||
};
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -23,7 +23,7 @@ use tracing::{info, instrument};
|
||||
use crate::{
|
||||
error::ApiError,
|
||||
service::{
|
||||
AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
|
||||
AdminService, OpenApiAuthMapping, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
|
||||
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
|
||||
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
||||
},
|
||||
@@ -31,6 +31,7 @@ use crate::{
|
||||
|
||||
mod external_references;
|
||||
mod job_contract;
|
||||
mod security;
|
||||
use external_references::ImportReplayContext;
|
||||
use job_contract::{
|
||||
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
|
||||
@@ -52,6 +53,14 @@ impl AdminService {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
|
||||
validate_openapi_upload(&upload)?;
|
||||
let literal_findings = crank_import::rest::scan_secret_literals(&upload.bytes)
|
||||
.map_err(|_| ApiError::openapi_upload(upload.locale, "invalid_document"))?;
|
||||
if !literal_findings.is_empty() {
|
||||
return Err(ApiError::openapi_upload(
|
||||
upload.locale,
|
||||
"literal_credentials_rejected",
|
||||
));
|
||||
}
|
||||
let OpenApiUpload {
|
||||
bytes,
|
||||
mime_type,
|
||||
@@ -105,6 +114,14 @@ impl AdminService {
|
||||
let mut dependencies = self
|
||||
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
|
||||
.await;
|
||||
if dependencies.secret_literal_rejected {
|
||||
dependencies.detach_all().await;
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::openapi_upload(
|
||||
locale,
|
||||
"literal_credentials_rejected",
|
||||
));
|
||||
}
|
||||
let parsed = match parse_verified_preview(
|
||||
verified.bytes,
|
||||
artifact.artifact_ref().digest_hex().to_owned(),
|
||||
@@ -132,6 +149,17 @@ impl AdminService {
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::openapi_upload(locale, "no_methods"));
|
||||
}
|
||||
let auth_profile_choices = match self
|
||||
.openapi_auth_profile_choices(workspace_id, &parsed.preview)
|
||||
.await
|
||||
{
|
||||
Ok(choices) => choices,
|
||||
Err(error) => {
|
||||
dependencies.detach_all().await;
|
||||
detach_guard.detach_now().await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let source_envelope = ImportJobSourceEnvelope {
|
||||
source_id,
|
||||
digest: artifact.artifact_ref().clone(),
|
||||
@@ -184,6 +212,7 @@ impl AdminService {
|
||||
expires_at: expires_at
|
||||
.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
auth_profile_choices,
|
||||
preview: parsed.preview,
|
||||
})
|
||||
}
|
||||
@@ -247,6 +276,15 @@ impl AdminService {
|
||||
));
|
||||
}
|
||||
let finished_at = OffsetDateTime::now_utc();
|
||||
let mut auth_mappings = BTreeMap::new();
|
||||
for mapping in &payload.auth_mappings {
|
||||
if auth_mappings
|
||||
.insert(mapping.operation_key.clone(), mapping)
|
||||
.is_some()
|
||||
{
|
||||
return Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"));
|
||||
}
|
||||
}
|
||||
let application_key = openapi_application_key(&payload)?;
|
||||
let conflict_mode = if payload.conflict_mode == "skip" {
|
||||
ImportConflictMode::Skip
|
||||
@@ -425,6 +463,20 @@ impl AdminService {
|
||||
candidates.insert(operation.key.clone(), operation);
|
||||
}
|
||||
}
|
||||
if auth_mappings.iter().any(|(operation_key, mapping)| {
|
||||
!selected.contains(operation_key)
|
||||
|| candidates.get(operation_key).is_none_or(|candidate| {
|
||||
mapping.alternative_index >= candidate.security_requirements.alternatives.len()
|
||||
})
|
||||
}) {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"auth_mapping_invalid",
|
||||
ApiError::openapi_upload(locale, "auth_mapping_invalid"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let mut skipped = Vec::new();
|
||||
let mut operations = Vec::new();
|
||||
@@ -438,6 +490,26 @@ impl AdminService {
|
||||
});
|
||||
continue;
|
||||
};
|
||||
let (auth_profile_ref, auth_requirement) = match self
|
||||
.resolve_openapi_auth_binding(
|
||||
workspace_id,
|
||||
candidate,
|
||||
auth_mappings.get(&operation_key).copied(),
|
||||
locale,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(binding) => binding,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"auth_binding_unavailable",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let mut draft =
|
||||
operation_draft_from_candidate(candidate, payload.server_url.as_deref());
|
||||
attach_import_findings(&mut draft, candidate);
|
||||
@@ -459,7 +531,7 @@ impl AdminService {
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref: None,
|
||||
auth_profile_ref,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: draft.tool_description,
|
||||
@@ -468,6 +540,7 @@ impl AdminService {
|
||||
operations.push(ImportOperationDraft {
|
||||
operation_key: candidate.key.clone(),
|
||||
operation,
|
||||
auth_requirement,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -482,7 +555,13 @@ impl AdminService {
|
||||
pre_skipped: &skipped,
|
||||
finished_at: &finished_at,
|
||||
})
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
RegistryError::ImportAuthBindingUnavailable => {
|
||||
ApiError::openapi_auth_binding_unavailable(locale)
|
||||
}
|
||||
error => error.into(),
|
||||
})?;
|
||||
|
||||
Ok(openapi_import_response(applied))
|
||||
}
|
||||
@@ -639,11 +718,13 @@ fn import_replay_contract(
|
||||
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
|
||||
return Ok(ImportReplayContract::Current);
|
||||
}
|
||||
// Historical preview payloads are replayed as their persisted projection.
|
||||
// They must never be parsed again with the current v4 semantics.
|
||||
// Historical v2-v4 preview payloads are replayed as their persisted
|
||||
// projection. They must never be parsed again with current v5 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"));
|
||||
}
|
||||
@@ -817,7 +898,15 @@ fn preview_has_blocker(
|
||||
.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(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& !matches!(
|
||||
finding.code.as_str(),
|
||||
"unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unresolved_security_scheme"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<String, ApiError> {
|
||||
@@ -826,8 +915,15 @@ fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<Strin
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut auth_mappings = payload.auth_mappings.clone();
|
||||
auth_mappings.sort_by(|left, right| {
|
||||
left.operation_key
|
||||
.cmp(&right.operation_key)
|
||||
.then(left.alternative_index.cmp(&right.alternative_index))
|
||||
});
|
||||
let canonical = serde_json::to_vec(&json!({
|
||||
"selected_operation_keys": selected_operation_keys,
|
||||
"auth_mappings": auth_mappings,
|
||||
"server_url": payload.server_url.as_deref(),
|
||||
"conflict_mode": payload.conflict_mode.as_str(),
|
||||
}))
|
||||
|
||||
@@ -4,6 +4,7 @@ use tracing::warn;
|
||||
|
||||
pub(super) struct MaterializedDependencies {
|
||||
pub(super) snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
|
||||
pub(super) secret_literal_rejected: bool,
|
||||
envelopes: Vec<ImportJobSourceEnvelope>,
|
||||
canonical_uris: Vec<String>,
|
||||
guards: Vec<SourceDetachGuard>,
|
||||
@@ -21,6 +22,7 @@ impl MaterializedDependencies {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
snapshots: Vec::new(),
|
||||
secret_literal_rejected: false,
|
||||
envelopes: Vec::new(),
|
||||
canonical_uris: Vec::new(),
|
||||
guards: Vec::new(),
|
||||
@@ -207,6 +209,26 @@ impl AdminService {
|
||||
);
|
||||
continue;
|
||||
};
|
||||
match crank_import::rest::scan_secret_literals(&bytes) {
|
||||
Ok(findings) if !findings.is_empty() => {
|
||||
materialization_failure(
|
||||
"security_scan",
|
||||
"literal_credentials_rejected",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
result.secret_literal_rejected = true;
|
||||
break;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => {
|
||||
materialization_failure(
|
||||
"security_scan",
|
||||
"invalid_document",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(references) = crank_import::rest::external_reference_uris(
|
||||
&document,
|
||||
&self.external_reference_normalization,
|
||||
@@ -368,6 +390,14 @@ impl AdminService {
|
||||
}
|
||||
let document = String::from_utf8(verified.bytes)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let findings = crank_import::rest::scan_secret_literals(document.as_bytes())
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
if !findings.is_empty() {
|
||||
return Err(ApiError::openapi_upload(
|
||||
locale,
|
||||
"literal_credentials_rejected",
|
||||
));
|
||||
}
|
||||
let digest =
|
||||
crank_import::rest::SourceDigest::parse(dependency.digest.digest_hex().to_owned())
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
use super::*;
|
||||
use crate::service::{OpenApiAuthProfileChoice, OpenApiAuthProfileOption};
|
||||
use crank_core::{AuthConfig, AuthProfile, AuthProfileId};
|
||||
|
||||
impl AdminService {
|
||||
pub(super) async fn openapi_auth_profile_choices(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
preview: &crank_import::rest::ImportPreview,
|
||||
) -> Result<Vec<OpenApiAuthProfileChoice>, ApiError> {
|
||||
let mut profiles = self
|
||||
.registry
|
||||
.list_auth_profiles(workspace_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|profile| profile.kind == profile.config.kind())
|
||||
.collect::<Vec<_>>();
|
||||
let mut available_profiles = Vec::with_capacity(profiles.len());
|
||||
for profile in profiles.drain(..) {
|
||||
if auth_profile_is_available(&self.registry, workspace_id, &profile).await? {
|
||||
available_profiles.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()
|
||||
{
|
||||
let scheme = (alternative.schemes.len() == 1)
|
||||
.then(|| operation.security_schemes.get(&alternative.schemes[0]))
|
||||
.flatten();
|
||||
let requirement = scheme.and_then(import_auth_requirement);
|
||||
let supported = alternative.supported
|
||||
&& (alternative.schemes.is_empty() || requirement.is_some());
|
||||
let options = requirement
|
||||
.as_ref()
|
||||
.map(|requirement| {
|
||||
available_profiles
|
||||
.iter()
|
||||
.filter(|profile| auth_profile_matches(profile, requirement))
|
||||
.map(|profile| OpenApiAuthProfileOption {
|
||||
id: profile.id.as_str().to_owned(),
|
||||
name: profile.name.clone(),
|
||||
kind: profile.kind,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
choices.push(OpenApiAuthProfileChoice {
|
||||
operation_key: operation.key.clone(),
|
||||
alternative_index,
|
||||
scheme_names: alternative.schemes.clone(),
|
||||
supported,
|
||||
profiles: options,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(choices)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_openapi_auth_binding(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
candidate: &ImportOperationCandidate,
|
||||
mapping: Option<&OpenApiAuthMapping>,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<(Option<AuthProfileId>, Option<ImportAuthRequirement>), ApiError> {
|
||||
let alternatives = &candidate.security_requirements.alternatives;
|
||||
if alternatives.is_empty() {
|
||||
return if mapping.is_none() {
|
||||
Ok((None, None))
|
||||
} else {
|
||||
Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
|
||||
};
|
||||
}
|
||||
let mapping =
|
||||
mapping.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
|
||||
let alternative = alternatives
|
||||
.get(mapping.alternative_index)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_invalid"))?;
|
||||
if !alternative.supported {
|
||||
return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
|
||||
}
|
||||
if alternative.schemes.is_empty() {
|
||||
return if mapping.auth_profile_id.is_none() {
|
||||
Ok((None, None))
|
||||
} else {
|
||||
Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
|
||||
};
|
||||
}
|
||||
if alternative.schemes.len() != 1 {
|
||||
return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
|
||||
}
|
||||
let scheme = candidate
|
||||
.security_schemes
|
||||
.get(&alternative.schemes[0])
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
|
||||
let requirement = import_auth_requirement(scheme)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
|
||||
let profile_id = mapping
|
||||
.auth_profile_id
|
||||
.as_deref()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
|
||||
let profile_id = AuthProfileId::new(profile_id.to_owned());
|
||||
let profile = self
|
||||
.registry
|
||||
.get_auth_profile(workspace_id, &profile_id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::openapi_auth_binding_unavailable(locale))?;
|
||||
if !auth_profile_matches(&profile, &requirement)
|
||||
|| !auth_profile_is_available(&self.registry, workspace_id, &profile).await?
|
||||
{
|
||||
return Err(ApiError::openapi_auth_binding_unavailable(locale));
|
||||
}
|
||||
Ok((Some(profile_id), Some(requirement)))
|
||||
}
|
||||
}
|
||||
|
||||
fn import_auth_requirement(
|
||||
scheme: &crank_import::rest::NormalizedSecurityScheme,
|
||||
) -> Option<ImportAuthRequirement> {
|
||||
use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
|
||||
|
||||
match &scheme.kind {
|
||||
NormalizedSecuritySchemeKind::Http { scheme, .. }
|
||||
if scheme.eq_ignore_ascii_case("bearer") =>
|
||||
{
|
||||
Some(ImportAuthRequirement::Bearer)
|
||||
}
|
||||
NormalizedSecuritySchemeKind::Http { scheme, .. }
|
||||
if scheme.eq_ignore_ascii_case("basic") =>
|
||||
{
|
||||
Some(ImportAuthRequirement::Basic)
|
||||
}
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Header,
|
||||
parameter_name,
|
||||
..
|
||||
} => Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: parameter_name.clone(),
|
||||
}),
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Query,
|
||||
parameter_name,
|
||||
..
|
||||
} => Some(ImportAuthRequirement::ApiKeyQuery {
|
||||
parameter_name: parameter_name.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_profile_matches(profile: &AuthProfile, requirement: &ImportAuthRequirement) -> bool {
|
||||
if profile.kind != profile.config.kind() {
|
||||
return false;
|
||||
}
|
||||
match (requirement, &profile.config) {
|
||||
(ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||
| (ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||
(
|
||||
ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => config.header_name.eq_ignore_ascii_case(parameter_name),
|
||||
(
|
||||
ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => config.param_name == *parameter_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_profile_is_available(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile: &AuthProfile,
|
||||
) -> Result<bool, ApiError> {
|
||||
for secret_id in profile.config.secret_ids() {
|
||||
if registry
|
||||
.get_current_secret_version(workspace_id, secret_id)
|
||||
.await?
|
||||
.is_none()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
use admin_api::service::{
|
||||
AdminServiceBuilder, OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale,
|
||||
AdminServiceBuilder, AuthProfilePayload, OpenApiAuthMapping, OpenApiImportCreatePayload,
|
||||
OpenApiImportCreateResponse, OpenApiUpload, OpenApiUploadLocale, SecretPayload,
|
||||
};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::ImportJobStatus;
|
||||
use crank_core::{
|
||||
AuthConfig, AuthKind, BearerAuthConfig, SecretId, SecretKind, Workspace, WorkspaceId,
|
||||
WorkspaceStatus,
|
||||
};
|
||||
use crank_registry::{CreateWorkspaceRequest, ImportJobStatus};
|
||||
use serde_json::json;
|
||||
use serial_test::serial;
|
||||
use sha2::Digest;
|
||||
|
||||
use super::common::{
|
||||
test_auth_settings, test_registry, test_secret_crypto, test_service, test_storage_root,
|
||||
@@ -11,6 +17,7 @@ use super::common::{
|
||||
|
||||
mod external_references;
|
||||
mod http_contract;
|
||||
mod security;
|
||||
|
||||
const OPENAPI3: &str = r#"
|
||||
openapi: 3.0.3
|
||||
@@ -78,11 +85,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"
|
||||
"normalized-ir-v5"
|
||||
);
|
||||
assert_eq!(
|
||||
preview_job.preview_payload["normalization"]["projection_version"],
|
||||
"preview-v4"
|
||||
"preview-v5"
|
||||
);
|
||||
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
|
||||
|
||||
@@ -92,6 +99,7 @@ async fn previews_openapi_and_creates_draft_operations() {
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -110,6 +118,7 @@ async fn previews_openapi_and_creates_draft_operations() {
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -162,6 +171,7 @@ async fn previews_openapi_and_creates_draft_operations() {
|
||||
&skip_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -184,6 +194,7 @@ async fn previews_openapi_and_creates_draft_operations() {
|
||||
&rename_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "rename".to_owned(),
|
||||
},
|
||||
@@ -213,6 +224,7 @@ async fn unknown_selected_operations_are_persisted_in_the_canonical_replay() {
|
||||
.unwrap();
|
||||
let payload = OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned(), "GET /missing".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
};
|
||||
@@ -254,6 +266,7 @@ async fn concurrent_openapi_import_replays_the_same_atomic_result() {
|
||||
let job_id = preview.job_id.as_str().into();
|
||||
let payload = OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "rename".to_owned(),
|
||||
};
|
||||
@@ -308,6 +321,7 @@ async fn concurrent_openapi_import_replays_the_same_atomic_result() {
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -349,6 +363,7 @@ async fn apply_fails_closed_when_the_preview_parser_contract_drifts() {
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "rename".to_owned(),
|
||||
},
|
||||
@@ -425,6 +440,7 @@ async fn apply_fails_closed_for_each_normalization_contract_field_and_digest_sha
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "rename".to_owned(),
|
||||
}
|
||||
@@ -493,6 +509,7 @@ async fn legacy_job_without_normalization_contract_replays_until_expiry() {
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -547,6 +564,7 @@ paths:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /valid".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -634,6 +652,7 @@ paths:
|
||||
&valid_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /valid".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -652,6 +671,7 @@ paths:
|
||||
&full_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /valid".to_owned(), "GET /broken".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "rename".to_owned(),
|
||||
},
|
||||
@@ -733,6 +753,7 @@ components:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /referenced".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
@@ -99,6 +99,7 @@ paths:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -117,6 +118,73 @@ paths:
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_literal_credential_is_rejected_before_snapshot_persistence() {
|
||||
let canary = "external-atdd-secret-canary-2-10";
|
||||
let app = Router::new().route(
|
||||
"/schemas.yaml",
|
||||
get(move || async move {
|
||||
format!(
|
||||
"Item: {{ type: object, properties: {{ token: {{ type: string, example: '{canary}' }} }} }}"
|
||||
)
|
||||
}),
|
||||
);
|
||||
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 origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_literal_credential"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: External secret canary }}
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: {{ $ref: '{origin}/schemas.yaml#/Item' }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(canary));
|
||||
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();
|
||||
let import_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!(dependency_sources, 0);
|
||||
assert_eq!(import_jobs, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
|
||||
@@ -188,6 +256,7 @@ paths:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -270,6 +339,7 @@ paths:
|
||||
&corrupt_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -522,6 +592,7 @@ async fn exact_v2_contract_replays_persisted_preview_without_v3_or_dependency_re
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -592,6 +663,84 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.created.len(), 1);
|
||||
let completed = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependency_reads() {
|
||||
use sha2::Digest;
|
||||
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v4_compatibility"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, openapi_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let mut job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let missing_dependency = serde_json::json!([{
|
||||
"source_id": "src_openapi_dep_v4_must_not_be_read",
|
||||
"digest": format!("sha256:{}", "0".repeat(64)),
|
||||
"canonical_uri": "https://schemas.example.test/v4.yaml"
|
||||
}]);
|
||||
let mut persisted_preview = job.preview_payload["preview"].clone();
|
||||
for group in persisted_preview["groups"].as_array_mut().unwrap() {
|
||||
for operation in group["operations"].as_array_mut().unwrap() {
|
||||
let object = operation.as_object_mut().unwrap();
|
||||
object.remove("security_requirements");
|
||||
object.remove("security_schemes");
|
||||
}
|
||||
}
|
||||
let expected_preview_digest = format!(
|
||||
"{:x}",
|
||||
sha2::Sha256::digest(serde_json::to_vec(&persisted_preview).unwrap())
|
||||
);
|
||||
job.preview_payload["preview"] = persisted_preview;
|
||||
job.preview_payload["preview_digest"] = serde_json::json!(expected_preview_digest);
|
||||
job.preview_payload["normalization"]["normalizer_version"] =
|
||||
serde_json::json!("normalized-ir-v4");
|
||||
job.preview_payload["normalization"]["projection_version"] = serde_json::json!("preview-v4");
|
||||
job.preview_payload["normalization"]["ir_fingerprint"] = serde_json::json!("a".repeat(64));
|
||||
job.preview_payload["dependency_snapshots"] = missing_dependency;
|
||||
sqlx::query("update import_jobs set preview_payload = $1 where workspace_id = $2 and id = $3")
|
||||
.bind(&job.preview_payload)
|
||||
.bind(workspace_id.as_str())
|
||||
.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 /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
@@ -108,6 +108,7 @@ async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_
|
||||
|
||||
let payload = OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec![candidate.key.clone()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
};
|
||||
@@ -199,6 +200,7 @@ async fn xml_and_unsupported_media_block_apply_without_registry_mutation() {
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec![candidate.key.clone()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn literal_credential_is_rejected_before_any_import_artifact_or_job_is_created() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_literal_credential_rejected"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let canary = "atdd-secret-canary-2-10-api";
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.0.3
|
||||
info: {{ title: Secret canary }}
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
responses:
|
||||
'200': {{ description: ok }}
|
||||
x-api-key: {canary}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(canary));
|
||||
let import_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();
|
||||
let artifact_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();
|
||||
assert_eq!(import_jobs, 0);
|
||||
assert_eq!(artifact_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current()
|
||||
{
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_auth_profile_binding"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "shared-openapi-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("integration-secret-canary"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let ciphertext = registry
|
||||
.get_current_secret_version(&workspace_id, &secret.id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.secret_version
|
||||
.ciphertext;
|
||||
let secret_hash = format!("{:x}", sha2::Sha256::digest(b"integration-secret-canary"));
|
||||
let profile_a = create_bearer_profile(&service, &workspace_id, "profile-a", &secret.id).await;
|
||||
let profile_b = create_bearer_profile(&service, &workspace_id, "profile-b", &secret.id).await;
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.auth_profile_choices.len(), 2);
|
||||
for choice in &preview.auth_profile_choices {
|
||||
assert!(choice.supported);
|
||||
assert_eq!(choice.profiles.len(), 2);
|
||||
}
|
||||
let response = serde_json::to_string(&preview).unwrap();
|
||||
assert!(!response.contains("integration-secret-canary"));
|
||||
|
||||
let applied = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(applied.created.len(), 2);
|
||||
for created in &applied.created {
|
||||
let version = service
|
||||
.get_operation_version(
|
||||
&workspace_id,
|
||||
&created.operation_id.as_str().into(),
|
||||
created.version,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile_ref = version
|
||||
.snapshot
|
||||
.execution_config
|
||||
.auth_profile_ref
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
let serialized_operation = serde_json::to_string(&version.snapshot).unwrap();
|
||||
assert!(serialized_operation.contains(profile_ref.as_str()));
|
||||
assert!(!serialized_operation.contains("integration-secret-canary"));
|
||||
assert!(!serialized_operation.contains(&ciphertext));
|
||||
assert!(!serialized_operation.contains(&secret_hash));
|
||||
}
|
||||
let changed_mapping_replay = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(changed_mapping_replay.is_err());
|
||||
assert_eq!(
|
||||
service.list_operations(&workspace_id).await.unwrap().len(),
|
||||
2
|
||||
);
|
||||
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let foreign_workspace_id = WorkspaceId::new("ws_openapi_auth_foreign");
|
||||
let foreign_workspace = Workspace {
|
||||
id: foreign_workspace_id.clone(),
|
||||
slug: "openapi-auth-foreign".to_owned(),
|
||||
display_name: "OpenAPI Auth Foreign".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &foreign_workspace,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_secret = service
|
||||
.create_secret(
|
||||
&foreign_workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "foreign-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("foreign-secret-canary"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_profile = create_bearer_profile(
|
||||
&service,
|
||||
&foreign_workspace_id,
|
||||
"foreign-profile",
|
||||
&foreign_secret.id,
|
||||
)
|
||||
.await;
|
||||
let choices_preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
choices_preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.flat_map(|choice| &choice.profiles)
|
||||
.all(|profile| profile.id != foreign_profile.id.as_str())
|
||||
);
|
||||
|
||||
let missing_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, "auth_missing_profile")
|
||||
.await
|
||||
.unwrap_err();
|
||||
let foreign_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, foreign_profile.id.as_str())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(format!("{missing_error:?}"), format!("{foreign_error:?}"));
|
||||
assert!(!format!("{foreign_error:?}").contains(foreign_profile.id.as_str()));
|
||||
|
||||
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret.id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let disabled_preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
disabled_preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.all(|choice| choice.profiles.is_empty())
|
||||
);
|
||||
let before_disabled_apply = service.list_operations(&workspace_id).await.unwrap().len();
|
||||
let disabled_error = service
|
||||
.create_openapi_import_with_locale(
|
||||
&workspace_id,
|
||||
&disabled_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
OpenApiUploadLocale::Ru,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
match &disabled_error {
|
||||
admin_api::error::ApiError::Unprocessable { message, context } => {
|
||||
assert_eq!(
|
||||
message,
|
||||
"выбранный профиль аутентификации недоступен для этого импорта"
|
||||
);
|
||||
assert_eq!(
|
||||
context.as_ref().unwrap()["error_code"],
|
||||
"openapi_auth_binding_unavailable"
|
||||
);
|
||||
}
|
||||
other => panic!("expected localized auth binding error, got {other:?}"),
|
||||
}
|
||||
let disabled_shared_profile_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, profile_b.id.as_str())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
format!("{disabled_shared_profile_error:?}"),
|
||||
format!("{missing_error:?}")
|
||||
);
|
||||
assert_eq!(
|
||||
service.list_operations(&workspace_id).await.unwrap().len(),
|
||||
before_disabled_apply
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics()
|
||||
{
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_import_auth_alternatives"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "or-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("or-profile-secret"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile = create_bearer_profile(&service, &workspace_id, "or-bearer", &secret.id).await;
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, security_alternatives_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let choices = preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.filter(|choice| choice.operation_key == "GET /choice")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(choices.len(), 2);
|
||||
assert!(choices[0].supported);
|
||||
assert_eq!(choices[0].profiles.len(), 1);
|
||||
assert!(!choices[1].supported);
|
||||
let either = preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.filter(|choice| choice.operation_key == "GET /either")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(either.len(), 2);
|
||||
assert!(either[1].supported);
|
||||
|
||||
let applied = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec![
|
||||
"GET /choice".to_owned(),
|
||||
"GET /either".to_owned(),
|
||||
"GET /public".to_owned(),
|
||||
],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /choice".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /either".to_owned(),
|
||||
alternative_index: 1,
|
||||
auth_profile_id: None,
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(applied.created.len(), 3);
|
||||
for created in &applied.created {
|
||||
let version = service
|
||||
.get_operation_version(
|
||||
&workspace_id,
|
||||
&created.operation_id.as_str().into(),
|
||||
created.version,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth_profile_ref = version.snapshot.execution_config.auth_profile_ref;
|
||||
match created.operation_key.as_str() {
|
||||
"GET /choice" => assert_eq!(auth_profile_ref, Some(profile.id.clone())),
|
||||
"GET /either" | "GET /public" => assert!(auth_profile_ref.is_none()),
|
||||
other => panic!("unexpected operation {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_security_scheme_drift"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "drift-test-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("scheme-drift-profile-secret"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile =
|
||||
create_bearer_profile(&service, &workspace_id, "drift-test-profile", &secret.id).await;
|
||||
let bearer_preview = service
|
||||
.preview_openapi_import(&workspace_id, security_scheme_upload(false))
|
||||
.await
|
||||
.unwrap();
|
||||
let api_key_preview = service
|
||||
.preview_openapi_import(&workspace_id, security_scheme_upload(true))
|
||||
.await
|
||||
.unwrap();
|
||||
let bearer_job: crank_registry::ImportJobId = bearer_preview.job_id.as_str().into();
|
||||
let api_key_job: crank_registry::ImportJobId = api_key_preview.job_id.as_str().into();
|
||||
let api_key_source = registry
|
||||
.get_import_job(&workspace_id, &api_key_job)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.preview_payload["source"]
|
||||
.clone();
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(
|
||||
jsonb_set(preview_payload, '{source,source_id}', $1, false),
|
||||
'{source,digest}', $2, false
|
||||
)
|
||||
where workspace_id = $3 and id = $4",
|
||||
)
|
||||
.bind(&api_key_source["source_id"])
|
||||
.bind(&api_key_source["digest"])
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(bearer_job.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&bearer_job,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /secure".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile.id.as_str().to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
match error {
|
||||
admin_api::error::ApiError::Unprocessable { context, .. } => assert_eq!(
|
||||
context.unwrap()["error_code"],
|
||||
"openapi_upload.source_integrity"
|
||||
),
|
||||
other => panic!("expected source integrity error, got {other:?}"),
|
||||
}
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &bearer_job)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
job.error_text.as_deref(),
|
||||
Some("import_replay_verification_failed")
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn auth_mapping_for_unselected_operation_is_rejected_without_draft_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_import_unselected_auth_mapping"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: None,
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
fn two_protected_operations_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: br#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Protected API }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth: { type: http, scheme: bearer }
|
||||
security:
|
||||
- bearerAuth: []
|
||||
paths:
|
||||
/a:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
/b:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
"#
|
||||
.to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_alternatives_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: br#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Security alternatives }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth: { type: http, scheme: bearer }
|
||||
oauth: { type: oauth2, flows: { implicit: { authorizationUrl: https://auth.example.test, scopes: {} } } }
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- oauth: []
|
||||
paths:
|
||||
/choice:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
/either:
|
||||
get:
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- {}
|
||||
responses: { '200': { description: ok } }
|
||||
/public:
|
||||
get:
|
||||
security: []
|
||||
responses: { '200': { description: ok } }
|
||||
"#
|
||||
.to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_scheme_upload(api_key: bool) -> OpenApiUpload {
|
||||
let security_scheme = if api_key {
|
||||
"auth: { type: apiKey, in: header, name: X-Token }"
|
||||
} else {
|
||||
"auth: { type: http, scheme: bearer }"
|
||||
};
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
"openapi: 3.0.3\ninfo: {{ title: Scheme drift }}\nservers: [{{ url: https://api.example.test }}]\ncomponents:\n securitySchemes:\n {security_scheme}\nsecurity:\n - auth: []\npaths:\n /secure:\n get:\n responses: {{ '200': {{ description: ok }} }}\n"
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_bearer_profile(
|
||||
service: &admin_api::service::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
name: &str,
|
||||
secret_id: &SecretId,
|
||||
) -> crank_core::AuthProfile {
|
||||
service
|
||||
.create_auth_profile(
|
||||
workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: name.to_owned(),
|
||||
kind: AuthKind::Bearer,
|
||||
config: AuthConfig::Bearer(BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id: secret_id.clone(),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn apply_first_protected_mapping(
|
||||
service: &admin_api::service::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
auth_profile_id: &str,
|
||||
) -> Result<OpenApiImportCreateResponse, admin_api::error::ApiError> {
|
||||
let preview = service
|
||||
.preview_openapi_import(workspace_id, two_protected_operations_upload())
|
||||
.await?;
|
||||
service
|
||||
.create_openapi_import(
|
||||
workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(auth_profile_id.to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -512,6 +512,7 @@ async fn apply_rereads_the_scoped_verified_source_and_expiry_detaches_it() {
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /health".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
@@ -245,6 +245,7 @@ async fn apply_health_operation(
|
||||
job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /health".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user