feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -2,20 +2,22 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crank_artifacts::{ArtifactError, MAX_ARTIFACT_BYTES};
|
||||
use crank_core::{
|
||||
ExecutionConfig, OperationSecurityLevel, Protocol, ToolQualityFinding, ToolQualitySeverity,
|
||||
WorkspaceId,
|
||||
AuthProfileId, ExecutionConfig, OperationId, OperationSecurityLevel, OperationStatus, Protocol,
|
||||
SecretStatus, ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
|
||||
};
|
||||
use crank_import::rest::{
|
||||
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, NORMALIZER_VERSION,
|
||||
PROJECTION_VERSION, operation_draft_from_candidate,
|
||||
ImportFinding, ImportFindingSeverity, ImportNameConflict, ImportOperationCandidate,
|
||||
NORMALIZER_VERSION, PROJECTION_VERSION, operation_draft_from_candidate,
|
||||
validate_document_source_safe,
|
||||
};
|
||||
use crank_registry::{
|
||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
|
||||
ImportAuthRequirement, ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, RegistryError,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
FinishImportJobRequest, ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobId,
|
||||
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, ImportPlanId,
|
||||
RegistryError, RegistryOperation,
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{Duration, OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use tracing::{info, instrument};
|
||||
@@ -23,26 +25,170 @@ use tracing::{info, instrument};
|
||||
use crate::{
|
||||
error::ApiError,
|
||||
service::{
|
||||
AdminService, OpenApiAuthMapping, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
|
||||
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
|
||||
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
||||
AdminService, OpenApiImportAuthProfileChoice, OpenApiImportCreatePayload,
|
||||
OpenApiImportCreateResponse, OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
|
||||
OpenApiImportPlanCandidateView, OpenApiImportPlanCounts, OpenApiImportPlanCreatePayload,
|
||||
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision,
|
||||
OpenApiImportPlanRevalidationResponse, OpenApiImportPreviewResponse,
|
||||
OpenApiImportSecurityProfileChoice, OpenApiImportSkippedOperation, OpenApiUpload,
|
||||
OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
||||
},
|
||||
};
|
||||
|
||||
mod external_references;
|
||||
mod import_plan;
|
||||
mod job_contract;
|
||||
mod security;
|
||||
mod plan_apply;
|
||||
mod verified_preview;
|
||||
|
||||
use external_references::ImportReplayContext;
|
||||
use import_plan::import_plan_repreview_error;
|
||||
use job_contract::{
|
||||
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
|
||||
};
|
||||
use verified_preview::{
|
||||
ImportPreviewResolution, artifact_error, openapi_source_error, parse_verified_preview,
|
||||
preview_digest, preview_has_blocker,
|
||||
};
|
||||
|
||||
const IMPORT_JOB_TTL_HOURS: i64 = 24;
|
||||
const OPENAPI_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
const OPENAPI_PARSE_CONCURRENCY: usize = 4;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
|
||||
const OPENAPI_SUPPORT_MATRIX_VERSION: &str = "1.0.3";
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_SERVER_URL_BYTES: usize = 8_192;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
|
||||
static OPENAPI_PARSE_SLOTS: tokio::sync::Semaphore =
|
||||
tokio::sync::Semaphore::const_new(OPENAPI_PARSE_CONCURRENCY);
|
||||
|
||||
fn preview_name_conflicts(
|
||||
preview: &crank_import::rest::ImportPreview,
|
||||
catalog_names: &[String],
|
||||
) -> Vec<ImportNameConflict> {
|
||||
let operations = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| group.operations.iter())
|
||||
.collect::<Vec<_>>();
|
||||
let mut operation_ids = BTreeMap::<&str, usize>::new();
|
||||
for candidate in &operations {
|
||||
if let Some(id) = candidate.operation_id.as_deref() {
|
||||
*operation_ids.entry(id).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let occupied = catalog_names
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut proposals = catalog_names.iter().cloned().collect::<BTreeSet<_>>();
|
||||
proposals.extend(
|
||||
operations
|
||||
.iter()
|
||||
.map(|candidate| candidate.suggested_name.clone()),
|
||||
);
|
||||
let mut conflicts = Vec::new();
|
||||
for candidate in operations {
|
||||
let duplicate = candidate
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.is_some_and(|id| operation_ids.get(id).is_some_and(|count| *count > 1));
|
||||
let invalid = candidate.operation_id.as_deref().is_some_and(|id| {
|
||||
id.is_empty()
|
||||
|| id.len() > MAX_IMPORT_PLAN_NAME_BYTES
|
||||
|| !id.bytes().enumerate().all(|(index, ch)| {
|
||||
ch.is_ascii_alphabetic() || ch == b'_' || (index > 0 && ch.is_ascii_digit())
|
||||
})
|
||||
});
|
||||
let taken = occupied.contains(candidate.suggested_name.as_str());
|
||||
if !duplicate && !invalid && !taken {
|
||||
continue;
|
||||
}
|
||||
let base = candidate
|
||||
.suggested_name
|
||||
.chars()
|
||||
.take(240)
|
||||
.collect::<String>();
|
||||
let proposal = next_available_name(&base, &mut proposals);
|
||||
for conflict_type in [
|
||||
duplicate.then_some("duplicate_name"),
|
||||
invalid.then_some("invalid_name"),
|
||||
taken.then_some("taken_name"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
conflicts.push(ImportNameConflict {
|
||||
operation_key: candidate.key.clone(),
|
||||
conflict_type: conflict_type.to_owned(),
|
||||
proposed_name: proposal.clone(),
|
||||
source_location: candidate.source_location.as_ref().map(|location| {
|
||||
crank_import::rest::SourceLocation {
|
||||
pointer: if candidate.operation_id.is_some() {
|
||||
format!("{}/operationId", location.pointer)
|
||||
} else {
|
||||
location.pointer.clone()
|
||||
},
|
||||
}
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
conflicts
|
||||
}
|
||||
|
||||
fn next_available_name(base: &str, occupied: &mut BTreeSet<String>) -> String {
|
||||
// A catalog may contain more names than the preview candidate cap. With
|
||||
// occupied.len() + 1 suffixes, at least one candidate must be free.
|
||||
(2..=occupied.len() + 2)
|
||||
.map(|index| format!("{base}_{index}"))
|
||||
.find(|name| occupied.insert(name.clone()))
|
||||
.expect("finite occupied names always leave a free suffix")
|
||||
}
|
||||
|
||||
fn attach_preview_readiness(
|
||||
preview: &mut crank_import::rest::ImportPreview,
|
||||
choices: &[OpenApiImportSecurityProfileChoice],
|
||||
) {
|
||||
let document_blocked = preview.findings.iter().any(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none()
|
||||
});
|
||||
for candidate in preview
|
||||
.groups
|
||||
.iter_mut()
|
||||
.flat_map(|group| group.operations.iter_mut())
|
||||
{
|
||||
let blocked = document_blocked
|
||||
|| candidate
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.severity == ImportFindingSeverity::Error);
|
||||
let alternatives = &candidate.security_requirements.alternatives;
|
||||
let public = alternatives.is_empty()
|
||||
|| alternatives
|
||||
.iter()
|
||||
.any(|alternative| alternative.supported && alternative.schemes.is_empty());
|
||||
candidate.status = if blocked {
|
||||
"blocked"
|
||||
} else if public {
|
||||
"actionable"
|
||||
} else if alternatives.iter().enumerate().any(|(index, alternative)| {
|
||||
alternative.supported
|
||||
&& choices.iter().any(|choice| {
|
||||
choice.operation_key == candidate.key
|
||||
&& choice.alternative_index == index
|
||||
&& !choice.profiles.is_empty()
|
||||
})
|
||||
}) {
|
||||
"unresolved"
|
||||
} else {
|
||||
"blocked"
|
||||
}
|
||||
.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
impl AdminService {
|
||||
#[instrument(skip(self, upload), fields(workspace_id = %workspace_id.as_str()))]
|
||||
pub async fn preview_openapi_import(
|
||||
@@ -53,29 +199,53 @@ 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,
|
||||
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,
|
||||
@@ -85,7 +255,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(),
|
||||
@@ -111,17 +288,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;
|
||||
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(),
|
||||
@@ -149,8 +315,22 @@ 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)
|
||||
let candidate_count: usize = parsed
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.operations.len())
|
||||
.sum();
|
||||
if candidate_count > MAX_IMPORT_PLAN_KEYS {
|
||||
dependencies.detach_all().await;
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::validation_with_context(
|
||||
"OpenAPI preview has too many candidates",
|
||||
json!({ "error_code": "openapi_preview_too_many_candidates", "limit": MAX_IMPORT_PLAN_KEYS }),
|
||||
));
|
||||
}
|
||||
let security_profile_choices = match self
|
||||
.security_profile_choices(workspace_id, &parsed.preview)
|
||||
.await
|
||||
{
|
||||
Ok(choices) => choices,
|
||||
@@ -160,6 +340,14 @@ impl AdminService {
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let catalog_names = match self.registry.list_import_catalog_names(workspace_id).await {
|
||||
Ok(names) => names,
|
||||
Err(error) => {
|
||||
dependencies.detach_all().await;
|
||||
detach_guard.detach_now().await;
|
||||
return Err(ApiError::from(error));
|
||||
}
|
||||
};
|
||||
let source_envelope = ImportJobSourceEnvelope {
|
||||
source_id,
|
||||
digest: artifact.artifact_ref().clone(),
|
||||
@@ -207,16 +395,92 @@ impl AdminService {
|
||||
dependencies.disarm();
|
||||
detach_guard.disarm();
|
||||
|
||||
let mut response_preview = parsed.preview;
|
||||
response_preview.conflicts = preview_name_conflicts(&response_preview, &catalog_names);
|
||||
attach_preview_readiness(&mut response_preview, &security_profile_choices);
|
||||
Ok(OpenApiImportPreviewResponse {
|
||||
job_id: job_id.as_str().to_owned(),
|
||||
expires_at: expires_at
|
||||
.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
auth_profile_choices,
|
||||
preview: parsed.preview,
|
||||
preview: response_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,
|
||||
@@ -259,7 +523,11 @@ impl AdminService {
|
||||
)
|
||||
})?;
|
||||
if job.expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(ApiError::validation("import preview has expired"));
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => "срок действия preview импорта истёк",
|
||||
OpenApiUploadLocale::En => "import preview has expired",
|
||||
};
|
||||
return Err(ApiError::validation(message));
|
||||
}
|
||||
if job.kind != ImportJobKind::OpenApi {
|
||||
return Err(ApiError::validation("import job kind is not openapi"));
|
||||
@@ -276,15 +544,6 @@ 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
|
||||
@@ -314,141 +573,20 @@ impl AdminService {
|
||||
return Ok(openapi_import_response(applied));
|
||||
}
|
||||
|
||||
let source = match import_job_source(&job.preview_payload, locale) {
|
||||
Ok(source) => source,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_source_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let verified = match self
|
||||
.registry
|
||||
.read_artifact_source(
|
||||
std::sync::Arc::clone(&self.artifact_store),
|
||||
workspace_id,
|
||||
&source.source_id,
|
||||
)
|
||||
let resolved_preview = match self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
{
|
||||
Ok(verified) => verified,
|
||||
Err(
|
||||
error @ (RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable),
|
||||
) => {
|
||||
Ok(resolved) => resolved,
|
||||
Err(ImportPreviewResolution::Fatal(error_code, error)) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_source_verification_failed",
|
||||
openapi_source_error(locale, error),
|
||||
)
|
||||
.fail_openapi_import_or_replay(&replay_context, error_code, error)
|
||||
.await;
|
||||
}
|
||||
Err(error @ RegistryError::SourceIntegrity) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_source_verification_failed",
|
||||
openapi_source_error(locale, error),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => return Err(openapi_source_error(locale, error)),
|
||||
Err(ImportPreviewResolution::NonFatal(error)) => return Err(error),
|
||||
};
|
||||
if verified.source.blob.artifact_ref != source.digest {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_source_verification_failed",
|
||||
ApiError::openapi_upload(locale, "source_integrity"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let replay_contract = match import_replay_contract(&job.preview_payload, locale) {
|
||||
Ok(contract) => contract,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let parsed = match replay_contract {
|
||||
ImportReplayContract::PersistedV2(parsed) => parsed,
|
||||
ImportReplayContract::LegacyV1 | ImportReplayContract::Current => {
|
||||
let legacy_v1 = matches!(replay_contract, ImportReplayContract::LegacyV1);
|
||||
let dependency_snapshots = match self
|
||||
.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
|
||||
.await
|
||||
{
|
||||
Ok(snapshots) => snapshots,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_dependency_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let normalization_config = match import_job_normalization_config(
|
||||
&job.preview_payload,
|
||||
&self.external_reference_normalization,
|
||||
legacy_v1,
|
||||
locale,
|
||||
) {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let parsed = match parse_verified_preview(
|
||||
verified.bytes,
|
||||
source.digest.digest_hex().to_owned(),
|
||||
dependency_snapshots,
|
||||
normalization_config,
|
||||
locale,
|
||||
legacy_v1,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
if let Err(error) = verify_preview_contract(&job.preview_payload, &parsed, locale) {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
};
|
||||
if preview_has_blocker(&parsed.preview, &selected) {
|
||||
let preview = resolved_preview.preview;
|
||||
if preview_has_blocker(&preview, &selected) {
|
||||
return self
|
||||
.fail_openapi_import_or_replay(
|
||||
&replay_context,
|
||||
@@ -458,25 +596,11 @@ impl AdminService {
|
||||
.await;
|
||||
}
|
||||
let mut candidates = BTreeMap::new();
|
||||
for group in &parsed.preview.groups {
|
||||
for group in &preview.groups {
|
||||
for operation in &group.operations {
|
||||
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();
|
||||
@@ -490,26 +614,6 @@ 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);
|
||||
@@ -531,7 +635,7 @@ impl AdminService {
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: draft.tool_description,
|
||||
@@ -540,7 +644,6 @@ impl AdminService {
|
||||
operations.push(ImportOperationDraft {
|
||||
operation_key: candidate.key.clone(),
|
||||
operation,
|
||||
auth_requirement,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -555,13 +658,7 @@ impl AdminService {
|
||||
pre_skipped: &skipped,
|
||||
finished_at: &finished_at,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
RegistryError::ImportAuthBindingUnavailable => {
|
||||
ApiError::openapi_auth_binding_unavailable(locale)
|
||||
}
|
||||
error => error.into(),
|
||||
})?;
|
||||
.await?;
|
||||
|
||||
Ok(openapi_import_response(applied))
|
||||
}
|
||||
@@ -611,6 +708,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
|
||||
operation.name
|
||||
),
|
||||
operation_key: Some(operation.operation_key.clone()),
|
||||
source_location: None,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -629,6 +727,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
|
||||
format!("Операция {name} уже существует и была пропущена.")
|
||||
},
|
||||
operation_key: Some(operation.operation_key.clone()),
|
||||
source_location: None,
|
||||
});
|
||||
OpenApiImportSkippedOperation {
|
||||
operation_key: operation.operation_key.clone(),
|
||||
@@ -678,252 +777,14 @@ fn validate_openapi_upload(upload: &OpenApiUpload) -> Result<(), ApiError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ParsedOpenApiPreview {
|
||||
preview: crank_import::rest::ImportPreview,
|
||||
ir_fingerprint: String,
|
||||
}
|
||||
|
||||
enum ImportReplayContract {
|
||||
LegacyV1,
|
||||
PersistedV2(ParsedOpenApiPreview),
|
||||
Current,
|
||||
}
|
||||
|
||||
fn import_replay_contract(
|
||||
payload: &serde_json::Value,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<ImportReplayContract, ApiError> {
|
||||
let Some(normalization) = payload.get("normalization") else {
|
||||
return Ok(ImportReplayContract::LegacyV1);
|
||||
};
|
||||
let normalizer = normalization
|
||||
.get("normalizer_version")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let projection = normalization
|
||||
.get("projection_version")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let ir_fingerprint = normalization
|
||||
.get("ir_fingerprint")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|value| is_lower_sha256(value))
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let expected_preview_digest = payload
|
||||
.get("preview_digest")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|value| is_lower_sha256(value))
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
|
||||
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
|
||||
return Ok(ImportReplayContract::Current);
|
||||
}
|
||||
// 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-v4", "preview-v4")
|
||||
) {
|
||||
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||
}
|
||||
|
||||
let preview_value = payload
|
||||
.get("preview")
|
||||
.cloned()
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
if preview_digest(&preview_value)? != expected_preview_digest {
|
||||
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||
}
|
||||
let preview = serde_json::from_value(preview_value)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
Ok(ImportReplayContract::PersistedV2(ParsedOpenApiPreview {
|
||||
preview,
|
||||
ir_fingerprint: ir_fingerprint.to_owned(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn is_lower_sha256(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
}
|
||||
|
||||
async fn parse_verified_preview(
|
||||
bytes: Vec<u8>,
|
||||
digest: String,
|
||||
snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
|
||||
normalization_config: crank_import::rest::NormalizationConfig,
|
||||
locale: OpenApiUploadLocale,
|
||||
legacy_v1: bool,
|
||||
) -> Result<ParsedOpenApiPreview, ApiError> {
|
||||
let started = tokio::time::Instant::now();
|
||||
let permit = tokio::time::timeout(OPENAPI_PARSE_DEADLINE, OPENAPI_PARSE_SLOTS.acquire())
|
||||
.await
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?;
|
||||
let parsing = tokio::task::spawn_blocking(move || {
|
||||
// Keep the permit inside the blocking task. Timing out the caller
|
||||
// cannot cancel CPU work already running, but abandoned parsers remain
|
||||
// globally bounded and release capacity when they actually finish.
|
||||
let _permit = permit;
|
||||
let document = std::str::from_utf8(&bytes)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "invalid_utf8"))?;
|
||||
if legacy_v1 {
|
||||
return crank_import::rest::preview_document_legacy_v1(document)
|
||||
.map(|preview| ParsedOpenApiPreview {
|
||||
preview,
|
||||
ir_fingerprint: String::new(),
|
||||
})
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"));
|
||||
}
|
||||
let digest = crank_import::rest::SourceDigest::parse(digest)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let ir = crank_import::rest::normalize_verified_bundle(
|
||||
document,
|
||||
digest,
|
||||
&snapshots,
|
||||
&normalization_config,
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
crank_import::rest::ImportParseError::NoMethods => {
|
||||
ApiError::openapi_upload(locale, "no_methods")
|
||||
}
|
||||
_ => ApiError::openapi_upload(locale, "invalid_document"),
|
||||
})?;
|
||||
let ir_fingerprint = preview_digest(
|
||||
&serde_json::to_value(&ir)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?,
|
||||
)?;
|
||||
Ok::<_, ApiError>(ParsedOpenApiPreview {
|
||||
preview: crank_import::rest::preview_from_ir(&ir),
|
||||
ir_fingerprint,
|
||||
})
|
||||
});
|
||||
let remaining = OPENAPI_PARSE_DEADLINE
|
||||
.checked_sub(started.elapsed())
|
||||
.unwrap_or(std::time::Duration::ZERO);
|
||||
tokio::time::timeout(remaining, parsing)
|
||||
.await
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
|
||||
}
|
||||
|
||||
fn artifact_error(locale: OpenApiUploadLocale, error: ArtifactError) -> ApiError {
|
||||
match error {
|
||||
ArtifactError::EmptySource => ApiError::openapi_upload(locale, "empty_file"),
|
||||
ArtifactError::SourceTooLarge => ApiError::openapi_upload(locale, "file_too_large"),
|
||||
ArtifactError::Integrity => ApiError::openapi_upload(locale, "source_integrity"),
|
||||
ArtifactError::Storage
|
||||
| ArtifactError::NotFound
|
||||
| ArtifactError::InvalidReference
|
||||
| ArtifactError::UnsafeRoot => ApiError::openapi_upload(locale, "storage_unavailable"),
|
||||
}
|
||||
}
|
||||
|
||||
fn openapi_source_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
|
||||
match error {
|
||||
RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable => {
|
||||
ApiError::openapi_upload(locale, "source_unavailable")
|
||||
}
|
||||
RegistryError::SourceIntegrity => ApiError::openapi_upload(locale, "source_integrity"),
|
||||
other => ApiError::from(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_digest(preview: &serde_json::Value) -> Result<String, ApiError> {
|
||||
let canonical =
|
||||
serde_json::to_vec(preview).map_err(|error| ApiError::internal(error.to_string()))?;
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
fn verify_preview_contract(
|
||||
payload: &serde_json::Value,
|
||||
parsed: &ParsedOpenApiPreview,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<(), ApiError> {
|
||||
// Pre-fingerprint jobs are legacy rolling-upgrade records. They retain the
|
||||
// old reparse behavior; new jobs fail closed if parser output drifts or a
|
||||
// persisted preview has been changed.
|
||||
let expected = payload
|
||||
.get("preview_digest")
|
||||
.and_then(serde_json::Value::as_str);
|
||||
if payload.get("normalization").is_some() && expected.is_none() {
|
||||
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||
}
|
||||
let Some(expected) = expected else {
|
||||
return Ok(());
|
||||
};
|
||||
let actual = preview_digest(
|
||||
&serde_json::to_value(&parsed.preview)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
)?;
|
||||
if actual == expected {
|
||||
if let Some(normalization) = payload.get("normalization") {
|
||||
let normalizer = normalization
|
||||
.get("normalizer_version")
|
||||
.and_then(serde_json::Value::as_str);
|
||||
let projection = normalization
|
||||
.get("projection_version")
|
||||
.and_then(serde_json::Value::as_str);
|
||||
let fingerprint = normalization
|
||||
.get("ir_fingerprint")
|
||||
.and_then(serde_json::Value::as_str);
|
||||
if normalizer != Some(NORMALIZER_VERSION)
|
||||
|| projection != Some(PROJECTION_VERSION)
|
||||
|| fingerprint != Some(parsed.ir_fingerprint.as_str())
|
||||
{
|
||||
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ApiError::openapi_upload(locale, "source_integrity"))
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_has_blocker(
|
||||
preview: &crank_import::rest::ImportPreview,
|
||||
selected_operation_keys: &BTreeSet<String>,
|
||||
) -> bool {
|
||||
preview
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|
||||
|| preview
|
||||
.groups
|
||||
.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
|
||||
&& !matches!(
|
||||
finding.code.as_str(),
|
||||
"unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unresolved_security_scheme"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<String, ApiError> {
|
||||
let selected_operation_keys = payload
|
||||
.selected_operation_keys
|
||||
.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(),
|
||||
}))
|
||||
@@ -965,3 +826,20 @@ fn tool_quality_finding_from_import(finding: &ImportFinding) -> ToolQualityFindi
|
||||
field_path: finding.operation_key.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preview_name_tests {
|
||||
use super::next_available_name;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn crowded_catalog_still_gets_a_free_deterministic_proposal() {
|
||||
let mut occupied = (2..=2_002)
|
||||
.map(|index| format!("shared_{index}"))
|
||||
.collect::<BTreeSet<_>>();
|
||||
occupied.insert("shared".to_owned());
|
||||
|
||||
assert_eq!(next_available_name("shared", &mut occupied), "shared_2003");
|
||||
assert_eq!(next_available_name("shared", &mut occupied), "shared_2004");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user