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
@@ -27,12 +27,18 @@ use crate::{
|
||||
},
|
||||
auth_profiles::{create_auth_profile, get_auth_profile, list_auth_profiles},
|
||||
capabilities::get_capabilities,
|
||||
imports::{create_openapi_import, preview_openapi_import},
|
||||
imports::{
|
||||
apply_openapi_import_plan, create_openapi_import, create_openapi_import_plan,
|
||||
preview_openapi_import, revalidate_openapi_import_plan,
|
||||
},
|
||||
observability::{
|
||||
approve_approval, deny_approval, export_logs_csv, export_usage_csv, get_agent_usage,
|
||||
get_approval, get_log, get_operation_usage, get_usage, list_approvals, list_logs,
|
||||
},
|
||||
onboarding::{get_onboarding, record_onboarding_event, reset_onboarding_selection},
|
||||
onboarding::{
|
||||
get_onboarding, record_onboarding_event, register_onboarding_import_context,
|
||||
reset_onboarding_selection, select_onboarding_import_draft,
|
||||
},
|
||||
operations::{
|
||||
analyze_operation_quality, archive_operation, create_operation, create_version,
|
||||
delete_operation, export_operation, generate_draft, get_operation,
|
||||
@@ -58,6 +64,18 @@ pub fn build_app(state: AppState) -> Router {
|
||||
"/imports/openapi/{job_id}/create",
|
||||
post(create_openapi_import),
|
||||
)
|
||||
.route(
|
||||
"/imports/openapi/{job_id}/plans",
|
||||
post(create_openapi_import_plan).layer(DefaultBodyLimit::max(16 * 1024 * 1024)),
|
||||
)
|
||||
.route(
|
||||
"/imports/openapi/plans/{plan_id}",
|
||||
get(revalidate_openapi_import_plan),
|
||||
)
|
||||
.route(
|
||||
"/imports/openapi/{plan_id}/apply",
|
||||
post(apply_openapi_import_plan).layer(DefaultBodyLimit::max(16 * 1024)),
|
||||
)
|
||||
.route(
|
||||
"/operations/analyze-quality",
|
||||
post(analyze_operation_quality),
|
||||
@@ -158,6 +176,14 @@ pub fn build_app(state: AppState) -> Router {
|
||||
.route(
|
||||
"/onboarding/reset-selection",
|
||||
post(reset_onboarding_selection),
|
||||
)
|
||||
.route(
|
||||
"/onboarding/import-context",
|
||||
post(register_onboarding_import_context).layer(DefaultBodyLimit::max(16 * 1024)),
|
||||
)
|
||||
.route(
|
||||
"/onboarding/select-draft",
|
||||
post(select_onboarding_import_draft).layer(DefaultBodyLimit::max(16 * 1024)),
|
||||
);
|
||||
|
||||
let workspace_root_router = Router::new()
|
||||
|
||||
@@ -186,6 +186,19 @@ async fn run() -> Result<ExitCode, CliError> {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let plan = json!({ "schema_version": 1, "sequence": sequence });
|
||||
if option == Some("--target-version") {
|
||||
let target_version = plan["sequence"]
|
||||
.as_array()
|
||||
.and_then(|sequence| sequence.last())
|
||||
.and_then(|migration| migration["version"].as_i64())
|
||||
.ok_or(CliError::new(
|
||||
"migration_sequence_invalid",
|
||||
"plan.target_version",
|
||||
"contact_operator",
|
||||
))?;
|
||||
println!("{target_version}");
|
||||
return Ok(ExitCode::SUCCESS);
|
||||
}
|
||||
if option == Some("--check") {
|
||||
let bytes = std::fs::read("docs/schemas/migration-sequence.json")
|
||||
.map_err(|_| CliError::new("contract_drift", "plan.read", "contact_operator"))?;
|
||||
|
||||
+151
-21
@@ -353,6 +353,35 @@ pub struct OnboardingResponse {
|
||||
pub platform_api_key_id: Option<String>,
|
||||
pub mcp_endpoint: Option<String>,
|
||||
pub first_call: Option<OnboardingFirstCallEvidence>,
|
||||
pub import_context: Option<OnboardingImportContextView>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OnboardingImportChoiceView {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub outcome: String,
|
||||
pub operation_id: Option<String>,
|
||||
pub version: Option<u32>,
|
||||
pub reason: Option<String>,
|
||||
pub selectable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OnboardingImportDriftView {
|
||||
pub reason: String,
|
||||
pub current_operation_version: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OnboardingImportContextView {
|
||||
pub application_idempotency_key: String,
|
||||
pub plan_digest: String,
|
||||
pub report: Value,
|
||||
pub choices: Vec<OnboardingImportChoiceView>,
|
||||
pub selected_operation_id: Option<String>,
|
||||
pub selected_operation_version: Option<u32>,
|
||||
pub drift: Option<OnboardingImportDriftView>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -375,6 +404,38 @@ pub struct ResetOnboardingSelectionResponse {
|
||||
pub onboarding: OnboardingResponse,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RegisterOnboardingImportContextPayload {
|
||||
pub application_idempotency_key: String,
|
||||
pub plan_digest: String,
|
||||
pub expected_revision: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct RegisterOnboardingImportContextResponse {
|
||||
pub registered: bool,
|
||||
#[serde(flatten)]
|
||||
pub onboarding: OnboardingResponse,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SelectOnboardingImportDraftPayload {
|
||||
pub application_idempotency_key: String,
|
||||
pub plan_digest: String,
|
||||
pub operation_id: String,
|
||||
pub operation_version: u32,
|
||||
pub expected_revision: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct SelectOnboardingImportDraftResponse {
|
||||
pub selected: bool,
|
||||
#[serde(flatten)]
|
||||
pub onboarding: OnboardingResponse,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct WorkspaceCatalogSnapshotResponse {
|
||||
pub kind: String,
|
||||
@@ -542,48 +603,34 @@ 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>,
|
||||
#[serde(default)]
|
||||
pub security_profile_choices: Vec<OpenApiImportSecurityProfileChoice>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiAuthProfileChoice {
|
||||
pub struct OpenApiImportSecurityProfileChoice {
|
||||
pub operation_key: String,
|
||||
pub alternative_index: usize,
|
||||
pub scheme_names: Vec<String>,
|
||||
pub supported: bool,
|
||||
pub profiles: Vec<OpenApiAuthProfileOption>,
|
||||
pub schemes: Vec<String>,
|
||||
pub profiles: Vec<OpenApiImportAuthProfileChoice>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiAuthProfileOption {
|
||||
pub struct OpenApiImportAuthProfileChoice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: AuthKind,
|
||||
pub kind: crank_core::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>,
|
||||
@@ -606,6 +653,89 @@ pub struct OpenApiImportSkippedOperation {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OpenApiImportPlanCreatePayload {
|
||||
#[serde(default = "default_openapi_plan_selection_mode")]
|
||||
pub selection_mode: String,
|
||||
#[serde(default)]
|
||||
pub selected_operation_keys: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub server_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub decisions: Vec<OpenApiImportPlanDecision>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OpenApiImportPlanApplyPayload {
|
||||
pub plan_digest: String,
|
||||
pub idempotency_key: String,
|
||||
}
|
||||
|
||||
fn default_openapi_plan_selection_mode() -> String {
|
||||
"full".to_owned()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OpenApiImportPlanDecision {
|
||||
pub operation_key: String,
|
||||
pub action: String,
|
||||
#[serde(default)]
|
||||
pub target_operation_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirmed_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub auth_profile_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub security_alternative_index: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct OpenApiImportPlanCounts {
|
||||
pub selected: usize,
|
||||
pub excluded: usize,
|
||||
pub actionable: usize,
|
||||
pub blocked: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct OpenApiImportPlanCandidateView {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub state: String,
|
||||
pub action: Option<String>,
|
||||
pub target_operation_id: Option<String>,
|
||||
pub confirmed_name: Option<String>,
|
||||
pub auth_profile_id: Option<String>,
|
||||
pub security_alternative_index: Option<usize>,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiImportPlanCreateResponse {
|
||||
pub plan_reference: String,
|
||||
pub plan_digest: String,
|
||||
pub catalog_revision: String,
|
||||
pub support_matrix_version: String,
|
||||
pub expires_at: String,
|
||||
pub selection_mode: String,
|
||||
pub counts: OpenApiImportPlanCounts,
|
||||
pub candidates: Vec<OpenApiImportPlanCandidateView>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct OpenApiImportPlanRevalidationResponse {
|
||||
pub plan_reference: String,
|
||||
pub plan_digest: String,
|
||||
pub revalidation_status: String,
|
||||
pub revalidation_required: bool,
|
||||
pub reason: Option<String>,
|
||||
pub counts: OpenApiImportPlanCounts,
|
||||
pub candidates: Vec<OpenApiImportPlanCandidateView>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct CreatedOperationResponse {
|
||||
pub operation_id: String,
|
||||
|
||||
+111
-51
@@ -135,41 +135,6 @@ 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 не содержит поддерживаемых методов"
|
||||
@@ -230,18 +195,6 @@ 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(),
|
||||
@@ -711,6 +664,29 @@ impl From<RegistryError> for ApiError {
|
||||
"onboarding domain steps are not complete",
|
||||
json!({"error_code":"onboarding_incomplete"}),
|
||||
),
|
||||
RegistryError::OnboardingImportDraftUnavailable => Self::unprocessable_with_context(
|
||||
"the requested operation is not an actionable imported Draft",
|
||||
json!({
|
||||
"error_code":"onboarding_import_draft_unavailable",
|
||||
"recovery":"reload_import_report"
|
||||
}),
|
||||
),
|
||||
RegistryError::OnboardingImportApplicationUnavailable => {
|
||||
Self::unprocessable_with_context(
|
||||
"no committed import apply report matches the requested application",
|
||||
json!({
|
||||
"error_code":"onboarding_import_application_unavailable",
|
||||
"recovery":"reload_import_report"
|
||||
}),
|
||||
)
|
||||
}
|
||||
RegistryError::OnboardingImportContextUnavailable => Self::unprocessable_with_context(
|
||||
"the workspace has no durable import context for the requested application",
|
||||
json!({
|
||||
"error_code":"onboarding_import_context_unavailable",
|
||||
"recovery":"register_import_context"
|
||||
}),
|
||||
),
|
||||
RegistryError::InvalidEnumRepresentation { field } => Self::validation_with_context(
|
||||
format!("unsupported enum representation for field {field}"),
|
||||
json!({ "field": field }),
|
||||
@@ -722,10 +698,6 @@ 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 }),
|
||||
@@ -738,6 +710,94 @@ impl From<RegistryError> for ApiError {
|
||||
format!("import job {job_id} was already applied with different parameters"),
|
||||
json!({ "job_id": job_id }),
|
||||
),
|
||||
RegistryError::InvalidImportPlan { field } => Self::validation_with_context(
|
||||
format!("invalid import plan input for field {field}"),
|
||||
json!({
|
||||
"field": field,
|
||||
"error_code": "import_plan_invalid_input"
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanConflict { plan_id } => Self::conflict_with_context(
|
||||
format!("import plan {plan_id} already exists with different material"),
|
||||
json!({
|
||||
"plan_id": plan_id,
|
||||
"error_code": "import_plan_conflict",
|
||||
"recovery": "repreview_required"
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanJobUnavailable { job_id } => Self::not_found_with_context(
|
||||
format!("import job {job_id} is unavailable for planning"),
|
||||
json!({ "job_id": job_id, "error_code": "import_plan_job_unavailable" }),
|
||||
),
|
||||
RegistryError::ImportPlanJobTerminal { job_id }
|
||||
| RegistryError::ImportPlanJobExpired { job_id } => Self::conflict_with_context(
|
||||
format!("import job {job_id} is not in planning state"),
|
||||
json!({
|
||||
"job_id": job_id,
|
||||
"error_code": "import_plan_job_terminal",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanNotFound { .. } => Self::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
),
|
||||
RegistryError::ImportPlanExpired { .. } => Self::conflict_with_context(
|
||||
"import plan has expired; create a fresh preview",
|
||||
json!({
|
||||
"error_code": "import_plan_expired",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanPayloadCorrupt { .. } => Self::conflict_with_context(
|
||||
"import plan is invalid; create a fresh preview",
|
||||
json!({
|
||||
"error_code": "import_plan_payload_invalid",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanFingerprintStale { .. } => Self::conflict_with_context(
|
||||
"import plan no longer matches the verified preview; create a fresh preview",
|
||||
json!({
|
||||
"error_code": "import_plan_fingerprint_stale",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanKeyDigestConflict { .. } => Self::conflict_with_context(
|
||||
"idempotency key was already committed for different plan material",
|
||||
json!({
|
||||
"error_code": "import_plan_key_digest_conflict",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanNameConflict { .. } => Self::conflict_with_context(
|
||||
"an operation name changed after the plan was created",
|
||||
json!({
|
||||
"error_code": "import_plan_name_conflict",
|
||||
"recovery": "confirm_skip_rename_or_new_version"
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanTargetStale { .. } => Self::conflict_with_context(
|
||||
"an operation changed after the plan was created; create a fresh preview",
|
||||
json!({
|
||||
"error_code": "import_plan_target_stale",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::ImportPlanAuthUnavailable { .. } => Self::conflict_with_context(
|
||||
"an authentication profile is unavailable; create a fresh preview",
|
||||
json!({
|
||||
"error_code": "import_plan_auth_unavailable",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
),
|
||||
RegistryError::SourceNotFound { .. } => Self::not_found_with_context(
|
||||
"artifact source was not found",
|
||||
json!({
|
||||
|
||||
@@ -10,7 +10,10 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
error::ApiError,
|
||||
service::{OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale},
|
||||
service::{
|
||||
OpenApiImportCreatePayload, OpenApiImportPlanApplyPayload, OpenApiImportPlanCreatePayload,
|
||||
OpenApiUpload, OpenApiUploadLocale,
|
||||
},
|
||||
state::AppState,
|
||||
};
|
||||
|
||||
@@ -25,6 +28,12 @@ pub struct WorkspaceImportPath {
|
||||
pub job_id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct WorkspacePlanPath {
|
||||
pub workspace_id: String,
|
||||
pub plan_id: String,
|
||||
}
|
||||
|
||||
pub async fn preview_openapi_import(
|
||||
Path(path): Path<WorkspacePath>,
|
||||
State(state): State<AppState>,
|
||||
@@ -198,6 +207,69 @@ pub async fn create_openapi_import(
|
||||
Ok(Json(json!(imported)))
|
||||
}
|
||||
|
||||
pub async fn create_openapi_import_plan(
|
||||
Path(path): Path<WorkspaceImportPath>,
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<OpenApiImportPlanCreatePayload>,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let plan = state
|
||||
.service
|
||||
.create_openapi_import_plan_with_locale(
|
||||
&path.workspace_id.as_str().into(),
|
||||
&path.job_id.as_str().into(),
|
||||
payload,
|
||||
openapi_upload_locale(&headers),
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(json!(plan)))
|
||||
}
|
||||
|
||||
pub async fn revalidate_openapi_import_plan(
|
||||
Path(path): Path<WorkspacePlanPath>,
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let plan = state
|
||||
.service
|
||||
.revalidate_openapi_import_plan_with_locale(
|
||||
&path.workspace_id.as_str().into(),
|
||||
&path.plan_id.as_str().into(),
|
||||
openapi_upload_locale(&headers),
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(json!(plan)))
|
||||
}
|
||||
|
||||
pub async fn apply_openapi_import_plan(
|
||||
Path(path): Path<WorkspacePlanPath>,
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<OpenApiImportPlanApplyPayload>,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let report = state
|
||||
.service
|
||||
.apply_openapi_import_plan_with_locale(
|
||||
&path.workspace_id.as_str().into(),
|
||||
&path.plan_id.as_str().into(),
|
||||
payload,
|
||||
openapi_upload_locale(&headers),
|
||||
)
|
||||
.await?;
|
||||
let status = if report.status == crank_registry::ImportPlanApplyStatus::Rejected {
|
||||
axum::http::StatusCode::CONFLICT
|
||||
} else {
|
||||
axum::http::StatusCode::OK
|
||||
};
|
||||
Ok((
|
||||
status,
|
||||
Json(
|
||||
serde_json::to_value(report)
|
||||
.map_err(|_| ApiError::internal("could not serialize import plan report"))?,
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::http::{HeaderMap, HeaderValue};
|
||||
|
||||
@@ -7,7 +7,9 @@ use crate::{
|
||||
error::ApiError,
|
||||
service::{
|
||||
OnboardingEventPayload, OnboardingEventResponse, OnboardingResponse,
|
||||
RegisterOnboardingImportContextPayload, RegisterOnboardingImportContextResponse,
|
||||
ResetOnboardingSelectionPayload, ResetOnboardingSelectionResponse,
|
||||
SelectOnboardingImportDraftPayload, SelectOnboardingImportDraftResponse,
|
||||
},
|
||||
state::AppState,
|
||||
};
|
||||
@@ -57,3 +59,29 @@ pub async fn record_onboarding_event(
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn register_onboarding_import_context(
|
||||
Path(path): Path<WorkspaceOnboardingPath>,
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<RegisterOnboardingImportContextPayload>,
|
||||
) -> Result<Json<RegisterOnboardingImportContextResponse>, ApiError> {
|
||||
Ok(Json(
|
||||
state
|
||||
.service
|
||||
.register_onboarding_import_context(&path.workspace_id.as_str().into(), payload)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn select_onboarding_import_draft(
|
||||
Path(path): Path<WorkspaceOnboardingPath>,
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<SelectOnboardingImportDraftPayload>,
|
||||
) -> Result<Json<SelectOnboardingImportDraftResponse>, ApiError> {
|
||||
Ok(Json(
|
||||
state
|
||||
.service
|
||||
.select_onboarding_import_draft(&path.workspace_id.as_str().into(), payload)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,16 @@ 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>,
|
||||
pub(super) unsafe_source: bool,
|
||||
}
|
||||
|
||||
struct StagedDependency {
|
||||
canonical_uri: String,
|
||||
bytes: Vec<u8>,
|
||||
document: String,
|
||||
}
|
||||
|
||||
pub(super) struct ImportReplayContext<'a> {
|
||||
@@ -22,10 +28,10 @@ impl MaterializedDependencies {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
snapshots: Vec::new(),
|
||||
secret_literal_rejected: false,
|
||||
envelopes: Vec::new(),
|
||||
canonical_uris: Vec::new(),
|
||||
guards: Vec::new(),
|
||||
unsafe_source: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,8 +184,8 @@ impl AdminService {
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut result = MaterializedDependencies::empty();
|
||||
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
|
||||
let mut staged = Vec::<StagedDependency>::new();
|
||||
let mut staged_documents = vec![primary.to_owned()];
|
||||
while let Some((canonical_uri, depth)) = queue.pop_front() {
|
||||
if !seen.insert(canonical_uri.clone())
|
||||
|| depth > self.external_reference_normalization.max_reference_depth
|
||||
@@ -196,52 +202,77 @@ impl AdminService {
|
||||
materialization_failure(
|
||||
"fetch",
|
||||
external_fetch_error_code(&error),
|
||||
result.snapshots.len(),
|
||||
staged.len(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(document) = std::str::from_utf8(&bytes).map(str::to_owned) else {
|
||||
materialization_failure(
|
||||
"dependency_decode",
|
||||
"invalid_utf8",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
materialization_failure("dependency_decode", "invalid_utf8", staged.len());
|
||||
continue;
|
||||
};
|
||||
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,
|
||||
) else {
|
||||
materialization_failure(
|
||||
"dependency_scan",
|
||||
"invalid_document",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
materialization_failure("dependency_scan", "invalid_document", staged.len());
|
||||
continue;
|
||||
};
|
||||
staged_documents.push(document.clone());
|
||||
staged.push(StagedDependency {
|
||||
canonical_uri: canonical_uri.clone(),
|
||||
bytes,
|
||||
document,
|
||||
});
|
||||
for reference in references {
|
||||
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
|
||||
{
|
||||
queue.push_back((uri, depth.saturating_add(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let staged_snapshots = staged
|
||||
.iter()
|
||||
.filter_map(|dependency| {
|
||||
let digest = format!("{:x}", Sha256::digest(&dependency.bytes));
|
||||
let digest = crank_import::rest::SourceDigest::parse(digest).ok()?;
|
||||
Some(crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: dependency.canonical_uri.clone(),
|
||||
digest,
|
||||
document: dependency.document.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let primary_digest =
|
||||
crank_import::rest::SourceDigest::parse(format!("{:x}", Sha256::digest(primary_bytes)))
|
||||
.expect("SHA-256 digest is valid");
|
||||
let raw_bundle_is_unsafe = crank_import::rest::validate_document_bundle_source_safe(
|
||||
&staged_documents
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
&self.external_reference_normalization,
|
||||
)
|
||||
.is_err();
|
||||
let resolved_bundle_is_unsafe = crank_import::rest::validate_resolved_bundle_source_safe(
|
||||
primary,
|
||||
primary_digest,
|
||||
&staged_snapshots,
|
||||
&self.external_reference_normalization,
|
||||
)
|
||||
.is_err();
|
||||
if raw_bundle_is_unsafe || resolved_bundle_is_unsafe {
|
||||
materialization_failure("dependency_redaction", "invalid_document", staged.len());
|
||||
let mut rejected = MaterializedDependencies::empty();
|
||||
rejected.unsafe_source = true;
|
||||
return rejected;
|
||||
}
|
||||
|
||||
let mut result = MaterializedDependencies::empty();
|
||||
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
|
||||
for dependency in staged {
|
||||
let store = self.artifact_store.clone();
|
||||
let artifact_bytes = bytes.clone();
|
||||
let artifact_bytes = dependency.bytes.clone();
|
||||
let Ok(Ok(artifact)) =
|
||||
tokio::task::spawn_blocking(move || store.put_registered(&artifact_bytes)).await
|
||||
else {
|
||||
@@ -317,31 +348,22 @@ impl AdminService {
|
||||
dependency_by_digest.insert(digest_key, index);
|
||||
index
|
||||
};
|
||||
let dependency = &result.envelopes[envelope_index];
|
||||
let snapshot_digest = match crank_import::rest::SourceDigest::parse(
|
||||
dependency.digest.digest_hex().to_owned(),
|
||||
) {
|
||||
Ok(digest) => digest,
|
||||
Err(_) => {
|
||||
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
|
||||
continue;
|
||||
}
|
||||
let dependency_envelope = &result.envelopes[envelope_index];
|
||||
let Ok(snapshot_digest) = crank_import::rest::SourceDigest::parse(
|
||||
dependency_envelope.digest.digest_hex().to_owned(),
|
||||
) else {
|
||||
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
|
||||
continue;
|
||||
};
|
||||
result
|
||||
.snapshots
|
||||
.push(crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: canonical_uri.clone(),
|
||||
canonical_uri: dependency.canonical_uri.clone(),
|
||||
digest: snapshot_digest,
|
||||
document,
|
||||
document: dependency.document,
|
||||
});
|
||||
materialized_count.store(result.snapshots.len(), std::sync::atomic::Ordering::Relaxed);
|
||||
result.canonical_uris.push(canonical_uri.clone());
|
||||
for reference in references {
|
||||
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
|
||||
{
|
||||
queue.push_back((uri, depth.saturating_add(1)));
|
||||
}
|
||||
}
|
||||
result.canonical_uris.push(dependency.canonical_uri);
|
||||
}
|
||||
// Registry ownership is one envelope per immutable digest, while the
|
||||
// resolver may map several canonical URIs to that same snapshot. Keep
|
||||
@@ -390,14 +412,6 @@ 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,976 @@
|
||||
mod validation;
|
||||
|
||||
use super::*;
|
||||
use crank_core::AuthConfig;
|
||||
use crank_import::rest::SecurityRequirementsSource as SecuritySource;
|
||||
|
||||
impl AdminService {
|
||||
pub async fn create_openapi_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &ImportJobId,
|
||||
payload: OpenApiImportPlanCreatePayload,
|
||||
) -> Result<OpenApiImportPlanCreateResponse, ApiError> {
|
||||
self.create_openapi_import_plan_with_locale(
|
||||
workspace_id,
|
||||
job_id,
|
||||
payload,
|
||||
OpenApiUploadLocale::En,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
|
||||
pub async fn create_openapi_import_plan_with_locale(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &ImportJobId,
|
||||
payload: OpenApiImportPlanCreatePayload,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<OpenApiImportPlanCreateResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let job = self
|
||||
.registry
|
||||
.get_import_job(workspace_id, job_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::not_found_with_context(
|
||||
"import job was not found",
|
||||
json!({ "job_id": job_id.as_str() }),
|
||||
)
|
||||
})?;
|
||||
if job.kind != ImportJobKind::OpenApi {
|
||||
return Err(ApiError::validation("import job kind is not openapi"));
|
||||
}
|
||||
if job.expires_at <= now {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => "срок действия preview импорта истёк",
|
||||
OpenApiUploadLocale::En => "import preview has expired",
|
||||
};
|
||||
return Err(ApiError::validation(message));
|
||||
}
|
||||
if job.status != ImportJobStatus::Pending {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_job_terminal",
|
||||
));
|
||||
}
|
||||
|
||||
if payload.decisions.len() > MAX_IMPORT_PLAN_KEYS {
|
||||
return Err(ApiError::validation(
|
||||
"too many decision blocks for this import plan",
|
||||
));
|
||||
}
|
||||
if payload.server_url.as_deref().is_some_and(|server_url| {
|
||||
server_url.is_empty() || server_url.len() > MAX_IMPORT_PLAN_SERVER_URL_BYTES
|
||||
}) {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"server_url is empty or too long",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
|
||||
// The plan is anchored to the verified job snapshots. A stale or
|
||||
// corrupt preview is reported as bounded re-preview guidance and
|
||||
// never mutates the job: other stored plans may still reference the
|
||||
// same job and its replay must remain readable.
|
||||
let resolved = self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
.map_err(|resolution| match resolution {
|
||||
ImportPreviewResolution::Fatal(error_code, _) => {
|
||||
import_plan_repreview_error(locale, error_code)
|
||||
}
|
||||
ImportPreviewResolution::NonFatal(error) => error,
|
||||
})?;
|
||||
let preview = &resolved.preview;
|
||||
let catalog_revision = self.registry.import_catalog_revision(workspace_id).await?;
|
||||
|
||||
// Stored external dependency snapshots are re-verified for every
|
||||
// replay variant (including historically persisted ones) without a
|
||||
// network fetch: detached or altered snapshots are re-preview
|
||||
// material and no plan is created.
|
||||
self.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
import_plan_repreview_error(locale, "import_dependency_verification_failed")
|
||||
})?;
|
||||
|
||||
let candidates: BTreeMap<String, &ImportOperationCandidate> = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| group.operations.iter())
|
||||
.map(|operation| (operation.key.clone(), operation))
|
||||
.collect();
|
||||
let all_set: BTreeSet<String> = candidates.keys().cloned().collect();
|
||||
if all_set.len() > MAX_IMPORT_PLAN_KEYS {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"too many candidates for an import plan",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
let selected = resolve_plan_selection(
|
||||
&payload.selection_mode,
|
||||
&payload.selected_operation_keys,
|
||||
&all_set,
|
||||
)?;
|
||||
if selected.len() > MAX_IMPORT_PLAN_KEYS
|
||||
|| all_set.len() - selected.len() > MAX_IMPORT_PLAN_KEYS
|
||||
{
|
||||
return Err(ApiError::validation_with_context(
|
||||
"too many candidates for an import plan",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
let selected_keys: Vec<String> = selected.iter().cloned().collect();
|
||||
let excluded: Vec<String> = all_set
|
||||
.iter()
|
||||
.filter(|key| !selected.contains(*key))
|
||||
.cloned()
|
||||
.collect();
|
||||
let excluded_reasons = excluded
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let name = candidates
|
||||
.get(key)
|
||||
.map(|candidate| candidate.draft.name.clone())
|
||||
.unwrap_or_else(|| key.clone());
|
||||
let reason = preview
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& finding.operation_key.is_none()
|
||||
})
|
||||
.map(|finding| finding.code.clone())
|
||||
.or_else(|| {
|
||||
candidates.get(key).and_then(|candidate| {
|
||||
candidate
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.severity == ImportFindingSeverity::Error)
|
||||
.map(|finding| finding.code.clone())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| "not_selected".to_owned());
|
||||
(key.clone(), (name, reason))
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let decisions = validation::validate_plan_decisions(&payload.decisions, &selected)?;
|
||||
|
||||
let global_blocker = preview
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none()
|
||||
})
|
||||
.map(|finding| finding.code.clone());
|
||||
|
||||
let mut planned = Vec::with_capacity(selected_keys.len());
|
||||
for key in &selected_keys {
|
||||
let Some(candidate) = candidates.get(key) else {
|
||||
unreachable!("selection is validated against the candidate set");
|
||||
};
|
||||
let blocker = global_blocker.clone().or_else(|| {
|
||||
candidate
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.severity == ImportFindingSeverity::Error)
|
||||
.map(|finding| finding.code.clone())
|
||||
});
|
||||
let candidate_plan = self
|
||||
.plan_import_candidate(
|
||||
workspace_id,
|
||||
payload.server_url.as_deref(),
|
||||
candidate,
|
||||
decisions.get(key).copied(),
|
||||
blocker,
|
||||
locale,
|
||||
)
|
||||
.await?;
|
||||
planned.push(candidate_plan);
|
||||
}
|
||||
|
||||
let counts = OpenApiImportPlanCounts {
|
||||
selected: planned.len(),
|
||||
excluded: excluded.len(),
|
||||
actionable: planned
|
||||
.iter()
|
||||
.filter(|candidate| !candidate.blocked)
|
||||
.count(),
|
||||
blocked: planned.iter().filter(|candidate| candidate.blocked).count(),
|
||||
};
|
||||
if payload.selection_mode == "partial" && counts.blocked != 0 {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"partial selection includes blocked candidates",
|
||||
json!({ "error_code": "import_plan_partial_blocked" }),
|
||||
));
|
||||
}
|
||||
if self.registry.import_catalog_revision(workspace_id).await? != catalog_revision {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_catalog_stale",
|
||||
));
|
||||
}
|
||||
|
||||
// Server-authored immutable plan. Client-supplied candidate material,
|
||||
// digests or payload fields are not read: every value below derives
|
||||
// from the verified job preview and the revalidated decisions.
|
||||
let all_keys: Vec<String> = all_set.iter().cloned().collect();
|
||||
let plan_counts_value = json!({
|
||||
"selected": counts.selected,
|
||||
"excluded": counts.excluded,
|
||||
"actionable": counts.actionable,
|
||||
"blocked": counts.blocked,
|
||||
});
|
||||
let plan_reference = new_prefixed_id("plan");
|
||||
let plan_payload = json!({
|
||||
"schema_version": "import-plan-v2",
|
||||
"plan_reference": plan_reference,
|
||||
"job_id": job_id.as_str(),
|
||||
"server_url": payload.server_url,
|
||||
"source": {
|
||||
"source_id": resolved.source.source_id.as_str(),
|
||||
"digest": resolved.source.digest.as_str(),
|
||||
},
|
||||
"dependencies": job.preview_payload.get("dependencies").cloned().unwrap_or(json!([])),
|
||||
"fingerprint": resolved.fingerprint,
|
||||
"catalog_revision": catalog_revision,
|
||||
"support_matrix_version": OPENAPI_SUPPORT_MATRIX_VERSION,
|
||||
"findings": {
|
||||
"document": preview.findings,
|
||||
"candidates": candidates.iter().map(|(key, candidate)| json!({
|
||||
"key": key,
|
||||
"findings": candidate.findings,
|
||||
})).collect::<Vec<_>>(),
|
||||
},
|
||||
"selection": {
|
||||
"mode": payload.selection_mode,
|
||||
"all": all_keys,
|
||||
"selected": selected_keys,
|
||||
"excluded": excluded,
|
||||
},
|
||||
"excluded_reasons": excluded_reasons.iter().map(|(key, (name, reason))| json!({
|
||||
"key": key,
|
||||
"name": name,
|
||||
"reason": reason,
|
||||
})).collect::<Vec<_>>(),
|
||||
"counts": plan_counts_value,
|
||||
"candidates": planned.iter().map(plan_candidate_payload).collect::<Result<Vec<_>, _>>()?,
|
||||
});
|
||||
|
||||
let plan_reference_id = ImportPlanId::new(&plan_reference);
|
||||
let created = self
|
||||
.registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_reference_id,
|
||||
workspace_id,
|
||||
job_id,
|
||||
payload: &plan_payload,
|
||||
created_at: &now,
|
||||
expires_at: &job.expires_at,
|
||||
})
|
||||
.await
|
||||
.map_err(ApiError::from)?;
|
||||
|
||||
let mut candidate_views: Vec<OpenApiImportPlanCandidateView> = planned
|
||||
.iter()
|
||||
.map(|candidate| OpenApiImportPlanCandidateView {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate.name.clone(),
|
||||
state: if candidate.blocked {
|
||||
"blocked"
|
||||
} else {
|
||||
"actionable"
|
||||
}
|
||||
.to_owned(),
|
||||
action: Some(candidate.action.clone()),
|
||||
target_operation_id: candidate.target_operation_id.clone(),
|
||||
confirmed_name: candidate.confirmed_name.clone(),
|
||||
auth_profile_id: candidate.auth_profile_id.clone(),
|
||||
security_alternative_index: candidate.security_alternative_index,
|
||||
reason: candidate.reason.clone(),
|
||||
})
|
||||
.collect();
|
||||
candidate_views.extend(excluded.iter().map(|key| {
|
||||
let name = excluded_reasons
|
||||
.get(key)
|
||||
.map(|(name, _)| name.clone())
|
||||
.unwrap_or_else(|| key.clone());
|
||||
OpenApiImportPlanCandidateView {
|
||||
key: key.clone(),
|
||||
name,
|
||||
state: "excluded".to_owned(),
|
||||
action: None,
|
||||
target_operation_id: None,
|
||||
confirmed_name: None,
|
||||
auth_profile_id: None,
|
||||
security_alternative_index: None,
|
||||
reason: excluded_reasons.get(key).map(|(_, reason)| reason.clone()),
|
||||
}
|
||||
}));
|
||||
|
||||
Ok(OpenApiImportPlanCreateResponse {
|
||||
plan_reference: created.id.as_str().to_owned(),
|
||||
plan_digest: created.digest,
|
||||
catalog_revision,
|
||||
support_matrix_version: OPENAPI_SUPPORT_MATRIX_VERSION.to_owned(),
|
||||
expires_at: created
|
||||
.expires_at
|
||||
.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
selection_mode: payload.selection_mode,
|
||||
counts,
|
||||
candidates: candidate_views,
|
||||
})
|
||||
}
|
||||
|
||||
/// Materializes one selected candidate of the plan: the confirmed
|
||||
/// decision, the exact authorized target with its expected state and the
|
||||
/// full Draft snapshot (create/rename/new_version) or the bounded
|
||||
/// redacted rejection reason (blocked).
|
||||
async fn plan_import_candidate(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
server_url: Option<&str>,
|
||||
candidate: &ImportOperationCandidate,
|
||||
decision: Option<&OpenApiImportPlanDecision>,
|
||||
blocker_reason: Option<String>,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<PlannedCandidate, ApiError> {
|
||||
let action = decision
|
||||
.map(|decision| decision.action.as_str())
|
||||
.unwrap_or("create");
|
||||
let target_operation_id =
|
||||
decision.and_then(|decision| decision.target_operation_id.clone());
|
||||
let confirmed_name = decision.and_then(|decision| decision.confirmed_name.clone());
|
||||
let auth_profile_id = decision.and_then(|decision| decision.auth_profile_id.clone());
|
||||
let requested_security_alternative =
|
||||
decision.and_then(|decision| decision.security_alternative_index);
|
||||
let mut blocker_reason = blocker_reason;
|
||||
let candidate_name = candidate.draft.name.clone();
|
||||
|
||||
let mut blocked = blocker_reason.is_some();
|
||||
|
||||
// Explicit skip/new_version targets are always resolved in the
|
||||
// workspace: an unknown target, a name mismatch, or an incompatible
|
||||
// protocol is a request error even when the candidate is already
|
||||
// blocked.
|
||||
let mut target = None;
|
||||
let mut target_summary = None;
|
||||
let mut next_version: Option<u32> = None;
|
||||
if matches!(action, "skip" | "new_version") {
|
||||
let target_id = target_operation_id
|
||||
.as_ref()
|
||||
.expect("target_operation_id is validated for skip/new_version")
|
||||
.clone();
|
||||
let target_operation = OperationId::new(target_id.clone());
|
||||
let summary = self
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &target_operation)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::validation_with_context(
|
||||
"decision target operation was not found in this workspace",
|
||||
json!({
|
||||
"target_operation_id": target_id,
|
||||
"error_code": "import_plan_target_invalid"
|
||||
}),
|
||||
)
|
||||
})?;
|
||||
if summary.name != candidate_name {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"decision target does not match the candidate name in this workspace",
|
||||
json!({
|
||||
"target_operation_id": target_id,
|
||||
"error_code": "import_plan_target_invalid"
|
||||
}),
|
||||
));
|
||||
}
|
||||
if action == "new_version"
|
||||
&& (summary.protocol != Protocol::Rest
|
||||
|| summary.status == OperationStatus::Archived)
|
||||
{
|
||||
return Err(ApiError::validation_with_context(
|
||||
"new_version target must be an active REST operation",
|
||||
json!({
|
||||
"target_operation_id": target_id,
|
||||
"error_code": "import_plan_target_invalid"
|
||||
}),
|
||||
));
|
||||
}
|
||||
target = Some(json!({
|
||||
"operation_id": target_id,
|
||||
"name": summary.name,
|
||||
"expected_state": {
|
||||
"status": serde_json::to_value(summary.status)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
"current_draft_version": summary.current_draft_version,
|
||||
"latest_published_version": summary.latest_published_version,
|
||||
},
|
||||
}));
|
||||
if action == "new_version" {
|
||||
let version = summary
|
||||
.current_draft_version
|
||||
.checked_add(1)
|
||||
.filter(|value| i32::try_from(*value).is_ok())
|
||||
.ok_or_else(|| {
|
||||
ApiError::conflict_with_context(
|
||||
"operation revision limit reached",
|
||||
json!({ "error_code": "operation_revision_exhausted" }),
|
||||
)
|
||||
})?;
|
||||
next_version = Some(version);
|
||||
}
|
||||
target_summary = Some(summary);
|
||||
}
|
||||
|
||||
// create/rename must land on a name that is free now; the server
|
||||
// never auto-selects a replacement when the confirmed name is taken.
|
||||
if !blocked && matches!(action, "create" | "rename") {
|
||||
let final_name = confirmed_name.as_deref().unwrap_or(candidate_name.as_str());
|
||||
if self
|
||||
.find_operation_by_name(workspace_id, final_name)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
if action == "create" && decision.is_none() {
|
||||
return Ok(PlannedCandidate {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate_name,
|
||||
blocked: true,
|
||||
reason: Some("operation_name_conflict".to_owned()),
|
||||
action: action.to_owned(),
|
||||
target_operation_id,
|
||||
confirmed_name,
|
||||
auth_profile_id,
|
||||
security_alternative_index: requested_security_alternative,
|
||||
auth_requirement: None,
|
||||
auth_snapshot: None,
|
||||
target: None,
|
||||
operation: None,
|
||||
});
|
||||
}
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => {
|
||||
format!("операция с именем {final_name} уже существует")
|
||||
}
|
||||
OpenApiUploadLocale::En => {
|
||||
format!("operation with name {final_name} already exists")
|
||||
}
|
||||
};
|
||||
return Err(ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"name": final_name,
|
||||
"error_code": "import_plan_name_conflict",
|
||||
"recovery": "confirm_skip_rename_or_new_version"
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Use an explicit decision or inherit the target reference for new_version.
|
||||
let mut auth_profile_ref = auth_profile_id
|
||||
.as_deref()
|
||||
.map(|id| AuthProfileId::new(id.to_owned()));
|
||||
let mut inherited_auth_profile = false;
|
||||
if let Some(summary) = target_summary.as_ref()
|
||||
&& !blocked
|
||||
&& action == "new_version"
|
||||
&& auth_profile_ref.is_none()
|
||||
&& (candidate.security_requirements.source == SecuritySource::None
|
||||
|| !candidate.security_requirements.alternatives.is_empty())
|
||||
{
|
||||
let record = self
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &summary.id, summary.current_draft_version)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::internal("current operation version is unavailable"))?;
|
||||
auth_profile_ref = record.snapshot.execution_config.auth_profile_ref;
|
||||
inherited_auth_profile = auth_profile_ref.is_some();
|
||||
}
|
||||
let auth_profile_id = auth_profile_ref.as_ref().map(|id| id.as_str().to_owned());
|
||||
let inherited_unconstrained_auth = inherited_auth_profile
|
||||
&& action == "new_version"
|
||||
&& candidate.security_requirements.source
|
||||
== crank_import::rest::SecurityRequirementsSource::None
|
||||
&& candidate.security_requirements.alternatives.is_empty()
|
||||
&& requested_security_alternative.is_none();
|
||||
let security_alternative_index = if blocked {
|
||||
requested_security_alternative
|
||||
} else if inherited_unconstrained_auth {
|
||||
None
|
||||
} else {
|
||||
resolve_security_binding(
|
||||
self,
|
||||
workspace_id,
|
||||
candidate,
|
||||
auth_profile_ref.as_ref(),
|
||||
requested_security_alternative,
|
||||
&mut blocker_reason,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
blocked = blocker_reason.is_some();
|
||||
let auth_requirement = if !blocked && inherited_unconstrained_auth {
|
||||
Some(json!({ "kind": "unconstrained" }))
|
||||
} else if !blocked && auth_profile_ref.is_some() {
|
||||
security_alternative_index
|
||||
.and_then(|index| candidate.security_requirements.alternatives.get(index))
|
||||
.and_then(|alternative| {
|
||||
(alternative.schemes.len() == 1).then(|| &alternative.schemes[0])
|
||||
})
|
||||
.and_then(|scheme_name| candidate.security_schemes.get(scheme_name))
|
||||
.and_then(|scheme| match &scheme.kind {
|
||||
crank_import::rest::NormalizedSecuritySchemeKind::Http { scheme, .. } => {
|
||||
match scheme.to_ascii_lowercase().as_str() {
|
||||
"bearer" => Some(json!({ "kind": "bearer" })),
|
||||
"basic" => Some(json!({ "kind": "basic" })),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: crank_import::rest::SecurityParameterLocation::Header,
|
||||
parameter_name,
|
||||
..
|
||||
} => {
|
||||
Some(json!({ "kind": "api_key_header", "parameter_name": parameter_name }))
|
||||
}
|
||||
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: crank_import::rest::SecurityParameterLocation::Query,
|
||||
parameter_name,
|
||||
..
|
||||
} => Some(json!({ "kind": "api_key_query", "parameter_name": parameter_name })),
|
||||
_ => None,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if blocked {
|
||||
return Ok(PlannedCandidate {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate_name,
|
||||
blocked: true,
|
||||
reason: blocker_reason,
|
||||
action: action.to_owned(),
|
||||
target_operation_id,
|
||||
confirmed_name,
|
||||
auth_profile_id,
|
||||
security_alternative_index,
|
||||
auth_requirement,
|
||||
auth_snapshot: None,
|
||||
target,
|
||||
operation: None,
|
||||
});
|
||||
}
|
||||
|
||||
if action == "skip" {
|
||||
return Ok(PlannedCandidate {
|
||||
key: candidate.key.clone(),
|
||||
name: candidate_name,
|
||||
blocked: false,
|
||||
reason: None,
|
||||
action: action.to_owned(),
|
||||
target_operation_id,
|
||||
confirmed_name,
|
||||
auth_profile_id,
|
||||
security_alternative_index,
|
||||
auth_requirement: None,
|
||||
auth_snapshot: None,
|
||||
target,
|
||||
operation: None,
|
||||
});
|
||||
}
|
||||
|
||||
let mut draft = operation_draft_from_candidate(candidate, server_url);
|
||||
if action == "rename" {
|
||||
draft.name = confirmed_name
|
||||
.clone()
|
||||
.expect("rename decisions carry the exact confirmed_name");
|
||||
}
|
||||
attach_import_findings(&mut draft, candidate);
|
||||
let operation = self.new_operation_snapshot(OperationPayload {
|
||||
name: draft.name.clone(),
|
||||
display_name: draft.display_name.clone(),
|
||||
category: draft.category,
|
||||
protocol: Protocol::Rest,
|
||||
security_level: OperationSecurityLevel::Standard,
|
||||
target: crank_core::Target::Rest(draft.target),
|
||||
input_schema: draft.input_schema,
|
||||
output_schema: draft.output_schema,
|
||||
input_mapping: draft.input_mapping,
|
||||
output_mapping: draft.output_mapping,
|
||||
execution_config: ExecutionConfig {
|
||||
timeout_ms: 10_000,
|
||||
retry_policy: None,
|
||||
response_cache: None,
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: draft.tool_description,
|
||||
wizard_state: draft.wizard_state,
|
||||
})?;
|
||||
// The same workspace/auth secret validator the operation creation
|
||||
// path uses: the referenced profile and its active secret refs must
|
||||
// resolve in this workspace before the plan is accepted.
|
||||
self.validate_registry_operation_in_workspace(workspace_id, &operation)
|
||||
.await?;
|
||||
let mut operation = operation;
|
||||
if action == "new_version" {
|
||||
let target_id = target_operation_id
|
||||
.clone()
|
||||
.expect("new_version decisions carry target_operation_id");
|
||||
operation.id = OperationId::new(target_id);
|
||||
operation.version = next_version.expect("new_version computes the next Draft version");
|
||||
}
|
||||
let auth_snapshot = match operation.execution_config.auth_profile_ref.as_ref() {
|
||||
Some(profile_id) => Some(self.import_auth_snapshot(workspace_id, profile_id).await?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(PlannedCandidate {
|
||||
key: candidate.key.clone(),
|
||||
name: draft.name,
|
||||
blocked: false,
|
||||
reason: None,
|
||||
action: action.to_owned(),
|
||||
target_operation_id,
|
||||
confirmed_name,
|
||||
auth_profile_id,
|
||||
security_alternative_index,
|
||||
auth_requirement,
|
||||
auth_snapshot,
|
||||
target,
|
||||
operation: Some(operation),
|
||||
})
|
||||
}
|
||||
|
||||
/// Captures only profile configuration and secret metadata. Credential
|
||||
/// values never enter the plan; Apply compares this snapshot under locks.
|
||||
async fn import_auth_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile_id: &AuthProfileId,
|
||||
) -> Result<Value, ApiError> {
|
||||
let unavailable = || {
|
||||
ApiError::unprocessable_with_context(
|
||||
"The selected authentication profile is unavailable for this import.",
|
||||
json!({ "error_code": "import_plan_auth_unavailable" }),
|
||||
)
|
||||
};
|
||||
let profile = self
|
||||
.registry
|
||||
.get_auth_profile(workspace_id, profile_id)
|
||||
.await?
|
||||
.ok_or_else(unavailable)?;
|
||||
let mut secret_ids: Vec<String> = profile
|
||||
.config
|
||||
.secret_ids()
|
||||
.into_iter()
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.collect();
|
||||
secret_ids.sort();
|
||||
secret_ids.dedup();
|
||||
let mut secrets = Vec::with_capacity(secret_ids.len());
|
||||
for id in secret_ids {
|
||||
let secret = self
|
||||
.registry
|
||||
.get_secret(workspace_id, &crank_core::SecretId::new(id.clone()))
|
||||
.await?
|
||||
.ok_or_else(unavailable)?
|
||||
.secret;
|
||||
secrets.push(json!({
|
||||
"id": id,
|
||||
"status": secret.status,
|
||||
"current_version": secret.current_version,
|
||||
"updated_at": secret.updated_at.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
}));
|
||||
}
|
||||
Ok(json!({
|
||||
"profile_id": profile_id.as_str(),
|
||||
"name": profile.name,
|
||||
"kind": profile.kind,
|
||||
"config": profile.config,
|
||||
"updated_at": profile.updated_at.format(&Rfc3339)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||
"secrets": secrets,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
struct PlannedCandidate {
|
||||
key: String,
|
||||
name: String,
|
||||
blocked: bool,
|
||||
reason: Option<String>,
|
||||
action: String,
|
||||
target_operation_id: Option<String>,
|
||||
confirmed_name: Option<String>,
|
||||
auth_profile_id: Option<String>,
|
||||
security_alternative_index: Option<usize>,
|
||||
auth_requirement: Option<Value>,
|
||||
auth_snapshot: Option<Value>,
|
||||
target: Option<Value>,
|
||||
operation: Option<RegistryOperation>,
|
||||
}
|
||||
|
||||
pub(super) fn import_plan_repreview_error(
|
||||
locale: OpenApiUploadLocale,
|
||||
error_code: &'static str,
|
||||
) -> ApiError {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => {
|
||||
"не удалось повторно проверить план импорта; создайте новый preview"
|
||||
}
|
||||
OpenApiUploadLocale::En => "import plan revalidation failed; create a fresh preview",
|
||||
};
|
||||
ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"error_code": error_code,
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Closes the selection against the current preview: `full` keeps every
|
||||
/// candidate (an explicit list must equal the whole candidate set), `partial`
|
||||
/// requires a non-empty exact subset. Unknown or duplicate keys are rejected
|
||||
/// before any plan material exists.
|
||||
fn resolve_plan_selection(
|
||||
selection_mode: &str,
|
||||
requested: &[String],
|
||||
all: &BTreeSet<String>,
|
||||
) -> Result<BTreeSet<String>, ApiError> {
|
||||
if !matches!(selection_mode, "full" | "partial") {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selection_mode must be full or partial",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
if requested.len() > MAX_IMPORT_PLAN_KEYS {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"too many selected_operation_keys for this import plan",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
for key in requested {
|
||||
if key.is_empty() || key.len() > MAX_IMPORT_PLAN_KEY_BYTES {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected_operation_keys entries are empty or too long",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
}
|
||||
let requested_set: BTreeSet<&String> = requested.iter().collect();
|
||||
if requested_set.len() != requested.len() {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected_operation_keys contains duplicates",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
let all_set: BTreeSet<&String> = all.iter().collect();
|
||||
match selection_mode {
|
||||
"full" => {
|
||||
if !requested_set.is_empty() && requested_set != all_set {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"full selection covers the entire candidate set; selected_operation_keys does not match the preview",
|
||||
json!({ "error_code": "import_plan_selection_mismatch" }),
|
||||
));
|
||||
}
|
||||
Ok(all.clone())
|
||||
}
|
||||
_ => {
|
||||
if requested_set.is_empty() {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"partial selection requires at least one selected_operation_key",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
if !requested_set.is_subset(&all_set) {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected_operation_keys reference operations absent from the preview",
|
||||
json!({ "error_code": "import_plan_unknown_operation_key" }),
|
||||
));
|
||||
}
|
||||
Ok(requested.iter().cloned().collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_security_binding(
|
||||
service: &AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
candidate: &ImportOperationCandidate,
|
||||
profile_ref: Option<&AuthProfileId>,
|
||||
requested_index: Option<usize>,
|
||||
blocker_reason: &mut Option<String>,
|
||||
) -> Result<Option<usize>, ApiError> {
|
||||
let alternatives = &candidate.security_requirements.alternatives;
|
||||
if alternatives.is_empty() {
|
||||
if profile_ref.is_some() || requested_index.is_some() {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"security binding was supplied for an operation with no security requirement",
|
||||
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
|
||||
));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let public_index = alternatives
|
||||
.iter()
|
||||
.position(|alternative| alternative.supported && alternative.schemes.is_empty());
|
||||
let compatible = if let Some(profile_ref) = profile_ref {
|
||||
let profile = service
|
||||
.registry
|
||||
.get_auth_profile(workspace_id, profile_ref)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::unprocessable_with_context(
|
||||
"selected Auth Profile is unavailable in this workspace",
|
||||
json!({ "error_code": "import_plan_auth_unavailable" }),
|
||||
)
|
||||
})?;
|
||||
let compatible = alternatives
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, alternative)| {
|
||||
alternative.supported
|
||||
&& alternative.schemes.len() == 1
|
||||
&& candidate
|
||||
.security_schemes
|
||||
.get(&alternative.schemes[0])
|
||||
.is_some_and(|scheme| auth_config_matches_scheme(&profile.config, scheme))
|
||||
})
|
||||
.map(|(index, _)| index)
|
||||
.collect::<Vec<_>>();
|
||||
Some((profile, compatible))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some((_, compatible_indices)) = compatible.as_ref() {
|
||||
let selected = match requested_index {
|
||||
Some(index) if compatible_indices.contains(&index) => index,
|
||||
Some(_) => {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected Auth Profile is incompatible with the selected security alternative",
|
||||
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
|
||||
));
|
||||
}
|
||||
None if compatible_indices.len() == 1 => compatible_indices[0],
|
||||
None if compatible_indices.is_empty() => {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected Auth Profile is incompatible with the source security schemes",
|
||||
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"security_alternative_index is required when a profile matches multiple alternatives",
|
||||
json!({ "operation_key": candidate.key, "error_code": "import_plan_security_alternative_required" }),
|
||||
));
|
||||
}
|
||||
};
|
||||
return Ok(Some(selected));
|
||||
}
|
||||
|
||||
if let Some(index) = requested_index {
|
||||
if alternatives
|
||||
.get(index)
|
||||
.is_none_or(|alternative| !alternative.supported)
|
||||
{
|
||||
return Err(ApiError::validation_with_context(
|
||||
"selected security alternative is unsupported",
|
||||
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
|
||||
));
|
||||
}
|
||||
if alternatives[index].schemes.is_empty() {
|
||||
return Ok(Some(index));
|
||||
}
|
||||
}
|
||||
if let Some(public_index) = public_index
|
||||
&& requested_index.is_none()
|
||||
{
|
||||
return Ok(Some(public_index));
|
||||
}
|
||||
*blocker_reason = Some("auth_profile_required".to_owned());
|
||||
Ok(requested_index)
|
||||
}
|
||||
|
||||
pub(super) fn auth_config_matches_scheme(
|
||||
config: &AuthConfig,
|
||||
scheme: &crank_import::rest::NormalizedSecurityScheme,
|
||||
) -> bool {
|
||||
use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
|
||||
match (&scheme.kind, config) {
|
||||
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Bearer(_)) => {
|
||||
scheme.eq_ignore_ascii_case("bearer")
|
||||
}
|
||||
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Basic(_)) => {
|
||||
scheme.eq_ignore_ascii_case("basic")
|
||||
}
|
||||
(
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Header,
|
||||
parameter_name,
|
||||
..
|
||||
},
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => parameter_name.eq_ignore_ascii_case(&config.header_name),
|
||||
(
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Query,
|
||||
parameter_name,
|
||||
..
|
||||
},
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => parameter_name == &config.param_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes one planned candidate into the versioned plan payload: the
|
||||
/// redacted decision, the bounded rejection reason (if any), the exact
|
||||
/// authorized target with expected state and, for mutating actions, the full
|
||||
/// server-authored Draft snapshot.
|
||||
fn plan_candidate_payload(candidate: &PlannedCandidate) -> Result<Value, ApiError> {
|
||||
let mut object = json!({
|
||||
"key": candidate.key,
|
||||
"name": candidate.name,
|
||||
"state": if candidate.blocked { "blocked" } else { "actionable" },
|
||||
"decision": {
|
||||
"action": candidate.action,
|
||||
"target_operation_id": candidate.target_operation_id,
|
||||
"confirmed_name": candidate.confirmed_name,
|
||||
"auth_profile_id": candidate.auth_profile_id,
|
||||
"security_alternative_index": candidate.security_alternative_index,
|
||||
},
|
||||
});
|
||||
if let Some(reason) = &candidate.reason {
|
||||
object["reason"] = json!(reason);
|
||||
}
|
||||
if let Some(target) = &candidate.target {
|
||||
object["target"] = target.clone();
|
||||
}
|
||||
if let Some(auth_snapshot) = &candidate.auth_snapshot {
|
||||
object["auth_snapshot"] = auth_snapshot.clone();
|
||||
}
|
||||
if let Some(auth_requirement) = &candidate.auth_requirement {
|
||||
object["auth_requirement"] = auth_requirement.clone();
|
||||
}
|
||||
if let Some(operation) = &candidate.operation {
|
||||
let value = serde_json::to_value(operation)
|
||||
.map_err(|error| ApiError::internal(error.to_string()))?;
|
||||
object["operation"] = value;
|
||||
}
|
||||
Ok(object)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use super::*;
|
||||
|
||||
/// Binds decisions to selected candidates with action-specific field rules:
|
||||
/// unknown/duplicate keys, foreign fields and oversized references are
|
||||
/// rejected before the plan is materialized.
|
||||
pub(super) fn validate_plan_decisions<'input>(
|
||||
decisions: &'input [OpenApiImportPlanDecision],
|
||||
selected: &BTreeSet<String>,
|
||||
) -> Result<BTreeMap<String, &'input OpenApiImportPlanDecision>, ApiError> {
|
||||
let invalid = |context: Value| {
|
||||
Err(ApiError::validation_with_context(
|
||||
"import plan decision is invalid",
|
||||
context,
|
||||
))
|
||||
};
|
||||
let mut mapping = BTreeMap::new();
|
||||
for decision in decisions {
|
||||
if decision.operation_key.is_empty()
|
||||
|| decision.operation_key.len() > MAX_IMPORT_PLAN_KEY_BYTES
|
||||
{
|
||||
return invalid(json!({
|
||||
"operation_key": decision.operation_key,
|
||||
"error_code": "import_plan_invalid_input"
|
||||
}));
|
||||
}
|
||||
if !matches!(
|
||||
decision.action.as_str(),
|
||||
"create" | "skip" | "rename" | "new_version"
|
||||
) {
|
||||
return invalid(json!({
|
||||
"operation_key": decision.operation_key,
|
||||
"error_code": "import_plan_invalid_input"
|
||||
}));
|
||||
}
|
||||
validate_decision_fields(decision)?;
|
||||
if !selected.contains(&decision.operation_key) {
|
||||
return invalid(json!({
|
||||
"operation_key": decision.operation_key,
|
||||
"error_code": "import_plan_decision_unselected"
|
||||
}));
|
||||
}
|
||||
if mapping
|
||||
.insert(decision.operation_key.clone(), decision)
|
||||
.is_some()
|
||||
{
|
||||
return invalid(json!({
|
||||
"operation_key": decision.operation_key,
|
||||
"error_code": "import_plan_invalid_input"
|
||||
}));
|
||||
}
|
||||
}
|
||||
Ok(mapping)
|
||||
}
|
||||
|
||||
fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(), ApiError> {
|
||||
let context = json!({
|
||||
"operation_key": decision.operation_key,
|
||||
"error_code": "import_plan_invalid_input"
|
||||
});
|
||||
let invalid = |message: &str| -> Result<(), ApiError> {
|
||||
Err(ApiError::validation_with_context(message, context.clone()))
|
||||
};
|
||||
if decision
|
||||
.target_operation_id
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
|
||||
{
|
||||
return invalid("decision target_operation_id is empty or too long");
|
||||
}
|
||||
if decision
|
||||
.confirmed_name
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_NAME_BYTES)
|
||||
{
|
||||
return invalid("decision confirmed_name is empty or too long");
|
||||
}
|
||||
if decision
|
||||
.auth_profile_id
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
|
||||
{
|
||||
return invalid("decision auth_profile_id is empty or too long");
|
||||
}
|
||||
if decision
|
||||
.security_alternative_index
|
||||
.is_some_and(|index| index > MAX_IMPORT_PLAN_KEYS)
|
||||
{
|
||||
return invalid("decision security_alternative_index is too large");
|
||||
}
|
||||
match decision.action.as_str() {
|
||||
"create" => {
|
||||
if decision.target_operation_id.is_some() || decision.confirmed_name.is_some() {
|
||||
return invalid(
|
||||
"target_operation_id and confirmed_name are not allowed for action create",
|
||||
);
|
||||
}
|
||||
}
|
||||
"skip" => {
|
||||
if decision.auth_profile_id.is_some() || decision.security_alternative_index.is_some() {
|
||||
return invalid("security binding is not allowed for action skip");
|
||||
}
|
||||
if decision.target_operation_id.is_none() {
|
||||
return invalid("action skip requires the exact target_operation_id");
|
||||
}
|
||||
if decision.confirmed_name.is_some() {
|
||||
return invalid("confirmed_name is not allowed for action skip");
|
||||
}
|
||||
}
|
||||
"rename" => {
|
||||
if decision.target_operation_id.is_some() {
|
||||
return invalid("target_operation_id is not allowed for action rename");
|
||||
}
|
||||
if decision.confirmed_name.is_none() {
|
||||
return invalid("action rename requires the exact confirmed_name");
|
||||
}
|
||||
}
|
||||
"new_version" => {
|
||||
if decision.target_operation_id.is_none() {
|
||||
return invalid("action new_version requires the exact target_operation_id");
|
||||
}
|
||||
if decision.confirmed_name.is_some() {
|
||||
return invalid("confirmed_name is not allowed for action new_version");
|
||||
}
|
||||
}
|
||||
_ => unreachable!("decision action is validated before the field rules"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
use super::*;
|
||||
use crank_registry::{ApplyImportPlanRequest, ImportPlanApplyReport};
|
||||
|
||||
const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
|
||||
|
||||
impl AdminService {
|
||||
/// Reads an immutable plan and checks its current authority without Apply mutations.
|
||||
pub async fn revalidate_openapi_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
|
||||
self.revalidate_openapi_import_plan_with_locale(
|
||||
workspace_id,
|
||||
plan_id,
|
||||
OpenApiUploadLocale::En,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Locale-aware variant used by the HTTP boundary.
|
||||
pub async fn revalidate_openapi_import_plan_with_locale(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
let plan = self
|
||||
.registry
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
)
|
||||
})?;
|
||||
let mut reason = None;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
reason = Some("import_plan_expired");
|
||||
} else if let Some(job) = self
|
||||
.registry
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
{
|
||||
if job.kind != ImportJobKind::OpenApi
|
||||
|| job.status != ImportJobStatus::Pending
|
||||
|| job.expires_at <= now
|
||||
{
|
||||
reason = Some("import_plan_job_terminal");
|
||||
} else {
|
||||
match self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => {
|
||||
let v2 = plan.payload.get("schema_version").and_then(Value::as_str)
|
||||
== Some("import-plan-v2");
|
||||
if self
|
||||
.read_import_job_dependencies(
|
||||
workspace_id,
|
||||
&job.preview_payload,
|
||||
locale,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
reason = Some("import_dependency_verification_failed");
|
||||
} else if !v2 {
|
||||
// Historical plans stay readable for audit, but lack the
|
||||
// catalog evidence required for current Apply authority.
|
||||
reason = Some("importer_version_changed");
|
||||
} else if resolved
|
||||
.fingerprint
|
||||
.get("normalizer_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(NORMALIZER_VERSION)
|
||||
|| resolved
|
||||
.fingerprint
|
||||
.get("projection_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(PROJECTION_VERSION)
|
||||
|| plan
|
||||
.payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION)
|
||||
{
|
||||
reason = Some("importer_version_changed");
|
||||
} else if self
|
||||
.registry
|
||||
.revalidate_import_plan(workspace_id, plan_id, &resolved.fingerprint)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
reason = Some("import_plan_revalidation_failed");
|
||||
}
|
||||
}
|
||||
Err(_) => reason = Some("import_preview_revalidation_failed"),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reason = Some("import_plan_job_unavailable");
|
||||
}
|
||||
|
||||
let counts = &plan.payload["counts"];
|
||||
let count = |key: &str| {
|
||||
counts
|
||||
.get(key)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| usize::try_from(value).ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let selected = plan.payload["candidates"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|candidate| {
|
||||
let decision = &candidate["decision"];
|
||||
let string = |value: &Value| value.as_str().map(str::to_owned);
|
||||
OpenApiImportPlanCandidateView {
|
||||
key: string(&candidate["key"]).unwrap_or_default(),
|
||||
name: string(&candidate["name"]).unwrap_or_default(),
|
||||
state: string(&candidate["state"]).unwrap_or_default(),
|
||||
action: string(&decision["action"]),
|
||||
target_operation_id: string(&decision["target_operation_id"]),
|
||||
confirmed_name: string(&decision["confirmed_name"]),
|
||||
auth_profile_id: string(&decision["auth_profile_id"]),
|
||||
security_alternative_index: decision["security_alternative_index"]
|
||||
.as_u64()
|
||||
.and_then(|value| usize::try_from(value).ok()),
|
||||
reason: string(&candidate["reason"]),
|
||||
}
|
||||
});
|
||||
let excluded = plan
|
||||
.payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|key| OpenApiImportPlanCandidateView {
|
||||
key: key.to_owned(),
|
||||
name: excluded_candidate_display_name(&plan.payload, key),
|
||||
state: "excluded".to_owned(),
|
||||
action: None,
|
||||
target_operation_id: None,
|
||||
confirmed_name: None,
|
||||
auth_profile_id: None,
|
||||
security_alternative_index: None,
|
||||
reason: plan.payload["excluded_reasons"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
|
||||
.and_then(|item| item["reason"].as_str())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| Some("not_selected".to_owned())),
|
||||
});
|
||||
Ok(OpenApiImportPlanRevalidationResponse {
|
||||
plan_reference: plan.id.as_str().to_owned(),
|
||||
plan_digest: plan.digest,
|
||||
revalidation_status: if reason.is_some() { "stale" } else { "current" }.to_owned(),
|
||||
revalidation_required: reason.is_some(),
|
||||
reason: reason.map(str::to_owned),
|
||||
counts: OpenApiImportPlanCounts {
|
||||
selected: count("selected"),
|
||||
excluded: count("excluded"),
|
||||
actionable: count("actionable"),
|
||||
blocked: count("blocked"),
|
||||
},
|
||||
candidates: selected.chain(excluded).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn apply_openapi_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
payload: OpenApiImportPlanApplyPayload,
|
||||
) -> Result<ImportPlanApplyReport, ApiError> {
|
||||
self.apply_openapi_import_plan_with_locale(
|
||||
workspace_id,
|
||||
plan_id,
|
||||
payload,
|
||||
OpenApiUploadLocale::En,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), plan_id = %plan_id.as_str()))]
|
||||
pub async fn apply_openapi_import_plan_with_locale(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
payload: OpenApiImportPlanApplyPayload,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<ImportPlanApplyReport, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
validate_apply_payload(&payload)?;
|
||||
|
||||
// The replay row is deliberately checked before the plan or job.
|
||||
// Its report remains authoritative after normal TTL cleanup removes
|
||||
// those source rows.
|
||||
if let Some(application) = self
|
||||
.registry
|
||||
.get_import_plan_application(workspace_id, &payload.idempotency_key)
|
||||
.await?
|
||||
{
|
||||
if application.plan_digest != payload.plan_digest {
|
||||
return Err(key_digest_conflict(locale));
|
||||
}
|
||||
return Ok(application.result.report);
|
||||
}
|
||||
|
||||
let plan = self
|
||||
.registry
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
)
|
||||
})?;
|
||||
|
||||
if plan.digest != payload.plan_digest {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_digest_mismatch",
|
||||
));
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
return Err(import_plan_repreview_error(locale, "import_plan_expired"));
|
||||
}
|
||||
|
||||
let job = self
|
||||
.registry
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
.ok_or_else(|| import_plan_repreview_error(locale, "import_plan_job_unavailable"))?;
|
||||
if job.kind != ImportJobKind::OpenApi {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_job_kind_mismatch",
|
||||
));
|
||||
}
|
||||
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"import_plan_job_terminal",
|
||||
));
|
||||
}
|
||||
|
||||
let resolved = self
|
||||
.resolve_verified_openapi_preview(workspace_id, &job, locale)
|
||||
.await
|
||||
.map_err(|resolution| match resolution {
|
||||
ImportPreviewResolution::Fatal(error_code, _) => {
|
||||
import_plan_repreview_error(locale, error_code)
|
||||
}
|
||||
ImportPreviewResolution::NonFatal(_) => {
|
||||
import_plan_repreview_error(locale, "import_preview_revalidation_failed")
|
||||
}
|
||||
})?;
|
||||
|
||||
// Applying a new plan requires the current normalizer/projection
|
||||
// contract. Historic jobs remain available to the legacy replay path,
|
||||
// but a plan created from a historic projection must be previewed
|
||||
// again before it can authorize mutations.
|
||||
if resolved
|
||||
.fingerprint
|
||||
.get("normalizer_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(NORMALIZER_VERSION)
|
||||
|| resolved
|
||||
.fingerprint
|
||||
.get("projection_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(PROJECTION_VERSION)
|
||||
|| (plan.payload.get("schema_version").and_then(Value::as_str)
|
||||
== Some("import-plan-v2")
|
||||
&& plan
|
||||
.payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION))
|
||||
{
|
||||
return Err(import_plan_repreview_error(
|
||||
locale,
|
||||
"importer_version_changed",
|
||||
));
|
||||
}
|
||||
|
||||
// Verify every persisted external snapshot again without making a
|
||||
// network request. The registry repeats source/dependency checks
|
||||
// under its transaction before it mutates operations.
|
||||
self.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
import_plan_repreview_error(locale, "import_dependency_verification_failed")
|
||||
})?;
|
||||
|
||||
let result = self
|
||||
.registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id,
|
||||
plan_id,
|
||||
plan_digest: &payload.plan_digest,
|
||||
idempotency_key: &payload.idempotency_key,
|
||||
verified_fingerprint: &resolved.fingerprint,
|
||||
applied_at: &now,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| map_apply_registry_error(locale, error))?;
|
||||
Ok(result.report)
|
||||
}
|
||||
}
|
||||
|
||||
fn excluded_candidate_display_name(plan: &Value, key: &str) -> String {
|
||||
plan["excluded_reasons"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
|
||||
.and_then(|item| item["name"].as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or(key)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn validate_apply_payload(payload: &OpenApiImportPlanApplyPayload) -> Result<(), ApiError> {
|
||||
let digest_valid = payload.plan_digest.len() == 64
|
||||
&& payload
|
||||
.plan_digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
|
||||
if !digest_valid {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"plan_digest must be 64 lowercase hexadecimal characters",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
if !(1..=MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES).contains(&payload.idempotency_key.len())
|
||||
|| payload.idempotency_key.trim() != payload.idempotency_key
|
||||
|| payload.idempotency_key.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ApiError::validation_with_context(
|
||||
"idempotency_key must be a non-empty bounded printable value",
|
||||
json!({ "error_code": "import_plan_invalid_input" }),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_apply_registry_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
|
||||
match error {
|
||||
RegistryError::ImportPlanNotFound { .. } => ApiError::not_found_with_context(
|
||||
"import plan was not found in this workspace",
|
||||
json!({ "error_code": "import_plan_not_found" }),
|
||||
),
|
||||
RegistryError::ImportPlanExpired { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_expired")
|
||||
}
|
||||
RegistryError::ImportPlanPayloadCorrupt { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_payload_invalid")
|
||||
}
|
||||
RegistryError::ImportPlanFingerprintStale { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_fingerprint_stale")
|
||||
}
|
||||
RegistryError::ImportPlanKeyDigestConflict { .. } => key_digest_conflict(locale),
|
||||
RegistryError::ImportPlanNameConflict { .. } => {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => "имя операции изменилось после создания плана",
|
||||
OpenApiUploadLocale::En => "an operation name changed after the plan was created",
|
||||
};
|
||||
ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"error_code": "import_plan_name_conflict",
|
||||
"recovery": "confirm_skip_rename_or_new_version"
|
||||
}),
|
||||
)
|
||||
}
|
||||
RegistryError::ImportPlanTargetStale { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_target_stale")
|
||||
}
|
||||
RegistryError::ImportPlanAuthUnavailable { .. } => {
|
||||
import_plan_repreview_error(locale, "import_plan_auth_unavailable")
|
||||
}
|
||||
other => ApiError::from(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn key_digest_conflict(locale: OpenApiUploadLocale) -> ApiError {
|
||||
let message = match locale {
|
||||
OpenApiUploadLocale::Ru => {
|
||||
"ключ идемпотентности уже зафиксирован для другого материала плана; создайте новый preview"
|
||||
}
|
||||
OpenApiUploadLocale::En => {
|
||||
"idempotency key was already committed for different plan material"
|
||||
}
|
||||
};
|
||||
ApiError::conflict_with_context(
|
||||
message,
|
||||
json!({
|
||||
"error_code": "import_plan_key_digest_conflict",
|
||||
"recovery": "repreview_required",
|
||||
"repreview_required": true
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::excluded_candidate_display_name;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn excluded_candidate_name_uses_persisted_display_name_and_legacy_key_fallback() {
|
||||
let current = json!({
|
||||
"excluded_reasons": [{
|
||||
"key": "GET /alpha",
|
||||
"name": "Alpha display label",
|
||||
"reason": "not_selected"
|
||||
}]
|
||||
});
|
||||
assert_eq!(
|
||||
excluded_candidate_display_name(¤t, "GET /alpha"),
|
||||
"Alpha display label"
|
||||
);
|
||||
|
||||
let historic = json!({
|
||||
"excluded_reasons": [{ "key": "GET /alpha", "reason": "not_selected" }]
|
||||
});
|
||||
assert_eq!(
|
||||
excluded_candidate_display_name(&historic, "GET /alpha"),
|
||||
"GET /alpha"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
use super::*;
|
||||
|
||||
/// Revalidates the verified source/dependency snapshots and the persisted
|
||||
/// replay contract of a stored job without mutating the job. Both the
|
||||
/// legacy Apply and the ImportPlan creation derive from this result, so
|
||||
/// the legacy failure-text code travels with the outcome.
|
||||
impl AdminService {
|
||||
pub(super) async fn resolve_verified_openapi_preview(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
job: &ImportJob,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<ResolvedOpenApiPreview, ImportPreviewResolution> {
|
||||
let source = match import_job_source(&job.preview_payload, locale) {
|
||||
Ok(source) => source,
|
||||
Err(error) => {
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_source_verification_failed",
|
||||
error,
|
||||
));
|
||||
}
|
||||
};
|
||||
let verified = match self
|
||||
.registry
|
||||
.read_artifact_source(
|
||||
std::sync::Arc::clone(&self.artifact_store),
|
||||
workspace_id,
|
||||
&source.source_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(verified) => verified,
|
||||
Err(
|
||||
error @ (RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable),
|
||||
) => {
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_source_verification_failed",
|
||||
openapi_source_error(locale, error),
|
||||
));
|
||||
}
|
||||
Err(error @ RegistryError::SourceIntegrity) => {
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_source_verification_failed",
|
||||
openapi_source_error(locale, error),
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(ImportPreviewResolution::NonFatal(openapi_source_error(
|
||||
locale, error,
|
||||
)));
|
||||
}
|
||||
};
|
||||
if verified.source.blob.artifact_ref != source.digest {
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_source_verification_failed",
|
||||
ApiError::openapi_upload(locale, "source_integrity"),
|
||||
));
|
||||
}
|
||||
let replay_contract = match import_replay_contract(&job.preview_payload, locale) {
|
||||
Ok(contract) => contract,
|
||||
Err(error) => {
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
));
|
||||
}
|
||||
};
|
||||
let (preview, normalizer_version, projection_version, ir_fingerprint) =
|
||||
match replay_contract {
|
||||
ImportReplayContract::PersistedV2(replay) => (
|
||||
replay.preview.preview,
|
||||
replay.normalizer_version,
|
||||
replay.projection_version,
|
||||
replay.preview.ir_fingerprint,
|
||||
),
|
||||
ImportReplayContract::LegacyV1 | ImportReplayContract::Current => {
|
||||
let legacy_v1 = matches!(replay_contract, ImportReplayContract::LegacyV1);
|
||||
let dependency_snapshots = self
|
||||
.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
ImportPreviewResolution::Fatal(
|
||||
"import_dependency_verification_failed",
|
||||
error,
|
||||
)
|
||||
})?;
|
||||
let normalization_config = import_job_normalization_config(
|
||||
&job.preview_payload,
|
||||
&self.external_reference_normalization,
|
||||
legacy_v1,
|
||||
locale,
|
||||
)
|
||||
.map_err(|error| {
|
||||
ImportPreviewResolution::Fatal("import_replay_verification_failed", error)
|
||||
})?;
|
||||
let parsed = parse_verified_preview(
|
||||
verified.bytes,
|
||||
source.digest.digest_hex().to_owned(),
|
||||
dependency_snapshots,
|
||||
normalization_config,
|
||||
locale,
|
||||
legacy_v1,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
ImportPreviewResolution::Fatal("import_replay_verification_failed", error)
|
||||
})?;
|
||||
if let Err(error) =
|
||||
verify_preview_contract(&job.preview_payload, &parsed, locale)
|
||||
{
|
||||
return Err(ImportPreviewResolution::Fatal(
|
||||
"import_replay_verification_failed",
|
||||
error,
|
||||
));
|
||||
}
|
||||
if legacy_v1 {
|
||||
(parsed.preview, String::new(), String::new(), String::new())
|
||||
} else {
|
||||
(
|
||||
parsed.preview,
|
||||
NORMALIZER_VERSION.to_owned(),
|
||||
PROJECTION_VERSION.to_owned(),
|
||||
parsed.ir_fingerprint,
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(ResolvedOpenApiPreview {
|
||||
source,
|
||||
preview,
|
||||
fingerprint: json!({
|
||||
"normalizer_version": if normalizer_version.is_empty() { Value::Null } else { Value::String(normalizer_version) },
|
||||
"projection_version": if projection_version.is_empty() { Value::Null } else { Value::String(projection_version) },
|
||||
"ir_fingerprint": if ir_fingerprint.is_empty() { Value::Null } else { Value::String(ir_fingerprint) },
|
||||
"preview_digest": job.preview_payload.get("preview_digest").and_then(Value::as_str).map(|digest| Value::String(digest.to_owned())).unwrap_or(Value::Null),
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ParsedOpenApiPreview {
|
||||
pub(super) preview: crank_import::rest::ImportPreview,
|
||||
pub(super) ir_fingerprint: String,
|
||||
}
|
||||
|
||||
/// Verified job preview material shared by the legacy Apply path and the
|
||||
/// ImportPlan creation: the replay contract has held, no job mutation
|
||||
/// happened.
|
||||
pub(super) struct ResolvedOpenApiPreview {
|
||||
pub(super) source: ImportJobSourceEnvelope,
|
||||
pub(super) preview: crank_import::rest::ImportPreview,
|
||||
pub(super) fingerprint: Value,
|
||||
}
|
||||
|
||||
/// Outcome of a failed preview revalidation. `Fatal` codes are the same
|
||||
/// stable failure texts the legacy path records on a failed job; the plan
|
||||
/// path must surface the same material as a bounded re-preview conflict
|
||||
/// without touching the job, because other stored plans may anchor to it.
|
||||
pub(super) enum ImportPreviewResolution {
|
||||
Fatal(&'static str, ApiError),
|
||||
NonFatal(ApiError),
|
||||
}
|
||||
|
||||
struct PersistedOpenApiReplay {
|
||||
preview: ParsedOpenApiPreview,
|
||||
normalizer_version: String,
|
||||
projection_version: String,
|
||||
}
|
||||
|
||||
enum ImportReplayContract {
|
||||
LegacyV1,
|
||||
PersistedV2(Box<PersistedOpenApiReplay>),
|
||||
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 preview payloads are replayed as their persisted projection.
|
||||
// They must never be parsed again with current normalization semantics.
|
||||
if !matches!(
|
||||
(normalizer, projection),
|
||||
("normalized-ir-v2", "preview-v2")
|
||||
| ("normalized-ir-v3", "preview-v3")
|
||||
| ("normalized-ir-v4", "preview-v4")
|
||||
| ("normalized-ir-v5", "preview-v5")
|
||||
) {
|
||||
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(Box::new(
|
||||
PersistedOpenApiReplay {
|
||||
preview: ParsedOpenApiPreview {
|
||||
preview,
|
||||
ir_fingerprint: ir_fingerprint.to_owned(),
|
||||
},
|
||||
normalizer_version: normalizer.to_owned(),
|
||||
projection_version: projection.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))
|
||||
}
|
||||
|
||||
pub(super) 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"))?
|
||||
}
|
||||
|
||||
pub(super) 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"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) 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),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) 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"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) 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))
|
||||
.any(|operation| {
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|
||||
|| (!operation.security_requirements.alternatives.is_empty()
|
||||
&& !operation.security_requirements.alternatives.iter().any(
|
||||
|alternative| alternative.supported && alternative.schemes.is_empty(),
|
||||
))
|
||||
})
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
use crank_core::{
|
||||
OnboardingProjection, OnboardingStepId, ProductEventId, ProductEventKind, WorkspaceId,
|
||||
OnboardingProjection, OnboardingStepId, OperationId, ProductEventId, ProductEventKind,
|
||||
WorkspaceId,
|
||||
};
|
||||
use crank_registry::{
|
||||
OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest, RegistryError,
|
||||
OnboardingImportContext, OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest,
|
||||
RegisterOnboardingImportContextRequest, RegistryError, SelectOnboardingImportDraftRequest,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
@@ -11,7 +13,10 @@ use crate::{
|
||||
error::ApiError,
|
||||
service::{
|
||||
AdminService, OnboardingEventPayload, OnboardingEventResponse, OnboardingFirstCallEvidence,
|
||||
OnboardingResponse, OnboardingStepView, ResetOnboardingSelectionResponse, format_timestamp,
|
||||
OnboardingImportChoiceView, OnboardingImportContextView, OnboardingImportDriftView,
|
||||
OnboardingResponse, OnboardingStepView, RegisterOnboardingImportContextPayload,
|
||||
RegisterOnboardingImportContextResponse, ResetOnboardingSelectionResponse,
|
||||
SelectOnboardingImportDraftPayload, SelectOnboardingImportDraftResponse, format_timestamp,
|
||||
new_prefixed_id,
|
||||
},
|
||||
};
|
||||
@@ -22,11 +27,12 @@ impl AdminService {
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
let projection = self
|
||||
let snapshot = self
|
||||
.registry
|
||||
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
|
||||
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
|
||||
.await?;
|
||||
self.map_onboarding_response(projection).await
|
||||
self.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn record_onboarding_event(
|
||||
@@ -67,13 +73,12 @@ impl AdminService {
|
||||
};
|
||||
// Presentation events must never exist outside the server-owned cohort,
|
||||
// including a direct API call before the first UI snapshot GET.
|
||||
let current = self
|
||||
.registry
|
||||
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
|
||||
self.registry
|
||||
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
|
||||
.await?;
|
||||
let outcome = self
|
||||
.registry
|
||||
.record_onboarding_milestone(RecordOnboardingMilestoneRequest {
|
||||
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
|
||||
workspace_id,
|
||||
event_id: &ProductEventId::new(new_prefixed_id("pe")),
|
||||
milestone,
|
||||
@@ -94,9 +99,18 @@ impl AdminService {
|
||||
.as_ref()
|
||||
.is_some_and(|record| record.event.kind == event_kind)
|
||||
{
|
||||
let latest = self
|
||||
.registry
|
||||
.ensure_onboarding_eligibility_snapshot(
|
||||
workspace_id,
|
||||
OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await?;
|
||||
return Ok(OnboardingEventResponse {
|
||||
accepted: false,
|
||||
onboarding: self.map_onboarding_response(current).await?,
|
||||
onboarding: self
|
||||
.map_onboarding_response(latest.projection, latest.import_context)
|
||||
.await?,
|
||||
});
|
||||
}
|
||||
if replay.is_some() {
|
||||
@@ -122,7 +136,12 @@ impl AdminService {
|
||||
};
|
||||
Ok(OnboardingEventResponse {
|
||||
accepted: outcome.accepted,
|
||||
onboarding: self.map_onboarding_response(outcome.projection).await?,
|
||||
onboarding: self
|
||||
.map_onboarding_response(
|
||||
outcome.snapshot.projection,
|
||||
outcome.snapshot.import_context,
|
||||
)
|
||||
.await?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -132,9 +151,13 @@ impl AdminService {
|
||||
expected_revision: i64,
|
||||
) -> Result<ResetOnboardingSelectionResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
let projection = self
|
||||
let snapshot = self
|
||||
.registry
|
||||
.reset_onboarding_selection(workspace_id, expected_revision, OffsetDateTime::now_utc())
|
||||
.reset_onboarding_selection_snapshot(
|
||||
workspace_id,
|
||||
expected_revision,
|
||||
OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
RegistryError::OnboardingStaleRevision => ApiError::conflict_with_context(
|
||||
@@ -145,13 +168,76 @@ impl AdminService {
|
||||
})?;
|
||||
Ok(ResetOnboardingSelectionResponse {
|
||||
selection_reset: true,
|
||||
onboarding: self.map_onboarding_response(projection).await?,
|
||||
onboarding: self
|
||||
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
||||
.await?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn register_onboarding_import_context(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
payload: RegisterOnboardingImportContextPayload,
|
||||
) -> Result<RegisterOnboardingImportContextResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
|
||||
let snapshot = self
|
||||
.registry
|
||||
.register_onboarding_import_context_snapshot(RegisterOnboardingImportContextRequest {
|
||||
workspace_id,
|
||||
application_idempotency_key: &payload.application_idempotency_key,
|
||||
plan_digest: &payload.plan_digest,
|
||||
expected_revision: payload.expected_revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await?;
|
||||
Ok(RegisterOnboardingImportContextResponse {
|
||||
registered: true,
|
||||
onboarding: self
|
||||
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
||||
.await?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn select_onboarding_import_draft(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
payload: SelectOnboardingImportDraftPayload,
|
||||
) -> Result<SelectOnboardingImportDraftResponse, ApiError> {
|
||||
self.ensure_workspace_exists(workspace_id).await?;
|
||||
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
|
||||
if payload.operation_id.is_empty() || payload.operation_id.len() > 128 {
|
||||
return Err(ApiError::validation(
|
||||
"operation_id must contain 1..128 bytes",
|
||||
));
|
||||
}
|
||||
if payload.operation_version == 0 {
|
||||
return Err(ApiError::validation("operation_version must be positive"));
|
||||
}
|
||||
let snapshot = self
|
||||
.registry
|
||||
.select_onboarding_import_draft_snapshot(SelectOnboardingImportDraftRequest {
|
||||
workspace_id,
|
||||
application_idempotency_key: &payload.application_idempotency_key,
|
||||
plan_digest: &payload.plan_digest,
|
||||
operation_id: &OperationId::new(payload.operation_id),
|
||||
operation_version: payload.operation_version,
|
||||
expected_revision: payload.expected_revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await?;
|
||||
Ok(SelectOnboardingImportDraftResponse {
|
||||
selected: true,
|
||||
onboarding: self
|
||||
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
||||
.await?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn map_onboarding_response(
|
||||
&self,
|
||||
projection: OnboardingProjection,
|
||||
import_context: Option<OnboardingImportContext>,
|
||||
) -> Result<OnboardingResponse, ApiError> {
|
||||
let endpoint = if let Some(agent_id) = projection.agent_id.as_ref() {
|
||||
let workspace = self.get_workspace(&projection.workspace_id).await?;
|
||||
@@ -195,6 +281,7 @@ impl AdminService {
|
||||
_ => None,
|
||||
};
|
||||
let first_incomplete = projection.steps.iter().position(|step| !step.completed);
|
||||
let import_context = import_context.map(map_import_context);
|
||||
Ok(OnboardingResponse {
|
||||
schema_version: 1,
|
||||
workspace_id: projection.workspace_id.as_str().to_owned(),
|
||||
@@ -244,10 +331,61 @@ impl AdminService {
|
||||
.map(|id| id.as_str().to_owned()),
|
||||
mcp_endpoint: endpoint,
|
||||
first_call,
|
||||
import_context,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn map_import_context(context: OnboardingImportContext) -> OnboardingImportContextView {
|
||||
OnboardingImportContextView {
|
||||
application_idempotency_key: context.application_idempotency_key,
|
||||
plan_digest: context.plan_digest,
|
||||
report: context.report,
|
||||
choices: context
|
||||
.choices
|
||||
.into_iter()
|
||||
.map(|choice| OnboardingImportChoiceView {
|
||||
key: choice.key,
|
||||
name: choice.name,
|
||||
outcome: choice.outcome,
|
||||
operation_id: choice.operation_id,
|
||||
version: choice.version,
|
||||
reason: choice.reason,
|
||||
selectable: choice.selectable,
|
||||
})
|
||||
.collect(),
|
||||
selected_operation_id: context
|
||||
.selected_operation_id
|
||||
.map(|id| id.as_str().to_owned()),
|
||||
selected_operation_version: context.selected_operation_version,
|
||||
drift: context.drift.map(|drift| OnboardingImportDriftView {
|
||||
reason: drift.reason,
|
||||
current_operation_version: drift.current_operation_version,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_application_identity(
|
||||
application_idempotency_key: &str,
|
||||
plan_digest: &str,
|
||||
) -> Result<(), ApiError> {
|
||||
if application_idempotency_key.is_empty() || application_idempotency_key.len() > 128 {
|
||||
return Err(ApiError::validation(
|
||||
"application_idempotency_key must contain 1..128 bytes",
|
||||
));
|
||||
}
|
||||
let valid_digest = plan_digest.len() == 64
|
||||
&& plan_digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
|
||||
if !valid_digest {
|
||||
return Err(ApiError::validation(
|
||||
"plan_digest must be 64 lowercase hex characters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn action_code(step: OnboardingStepId) -> &'static str {
|
||||
match step {
|
||||
OnboardingStepId::Operation => "create_operation",
|
||||
|
||||
@@ -111,7 +111,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(13),
|
||||
Some(15),
|
||||
"migration binary must install the current canonical ledger",
|
||||
);
|
||||
sqlx::query(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
env, fmt,
|
||||
str::FromStr,
|
||||
sync::Arc,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
@@ -15,7 +16,9 @@ use crank_core::{
|
||||
};
|
||||
use crank_core::{IdentityError, IdentityProvider, IdentityProviderKind, LoginOutcome};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::{MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresRegistry};
|
||||
use crank_registry::{
|
||||
MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresPoolConfig, PostgresRegistry,
|
||||
};
|
||||
use crank_runtime::SecretCrypto;
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
use serde_json::{Value, json};
|
||||
@@ -358,11 +361,33 @@ pub(super) async fn create_lead(Json(payload): Json<Value>) -> Json<Value> {
|
||||
|
||||
pub(super) async fn test_registry() -> PostgresRegistry {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_admin_api").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
test_registry_at_url(&database_url, None).await
|
||||
}
|
||||
|
||||
pub(super) async fn test_registry_with_single_connection() -> (PostgresRegistry, String) {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_admin_api_replay").await;
|
||||
let pool_config = PostgresPoolConfig::try_new(1, 0, 5_000, 60_000, 1_800_000).unwrap();
|
||||
let registry = test_registry_at_url(&database_url, Some(pool_config)).await;
|
||||
(registry, database_url)
|
||||
}
|
||||
|
||||
async fn test_registry_at_url(
|
||||
database_url: &str,
|
||||
pool_config: Option<PostgresPoolConfig>,
|
||||
) -> PostgresRegistry {
|
||||
let pool = sqlx::PgPool::connect(database_url).await.unwrap();
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
|
||||
let registry = match pool_config {
|
||||
Some(config) => {
|
||||
let options = sqlx::postgres::PgConnectOptions::from_str(database_url).unwrap();
|
||||
PostgresRegistry::connect_with_options_and_pool_config(options, config)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
None => PostgresRegistry::connect(database_url).await.unwrap(),
|
||||
};
|
||||
let secret_crypto = test_secret_crypto();
|
||||
registry
|
||||
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
|
||||
|
||||
@@ -5,6 +5,8 @@ use super::common::*;
|
||||
use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
|
||||
mod replay;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn exposes_server_authoritative_onboarding_projection() {
|
||||
@@ -264,6 +266,573 @@ async fn direct_presentation_mutation_cannot_precede_server_eligibility() {
|
||||
assert_eq!(snapshot["status"], "in_progress");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn import_context_registration_and_selection_are_revision_guarded() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("onboarding_select_draft");
|
||||
let pool = registry.pool();
|
||||
insert_admin_import_fixture(pool).await;
|
||||
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let initial = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let revision = initial["revision"].as_i64().unwrap();
|
||||
assert!(initial["import_context"].is_null());
|
||||
|
||||
// Forged identity: no committed immutable apply report.
|
||||
let forged = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_missing",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let forged_status = forged.status();
|
||||
let forged = forged.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
forged_status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"body={forged}"
|
||||
);
|
||||
assert_eq!(
|
||||
forged["error"]["code"],
|
||||
"onboarding_import_application_unavailable"
|
||||
);
|
||||
|
||||
// Stale revision cannot register a context.
|
||||
let stale = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": revision + 1,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let stale_status = stale.status();
|
||||
let stale = stale.json::<Value>().await.unwrap();
|
||||
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
|
||||
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
|
||||
|
||||
// A valid registration stores a pending, recoverable import context and
|
||||
// suppresses generic automatic Operation selection.
|
||||
let registered = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let registered_status = registered.status();
|
||||
let registered = registered.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
registered_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"body={registered}"
|
||||
);
|
||||
assert_eq!(registered["registered"], true);
|
||||
assert_eq!(registered["operation_id"], Value::Null);
|
||||
assert_eq!(
|
||||
registered["import_context"]["selected_operation_id"],
|
||||
Value::Null
|
||||
);
|
||||
assert_eq!(registered["import_context"]["plan_digest"], "b".repeat(64));
|
||||
assert_eq!(
|
||||
registered["import_context"]["report"]["schema_version"],
|
||||
"import-plan-apply-report-v1"
|
||||
);
|
||||
assert_eq!(
|
||||
registered["import_context"]["choices"][0]["selectable"],
|
||||
true
|
||||
);
|
||||
let registered_revision = registered["revision"].as_i64().unwrap();
|
||||
|
||||
// Selecting under a different application identity is rejected.
|
||||
let mismatched = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_other",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let mismatched_status = mismatched.status();
|
||||
let mismatched = mismatched.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
mismatched_status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"body={mismatched}"
|
||||
);
|
||||
assert_eq!(
|
||||
mismatched["error"]["code"],
|
||||
"onboarding_import_context_unavailable"
|
||||
);
|
||||
|
||||
// A forged operation is not a successful outcome of the report.
|
||||
let forged = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_forged",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let forged_status = forged.status();
|
||||
let forged = forged.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
forged_status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"body={forged}"
|
||||
);
|
||||
assert_eq!(
|
||||
forged["error"]["code"],
|
||||
"onboarding_import_draft_unavailable"
|
||||
);
|
||||
|
||||
// Unknown/raw client fields are rejected outright.
|
||||
let unknown = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
"raw_credential": "crk_forbidden_canary",
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let unknown_status = unknown.status();
|
||||
let unknown = unknown.text().await.unwrap();
|
||||
assert_eq!(
|
||||
unknown_status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"body={unknown}"
|
||||
);
|
||||
|
||||
// A verified choice anchors the exact imported Draft.
|
||||
let selected = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let selected_status = selected.status();
|
||||
let selected = selected.json::<Value>().await.unwrap();
|
||||
assert_eq!(selected_status, reqwest::StatusCode::OK, "body={selected}");
|
||||
assert_eq!(selected["selected"], true);
|
||||
assert_eq!(selected["operation_id"], "op_admin_import");
|
||||
assert_eq!(selected["status"], "in_progress");
|
||||
assert_eq!(selected["import_context"]["selected_operation_version"], 1);
|
||||
|
||||
// Recovery after a fresh GET preserves the explicit selection.
|
||||
let recovered = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recovered["import_context"]["selected_operation_id"],
|
||||
"op_admin_import"
|
||||
);
|
||||
assert_eq!(recovered["import_context"]["selected_operation_version"], 1);
|
||||
assert!(recovered["import_context"]["drift"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn onboarding_revision_round_trips_through_js_safe_integer() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("onboarding_revision_round_trip");
|
||||
let pool = registry.pool();
|
||||
insert_admin_import_fixture(pool).await;
|
||||
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
// Real GET JSON -> browser JS Number -> POST expected_revision CAS. The
|
||||
// deterministic SQL mask keeps the revision a safe integer so the value
|
||||
// survives the f64 round trip that a browser performs.
|
||||
let value = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let revision = value["revision"].as_i64().unwrap();
|
||||
assert!(revision >= 0);
|
||||
assert!(
|
||||
revision <= 9_007_199_254_740_991,
|
||||
"revision must stay within Number.MAX_SAFE_INTEGER"
|
||||
);
|
||||
let js_round_trip = (revision as f64) as i64;
|
||||
assert_eq!(
|
||||
js_round_trip, revision,
|
||||
"revision must round trip through a browser JS Number"
|
||||
);
|
||||
|
||||
let registered = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": js_round_trip,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let registered_status = registered.status();
|
||||
let registered = registered.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
registered_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"body={registered}"
|
||||
);
|
||||
let registered_revision = registered["revision"].as_i64().unwrap();
|
||||
assert!((registered_revision as f64) as i64 == registered_revision);
|
||||
|
||||
// A stale JS-safe revision is rejected without mutation.
|
||||
let stale = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision - 1,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let stale_status = stale.status();
|
||||
let stale = stale.json::<Value>().await.unwrap();
|
||||
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
|
||||
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
|
||||
|
||||
let selected = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": (registered_revision as f64) as i64,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let selected_status = selected.status();
|
||||
let selected = selected.json::<Value>().await.unwrap();
|
||||
assert_eq!(selected_status, reqwest::StatusCode::OK, "body={selected}");
|
||||
assert_eq!(selected["selected"], true);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn import_context_snapshot_stays_consistent_when_candidate_changes() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("onboarding_import_snapshot");
|
||||
let pool = registry.pool().clone();
|
||||
insert_admin_import_fixture(&pool).await;
|
||||
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let initial = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let revision = initial["revision"].as_i64().unwrap();
|
||||
|
||||
let registered = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let registered_status = registered.status();
|
||||
let registered = registered.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
registered_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"body={registered}"
|
||||
);
|
||||
let registered_revision = registered["revision"].as_i64().unwrap();
|
||||
// Projection revision and import_context come from one authoritative
|
||||
// snapshot: the choice is actionable and nothing is selected yet.
|
||||
assert_eq!(
|
||||
registered["import_context"]["selected_operation_id"],
|
||||
Value::Null
|
||||
);
|
||||
assert_eq!(
|
||||
registered["import_context"]["choices"][0]["outcome"],
|
||||
"created"
|
||||
);
|
||||
assert_eq!(
|
||||
registered["import_context"]["choices"][0]["selectable"],
|
||||
true
|
||||
);
|
||||
|
||||
// The pending candidate becomes non-actionable between requests.
|
||||
sqlx::query("update operations set status = 'archived' where id = 'op_admin_import'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let snapshot = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot_revision = snapshot["revision"].as_i64().unwrap();
|
||||
assert_ne!(snapshot_revision, registered_revision);
|
||||
// The same response carries the updated revision and matching choices.
|
||||
assert_eq!(
|
||||
snapshot["import_context"]["choices"][0]["selectable"],
|
||||
false
|
||||
);
|
||||
|
||||
let stale = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let stale_status = stale.status();
|
||||
let stale = stale.json::<Value>().await.unwrap();
|
||||
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
|
||||
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
|
||||
|
||||
let unavailable = client
|
||||
.post(format!("{base_url}/onboarding/select-draft"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": snapshot_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let unavailable_status = unavailable.status();
|
||||
let unavailable = unavailable.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
unavailable_status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"body={unavailable}"
|
||||
);
|
||||
assert_eq!(
|
||||
unavailable["error"]["code"],
|
||||
"onboarding_import_draft_unavailable"
|
||||
);
|
||||
|
||||
let selected: Option<String> = sqlx::query_scalar(
|
||||
"select selected_operation_id from onboarding_import_selections
|
||||
where workspace_id = 'ws_default'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
selected.is_none(),
|
||||
"rejected selections must not mutate state"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[serial]
|
||||
async fn concurrent_archive_vs_select_draft_rejects_without_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("onboarding_concurrent_select");
|
||||
let pool = registry.pool().clone();
|
||||
insert_admin_import_fixture(&pool).await;
|
||||
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let initial = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let revision = initial["revision"].as_i64().unwrap();
|
||||
let registered = client
|
||||
.post(format!("{base_url}/onboarding/import-context"))
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"expected_revision": revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<Value>()
|
||||
.await
|
||||
.unwrap();
|
||||
let registered_revision = registered["revision"].as_i64().unwrap();
|
||||
|
||||
// Hold the exact candidate row lock while the HTTP selection contends.
|
||||
let mut blocker = pool.begin().await.unwrap();
|
||||
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
|
||||
.bind("ws_default")
|
||||
.bind("op_admin_import")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let select_client = client.clone();
|
||||
let select_url = format!("{base_url}/onboarding/select-draft");
|
||||
let select_task = tokio::spawn(async move {
|
||||
select_client
|
||||
.post(select_url)
|
||||
.json(&json!({
|
||||
"application_idempotency_key": "idem_admin_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"operation_id": "op_admin_import",
|
||||
"operation_version": 1,
|
||||
"expected_revision": registered_revision,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
sqlx::query(
|
||||
"update operations set status = 'archived', updated_at = now()
|
||||
where workspace_id = 'ws_default' and id = 'op_admin_import'",
|
||||
)
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
blocker.commit().await.unwrap();
|
||||
|
||||
let response = select_task.await.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.json::<Value>().await.unwrap();
|
||||
assert!(
|
||||
status == reqwest::StatusCode::CONFLICT
|
||||
|| status == reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"concurrent archive must reject the selection: status={status} body={body}"
|
||||
);
|
||||
let selected: Option<String> = sqlx::query_scalar(
|
||||
"select selected_operation_id from onboarding_import_selections
|
||||
where workspace_id = 'ws_default'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
selected.is_none(),
|
||||
"rejected selection must not mutate state"
|
||||
);
|
||||
}
|
||||
|
||||
async fn insert_admin_import_fixture(pool: &sqlx::PgPool) {
|
||||
sqlx::query(
|
||||
"insert into operations (
|
||||
id, workspace_id, name, display_name, category, protocol, security_level, status,
|
||||
current_draft_version, latest_published_version, created_at, updated_at
|
||||
) values ('op_admin_import', 'ws_default', 'admin_import', 'Admin Import', 'general',
|
||||
'rest', 'standard', 'draft', 1, null, now(), now())",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into operation_versions (
|
||||
operation_id, version, status, target_json, input_schema_json, output_schema_json,
|
||||
input_mapping_json, output_mapping_json, execution_config_json,
|
||||
tool_description_json, name, display_name, category, protocol, security_level,
|
||||
snapshot_provenance, snapshot_observed_at, created_at
|
||||
) values ('op_admin_import', 1, 'draft', '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
|
||||
'{}'::jsonb, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
|
||||
'admin_import', 'Admin Import', 'general', 'rest', 'standard',
|
||||
'native_v4', now(), now())",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into import_plan_applications (
|
||||
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
|
||||
) values ('ws_default', 'idem_admin_import', 'plan_admin', $1, $2, now())",
|
||||
)
|
||||
.bind("b".repeat(64))
|
||||
.bind(json!({
|
||||
"schema_version": "import-plan-apply-report-v1",
|
||||
"status": "applied",
|
||||
"source_digest": "c".repeat(64),
|
||||
"outcomes": [{
|
||||
"key": "candidate_admin",
|
||||
"name": "adminImport",
|
||||
"outcome": "created",
|
||||
"operation_id": "op_admin_import",
|
||||
"version": 1,
|
||||
}],
|
||||
}))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn reset_selection_is_explicit_and_revision_guarded() {
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
use super::*;
|
||||
use std::{future::Future, pin::Pin, task::Poll};
|
||||
|
||||
use crank_core::{OperationId, ProductEventId, WorkspaceId};
|
||||
use crank_registry::{
|
||||
OnboardingPresentationMilestone, PostgresRegistry, RecordOnboardingMilestoneRequest,
|
||||
RegisterOnboardingImportContextRequest, SelectOnboardingImportDraftRequest,
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
async fn poll_once_is_pending<F: Future>(mut future: Pin<&mut F>) -> bool {
|
||||
std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx).is_pending())).await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn stale_same_kind_replay_returns_projection_after_concurrent_change() {
|
||||
let (registry, database_url) = test_registry_with_single_connection().await;
|
||||
let pool = registry.pool().clone();
|
||||
let external_registry = PostgresRegistry::connect(&database_url).await.unwrap();
|
||||
let raw = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
insert_admin_import_fixture(&raw).await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("onboarding_stale_replay"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let initial = registry
|
||||
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
|
||||
.await
|
||||
.unwrap();
|
||||
let registered = registry
|
||||
.register_onboarding_import_context_snapshot(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_admin_import",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.projection.revision,
|
||||
occurred_at: now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let selected = registry
|
||||
.select_onboarding_import_draft_snapshot(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_admin_import",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &OperationId::new("op_admin_import"),
|
||||
operation_version: 1,
|
||||
expected_revision: registered.projection.revision,
|
||||
occurred_at: now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let legacy_key = "legacy-started-replay";
|
||||
registry
|
||||
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
|
||||
workspace_id: &workspace_id,
|
||||
event_id: &ProductEventId::new("pe_legacy_started_replay"),
|
||||
milestone: OnboardingPresentationMilestone::Started,
|
||||
idempotency_key: legacy_key,
|
||||
expected_revision: selected.projection.revision,
|
||||
occurred_at: now,
|
||||
eligible_since: initial.projection.eligible_since,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let before = registry
|
||||
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(before.import_context.as_ref().unwrap().choices[0].selectable);
|
||||
|
||||
let mut service_call = Box::pin(service.record_onboarding_event(
|
||||
&workspace_id,
|
||||
admin_api::dto::OnboardingEventPayload {
|
||||
event: "started".to_owned(),
|
||||
idempotency_key: legacy_key.to_owned(),
|
||||
expected_revision: before.projection.revision,
|
||||
completed_steps: None,
|
||||
},
|
||||
));
|
||||
|
||||
// Queue the service's workspace lookup ahead of the first connection
|
||||
// barrier, then prove that the first onboarding snapshot is queued ahead
|
||||
// of the second barrier. sqlx's pool acquisition queue is FIFO.
|
||||
let held = pool.acquire().await.unwrap();
|
||||
assert!(poll_once_is_pending(service_call.as_mut()).await);
|
||||
let mut first_barrier = Box::pin(pool.acquire());
|
||||
assert!(poll_once_is_pending(first_barrier.as_mut()).await);
|
||||
drop(held);
|
||||
let first_connection = tokio::select! {
|
||||
connection = first_barrier.as_mut() => connection.unwrap(),
|
||||
_ = service_call.as_mut() => panic!("service call completed before first snapshot barrier"),
|
||||
};
|
||||
assert!(poll_once_is_pending(service_call.as_mut()).await);
|
||||
|
||||
let mut second_barrier = Box::pin(pool.acquire());
|
||||
assert!(poll_once_is_pending(second_barrier.as_mut()).await);
|
||||
drop(first_connection);
|
||||
let second_connection = tokio::select! {
|
||||
connection = second_barrier.as_mut() => connection.unwrap(),
|
||||
_ = service_call.as_mut() => panic!("service call completed before second snapshot barrier"),
|
||||
};
|
||||
assert!(poll_once_is_pending(service_call.as_mut()).await);
|
||||
|
||||
// The first snapshot has completed and the event write is now queued
|
||||
// behind the second barrier. Change the projection and import context from
|
||||
// an independent registry connection before allowing that write to observe state.
|
||||
sqlx::query(
|
||||
"update operations set status = 'archived', updated_at = now()
|
||||
where workspace_id = 'ws_default' and id = 'op_admin_import'",
|
||||
)
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let pre_mutation = external_registry
|
||||
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
|
||||
.await
|
||||
.unwrap();
|
||||
external_registry
|
||||
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
|
||||
workspace_id: &workspace_id,
|
||||
event_id: &ProductEventId::new("pe_replay_race_mutation"),
|
||||
milestone: OnboardingPresentationMilestone::Dismissed,
|
||||
idempotency_key: "mutation-between-snapshots",
|
||||
expected_revision: pre_mutation.projection.revision,
|
||||
occurred_at: now,
|
||||
eligible_since: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let fresh = external_registry
|
||||
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(fresh.projection.revision, pre_mutation.projection.revision);
|
||||
assert!(!fresh.import_context.as_ref().unwrap().choices[0].selectable);
|
||||
assert!(fresh.import_context.as_ref().unwrap().drift.is_some());
|
||||
drop(second_connection);
|
||||
|
||||
let response = service_call.await.unwrap();
|
||||
assert!(!response.accepted);
|
||||
assert_eq!(
|
||||
response.onboarding.revision, fresh.projection.revision,
|
||||
"same-kind idempotency replay must return the latest projection after the concurrent mutation"
|
||||
);
|
||||
assert!(!response.onboarding.import_context.as_ref().unwrap().choices[0].selectable);
|
||||
assert!(
|
||||
response
|
||||
.onboarding
|
||||
.import_context
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.drift
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,9 @@
|
||||
use admin_api::service::{
|
||||
AdminServiceBuilder, AuthProfilePayload, OpenApiAuthMapping, OpenApiImportCreatePayload,
|
||||
OpenApiImportCreateResponse, OpenApiUpload, OpenApiUploadLocale, SecretPayload,
|
||||
AdminServiceBuilder, OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale,
|
||||
};
|
||||
use crank_core::{
|
||||
AuthConfig, AuthKind, BearerAuthConfig, SecretId, SecretKind, Workspace, WorkspaceId,
|
||||
WorkspaceStatus,
|
||||
};
|
||||
use crank_registry::{CreateWorkspaceRequest, ImportJobStatus};
|
||||
use serde_json::json;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::ImportJobStatus;
|
||||
use serial_test::serial;
|
||||
use sha2::Digest;
|
||||
|
||||
use super::common::{
|
||||
test_auth_settings, test_registry, test_secret_crypto, test_service, test_storage_root,
|
||||
@@ -17,7 +11,120 @@ use super::common::{
|
||||
|
||||
mod external_references;
|
||||
mod http_contract;
|
||||
mod security;
|
||||
mod import_plan_apply;
|
||||
mod import_plan_create;
|
||||
mod large_preview;
|
||||
mod upload_outcomes;
|
||||
mod v5_replay;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn upload_rejects_credential_literals_before_persisting_source_artifacts() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_storage_redaction");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root,
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Redaction persistence","version":"1"},
|
||||
"servers":[{"url":"https://bare-canary@api.example.test/v1?api_key=query-canary"}],
|
||||
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
|
||||
"paths":{"/private":{"get":{
|
||||
"operationId":"privateOperation",
|
||||
"parameters":[{"name":"X-Api-Key","in":"header","example":"opaque-canary-42"}],
|
||||
"responses":{"200":{"description":"ok"}},
|
||||
"x-client-secret":true
|
||||
}}}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.expect_err("credential-bearing uploads must be rejected before persistence");
|
||||
let rendered_error = format!("{error:?}");
|
||||
assert!(
|
||||
rendered_error.contains("invalid_document"),
|
||||
"unexpected typed error: {rendered_error}"
|
||||
);
|
||||
for canary in ["bare-canary", "query-canary", "opaque-canary-42"] {
|
||||
assert!(
|
||||
!rendered_error.contains(canary),
|
||||
"API error leaked {canary}"
|
||||
);
|
||||
}
|
||||
let source_count: i64 =
|
||||
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(source_count, 0, "unsafe upload created an artifact source");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn legacy_apply_rejects_required_auth_without_binding_before_creating_draft() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_unresolved_auth"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Required auth","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer"}}},
|
||||
"security":[{"bearer":[]}],
|
||||
"paths":{"/secure":{"get":{"operationId":"secureOperation","responses":{"200":{"description":"ok"}}}}}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
server_url: None,
|
||||
conflict_mode: "rename".to_owned(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let error = result.expect_err("legacy apply cannot bypass unresolved required auth");
|
||||
assert!(format!("{error:?}").contains("invalid_document"));
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(job.status, ImportJobStatus::Failed);
|
||||
}
|
||||
|
||||
const OPENAPI3: &str = r#"
|
||||
openapi: 3.0.3
|
||||
@@ -85,11 +192,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-v5"
|
||||
crank_import::rest::NORMALIZER_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
preview_job.preview_payload["normalization"]["projection_version"],
|
||||
"preview-v5"
|
||||
crank_import::rest::PROJECTION_VERSION
|
||||
);
|
||||
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
|
||||
|
||||
@@ -99,7 +206,6 @@ 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(),
|
||||
},
|
||||
@@ -118,7 +224,6 @@ 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(),
|
||||
},
|
||||
@@ -171,7 +276,6 @@ 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(),
|
||||
},
|
||||
@@ -194,7 +298,6 @@ 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(),
|
||||
},
|
||||
@@ -224,7 +327,6 @@ 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(),
|
||||
};
|
||||
@@ -266,7 +368,6 @@ 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(),
|
||||
};
|
||||
@@ -321,7 +422,6 @@ 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(),
|
||||
},
|
||||
@@ -363,7 +463,6 @@ 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(),
|
||||
},
|
||||
@@ -440,7 +539,6 @@ 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(),
|
||||
}
|
||||
@@ -509,7 +607,6 @@ 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(),
|
||||
},
|
||||
@@ -564,7 +661,6 @@ 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(),
|
||||
},
|
||||
@@ -652,7 +748,6 @@ 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(),
|
||||
},
|
||||
@@ -671,7 +766,6 @@ 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(),
|
||||
},
|
||||
@@ -753,7 +847,6 @@ 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(),
|
||||
},
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
use super::super::common::test_service_with_external_references;
|
||||
use super::*;
|
||||
use axum::{Router, routing::get};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
|
||||
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет
Line truncated
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_relative_chain_survives_reversed_builder_order_and_apply_never_refetches() {
|
||||
@@ -35,7 +39,7 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
@@ -99,13 +103,13 @@ 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(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
server.abort();
|
||||
assert_eq!(applied.created.len(), 1);
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 2);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
@@ -120,53 +124,80 @@ paths:
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_literal_credential_is_rejected_before_snapshot_persistence() {
|
||||
let canary = "external-atdd-secret-canary-2-10";
|
||||
async fn external_secret_document_is_rejected_before_blob_registration() {
|
||||
let external_document = "Item: { type: object, x-api-key: external-secret-canary-42, properties: { id: { type: string } } }";
|
||||
let fetched = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetched);
|
||||
let app = Router::new().route(
|
||||
"/schemas.yaml",
|
||||
get(move || async move {
|
||||
format!(
|
||||
"Item: {{ type: object, properties: {{ token: {{ type: string, example: '{canary}' }} }} }}"
|
||||
)
|
||||
get(move || {
|
||||
let fetch_count = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
external_document
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_secret_rejected");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_literal_credential"),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
let error = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: External secret canary }}
|
||||
info: {{ title: Safe primary with unsafe external }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: {{ $ref: '{origin}/schemas.yaml#/Item' }}
|
||||
content: {{ application/json: {{ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }} }} }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.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));
|
||||
.expect_err("unsafe external bundle must be rejected before source persistence");
|
||||
server.abort();
|
||||
assert_eq!(fetched.load(Ordering::SeqCst), 1);
|
||||
let rendered_error = format!("{error:?}");
|
||||
assert!(rendered_error.contains("invalid_document"));
|
||||
assert!(!rendered_error.contains("external-secret-canary-42"));
|
||||
|
||||
// The raw dependency's content-addressed path must not exist even as an
|
||||
// unregistered blob, and no other stored file may contain its literal.
|
||||
let external_digest = format!("{:x}", Sha256::digest(external_document.as_bytes()));
|
||||
let external_blob = storage_root
|
||||
.join("sha256")
|
||||
.join(&external_digest[..2])
|
||||
.join(&external_digest);
|
||||
assert!(
|
||||
!external_blob.exists(),
|
||||
"secret-bearing external response was written to the artifact store"
|
||||
);
|
||||
assert!(!storage_contains_literal(
|
||||
&storage_root,
|
||||
b"external-secret-canary-42"
|
||||
));
|
||||
|
||||
let dependency_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources
|
||||
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
|
||||
@@ -175,14 +206,29 @@ paths:
|
||||
.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);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
fn storage_contains_literal(root: &std::path::Path, literal: &[u8]) -> bool {
|
||||
std::fs::read_dir(root).unwrap().any(|entry| {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
storage_contains_literal(&path, literal)
|
||||
} else {
|
||||
std::fs::read(path)
|
||||
.unwrap()
|
||||
.windows(literal.len())
|
||||
.any(|window| window == literal)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -256,7 +302,6 @@ 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(),
|
||||
},
|
||||
@@ -339,7 +384,6 @@ 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(),
|
||||
},
|
||||
@@ -386,7 +430,7 @@ async fn external_materialization_uses_one_wall_clock_timeout_and_cleans_cancell
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let timeout_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
@@ -438,6 +482,7 @@ paths:
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
timeout_server.abort();
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(800));
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 2);
|
||||
let job = registry
|
||||
@@ -473,7 +518,10 @@ paths:
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(detached_dependencies, 1);
|
||||
assert_eq!(
|
||||
detached_dependencies, 0,
|
||||
"staged dependencies must not be persisted before the fetch chain completes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -592,7 +640,6 @@ 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(),
|
||||
},
|
||||
@@ -663,7 +710,6 @@ 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(),
|
||||
},
|
||||
@@ -681,54 +727,58 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependency_reads() {
|
||||
use sha2::Digest;
|
||||
|
||||
async fn exact_v4_security_contract_replays_its_persisted_security_classification() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v4_compatibility"),
|
||||
test_storage_root("openapi_import_v4_security_compatibility"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Historical security","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"components":{"securitySchemes":{"basic":{"type":"http","scheme":"basic"}}},
|
||||
"security":[{"basic":[]}],
|
||||
"paths":{
|
||||
"/secure":{"get":{"operationId":"secure","responses":{"200":{"description":"ok"}}}},
|
||||
"/public":{"get":{"operationId":"public","security":[],"responses":{"200":{"description":"ok"}}}}
|
||||
}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, openapi_upload())
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let mut job = registry
|
||||
let 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())
|
||||
// Keep the genuine baseline-v4 normalization/projection, preview and digest intact.
|
||||
// Only bind its source envelope to this test's newly registered immutable source blob.
|
||||
let mut payload: serde_json::Value =
|
||||
serde_json::from_str(BASELINE_V4_SECURITY_PREVIEW_PAYLOAD).unwrap();
|
||||
assert_eq!(
|
||||
payload.pointer("/source/digest"),
|
||||
job.preview_payload.pointer("/source/digest"),
|
||||
"baseline fixture must refer to the exact uploaded source bytes",
|
||||
);
|
||||
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())
|
||||
payload["source"]["source_id"] = job.preview_payload["source"]["source_id"].clone();
|
||||
assert_eq!(
|
||||
payload["normalization"]["normalizer_version"],
|
||||
"normalized-ir-v4"
|
||||
);
|
||||
assert_eq!(payload["normalization"]["projection_version"], "preview-v4");
|
||||
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
|
||||
.bind(serde_json::to_string(&payload).unwrap())
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
@@ -739,19 +789,25 @@ async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependen
|
||||
&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()),
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
server_url: Some("https://api.example.test".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);
|
||||
.await;
|
||||
let error =
|
||||
result.expect_err("historical v4 security blocker must refuse the selected candidate");
|
||||
assert!(
|
||||
format!("{error:?}").contains("invalid_document"),
|
||||
"v4 contract was rejected before candidate validation: {error:?}"
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
mod security_bundle;
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
use super::*;
|
||||
|
||||
// --- Referenced security credentials RED regressions ---
|
||||
// These tests prove that credential literals hidden behind local/external $ref
|
||||
// security scheme + parameter splits are rejected before artifact persistence.
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn referenced_security_credentials_local_scheme_ref_with_parameter_default_canary_rejected() {
|
||||
let canary = b"local-ref-canary-001-Zx9qK";
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_local_scheme_ref_canary");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: r##"{
|
||||
"openapi":"3.1.0",
|
||||
"info":{"title":"Local ref scheme","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"},
|
||||
"x-key":{"type":"string","default":"local-ref-canary-001-Zx9qK"},
|
||||
"components":{
|
||||
"securitySchemes":{"custom":{"$ref":"#/x-scheme"}}
|
||||
},
|
||||
"security":[{"custom":[]}],
|
||||
"paths":{
|
||||
"/test":{"get":{
|
||||
"operationId":"test", "security":[{"custom":[]}],
|
||||
"parameters":[{"name":"X-Custom","in":"header","schema":{"$ref":"#/x-key"}}],
|
||||
"responses":{"200":{"description":"ok"}}
|
||||
}}
|
||||
}
|
||||
}"##
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let result = service.preview_openapi_import(&workspace_id, upload).await;
|
||||
|
||||
// Canary must NOT appear in the API response (error or preview).
|
||||
let response_repr = match &result {
|
||||
Ok(preview) => serde_json::to_string(preview).unwrap(),
|
||||
Err(err) => format!("{err:?}"),
|
||||
};
|
||||
assert!(
|
||||
response_repr.contains("invalid_document"),
|
||||
"unsafe local ref bundle was not rejected: {response_repr}"
|
||||
);
|
||||
assert!(
|
||||
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
|
||||
"credential canary leaked into API response"
|
||||
);
|
||||
|
||||
// Canary must NOT be persisted to artifact storage.
|
||||
assert!(
|
||||
!storage_contains_literal(&storage_root, canary),
|
||||
"raw credential literal from referenced local scheme ref persisted to storage"
|
||||
);
|
||||
assert_rejected_bundle_unpersisted(®istry, &workspace_id, &storage_root).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn encoded_access_token_fragment_is_rejected_before_persistence() {
|
||||
let canary = b"fragment-ingress-canary-004-Qm7vN";
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_encoded_fragment_canary");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br##"{
|
||||
"openapi":"3.1.0",
|
||||
"info":{"title":"Encoded fragment credential","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test/v1#%61%63%63%65%73%73%5F%74%6F%6B%65%6E=fragment-ingress-canary-004-Qm7vN"}],
|
||||
"paths":{"/health":{"get":{"responses":{"200":{"description":"ok"}}}}}
|
||||
}"##
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.expect_err("encoded access_token fragment must be rejected at ingress");
|
||||
let rendered_error = format!("{error:?}");
|
||||
assert!(rendered_error.contains("invalid_document"));
|
||||
assert!(rendered_error.len() <= 512, "error must remain bounded");
|
||||
assert!(!rendered_error.contains("fragment-ingress-canary-004-Qm7vN"));
|
||||
assert!(!rendered_error.contains("%61%63%63%65%73%73%5F%74%6F%6B%65%6E"));
|
||||
assert_rejected_bundle_unpersisted(®istry, &workspace_id, &storage_root).await;
|
||||
assert!(!storage_contains_literal(&storage_root, canary));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn referenced_security_credentials_external_scheme_ref_local_parameter_default_canary_rejected()
|
||||
{
|
||||
let canary = b"split-ext-canary-002-Yw8pJ";
|
||||
// External document defines the apiKey security scheme with header X-Custom.
|
||||
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
|
||||
let fetched = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetched);
|
||||
let app = Router::new().route(
|
||||
"/scheme.yaml",
|
||||
get(move || {
|
||||
let fc = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
fc.fetch_add(1, Ordering::SeqCst);
|
||||
external_doc.to_owned()
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_ext_scheme_ref_canary");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
// Primary references the external scheme; contains a local parameter
|
||||
// with name X-Custom and schema.default = canary.
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"{{
|
||||
"openapi":"3.1.0",
|
||||
"info":{{"title":"Ext scheme ref","version":"1"}},
|
||||
"servers":[{{"url":"https://api.example.test"}}],
|
||||
"components":{{
|
||||
"securitySchemes":{{"custom":{{"$ref":"{origin}/scheme.yaml#/x-scheme"}}}}
|
||||
}},
|
||||
"security":[{{"custom":[]}}],
|
||||
"paths":{{
|
||||
"/test":{{"get":{{
|
||||
"operationId":"test", "security":[{{"custom":[]}}],
|
||||
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"type":"string","default":"{canary}"}}}}],
|
||||
"responses":{{"200":{{"description":"ok"}}}}
|
||||
}}}}
|
||||
}}
|
||||
}}"#,
|
||||
origin = origin,
|
||||
canary = std::str::from_utf8(canary).unwrap(),
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let result = service.preview_openapi_import(&workspace_id, upload).await;
|
||||
server.abort();
|
||||
assert_eq!(
|
||||
fetched.load(Ordering::SeqCst),
|
||||
1,
|
||||
"external scheme must be fetched before the split is checked"
|
||||
);
|
||||
|
||||
let response_repr = match &result {
|
||||
Ok(preview) => serde_json::to_string(preview).unwrap(),
|
||||
Err(err) => format!("{err:?}"),
|
||||
};
|
||||
assert!(
|
||||
response_repr.contains("invalid_document"),
|
||||
"unsafe external scheme bundle was not rejected: {response_repr}"
|
||||
);
|
||||
assert!(
|
||||
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
|
||||
"credential canary leaked into API response"
|
||||
);
|
||||
assert!(
|
||||
!storage_contains_literal(&storage_root, canary),
|
||||
"raw credential literal from split external scheme ref persisted to storage"
|
||||
);
|
||||
assert_rejected_bundle_unpersisted(®istry, &workspace_id, &storage_root).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn referenced_security_credentials_local_scheme_external_parameter_default_canary_rejected() {
|
||||
let canary = b"split-local-canary-003-Xv7oI";
|
||||
// External document defines a parameter schema whose default is the canary.
|
||||
let external_doc = format!(
|
||||
r#"{{"x-key":{{"type":"string","default":"{canary}"}}}}"#,
|
||||
canary = std::str::from_utf8(canary).unwrap(),
|
||||
);
|
||||
let fetched = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetched);
|
||||
let app = Router::new().route(
|
||||
"/key.yaml",
|
||||
get(move || {
|
||||
let fc = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
fc.fetch_add(1, Ordering::SeqCst);
|
||||
external_doc.clone()
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_local_scheme_ext_param_canary");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
// Primary declares the scheme directly (no $ref); parameter schema is
|
||||
// an external $ref whose resolved default would be the canary.
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"{{
|
||||
"openapi":"3.1.0",
|
||||
"info":{{"title":"Local scheme ext param","version":"1"}},
|
||||
"servers":[{{"url":"https://api.example.test"}}],
|
||||
"components":{{
|
||||
"securitySchemes":{{"custom":{{"type":"apiKey","in":"header","name":"X-Custom"}}}}
|
||||
}},
|
||||
"security":[{{"custom":[]}}],
|
||||
"paths":{{
|
||||
"/test":{{"get":{{
|
||||
"operationId":"test", "security":[{{"custom":[]}}],
|
||||
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"$ref":"{origin}/key.yaml#/x-key"}}}}],
|
||||
"responses":{{"200":{{"description":"ok"}}}}
|
||||
}}}}
|
||||
}}
|
||||
}}"#,
|
||||
origin = origin,
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let result = service.preview_openapi_import(&workspace_id, upload).await;
|
||||
server.abort();
|
||||
assert_eq!(
|
||||
fetched.load(Ordering::SeqCst),
|
||||
1,
|
||||
"external parameter must be fetched before the split is checked"
|
||||
);
|
||||
|
||||
let response_repr = match &result {
|
||||
Ok(preview) => serde_json::to_string(preview).unwrap(),
|
||||
Err(err) => format!("{err:?}"),
|
||||
};
|
||||
assert!(
|
||||
response_repr.contains("invalid_document"),
|
||||
"unsafe external parameter bundle was not rejected: {response_repr}"
|
||||
);
|
||||
assert!(
|
||||
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
|
||||
"credential canary leaked into API response"
|
||||
);
|
||||
assert!(
|
||||
!storage_contains_literal(&storage_root, canary),
|
||||
"raw credential literal from external referenced parameter persisted to storage"
|
||||
);
|
||||
assert_rejected_bundle_unpersisted(®istry, &workspace_id, &storage_root).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn safe_external_security_scheme_and_parameter_are_preserved() {
|
||||
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
|
||||
let fetched = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetched);
|
||||
let app = Router::new().route(
|
||||
"/scheme.yaml",
|
||||
get(move || {
|
||||
let count = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
external_doc
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_safe_external_security_ref");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root,
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"openapi: 3.1.0
|
||||
info: {{ title: Safe external scheme, version: '1' }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
components:
|
||||
securitySchemes:
|
||||
custom: {{ $ref: '{origin}/scheme.yaml#/x-scheme' }}
|
||||
security: [{{ custom: [] }}]
|
||||
paths:
|
||||
/test:
|
||||
get:
|
||||
operationId: safeExternalSecurity
|
||||
security: [{{ custom: [] }}]
|
||||
parameters:
|
||||
- name: X-Custom
|
||||
in: header
|
||||
schema: {{ type: string }}
|
||||
- name: locale
|
||||
in: query
|
||||
schema: {{ type: string, default: en }}
|
||||
responses:
|
||||
'200': {{ description: ok }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("safe referenced schemes and parameters remain importable");
|
||||
server.abort();
|
||||
assert_eq!(fetched.load(Ordering::SeqCst), 1);
|
||||
let operation = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.find(|operation| operation.key == "GET /test")
|
||||
.expect("operation preview is preserved");
|
||||
assert!(matches!(
|
||||
&operation.security_schemes["custom"].kind,
|
||||
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
|
||||
parameter_name,
|
||||
location: crank_import::rest::SecurityParameterLocation::Header,
|
||||
..
|
||||
} if parameter_name == "X-Custom"
|
||||
));
|
||||
let input_schema = serde_json::to_value(&operation.draft.input_schema).unwrap();
|
||||
assert_eq!(
|
||||
input_schema.pointer("/fields/locale/default_value"),
|
||||
Some(&serde_json::json!("en")),
|
||||
"benign locale default must remain visible in the preview"
|
||||
);
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
job.preview_payload["dependency_snapshots"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
async fn assert_rejected_bundle_unpersisted(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
storage_root: &std::path::Path,
|
||||
) {
|
||||
let sources: i64 =
|
||||
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let jobs: i64 = sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sources, 0, "rejected bundle registered a source");
|
||||
assert_eq!(jobs, 0, "rejected bundle created an import job");
|
||||
assert!(
|
||||
!storage_has_files(storage_root),
|
||||
"rejected bundle stored artifact bytes"
|
||||
);
|
||||
}
|
||||
|
||||
fn storage_has_files(path: &std::path::Path) -> bool {
|
||||
std::fs::read_dir(path).unwrap().any(|entry| {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
storage_has_files(&path)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -26,10 +26,17 @@ async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_
|
||||
.unwrap()
|
||||
.preview_payload["preview"]
|
||||
.clone();
|
||||
assert_eq!(
|
||||
persisted_preview_before_apply,
|
||||
serde_json::to_value(&preview.preview).unwrap()
|
||||
);
|
||||
// Readiness is workspace-aware response metadata, not part of the immutable
|
||||
// projection persisted with the source job.
|
||||
let mut response_projection = serde_json::to_value(&preview.preview).unwrap();
|
||||
for group in response_projection["groups"].as_array_mut().unwrap() {
|
||||
for operation in group["operations"].as_array_mut().unwrap() {
|
||||
assert_eq!(operation["status"], "actionable");
|
||||
operation.as_object_mut().unwrap().remove("status");
|
||||
}
|
||||
}
|
||||
assert!(preview.preview.conflicts.is_empty());
|
||||
assert_eq!(persisted_preview_before_apply, response_projection);
|
||||
|
||||
let operations = preview
|
||||
.preview
|
||||
@@ -108,7 +115,6 @@ 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(),
|
||||
};
|
||||
@@ -200,7 +206,6 @@ 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,991 @@
|
||||
use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use crank_community_mcp::session::InMemorySessionStore;
|
||||
use crank_core::{
|
||||
MachineAccessMode, MachineCredentialVerifier, MachineCredentialVerifierError,
|
||||
OperationSecurityLevel, PlatformApiKeyScope, VerifiedMachineCredential,
|
||||
};
|
||||
|
||||
struct CorpusMcpCredentialVerifier;
|
||||
|
||||
#[async_trait]
|
||||
impl MachineCredentialVerifier for CorpusMcpCredentialVerifier {
|
||||
async fn verify_bearer_token(
|
||||
&self,
|
||||
_workspace_slug: &str,
|
||||
_agent_slug: &str,
|
||||
token: &str,
|
||||
) -> Result<Option<VerifiedMachineCredential>, MachineCredentialVerifierError> {
|
||||
Ok(
|
||||
(token == "corpus-test-token").then_some(VerifiedMachineCredential {
|
||||
machine_access_mode: MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: OperationSecurityLevel::Standard,
|
||||
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
platform_api_key_id: None,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
use super::super::common::*;
|
||||
|
||||
const OPENAPI_SINGLE: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Apply test }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/alpha:
|
||||
get:
|
||||
operationId: alpha
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_TWO_OPERATIONS: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Partial Apply test }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/alpha:
|
||||
get:
|
||||
operationId: alpha
|
||||
responses: { '200': { description: ok } }
|
||||
/beta:
|
||||
get:
|
||||
operationId: beta
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_TWO_APIKEY_OPERATIONS: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Authenticated Apply test, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
|
||||
security: [{ apiKey: [] }]
|
||||
paths:
|
||||
/alpha: { get: { operationId: alpha, responses: { '200': { description: ok } } } }
|
||||
/beta: { get: { operationId: beta, responses: { '200': { description: ok } } } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_SINGLE_APIKEY_OPERATION: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Authenticated Apply test, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
|
||||
paths:
|
||||
/alpha: { get: { operationId: alpha, security: [{ apiKey: [] }], responses: { '200': { description: ok } } } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_WITH_BLOCKER: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Blocked full Apply test }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/actionable:
|
||||
get:
|
||||
operationId: actionable
|
||||
responses: { '200': { description: ok } }
|
||||
/blocked:
|
||||
post:
|
||||
operationId: blocked
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/xml:
|
||||
schema: { type: string }
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
struct CreatedPlan {
|
||||
reference: String,
|
||||
digest: String,
|
||||
body: Value,
|
||||
preview: Value,
|
||||
}
|
||||
|
||||
async fn create_plan(
|
||||
client: &reqwest::Client,
|
||||
base_url: impl AsRef<str>,
|
||||
document: &str,
|
||||
plan_payload: Value,
|
||||
) -> CreatedPlan {
|
||||
let base_url = base_url.as_ref();
|
||||
let upload = reqwest::multipart::Part::bytes(document.as_bytes().to_vec())
|
||||
.file_name("import.yaml")
|
||||
.mime_str("application/yaml")
|
||||
.unwrap();
|
||||
let preview_response = client
|
||||
.post(format!("{base_url}/imports/openapi/preview"))
|
||||
.multipart(reqwest::multipart::Form::new().part("file", upload))
|
||||
.send()
|
||||
.await
|
||||
.expect("OpenAPI preview request should reach the Admin API");
|
||||
assert_eq!(
|
||||
preview_response.status(),
|
||||
reqwest::StatusCode::OK,
|
||||
"preview failed: {}",
|
||||
preview_response.text().await.unwrap_or_default()
|
||||
);
|
||||
let preview: Value = preview_response.json().await.unwrap();
|
||||
let job_id = preview["job_id"]
|
||||
.as_str()
|
||||
.expect("preview response must include the persisted job ID");
|
||||
|
||||
let plan_response = client
|
||||
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
|
||||
.json(&plan_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("ImportPlan request should reach the Admin API");
|
||||
let status = plan_response.status();
|
||||
let body: Value = plan_response.json().await.unwrap_or(Value::Null);
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"plan creation failed: {body}"
|
||||
);
|
||||
let reference = body["plan_reference"]
|
||||
.as_str()
|
||||
.expect("CreatePlan must return its server-issued reference")
|
||||
.to_owned();
|
||||
let digest = body["plan_digest"]
|
||||
.as_str()
|
||||
.expect("CreatePlan must return its server-derived digest")
|
||||
.to_owned();
|
||||
assert!(reference.starts_with("plan_"));
|
||||
assert_eq!(digest.len(), 64);
|
||||
assert!(digest.bytes().all(|byte| byte.is_ascii_hexdigit()));
|
||||
CreatedPlan {
|
||||
reference,
|
||||
digest,
|
||||
body,
|
||||
preview,
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_plan(
|
||||
client: &reqwest::Client,
|
||||
base_url: impl AsRef<str>,
|
||||
plan: &CreatedPlan,
|
||||
idempotency_key: &str,
|
||||
) -> (reqwest::StatusCode, Value) {
|
||||
let base_url = base_url.as_ref();
|
||||
let response = client
|
||||
.post(format!(
|
||||
"{base_url}/imports/openapi/{}/apply",
|
||||
plan.reference
|
||||
))
|
||||
.json(&json!({
|
||||
"plan_digest": plan.digest,
|
||||
"idempotency_key": idempotency_key
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("Apply request should reach the Admin API");
|
||||
let status = response.status();
|
||||
let body = response.json::<Value>().await.unwrap_or(Value::Null);
|
||||
(status, body)
|
||||
}
|
||||
|
||||
async fn operation_list(client: &reqwest::Client, base_url: impl AsRef<str>) -> Value {
|
||||
let base_url = base_url.as_ref();
|
||||
let response = client
|
||||
.get(format!("{base_url}/operations"))
|
||||
.send()
|
||||
.await
|
||||
.expect("operation list request should reach the Admin API");
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
response.json().await.unwrap()
|
||||
}
|
||||
|
||||
fn full_plan() -> Value {
|
||||
json!({ "selection_mode": "full", "selected_operation_keys": [] })
|
||||
}
|
||||
|
||||
fn report_has_outcome_status(report: &Value, expected: &str) -> bool {
|
||||
report["outcomes"].as_array().is_some_and(|outcomes| {
|
||||
outcomes
|
||||
.iter()
|
||||
.any(|outcome| outcome["status"] == expected || outcome["outcome"] == expected)
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn apply_creates_one_draft_from_a_server_created_plan() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_new_draft"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
assert_eq!(plan.body["counts"]["actionable"], 1);
|
||||
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-new-draft").await;
|
||||
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
|
||||
assert_eq!(report["plan_digest"], plan.digest);
|
||||
assert_eq!(report["outcomes"].as_array().unwrap().len(), 1);
|
||||
assert!(report_has_outcome_status(&report, "created"));
|
||||
assert!(report["outcomes"].to_string().contains("GET /alpha"));
|
||||
let operations = operation_list(&client, &base_url).await;
|
||||
assert_eq!(operations["total"], 1);
|
||||
assert_eq!(operations["items"][0]["status"], "draft");
|
||||
assert_eq!(operations["items"][0]["current_draft_version"], 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn full_apply_with_a_blocked_candidate_is_atomic_and_reports_the_failure() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_full_blocked"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_WITH_BLOCKER, full_plan()).await;
|
||||
assert_eq!(plan.body["counts"]["blocked"], 1);
|
||||
let before = operation_list(&client, &base_url).await;
|
||||
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-full-blocked").await;
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::CONFLICT,
|
||||
"unexpected report: {report}"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
assert!(
|
||||
report["outcomes"].is_array(),
|
||||
"blocked Apply must return outcomes: {report}"
|
||||
);
|
||||
assert!(report_has_outcome_status(&report, "rejected"));
|
||||
assert!(report["outcomes"].to_string().contains("POST /blocked"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn explicit_partial_plan_applies_only_selected_candidates_and_explains_exclusions() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_partial"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_TWO_OPERATIONS,
|
||||
json!({
|
||||
"selection_mode": "partial",
|
||||
"selected_operation_keys": ["GET /alpha"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(plan.body["counts"]["selected"], 1);
|
||||
assert_eq!(plan.body["counts"]["excluded"], 1);
|
||||
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-partial").await;
|
||||
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
|
||||
assert!(report["outcomes"].is_array());
|
||||
assert!(report_has_outcome_status(&report, "created"));
|
||||
let report_text = report.to_string();
|
||||
assert!(report_text.contains("GET /alpha"));
|
||||
assert!(report_text.contains("GET /beta"));
|
||||
assert!(report_text.contains("excluded"));
|
||||
let operations = operation_list(&client, &base_url).await;
|
||||
assert_eq!(operations["total"], 1);
|
||||
assert_eq!(operations["items"][0]["name"], "alpha");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn same_key_and_digest_replay_report_without_extra_draft_and_changed_digest_conflicts() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_idempotency"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
let (first_status, first_report) =
|
||||
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
|
||||
assert_eq!(
|
||||
first_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"Apply failed: {first_report}"
|
||||
);
|
||||
let operations_after_first = operation_list(&client, &base_url).await;
|
||||
|
||||
let (replay_status, replay_report) =
|
||||
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
|
||||
assert_eq!(replay_status, reqwest::StatusCode::OK);
|
||||
assert_eq!(replay_report, first_report);
|
||||
assert_eq!(
|
||||
operation_list(&client, &base_url).await,
|
||||
operations_after_first
|
||||
);
|
||||
|
||||
let changed = CreatedPlan {
|
||||
reference: plan.reference.clone(),
|
||||
digest: "0".repeat(64),
|
||||
body: plan.body.clone(),
|
||||
preview: plan.preview.clone(),
|
||||
};
|
||||
let (changed_status, _) = apply_plan(&client, &base_url, &changed, "stable-apply-key").await;
|
||||
assert_eq!(changed_status, reqwest::StatusCode::CONFLICT);
|
||||
assert_eq!(
|
||||
operation_list(&client, &base_url).await,
|
||||
operations_after_first
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn concurrent_same_key_apply_converges_on_one_persisted_report() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_concurrent_replay"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
|
||||
let (left, right) = tokio::join!(
|
||||
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
|
||||
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
|
||||
);
|
||||
|
||||
assert_eq!(left.0, reqwest::StatusCode::OK, "left: {}", left.1);
|
||||
assert_eq!(right.0, reqwest::StatusCode::OK, "right: {}", right.1);
|
||||
assert_eq!(left.1, right.1);
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn apply_rejects_client_candidate_fields_and_malformed_digest() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_input_validation"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
let url = format!("{base_url}/imports/openapi/{}/apply", plan.reference);
|
||||
|
||||
let extra_fields = client
|
||||
.post(&url)
|
||||
.json(&json!({
|
||||
"plan_digest": plan.digest,
|
||||
"idempotency_key": "validation-key",
|
||||
"operations": [{ "operation_id": "attacker-chosen" }]
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
extra_fields.status(),
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
|
||||
let malformed_digest = client
|
||||
.post(url)
|
||||
.json(&json!({
|
||||
"plan_digest": "not-a-digest",
|
||||
"idempotency_key": "validation-key"
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(malformed_digest.status(), reqwest::StatusCode::BAD_REQUEST);
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn exact_skip_and_rename_decisions_affect_only_the_confirmed_operations() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_skip_rename"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let initial = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
let (initial_status, initial_report) =
|
||||
apply_plan(&client, &base_url, &initial, "skip-rename-seed").await;
|
||||
assert_eq!(initial_status, reqwest::StatusCode::OK, "{initial_report}");
|
||||
let before_skip = operation_list(&client, &base_url).await;
|
||||
let operation_id = before_skip["items"][0]["id"]
|
||||
.as_str()
|
||||
.expect("operation list includes the workspace operation ID");
|
||||
|
||||
let skip = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /alpha",
|
||||
"action": "skip",
|
||||
"target_operation_id": operation_id
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (skip_status, skip_report) =
|
||||
apply_plan(&client, &base_url, &skip, "skip-exact-target").await;
|
||||
assert_eq!(skip_status, reqwest::StatusCode::OK, "{skip_report}");
|
||||
assert!(report_has_outcome_status(&skip_report, "skipped"));
|
||||
assert_eq!(skip_report["outcomes"][0]["operation_id"], operation_id);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before_skip);
|
||||
|
||||
let rename = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /alpha",
|
||||
"action": "rename",
|
||||
"confirmed_name": "alpha_imported"
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (rename_status, rename_report) =
|
||||
apply_plan(&client, &base_url, &rename, "rename-confirmed-name").await;
|
||||
assert_eq!(rename_status, reqwest::StatusCode::OK, "{rename_report}");
|
||||
assert!(report_has_outcome_status(&rename_report, "renamed"));
|
||||
let after_rename = operation_list(&client, &base_url).await;
|
||||
assert_eq!(after_rename["total"], 2);
|
||||
assert!(
|
||||
after_rename["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|item| { item["name"] == "alpha_imported" && item["status"] == "draft" })
|
||||
);
|
||||
assert!(
|
||||
after_rename["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|item| { item["id"] == operation_id && item["name"] == "alpha" })
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn new_version_preserves_published_version_and_prior_version() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_new_version_published"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let seed = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
let (seed_status, seed_report) =
|
||||
apply_plan(&client, &base_url, &seed, "new-version-seed").await;
|
||||
assert_eq!(seed_status, reqwest::StatusCode::OK, "{seed_report}");
|
||||
let seeded = operation_list(&client, &base_url).await;
|
||||
let operation_id = seeded["items"][0]["id"].as_str().unwrap().to_owned();
|
||||
|
||||
let publish = client
|
||||
.post(format!("{base_url}/operations/{operation_id}/publish"))
|
||||
.header(
|
||||
reqwest::header::IF_MATCH,
|
||||
operation_etag(&client, &base_url, &operation_id).await,
|
||||
)
|
||||
.json(&json!({ "version": 1 }))
|
||||
.send()
|
||||
.await
|
||||
.expect("publish request should reach the Admin API");
|
||||
assert_eq!(publish.status(), reqwest::StatusCode::OK);
|
||||
let published: Value = publish.json().await.unwrap();
|
||||
assert_eq!(published["published_version"], 1);
|
||||
let prior_version_before: Value = client
|
||||
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /alpha",
|
||||
"action": "new_version",
|
||||
"target_operation_id": operation_id
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "new-version-exact-target").await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
|
||||
assert!(report_has_outcome_status(&report, "versioned"));
|
||||
assert_eq!(report["outcomes"][0]["operation_id"], operation_id);
|
||||
assert_eq!(report["outcomes"][0]["version"], 2);
|
||||
|
||||
let after = operation_list(&client, &base_url).await;
|
||||
assert_eq!(after["total"], 1);
|
||||
assert_eq!(after["items"][0]["id"], operation_id);
|
||||
assert_eq!(after["items"][0]["latest_published_version"], 1);
|
||||
assert_eq!(after["items"][0]["current_draft_version"], 2);
|
||||
let published_again: Value = client
|
||||
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(published_again, prior_version_before);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("import_plan_apply_revoked_auth"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let secret_canary = "import-plan-auth-canary-must-not-leak";
|
||||
let secret_response = client
|
||||
.post(format!("{base_url}/secrets"))
|
||||
.json(&json!({
|
||||
"name": "import-plan-auth-token",
|
||||
"kind": "token",
|
||||
"value": { "token": secret_canary }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
|
||||
let secret: Value = secret_response.json().await.unwrap();
|
||||
let secret_id = secret["id"].as_str().unwrap();
|
||||
let profile_response = client
|
||||
.post(format!("{base_url}/auth-profiles"))
|
||||
.json(&json!({
|
||||
"name": "import-plan-auth-profile",
|
||||
"kind": "api_key_header",
|
||||
"config": {
|
||||
"api_key_header": {
|
||||
"header_name": "X-Api-Key",
|
||||
"secret_id": secret_id
|
||||
}
|
||||
}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
|
||||
let profile: Value = profile_response.json().await.unwrap();
|
||||
let auth_profile_id = profile["id"].as_str().unwrap();
|
||||
|
||||
let redacted_plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_TWO_APIKEY_OPERATIONS,
|
||||
json!({
|
||||
"selection_mode": "partial",
|
||||
"selected_operation_keys": ["GET /beta"],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /beta",
|
||||
"action": "create",
|
||||
"auth_profile_id": auth_profile_id
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (redacted_status, redacted_report) =
|
||||
apply_plan(&client, &base_url, &redacted_plan, "redacted-auth-report").await;
|
||||
assert_eq!(
|
||||
redacted_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"{redacted_report}"
|
||||
);
|
||||
assert!(redacted_report["source_digest"].is_string());
|
||||
assert!(!redacted_report.to_string().contains(secret_canary));
|
||||
assert!(!redacted_report.to_string().contains("ciphertext"));
|
||||
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE_APIKEY_OPERATION,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /alpha",
|
||||
"action": "create",
|
||||
"auth_profile_id": auth_profile_id
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
// A profile can remain active while its credential mapping changes.
|
||||
// The confirmed plan must not silently adopt the new configuration.
|
||||
sqlx::query(
|
||||
"update auth_profiles
|
||||
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-Changed-Key\"'),
|
||||
updated_at = now()
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(auth_profile_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let (drift_status, drift_error) =
|
||||
apply_plan(&client, &base_url, &plan, "changed-auth-config-apply").await;
|
||||
assert_eq!(drift_status, reqwest::StatusCode::CONFLICT, "{drift_error}");
|
||||
assert_eq!(
|
||||
drift_error["error"]["context"]["error_code"],
|
||||
"import_plan_auth_unavailable"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
|
||||
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&OPENAPI_SINGLE_APIKEY_OPERATION.replace("X-Api-Key", "X-Changed-Key"),
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /alpha",
|
||||
"action": "create",
|
||||
"auth_profile_id": auth_profile_id
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
// There is no profile revoke endpoint; disabling its backing credential
|
||||
// models revocation between confirmation and apply.
|
||||
sqlx::query(
|
||||
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(secret_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (status, error) = apply_plan(&client, &base_url, &plan, "revoked-auth-apply").await;
|
||||
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
|
||||
assert_eq!(
|
||||
error["error"]["context"]["error_code"],
|
||||
"import_plan_auth_unavailable"
|
||||
);
|
||||
let response_text = error.to_string();
|
||||
assert!(!response_text.contains(secret_canary));
|
||||
assert!(!response_text.contains("ciphertext"));
|
||||
let after = operation_list(&client, &base_url).await;
|
||||
assert_eq!(after["total"], 1);
|
||||
assert_eq!(after["items"][0]["name"], "beta");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn profiles_sharing_active_secret_are_selectable_and_both_block_after_disable() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("import_plan_shared_auth_secret"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let secret_response = client
|
||||
.post(format!("{base_url}/secrets"))
|
||||
.json(&json!({
|
||||
"name": "shared-import-auth-token",
|
||||
"kind": "token",
|
||||
"value": { "token": "shared-import-canary" }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
|
||||
let secret: Value = secret_response.json().await.unwrap();
|
||||
let secret_id = secret["id"].as_str().unwrap();
|
||||
let make_profile = |name: &str| {
|
||||
client
|
||||
.post(format!("{base_url}/auth-profiles"))
|
||||
.json(&json!({
|
||||
"name": name,
|
||||
"kind": "api_key_header",
|
||||
"config": { "api_key_header": {
|
||||
"header_name": "X-Api-Key",
|
||||
"secret_id": secret_id
|
||||
}}
|
||||
}))
|
||||
};
|
||||
let first: Value = make_profile("shared-auth-a")
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let second: Value = make_profile("shared-auth-b")
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let document = r#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Shared profile test","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
|
||||
"paths":{
|
||||
"/a":{"get":{"operationId":"sharedA","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}},
|
||||
"/b":{"get":{"operationId":"sharedB","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}}
|
||||
}
|
||||
}"#;
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
document,
|
||||
json!({
|
||||
"selection_mode":"full",
|
||||
"selected_operation_keys":[],
|
||||
"decisions":[
|
||||
{"operation_key":"GET /a","action":"create","auth_profile_id":first["id"]},
|
||||
{"operation_key":"GET /b","action":"create","auth_profile_id":second["id"]}
|
||||
]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "shared-secret-active").await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
|
||||
|
||||
let first_id = first["id"].as_str().unwrap();
|
||||
let second_id = second["id"].as_str().unwrap();
|
||||
let disabled_document = document
|
||||
.replace("sharedA", "sharedAAfterDisable")
|
||||
.replace("sharedB", "sharedBAfterDisable");
|
||||
let mut disabled_plans = Vec::new();
|
||||
for (key, profile_id) in [("GET /a", first_id), ("GET /b", second_id)] {
|
||||
disabled_plans.push((
|
||||
key,
|
||||
create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&disabled_document,
|
||||
json!({
|
||||
"selection_mode":"partial",
|
||||
"selected_operation_keys":[key],
|
||||
"decisions":[{"operation_key":key,"action":"create","auth_profile_id":profile_id}]
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
));
|
||||
}
|
||||
sqlx::query("update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2")
|
||||
.bind("ws_default")
|
||||
.bind(secret_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
for (key, plan) in disabled_plans {
|
||||
let (status, error) = apply_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&plan,
|
||||
&format!("shared-secret-disabled-{key}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
|
||||
assert_eq!(
|
||||
error["error"]["context"]["error_code"],
|
||||
"import_plan_auth_unavailable"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
|
||||
use axum::{Json, Router};
|
||||
|
||||
let registry = test_registry().await;
|
||||
let (request_tx, mut request_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let upstream =
|
||||
Router::new().fallback(move |method: axum::http::Method, uri: axum::http::Uri| {
|
||||
let request_tx = request_tx.clone();
|
||||
async move {
|
||||
request_tx.send((method, uri)).unwrap();
|
||||
Json(json!({"id":"corpus-0"}))
|
||||
}
|
||||
});
|
||||
let upstream_base = spawn_admin_api(upstream).await;
|
||||
let storage = test_storage_root("corpus_ac4");
|
||||
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../crates/crank-import/tests/corpus/representative-00.json");
|
||||
let mut fixture: Value = serde_json::from_slice(&std::fs::read(fixture_path).unwrap()).unwrap();
|
||||
let upstream_origin = upstream_base
|
||||
.as_ref()
|
||||
.split("/api/admin/workspaces/")
|
||||
.next()
|
||||
.unwrap();
|
||||
fixture["servers"] = json!([{ "url": upstream_origin }]);
|
||||
let document = serde_json::to_string(&fixture).unwrap();
|
||||
let plan = create_plan(&client, &base_url, &document, full_plan()).await;
|
||||
assert_eq!(plan.body["counts"]["actionable"], 1);
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac4-import").await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
|
||||
assert!(report_has_outcome_status(&report, "created"));
|
||||
let operations = operation_list(&client, &base_url).await;
|
||||
assert_eq!(operations["total"], 1);
|
||||
assert_eq!(operations["items"][0]["status"], "draft");
|
||||
let operation_id = operations["items"][0]["id"].as_str().unwrap().to_owned();
|
||||
|
||||
// The admin test run performs the persisted Draft validation and a real
|
||||
// HTTP execution against the local fixture server before publication.
|
||||
let test_run = client
|
||||
.post(format!("{base_url}/operations/{operation_id}/test-runs"))
|
||||
.json(&json!({"version":1,"input":{}}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(test_run.status(), reqwest::StatusCode::OK);
|
||||
let test_result: Value = test_run.json().await.unwrap();
|
||||
assert_eq!(test_result["ok"], true, "Draft test failed: {test_result}");
|
||||
let published = client
|
||||
.post(format!("{base_url}/operations/{operation_id}/publish"))
|
||||
.header(
|
||||
reqwest::header::IF_MATCH,
|
||||
operation_etag(&client, &base_url, &operation_id).await,
|
||||
)
|
||||
.json(&json!({"version":1}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(published.status(), reqwest::StatusCode::OK);
|
||||
|
||||
let agent = client.post(format!("{base_url}/agents")).json(&json!({
|
||||
"slug":"corpus-regression-agent","display_name":"Corpus Regression Agent",
|
||||
"description":"Local corpus acceptance fixture","instructions":{},"tool_selection_policy":{}
|
||||
})).send().await.unwrap().json::<Value>().await.unwrap();
|
||||
let agent_id = agent["agent_id"].as_str().unwrap();
|
||||
let bindings = client.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, agent_etag(&client, &base_url, agent_id).await)
|
||||
.json(&json!([{"operation_id":operation_id,"operation_version":1,"tool_name":"corpusOperation00","tool_title":"Synthetic operation 00","enabled":true}]))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(bindings.status(), reqwest::StatusCode::OK);
|
||||
let agent_publish = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/publish"))
|
||||
.header(
|
||||
reqwest::header::IF_MATCH,
|
||||
agent_etag(&client, &base_url, agent_id).await,
|
||||
)
|
||||
.json(&json!({"version":1}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(agent_publish.status(), reqwest::StatusCode::OK);
|
||||
|
||||
let mcp = crank_community_mcp::build_app(
|
||||
registry,
|
||||
Duration::ZERO,
|
||||
None,
|
||||
test_secret_crypto(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
crank_runtime::RequestRateLimiter::new(
|
||||
crank_runtime::RequestRateLimitConfig::new(100, 100).unwrap(),
|
||||
),
|
||||
Arc::new(crank_runtime::InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(InMemorySessionStore::default()),
|
||||
Arc::new(CorpusMcpCredentialVerifier),
|
||||
);
|
||||
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, mcp).await.unwrap();
|
||||
});
|
||||
let mcp_base = format!("http://{address}");
|
||||
let mcp_url = format!("{mcp_base}/v1/default/corpus-regression-agent");
|
||||
let initialized = client.post(&mcp_url).bearer_auth("corpus-test-token")
|
||||
.header("accept", "application/json, text/event-stream")
|
||||
.json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"corpus","version":"1"}}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(initialized.status(), reqwest::StatusCode::OK);
|
||||
let session = initialized
|
||||
.headers()
|
||||
.get("mcp-session-id")
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let notification = client
|
||||
.post(&mcp_url)
|
||||
.bearer_auth("corpus-test-token")
|
||||
.header("accept", "application/json, text/event-stream")
|
||||
.header("mcp-session-id", &session)
|
||||
.header("mcp-protocol-version", "2025-11-25")
|
||||
.json(&json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(notification.status(), reqwest::StatusCode::ACCEPTED);
|
||||
let called = client.post(&mcp_url).bearer_auth("corpus-test-token")
|
||||
.header("accept", "application/json, text/event-stream").header("mcp-session-id", session)
|
||||
.header("mcp-protocol-version", "2025-11-25")
|
||||
.json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"corpusOperation00","arguments":{}}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(called.status(), reqwest::StatusCode::OK);
|
||||
let call: Value = called.json().await.unwrap();
|
||||
assert_eq!(call["result"]["isError"], false, "MCP call failed: {call}");
|
||||
assert_eq!(call["result"]["structuredContent"]["id"], "corpus-0");
|
||||
for stage in ["Draft test run", "MCP call"] {
|
||||
let (method, uri) = request_rx
|
||||
.try_recv()
|
||||
.unwrap_or_else(|_| panic!("{stage} missed upstream"));
|
||||
assert_eq!(method, axum::http::Method::GET, "{stage}");
|
||||
assert_eq!(uri.path(), "/items/0", "{stage}");
|
||||
}
|
||||
}
|
||||
|
||||
mod corpus_hostile;
|
||||
mod locale;
|
||||
mod security_source;
|
||||
mod support_matrix;
|
||||
@@ -0,0 +1,292 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, test_storage_root("corpus_ac5"))).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../crates/crank-import/tests/corpus");
|
||||
let hostile_xml = std::fs::read_to_string(root.join("hostile-xml.json")).unwrap();
|
||||
let before = operation_list(&client, &base_url).await;
|
||||
let started = std::time::Instant::now();
|
||||
let plan = create_plan(&client, &base_url, &hostile_xml, full_plan()).await;
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"hostile document exceeded bounded test budget"
|
||||
);
|
||||
assert!(
|
||||
plan.body["counts"]["blocked"].as_u64().unwrap_or(0) > 0,
|
||||
"hostile XML must be a blocker: {}",
|
||||
plan.body
|
||||
);
|
||||
let xml_candidate = &plan.preview["preview"]["groups"][0]["operations"][0];
|
||||
assert_eq!(xml_candidate["key"], "GET /xml");
|
||||
assert!(
|
||||
xml_candidate["findings"]
|
||||
.as_array()
|
||||
.is_some_and(|findings| findings.iter().any(|finding| finding["code"]
|
||||
== "unsupported_xml_response_media_type"
|
||||
&& finding["severity"] == "error")),
|
||||
"HTTP preview must expose the exact XML blocker: {}",
|
||||
plan.preview
|
||||
);
|
||||
assert_eq!(
|
||||
plan.body["candidates"][0]["reason"], "unsupported_xml_response_media_type",
|
||||
"HTTP plan must retain the XML blocker: {}",
|
||||
plan.body
|
||||
);
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac5-hostile").await;
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::CONFLICT,
|
||||
"blocker must reject atomically: {report}"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
|
||||
// Credential-bearing sources are rejected before their original bytes
|
||||
// can enter artifact storage, rather than producing a persisted plan.
|
||||
for file in [
|
||||
"hostile-secret.json",
|
||||
"hostile-malformed.json",
|
||||
"hostile-oversized.json",
|
||||
] {
|
||||
let source = std::fs::read(root.join(file)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let upload = reqwest::multipart::Part::bytes(source)
|
||||
.file_name(file)
|
||||
.mime_str("application/json")
|
||||
.unwrap();
|
||||
let response = client
|
||||
.post(format!("{base_url}/imports/openapi/preview"))
|
||||
.multipart(reqwest::multipart::Form::new().part("file", upload))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
assert!(
|
||||
!status.is_success(),
|
||||
"{file} unexpectedly passed preview: {body}"
|
||||
);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"{file} exceeded bounded upload/parse time"
|
||||
);
|
||||
assert!(
|
||||
!body.contains("sk_test_corpus_secret_canary"),
|
||||
"hostile error response leaked a secret canary"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_list(&client, &base_url).await,
|
||||
before,
|
||||
"{file} mutated the operation registry"
|
||||
);
|
||||
}
|
||||
|
||||
// Real HTTP preview+plan: a root security requirement combined with an
|
||||
// explicit empty operation override must leave the public operation
|
||||
// actionable and leave the inherited one unresolved without a profile.
|
||||
let mixed_security: Value = serde_json::json!({
|
||||
"openapi": "3.0.3",
|
||||
"info": { "title": "Mixed security plan probe", "version": "1" },
|
||||
"servers": [{ "url": "https://security.example.test" }],
|
||||
"components": { "securitySchemes": { "probe": { "type": "http", "scheme": "basic" } } },
|
||||
"security": [{ "probe": [] }],
|
||||
"paths": {
|
||||
"/public": { "get": { "security": [], "operationId": "securityPublic",
|
||||
"responses": { "200": { "description": "ok" } } } },
|
||||
"/secured": { "get": { "operationId": "securitySecured",
|
||||
"responses": { "200": { "description": "ok" } } } }
|
||||
}
|
||||
});
|
||||
let security_mixed = serde_json::to_string(&mixed_security).unwrap();
|
||||
let security_plan = create_plan(&client, &base_url, &security_mixed, full_plan()).await;
|
||||
assert_eq!(
|
||||
security_plan.body["counts"]["selected"], 2,
|
||||
"{}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
security_plan.body["counts"]["actionable"], 1,
|
||||
"{}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
security_plan.body["counts"]["blocked"], 1,
|
||||
"{}",
|
||||
security_plan.body
|
||||
);
|
||||
let security_candidates = security_plan.body["candidates"].as_array().unwrap();
|
||||
let by_key = |key: &str| {
|
||||
security_candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate["key"] == key)
|
||||
.unwrap_or_else(|| panic!("candidate {key} missing: {}", security_plan.body))
|
||||
};
|
||||
let public = by_key("GET /public");
|
||||
let secured = by_key("GET /secured");
|
||||
assert_eq!(
|
||||
public["state"].as_str(),
|
||||
Some("actionable"),
|
||||
"public candidate with empty security override must stay actionable: {}",
|
||||
security_plan.body
|
||||
);
|
||||
assert!(
|
||||
public["reason"].is_null(),
|
||||
"public candidate must not carry a security blocker: {}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
secured["state"].as_str(),
|
||||
Some("blocked"),
|
||||
"inherited security requirement must block the affected candidate: {}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
secured["reason"].as_str(),
|
||||
Some("auth_profile_required"),
|
||||
"secured candidate must expose its unresolved binding: {}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
operation_list(&client, &base_url).await,
|
||||
before,
|
||||
"security-scoped plan must not mutate the operation registry"
|
||||
);
|
||||
let (blocked_status, blocked_report) = apply_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&security_plan,
|
||||
"corpus-ac5-security-blocked",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
blocked_status,
|
||||
reqwest::StatusCode::CONFLICT,
|
||||
"{blocked_report}"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
|
||||
let public_plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&security_mixed,
|
||||
json!({
|
||||
"selection_mode": "partial",
|
||||
"selected_operation_keys": ["GET /public"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(public_plan.body["counts"]["actionable"], 1);
|
||||
assert_eq!(public_plan.body["counts"]["blocked"], 0);
|
||||
let (public_status, public_report) = apply_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&public_plan,
|
||||
"corpus-ac5-security-public",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(public_status, reqwest::StatusCode::OK, "{public_report}");
|
||||
assert!(report_has_outcome_status(&public_report, "created"));
|
||||
let after = operation_list(&client, &base_url).await;
|
||||
assert_eq!(after["total"], 1, "{after}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn p0_api_malformed_local_security_is_atomic_across_openapi_versions() {
|
||||
for (version, document) in [
|
||||
(
|
||||
"openapi-3.1",
|
||||
serde_json::json!({
|
||||
"openapi": "3.1.0",
|
||||
"info": { "title": "Security API regression", "version": "1" },
|
||||
"servers": [{ "url": "https://security.example.test" }],
|
||||
"security": [{ "probe": [] }],
|
||||
"paths": {
|
||||
"/bad": { "get": { "security": "basic", "operationId": "badOp",
|
||||
"responses": { "200": { "description": "ok" } } } },
|
||||
"/public": { "get": { "security": [], "operationId": "publicOp",
|
||||
"responses": { "200": { "description": "ok" } } } }
|
||||
}
|
||||
}),
|
||||
),
|
||||
(
|
||||
"swagger-2.0",
|
||||
serde_json::json!({
|
||||
"swagger": "2.0",
|
||||
"info": { "title": "Security API regression", "version": "1" },
|
||||
"host": "security.example.test",
|
||||
"schemes": ["https"],
|
||||
"security": [{ "apiKey": [] }],
|
||||
"paths": {
|
||||
"/bad": { "get": { "security": "apikey", "operationId": "badOp",
|
||||
"responses": { "200": { "description": "ok" } } } },
|
||||
"/public": { "get": { "security": [], "operationId": "publicOp",
|
||||
"responses": { "200": { "description": "ok" } } } }
|
||||
}
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root(&format!("security_api_{version}")),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let source = serde_json::to_string(&document).unwrap();
|
||||
let before = operation_list(&client, &base_url).await;
|
||||
|
||||
let plan = create_plan(&client, &base_url, &source, full_plan()).await;
|
||||
assert_eq!(
|
||||
plan.body["counts"]["actionable"], 1,
|
||||
"{version}: {}",
|
||||
plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
plan.body["counts"]["blocked"], 1,
|
||||
"{version}: {}",
|
||||
plan.body
|
||||
);
|
||||
let candidates = plan.body["candidates"].as_array().unwrap();
|
||||
let bad = candidates
|
||||
.iter()
|
||||
.find(|item| item["key"] == "GET /bad")
|
||||
.unwrap();
|
||||
let public = candidates
|
||||
.iter()
|
||||
.find(|item| item["key"] == "GET /public")
|
||||
.unwrap();
|
||||
assert_eq!(bad["state"], "blocked", "{version}: {}", plan.body);
|
||||
assert_eq!(bad["reason"], "invalid_security_requirements");
|
||||
assert_eq!(public["state"], "actionable", "{version}: {}", plan.body);
|
||||
assert!(public["reason"].is_null());
|
||||
|
||||
let (status, report) = apply_plan(&client, &base_url, &plan, "security-full").await;
|
||||
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{version}: {report}");
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
|
||||
let public_plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
&source,
|
||||
json!({
|
||||
"selection_mode": "partial",
|
||||
"selected_operation_keys": ["GET /public"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(public_plan.body["counts"]["actionable"], 1);
|
||||
assert_eq!(public_plan.body["counts"]["blocked"], 0);
|
||||
let (status, report) =
|
||||
apply_plan(&client, &base_url, &public_plan, "security-public").await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "{version}: {report}");
|
||||
assert!(report_has_outcome_status(&report, "created"));
|
||||
let after = operation_list(&client, &base_url).await;
|
||||
assert_eq!(after["total"], 1, "{version}: {after}");
|
||||
assert_eq!(after["items"][0]["status"], "draft");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use super::*;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_apply_localizes_repreview_guidance_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let base_url = spawn_admin_api(build_test_app(
|
||||
registry,
|
||||
test_storage_root("import_plan_apply_locale"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
let url = format!(
|
||||
"{}/imports/openapi/{}/apply",
|
||||
base_url.as_ref(),
|
||||
plan.reference
|
||||
);
|
||||
let wrong_digest = "0".repeat(64);
|
||||
|
||||
// Russian session: Russian recovery guidance, identical machine code and
|
||||
// recovery flags.
|
||||
let ru = client
|
||||
.post(&url)
|
||||
.header("accept-language", "ru")
|
||||
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-ru" }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
|
||||
let ru_body: Value = ru.json().await.unwrap();
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["error_code"],
|
||||
"import_plan_digest_mismatch"
|
||||
);
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["repreview_required"],
|
||||
json!(true)
|
||||
);
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["recovery"],
|
||||
"repreview_required"
|
||||
);
|
||||
assert!(
|
||||
ru_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("создайте новый preview"),
|
||||
"Russian session must receive Russian guidance: {ru_body:?}"
|
||||
);
|
||||
|
||||
// No locale header keeps the English default behavior.
|
||||
let en = client
|
||||
.post(&url)
|
||||
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-en" }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
|
||||
let en_body: Value = en.json().await.unwrap();
|
||||
assert_eq!(
|
||||
en_body["error"]["context"]["error_code"],
|
||||
"import_plan_digest_mismatch"
|
||||
);
|
||||
assert!(
|
||||
en_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("create a fresh preview"),
|
||||
"EN default must remain English: {en_body:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_apply_localizes_registry_name_conflict_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("import_plan_apply_locale_name_conflict");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let created = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
|
||||
|
||||
// Keep a historical v1-shaped plan to exercise the registry's typed
|
||||
// name-conflict mapping directly. A v2 plan would stop earlier at the
|
||||
// catalog-revision guard after the concurrent name claim below.
|
||||
let original_id: ImportPlanId = created.reference.as_str().into();
|
||||
let original = registry
|
||||
.get_import_plan(&workspace_id, &original_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("HTTP-created plan is persisted");
|
||||
let legacy_id: ImportPlanId = "plan_locale_apply_name_conflict_v1".into();
|
||||
let mut legacy_payload = original.payload.clone();
|
||||
legacy_payload["schema_version"] = json!("import-plan-v1");
|
||||
legacy_payload["plan_reference"] = json!(legacy_id.as_str());
|
||||
let legacy_fields = legacy_payload.as_object_mut().unwrap();
|
||||
for field in [
|
||||
"catalog_revision",
|
||||
"excluded_reasons",
|
||||
"findings",
|
||||
"support_matrix_version",
|
||||
] {
|
||||
legacy_fields.remove(field);
|
||||
}
|
||||
let legacy = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &legacy_id,
|
||||
workspace_id: &workspace_id,
|
||||
job_id: &original.job_id,
|
||||
payload: &legacy_payload,
|
||||
created_at: &original.created_at,
|
||||
expires_at: &original.expires_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let candidate_name = created.body["candidates"][0]["name"]
|
||||
.as_str()
|
||||
.expect("plan contains its candidate name");
|
||||
service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload("https://api.example.test", candidate_name),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let url = format!(
|
||||
"{}/imports/openapi/{}/apply",
|
||||
base_url.as_ref(),
|
||||
legacy_id.as_str()
|
||||
);
|
||||
for (locale, idempotency_key, expected_message) in [
|
||||
(
|
||||
Some("ru"),
|
||||
"name-conflict-ru",
|
||||
"имя операции изменилось после создания плана",
|
||||
),
|
||||
(
|
||||
None,
|
||||
"name-conflict-en",
|
||||
"an operation name changed after the plan was created",
|
||||
),
|
||||
] {
|
||||
let mut request = client.post(&url).json(&json!({
|
||||
"plan_digest": legacy.digest,
|
||||
"idempotency_key": idempotency_key
|
||||
}));
|
||||
if let Some(locale) = locale {
|
||||
request = request.header("accept-language", locale);
|
||||
}
|
||||
let response = request.send().await.unwrap();
|
||||
assert_eq!(response.status(), reqwest::StatusCode::CONFLICT);
|
||||
let body: Value = response.json().await.unwrap();
|
||||
assert_eq!(
|
||||
body["error"]["context"]["error_code"],
|
||||
"import_plan_name_conflict"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["context"]["recovery"],
|
||||
"confirm_skip_rename_or_new_version"
|
||||
);
|
||||
assert_eq!(body["error"]["message"], expected_message);
|
||||
}
|
||||
|
||||
let matching_operations: i64 =
|
||||
sqlx::query_scalar("select count(*) from operations where workspace_id = $1 and name = $2")
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(candidate_name)
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
matching_operations, 1,
|
||||
"Apply must not create another operation"
|
||||
);
|
||||
let applications: i64 = sqlx::query_scalar(
|
||||
"select count(*) from import_plan_applications where workspace_id = $1 and plan_id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(legacy_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
applications, 0,
|
||||
"a rejected Apply must not persist an application"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use super::*;
|
||||
|
||||
const SECURITY_SOURCE_A: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Security source A, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
apiKey:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-Api-Key
|
||||
paths:
|
||||
/secure:
|
||||
get:
|
||||
operationId: secureWithApiKey
|
||||
security: [{ apiKey: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const SECURITY_SOURCE_B: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Security source A, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
apiKey:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-Rotated-Key
|
||||
paths:
|
||||
/secure:
|
||||
get:
|
||||
operationId: secureWithApiKey
|
||||
security: [{ apiKey: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn changed_security_scheme_invalidates_old_plan_before_draft_creation() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("import_plan_security_source_change");
|
||||
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let secret_response = client
|
||||
.post(format!("{base_url}/secrets"))
|
||||
.json(&json!({
|
||||
"name": "security-source-test-secret",
|
||||
"kind": "token",
|
||||
"value": { "token": "source-change-canary" }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
|
||||
let secret: Value = secret_response.json().await.unwrap();
|
||||
let profile_response = client
|
||||
.post(format!("{base_url}/auth-profiles"))
|
||||
.json(&json!({
|
||||
"name": "security-source-test-profile",
|
||||
"kind": "api_key_header",
|
||||
"config": { "api_key_header": {
|
||||
"header_name": "X-Api-Key",
|
||||
"secret_id": secret["id"]
|
||||
}}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
|
||||
let profile: Value = profile_response.json().await.unwrap();
|
||||
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
SECURITY_SOURCE_A,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /secure",
|
||||
"action": "create",
|
||||
"auth_profile_id": profile["id"]
|
||||
}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(plan.body["candidates"][0]["auth_profile_id"], profile["id"]);
|
||||
assert_eq!(plan.body["candidates"][0]["security_alternative_index"], 0);
|
||||
let stored_plan = registry
|
||||
.get_import_plan(
|
||||
&crank_core::WorkspaceId::new("ws_default"),
|
||||
&plan.reference.clone().into(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored_plan.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
|
||||
profile["id"],
|
||||
"the old plan must persist its explicit profile binding"
|
||||
);
|
||||
assert_eq!(
|
||||
stored_plan.payload["candidates"][0]["auth_requirement"]["parameter_name"],
|
||||
"X-Api-Key"
|
||||
);
|
||||
|
||||
// Register a second immutable source with only the security parameter
|
||||
// changed. Its own upload/preview proves these are valid changed bytes,
|
||||
// rather than corruption of the first content-addressed artifact.
|
||||
let source_b_upload = reqwest::multipart::Part::bytes(SECURITY_SOURCE_B.as_bytes().to_vec())
|
||||
.file_name("security-b.yaml")
|
||||
.mime_str("application/yaml")
|
||||
.unwrap();
|
||||
let source_b_response = client
|
||||
.post(format!("{base_url}/imports/openapi/preview"))
|
||||
.multipart(reqwest::multipart::Form::new().part("file", source_b_upload))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(source_b_response.status(), reqwest::StatusCode::OK);
|
||||
let source_b_preview: Value = source_b_response.json().await.unwrap();
|
||||
assert_eq!(
|
||||
source_b_preview["preview"]["groups"][0]["operations"][0]["security_schemes"]["apiKey"]["kind"]
|
||||
["parameter_name"],
|
||||
"X-Rotated-Key"
|
||||
);
|
||||
let workspace_id = crank_core::WorkspaceId::new("ws_default");
|
||||
let original_job_id: crank_registry::ImportJobId =
|
||||
plan.preview["job_id"].as_str().unwrap().into();
|
||||
let changed_job_id: crank_registry::ImportJobId =
|
||||
source_b_preview["job_id"].as_str().unwrap().into();
|
||||
let original_job = registry
|
||||
.get_import_job(&workspace_id, &original_job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let changed_job = registry
|
||||
.get_import_job(&workspace_id, &changed_job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_ne!(
|
||||
original_job.preview_payload["source"]["digest"],
|
||||
changed_job.preview_payload["source"]["digest"],
|
||||
"the changed scheme must come from a different verified source artifact"
|
||||
);
|
||||
assert_eq!(
|
||||
stored_plan.payload["source"]["digest"], original_job.preview_payload["source"]["digest"],
|
||||
"the plan must remain anchored to source A"
|
||||
);
|
||||
|
||||
// Simulate the existing new-source/re-preview condition on the anchored
|
||||
// pending job while retaining its original plan. The replacement is a
|
||||
// separately registered and digest-verified B snapshot; Apply must
|
||||
// compare the newly derived fingerprint with the old plan fingerprint.
|
||||
sqlx::query("update import_jobs set preview_payload = $3 where id = $1 and workspace_id = $2")
|
||||
.bind(original_job_id.as_str())
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&changed_job.preview_payload)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let replaced_job = registry
|
||||
.get_import_job(&workspace_id, &original_job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
replaced_job.preview_payload["source"]["digest"],
|
||||
changed_job.preview_payload["source"]["digest"]
|
||||
);
|
||||
|
||||
let (status, error) = apply_plan(&client, &base_url, &plan, "security-source-changed").await;
|
||||
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
|
||||
assert_eq!(
|
||||
error["error"]["context"]["error_code"], "import_plan_fingerprint_stale",
|
||||
"the old plan must require re-preview after source security changes"
|
||||
);
|
||||
assert_eq!(error["error"]["context"]["repreview_required"], true);
|
||||
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
use super::*;
|
||||
|
||||
use admin_api::error::ApiError;
|
||||
use admin_api::service::{
|
||||
OpenApiImportPlanApplyPayload, OpenApiImportPlanCreatePayload, OpenApiUpload,
|
||||
OpenApiUploadLocale,
|
||||
};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn older_v2_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_old_support_matrix_apply"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: OPENAPI_SINGLE.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.as_str().into();
|
||||
let created = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportPlanCreatePayload {
|
||||
selection_mode: "full".to_owned(),
|
||||
selected_operation_keys: Vec::new(),
|
||||
server_url: None,
|
||||
decisions: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let original_id: ImportPlanId = created.plan_reference.as_str().into();
|
||||
let original = registry
|
||||
.get_import_plan(&workspace_id, &original_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// Model an immutable plan saved under an earlier support matrix. The
|
||||
// registry derives its valid semantic digest from the changed payload.
|
||||
let old_id: ImportPlanId = "plan_older_support_matrix".into();
|
||||
let mut old_payload = original.payload.clone();
|
||||
old_payload["plan_reference"] = json!(old_id.as_str());
|
||||
old_payload["support_matrix_version"] = json!("1.0.2");
|
||||
let older = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &old_id,
|
||||
workspace_id: &workspace_id,
|
||||
job_id: &original.job_id,
|
||||
payload: &old_payload,
|
||||
created_at: &original.created_at,
|
||||
expires_at: &original.expires_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(older.digest, original.digest);
|
||||
|
||||
let audit = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &old_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(audit.revalidation_status, "stale");
|
||||
assert!(audit.revalidation_required);
|
||||
assert_eq!(audit.reason.as_deref(), Some("importer_version_changed"));
|
||||
|
||||
let error = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&old_id,
|
||||
OpenApiImportPlanApplyPayload {
|
||||
plan_digest: older.digest,
|
||||
idempotency_key: "old-matrix-new-attempt".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("old support matrix must not authorize a new Apply");
|
||||
match error {
|
||||
ApiError::Conflict {
|
||||
context: Some(context),
|
||||
..
|
||||
} => assert_eq!(context["error_code"], "importer_version_changed"),
|
||||
other => panic!("expected typed re-preview conflict, got {other:?}"),
|
||||
}
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,997 @@
|
||||
use super::*;
|
||||
|
||||
pub(crate) const OPENAPI_SINGLE_SECURITY: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Import security, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
Key: { type: apiKey, in: header, name: X-Api-Key }
|
||||
Bearer: { type: http, scheme: bearer }
|
||||
paths:
|
||||
/v2/latest:
|
||||
get:
|
||||
operationId: latestRates
|
||||
security: [{ Key: [] }, { Bearer: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn preview_name_conflicts_are_typed_and_deterministic() {
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_preview_name_conflicts"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace = WorkspaceId::new("ws_default");
|
||||
service
|
||||
.create_operation(
|
||||
&workspace,
|
||||
test_operation_payload(&upstream, "duplicate_id"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Naming }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/one:
|
||||
get:
|
||||
operationId: duplicate_id
|
||||
responses: { '200': { description: ok } }
|
||||
/two:
|
||||
get:
|
||||
operationId: duplicate_id
|
||||
responses: { '200': { description: ok } }
|
||||
/bad:
|
||||
get:
|
||||
operationId: bad-id
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
let first = service
|
||||
.preview_openapi_import(&workspace, upload(document))
|
||||
.await
|
||||
.unwrap();
|
||||
let repeated = service
|
||||
.preview_openapi_import(&workspace, upload(document))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.preview.conflicts, repeated.preview.conflicts);
|
||||
assert!(
|
||||
first
|
||||
.preview
|
||||
.conflicts
|
||||
.iter()
|
||||
.any(|item| item.conflict_type == "duplicate_name")
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.preview
|
||||
.conflicts
|
||||
.iter()
|
||||
.any(|item| item.conflict_type == "invalid_name")
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.preview
|
||||
.conflicts
|
||||
.iter()
|
||||
.any(|item| item.conflict_type == "taken_name")
|
||||
);
|
||||
assert!(first.preview.conflicts.iter().all(|item| {
|
||||
item.source_location
|
||||
.as_ref()
|
||||
.is_some_and(|location| location.pointer.starts_with("/paths/"))
|
||||
&& !item.proposed_name.is_empty()
|
||||
}));
|
||||
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn reopening_plan_is_read_only_and_reports_catalog_drift() {
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_plan_reopen_catalog"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
let plan_id = plan.plan_reference.as_str().into();
|
||||
let current = service
|
||||
.revalidate_openapi_import_plan(&workspace, &plan_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(current.revalidation_status, "current");
|
||||
assert!(!current.revalidation_required);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
service
|
||||
.create_operation(
|
||||
&workspace,
|
||||
test_operation_payload(&upstream, "unrelated_operation"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stale = service
|
||||
.revalidate_openapi_import_plan(&workspace, &plan_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stale.revalidation_status, "stale");
|
||||
assert!(stale.revalidation_required);
|
||||
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_full"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.preview.groups[0].operations[0].status, "actionable");
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(plan.plan_reference.starts_with("plan_"));
|
||||
assert!(
|
||||
plan.plan_digest.len() == 64
|
||||
&& plan
|
||||
.plan_digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit())
|
||||
);
|
||||
assert_eq!(plan.selection_mode, "full");
|
||||
assert_eq!(plan.counts.selected, 1);
|
||||
assert_eq!(plan.counts.excluded, 0);
|
||||
assert_eq!(plan.counts.actionable, 1);
|
||||
assert_eq!(plan.counts.blocked, 0);
|
||||
let candidate = &plan.candidates[0];
|
||||
assert_eq!(candidate.key, "GET /v2/latest");
|
||||
assert_eq!(candidate.name, "latest_rates");
|
||||
assert_eq!(candidate.state, "actionable");
|
||||
assert_eq!(candidate.action.as_deref(), Some("create"));
|
||||
assert_eq!(candidate.reason, None);
|
||||
|
||||
let expires_at = OffsetDateTime::parse(
|
||||
&plan.expires_at,
|
||||
&time::format_description::well_known::Rfc3339,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(expires_at > OffsetDateTime::now_utc());
|
||||
assert!(expires_at <= job.expires_at);
|
||||
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the created plan must be readable in its workspace");
|
||||
assert_eq!(stored.digest, plan.plan_digest);
|
||||
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
|
||||
assert_eq!(stored.payload["catalog_revision"], plan.catalog_revision);
|
||||
assert_eq!(stored.payload["support_matrix_version"], "1.0.3");
|
||||
assert!(stored.payload["findings"]["document"].is_array());
|
||||
assert!(stored.payload["findings"]["candidates"].is_array());
|
||||
assert_eq!(stored.expires_at, expires_at);
|
||||
assert_eq!(
|
||||
stored.payload["selection"]["selected"],
|
||||
json!(["GET /v2/latest"])
|
||||
);
|
||||
assert_eq!(stored.payload["selection"]["excluded"], json!([]));
|
||||
assert_eq!(stored.payload["counts"]["actionable"], json!(1));
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(candidate["decision"]["action"], "create");
|
||||
assert!(
|
||||
candidate["operation"]["id"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("op_")
|
||||
);
|
||||
assert_eq!(candidate["operation"]["status"], "draft");
|
||||
assert_eq!(
|
||||
stored.payload["source"]["digest"],
|
||||
job.preview_payload["source"]["digest"]
|
||||
);
|
||||
assert!(stored.payload["fingerprint"]["ir_fingerprint"].is_string());
|
||||
let repeated = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(repeated.plan_reference, plan.plan_reference);
|
||||
assert_eq!(repeated.plan_digest, plan.plan_digest);
|
||||
let repeated_stored = registry
|
||||
.get_import_plan(&workspace_id, &repeated.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_ne!(
|
||||
repeated_stored.payload["candidates"][0]["operation"]["id"],
|
||||
stored.payload["candidates"][0]["operation"]["id"]
|
||||
);
|
||||
// Planning is non-mutating: no operation exists and the job stays pending.
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(job.status, ImportJobStatus::Pending);
|
||||
assert_eq!(job.error_text, None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn partial_plan_counts_selection_and_rejects_invalid_request_material() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_partial"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_TWO_OPS))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let keys = preview_operation_keys(&preview);
|
||||
assert_eq!(keys.len(), 2);
|
||||
let (first, second) = (keys[0].clone(), keys[1].clone());
|
||||
let expected_display_name = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.find(|candidate| candidate.key == second)
|
||||
.expect("excluded candidate is in preview")
|
||||
.draft
|
||||
.name
|
||||
.clone();
|
||||
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload("partial", vec![first.clone()], vec![]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(plan.counts.selected, 1);
|
||||
assert_eq!(plan.counts.excluded, 1);
|
||||
assert_eq!(plan.counts.actionable, 1);
|
||||
assert_eq!(plan.counts.blocked, 0);
|
||||
let excluded = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == second)
|
||||
.expect("the excluded candidate is listed for confirmation");
|
||||
assert_eq!(excluded.state, "excluded");
|
||||
assert_eq!(excluded.name, expected_display_name);
|
||||
assert_eq!(excluded.reason.as_deref(), Some("not_selected"));
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["excluded_reasons"],
|
||||
json!([{
|
||||
"key": second,
|
||||
"name": expected_display_name,
|
||||
"reason": "not_selected",
|
||||
}])
|
||||
);
|
||||
|
||||
let plan_id: crank_registry::ImportPlanId = plan.plan_reference.as_str().into();
|
||||
let revalidated = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let revalidated_excluded = revalidated
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == second)
|
||||
.expect("excluded candidate remains visible during revalidation");
|
||||
assert_eq!(revalidated_excluded.name, expected_display_name);
|
||||
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let expected_all = json!([first, second]);
|
||||
assert_eq!(stored.payload["selection"]["all"], expected_all);
|
||||
// `excluded` candidates never receive a decision, target or draft material.
|
||||
let listed = stored.payload["candidates"].as_array().unwrap();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0]["key"], first);
|
||||
assert!(listed[0].get("target").is_none());
|
||||
|
||||
let cases: Vec<(OpenApiImportPlanCreatePayload, &'static str)> = vec![
|
||||
(
|
||||
plan_payload("full", vec![first.clone()], vec![]),
|
||||
"import_plan_selection_mismatch",
|
||||
),
|
||||
(
|
||||
plan_payload("partial", vec!["GET /unknown".to_owned()], vec![]),
|
||||
"import_plan_unknown_operation_key",
|
||||
),
|
||||
(
|
||||
plan_payload("partial", vec![], vec![]),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload("partial", vec![first.clone(), first.clone()], vec![]),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload("bogus", vec![first.clone()], vec![]),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone()],
|
||||
vec![decision("GET /other", "create", None, None, None)],
|
||||
),
|
||||
"import_plan_decision_unselected",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone(), second.clone()],
|
||||
vec![
|
||||
decision(&first, "create", None, None, None),
|
||||
decision(&first, "skip", Some("op_other"), None, None),
|
||||
],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone()],
|
||||
vec![decision(&first, "skip", None, None, None)],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone()],
|
||||
vec![decision(
|
||||
&first,
|
||||
"skip",
|
||||
Some("op_other"),
|
||||
Some("other_name"),
|
||||
None,
|
||||
)],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone(), second.clone()],
|
||||
vec![decision(
|
||||
&first,
|
||||
"skip",
|
||||
Some("op_other"),
|
||||
None,
|
||||
Some("auth_profile_any"),
|
||||
)],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone(), second.clone()],
|
||||
vec![
|
||||
decision(&first, "create", None, Some("renamed"), None),
|
||||
decision(&second, "rename", Some("op_other"), None, None),
|
||||
],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone()],
|
||||
vec![decision(&first, "rename", None, None, None)],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
(
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![first.clone()],
|
||||
vec![decision(&first, "new_version", None, None, None)],
|
||||
),
|
||||
"import_plan_invalid_input",
|
||||
),
|
||||
];
|
||||
for (payload, expected_code) in cases {
|
||||
let error = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, payload)
|
||||
.await
|
||||
.expect_err("invalid plan material must be rejected");
|
||||
assert_error_code(&error, expected_code);
|
||||
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
|
||||
}
|
||||
// The successful plan above still exists untouched.
|
||||
let readable = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(readable.is_some());
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn client_supplied_candidate_material_has_no_authority() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_client_authority"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
|
||||
// Client-supplied digests, payloads or candidate arrays are not part of
|
||||
// the request contract and must not influence the server-authored plan.
|
||||
let request = json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"plan_digest": format!("sha256:{}", "ab".repeat(32)),
|
||||
"plan_payload": {
|
||||
"schema_version": "import-plan-client-v999",
|
||||
"candidates": [{ "key": "GET /forged", "name": "forged" }],
|
||||
},
|
||||
"candidates": [{ "key": "GET /forged" }],
|
||||
});
|
||||
assert!(
|
||||
serde_json::from_value::<OpenApiImportPlanCreatePayload>(request).is_err(),
|
||||
"client-supplied candidate material must be rejected at the request boundary"
|
||||
);
|
||||
let payload: OpenApiImportPlanCreatePayload = serde_json::from_value(json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": []
|
||||
}))
|
||||
.unwrap();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, payload)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let material = stored.payload.to_string();
|
||||
assert!(!material.contains("import-plan-client-v999"));
|
||||
assert!(!material.contains("GET /forged"));
|
||||
assert!(!material.contains("abababab"));
|
||||
assert_eq!(
|
||||
stored.payload["selection"]["all"],
|
||||
json!(["GET /v2/latest"])
|
||||
);
|
||||
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
|
||||
assert!(stored.digest.len() == 64 && stored.digest.bytes().all(|b| b.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_creation_is_workspace_scoped() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_scope"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let primary = WorkspaceId::new("ws_default");
|
||||
let secondary = WorkspaceId::new("ws_plan_scope_secondary");
|
||||
let created_at = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: secondary.clone(),
|
||||
slug: "ws-plan-scope-secondary".to_owned(),
|
||||
display_name: "Plan scope secondary".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&primary, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&primary, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let cross_scope_error = service
|
||||
.create_openapi_import_plan(&secondary, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.expect_err("a foreign job must be invisible, not planned");
|
||||
assert_http_status(cross_scope_error, axum::http::StatusCode::NOT_FOUND);
|
||||
let stored = registry
|
||||
.get_import_plan(&secondary, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(stored.is_none(), "a foreign plan id must be invisible");
|
||||
let reopen_error = service
|
||||
.revalidate_openapi_import_plan(&secondary, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.expect_err("a foreign plan cannot be reopened");
|
||||
assert_http_status(reopen_error, axum::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn exact_skip_rename_and_new_version_decisions_are_saved_verbatim() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_decisions"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
// A conflicting existing operation so `create` is no longer safe by default.
|
||||
let existing = service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload(&upstream_base_url, "latest_rates"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let operation_id = existing.operation_id;
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"skip",
|
||||
Some(operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("skip must target the exact existing operation");
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(plan.counts.actionable, 1);
|
||||
assert_eq!(candidate["decision"]["action"], "skip");
|
||||
assert_eq!(candidate["target"]["operation_id"], json!(operation_id));
|
||||
assert_eq!(
|
||||
candidate["target"]["expected_state"],
|
||||
json!({
|
||||
"status": "draft",
|
||||
"current_draft_version": 1,
|
||||
"latest_published_version": null
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
candidate.get("operation").is_none(),
|
||||
"skip must not create draft material"
|
||||
);
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let renamed = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"rename",
|
||||
None,
|
||||
Some("latest_rates_confirmed"),
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &renamed.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["candidates"][0]["decision"]["confirmed_name"],
|
||||
"latest_rates_confirmed"
|
||||
);
|
||||
assert_eq!(
|
||||
stored.payload["candidates"][0]["operation"]["name"],
|
||||
"latest_rates_confirmed"
|
||||
);
|
||||
assert!(
|
||||
stored.payload["candidates"][0]["operation"]["id"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("op_")
|
||||
);
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let versioned = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &versioned.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(
|
||||
candidate["operation"]["id"], operation_id,
|
||||
"new_version snapshot must bind the exact target operation"
|
||||
);
|
||||
assert_eq!(candidate["operation"]["version"], 2);
|
||||
assert_eq!(
|
||||
candidate["target"]["expected_state"],
|
||||
json!({
|
||||
"status": "draft",
|
||||
"current_draft_version": 1,
|
||||
"latest_published_version": null
|
||||
})
|
||||
);
|
||||
|
||||
// Planning never mutates: only the original Draft Version exists.
|
||||
let operations = service.list_operations(&workspace_id).await.unwrap();
|
||||
assert_eq!(operations.len(), 1);
|
||||
assert_eq!(operations[0].name, "latest_rates");
|
||||
assert_eq!(operations[0].current_draft_version, 1);
|
||||
|
||||
// A mismatched target is rejected with the stable target code.
|
||||
let other = service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload(&upstream_base_url, "other_operation"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for mismatched in [
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"skip",
|
||||
Some(other.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(other.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
] {
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload("full", vec![], mismatched),
|
||||
)
|
||||
.await
|
||||
.expect_err("a mismatched target must be rejected");
|
||||
assert_error_code(&error, "import_plan_target_invalid");
|
||||
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
// An explicit `create` against a taken name conflicts; the server never
|
||||
// auto-selects a replacement name.
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision("GET /v2/latest", "create", None, None, None)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("create with a taken name must conflict");
|
||||
assert_error_code(&error, "import_plan_name_conflict");
|
||||
assert_http_status(error, axum::http::StatusCode::CONFLICT);
|
||||
|
||||
// Without an explicit decision the same collision stays a bounded,
|
||||
// redacted blocked candidate inside the immutable plan.
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(plan.counts.actionable, 0);
|
||||
assert_eq!(plan.counts.blocked, 1);
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(candidate["state"], "blocked");
|
||||
assert_eq!(candidate["reason"], "operation_name_conflict");
|
||||
assert!(candidate.get("operation").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn stale_or_terminal_jobs_preview_again_without_mutating_the_job() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_stale"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
|
||||
where id = $2",
|
||||
)
|
||||
.bind("0".repeat(64))
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.expect_err("a stale preview contract must be rejected");
|
||||
assert_error_code(&error, "import_replay_verification_failed");
|
||||
let context = public_error_context(&error).cloned().unwrap();
|
||||
assert_eq!(context["repreview_required"], json!(true));
|
||||
assert_eq!(
|
||||
context.get("recovery").and_then(Value::as_str),
|
||||
Some("repreview_required")
|
||||
);
|
||||
assert_http_status(error, axum::http::StatusCode::CONFLICT);
|
||||
|
||||
// Unlike the legacy path the job itself is untouched: other stored
|
||||
// plans anchored to it must remain readable.
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(job.status, ImportJobStatus::Pending);
|
||||
assert_eq!(job.error_text, None);
|
||||
assert!(job.finished_at.is_none());
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let completed_at = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.finish_import_job(FinishImportJobRequest {
|
||||
id: &job_id,
|
||||
status: ImportJobStatus::Failed,
|
||||
created_operation_ids: &json!([]),
|
||||
error_text: Some("test_finalized"),
|
||||
finished_at: &completed_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let error = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.expect_err("a terminal job cannot be planned");
|
||||
assert_error_code(&error, "import_plan_job_terminal");
|
||||
assert_http_status(error, axum::http::StatusCode::CONFLICT);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn public_plan_route_returns_bounded_confirmation_and_requires_a_session() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_plan_http");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let app = build_test_app(registry.clone(), storage_root);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.clone();
|
||||
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
|
||||
|
||||
// Without a session (and thus without a workspace owner context) the
|
||||
// public contract refuses and no plan is created.
|
||||
let anonymous = reqwest::Client::new();
|
||||
let denied = anonymous
|
||||
.post(&url)
|
||||
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(denied.status(), reqwest::StatusCode::UNAUTHORIZED);
|
||||
|
||||
let accepted = client
|
||||
.post(&url)
|
||||
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(accepted.status(), reqwest::StatusCode::OK);
|
||||
let body: Value = accepted.json().await.unwrap();
|
||||
let plan_reference = body["plan_reference"].as_str().unwrap_or_default();
|
||||
assert!(
|
||||
plan_reference.starts_with("plan_"),
|
||||
"plan reference must be server-issued: {body:?}"
|
||||
);
|
||||
let plan_digest = body["plan_digest"].as_str().unwrap_or_default();
|
||||
assert!(
|
||||
plan_digest.len() == 64 && plan_digest.bytes().all(|b| b.is_ascii_hexdigit()),
|
||||
"plan digest must be the registry-derived SHA-256: {body:?}"
|
||||
);
|
||||
assert_eq!(body["selection_mode"], "full");
|
||||
assert_eq!(
|
||||
body["counts"],
|
||||
json!({ "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 })
|
||||
);
|
||||
assert_eq!(body["candidates"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(body["candidates"][0]["key"], "GET /v2/latest");
|
||||
assert_eq!(body["candidates"][0]["state"], "actionable");
|
||||
assert_eq!(body["candidates"][0]["action"], "create");
|
||||
assert!(body["expires_at"].is_string());
|
||||
// The HTTP response is the bounded confirmation only: no draft snapshot,
|
||||
// no raw preview material, no secret material.
|
||||
assert!(body["candidates"][0].get("operation").is_none());
|
||||
assert!(!body.to_string().to_lowercase().contains("password"));
|
||||
|
||||
// The plan is readable in the same workspace right after the 200.
|
||||
let plan_id = crank_registry::ImportPlanId::new(plan_reference);
|
||||
let readable = registry
|
||||
.get_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the HTTP-created plan must be persisted");
|
||||
assert_eq!(readable.digest, plan_digest);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn partial_plan_applies_when_excluded_operation_name_exceeds_selected_name_limit() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_long_excluded_name"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let long_operation_id = "a".repeat(257);
|
||||
let document = format!(
|
||||
r#"openapi: 3.0.3
|
||||
info:
|
||||
title: Long excluded operation name
|
||||
version: "1"
|
||||
servers:
|
||||
- url: https://api.example.test
|
||||
paths:
|
||||
/selected:
|
||||
get:
|
||||
operationId: selectedMethod
|
||||
responses:
|
||||
"200":
|
||||
description: ok
|
||||
/excluded:
|
||||
get:
|
||||
operationId: {long_operation_id}
|
||||
responses:
|
||||
"200":
|
||||
description: ok
|
||||
"#
|
||||
);
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(&document))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let selected_key = "GET /selected";
|
||||
let excluded_key = "GET /excluded";
|
||||
let excluded_draft_name = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.find(|candidate| candidate.key == excluded_key)
|
||||
.expect("long-name method is present in preview")
|
||||
.draft
|
||||
.name
|
||||
.clone();
|
||||
assert_eq!(excluded_draft_name, long_operation_id);
|
||||
assert!(excluded_draft_name.len() > 256);
|
||||
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec![selected_key.to_owned()],
|
||||
vec![decision(selected_key, "create", None, None, None)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let created_excluded = plan
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == excluded_key)
|
||||
.expect("excluded method is returned by plan creation");
|
||||
assert_eq!(created_excluded.name, excluded_draft_name);
|
||||
assert_eq!(plan.counts.selected, 1);
|
||||
assert_eq!(plan.counts.excluded, 1);
|
||||
|
||||
let plan_id = crank_registry::ImportPlanId::new(plan.plan_reference.clone());
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("created plan is persisted");
|
||||
assert_eq!(
|
||||
stored.payload["excluded_reasons"][0]["name"],
|
||||
excluded_draft_name
|
||||
);
|
||||
|
||||
let revalidated = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let revalidated_excluded = revalidated
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == excluded_key)
|
||||
.expect("excluded method remains visible during revalidation");
|
||||
assert_eq!(revalidated_excluded.name, excluded_draft_name);
|
||||
|
||||
let report = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&plan_id,
|
||||
admin_api::service::OpenApiImportPlanApplyPayload {
|
||||
plan_digest: plan.plan_digest,
|
||||
idempotency_key: "long-excluded-name-apply".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("excluded descriptive metadata must not invalidate a partial plan");
|
||||
assert_eq!(
|
||||
report.status,
|
||||
crank_registry::ImportPlanApplyStatus::Applied
|
||||
);
|
||||
assert_eq!(report.counts.created, 1);
|
||||
assert_eq!(
|
||||
report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|outcome| outcome.key == selected_key)
|
||||
.expect("selected method appears in apply report")
|
||||
.outcome,
|
||||
crank_registry::ImportPlanCandidateOutcome::Created
|
||||
);
|
||||
let reported_excluded = report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|outcome| outcome.key == excluded_key)
|
||||
.expect("apply report includes the excluded method");
|
||||
assert_eq!(reported_excluded.name, excluded_draft_name);
|
||||
let operations = service.list_operations(&workspace_id).await.unwrap();
|
||||
assert_eq!(operations.len(), 1, "only the selected method is applied");
|
||||
assert_eq!(operations[0].status, crank_core::OperationStatus::Draft);
|
||||
assert_eq!(operations[0].current_draft_version, 1);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
use super::*;
|
||||
|
||||
/// Server-created plan reached through the public HTTP contract, so the locale
|
||||
/// tests exercise the real route handlers rather than the service methods.
|
||||
struct HttpPlan {
|
||||
plan_reference: String,
|
||||
plan_digest: String,
|
||||
}
|
||||
|
||||
async fn create_http_plan(client: &reqwest::Client, base_url: &str) -> HttpPlan {
|
||||
let upload_part = reqwest::multipart::Part::bytes(OPENAPI_SINGLE.as_bytes().to_vec())
|
||||
.file_name("import.yaml")
|
||||
.mime_str("application/yaml")
|
||||
.unwrap();
|
||||
let preview = client
|
||||
.post(format!("{base_url}/imports/openapi/preview"))
|
||||
.multipart(reqwest::multipart::Form::new().part("file", upload_part))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.status(), reqwest::StatusCode::OK);
|
||||
let preview: Value = preview.json().await.unwrap();
|
||||
let job_id = preview["job_id"].as_str().unwrap().to_owned();
|
||||
|
||||
let plan = client
|
||||
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
|
||||
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(plan.status(), reqwest::StatusCode::OK);
|
||||
let plan: Value = plan.json().await.unwrap();
|
||||
HttpPlan {
|
||||
plan_reference: plan["plan_reference"].as_str().unwrap().to_owned(),
|
||||
plan_digest: plan["plan_digest"].as_str().unwrap().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_create_localizes_repreview_guidance_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_plan_locale_create");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let app = build_test_app(registry.clone(), storage_root);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.clone();
|
||||
|
||||
// Corrupt the persisted preview contract so plan creation must ask for a
|
||||
// fresh preview.
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
|
||||
where id = $2",
|
||||
)
|
||||
.bind("0".repeat(64))
|
||||
.bind(&job_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
|
||||
|
||||
// Russian session: Russian recovery guidance, identical machine code and
|
||||
// recovery flags.
|
||||
let ru = client
|
||||
.post(&url)
|
||||
.header("accept-language", "ru-RU, ru;q=0.9")
|
||||
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
|
||||
let ru_body: Value = ru.json().await.unwrap();
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["error_code"],
|
||||
"import_replay_verification_failed"
|
||||
);
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["repreview_required"],
|
||||
json!(true)
|
||||
);
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["recovery"],
|
||||
"repreview_required"
|
||||
);
|
||||
assert!(
|
||||
ru_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("создайте новый preview"),
|
||||
"Russian session must receive Russian guidance: {ru_body:?}"
|
||||
);
|
||||
|
||||
// No locale header keeps the English default behavior.
|
||||
let en = client
|
||||
.post(&url)
|
||||
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
|
||||
let en_body: Value = en.json().await.unwrap();
|
||||
assert_eq!(
|
||||
en_body["error"]["context"]["error_code"],
|
||||
"import_replay_verification_failed"
|
||||
);
|
||||
assert!(
|
||||
en_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("create a fresh preview"),
|
||||
"EN default must remain English: {en_body:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_revalidate_accepts_locale_without_machine_drift() {
|
||||
let registry = test_registry().await;
|
||||
let app = build_test_app(
|
||||
registry,
|
||||
test_storage_root("openapi_import_plan_locale_revalidate"),
|
||||
);
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let plan = create_http_plan(&client, server.as_ref()).await;
|
||||
|
||||
let url = format!(
|
||||
"{}/imports/openapi/plans/{}",
|
||||
server.as_ref(),
|
||||
plan.plan_reference
|
||||
);
|
||||
let ru = client
|
||||
.get(&url)
|
||||
.header("accept-language", "ru")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::OK);
|
||||
let ru: Value = ru.json().await.unwrap();
|
||||
assert_eq!(ru["plan_digest"], plan.plan_digest);
|
||||
assert_eq!(ru["revalidation_status"], "current");
|
||||
assert_eq!(ru["revalidation_required"], false);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_create_localizes_expired_preview_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_plan_locale_expired");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let app = build_test_app(registry.clone(), storage_root);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.clone();
|
||||
|
||||
// Expire the preview job without corrupting its replay contract.
|
||||
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
|
||||
.bind(&job_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
|
||||
let body = json!({ "selection_mode": "full", "selected_operation_keys": [] });
|
||||
|
||||
let ru = client
|
||||
.post(&url)
|
||||
.header("accept-language", "ru")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
|
||||
let ru_body: Value = ru.json().await.unwrap();
|
||||
assert_eq!(ru_body["error"]["code"], "validation_error");
|
||||
assert!(
|
||||
ru_body["error"].get("context").is_none(),
|
||||
"expired-preview validation keeps no context: {ru_body:?}"
|
||||
);
|
||||
assert!(
|
||||
ru_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("истёк"),
|
||||
"Russian session must receive Russian guidance: {ru_body:?}"
|
||||
);
|
||||
|
||||
// No locale header keeps the English default behavior.
|
||||
let en = client.post(&url).json(&body).send().await.unwrap();
|
||||
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
|
||||
let en_body: Value = en.json().await.unwrap();
|
||||
assert_eq!(en_body["error"]["code"], "validation_error");
|
||||
assert!(en_body["error"].get("context").is_none());
|
||||
assert_eq!(en_body["error"]["message"], "import preview has expired");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_create_localizes_name_conflict_guidance_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_plan_locale_name_conflict");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let app = build_test_app(registry.clone(), storage_root);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
// Occupy the candidate's suggested name so an explicit `create` decision
|
||||
// conflicts.
|
||||
service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload("https://api.example.test", "latest_rates"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.clone();
|
||||
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
|
||||
let body = json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
"decisions": [{
|
||||
"operation_key": "GET /v2/latest",
|
||||
"action": "create",
|
||||
}]
|
||||
});
|
||||
|
||||
let ru = client
|
||||
.post(&url)
|
||||
.header("accept-language", "ru")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
|
||||
let ru_body: Value = ru.json().await.unwrap();
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["error_code"],
|
||||
"import_plan_name_conflict"
|
||||
);
|
||||
assert_eq!(
|
||||
ru_body["error"]["context"]["recovery"],
|
||||
"confirm_skip_rename_or_new_version"
|
||||
);
|
||||
assert!(
|
||||
ru_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("уже существует"),
|
||||
"Russian session must receive Russian guidance: {ru_body:?}"
|
||||
);
|
||||
|
||||
// No locale header keeps the exact English wording.
|
||||
let en = client.post(&url).json(&body).send().await.unwrap();
|
||||
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
|
||||
let en_body: Value = en.json().await.unwrap();
|
||||
assert_eq!(
|
||||
en_body["error"]["context"]["error_code"],
|
||||
"import_plan_name_conflict"
|
||||
);
|
||||
assert_eq!(
|
||||
en_body["error"]["message"],
|
||||
"operation with name latest_rates already exists"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn legacy_create_localizes_expired_preview_by_accept_language() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_legacy_create_locale_expired");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let app = build_test_app(registry.clone(), storage_root);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.clone();
|
||||
|
||||
// Expire the preview job so the legacy create route /imports/openapi/{id}/create
|
||||
// rejects before any selection work.
|
||||
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
|
||||
.bind(&job_id)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{}/imports/openapi/{}/create", server.as_ref(), job_id);
|
||||
let body = json!({ "selected_operation_keys": [] });
|
||||
|
||||
let ru = client
|
||||
.post(&url)
|
||||
.header("accept-language", "ru")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
|
||||
let ru_body: Value = ru.json().await.unwrap();
|
||||
assert_eq!(ru_body["error"]["code"], "validation_error");
|
||||
assert!(
|
||||
ru_body["error"].get("context").is_none(),
|
||||
"legacy expired-preview validation keeps no context: {ru_body:?}"
|
||||
);
|
||||
assert!(
|
||||
ru_body["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.contains("истёк"),
|
||||
"Russian session must receive Russian guidance: {ru_body:?}"
|
||||
);
|
||||
|
||||
// No locale header keeps the exact English wording.
|
||||
let en = client.post(&url).json(&body).send().await.unwrap();
|
||||
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
|
||||
let en_body: Value = en.json().await.unwrap();
|
||||
assert_eq!(en_body["error"]["code"], "validation_error");
|
||||
assert_eq!(en_body["error"]["message"], "import preview has expired");
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
use admin_api::{
|
||||
error::ApiError,
|
||||
service::{
|
||||
AuthProfilePayload, OpenApiImportPlanCreatePayload, OpenApiImportPlanDecision,
|
||||
OpenApiUpload, OpenApiUploadLocale, SecretPayload,
|
||||
},
|
||||
};
|
||||
use axum::response::IntoResponse;
|
||||
use crank_core::{
|
||||
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfileId, OperationId, SecretId, SecretKind,
|
||||
Workspace, WorkspaceId, WorkspaceStatus,
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateWorkspaceRequest, FinishImportJobRequest, ImportJobId, ImportJobStatus,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::super::common::*;
|
||||
const OPENAPI_SINGLE: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: Frankfurter API
|
||||
servers:
|
||||
- url: https://api.frankfurter.dev
|
||||
paths:
|
||||
/v2/latest:
|
||||
get:
|
||||
operationId: latestRates
|
||||
summary: Получить последние курсы валют
|
||||
tags: [currency]
|
||||
parameters:
|
||||
- name: base
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string }
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
base: { type: string }
|
||||
rates:
|
||||
type: object
|
||||
"#;
|
||||
|
||||
const OPENAPI_TWO_OPS: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Two Operations }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/alpha:
|
||||
get:
|
||||
operationId: alpha
|
||||
responses: { '200': { description: ok } }
|
||||
/beta:
|
||||
get:
|
||||
operationId: betaOp
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_GLOBAL_BLOCKER: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Global blocker }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/valid:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
/broken: not-a-path-item
|
||||
"#;
|
||||
|
||||
fn upload(document: &str) -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: document.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_operation_keys(
|
||||
preview: &admin_api::service::OpenApiImportPreviewResponse,
|
||||
) -> Vec<String> {
|
||||
let mut keys = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.map(|operation| operation.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort();
|
||||
keys
|
||||
}
|
||||
|
||||
fn decision(
|
||||
key: &str,
|
||||
action: &str,
|
||||
target: Option<&str>,
|
||||
name: Option<&str>,
|
||||
auth: Option<&str>,
|
||||
) -> OpenApiImportPlanDecision {
|
||||
OpenApiImportPlanDecision {
|
||||
operation_key: key.to_owned(),
|
||||
action: action.to_owned(),
|
||||
target_operation_id: target.map(ToOwned::to_owned),
|
||||
confirmed_name: name.map(ToOwned::to_owned),
|
||||
auth_profile_id: auth.map(ToOwned::to_owned),
|
||||
security_alternative_index: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn plan_payload(
|
||||
selection_mode: &str,
|
||||
selected: Vec<String>,
|
||||
decisions: Vec<OpenApiImportPlanDecision>,
|
||||
) -> OpenApiImportPlanCreatePayload {
|
||||
OpenApiImportPlanCreatePayload {
|
||||
selection_mode: selection_mode.to_owned(),
|
||||
selected_operation_keys: selected,
|
||||
server_url: None,
|
||||
decisions,
|
||||
}
|
||||
}
|
||||
|
||||
fn public_error_context(error: &ApiError) -> Option<&Value> {
|
||||
match error {
|
||||
ApiError::Unauthorized { context, .. }
|
||||
| ApiError::Forbidden { context, .. }
|
||||
| ApiError::Validation { context, .. }
|
||||
| ApiError::Unprocessable { context, .. }
|
||||
| ApiError::NotFound { context, .. }
|
||||
| ApiError::Conflict { context, .. }
|
||||
| ApiError::PayloadTooLarge { context, .. }
|
||||
| ApiError::PreconditionRequired { context, .. }
|
||||
| ApiError::RateLimited { context, .. }
|
||||
| ApiError::Internal { context, .. } => context.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_error_code(error: &ApiError, expected_code: &str) {
|
||||
assert_eq!(
|
||||
public_error_context(error)
|
||||
.and_then(|context| context.get("error_code"))
|
||||
.and_then(Value::as_str),
|
||||
Some(expected_code),
|
||||
"unexpected API error: {error:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Asserts the rendered HTTP status of a rejection without private accessors.
|
||||
fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
|
||||
assert_eq!(
|
||||
error.into_response().status(),
|
||||
expected,
|
||||
"the rendered status must match the public contract"
|
||||
);
|
||||
}
|
||||
|
||||
mod creation;
|
||||
mod excluded_names;
|
||||
mod locale;
|
||||
mod route_get;
|
||||
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
|
||||
mod security_availability;
|
||||
mod security_binding;
|
||||
mod validation;
|
||||
@@ -0,0 +1,87 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn persisted_plan_get_requires_owner_and_reports_catalog_drift() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_plan_get_route");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
let plan_id = plan.plan_reference.clone();
|
||||
let plan_digest = plan.plan_digest.clone();
|
||||
|
||||
let foreign_workspace = WorkspaceId::new("ws_plan_get_foreign");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: foreign_workspace.clone(),
|
||||
slug: "ws-plan-get-foreign".to_owned(),
|
||||
display_name: "Foreign plan workspace".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let server = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let url = format!("{server}/imports/openapi/plans/{plan_id}");
|
||||
let anonymous = reqwest::Client::new().get(&url).send().await.unwrap();
|
||||
assert_eq!(anonymous.status(), reqwest::StatusCode::UNAUTHORIZED);
|
||||
let foreign = client
|
||||
.get(url.replace("ws_default", foreign_workspace.as_str()))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(foreign.status(), reqwest::StatusCode::FORBIDDEN);
|
||||
|
||||
let current = client.get(&url).send().await.unwrap();
|
||||
assert_eq!(current.status(), reqwest::StatusCode::OK);
|
||||
let current: Value = current.json().await.unwrap();
|
||||
assert_eq!(current["plan_reference"], plan_id);
|
||||
assert_eq!(current["plan_digest"], plan_digest);
|
||||
assert_eq!(current["revalidation_status"], "current");
|
||||
assert_eq!(current["revalidation_required"], false);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let upstream = spawn_upstream_server().await;
|
||||
service
|
||||
.create_operation(
|
||||
&workspace,
|
||||
test_operation_payload(&upstream, "plan_get_catalog_drift"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stale = client.get(&url).send().await.unwrap();
|
||||
assert_eq!(stale.status(), reqwest::StatusCode::OK);
|
||||
let stale: Value = stale.json().await.unwrap();
|
||||
assert_eq!(stale["plan_reference"], plan_id);
|
||||
assert_eq!(stale["plan_digest"], plan_digest);
|
||||
assert_eq!(stale["revalidation_status"], "stale");
|
||||
assert_eq!(stale["revalidation_required"], true);
|
||||
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
use super::*;
|
||||
|
||||
const OPENAPI_SECURITY_BINDING: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Security binding availability, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
Key: { type: apiKey, in: header, name: X-Api-Key }
|
||||
Bearer: { type: http, scheme: bearer }
|
||||
paths:
|
||||
/v2/latest:
|
||||
get:
|
||||
operationId: latestRates
|
||||
security: [{ Key: [] }, { Bearer: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
fn security_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: OPENAPI_SECURITY_BINDING.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn binding_decision(auth_profile_id: &str) -> OpenApiImportPlanDecision {
|
||||
let mut binding = decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(auth_profile_id),
|
||||
);
|
||||
binding.security_alternative_index = Some(0);
|
||||
binding
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn security_binding_refuses_foreign_and_unavailable_auth_material_before_draft() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_plan_security_availability"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let primary = WorkspaceId::new("ws_default");
|
||||
let foreign = WorkspaceId::new("ws_security_foreign");
|
||||
let created_at = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: foreign.clone(),
|
||||
slug: "ws-security-foreign".to_owned(),
|
||||
display_name: "Foreign security workspace".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let foreign_canary = "foreign-security-profile-canary";
|
||||
let foreign_secret = service
|
||||
.create_secret(
|
||||
&foreign,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "foreign-security-secret".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": foreign_canary }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_profile = service
|
||||
.create_auth_profile(
|
||||
&foreign,
|
||||
AuthProfilePayload {
|
||||
name: "foreign-security-profile-name".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: SecretId::new(foreign_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A foreign profile is absent from the current workspace's advertised
|
||||
// choices and submission fails with a generic workspace-safe error.
|
||||
let preview = service
|
||||
.preview_openapi_import(&primary, security_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let preview_text = serde_json::to_string(&preview).unwrap();
|
||||
for private_value in [
|
||||
foreign_profile.id.as_str(),
|
||||
foreign_profile.name.as_str(),
|
||||
foreign_secret.id.as_str(),
|
||||
foreign_canary,
|
||||
] {
|
||||
assert!(
|
||||
!preview_text.contains(private_value),
|
||||
"foreign profile metadata appeared in preview choices"
|
||||
);
|
||||
}
|
||||
assert!(preview.security_profile_choices.iter().all(|choice| {
|
||||
choice
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|profile| profile.id != foreign_profile.id.as_str())
|
||||
}));
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let foreign_error = service
|
||||
.create_openapi_import_plan(
|
||||
&primary,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![binding_decision(foreign_profile.id.as_str())],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("a profile from another workspace must not bind");
|
||||
assert_error_code(&foreign_error, "import_plan_auth_unavailable");
|
||||
let foreign_error_text = format!("{foreign_error:?}");
|
||||
assert_http_status(foreign_error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||
for private_value in [
|
||||
foreign_profile.id.as_str(),
|
||||
foreign_profile.name.as_str(),
|
||||
foreign_secret.id.as_str(),
|
||||
foreign_canary,
|
||||
] {
|
||||
assert!(
|
||||
!foreign_error_text.contains(private_value),
|
||||
"foreign profile or secret metadata leaked: {foreign_error_text}"
|
||||
);
|
||||
}
|
||||
|
||||
// A previously valid local profile whose Secret is disabled is removed
|
||||
// from choices and cannot be used in a newly confirmed ImportPlan.
|
||||
let disabled_canary = "disabled-security-secret-canary";
|
||||
let disabled_secret = service
|
||||
.create_secret(
|
||||
&primary,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "disabled-security-secret".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": disabled_canary }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let disabled_profile = service
|
||||
.create_auth_profile(
|
||||
&primary,
|
||||
AuthProfilePayload {
|
||||
name: "disabled-security-profile".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: SecretId::new(disabled_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(primary.as_str())
|
||||
.bind(disabled_secret.id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let preview = service
|
||||
.preview_openapi_import(&primary, security_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(preview.security_profile_choices.iter().all(|choice| {
|
||||
choice
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|profile| profile.id != disabled_profile.id.as_str())
|
||||
}));
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let disabled_error = service
|
||||
.create_openapi_import_plan(
|
||||
&primary,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![binding_decision(disabled_profile.id.as_str())],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("a disabled linked Secret must reject the profile binding");
|
||||
assert_error_code(&disabled_error, "secret_not_active");
|
||||
let disabled_error_text = format!("{disabled_error:?}");
|
||||
assert!(!disabled_error_text.contains(disabled_canary));
|
||||
|
||||
// A profile whose active Secret has no stored current version is equally
|
||||
// unavailable. Direct SQL models the broken persisted reference while
|
||||
// retaining the real Admin preview and plan validation paths.
|
||||
let missing_version_canary = "missing-version-security-canary";
|
||||
let missing_version_secret = service
|
||||
.create_secret(
|
||||
&primary,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "missing-version-security-secret".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": missing_version_canary }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let missing_version_profile = service
|
||||
.create_auth_profile(
|
||||
&primary,
|
||||
AuthProfilePayload {
|
||||
name: "missing-version-security-profile".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: SecretId::new(missing_version_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("delete from secret_versions where secret_id = $1 and version = 1")
|
||||
.bind(missing_version_secret.id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let preview = service
|
||||
.preview_openapi_import(&primary, security_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(preview.security_profile_choices.iter().all(|choice| {
|
||||
choice
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|profile| profile.id != missing_version_profile.id.as_str())
|
||||
}));
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let missing_version_error = service
|
||||
.create_openapi_import_plan(
|
||||
&primary,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![binding_decision(missing_version_profile.id.as_str())],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("a Secret without a current version must reject the profile binding");
|
||||
assert_error_code(&missing_version_error, "operation_auth_profile_invalid");
|
||||
let missing_version_error_text = format!("{missing_version_error:?}");
|
||||
for private_value in [
|
||||
missing_version_profile.id.as_str(),
|
||||
missing_version_profile.name.as_str(),
|
||||
missing_version_secret.id.as_str(),
|
||||
missing_version_canary,
|
||||
] {
|
||||
assert!(
|
||||
!missing_version_error_text.contains(private_value),
|
||||
"missing-version Secret metadata leaked: {missing_version_error_text}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
service.list_operations(&primary).await.unwrap().is_empty(),
|
||||
"no unavailable profile binding may create a Draft"
|
||||
);
|
||||
}
|
||||
+770
@@ -0,0 +1,770 @@
|
||||
use super::*;
|
||||
|
||||
const OPENAPI_SINGLE_PUBLIC: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Public import, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/v2/latest:
|
||||
get:
|
||||
operationId: latestRates
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_SINGLE_EXPLICIT_NO_AUTH: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Explicit no auth import, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/v2/latest:
|
||||
get:
|
||||
operationId: latestRates
|
||||
security: []
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
const OPENAPI_BASIC_AND_QUERY_SECURITY: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Basic and query import, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
Basic: { type: http, scheme: basic }
|
||||
QueryKey: { type: apiKey, in: query, name: access_token }
|
||||
paths:
|
||||
/v2/basic:
|
||||
get:
|
||||
operationId: basicRates
|
||||
security: [{ Basic: [] }, { QueryKey: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
/v2/query:
|
||||
get:
|
||||
operationId: queryRates
|
||||
security: [{ Basic: [] }, { QueryKey: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn auth_profile_references_are_validated_stored_and_inherited() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_auth"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let secret_token = "plan-secret-canary-2-13";
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "plan-auth-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": secret_token }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "plan-auth-profile".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: SecretId::new(secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let bearer_secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "plan-bearer-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": "bearer-choice-canary" }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let bearer_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "plan-bearer-profile".to_owned(),
|
||||
kind: AuthKind::Bearer,
|
||||
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id: SecretId::new(bearer_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.preview.groups[0].operations[0].status, "unresolved");
|
||||
let selectable = preview
|
||||
.security_profile_choices
|
||||
.iter()
|
||||
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 0)
|
||||
.expect("preview must expose choices for supported security alternatives");
|
||||
assert!(selectable.profiles.iter().any(|choice| {
|
||||
choice.id == auth_profile.id.as_str() && choice.kind == AuthKind::ApiKeyHeader
|
||||
}));
|
||||
assert!(
|
||||
selectable
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| { choice.id != bearer_profile.id.as_str() })
|
||||
);
|
||||
let bearer_choice = preview
|
||||
.security_profile_choices
|
||||
.iter()
|
||||
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 1)
|
||||
.expect("preview must expose profile choices for the second OR alternative");
|
||||
assert!(bearer_choice.profiles.iter().any(|choice| {
|
||||
choice.id == bearer_profile.id.as_str() && choice.kind == AuthKind::Bearer
|
||||
}));
|
||||
assert!(
|
||||
bearer_choice
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| { choice.id != auth_profile.id.as_str() })
|
||||
);
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let mut auth_decision = decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(auth_profile.id.as_str()),
|
||||
);
|
||||
auth_decision.security_alternative_index = Some(0);
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload("full", vec![], vec![auth_decision]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
|
||||
auth_profile.id.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
stored.payload["candidates"][0]["decision"]["security_alternative_index"],
|
||||
0
|
||||
);
|
||||
// Only the reference survives: no secret material anywhere in the plan.
|
||||
assert!(!stored.payload.to_string().contains(secret_token));
|
||||
assert_eq!(
|
||||
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
|
||||
Some(auth_profile.id.as_str())
|
||||
);
|
||||
|
||||
let mut bearer_decision = decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(bearer_profile.id.as_str()),
|
||||
);
|
||||
bearer_decision.security_alternative_index = Some(1);
|
||||
let bearer_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload("full", vec![], vec![bearer_decision]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored_bearer = registry
|
||||
.get_import_plan(&workspace_id, &bearer_plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored_bearer.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
|
||||
bearer_profile.id.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
stored_bearer.payload["candidates"][0]["decision"]["security_alternative_index"],
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
!stored_bearer
|
||||
.payload
|
||||
.to_string()
|
||||
.contains("bearer-choice-canary")
|
||||
);
|
||||
|
||||
// An unknown profile reference fails closed in the workspace scope check.
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some("auth_missing_profile"),
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("an unknown auth profile reference must be rejected");
|
||||
assert_error_code(&error, "import_plan_auth_unavailable");
|
||||
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||
|
||||
// `new_version` without an explicit choice inherits the target's ref.
|
||||
let existing = service
|
||||
.create_operation(&workspace_id, {
|
||||
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
|
||||
payload.execution_config.auth_profile_ref =
|
||||
Some(AuthProfileId::new(auth_profile.id.as_str()));
|
||||
payload
|
||||
})
|
||||
.await
|
||||
.expect("an existing operation with the candidate name");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(
|
||||
candidate["decision"]["auth_profile_id"],
|
||||
auth_profile.id.as_str(),
|
||||
"the inherited target reference is reflected in the candidate summary"
|
||||
);
|
||||
assert_eq!(
|
||||
candidate["operation"]["execution_config"]["auth_profile_ref"],
|
||||
auth_profile.id.as_str(),
|
||||
"the inherited target reference must be retained in the snapshot"
|
||||
);
|
||||
assert!(!stored.payload.to_string().contains(secret_token));
|
||||
|
||||
let public_preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_PUBLIC))
|
||||
.await
|
||||
.unwrap();
|
||||
let public_job_id: ImportJobId = public_preview.job_id.as_str().into();
|
||||
let public_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&public_job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a no-security source may inherit the target's existing profile");
|
||||
let public_stored = registry
|
||||
.get_import_plan(&workspace_id, &public_plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
public_stored.payload["candidates"][0]["auth_requirement"]["kind"], "unconstrained",
|
||||
"no source security declaration is represented explicitly for transactional Apply"
|
||||
);
|
||||
let report = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&crank_registry::ImportPlanId::new(public_plan.plan_reference.clone()),
|
||||
admin_api::service::OpenApiImportPlanApplyPayload {
|
||||
plan_digest: public_plan.plan_digest.clone(),
|
||||
idempotency_key: "new-version-inherited-public".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("Apply must retain profile and Secret transactional validation");
|
||||
assert_eq!(
|
||||
report.status,
|
||||
crank_registry::ImportPlanApplyStatus::Applied
|
||||
);
|
||||
assert_eq!(
|
||||
report.outcomes[0].outcome,
|
||||
crank_registry::ImportPlanCandidateOutcome::Versioned
|
||||
);
|
||||
assert_eq!(report.outcomes[0].version, Some(2));
|
||||
let operation = service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|operation| operation.id == existing.operation_id.as_str())
|
||||
.unwrap();
|
||||
assert_eq!(operation.current_draft_version, 2);
|
||||
|
||||
let explicit_no_auth_preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_EXPLICIT_NO_AUTH))
|
||||
.await
|
||||
.unwrap();
|
||||
let explicit_no_auth_job_id: ImportJobId = explicit_no_auth_preview.job_id.as_str().into();
|
||||
let incompatible_profile_decision = decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
Some(auth_profile.id.as_str()),
|
||||
);
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&explicit_no_auth_job_id,
|
||||
plan_payload("full", vec![], vec![incompatible_profile_decision]),
|
||||
)
|
||||
.await
|
||||
.expect_err("explicit Auth Profile stays incompatible with security: []");
|
||||
assert_error_code(&error, "import_plan_auth_incompatible");
|
||||
|
||||
let explicit_no_auth_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&explicit_no_auth_job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("an explicit empty security requirement clears inherited auth");
|
||||
let no_auth_stored = registry
|
||||
.get_import_plan(
|
||||
&workspace_id,
|
||||
&explicit_no_auth_plan.plan_reference.as_str().into(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(no_auth_stored.payload["candidates"][0]["operation"]["execution_config"]
|
||||
["auth_profile_ref"]
|
||||
.is_null());
|
||||
let no_auth_report = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&crank_registry::ImportPlanId::new(explicit_no_auth_plan.plan_reference.clone()),
|
||||
admin_api::service::OpenApiImportPlanApplyPayload {
|
||||
plan_digest: explicit_no_auth_plan.plan_digest.clone(),
|
||||
idempotency_key: "new-version-explicit-no-auth".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("explicit no-auth new_version applies without inherited credentials");
|
||||
assert_eq!(
|
||||
no_auth_report.outcomes[0].outcome,
|
||||
crank_registry::ImportPlanCandidateOutcome::Versioned
|
||||
);
|
||||
assert_eq!(no_auth_report.outcomes[0].version, Some(3));
|
||||
let operation = service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|operation| operation.id == existing.operation_id.as_str())
|
||||
.unwrap();
|
||||
assert_eq!(operation.current_draft_version, 3);
|
||||
let operation_id = OperationId::new(existing.operation_id.clone());
|
||||
let version = registry
|
||||
.get_operation_version(&workspace_id, &operation_id, 3)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(version.snapshot.execution_config.auth_profile_ref.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_apply() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_basic_query_auth"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let username_secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "basic-username".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": "plan-user" }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let password_secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "basic-password".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": "plan-password-canary" }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let basic_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "basic-profile".to_owned(),
|
||||
kind: AuthKind::Basic,
|
||||
config: AuthConfig::Basic(crank_core::BasicAuthConfig {
|
||||
username_secret_id: SecretId::new(username_secret.id.as_str()),
|
||||
password_secret_id: SecretId::new(password_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let query_secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "query-key".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": "query-key-canary" }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let query_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "query-profile".to_owned(),
|
||||
kind: AuthKind::ApiKeyQuery,
|
||||
config: AuthConfig::ApiKeyQuery(crank_core::ApiKeyQueryAuthConfig {
|
||||
param_name: "access_token".to_owned(),
|
||||
secret_id: SecretId::new(query_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let incompatible_secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "incompatible-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": "incompatible-canary" }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let incompatible_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "incompatible-bearer-profile".to_owned(),
|
||||
kind: AuthKind::Bearer,
|
||||
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id: SecretId::new(incompatible_secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
|
||||
.await
|
||||
.unwrap();
|
||||
for operation_key in ["GET /v2/basic", "GET /v2/query"] {
|
||||
let basic_alternative = preview
|
||||
.security_profile_choices
|
||||
.iter()
|
||||
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 0)
|
||||
.expect("Basic alternative must be represented in preview");
|
||||
assert!(basic_alternative.profiles.iter().any(|choice| {
|
||||
choice.id == basic_profile.id.as_str() && choice.kind == AuthKind::Basic
|
||||
}));
|
||||
assert!(
|
||||
basic_alternative
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| choice.id != query_profile.id.as_str())
|
||||
);
|
||||
assert!(
|
||||
basic_alternative
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| choice.id != incompatible_profile.id.as_str())
|
||||
);
|
||||
|
||||
let query_alternative = preview
|
||||
.security_profile_choices
|
||||
.iter()
|
||||
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 1)
|
||||
.expect("query alternative must be represented in preview");
|
||||
assert!(query_alternative.profiles.iter().any(|choice| {
|
||||
choice.id == query_profile.id.as_str() && choice.kind == AuthKind::ApiKeyQuery
|
||||
}));
|
||||
assert!(
|
||||
query_alternative
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| choice.id != basic_profile.id.as_str())
|
||||
);
|
||||
assert!(
|
||||
query_alternative
|
||||
.profiles
|
||||
.iter()
|
||||
.all(|choice| choice.id != incompatible_profile.id.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let mut basic_decision = decision(
|
||||
"GET /v2/basic",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(basic_profile.id.as_str()),
|
||||
);
|
||||
basic_decision.security_alternative_index = Some(0);
|
||||
let basic_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec!["GET /v2/basic".to_owned()],
|
||||
vec![basic_decision],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(basic_plan.counts.actionable, 1);
|
||||
let basic_candidate = basic_plan
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == "GET /v2/basic")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
basic_candidate.auth_profile_id.as_deref(),
|
||||
Some(basic_profile.id.as_str())
|
||||
);
|
||||
|
||||
let mut query_decision = decision(
|
||||
"GET /v2/query",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(query_profile.id.as_str()),
|
||||
);
|
||||
query_decision.security_alternative_index = Some(1);
|
||||
let query_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec!["GET /v2/query".to_owned()],
|
||||
vec![query_decision.clone()],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(query_plan.counts.actionable, 1);
|
||||
let query_candidate = query_plan
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.key == "GET /v2/query")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
query_candidate.auth_profile_id.as_deref(),
|
||||
Some(query_profile.id.as_str())
|
||||
);
|
||||
|
||||
for (index, (plan, expected_profile, idempotency_key)) in [
|
||||
(
|
||||
&basic_plan,
|
||||
basic_profile.id.as_str(),
|
||||
"apply-basic-profile",
|
||||
),
|
||||
(
|
||||
&query_plan,
|
||||
query_profile.id.as_str(),
|
||||
"apply-query-profile",
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let fresh_plan;
|
||||
let plan = if index == 1 {
|
||||
let stale = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
|
||||
admin_api::service::OpenApiImportPlanApplyPayload {
|
||||
plan_digest: plan.plan_digest.clone(),
|
||||
idempotency_key: "stale-query-profile".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("the earlier query plan is stale after catalog mutation");
|
||||
assert_error_code(&stale, "import_plan_fingerprint_stale");
|
||||
let refreshed = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
|
||||
.await
|
||||
.unwrap();
|
||||
fresh_plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&refreshed.job_id.as_str().into(),
|
||||
plan_payload(
|
||||
"partial",
|
||||
vec!["GET /v2/query".to_owned()],
|
||||
vec![query_decision.clone()],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
&fresh_plan
|
||||
} else {
|
||||
plan
|
||||
};
|
||||
let report = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
|
||||
admin_api::service::OpenApiImportPlanApplyPayload {
|
||||
plan_digest: plan.plan_digest.clone(),
|
||||
idempotency_key: idempotency_key.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
report.status,
|
||||
crank_registry::ImportPlanApplyStatus::Applied
|
||||
);
|
||||
let operation_id = OperationId::new(report.outcomes[0].operation_id.clone().unwrap());
|
||||
let version = registry
|
||||
.get_operation_version(&workspace_id, &operation_id, 1)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
version
|
||||
.snapshot
|
||||
.execution_config
|
||||
.auth_profile_ref
|
||||
.as_ref()
|
||||
.map(|profile_id| profile_id.as_str()),
|
||||
Some(expected_profile)
|
||||
);
|
||||
}
|
||||
let basic_stored = registry
|
||||
.get_import_plan(&workspace_id, &basic_plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!basic_stored
|
||||
.payload
|
||||
.to_string()
|
||||
.contains("plan-password-canary")
|
||||
);
|
||||
let query_stored = registry
|
||||
.get_import_plan(&workspace_id, &query_plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!query_stored
|
||||
.payload
|
||||
.to_string()
|
||||
.contains("query-key-canary")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn preview_rejects_candidate_2001_without_truncation_or_operations() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_preview_candidate_limit"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace = WorkspaceId::new("ws_default");
|
||||
let mut document = String::from(
|
||||
"openapi: 3.0.3\ninfo: { title: Limit }\nservers: [{ url: https://api.example.test }]\npaths:\n",
|
||||
);
|
||||
for index in 0..2001 {
|
||||
document.push_str(&format!(" /p{index}:\n get:\n operationId: op{index}\n responses: {{ '200': {{ description: ok }} }}\n"));
|
||||
}
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace, upload(&document))
|
||||
.await
|
||||
.expect_err("candidate 2001 must be rejected as a whole");
|
||||
assert_error_code(&error, "openapi_preview_too_many_candidates");
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
|
||||
)
|
||||
.bind(workspace.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn partial_plan_rejects_selected_blocker_before_persistence() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_partial_blocker"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.preview.groups[0].operations[0].status, "blocked");
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let key = preview.preview.groups[0].operations[0].key.clone();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload("partial", vec![key], vec![]),
|
||||
)
|
||||
.await
|
||||
.expect_err("blocked partial selection must be rejected");
|
||||
assert_error_code(&error, "import_plan_partial_blocked");
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn explicit_targets_are_checked_even_when_the_candidate_is_blocked() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_blocked_target"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
|
||||
.await
|
||||
.unwrap();
|
||||
let blocker_code = preview
|
||||
.preview
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.severity == crank_import::rest::ImportFindingSeverity::Error)
|
||||
.map(|finding| finding.code.clone())
|
||||
.expect("the fixture produces a global error finding");
|
||||
let candidate = &preview.preview.groups[0].operations[0];
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
|
||||
// A mismatched/unknown explicit target is a request error even though
|
||||
// the candidate is already blocked by the preview.
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
&candidate.key,
|
||||
"skip",
|
||||
Some("op_does_not_exist"),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("an unknown target is a request error even for a blocked candidate");
|
||||
assert_error_code(&error, "import_plan_target_invalid");
|
||||
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
|
||||
|
||||
// A resolvable exact target is recorded while the candidate stays
|
||||
// blocked with its bounded redacted reason.
|
||||
let existing = service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload(&upstream_base_url, &candidate.draft.name),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
&candidate.key,
|
||||
"skip",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a valid explicit target is accepted for a blocked candidate");
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(candidate["state"], "blocked");
|
||||
assert_eq!(candidate["reason"], blocker_code);
|
||||
assert_eq!(
|
||||
candidate["target"]["operation_id"],
|
||||
json!(existing.operation_id)
|
||||
);
|
||||
assert!(
|
||||
candidate.get("operation").is_none(),
|
||||
"a blocked candidate never stores draft material"
|
||||
);
|
||||
assert!(service.list_operations(&workspace_id).await.unwrap().len() <= 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn archived_rest_target_cannot_be_planned_for_new_version() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_archived_target"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let existing = service
|
||||
.create_operation(
|
||||
&workspace_id,
|
||||
test_operation_payload(&upstream_base_url, "latest_rates"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.archive_operation(
|
||||
&workspace_id,
|
||||
&OperationId::new(existing.operation_id.clone()),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("archived target cannot accept a new Draft Version");
|
||||
assert_error_code(&error, "import_plan_target_invalid");
|
||||
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn detached_dependency_snapshot_repreview_requires_without_a_plan() {
|
||||
let app = axum::Router::new().route(
|
||||
"/schema.yaml",
|
||||
axum::routing::get(|| async {
|
||||
"Result: { type: object, properties: { id: { type: string } } }"
|
||||
}),
|
||||
);
|
||||
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_plan_dependency_stale"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: External dependency }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: {{ $ref: '{origin}/schema.yaml#/Result' }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let dependency_sources = job.preview_payload["dependencies"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!dependency_sources.is_empty(),
|
||||
"fixture must create a dependency"
|
||||
);
|
||||
|
||||
// The plan is creatable while the stored snapshot is still active.
|
||||
let fresh = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.expect("an active dependency snapshot must not block planning");
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan(&workspace_id, &fresh.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.payload["dependencies"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
dependency_sources.len()
|
||||
);
|
||||
|
||||
// Detach one stored snapshot: the same job now requires re-preview and
|
||||
// no plan is created; the legacy job itself stays untouched.
|
||||
let victim = &dependency_sources[0];
|
||||
sqlx::query(
|
||||
"update artifact_sources
|
||||
set lifecycle = 'detached', updated_at = now(), detached_at = now()
|
||||
where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(victim["source_id"].as_str().unwrap())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let error = service
|
||||
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
|
||||
.await
|
||||
.expect_err("a detached dependency snapshot is re-preview material");
|
||||
assert_error_code(&error, "import_dependency_verification_failed");
|
||||
let context = public_error_context(&error).cloned().unwrap();
|
||||
assert_eq!(context["repreview_required"], json!(true));
|
||||
assert_http_status(error, axum::http::StatusCode::CONFLICT);
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(job.status, ImportJobStatus::Pending);
|
||||
assert_eq!(job.error_text, None);
|
||||
assert!(job.finished_at.is_none());
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::*;
|
||||
|
||||
use admin_api::service::OpenApiImportPlanCreatePayload;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
const OPERATION_COUNT: usize = 2_000;
|
||||
const MAX_UPLOAD_BYTES: usize = 256 * 1024;
|
||||
const MAX_STORED_PLAN_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
fn large_openapi_document() -> String {
|
||||
let mut document = String::from(
|
||||
"openapi: 3.0.3\n\
|
||||
info: { title: Large preview, version: '1' }\n\
|
||||
servers: [{ url: 'https://api.example.test' }]\n\
|
||||
paths:\n",
|
||||
);
|
||||
for index in 0..OPERATION_COUNT {
|
||||
writeln!(
|
||||
document,
|
||||
" /p{index:04}:\n get:\n operationId: o{index:04}\n responses: {{ '200': {{ description: ok }} }}"
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
document
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn previews_and_plans_two_thousand_operations_without_catalog_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_large_preview"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let document = large_openapi_document();
|
||||
assert!(
|
||||
document.len() <= MAX_UPLOAD_BYTES,
|
||||
"generated document is {} bytes, over the 256 KiB upload limit",
|
||||
document.len()
|
||||
);
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: document.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("valid 2,000-operation OpenAPI document should preview");
|
||||
let preview_candidates = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(preview_candidates.len(), OPERATION_COUNT);
|
||||
assert_eq!(preview_candidates[0].key, "GET /p0000");
|
||||
assert_eq!(preview_candidates[OPERATION_COUNT - 1].key, "GET /p1999");
|
||||
assert!(preview_candidates.iter().all(|candidate| {
|
||||
candidate.status == "actionable"
|
||||
&& candidate.method == crank_core::HttpMethod::Get
|
||||
&& candidate.path.starts_with("/p")
|
||||
}));
|
||||
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportPlanCreatePayload {
|
||||
selection_mode: "full".to_owned(),
|
||||
selected_operation_keys: Vec::new(),
|
||||
server_url: None,
|
||||
decisions: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("full plan should include all 2,000 operations");
|
||||
assert_eq!(plan.counts.selected, OPERATION_COUNT);
|
||||
assert_eq!(plan.counts.actionable, OPERATION_COUNT);
|
||||
assert_eq!(plan.counts.excluded, 0);
|
||||
assert_eq!(plan.counts.blocked, 0);
|
||||
assert_eq!(plan.candidates.len(), OPERATION_COUNT);
|
||||
assert!(plan.candidates.iter().all(|candidate| {
|
||||
candidate.state == "actionable" && candidate.action.as_deref() == Some("create")
|
||||
}));
|
||||
|
||||
let plan_id = plan.plan_reference.as_str().into();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("full plan should be persisted and readable");
|
||||
let stored_payload_bytes = serde_json::to_vec(&stored.payload).unwrap().len();
|
||||
assert!(
|
||||
stored_payload_bytes <= MAX_STORED_PLAN_BYTES,
|
||||
"stored plan payload is {stored_payload_bytes} bytes, over 16 MiB"
|
||||
);
|
||||
let stored_candidates = stored.payload["candidates"]
|
||||
.as_array()
|
||||
.expect("stored plan contains its full candidate list");
|
||||
assert_eq!(stored_candidates.len(), OPERATION_COUNT);
|
||||
assert!(stored_candidates.iter().all(|candidate| {
|
||||
candidate["state"] == "actionable" && candidate["decision"]["action"] == "create"
|
||||
}));
|
||||
assert_eq!(stored.payload["counts"]["selected"], OPERATION_COUNT);
|
||||
assert_eq!(stored.payload["counts"]["actionable"], OPERATION_COUNT);
|
||||
|
||||
let revalidated = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
|
||||
.await
|
||||
.expect("revalidating the unchanged plan should be read-only and current");
|
||||
assert_eq!(revalidated.revalidation_status, "current");
|
||||
assert!(!revalidated.revalidation_required);
|
||||
assert_eq!(revalidated.counts.selected, OPERATION_COUNT);
|
||||
assert_eq!(revalidated.counts.actionable, OPERATION_COUNT);
|
||||
assert_eq!(revalidated.counts.excluded, 0);
|
||||
assert_eq!(revalidated.counts.blocked, 0);
|
||||
assert_eq!(revalidated.candidates.len(), OPERATION_COUNT);
|
||||
|
||||
let (operations, operation_versions) = sqlx::query_as::<_, (i64, i64)>(
|
||||
"select
|
||||
(select count(*) from operations where workspace_id = $1),
|
||||
(select count(*) from operation_versions ov
|
||||
join operations o on o.id = ov.operation_id where o.workspace_id = $1)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(operations, 0, "preview and plan must not create operations");
|
||||
assert_eq!(
|
||||
operation_versions, 0,
|
||||
"preview and plan must not create operation versions"
|
||||
);
|
||||
}
|
||||
@@ -1,659 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use super::*;
|
||||
|
||||
use admin_api::error::ApiError;
|
||||
use crank_artifacts::MAX_ARTIFACT_BYTES;
|
||||
use crank_core::HttpMethod;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct CatalogCounts {
|
||||
operations: i64,
|
||||
operation_versions: i64,
|
||||
auth_profiles: i64,
|
||||
agent_operation_bindings: i64,
|
||||
}
|
||||
|
||||
async fn catalog_counts(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> CatalogCounts {
|
||||
let (operations, operation_versions, auth_profiles, agent_operation_bindings) =
|
||||
sqlx::query_as::<_, (i64, i64, i64, i64)>(
|
||||
"select
|
||||
(select count(*) from operations where workspace_id = $1),
|
||||
(select count(*) from operation_versions ov
|
||||
join operations o on o.id = ov.operation_id where o.workspace_id = $1),
|
||||
(select count(*) from auth_profiles where workspace_id = $1),
|
||||
(select count(*) from agent_operation_bindings b
|
||||
join operations o on o.id = b.operation_id where o.workspace_id = $1)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
CatalogCounts {
|
||||
operations,
|
||||
operation_versions,
|
||||
auth_profiles,
|
||||
agent_operation_bindings,
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(bytes: Vec<u8>) -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes,
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
const PREVIEWABLE_DOCUMENT: &[u8] = br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Preview lifecycle","version":"1"},
|
||||
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
|
||||
}"#;
|
||||
|
||||
async fn insert_malformed_auth_profile(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
) {
|
||||
sqlx::query(
|
||||
"insert into auth_profiles
|
||||
(id, workspace_id, name, kind, config_json, created_at, updated_at)
|
||||
values ('auth_decode_failure', $1, 'decode-failure', 'bearer', 'null'::jsonb, now(), now())",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn insert_catalog_overflow(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
) {
|
||||
sqlx::query(
|
||||
"insert into operations
|
||||
(id, workspace_id, name, display_name, protocol, status, created_at, updated_at)
|
||||
select 'op_catalog_' || g, $1, 'catalog_op_' || g, 'Catalog Op ' || g,
|
||||
'rest', 'draft', now(), now()
|
||||
from generate_series(1, 10001) as g",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn durable_import_jobs(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn active_artifact_sources(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> i64 {
|
||||
sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn assert_upload_error(error: ApiError, variant: &str, code: &str) {
|
||||
let context = match (variant, error) {
|
||||
("validation", ApiError::Validation { context, .. }) => context,
|
||||
("payload_too_large", ApiError::PayloadTooLarge { context, .. }) => context,
|
||||
(expected, actual) => panic!("expected {expected} error, got {actual:?}"),
|
||||
}
|
||||
.expect("OpenAPI upload errors carry a machine-readable code");
|
||||
assert_eq!(context["error_code"], format!("openapi_upload.{code}"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn preview_outcomes_do_not_mutate_operation_catalog() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_upload_outcomes"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let before = catalog_counts(®istry, &workspace_id).await;
|
||||
let preview = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
upload(
|
||||
br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Upload outcomes","version":"1"},
|
||||
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
|
||||
}"#
|
||||
.to_vec(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("valid OpenAPI document should return a preview");
|
||||
let candidates = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(candidates.len(), 1);
|
||||
assert_eq!(candidates[0].method, HttpMethod::Get);
|
||||
assert_eq!(candidates[0].path, "/ready");
|
||||
assert_eq!(candidates[0].key, "GET /ready");
|
||||
assert_eq!(catalog_counts(®istry, &workspace_id).await, before);
|
||||
|
||||
let before = catalog_counts(®istry, &workspace_id).await;
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload(Vec::new()))
|
||||
.await
|
||||
.expect_err("empty upload should be rejected");
|
||||
assert_upload_error(error, "validation", "empty_file");
|
||||
assert_eq!(catalog_counts(®istry, &workspace_id).await, before);
|
||||
|
||||
let before = catalog_counts(®istry, &workspace_id).await;
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload(b"{".to_vec()))
|
||||
.await
|
||||
.expect_err("malformed OpenAPI document should be rejected");
|
||||
assert_upload_error(error, "validation", "invalid_document");
|
||||
assert_eq!(catalog_counts(®istry, &workspace_id).await, before);
|
||||
|
||||
let before = catalog_counts(®istry, &workspace_id).await;
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload(vec![b' '; MAX_ARTIFACT_BYTES + 1]))
|
||||
.await
|
||||
.expect_err("oversized upload should be rejected");
|
||||
assert_upload_error(error, "payload_too_large", "file_too_large");
|
||||
assert_eq!(catalog_counts(®istry, &workspace_id).await, before);
|
||||
|
||||
let before = catalog_counts(®istry, &workspace_id).await;
|
||||
let error = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
upload(
|
||||
br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"No methods","version":"1"},
|
||||
"paths":{}
|
||||
}"#
|
||||
.to_vec(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("document without supported methods should be rejected");
|
||||
assert_upload_error(error, "validation", "no_methods");
|
||||
assert_eq!(catalog_counts(®istry, &workspace_id).await, before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn preview_profile_decode_failure_leaves_no_pending_job_or_source() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_upload_profile_decode_failure"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
insert_malformed_auth_profile(®istry, &workspace_id).await;
|
||||
|
||||
service
|
||||
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
|
||||
.await
|
||||
.expect_err("malformed auth profile must fail preview enrichment");
|
||||
|
||||
assert_eq!(
|
||||
durable_import_jobs(®istry, &workspace_id).await,
|
||||
0,
|
||||
"profile lookup failure must not leave a durable import job"
|
||||
);
|
||||
assert_eq!(
|
||||
active_artifact_sources(®istry, &workspace_id).await,
|
||||
0,
|
||||
"profile lookup failure must not leave attached sources"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn preview_catalog_limit_failure_leaves_no_pending_job_or_source() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_upload_catalog_limit_failure"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
insert_catalog_overflow(®istry, &workspace_id).await;
|
||||
|
||||
service
|
||||
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
|
||||
.await
|
||||
.expect_err("catalog over the import limit must fail preview enrichment");
|
||||
|
||||
assert_eq!(
|
||||
durable_import_jobs(®istry, &workspace_id).await,
|
||||
0,
|
||||
"catalog lookup failure must not leave a durable import job"
|
||||
);
|
||||
assert_eq!(
|
||||
active_artifact_sources(®istry, &workspace_id).await,
|
||||
0,
|
||||
"catalog lookup failure must not leave attached sources"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn exact_v5_contract_replays_saved_preview_without_source_locations() {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn remove_source_locations(value: &mut serde_json::Value) {
|
||||
match value {
|
||||
serde_json::Value::Object(object) => {
|
||||
object.remove("source_location");
|
||||
for value in object.values_mut() {
|
||||
remove_source_locations(value);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(values) => {
|
||||
for value in values {
|
||||
remove_source_locations(value);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v5_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 payload = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.preview_payload;
|
||||
|
||||
// A preview persisted under v5 has the then-current projection and digest,
|
||||
// without the source_location fields added by v6.
|
||||
let persisted_preview = payload
|
||||
.get_mut("preview")
|
||||
.expect("newly saved job includes its preview");
|
||||
assert!(persisted_preview.to_string().contains("source_location"));
|
||||
remove_source_locations(persisted_preview);
|
||||
let digest = format!(
|
||||
"{:x}",
|
||||
Sha256::digest(serde_json::to_vec(persisted_preview).unwrap())
|
||||
);
|
||||
payload["normalization"]["normalizer_version"] = "normalized-ir-v5".into();
|
||||
payload["normalization"]["projection_version"] = "preview-v5".into();
|
||||
payload["normalization"]["config"]["normalizer_version"] = "normalized-ir-v5".into();
|
||||
payload["normalization"]["config"]["projection_version"] = "preview-v5".into();
|
||||
payload["preview_digest"] = digest.into();
|
||||
// If v5 is reparsed, this deliberately absent dependency makes the replay fail.
|
||||
payload["dependency_snapshots"] = serde_json::json!([{
|
||||
"source_id": "src_openapi_dep_v5_must_not_be_read",
|
||||
"digest": format!("sha256:{}", "0".repeat(64)),
|
||||
"canonical_uri": "https://schemas.example.test/v5.yaml"
|
||||
}]);
|
||||
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
|
||||
.bind(serde_json::to_string(&payload).unwrap())
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
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);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ use serial_test::serial;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
mod apply_failures;
|
||||
mod body_limit;
|
||||
mod telemetry;
|
||||
|
||||
const OPENAPI: &str = r#"
|
||||
@@ -512,7 +513,6 @@ 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,7 +245,6 @@ 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(),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::*;
|
||||
|
||||
const DEFAULT_HTTP_BODY_BYTES: usize = 2 * 1024 * 1024;
|
||||
const MAX_STORED_PLAN_BYTES: usize = 16 * 1024 * 1024;
|
||||
const PATH_COUNT: usize = 49;
|
||||
const PATH_LEN: usize = 3100;
|
||||
const METHODS: [&str; 7] = ["get", "post", "put", "patch", "delete", "head", "options"];
|
||||
const OPERATION_COUNT: usize = PATH_COUNT * METHODS.len();
|
||||
|
||||
// Complete descriptions and schemas avoid multiplying quality findings for
|
||||
// long paths. The test must pass the stored-plan cap before exercising HTTP.
|
||||
fn long_path_document_and_keys() -> (String, Vec<String>) {
|
||||
let mut paths = serde_json::Map::new();
|
||||
let mut keys = Vec::new();
|
||||
for index in 0..PATH_COUNT {
|
||||
let path = format!("/{index:04}{}", "a".repeat(PATH_LEN - 5));
|
||||
let mut item = serde_json::Map::new();
|
||||
item.insert(
|
||||
"parameters".to_owned(),
|
||||
serde_json::json!([{
|
||||
"name": "filter", "in": "query", "description": "Record filter",
|
||||
"schema": { "type": "string" }
|
||||
}]),
|
||||
);
|
||||
for (method_index, method) in METHODS.iter().enumerate() {
|
||||
keys.push(format!("{} {path}", method.to_uppercase()));
|
||||
item.insert(
|
||||
(*method).to_owned(),
|
||||
serde_json::json!({
|
||||
"operationId": format!("read_record_{index}_{method_index}"),
|
||||
"summary": "Read record",
|
||||
"description": "Returns a matching record for the requested filter.",
|
||||
"responses": { "200": {
|
||||
"description": "Matched record",
|
||||
"content": { "application/json": { "schema": {
|
||||
"type": "object", "properties": { "result": { "type": "string" } }
|
||||
} } }
|
||||
} }
|
||||
}),
|
||||
);
|
||||
}
|
||||
paths.insert(path, Value::Object(item));
|
||||
}
|
||||
(
|
||||
serde_json::json!({
|
||||
"openapi": "3.0.3", "info": { "title": "Long path keys", "version": "1" },
|
||||
"servers": [{ "url": "https://api.example.test" }], "paths": paths
|
||||
})
|
||||
.to_string(),
|
||||
keys,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn plan_http_body_limit_accepts_valid_large_confirmation() {
|
||||
let (document, keys) = long_path_document_and_keys();
|
||||
assert!(document.len() <= MAX_ARTIFACT_BYTES);
|
||||
assert_eq!(keys.len(), OPERATION_COUNT);
|
||||
assert!(keys.iter().all(|key| key.len() <= 4096));
|
||||
println!(
|
||||
"B1_FIXTURE document_bytes={} operations={}",
|
||||
document.len(),
|
||||
keys.len()
|
||||
);
|
||||
|
||||
let registry = test_registry().await;
|
||||
let app = build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_plan_body_limit"),
|
||||
);
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let response = client
|
||||
.post(format!("{server}/imports/openapi/preview"))
|
||||
.multipart(Form::new().part(
|
||||
"file",
|
||||
file_part(document.as_bytes(), "openapi.json", "application/json"),
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let preview: Value = response.json().await.unwrap();
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "{preview}");
|
||||
let job_id = preview["job_id"].as_str().unwrap();
|
||||
|
||||
// The smaller control proves actual persistence. Explicit create decisions
|
||||
// add no semantic change, but repeat the keys in a larger HTTP request.
|
||||
for explicit_decisions in [false, true] {
|
||||
let decisions: Vec<Value> = if explicit_decisions {
|
||||
keys.iter()
|
||||
.map(|key| {
|
||||
serde_json::json!({
|
||||
"operation_key": key, "action": "create"
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let payload = serde_json::json!({
|
||||
"selection_mode": "full", "selected_operation_keys": keys, "decisions": decisions
|
||||
});
|
||||
let request_bytes = serde_json::to_vec(&payload).unwrap().len();
|
||||
assert_eq!(request_bytes > DEFAULT_HTTP_BODY_BYTES, explicit_decisions);
|
||||
let response = client
|
||||
.post(format!("{server}/imports/openapi/{job_id}/plans"))
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
println!(
|
||||
"B1_HTTP explicit_decisions={explicit_decisions} request_bytes={request_bytes} status={status}"
|
||||
);
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"valid plan rejected: {}",
|
||||
body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
let plan: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(plan["counts"]["selected"], OPERATION_COUNT);
|
||||
assert_eq!(plan["counts"]["actionable"], OPERATION_COUNT);
|
||||
assert_eq!(plan["counts"]["blocked"], 0);
|
||||
assert_eq!(plan["counts"]["excluded"], 0);
|
||||
let plan_id: crank_registry::ImportPlanId = plan["plan_reference"].as_str().unwrap().into();
|
||||
let stored = registry
|
||||
.get_import_plan(&WorkspaceId::new("ws_default"), &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let stored_bytes = serde_json::to_vec(&stored.payload).unwrap().len();
|
||||
println!(
|
||||
"B1_PERSISTED explicit_decisions={explicit_decisions} stored_bytes={stored_bytes}"
|
||||
);
|
||||
assert!(stored_bytes <= MAX_STORED_PLAN_BYTES);
|
||||
assert_eq!(stored.payload["counts"]["selected"], OPERATION_COUNT);
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,20 @@ fn plan_is_deterministic_and_committed_contract_is_current() {
|
||||
);
|
||||
assert_eq!(first.stdout, second.stdout);
|
||||
let plan: serde_json::Value = serde_json::from_slice(&first.stdout).unwrap();
|
||||
assert_eq!(plan["sequence"].as_array().unwrap().len(), 13);
|
||||
assert_eq!(plan["sequence"].as_array().unwrap().len(), 15);
|
||||
let target = command(&["plan", "--target-version"], None);
|
||||
assert!(
|
||||
target.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&target.stderr)
|
||||
);
|
||||
let last_version = plan["sequence"].as_array().unwrap().last().unwrap()["version"]
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8(target.stdout).unwrap(),
|
||||
format!("{last_version}\n")
|
||||
);
|
||||
|
||||
let checked = command(&["plan", "--check"], None);
|
||||
assert!(
|
||||
@@ -50,6 +63,15 @@ fn plan_is_deterministic_and_committed_contract_is_current() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_plan_option_is_rejected_without_success_output() {
|
||||
let output = command(&["plan", "--not-an-option"], None);
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let diagnostic: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
|
||||
assert_eq!(diagnostic["code"], "invalid_command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_command_is_bounded_and_does_not_echo_arguments() {
|
||||
let canary = "secret-command-canary";
|
||||
@@ -82,7 +104,7 @@ async fn database_only_config_can_apply_and_preflight_a_fresh_schema() {
|
||||
);
|
||||
let result: serde_json::Value = serde_json::from_slice(&preflight.stdout).unwrap();
|
||||
assert_eq!(result["status"], "current");
|
||||
assert_eq!(result["version"], 13);
|
||||
assert_eq!(result["version"], 15);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in new issue
Block a user