Завершить импорт OpenAPI и пошаговый первый запуск (2-15) #90
No files matched your search
@@ -21,6 +21,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
@@ -109,6 +111,31 @@ jobs:
|
||||
- name: Check Rust boundaries
|
||||
run: scripts/check-rust-boundaries.sh
|
||||
|
||||
- name: Run offline OpenAPI support corpus gate
|
||||
run: cargo test -p crank-import --test corpus -- --test-threads=1
|
||||
|
||||
- name: Check OpenAPI matrix and corpus compatibility versions
|
||||
env:
|
||||
MATRIX_BASE_REF: ${{ gitea.base_ref }}
|
||||
MATRIX_EVENT_BEFORE: ${{ gitea.event.before }}
|
||||
run: |
|
||||
if [ -n "$MATRIX_BASE_REF" ]; then
|
||||
base_ref="origin/$MATRIX_BASE_REF"
|
||||
elif [ -n "$MATRIX_EVENT_BEFORE" ] && ! printf '%s' "$MATRIX_EVENT_BEFORE" | grep -Eq '^0+$'; then
|
||||
base_ref="$MATRIX_EVENT_BEFORE"
|
||||
else
|
||||
base_ref="$(git merge-base HEAD origin/main)"
|
||||
fi
|
||||
python3 scripts/check-openapi-matrix-compatibility.py --base "$base_ref"
|
||||
|
||||
- name: Save OpenAPI corpus evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: openapi-corpus-evidence
|
||||
path: crates/crank-import/target/openapi-corpus/evidence-*.json
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Run clippy
|
||||
run: cargo clippy --workspace --all-targets --all-features --jobs "$CARGO_BUILD_JOBS" -- -D warnings
|
||||
|
||||
|
||||
Generated
+1
@@ -766,6 +766,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.18",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -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(_) => {
|
||||
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 {
|
||||
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,
|
||||
};
|
||||
|
||||
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")
|
||||
assert_eq!(dependency_sources, 0);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(dependency_sources, 0);
|
||||
assert_eq!(import_jobs, 0);
|
||||
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;
|
||||
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()
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
.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]
|
||||
|
||||
@@ -64,6 +64,15 @@
|
||||
.onboarding-first-call-evidence dt { color: var(--text-muted, #8b949e); }
|
||||
.onboarding-first-call-evidence dd { margin: 0; font-family: var(--font-mono, monospace); overflow-wrap: anywhere; }
|
||||
.onboarding-deep-link-stale { position: fixed; left: 50%; top: 76px; z-index: 810; width: min(520px, calc(100vw - 28px)); transform: translateX(-50%); padding: 14px; border: 1px solid var(--amber, #d29922); border-radius: 10px; background: var(--surface-raised, #161b22); color: var(--text-primary, #f0f6fc); box-shadow: 0 12px 36px rgba(0, 0, 0, .35); }
|
||||
.onboarding-openapi-path { margin-top: 14px; padding: 12px; border: 1px dashed var(--border-color, #30363d); border-radius: 9px; }
|
||||
.onboarding-openapi-hint { margin: 0 0 8px; color: var(--text-muted, #8b949e); font-size: 12px; }
|
||||
.onboarding-import-report { margin-top: 12px; padding: 12px; border: 1px solid var(--border-color, #30363d); border-radius: 9px; }
|
||||
.onboarding-import-report h3 { margin: 0 0 8px; font-size: 14px; }
|
||||
.onboarding-import-report-list { display: grid; gap: 8px; margin: 0; padding-left: 20px; }
|
||||
.onboarding-import-report-item { display: grid; gap: 4px; overflow-wrap: anywhere; font-size: 12px; }
|
||||
.onboarding-import-drift, .onboarding-import-error { color: var(--amber, #d29922); font-size: 12px; }
|
||||
.onboarding-import-selected { color: var(--success, #3fb950); font-size: 12px; }
|
||||
.onboarding-return-context { display: none; }
|
||||
.onboarding-footer { display: flex; justify-content: space-between; gap: 8px; margin-top: 12px; }
|
||||
.onboarding-link-button { border: 0; background: transparent; color: var(--text-muted, #8b949e); text-decoration: underline; cursor: pointer; font: inherit; font-size: 12px; }
|
||||
|
||||
|
||||
Vendored
+358
-4
@@ -160,6 +160,124 @@
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-confirmation {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
padding: 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
background: var(--bg-surface);
|
||||
}
|
||||
|
||||
.openapi-import-plan-confirmation[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.openapi-import-plan-confirmation h3,
|
||||
.openapi-import-plan-intro,
|
||||
.openapi-import-plan-versioning,
|
||||
.openapi-import-plan-summary {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.openapi-import-plan-intro,
|
||||
.openapi-import-plan-versioning {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-versioning:not([hidden]) {
|
||||
padding: 12px;
|
||||
border-left: 3px solid var(--accent);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-overlay);
|
||||
}
|
||||
|
||||
.openapi-import-plan-counts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-count {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-candidates,
|
||||
.openapi-import-plan-outcomes {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.openapi-import-findings summary {
|
||||
cursor: pointer;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-findings-page {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.openapi-import-findings-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 8px;
|
||||
padding-top: 6px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.openapi-import-plan-candidate,
|
||||
.openapi-import-plan-outcome {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-overlay);
|
||||
}
|
||||
|
||||
.openapi-import-plan-candidate[data-state="blocked"],
|
||||
.openapi-import-plan-outcome[data-outcome="rejected"] {
|
||||
border-color: color-mix(in srgb, var(--red) 45%, var(--border));
|
||||
}
|
||||
|
||||
.openapi-import-plan-candidate code,
|
||||
.openapi-import-plan-outcome code {
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.openapi-import-plan-candidate p,
|
||||
.openapi-import-plan-outcome p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-reason {
|
||||
color: var(--text-muted) !important;
|
||||
}
|
||||
|
||||
.openapi-import-plan-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-summary {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.openapi-import-source,
|
||||
.openapi-import-group {
|
||||
border: 1px solid var(--border);
|
||||
@@ -185,7 +303,6 @@
|
||||
}
|
||||
|
||||
#openapi-import-server,
|
||||
#openapi-import-conflict-mode,
|
||||
#openapi-import-search,
|
||||
#openapi-import-method-filter,
|
||||
.openapi-import-server-custom {
|
||||
@@ -238,6 +355,30 @@
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.openapi-import-partial-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
width: fit-content;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 4px 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.openapi-import-pagination[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.openapi-import-group-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -266,12 +407,109 @@
|
||||
}
|
||||
|
||||
.openapi-import-operation {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.openapi-import-operation-selection {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
gap: 12px;
|
||||
align-items: start;
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.openapi-import-security-status {
|
||||
padding: 6px 0 6px 28px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls,
|
||||
.openapi-import-security-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 14px;
|
||||
padding-left: 28px;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls label,
|
||||
.openapi-import-security-controls label {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls select,
|
||||
.openapi-import-decision-controls input,
|
||||
.openapi-import-security-controls select,
|
||||
.openapi-import-security-controls input {
|
||||
min-width: 210px;
|
||||
max-width: min(100%, 360px);
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-surface);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.openapi-import-security {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status {
|
||||
padding-left: 28px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status[data-status="blocked"] {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status[data-status="resolved"] {
|
||||
color: var(--green, var(--text-secondary));
|
||||
}
|
||||
|
||||
.openapi-import-security-findings {
|
||||
align-self: center;
|
||||
color: var(--amber, var(--text-secondary));
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-security-guidance {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-blocked-help {
|
||||
margin: 0;
|
||||
color: var(--red);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-plan-version,
|
||||
.openapi-import-plan-revalidation {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.openapi-import-plan-stale {
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--red);
|
||||
border-radius: 10px;
|
||||
color: var(--red);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-operation:last-child {
|
||||
@@ -288,6 +526,25 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-source-location {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.openapi-import-conflict {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
color: var(--amber);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-conflict-proposal {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.openapi-import-method {
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
@@ -297,6 +554,26 @@
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.openapi-import-operation-readiness {
|
||||
justify-self: start;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-muted, #21262d);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.openapi-import-operation-readiness-actionable {
|
||||
background: var(--green-glow, rgba(63, 185, 80, 0.16));
|
||||
color: var(--green);
|
||||
}
|
||||
|
||||
.openapi-import-operation-readiness-blocked {
|
||||
background: var(--red-glow, rgba(248, 81, 73, 0.16));
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.openapi-import-findings {
|
||||
grid-column: 2 / -1;
|
||||
display: grid;
|
||||
@@ -304,6 +581,10 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-operation .openapi-import-findings {
|
||||
grid-column: auto;
|
||||
}
|
||||
|
||||
.openapi-import-finding {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
@@ -461,6 +742,17 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.openapi-import-result-skipped-page {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.openapi-import-result-skipped-page ul {
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding-left: 22px;
|
||||
}
|
||||
|
||||
.openapi-import-created-list {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
@@ -475,6 +767,68 @@
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.openapi-import-blockers-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--danger, #f85149);
|
||||
border-radius: 8px;
|
||||
color: var(--danger, #f85149);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-blockers-summary[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.openapi-import-blockers-count {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-blocker-code {
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
background: rgba(248, 81, 73, .12);
|
||||
font-family: var(--font-mono, monospace);
|
||||
}
|
||||
.onboarding-import-draft-choice {
|
||||
margin-top: 14px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--accent, #58a6ff);
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
.onboarding-import-draft-choice-title {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.onboarding-import-draft-choice-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.onboarding-import-draft-option-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 8px 0;
|
||||
border-top: 1px solid var(--border-color, #30363d);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.onboarding-import-drift {
|
||||
color: var(--amber, #d29922);
|
||||
}
|
||||
|
||||
.onboarding-import-draft-selected {
|
||||
color: var(--success, #3fb950);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.openapi-import-toolbar {
|
||||
grid-template-columns: 1fr;
|
||||
@@ -484,7 +838,7 @@
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.openapi-import-operation {
|
||||
.openapi-import-operation-selection {
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
|
||||
|
||||
@@ -178,7 +178,19 @@
|
||||
</div><!-- /step-sidebar -->
|
||||
|
||||
<!-- ── Main step panel ── -->
|
||||
<div class="wizard-main"><div id="step-panel-container"><!-- steps loaded dynamically --></div></div>
|
||||
<div class="wizard-main">
|
||||
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
|
||||
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="8" cy="8" r="7"/>
|
||||
<path d="M8 11V8M8 5v-.5"/>
|
||||
</svg>
|
||||
<div class="info-callout-body">
|
||||
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
|
||||
<div class="info-callout-text" id="wizard-live-status-text"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="step-panel-container"><!-- steps loaded dynamically --></div>
|
||||
</div>
|
||||
</div><!-- /wizard-body -->
|
||||
|
||||
<!-- ══ BOTTOM ACTION BAR ══ -->
|
||||
|
||||
@@ -131,17 +131,6 @@ tls:
|
||||
<div class="section-divider-line"></div>
|
||||
</div>
|
||||
|
||||
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
|
||||
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="8" cy="8" r="7"/>
|
||||
<path d="M8 11V8M8 5v-.5"/>
|
||||
</svg>
|
||||
<div class="info-callout-body">
|
||||
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
|
||||
<div class="info-callout-text" id="wizard-live-status-text"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="wizard-mapping-warnings" class="mapping-warnings" hidden data-testid="wizard-mapping-warnings"></div>
|
||||
|
||||
<div class="config-card" id="agent-facing-preview-card" style="margin-bottom: 20px;">
|
||||
|
||||
+32
-9
@@ -417,13 +417,6 @@
|
||||
<select id="openapi-import-server"></select>
|
||||
<input id="openapi-import-server-custom" class="openapi-import-server-custom" type="url" data-i18n-aria-label="openapi.server.custom_aria" aria-label="Свой Base URL" data-i18n-ph="openapi.server.placeholder" placeholder="Или укажите свой base URL, например https://api.example.com">
|
||||
</div>
|
||||
<div class="openapi-import-server-row">
|
||||
<label for="openapi-import-conflict-mode" data-i18n="openapi.conflict.label">Если операция уже существует</label>
|
||||
<select id="openapi-import-conflict-mode">
|
||||
<option value="rename" selected data-i18n="openapi.conflict.rename">Создать копию с новым именем</option>
|
||||
<option value="skip" data-i18n="openapi.conflict.skip">Пропустить</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="openapi-import-toolbar">
|
||||
<div class="openapi-import-filter">
|
||||
<label for="openapi-import-search" data-i18n="openapi.search.label">Поиск методов</label>
|
||||
@@ -440,13 +433,43 @@
|
||||
<button class="btn-secondary" id="openapi-import-clear-visible" type="button" data-i18n="openapi.clear_visible">Снять видимые</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="openapi-import-partial-toggle">
|
||||
<input id="openapi-import-partial-mode" type="checkbox">
|
||||
<span data-i18n="openapi.partial_mode">Enable partial import</span>
|
||||
</label>
|
||||
<div class="openapi-import-groups" id="openapi-import-groups"></div>
|
||||
<nav class="openapi-import-pagination" id="openapi-import-pagination" data-testid="openapi-import-pagination" data-i18n-aria-label="openapi.pagination.label" aria-label="Pagination" hidden>
|
||||
<button class="btn-secondary" id="openapi-import-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
|
||||
<span id="openapi-import-page-status" data-testid="openapi-import-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
|
||||
<button class="btn-secondary" id="openapi-import-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
|
||||
</nav>
|
||||
<div class="openapi-import-footer">
|
||||
<span id="openapi-import-selection" data-i18n="openapi.selection.empty">Выбрано: 0</span>
|
||||
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.create">Создать черновики</button>
|
||||
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.plan.create">Просмотреть план импорта</button>
|
||||
</div>
|
||||
<div class="openapi-import-result" id="openapi-import-result" hidden></div>
|
||||
<section class="openapi-import-plan-confirmation" id="openapi-import-plan-confirmation" data-testid="openapi-import-apply-confirmation" aria-labelledby="openapi-import-plan-title" hidden>
|
||||
<h3 id="openapi-import-plan-title" data-i18n="openapi.plan.confirm_title">Подтвердите план импорта</h3>
|
||||
<p class="openapi-import-plan-intro" data-i18n="openapi.plan.confirm_intro">Перед применением проверьте точный план сервера.</p>
|
||||
<p class="openapi-import-plan-version" id="openapi-import-plan-version" data-testid="openapi-import-plan-version"></p>
|
||||
<p class="openapi-import-plan-revalidation" id="openapi-import-plan-revalidation-status" data-testid="openapi-import-plan-revalidation-status" role="status" aria-live="polite" aria-atomic="true"></p>
|
||||
<p class="openapi-import-plan-stale" id="openapi-import-plan-stale" data-testid="openapi-import-plan-stale" hidden></p>
|
||||
<p class="openapi-import-plan-blocked-help" id="openapi-import-plan-blocked-help" data-i18n="openapi.plan.blocked_help" hidden>Исправьте решения для заблокированных операций и создайте план заново.</p>
|
||||
<div class="openapi-import-plan-counts" id="openapi-import-plan-counts" data-testid="openapi-import-apply-counts"></div>
|
||||
<nav class="openapi-import-pagination" id="openapi-import-plan-pagination" data-testid="openapi-import-plan-pagination" data-i18n-aria-label="openapi.pagination.plan_label" aria-label="Plan candidates" hidden>
|
||||
<button class="btn-secondary" id="openapi-import-plan-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
|
||||
<span id="openapi-import-plan-page-status" data-testid="openapi-import-plan-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
|
||||
<button class="btn-secondary" id="openapi-import-plan-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
|
||||
</nav>
|
||||
<div class="openapi-import-plan-candidates" id="openapi-import-plan-candidates"></div>
|
||||
<p class="openapi-import-plan-versioning" id="openapi-import-versioning-consequences" data-testid="openapi-import-versioning-consequences" hidden></p>
|
||||
<div class="openapi-import-plan-actions">
|
||||
<button class="btn-secondary" id="openapi-import-plan-reopen" type="button" data-testid="openapi-import-plan-reopen" data-i18n="openapi.plan.reopen">Reopen and check current plan</button>
|
||||
<button class="btn-secondary" id="openapi-import-plan-back" type="button" data-i18n="openapi.plan.back">Назад к выбору</button>
|
||||
<button class="btn-primary" id="openapi-import-plan-apply" type="button" data-testid="openapi-import-plan-apply" data-i18n="openapi.plan.apply">Применить импорт</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="openapi-import-result" id="openapi-import-result" data-testid="openapi-import-apply-result" hidden></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -328,6 +328,12 @@
|
||||
expected_revision: expectedRevision,
|
||||
});
|
||||
},
|
||||
registerOnboardingImportContext: function(workspaceId, payload) {
|
||||
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/import-context', payload);
|
||||
},
|
||||
selectOnboardingImportDraft: function(workspaceId, payload) {
|
||||
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/select-draft', payload);
|
||||
},
|
||||
updateWorkspace: function(workspaceId, payload) {
|
||||
return patch('/workspaces/' + encodeURIComponent(workspaceId), payload);
|
||||
},
|
||||
@@ -436,6 +442,35 @@
|
||||
signal: options && options.signal,
|
||||
});
|
||||
},
|
||||
createOpenApiImportPlan: function(workspaceId, jobId, payload, options) {
|
||||
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(jobId) + '/plans', {
|
||||
method: 'POST',
|
||||
headers: headers({
|
||||
'Content-Type': 'application/json',
|
||||
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
signal: options && options.signal,
|
||||
});
|
||||
},
|
||||
revalidateOpenApiImportPlan: function(workspaceId, planReference, options) {
|
||||
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/plans/' + encodeURIComponent(planReference), {
|
||||
method: 'GET',
|
||||
headers: headers({ 'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en' }),
|
||||
signal: options && options.signal,
|
||||
});
|
||||
},
|
||||
applyOpenApiImportPlan: function(workspaceId, planReference, payload, options) {
|
||||
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(planReference) + '/apply', {
|
||||
method: 'POST',
|
||||
headers: headers({
|
||||
'Content-Type': 'application/json',
|
||||
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
signal: options && options.signal,
|
||||
});
|
||||
},
|
||||
listAgents: function(workspaceId) {
|
||||
return get('/workspaces/' + encodeURIComponent(workspaceId) + '/agents');
|
||||
},
|
||||
|
||||
+216
-3
@@ -611,6 +611,27 @@ var TRANSLATIONS = {
|
||||
'wizard.step2.auth_mode.none': 'No auth',
|
||||
'wizard.step2.auth_mode.existing': 'Use existing authorization profile',
|
||||
'wizard.step2.auth_mode.create': 'Create authorization profile now',
|
||||
'openapi.error.plan_too_large': 'Select at most 512 operations and leave at most 512 excluded operations.',
|
||||
'openapi.security.alternative_label': 'Security alternative',
|
||||
'openapi.security.alternative_placeholder': 'Choose a security alternative',
|
||||
'openapi.security.no_auth': 'No authentication',
|
||||
'openapi.security.unsupported': 'unsupported',
|
||||
'openapi.security.profile_label': 'Auth Profile',
|
||||
'openapi.security.profile_placeholder': 'Choose an Auth Profile',
|
||||
'openapi.security.status_no_auth': 'No authentication',
|
||||
'openapi.security.status_required': 'Authentication required',
|
||||
'openapi.security.status_unresolved': 'Unresolved',
|
||||
'openapi.security.status_unverified': 'Unverified',
|
||||
'openapi.security.status_resolved': 'Resolved',
|
||||
'openapi.security.status_blocked': 'Blocked',
|
||||
'openapi.security.empty_profiles': 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.',
|
||||
'openapi.finding.unsupported_security_scheme': 'Some security requirements could not be imported. Choose a supported alternative or remove the unsupported requirement.',
|
||||
'openapi.finding.unsupported_security_and_requirement': 'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.',
|
||||
'openapi.error.security_with_skip': 'A skipped operation cannot be bound to an Auth Profile or a security alternative.',
|
||||
'openapi.error.auth_unavailable': 'The selected Auth Profile is unavailable or its required Secret is missing. Choose another compatible profile and create a new plan.',
|
||||
'openapi.error.auth_incompatible': 'The Auth Profile scheme does not match the selected security alternative. Choose a compatible alternative or profile and create a new plan.',
|
||||
'openapi.error.auth_profile_required': 'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.',
|
||||
'openapi.error.security_alternative_required': 'The Auth Profile matches multiple security alternatives. Select the exact alternative and create a new plan.',
|
||||
'wizard.step2.auth_profile': 'Authorization profile',
|
||||
'wizard.step2.auth_profile_hint': 'The selected profile is applied automatically on every tool call.',
|
||||
'wizard.step2.auth_profile_empty': 'No authorization profiles yet. Create one below.',
|
||||
@@ -1658,6 +1679,27 @@ var TRANSLATIONS = {
|
||||
'wizard.step2.auth_mode.none': 'Без авторизации',
|
||||
'wizard.step2.auth_mode.existing': 'Использовать существующий профиль авторизации',
|
||||
'wizard.step2.auth_mode.create': 'Создать профиль авторизации сейчас',
|
||||
'openapi.error.plan_too_large': 'Выберите не более 512 операций и оставьте не более 512 исключённых операций.',
|
||||
'openapi.security.alternative_label': 'Вариант безопасности',
|
||||
'openapi.security.alternative_placeholder': 'Выберите вариант безопасности',
|
||||
'openapi.security.no_auth': 'Без аутентификации',
|
||||
'openapi.security.unsupported': 'не поддерживается',
|
||||
'openapi.security.profile_label': 'Профиль авторизации',
|
||||
'openapi.security.profile_placeholder': 'Выберите профиль авторизации',
|
||||
'openapi.security.status_no_auth': 'Без аутентификации',
|
||||
'openapi.security.status_required': 'Требуется аутентификация',
|
||||
'openapi.security.status_unresolved': 'Не разрешено',
|
||||
'openapi.security.status_unverified': 'Не проверено',
|
||||
'openapi.security.status_resolved': 'Разрешено',
|
||||
'openapi.security.status_blocked': 'Заблокировано',
|
||||
'openapi.security.empty_profiles': 'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.',
|
||||
'openapi.finding.unsupported_security_scheme': 'Некоторые security requirements нельзя импортировать. Выберите поддерживаемый вариант или уберите неподдерживаемое требование.',
|
||||
'openapi.finding.unsupported_security_and_requirement': 'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.',
|
||||
'openapi.error.security_with_skip': 'Пропускаемая операция не может быть связана с профилем авторизации или вариантом безопасности.',
|
||||
'openapi.error.auth_unavailable': 'Выбранный профиль авторизации недоступен, либо отсутствует его обязательный Secret. Выберите другой совместимый профиль и создайте новый план.',
|
||||
'openapi.error.auth_incompatible': 'Схема профиля авторизации не совпадает с выбранным вариантом безопасности. Выберите совместимый вариант или профиль и создайте новый план.',
|
||||
'openapi.error.auth_profile_required': 'Для этой операции требуется профиль авторизации. Выберите совместимый профиль и создайте новый план.',
|
||||
'openapi.error.security_alternative_required': 'Профиль авторизации подходит к нескольким вариантам безопасности. Выберите точный вариант и создайте новый план.',
|
||||
'wizard.step2.auth_profile': 'Профиль авторизации',
|
||||
'wizard.step2.auth_profile_hint': 'Выбранный профиль применяется автоматически при каждом вызове инструмента.',
|
||||
'wizard.step2.auth_profile_empty': 'Профилей авторизации пока нет. Создайте профиль ниже.',
|
||||
@@ -2092,12 +2134,81 @@ Object.assign(TRANSLATIONS.en, {
|
||||
'openapi.method.all': 'All methods',
|
||||
'openapi.select_visible': 'Select visible',
|
||||
'openapi.clear_visible': 'Clear visible',
|
||||
'openapi.partial_mode': 'Enable partial import',
|
||||
'openapi.pagination.previous': 'Previous',
|
||||
'openapi.pagination.next': 'Next',
|
||||
'openapi.pagination.label': 'Preview pages',
|
||||
'openapi.pagination.plan_label': 'Import plan candidates',
|
||||
'openapi.pagination.result_label': 'Import results',
|
||||
'openapi.findings.summary': 'Findings: {count}',
|
||||
'openapi.pagination.status': 'Page {page} of {pages} · {total} matching operations',
|
||||
'openapi.create': 'Create drafts',
|
||||
'openapi.plan.create': 'Review import plan',
|
||||
'openapi.plan.confirm_title': 'Confirm import plan',
|
||||
'openapi.plan.confirm_intro': 'Review the exact server plan before applying it.',
|
||||
'openapi.plan.reopen': 'Reopen and check current plan',
|
||||
'openapi.plan.version': 'Review {version} · reference {reference} · digest {digest}',
|
||||
'openapi.plan.revalidation_pending': 'Checking this saved plan…',
|
||||
'openapi.plan.revalidation_current': 'The saved plan is current.',
|
||||
'openapi.plan.revalidation_stale': 'The saved plan is stale.',
|
||||
'openapi.plan.revalidation_error': 'The saved plan could not be verified.',
|
||||
'openapi.plan.revalidation_guidance': 'Return to the preview and create a new plan before applying.',
|
||||
'openapi.plan.back': 'Back to selection',
|
||||
'openapi.plan.back_fix': 'Back to fix decisions',
|
||||
'openapi.plan.apply': 'Apply import',
|
||||
'openapi.plan.blocked_help': 'Fix the decisions for blocked operations, then create a new plan.',
|
||||
'openapi.plan.exact_target': 'Exact operation',
|
||||
'openapi.plan.confirmed_name': 'Confirmed name',
|
||||
'openapi.decision.action_label': 'Import decision',
|
||||
'openapi.decision.create': 'Create',
|
||||
'openapi.decision.skip': 'Skip existing operation',
|
||||
'openapi.decision.rename': 'Create with a confirmed name',
|
||||
'openapi.decision.new_version': 'Create a new Draft Version',
|
||||
'openapi.decision.target_label': 'Existing operation',
|
||||
'openapi.decision.target_placeholder': 'Choose the exact operation',
|
||||
'openapi.decision.confirmed_name_label': 'Confirmed name',
|
||||
'openapi.decision.confirmed_name_placeholder': 'Enter the exact new name',
|
||||
'openapi.plan.selected': 'Selected: {count}',
|
||||
'openapi.plan.excluded': 'Excluded: {count}',
|
||||
'openapi.plan.actionable': 'Actionable: {count}',
|
||||
'openapi.plan.blocked': 'Blocked: {count}',
|
||||
'openapi.plan.versioning_new': 'Creates a new Draft Version. The Published Version and history remain unchanged.',
|
||||
'openapi.plan.action.create': 'Create a new Draft',
|
||||
'openapi.plan.action.new_version': 'Create a new Draft Version',
|
||||
'openapi.plan.action.rename': 'Create a separate Draft with the confirmed name',
|
||||
'openapi.plan.action.skip': 'Keep the existing operation unchanged',
|
||||
'openapi.plan.action.excluded': 'Excluded from this partial import',
|
||||
'openapi.plan.action.blocked': 'Blocked and will not be applied',
|
||||
'openapi.plan.result_title': 'Import plan result',
|
||||
'openapi.plan.outcome.created': 'Created',
|
||||
'openapi.plan.outcome.versioned': 'New Draft Version',
|
||||
'openapi.plan.outcome.renamed': 'Created with confirmed name',
|
||||
'openapi.plan.outcome.skipped': 'Skipped',
|
||||
'openapi.plan.outcome.excluded': 'Excluded',
|
||||
'openapi.plan.outcome.rejected': 'Rejected',
|
||||
'openapi.plan.summary': 'Applied: {applied}; skipped: {skipped}; excluded: {excluded}; rejected: {rejected}.',
|
||||
'openapi.plan.repreview': 'This plan is stale or could not be verified. Create a fresh preview and review a new plan.',
|
||||
'openapi.plan.resolve_conflict': 'Review the conflict decision and create a new plan before applying again.',
|
||||
'openapi.plan.retry_unknown': 'The Apply result is unknown. Retry sends the same plan reference, digest and idempotency key.',
|
||||
'openapi.status.planning': 'Preparing the import plan…',
|
||||
'openapi.status.plan_ready': 'Review the server plan and confirm to apply it.',
|
||||
'openapi.status.applying': 'Applying the import plan…',
|
||||
'openapi.status.applied': 'Import plan applied.',
|
||||
'openapi.error.plan': 'The import plan could not be created.',
|
||||
'openapi.error.apply': 'The import plan could not be applied.',
|
||||
'openapi.error.operations_unavailable': 'The workspace operations could not be loaded. Retry the preview before creating a plan.',
|
||||
'openapi.error.decision_target': 'Choose an exact existing operation for this decision.',
|
||||
'openapi.error.confirmed_name': 'Enter the exact confirmed name for the rename decision.',
|
||||
'openapi.error.decision_action': 'Choose a valid import decision.',
|
||||
'openapi.status.loading_operations': 'Checking existing workspace operations…',
|
||||
'openapi.selection.empty': 'Selected: 0',
|
||||
'openapi.selection': 'Selected: {selected} of {total}, shown: {visible}',
|
||||
'openapi.group.selection': 'selected {selected} of {total}, shown {visible}',
|
||||
'openapi.group.select': 'Select group',
|
||||
'openapi.group.select': 'Select group on this page',
|
||||
'openapi.operation.fields': 'inputs: {input} · outputs: {output}',
|
||||
'openapi.operation.readiness_actionable': 'Actionable',
|
||||
'openapi.operation.readiness_blocked': 'Blocked',
|
||||
'openapi.operation.readiness_unresolved': 'Authentication required',
|
||||
'openapi.mapping.path': 'Path',
|
||||
'openapi.mapping.query': 'Query',
|
||||
'openapi.mapping.header': 'Header',
|
||||
@@ -2106,6 +2217,8 @@ Object.assign(TRANSLATIONS.en, {
|
||||
'openapi.source.summary': '{name} · {size} · methods: {count}',
|
||||
'openapi.status.file_ready': 'File is ready for preview.',
|
||||
'openapi.status.previewing': 'Uploading and parsing the document…',
|
||||
'openapi.status.uploading': 'Uploading the document…',
|
||||
'openapi.status.parsing': 'Parsing the OpenAPI document…',
|
||||
'openapi.status.preview_ready': 'Document is ready. Select methods to import.',
|
||||
'openapi.status.creating': 'Creating drafts…',
|
||||
'openapi.status.created': 'Created: {created}; skipped: {skipped}.',
|
||||
@@ -2150,6 +2263,21 @@ Object.assign(TRANSLATIONS.en, {
|
||||
'openapi.result.fix': 'Fix in wizard',
|
||||
'openapi.result.open': 'Open in wizard',
|
||||
'openapi.result.skipped': 'Skipped',
|
||||
'openapi.result.skipped_count': 'Skipped: {count} candidates',
|
||||
'openapi.blockers.summary': 'Blocked operations: {count}',
|
||||
'onboarding.openapi_path': 'Start from an OpenAPI document',
|
||||
'onboarding.openapi_hint': 'Use the canonical OpenAPI import: preview, review the exact plan, then apply it atomically.',
|
||||
'onboarding.import.choose_draft': 'Choose one Draft to continue with test and publish',
|
||||
'onboarding.import.report_title': 'OpenAPI import report and Draft choices',
|
||||
'onboarding.import.continue': 'Continue with this Draft',
|
||||
'onboarding.import.selected': 'Selected for onboarding',
|
||||
'onboarding.import.drift': 'The selected Draft changed or is unavailable. Review the report and choose an available Draft again.',
|
||||
'onboarding.import.registration_pending': 'Import report is being registered. Refresh onboarding before selecting.',
|
||||
'onboarding.import.registration_failed': 'The import was applied, but its onboarding context could not be confirmed. Refresh to recover the report before continuing.',
|
||||
'onboarding.import.selection_failed': 'This Draft could not be selected. Refresh the report and review the current Draft choices.',
|
||||
'onboarding.import.conflict_reload': 'The onboarding state changed. The latest report has been loaded; review it before trying again.',
|
||||
'onboarding.import.retry_registration': 'Retry report recovery',
|
||||
'onboarding.import.view_report': 'View the full import report',
|
||||
|
||||
});
|
||||
|
||||
@@ -2208,12 +2336,81 @@ Object.assign(TRANSLATIONS.ru, {
|
||||
'openapi.method.all': 'Все методы',
|
||||
'openapi.select_visible': 'Выбрать видимые',
|
||||
'openapi.clear_visible': 'Снять видимые',
|
||||
'openapi.partial_mode': 'Включить частичный импорт',
|
||||
'openapi.pagination.previous': 'Назад',
|
||||
'openapi.pagination.next': 'Далее',
|
||||
'openapi.pagination.label': 'Страницы предпросмотра',
|
||||
'openapi.pagination.plan_label': 'Кандидаты плана импорта',
|
||||
'openapi.pagination.result_label': 'Результаты импорта',
|
||||
'openapi.findings.summary': 'Замечаний: {count}',
|
||||
'openapi.pagination.status': 'Страница {page} из {pages} · операций по фильтру: {total}',
|
||||
'openapi.create': 'Создать черновики',
|
||||
'openapi.plan.create': 'Проверить план импорта',
|
||||
'openapi.plan.confirm_title': 'Подтвердите план импорта',
|
||||
'openapi.plan.confirm_intro': 'Перед применением проверьте точный план сервера.',
|
||||
'openapi.plan.reopen': 'Повторно открыть и проверить план',
|
||||
'openapi.plan.version': 'Проверка {version} · ссылка {reference} · digest {digest}',
|
||||
'openapi.plan.revalidation_pending': 'Проверяем сохранённый план…',
|
||||
'openapi.plan.revalidation_current': 'Сохранённый план актуален.',
|
||||
'openapi.plan.revalidation_stale': 'Сохранённый план устарел.',
|
||||
'openapi.plan.revalidation_error': 'Не удалось проверить сохранённый план.',
|
||||
'openapi.plan.revalidation_guidance': 'Вернитесь к предпросмотру и создайте новый план перед применением.',
|
||||
'openapi.plan.back': 'Назад к выбору',
|
||||
'openapi.plan.back_fix': 'Назад к исправлению решений',
|
||||
'openapi.plan.apply': 'Применить импорт',
|
||||
'openapi.plan.blocked_help': 'Исправьте решения для заблокированных операций и создайте новый план.',
|
||||
'openapi.plan.exact_target': 'Точная операция',
|
||||
'openapi.plan.confirmed_name': 'Подтверждённое имя',
|
||||
'openapi.decision.action_label': 'Решение для импорта',
|
||||
'openapi.decision.create': 'Создать',
|
||||
'openapi.decision.skip': 'Пропустить существующую операцию',
|
||||
'openapi.decision.rename': 'Создать с подтверждённым именем',
|
||||
'openapi.decision.new_version': 'Создать новую версию черновика',
|
||||
'openapi.decision.target_label': 'Существующая операция',
|
||||
'openapi.decision.target_placeholder': 'Выберите точную операцию',
|
||||
'openapi.decision.confirmed_name_label': 'Подтверждённое имя',
|
||||
'openapi.decision.confirmed_name_placeholder': 'Введите точное новое имя',
|
||||
'openapi.plan.selected': 'Выбрано: {count}',
|
||||
'openapi.plan.excluded': 'Исключено: {count}',
|
||||
'openapi.plan.actionable': 'Можно применить: {count}',
|
||||
'openapi.plan.blocked': 'Заблокировано: {count}',
|
||||
'openapi.plan.versioning_new': 'Будет создана новая версия черновика. Опубликованная версия и история останутся без изменений.',
|
||||
'openapi.plan.action.create': 'Создать черновик',
|
||||
'openapi.plan.action.new_version': 'Создать новую версию черновика',
|
||||
'openapi.plan.action.rename': 'Создать отдельный черновик с подтверждённым именем',
|
||||
'openapi.plan.action.skip': 'Оставить существующую операцию без изменений',
|
||||
'openapi.plan.action.excluded': 'Исключено из частичного импорта',
|
||||
'openapi.plan.action.blocked': 'Заблокировано и не будет применено',
|
||||
'openapi.plan.result_title': 'Результат плана импорта',
|
||||
'openapi.plan.outcome.created': 'Создано',
|
||||
'openapi.plan.outcome.versioned': 'Новая версия черновика',
|
||||
'openapi.plan.outcome.renamed': 'Создано с подтверждённым именем',
|
||||
'openapi.plan.outcome.skipped': 'Пропущено',
|
||||
'openapi.plan.outcome.excluded': 'Исключено',
|
||||
'openapi.plan.outcome.rejected': 'Отклонено',
|
||||
'openapi.plan.summary': 'Применено: {applied}; пропущено: {skipped}; исключено: {excluded}; отклонено: {rejected}.',
|
||||
'openapi.plan.repreview': 'План устарел или не прошёл проверку. Создайте новый предпросмотр и проверьте новый план.',
|
||||
'openapi.plan.resolve_conflict': 'Проверьте решение конфликта и создайте новый план перед повторным применением.',
|
||||
'openapi.plan.retry_unknown': 'Результат применения неизвестен. Повтор отправит те же ссылку, digest и ключ идемпотентности.',
|
||||
'openapi.status.planning': 'Подготавливаю план импорта…',
|
||||
'openapi.status.plan_ready': 'Проверьте план сервера и подтвердите его применение.',
|
||||
'openapi.status.applying': 'Применяю план импорта…',
|
||||
'openapi.status.applied': 'План импорта применён.',
|
||||
'openapi.error.plan': 'Не удалось создать план импорта.',
|
||||
'openapi.error.apply': 'Не удалось применить план импорта.',
|
||||
'openapi.error.operations_unavailable': 'Не удалось загрузить операции workspace. Повторите предпросмотр перед созданием плана.',
|
||||
'openapi.error.decision_target': 'Выберите точную существующую операцию для этого решения.',
|
||||
'openapi.error.confirmed_name': 'Введите точное подтверждённое имя для переименования.',
|
||||
'openapi.error.decision_action': 'Выберите допустимое решение для импорта.',
|
||||
'openapi.status.loading_operations': 'Проверяю существующие операции workspace…',
|
||||
'openapi.selection.empty': 'Выбрано: 0',
|
||||
'openapi.selection': 'Выбрано: {selected} из {total}, показано: {visible}',
|
||||
'openapi.group.selection': 'выбрано {selected} из {total}, показано {visible}',
|
||||
'openapi.group.select': 'Выбрать группу',
|
||||
'openapi.group.select': 'Выбрать группу на этой странице',
|
||||
'openapi.operation.fields': 'входов: {input} · выходов: {output}',
|
||||
'openapi.operation.readiness_actionable': 'Можно импортировать',
|
||||
'openapi.operation.readiness_blocked': 'Заблокировано',
|
||||
'openapi.operation.readiness_unresolved': 'Требуется авторизация',
|
||||
'openapi.mapping.path': 'Path',
|
||||
'openapi.mapping.query': 'Query',
|
||||
'openapi.mapping.header': 'Header',
|
||||
@@ -2222,6 +2419,8 @@ Object.assign(TRANSLATIONS.ru, {
|
||||
'openapi.source.summary': '{name} · {size} · методов: {count}',
|
||||
'openapi.status.file_ready': 'Файл готов к разбору.',
|
||||
'openapi.status.previewing': 'Загружаю и разбираю документ…',
|
||||
'openapi.status.uploading': 'Загружаю документ…',
|
||||
'openapi.status.parsing': 'Разбираю документ OpenAPI…',
|
||||
'openapi.status.preview_ready': 'Документ готов. Выберите методы для импорта.',
|
||||
'openapi.status.creating': 'Создаю черновики…',
|
||||
'openapi.status.created': 'Создано: {created}; пропущено: {skipped}.',
|
||||
@@ -2266,7 +2465,21 @@ Object.assign(TRANSLATIONS.ru, {
|
||||
'openapi.result.fix': 'Исправить в мастере',
|
||||
'openapi.result.open': 'Открыть в мастере',
|
||||
'openapi.result.skipped': 'Пропущено',
|
||||
|
||||
'openapi.result.skipped_count': 'Пропущено кандидатов: {count}',
|
||||
'openapi.blockers.summary': 'Заблокированные операции: {count}',
|
||||
'onboarding.openapi_path': 'Начать с документа OpenAPI',
|
||||
'onboarding.openapi_hint': 'Используйте канонический импорт OpenAPI: предпросмотр, проверка точного плана и атомарное применение.',
|
||||
'onboarding.import.choose_draft': 'Выберите один черновик для продолжения тестирования и публикации',
|
||||
'onboarding.import.report_title': 'Отчёт OpenAPI и выбор черновика',
|
||||
'onboarding.import.continue': 'Продолжить с этим черновиком',
|
||||
'onboarding.import.selected': 'Выбран для onboarding',
|
||||
'onboarding.import.drift': 'Выбранный черновик изменился или недоступен. Проверьте отчёт и явно выберите доступный черновик.',
|
||||
'onboarding.import.registration_pending': 'Отчёт импорта регистрируется. Обновите onboarding перед выбором.',
|
||||
'onboarding.import.registration_failed': 'Импорт применён, но его контекст onboarding не подтверждён. Обновите страницу, чтобы восстановить отчёт.',
|
||||
'onboarding.import.selection_failed': 'Не удалось выбрать этот черновик. Обновите отчёт и проверьте актуальные варианты.',
|
||||
'onboarding.import.conflict_reload': 'Состояние onboarding изменилось. Загружен актуальный отчёт; проверьте его перед новой попыткой.',
|
||||
'onboarding.import.retry_registration': 'Повторить восстановление отчёта',
|
||||
'onboarding.import.view_report': 'Открыть полный отчёт импорта',
|
||||
|
||||
});
|
||||
|
||||
|
||||
+243
-1
@@ -12,6 +12,7 @@
|
||||
refreshPromise: null,
|
||||
refreshQueued: false,
|
||||
startedRequested: false,
|
||||
importError: null,
|
||||
};
|
||||
var channel = null;
|
||||
var trigger = null;
|
||||
@@ -79,7 +80,7 @@
|
||||
function actionLabel(id) { return tKey('onboarding.action.' + id); }
|
||||
function deepLink(step) {
|
||||
var snapshot = state.snapshot || {};
|
||||
var returnTo = encodeURIComponent(window.location.pathname + window.location.search);
|
||||
var returnTo = encodeURIComponent(boundedReturnContext());
|
||||
if (step.id === 'operation') return '/wizard/?onboarding=1&return=' + returnTo;
|
||||
if (step.id === 'test' || step.id === 'publish_operation') {
|
||||
if (!snapshot.operation_id) return '/wizard/?onboarding=1&return=' + returnTo;
|
||||
@@ -100,6 +101,220 @@
|
||||
return '/logs?agent_id=' + encodeURIComponent(snapshot.agent_id || '');
|
||||
}
|
||||
function navigate(step) { window.location.href = deepLink(step); }
|
||||
function safeReturnContext(raw) {
|
||||
if (typeof raw !== 'string' || raw.charAt(0) !== '/' || raw.indexOf('//') === 0
|
||||
|| /[\u0000-\u001f\\]/.test(raw) || raw.length > 2048) return null;
|
||||
var url;
|
||||
try { url = new URL(raw, window.location.origin); } catch (_error) { return null; }
|
||||
if (url.origin !== window.location.origin) return null;
|
||||
var allowed = {
|
||||
'/': [],
|
||||
'/agents': ['onboarding', 'action', 'operationId', 'operationVersion'],
|
||||
'/api-keys': ['onboarding', 'action', 'agentId', 'agentRevision'],
|
||||
'/logs': ['log_id', 'agent_id', 'operation_id'],
|
||||
'/secrets': [],
|
||||
'/settings': [],
|
||||
'/usage': [],
|
||||
'/workspace-setup': [],
|
||||
'/wizard/': ['mode', 'operationId', 'step', 'onboarding'],
|
||||
};
|
||||
var keys = allowed[url.pathname];
|
||||
if (!keys) return null;
|
||||
var safe = new URLSearchParams();
|
||||
url.searchParams.forEach(function(value, key) {
|
||||
if (keys.indexOf(key) < 0) return;
|
||||
if (key === 'onboarding' && value === '1') safe.set(key, value);
|
||||
else if (key === 'action' && value === 'create') safe.set(key, value);
|
||||
else if (key === 'mode' && (value === 'create' || value === 'edit')) safe.set(key, value);
|
||||
else if ((key === 'operationVersion' || key === 'agentRevision' || key === 'step')
|
||||
&& /^[0-9]{1,16}$/.test(value)) safe.set(key, value);
|
||||
else if (/^(?:operationId|agentId|log_id|agent_id|operation_id)$/.test(key)
|
||||
&& /^[A-Za-z0-9_-]{1,128}$/.test(value)) safe.set(key, value);
|
||||
});
|
||||
var context = url.pathname + (safe.size ? '?' + safe.toString() : '');
|
||||
return context.length <= 256 ? context : url.pathname;
|
||||
}
|
||||
function boundedReturnContext() {
|
||||
return safeReturnContext(window.location.pathname + window.location.search) || '/';
|
||||
}
|
||||
function returnContextFromQuery() {
|
||||
var candidate = new URLSearchParams(window.location.search).get('return');
|
||||
return safeReturnContext(candidate) || boundedReturnContext();
|
||||
}
|
||||
function openOpenApiPath() {
|
||||
if (!window.CrankOpenApiImport || typeof window.CrankOpenApiImport.open !== 'function') {
|
||||
window.location.href = '/?onboarding_openapi=1&return=' + encodeURIComponent(boundedReturnContext());
|
||||
return;
|
||||
}
|
||||
window.CrankOpenApiImport.open({
|
||||
workspaceId: state.workspaceId,
|
||||
onboarding: true,
|
||||
returnContext: returnContextFromQuery(),
|
||||
importContext: state.snapshot && state.snapshot.import_context,
|
||||
onImported: function(identity) { return registerImportedApplication(identity); },
|
||||
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
|
||||
});
|
||||
}
|
||||
async function registerImportedApplication(identity) {
|
||||
var workspaceId = state.workspaceId;
|
||||
var epoch = state.epoch;
|
||||
if (!identity || !identity.applicationIdempotencyKey || !identity.planDigest
|
||||
|| !window.CrankApi || typeof window.CrankApi.registerOnboardingImportContext !== 'function') {
|
||||
throw new Error(tKey('onboarding.import.registration_failed'));
|
||||
}
|
||||
try {
|
||||
var authoritative = await window.CrankApi.getOnboarding(workspaceId);
|
||||
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
|
||||
throw new Error(tKey('onboarding.import.registration_failed'));
|
||||
}
|
||||
state.snapshot = authoritative;
|
||||
render();
|
||||
var response = await window.CrankApi.registerOnboardingImportContext(workspaceId, {
|
||||
application_idempotency_key: identity.applicationIdempotencyKey,
|
||||
plan_digest: identity.planDigest,
|
||||
expected_revision: Number(authoritative && authoritative.revision || 0),
|
||||
});
|
||||
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
|
||||
throw new Error(tKey('onboarding.import.registration_failed'));
|
||||
}
|
||||
var current = response && response.onboarding ? response.onboarding : response;
|
||||
if (!current || !current.import_context) throw new Error(tKey('onboarding.import.registration_failed'));
|
||||
state.snapshot = current;
|
||||
render();
|
||||
return current;
|
||||
} catch (error) {
|
||||
if (epoch === state.epoch && workspaceId === state.workspaceId) {
|
||||
await refresh();
|
||||
var recovered = state.snapshot && state.snapshot.import_context;
|
||||
if (recovered
|
||||
&& recovered.application_idempotency_key === identity.applicationIdempotencyKey
|
||||
&& recovered.plan_digest === identity.planDigest) return state.snapshot;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function selectImportedDraft(operationId, version, identity) {
|
||||
if (!operationId || !window.CrankApi || typeof window.CrankApi.selectOnboardingImportDraft !== 'function') return null;
|
||||
var workspaceId = state.workspaceId;
|
||||
var epoch = state.epoch;
|
||||
var context = state.snapshot && state.snapshot.import_context;
|
||||
var applicationKey = identity && identity.applicationIdempotencyKey || (context && context.application_idempotency_key);
|
||||
var digest = identity && identity.planDigest || (context && context.plan_digest);
|
||||
if (!applicationKey || !digest || !Number.isInteger(version) || version < 1) {
|
||||
throw new Error(tKey('onboarding.import.selection_failed'));
|
||||
}
|
||||
try {
|
||||
var response = await window.CrankApi.selectOnboardingImportDraft(workspaceId, {
|
||||
application_idempotency_key: applicationKey,
|
||||
plan_digest: digest,
|
||||
operation_id: operationId,
|
||||
operation_version: version,
|
||||
expected_revision: Number(state.snapshot && state.snapshot.revision || 0),
|
||||
});
|
||||
var current = response && response.onboarding ? response.onboarding : response;
|
||||
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
|
||||
throw new Error(tKey('onboarding.import.selection_failed'));
|
||||
}
|
||||
if (!current || !current.import_context
|
||||
|| current.import_context.selected_operation_id !== operationId
|
||||
|| Number(current.import_context.selected_operation_version) !== version) {
|
||||
throw new Error(tKey('onboarding.import.selection_failed'));
|
||||
}
|
||||
if (current && typeof current === 'object' && 'revision' in current) {
|
||||
state.snapshot = current;
|
||||
render();
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (error && error.status === 409 && epoch === state.epoch && workspaceId === state.workspaceId) {
|
||||
await refresh();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function renderOpenApiPath() {
|
||||
var section = document.createElement('div');
|
||||
section.className = 'onboarding-openapi-path';
|
||||
var hint = document.createElement('p');
|
||||
hint.className = 'onboarding-openapi-hint';
|
||||
hint.textContent = tKey('onboarding.openapi_hint');
|
||||
var openButton = button(tKey('onboarding.openapi_path'), 'onboarding-openapi-path', openOpenApiPath, 'onboarding-step-action');
|
||||
section.appendChild(hint);
|
||||
section.appendChild(openButton);
|
||||
return section;
|
||||
}
|
||||
async function continueWithImportedDraft(choice) {
|
||||
var context = state.snapshot && state.snapshot.import_context;
|
||||
if (!context || !choice || choice.selectable !== true) return;
|
||||
state.importError = null;
|
||||
render();
|
||||
try {
|
||||
await selectImportedDraft(choice.operation_id, choice.version, null);
|
||||
window.location.href = '/wizard/?mode=edit&operationId=' + encodeURIComponent(choice.operation_id)
|
||||
+ '&operationVersion=' + encodeURIComponent(choice.version) + '&onboarding=1'
|
||||
+ '&return=' + encodeURIComponent(boundedReturnContext());
|
||||
} catch (_error) {
|
||||
state.importError = tKey('onboarding.import.selection_failed');
|
||||
render();
|
||||
}
|
||||
}
|
||||
function renderImportContext() {
|
||||
var context = state.snapshot && state.snapshot.import_context;
|
||||
if (!context) return null;
|
||||
var section = document.createElement('section');
|
||||
section.className = 'onboarding-import-report';
|
||||
section.dataset.testid = 'onboarding-import-context';
|
||||
var title = document.createElement('h3');
|
||||
title.textContent = tKey('onboarding.import.report_title');
|
||||
section.appendChild(title);
|
||||
if (context.drift) {
|
||||
var drift = document.createElement('p');
|
||||
drift.className = 'onboarding-import-drift';
|
||||
drift.setAttribute('role', 'alert');
|
||||
drift.textContent = tKey('onboarding.import.drift');
|
||||
section.appendChild(drift);
|
||||
}
|
||||
if (state.importError) {
|
||||
var error = document.createElement('p');
|
||||
error.className = 'onboarding-import-error';
|
||||
error.setAttribute('role', 'alert');
|
||||
error.textContent = state.importError;
|
||||
section.appendChild(error);
|
||||
}
|
||||
var choices = Array.isArray(context.choices) ? context.choices : [];
|
||||
function outcomeLabel(outcome) {
|
||||
var key = 'openapi.plan.outcome.' + String(outcome || '');
|
||||
return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key);
|
||||
}
|
||||
function reasonLabel(reason) {
|
||||
if (!reason) return '';
|
||||
return window.CrankOpenApiImport && typeof window.CrankOpenApiImport.describeFinding === 'function'
|
||||
? window.CrankOpenApiImport.describeFinding(reason)
|
||||
: tKey('openapi.finding.generic');
|
||||
}
|
||||
var list = document.createElement('ul');
|
||||
list.className = 'onboarding-import-report-list';
|
||||
choices.forEach(function(choice) {
|
||||
var item = document.createElement('li');
|
||||
item.className = 'onboarding-import-report-item';
|
||||
var summary = document.createElement('span');
|
||||
summary.textContent = [choice.name || choice.key || '', outcomeLabel(choice.outcome), choice.version ? 'v' + choice.version : '', reasonLabel(choice.reason)]
|
||||
.filter(Boolean).join(' · ');
|
||||
item.appendChild(summary);
|
||||
if (choice.selectable === true && (!context.selected_operation_id || context.drift)) {
|
||||
item.appendChild(button(tKey('onboarding.import.continue'), null, function() { continueWithImportedDraft(choice); }, 'onboarding-step-action'));
|
||||
} else if (choice.operation_id === context.selected_operation_id && Number(choice.version) === Number(context.selected_operation_version)) {
|
||||
var selected = document.createElement('span');
|
||||
selected.className = 'onboarding-import-selected';
|
||||
selected.textContent = tKey('onboarding.import.selected');
|
||||
item.appendChild(selected);
|
||||
}
|
||||
list.appendChild(item);
|
||||
});
|
||||
section.appendChild(list);
|
||||
section.appendChild(button(tKey('onboarding.import.view_report'), null, openOpenApiPath, 'onboarding-link-button'));
|
||||
return section;
|
||||
}
|
||||
function recordStarted() {
|
||||
if (state.startedRequested || !state.snapshot || state.snapshot.completed) return;
|
||||
state.startedRequested = true;
|
||||
@@ -240,6 +455,17 @@
|
||||
});
|
||||
body.appendChild(list);
|
||||
}
|
||||
var returnContext = document.createElement('span');
|
||||
returnContext.className = 'onboarding-return-context';
|
||||
returnContext.dataset.testid = 'onboarding-return-context';
|
||||
returnContext.hidden = true;
|
||||
returnContext.textContent = returnContextFromQuery();
|
||||
body.appendChild(returnContext);
|
||||
if (!state.snapshot.completed) {
|
||||
body.appendChild(renderOpenApiPath());
|
||||
}
|
||||
var importReport = renderImportContext();
|
||||
if (importReport) body.appendChild(importReport);
|
||||
var footer = document.createElement('div');
|
||||
footer.className = 'onboarding-footer';
|
||||
footer.appendChild(button(tKey('onboarding.refresh'), 'onboarding-refresh', refresh, 'onboarding-link-button'));
|
||||
@@ -295,6 +521,7 @@
|
||||
var snapshot = await window.CrankApi.getOnboarding(workspaceId);
|
||||
if (epoch !== state.epoch || workspaceId !== (currentWorkspace() && currentWorkspace().id)) return;
|
||||
state.snapshot = snapshot;
|
||||
state.importError = null;
|
||||
var preference = safePreference();
|
||||
if (window.location.pathname === '/'
|
||||
&& !preference.opened
|
||||
@@ -304,6 +531,21 @@
|
||||
setOpen(true);
|
||||
}
|
||||
renderDeepLinkRecovery(snapshot);
|
||||
if (window.location.pathname === '/' && new URLSearchParams(window.location.search).get('onboarding_openapi') === '1'
|
||||
&& window.CrankOpenApiImport && typeof window.CrankOpenApiImport.open === 'function') {
|
||||
var openUrl = new URL(window.location.href);
|
||||
openUrl.searchParams.delete('onboarding_openapi');
|
||||
window.history.replaceState(window.history.state, '', openUrl.pathname + openUrl.search + openUrl.hash);
|
||||
window.CrankOpenApiImport.open({
|
||||
workspaceId: workspaceId,
|
||||
onboarding: true,
|
||||
returnContext: returnContextFromQuery(),
|
||||
importContext: snapshot.import_context || null,
|
||||
onImported: function(identity) { return registerImportedApplication(identity); },
|
||||
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
|
||||
});
|
||||
}
|
||||
return snapshot;
|
||||
} catch (error) {
|
||||
if (epoch !== state.epoch) return;
|
||||
state.error = error;
|
||||
|
||||
+1785
-179
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,8 @@
|
||||
var wizardOperationLoadGeneration = 0;
|
||||
var wizardLifecycleActionBusy = false;
|
||||
var wizardTestConfirmationToken = null;
|
||||
var wizardSavedDraftPayload = null;
|
||||
var wizardPinnedVersionStale = false;
|
||||
|
||||
function operationErrorCode(error) {
|
||||
return error && error.payload && error.payload.error
|
||||
@@ -130,12 +132,33 @@ async function saveOperation(stayOnPage) {
|
||||
async function loadOperationForEdit() {
|
||||
if (!wizardWorkspaceId || !wizardEditId) return;
|
||||
var generation = ++wizardOperationLoadGeneration;
|
||||
wizardCurrentOperation = null;
|
||||
wizardCurrentVersion = null;
|
||||
wizardSavedDraftPayload = null;
|
||||
wizardPinnedVersionStale = false;
|
||||
var pinnedVersionValue = new URLSearchParams(window.location.search).get('operationVersion');
|
||||
var pinnedVersion = null;
|
||||
if (pinnedVersionValue !== null) {
|
||||
pinnedVersion = Number(pinnedVersionValue);
|
||||
if (!/^[0-9]{1,10}$/.test(pinnedVersionValue) || !Number.isSafeInteger(pinnedVersion) || pinnedVersion < 1) {
|
||||
wizardPinnedVersionStale = true;
|
||||
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
var requestedWorkspaceId = wizardWorkspaceId;
|
||||
var requestedOperationId = wizardEditId;
|
||||
var detail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
|
||||
if (generation !== wizardOperationLoadGeneration
|
||||
|| requestedWorkspaceId !== wizardWorkspaceId
|
||||
|| requestedOperationId !== wizardEditId) return;
|
||||
var detailDraftVersion = Number(detail.draft_version_ref && detail.draft_version_ref.version
|
||||
|| detail.current_draft_version);
|
||||
if (pinnedVersion !== null && detailDraftVersion !== pinnedVersion) {
|
||||
wizardPinnedVersionStale = true;
|
||||
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
|
||||
return;
|
||||
}
|
||||
wizardProtocol = detail.protocol || 'rest';
|
||||
await loadWizardPanels([3]);
|
||||
var draftVersion = await window.CrankApi.getOperationVersion(
|
||||
@@ -146,9 +169,24 @@ async function loadOperationForEdit() {
|
||||
if (generation !== wizardOperationLoadGeneration
|
||||
|| requestedWorkspaceId !== wizardWorkspaceId
|
||||
|| requestedOperationId !== wizardEditId) return;
|
||||
if (pinnedVersion !== null) {
|
||||
var currentDetail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
|
||||
if (generation !== wizardOperationLoadGeneration
|
||||
|| requestedWorkspaceId !== wizardWorkspaceId
|
||||
|| requestedOperationId !== wizardEditId) return;
|
||||
var currentDraftVersion = Number(currentDetail.draft_version_ref && currentDetail.draft_version_ref.version
|
||||
|| currentDetail.current_draft_version);
|
||||
if (currentDraftVersion !== pinnedVersion) {
|
||||
wizardPinnedVersionStale = true;
|
||||
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
|
||||
return;
|
||||
}
|
||||
detail = currentDetail;
|
||||
}
|
||||
wizardCurrentOperation = detail;
|
||||
wizardCurrentVersion = draftVersion;
|
||||
prefillWizardFromEdit(detail, draftVersion);
|
||||
wizardSavedDraftPayload = updateOperationPayload(collectWizardPayload());
|
||||
renderAgentFacingPreview();
|
||||
renderImportQualityFindings(draftVersion);
|
||||
}
|
||||
@@ -375,6 +413,27 @@ function updateOperationPayload(payload) {
|
||||
};
|
||||
}
|
||||
|
||||
function canonicalDraftPayload(payload) {
|
||||
var editablePayload = updateOperationPayload(payload);
|
||||
delete editablePayload.category;
|
||||
|
||||
function sortKeys(value) {
|
||||
if (Array.isArray(value)) return value.map(sortKeys);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
return Object.keys(value).sort().reduce(function(sorted, key) {
|
||||
sorted[key] = sortKeys(value[key]);
|
||||
return sorted;
|
||||
}, {});
|
||||
}
|
||||
|
||||
return JSON.stringify(sortKeys(editablePayload));
|
||||
}
|
||||
|
||||
function draftPayloadMatchesBaseline(payload) {
|
||||
return wizardSavedDraftPayload !== null
|
||||
&& canonicalDraftPayload(payload) === canonicalDraftPayload(wizardSavedDraftPayload);
|
||||
}
|
||||
|
||||
async function refreshCurrentOperationState() {
|
||||
if (!wizardWorkspaceId || !wizardEditId) return null;
|
||||
var detail = await window.CrankApi.getOperation(wizardWorkspaceId, wizardEditId);
|
||||
@@ -396,6 +455,9 @@ async function refreshCurrentOperationState() {
|
||||
}
|
||||
|
||||
async function persistCurrentDraft(stayOnPage) {
|
||||
if (wizardPinnedVersionStale) {
|
||||
throw new Error(tKey('wizard.stale.body'));
|
||||
}
|
||||
if (!wizardWorkspaceId) {
|
||||
throw new Error(tKey('wizard.error.no_workspace'));
|
||||
}
|
||||
@@ -405,14 +467,33 @@ async function persistCurrentDraft(stayOnPage) {
|
||||
var createdNow = false;
|
||||
|
||||
if (wizardMode === 'edit' && wizardEditId) {
|
||||
if (draftPayloadMatchesBaseline(payload)) {
|
||||
if (stayOnPage) {
|
||||
var unchangedSaveDraftBtn = document.querySelector('.btn-save-draft');
|
||||
if (unchangedSaveDraftBtn) {
|
||||
var unchangedLabel = unchangedSaveDraftBtn.textContent;
|
||||
unchangedSaveDraftBtn.textContent = tKey('wizard.save.saved');
|
||||
setTimeout(function() {
|
||||
unchangedSaveDraftBtn.textContent = unchangedLabel;
|
||||
}, 1400);
|
||||
}
|
||||
}
|
||||
return {
|
||||
operation_id: wizardEditId,
|
||||
version: currentDraftVersion(),
|
||||
status: 'draft',
|
||||
};
|
||||
}
|
||||
response = await window.CrankApi.updateOperation(
|
||||
wizardWorkspaceId,
|
||||
wizardEditId,
|
||||
updateOperationPayload(payload)
|
||||
);
|
||||
wizardSavedDraftPayload = updateOperationPayload(payload);
|
||||
} else {
|
||||
response = await window.CrankApi.createOperation(wizardWorkspaceId, payload);
|
||||
createdNow = true;
|
||||
wizardSavedDraftPayload = updateOperationPayload(payload);
|
||||
wizardEditId = response.operation_id;
|
||||
wizardMode = 'edit';
|
||||
history.replaceState(
|
||||
|
||||
@@ -253,7 +253,7 @@
|
||||
var source = mappingEntrySource(parsed[outputField]);
|
||||
return {
|
||||
output: outputField,
|
||||
responsePath: responseSourceToPath(source) || outputField,
|
||||
responsePath: responseSourceToPath(source),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -492,7 +492,7 @@
|
||||
responseRows.forEach(function(row) {
|
||||
var responsePath = valueIn(row, 'responsePath');
|
||||
var output = valueIn(row, 'output') || outputNameFromPath(responsePath);
|
||||
if (!responsePath || !output) return;
|
||||
if (!output) return;
|
||||
responseMapping[output] = joinJsonPath('$.response.body', responsePath);
|
||||
});
|
||||
writeText('tool-output-mapping', dumpYaml(responseMapping));
|
||||
|
||||
@@ -371,7 +371,7 @@ function startNewUpstream() {
|
||||
setValue('new-auth-profile-password-secret', '');
|
||||
updateUpstreamAuthUi();
|
||||
var first = form.querySelector('input');
|
||||
if (first) setTimeout(function() { first.focus(); }, 50);
|
||||
if (first) first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,16 @@ server {
|
||||
return 302 /;
|
||||
}
|
||||
|
||||
location ~ ^/api/admin/workspaces/[^/]+/imports/openapi/[^/]+/plans$ {
|
||||
client_max_body_size 16m;
|
||||
proxy_pass http://admin-api:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://admin-api:3001;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -133,6 +133,59 @@ test('optional Getting Started checklist is server-derived, resumable, bilingual
|
||||
await expect(page.getByTestId('onboarding-checklist')).toHaveCSS('scroll-behavior', 'auto');
|
||||
});
|
||||
|
||||
test('onboarding return context drops unknown query secrets and bounds allowlisted navigation context', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
await routeOnboarding(page, async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(onboardingSnapshot(workspace.id)),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/agents?onboarding=1&token=crk_return_secret_canary');
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
|
||||
const returnContext = page.getByTestId('onboarding-return-context');
|
||||
await expect(returnContext).toHaveText('/agents?onboarding=1');
|
||||
await expect(returnContext).not.toContainText('crk_return_secret_canary');
|
||||
|
||||
await page.goto('/logs?log_id=' + 'a'.repeat(128) + '&agent_id=' + 'b'.repeat(128) + '&operation_id=' + 'c'.repeat(128));
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/logs');
|
||||
await page.goto('/secrets?token=crk_return_secret_canary');
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/secrets');
|
||||
});
|
||||
|
||||
test('a stale onboarding-pinned wizard version is rejected before loading or saving another Draft', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const operationId = 'op_pinned';
|
||||
let versionReads = 0;
|
||||
let writes = 0;
|
||||
await page.route(`**/workspaces/${workspace.id}/operations/${operationId}`, async (route) => {
|
||||
if (route.request().method() !== 'GET') writes += 1;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({
|
||||
id: operationId, protocol: 'rest', current_draft_version: 3,
|
||||
draft_version_ref: { version: 3 },
|
||||
}) });
|
||||
});
|
||||
await page.route(`**/operations/${operationId}/versions/*`, async (route) => {
|
||||
versionReads += 1;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ version: 3 }) });
|
||||
});
|
||||
await page.goto(`/wizard/?mode=edit&operationId=${operationId}&operationVersion=2`);
|
||||
await page.waitForFunction(() => window.CrankWizardReady === true);
|
||||
await expect(page.locator('#wizard-live-status')).toBeVisible();
|
||||
await expect(page.locator('#tool-name')).not.toHaveValue('wrong newer Draft');
|
||||
await page.locator('.btn-save-draft').click();
|
||||
expect(versionReads).toBe(0);
|
||||
expect(writes).toBe(0);
|
||||
expect(await page.evaluate(() => window.wizardCurrentOperation)).toBeNull();
|
||||
|
||||
});
|
||||
|
||||
test('onboarding error exposes safe support correlation and retries without a client completion bypass', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
@@ -156,6 +209,7 @@ test('onboarding error exposes safe support correlation and retries without a cl
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
@@ -183,7 +237,7 @@ test('validation, upstream and compatibility errors recover from the last author
|
||||
];
|
||||
let failureIndex = -1;
|
||||
await routeOnboarding(page, async (route) => {
|
||||
if (failureIndex >= 0) {
|
||||
if (failureIndex >= 0 && route.request().method() === 'GET') {
|
||||
const failure = failures[failureIndex];
|
||||
await route.fulfill({
|
||||
status: failure.status,
|
||||
@@ -201,6 +255,7 @@ test('validation, upstream and compatibility errors recover from the last author
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
@@ -237,7 +292,9 @@ test('authentication recovery returns to an incomplete authoritative onboarding
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
rejectOnce = true;
|
||||
await page.getByTestId('onboarding-refresh').click();
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { login, localized, uniqueName } = require('./helpers');
|
||||
|
||||
async function dismissOnboardingIfOpen(page) {
|
||||
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
|
||||
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
|
||||
await page.evaluate(() => {
|
||||
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
|
||||
if (dismiss) dismiss.click();
|
||||
});
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
}
|
||||
|
||||
function importDocument(prefix) {
|
||||
return [
|
||||
'openapi: 3.0.3',
|
||||
'info: { title: ImportPlan UI test, version: \'1\' }',
|
||||
'paths:',
|
||||
' /' + prefix + '-selected:',
|
||||
' get:',
|
||||
' operationId: ' + prefix + '_selected',
|
||||
' responses:',
|
||||
' \'200\': { description: OK }',
|
||||
' /' + prefix + '-excluded:',
|
||||
' get:',
|
||||
' operationId: ' + prefix + '_excluded',
|
||||
' responses:',
|
||||
' \'200\': { description: OK }',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function planResponse(prefix) {
|
||||
return {
|
||||
plan_reference: 'plan_e2e_importplan_213',
|
||||
plan_digest: 'a'.repeat(64),
|
||||
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
selection_mode: 'partial',
|
||||
counts: { selected: 1, excluded: 1, actionable: 1, blocked: 0 },
|
||||
candidates: [
|
||||
{
|
||||
key: 'GET /' + prefix + '-selected',
|
||||
name: 'selected_operation',
|
||||
state: 'actionable',
|
||||
action: 'new_version',
|
||||
target_operation_id: 'op_existing_target',
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
reason: null,
|
||||
},
|
||||
{
|
||||
key: 'GET /' + prefix + '-excluded',
|
||||
name: 'excluded_operation',
|
||||
state: 'excluded',
|
||||
action: null,
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
reason: 'not_selected',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function preparePlanFlow(page, locale) {
|
||||
const planCalls = [];
|
||||
const applyCalls = [];
|
||||
const prefix = uniqueName('plan_apply');
|
||||
let releaseApplyResponse;
|
||||
const applyResponseHeld = new Promise((resolve) => {
|
||||
releaseApplyResponse = resolve;
|
||||
});
|
||||
|
||||
// Keep this mock aligned with the public CreatePlan response shape.
|
||||
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
|
||||
});
|
||||
});
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
|
||||
planCalls.push({
|
||||
url: route.request().url(),
|
||||
payload: route.request().postDataJSON(),
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(planResponse(prefix)),
|
||||
});
|
||||
});
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/apply$/, async (route) => {
|
||||
applyCalls.push({
|
||||
url: route.request().url(),
|
||||
payload: route.request().postDataJSON(),
|
||||
});
|
||||
// Keep the request pending until the test has checked the duplicate guard.
|
||||
await applyResponseHeld;
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_digest: 'a'.repeat(64),
|
||||
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
|
||||
outcomes: [{ status: 'versioned' }],
|
||||
}),
|
||||
});
|
||||
});
|
||||
// Contain the legacy path so this red-phase test cannot mutate the E2E DB.
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/create$/, async (route) => {
|
||||
await route.fulfill({
|
||||
status: 409,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ message: 'ImportPlan flow required' }),
|
||||
});
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'import-plan.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from(importDocument(prefix)),
|
||||
});
|
||||
const previewResponse = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/preview'),
|
||||
);
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await previewResponse;
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
|
||||
|
||||
// The existing preview action becomes Plan creation followed by confirmation.
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await expect.poll(() => planCalls.length).toBe(1);
|
||||
return { planCalls, applyCalls, prefix, releaseApplyResponse };
|
||||
}
|
||||
|
||||
async function assertConfirmation(page, prefix) {
|
||||
const confirmation = page.locator('[data-testid="openapi-import-apply-confirmation"]');
|
||||
const counts = page.locator('[data-testid="openapi-import-apply-counts"]');
|
||||
const versioning = page.locator('[data-testid="openapi-import-versioning-consequences"]');
|
||||
|
||||
await expect(counts).toContainText(localized('Selected: 1', 'Выбрано: 1'));
|
||||
await expect(counts).toContainText(localized('Excluded: 1', 'Исключено: 1'));
|
||||
await expect(counts).toContainText(localized('Actionable: 1', 'Можно применить: 1'));
|
||||
await expect(counts).toContainText(localized('Blocked: 0', 'Заблокировано: 0'));
|
||||
await expect(versioning).toContainText(localized('new Draft Version', 'новая версия черновика'));
|
||||
await expect(versioning).toContainText(
|
||||
localized('Published Version and history remain unchanged', 'Опубликованная версия и история останутся без изменений'),
|
||||
);
|
||||
await expect(confirmation).toContainText('GET /' + prefix + '-selected');
|
||||
await expect(confirmation).toContainText('GET /' + prefix + '-excluded');
|
||||
await expect(confirmation).toContainText('op_existing_target');
|
||||
}
|
||||
|
||||
test('[P1] AC-13 renders server-confirmed partial and new_version consequences in RU and EN', async ({ page }) => {
|
||||
// This test covers rendering of a stored server plan only. It does not
|
||||
// specify how UI controls compose selection/decision request fields.
|
||||
const { planCalls, prefix } = await preparePlanFlow(page, 'ru');
|
||||
for (const locale of ['ru', 'en']) {
|
||||
await test.step('confirmation in ' + locale, async () => {
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await assertConfirmation(page, prefix);
|
||||
});
|
||||
}
|
||||
expect(planCalls).toHaveLength(1);
|
||||
expect(planCalls[0].url).toMatch(/\/imports\/openapi\/[^/]+\/plans$/);
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
|
||||
name: localized('Apply import', 'Применить импорт'),
|
||||
})).toBeVisible();
|
||||
});
|
||||
|
||||
test('[P1] AC-13 double-click sends one Apply with the stored reference, digest and idempotency key', async ({ page }) => {
|
||||
const { applyCalls, releaseApplyResponse } = await preparePlanFlow(page, 'en');
|
||||
const applyButton = page.getByRole('button', {
|
||||
name: localized('Apply import', 'Применить импорт'),
|
||||
});
|
||||
|
||||
await applyButton.dblclick();
|
||||
|
||||
await expect.poll(() => applyCalls.length).toBe(1);
|
||||
await expect(applyButton).toBeDisabled();
|
||||
releaseApplyResponse();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-result"]')).toBeVisible();
|
||||
expect(applyCalls).toHaveLength(1);
|
||||
expect(applyCalls[0].url).toMatch(/\/imports\/openapi\/plan_e2e_importplan_213\/apply$/);
|
||||
expect(applyCalls[0].payload).toMatchObject({
|
||||
plan_digest: 'a'.repeat(64),
|
||||
});
|
||||
expect(typeof applyCalls[0].payload.idempotency_key).toBe('string');
|
||||
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
|
||||
const prefix = uniqueName('plan_version');
|
||||
const targetOperationId = 'op_exact_importplan_target';
|
||||
const planCalls = [];
|
||||
const expectedName = prefix + '_selected';
|
||||
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
items: [{ id: targetOperationId, name: expectedName, protocol: 'rest', status: 'draft' }],
|
||||
page: 1,
|
||||
page_size: 1,
|
||||
total: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planCalls.push(payload);
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_e2e_importplan_decision',
|
||||
plan_digest: 'b'.repeat(64),
|
||||
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
selection_mode: payload.selection_mode,
|
||||
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
|
||||
candidates: [{
|
||||
key: payload.decisions[0].operation_key,
|
||||
name: expectedName,
|
||||
state: 'actionable',
|
||||
action: 'new_version',
|
||||
target_operation_id: targetOperationId,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
reason: null,
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'import-plan-decision.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from(importDocument(prefix)),
|
||||
});
|
||||
const previewResponse = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'),
|
||||
);
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await previewResponse;
|
||||
const operationRow = page.locator('.openapi-import-operation').filter({ hasText: expectedName });
|
||||
const operationCheckbox = operationRow.locator('[data-openapi-operation]');
|
||||
await expect(operationCheckbox).toBeVisible();
|
||||
const operationKey = await operationCheckbox.inputValue();
|
||||
await page.locator('#openapi-import-partial-mode').check();
|
||||
for (const checkbox of await page.locator('[data-openapi-operation]').all()) {
|
||||
if (await checkbox.inputValue() !== operationKey) await checkbox.uncheck();
|
||||
}
|
||||
await expect(operationRow.locator('.openapi-import-operation-meta')).toContainText(expectedName);
|
||||
const action = operationRow.locator('[data-openapi-decision-action]');
|
||||
await expect(action.locator('option[value="new_version"]')).toBeEnabled();
|
||||
await action.selectOption('new_version');
|
||||
await expect(operationRow.locator('[data-openapi-decision-target]')).toHaveValue(targetOperationId);
|
||||
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(targetOperationId);
|
||||
|
||||
expect(planCalls).toHaveLength(1);
|
||||
expect(planCalls[0].selection_mode).toBe('partial');
|
||||
expect(planCalls[0].selected_operation_keys).toEqual([operationKey]);
|
||||
expect(planCalls[0].decisions).toEqual([{
|
||||
operation_key: operationKey,
|
||||
action: 'new_version',
|
||||
target_operation_id: targetOperationId,
|
||||
}]);
|
||||
});
|
||||
@@ -0,0 +1,943 @@
|
||||
// Story 2.15 browser acceptance: OpenAPI branch in the guided onboarding.
|
||||
//
|
||||
// STATUS: ACTIVE. All leaves are activated and assert the behavior promised by the
|
||||
// approved spec `_bmad-output/implementation-artifacts/spec-2-15-openapi-guided-onboarding.md`.
|
||||
//
|
||||
// Backend authority (immutable ImportPlan apply/replay, onboarding selection and
|
||||
// event rollups, migration/schema guards) is covered by the Rust integration
|
||||
// suites mapped in
|
||||
// `_bmad-output/test-artifacts/atdd-checklist-2-15-openapi-guided-onboarding.md`.
|
||||
// This file only covers user-observable browser behavior.
|
||||
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
|
||||
|
||||
const SECRET_CANARY = 'crk_onboarding_raw_secret_canary';
|
||||
const REPRESENTATIVE_OPENAPI = [
|
||||
'openapi: 3.0.3',
|
||||
"info: { title: 'Onboarding representative document', version: '1' }",
|
||||
'servers: [{ url: http://127.0.0.1:3310 }]',
|
||||
'paths:',
|
||||
' /rates:',
|
||||
' get:',
|
||||
' operationId: listRates',
|
||||
' responses:',
|
||||
" '200':",
|
||||
' description: JSON exchange rates',
|
||||
' content:',
|
||||
' application/json:',
|
||||
' schema:',
|
||||
' type: object',
|
||||
' properties:',
|
||||
' amount: { type: number }',
|
||||
' base: { type: string }',
|
||||
' date: { type: string }',
|
||||
' rates:',
|
||||
' type: object',
|
||||
' properties:',
|
||||
' EUR: { type: number }',
|
||||
' /health:',
|
||||
' get:',
|
||||
' operationId: getHealth',
|
||||
' responses:',
|
||||
" '200':",
|
||||
' description: JSON service health',
|
||||
' content:',
|
||||
' application/json:',
|
||||
' schema:',
|
||||
' type: object',
|
||||
' properties:',
|
||||
' status: { type: string }',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
function representativeOpenApi(suffix) {
|
||||
const safeSuffix = suffix.replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
return REPRESENTATIVE_OPENAPI
|
||||
.replace('operationId: listRates', `operationId: listRates_${safeSuffix}`)
|
||||
.replace('operationId: getHealth', `operationId: getHealth_${safeSuffix}`);
|
||||
}
|
||||
|
||||
function importContext(report, overrides = {}) {
|
||||
return Object.assign({
|
||||
application_idempotency_key: report.idempotency_key,
|
||||
plan_digest: report.plan_digest,
|
||||
report,
|
||||
choices: report.outcomes.map((outcome) => ({
|
||||
key: outcome.key,
|
||||
name: outcome.name,
|
||||
outcome: outcome.outcome,
|
||||
operation_id: outcome.operation_id,
|
||||
version: outcome.version,
|
||||
reason: outcome.reason,
|
||||
selectable: ['created', 'versioned', 'renamed'].includes(outcome.outcome),
|
||||
})),
|
||||
selected_operation_id: null,
|
||||
selected_operation_version: null,
|
||||
drift: null,
|
||||
}, overrides);
|
||||
}
|
||||
|
||||
function registeredResponse(snapshot, context) {
|
||||
return Object.assign({}, snapshot, {
|
||||
registered: true,
|
||||
revision: snapshot.revision + 1,
|
||||
import_context: context,
|
||||
});
|
||||
}
|
||||
|
||||
function selectedResponse(snapshot, context, operationId, version) {
|
||||
return Object.assign({}, snapshot, {
|
||||
selected: true,
|
||||
revision: snapshot.revision + 1,
|
||||
operation_id: operationId,
|
||||
operation_version: version,
|
||||
import_context: Object.assign({}, context, {
|
||||
selected_operation_id: operationId,
|
||||
selected_operation_version: version,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function onboardingSnapshot(workspaceId, overrides = {}) {
|
||||
return {
|
||||
schema_version: 1,
|
||||
workspace_id: workspaceId,
|
||||
revision: 7,
|
||||
status: 'in_progress',
|
||||
completed: false,
|
||||
eligible_since: '2026-10-03T08:00:00Z',
|
||||
steps: [
|
||||
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
|
||||
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
|
||||
],
|
||||
operation_id: null,
|
||||
operation_version: null,
|
||||
agent_id: null,
|
||||
catalog_revision: null,
|
||||
platform_api_key_id: null,
|
||||
mcp_endpoint: 'http://127.0.0.1:3302/mcp',
|
||||
first_call: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function candidate(name, overrides = {}) {
|
||||
const draft = {
|
||||
name,
|
||||
display_name: name,
|
||||
category: 'default',
|
||||
target: { method: 'GET', path: '/' + name, server_url: 'https://api.example.test' },
|
||||
input_schema: { type: 'object', properties: {} },
|
||||
output_schema: { type: 'object', properties: {} },
|
||||
input_mapping: [],
|
||||
output_mapping: [],
|
||||
tool_description: {},
|
||||
wizard_state: null,
|
||||
};
|
||||
return Object.assign(
|
||||
{
|
||||
key: 'GET /' + name,
|
||||
method: 'GET',
|
||||
path: '/' + name,
|
||||
status: 'actionable',
|
||||
operation_id: null,
|
||||
suggested_name: name,
|
||||
suggested_display_name: name,
|
||||
description: 'ATDD candidate',
|
||||
category: 'default',
|
||||
input_fields: 0,
|
||||
output_fields: 1,
|
||||
server_urls: ['https://api.example.test'],
|
||||
source_location: { pointer: '/paths/~1' + name + '/get' },
|
||||
findings: [],
|
||||
security_requirements: { source: 'none', alternatives: [] },
|
||||
security_schemes: {},
|
||||
draft,
|
||||
},
|
||||
overrides,
|
||||
);
|
||||
}
|
||||
|
||||
function previewResponse(operations, extra = {}) {
|
||||
const base = {
|
||||
job_id: 'imp_e2e_onboarding_215',
|
||||
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
preview: {
|
||||
source: { format: 'openapi', version: '3.0.3', title: 'Onboarding ATDD', servers: ['https://api.example.test'] },
|
||||
groups: [{ key: 'default', title: 'Default', operations }],
|
||||
findings: [],
|
||||
conflicts: [],
|
||||
},
|
||||
security_profile_choices: [],
|
||||
};
|
||||
return Object.assign(base, extra, {
|
||||
preview: Object.assign(base.preview, extra.preview || {}),
|
||||
});
|
||||
}
|
||||
|
||||
function planResponse(candidates, overrides = {}) {
|
||||
return Object.assign(
|
||||
{
|
||||
plan_reference: 'plan_e2e_onboarding_215',
|
||||
plan_digest: 'a'.repeat(64),
|
||||
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
selection_mode: 'full',
|
||||
counts: { selected: candidates.length, excluded: 0, actionable: candidates.length, blocked: 0 },
|
||||
candidates,
|
||||
},
|
||||
overrides,
|
||||
);
|
||||
}
|
||||
|
||||
function applyReport(outcomes, overrides = {}) {
|
||||
return Object.assign(
|
||||
{
|
||||
schema_version: 'import-plan-apply-report-v1',
|
||||
status: 'applied',
|
||||
plan_id: 'plan_e2e_onboarding_215',
|
||||
plan_digest: 'a'.repeat(64),
|
||||
job_id: 'imp_e2e_onboarding_215',
|
||||
idempotency_key: 'onboarding:apply:1',
|
||||
source_id: 'src_e2e_onboarding',
|
||||
source_digest: 'b'.repeat(64),
|
||||
dependencies: [],
|
||||
counts: { created: outcomes.length, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 0 },
|
||||
outcomes,
|
||||
summary: 'Plan applied',
|
||||
recovery: 'none',
|
||||
applied_at: '2026-10-03T08:05:00Z',
|
||||
},
|
||||
overrides,
|
||||
);
|
||||
}
|
||||
|
||||
async function routeOnboarding(page, snapshot) {
|
||||
await page.route(
|
||||
/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\/events|\/reset-selection)?(?:\?.*)?$/,
|
||||
async (route) => {
|
||||
if (route.request().method() === 'GET') {
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(snapshot) });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(Object.assign({ accepted: true }, snapshot)),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function routePreview(page, body, status = 200) {
|
||||
await page.route(/\/imports\/openapi\/preview(?:\?.*)?$/, (route) => route.fulfill({
|
||||
status,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body),
|
||||
}));
|
||||
}
|
||||
|
||||
async function routePlanCreate(page, body, status = 200) {
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/plans(?:\?.*)?$/, (route) => route.fulfill({
|
||||
status,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body),
|
||||
}));
|
||||
}
|
||||
|
||||
async function routeApply(page, body, status = 200) {
|
||||
await page.route(/\/imports\/openapi\/[^/]+\/apply(?:\?.*)?$/, async (route) => {
|
||||
const requestBody = route.request().postDataJSON();
|
||||
const responseBody = typeof body === 'function' ? body(requestBody) : body;
|
||||
await route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(responseBody) });
|
||||
});
|
||||
}
|
||||
|
||||
async function openOnboarding(page) {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
await routeOnboarding(page, onboardingSnapshot(workspace.id));
|
||||
await page.goto('/?onboarding=1');
|
||||
const checklist = page.getByTestId('onboarding-checklist');
|
||||
if (!(await checklist.isVisible())) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
await expect(checklist).toBeVisible();
|
||||
return workspace;
|
||||
}
|
||||
|
||||
async function chooseOpenApiPath(page) {
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
}
|
||||
|
||||
async function uploadPreview(page, document = REPRESENTATIVE_OPENAPI) {
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'openapi.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from(document),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
}
|
||||
|
||||
function parseMcpResponse(response) {
|
||||
return response.text().then((text) => {
|
||||
const dataLine = text.split(/\r?\n/).find((line) => line.startsWith('data:'));
|
||||
return JSON.parse(dataLine ? dataLine.slice(5).trim() : text);
|
||||
});
|
||||
}
|
||||
|
||||
async function mcpPost(request, endpoint, key, payload, sessionId) {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${key}`,
|
||||
Accept: 'application/json, text/event-stream',
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (sessionId) {
|
||||
headers['MCP-Session-Id'] = sessionId;
|
||||
headers['MCP-Protocol-Version'] = '2025-06-18';
|
||||
}
|
||||
return request.post(endpoint, { headers, data: payload });
|
||||
}
|
||||
|
||||
test.describe('Story 2.15 OpenAPI guided onboarding acceptance', () => {
|
||||
test('[P1] AC-1 a protected non-Operations entry safely routes to canonical OpenAPI and preserves same-origin return context', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
await routeOnboarding(page, onboardingSnapshot(workspace.id));
|
||||
await page.goto('/agents?onboarding=1');
|
||||
const trigger = page.getByTestId('onboarding-trigger');
|
||||
if (!await trigger.isVisible()) await expect(trigger).toBeVisible();
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) await trigger.click();
|
||||
await expect(page.getByTestId('onboarding-openapi-path')).toBeVisible();
|
||||
expect(await page.evaluate(() => Boolean(window.CrankOpenApiImport))).toBe(false);
|
||||
|
||||
// Without the Operations importer bundle, the visible onboarding entry
|
||||
// routes to Operations with a bounded, same-origin return hint.
|
||||
const operationsNavigation = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url());
|
||||
return request.isNavigationRequest()
|
||||
&& url.pathname === '/'
|
||||
&& url.searchParams.get('onboarding_openapi') === '1';
|
||||
});
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
const navigation = await operationsNavigation;
|
||||
expect(new URL(navigation.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
|
||||
expect(new URL(page.url()).pathname).toBe('/');
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-file')).toBeAttached();
|
||||
const returnHint = new URL(page.url()).searchParams.get('return');
|
||||
expect(returnHint).toBe('/agents?onboarding=1');
|
||||
expect(returnHint.length).toBeLessThanOrEqual(256);
|
||||
const returnContext = await page.getByTestId('onboarding-return-context').textContent();
|
||||
expect(returnContext).toBe('/agents?onboarding=1');
|
||||
expect(returnContext).not.toContain('://');
|
||||
expect(new URL(page.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
|
||||
});
|
||||
|
||||
test('[P1] AC-2 guided preview shows methods, findings, the exact proposed Operation and apply consequences without hiding blockers', async ({ page }) => {
|
||||
await openOnboarding(page);
|
||||
const actionable = candidate('onboarding-rates');
|
||||
const blocked = candidate('onboarding-blocked', {
|
||||
status: 'blocked',
|
||||
findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: 'GET /onboarding-blocked', source_location: { pointer: '/paths/~1onboarding-blocked/post' } }],
|
||||
});
|
||||
await routePreview(page, previewResponse([actionable, blocked], {
|
||||
preview: { findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: blocked.key, source_location: { pointer: '/paths/~1onboarding-blocked/post' } }] },
|
||||
}));
|
||||
await chooseOpenApiPath(page);
|
||||
await uploadPreview(page);
|
||||
|
||||
// Criterion-defining assertion: the exact proposed Operation is visible for the selected candidate.
|
||||
await expect(page.locator('#openapi-import-groups')).toContainText(actionable.suggested_name);
|
||||
await expect(page.locator('#openapi-import-groups')).toContainText('GET');
|
||||
await expect(page.locator('[data-testid="openapi-import-finding-code"]')).toContainText('unsupported_xml_body');
|
||||
// A blocker cannot be hidden to continue: the blocker summary is shown and
|
||||
// creation stays unavailable until the finding is resolved.
|
||||
await expect(page.locator('[data-testid="openapi-import-blockers"]')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-create')).toBeDisabled();
|
||||
});
|
||||
|
||||
test('[P1] AC-3 security mapping requires only a canonical Auth Profile reference and never stores a raw credential', async ({ page }) => {
|
||||
await openOnboarding(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const profileName = uniqueName('onboarding_auth_profile');
|
||||
const secretValue = SECRET_CANARY + '_' + uniqueName('value');
|
||||
const secret = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
|
||||
{ name: uniqueName('onboarding_secret'), kind: 'token', value: secretValue },
|
||||
);
|
||||
const profile = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
|
||||
{
|
||||
name: profileName,
|
||||
kind: 'bearer',
|
||||
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
|
||||
},
|
||||
);
|
||||
await chooseOpenApiPath(page);
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'onboarding-security.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from([
|
||||
'openapi: 3.0.3',
|
||||
`info: { title: ${profileName}, version: "1" }`,
|
||||
'servers: [{ url: "http://127.0.0.1:3310" }]',
|
||||
'paths:',
|
||||
' /rates:',
|
||||
' get:',
|
||||
' operationId: onboarding_secured_rates',
|
||||
' security:',
|
||||
' - bearerAuth: []',
|
||||
' responses:',
|
||||
" '200': { description: OK }",
|
||||
'components:',
|
||||
' securitySchemes:',
|
||||
' bearerAuth: { type: http, scheme: bearer }',
|
||||
].join('\n')),
|
||||
});
|
||||
const previewResponsePromise = page.waitForResponse((response) => response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
const previewResponseReal = await previewResponsePromise;
|
||||
expect(previewResponseReal.status()).toBe(200);
|
||||
const previewArtifact = await previewResponseReal.json();
|
||||
expect(JSON.stringify(previewArtifact)).not.toContain(secretValue);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
|
||||
// Criterion-defining assertion: the canonical Auth Profile picker is shown.
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
|
||||
await bearerOption.waitFor({ state: 'attached' });
|
||||
const bearerIndex = await bearerOption.getAttribute('value');
|
||||
expect(bearerIndex).toMatch(/^\d+$/);
|
||||
await alternative.selectOption(bearerIndex);
|
||||
const profilePicker = page.locator('#openapi-import-groups [data-openapi-security-profile]').first();
|
||||
await expect(profilePicker).toBeVisible();
|
||||
await profilePicker.selectOption(profile.id);
|
||||
|
||||
const planRequest = page.waitForRequest((request) => request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
const sentPlanRequest = await planRequest;
|
||||
const planPayload = sentPlanRequest.postDataJSON();
|
||||
expect(planPayload.decisions[0]).toMatchObject({ auth_profile_id: profile.id });
|
||||
expect(planPayload.decisions[0].security_alternative_index).toEqual(expect.any(Number));
|
||||
const planResponseReal = await sentPlanRequest.response();
|
||||
expect(planResponseReal.ok(), await planResponseReal.text()).toBe(true);
|
||||
const planArtifact = await planResponseReal.json();
|
||||
expect(JSON.stringify(planPayload)).not.toContain(secretValue);
|
||||
|
||||
// The canonical artifact, onboarding projection and browser state carry the
|
||||
// typed reference only. Secret material remains server-side.
|
||||
const onboarding = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
|
||||
const browserState = await page.evaluate(() => JSON.stringify({
|
||||
local: Object.values(localStorage),
|
||||
session: Object.values(sessionStorage),
|
||||
url: location.href,
|
||||
body: document.body.innerText,
|
||||
}));
|
||||
for (const value of [JSON.stringify(previewArtifact), JSON.stringify(planArtifact), JSON.stringify(onboarding), browserState, JSON.stringify(planPayload)]) {
|
||||
expect(value).not.toContain(secretValue);
|
||||
}
|
||||
expect(JSON.stringify(planPayload)).toContain(profile.id);
|
||||
expect(JSON.stringify(planArtifact)).toContain(profile.id);
|
||||
await expect(page.locator('body')).not.toContainText(secretValue);
|
||||
});
|
||||
|
||||
test('[P1] AC-4 after atomic apply of multiple Drafts the onboarding explicitly selects one actionable Draft and never auto-publishes', async ({ page }) => {
|
||||
await openOnboarding(page);
|
||||
const first = candidate('onboarding-rates');
|
||||
const second = candidate('onboarding-currencies');
|
||||
await routePreview(page, previewResponse([first, second]));
|
||||
await routePlanCreate(page, planResponse([
|
||||
{ key: first.key, name: first.suggested_name, state: 'actionable', action: 'create' },
|
||||
{ key: second.key, name: second.suggested_name, state: 'actionable', action: 'create' },
|
||||
]));
|
||||
const outcomes = [
|
||||
{ key: first.key, name: first.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
|
||||
{ key: second.key, name: second.suggested_name, outcome: 'created', operation_id: 'op_onboarding_currencies', version: 1, reason: null },
|
||||
];
|
||||
let report;
|
||||
const initial = onboardingSnapshot((await getCurrentWorkspace(page)).id);
|
||||
let context;
|
||||
const registrationRequests = [];
|
||||
const selectionRequests = [];
|
||||
let latestOnboarding = initial;
|
||||
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\?.*)?$/, async (route) => {
|
||||
if (route.request().method() !== 'GET') return route.fallback();
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(latestOnboarding) });
|
||||
});
|
||||
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
|
||||
registrationRequests.push(route.request().postDataJSON());
|
||||
context = importContext(report);
|
||||
const response = registeredResponse(initial, context);
|
||||
latestOnboarding = response;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
|
||||
});
|
||||
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
selectionRequests.push(payload);
|
||||
const response = selectedResponse(latestOnboarding, context, payload.operation_id, payload.operation_version);
|
||||
latestOnboarding = response;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
|
||||
});
|
||||
await routeApply(page, (payload) => {
|
||||
report = applyReport(outcomes, {
|
||||
idempotency_key: payload.idempotency_key,
|
||||
plan_digest: payload.plan_digest,
|
||||
});
|
||||
return report;
|
||||
});
|
||||
|
||||
const publishRequests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\/publish(?:es)?(?:\?|$)/.test(new URL(request.url()).pathname)) publishRequests.push(request.url());
|
||||
});
|
||||
|
||||
await chooseOpenApiPath(page);
|
||||
await uploadPreview(page);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
|
||||
|
||||
// Criterion-defining assertion: an explicit Draft chooser lists the created Drafts.
|
||||
const chooser = page.getByTestId('onboarding-import-draft-choice');
|
||||
await expect(chooser).toBeVisible();
|
||||
await expect(chooser).toContainText(first.suggested_name);
|
||||
await expect(chooser).toContainText(second.suggested_name);
|
||||
// The full import report remains available and nothing is auto-published.
|
||||
await expect(page.locator('#openapi-import-result')).toBeVisible();
|
||||
expect(publishRequests).toEqual([]);
|
||||
await expect.poll(() => registrationRequests.length).toBe(1);
|
||||
expect(registrationRequests[0]).toEqual({
|
||||
application_idempotency_key: report.idempotency_key,
|
||||
plan_digest: report.plan_digest,
|
||||
expected_revision: initial.revision,
|
||||
});
|
||||
expect(context.report).toEqual(report);
|
||||
|
||||
const chosen = page.waitForRequest((request) => request.method() === 'POST' && /\/onboarding\/select-draft$/.test(request.url()));
|
||||
const firstChoice = chooser.locator('.onboarding-import-draft-option-row')
|
||||
.filter({ hasText: first.suggested_name }).getByRole('button');
|
||||
await firstChoice.click();
|
||||
const selectedRequest = await chosen;
|
||||
expect(selectedRequest.postDataJSON()).toEqual({
|
||||
application_idempotency_key: report.idempotency_key,
|
||||
plan_digest: report.plan_digest,
|
||||
operation_id: 'op_onboarding_rates',
|
||||
operation_version: 1,
|
||||
expected_revision: initial.revision + 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('[P1] AC-5 refresh or source correction restores the checklist from authoritative state without duplicating a version and requires a new preview for a changed digest', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const pendingReport = applyReport([
|
||||
{ key: 'GET /onboarding-rates', name: 'onboarding_rates', outcome: 'created', operation_id: 'op_imported_rates', version: 1, reason: null },
|
||||
{ key: 'GET /onboarding-blocked', name: 'onboarding_blocked', outcome: 'rejected', operation_id: null, version: null, reason: 'unsupported_xml_body' },
|
||||
], {
|
||||
idempotency_key: 'ws_default:apply:openapi_onboarding:v1',
|
||||
counts: { created: 1, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 1 },
|
||||
});
|
||||
const imported = onboardingSnapshot(workspace.id, {
|
||||
revision: 9,
|
||||
operation_id: null,
|
||||
operation_version: null,
|
||||
import_context: importContext(pendingReport),
|
||||
steps: [
|
||||
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
|
||||
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
|
||||
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
|
||||
],
|
||||
});
|
||||
await routeOnboarding(page, imported);
|
||||
await page.goto('/?onboarding=1');
|
||||
|
||||
const checklist = page.getByTestId('onboarding-checklist');
|
||||
if (!(await checklist.isVisible())) await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(checklist.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
|
||||
await expect(page.getByTestId('onboarding-import-context')).toContainText('onboarding_rates');
|
||||
|
||||
// A full page refresh must recover the pending report and every outcome
|
||||
// from the authoritative onboarding projection before explicit selection.
|
||||
await page.reload();
|
||||
const resumed = page.getByTestId('onboarding-checklist');
|
||||
if (!(await resumed.isVisible())) await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(resumed.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-result')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="created"]')).toContainText('onboarding_rates');
|
||||
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="rejected"]')).toContainText('onboarding_blocked');
|
||||
const restoredChooser = page.getByTestId('onboarding-import-draft-choice');
|
||||
await expect(restoredChooser).toContainText('onboarding_rates');
|
||||
await expect(restoredChooser).toContainText(localized(
|
||||
'This imported item needs review in the wizard.',
|
||||
'Этот импортированный элемент нужно проверить в мастере.',
|
||||
));
|
||||
|
||||
// A changed source digest yields visible 409 recovery and disables Apply
|
||||
// until a fresh preview/confirmation is created.
|
||||
const resumeCandidate = candidate('onboarding-rates');
|
||||
await page.locator('[data-openapi-close]').last().click();
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
await routePreview(page, previewResponse([resumeCandidate]));
|
||||
await uploadPreview(page);
|
||||
await routePlanCreate(page, planResponse([
|
||||
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
|
||||
], { plan_reference: 'plan_e2e_onboarding_215_fresh', plan_digest: 'c'.repeat(64) }));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
|
||||
await page.route(/\/imports\/openapi\/plans\/[^/]+(?:\?.*)?$/, (route) => route.fulfill({
|
||||
status: 409,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_stale', message: 'Import source changed', context: { recovery: 'preview', reason: 'source_digest_changed' } } }),
|
||||
}));
|
||||
await page.locator('[data-testid="openapi-import-plan-reopen"]').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-plan-stale"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="openapi-import-plan-apply"]')).toBeDisabled();
|
||||
await expect(page.locator('#openapi-import-status')).not.toHaveText('');
|
||||
|
||||
await page.locator('[data-openapi-close]').last().click();
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
await routePreview(page, previewResponse([resumeCandidate], { job_id: 'imp_e2e_onboarding_215_recovered' }));
|
||||
await uploadPreview(page);
|
||||
await routePlanCreate(page, planResponse([
|
||||
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
|
||||
], { plan_reference: 'plan_e2e_onboarding_215_recovered', plan_digest: 'd'.repeat(64) }));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
|
||||
await page.locator('[data-openapi-close]').last().click();
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
const selectionRequests = [];
|
||||
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
selectionRequests.push(payload);
|
||||
if (selectionRequests.length === 1) {
|
||||
await route.fulfill({
|
||||
status: 409,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'onboarding_stale_revision', message: 'Reload required', context: { recovery: 'reload' } } }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(selectedResponse(imported, importContext(pendingReport), payload.operation_id, payload.operation_version)) });
|
||||
});
|
||||
const continueButton = page.getByTestId('onboarding-import-draft-choice').getByRole('button').first();
|
||||
await continueButton.click();
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(/reload|latest report|state changed|обнов|измен/i);
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await expect(continueButton).toBeVisible();
|
||||
await continueButton.click();
|
||||
await page.waitForURL(/\/wizard\/\?mode=edit/);
|
||||
expect(selectionRequests).toHaveLength(2);
|
||||
for (const payload of selectionRequests) {
|
||||
expect(payload).toEqual({
|
||||
application_idempotency_key: pendingReport.idempotency_key,
|
||||
plan_digest: pendingReport.plan_digest,
|
||||
operation_id: 'op_imported_rates',
|
||||
operation_version: 1,
|
||||
expected_revision: imported.revision,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('[P1] AC-6 presentation event requests carry only the bounded client contract and make no external calls', async ({ page }) => {
|
||||
const requests = [];
|
||||
page.on('request', (request) => requests.push({ url: request.url(), postData: request.postData() }));
|
||||
const workspace = await openOnboarding(page);
|
||||
const actionable = candidate('onboarding-rates');
|
||||
await routePreview(page, previewResponse([actionable]));
|
||||
await routePlanCreate(page, planResponse([{ key: actionable.key, name: actionable.suggested_name, state: 'actionable', action: 'create' }]));
|
||||
let report;
|
||||
await routeApply(page, (payload) => {
|
||||
report = applyReport([
|
||||
{ key: actionable.key, name: actionable.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
|
||||
], { idempotency_key: payload.idempotency_key, plan_digest: payload.plan_digest });
|
||||
return report;
|
||||
});
|
||||
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(registeredResponse(onboardingSnapshot(workspace.id), importContext(report))) });
|
||||
});
|
||||
|
||||
await chooseOpenApiPath(page);
|
||||
await uploadPreview(page);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
|
||||
|
||||
// Presentation requests are client-owned UI signals with a closed payload.
|
||||
const eventPosts = requests.filter((item) => /\/onboarding\/events(?:\?|$)/.test(item.url));
|
||||
expect(eventPosts.length).toBeGreaterThan(0);
|
||||
eventPosts.forEach((item) => {
|
||||
const payload = JSON.parse(item.postData || '{}');
|
||||
expect(Object.keys(payload).sort()).toEqual(['event', 'expected_revision', 'idempotency_key']);
|
||||
expect(payload.event).toMatch(/^(started|resumed|dismissed|abandoned)$/);
|
||||
expect(payload.idempotency_key).toMatch(/^ui:/);
|
||||
expect(typeof payload.expected_revision).toBe('number');
|
||||
expect(JSON.stringify(payload)).not.toContain('openapi: 3.0');
|
||||
expect(JSON.stringify(payload)).not.toContain(SECRET_CANARY);
|
||||
expect(Object.keys(payload)).not.toContain('user_id');
|
||||
});
|
||||
// ...and keep all telemetry local unless the operator opts in (no external egress).
|
||||
const external = requests.filter((item) => !/^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//.test(item.url));
|
||||
expect(external).toEqual([]);
|
||||
// Server-owned properties for all three funnel milestones, including the
|
||||
// exact keys and raw-data exclusion, are asserted against stored PG rows by
|
||||
// `crates/crank-registry/tests/integration/onboarding_import_selection.rs`.
|
||||
});
|
||||
|
||||
for (const locale of ['ru', 'en']) {
|
||||
test(`[P1] AC-7 ${locale} OpenAPI import reaches an authoritative public MCP call after selection reset`, async ({ page, request }) => {
|
||||
test.setTimeout(180_000);
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
// The shared E2E admin workspace may have terminal evidence from an earlier
|
||||
// suite. Reset only its canonical onboarding selection; every milestone
|
||||
// below is recreated through the real import/UI/public endpoint journey.
|
||||
let reset;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
const prior = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
|
||||
reset = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding/reset-selection`,
|
||||
{ expected_revision: prior.revision },
|
||||
[200, 409],
|
||||
);
|
||||
if (!reset.error) break;
|
||||
expect(reset.error.code).toBe('onboarding_stale_revision');
|
||||
}
|
||||
expect(reset.error).toBeUndefined();
|
||||
const resetProjection = reset.onboarding || reset;
|
||||
expect(resetProjection.status).not.toBe('complete');
|
||||
expect(resetProjection.import_context).toBeNull();
|
||||
expect(resetProjection.first_call).toBeNull();
|
||||
|
||||
const suffix = uniqueName('openapi_onboarding').replace(/_/g, '-');
|
||||
const agentSlug = `onboarding-${suffix}`.toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
|
||||
await page.goto('/?onboarding_openapi=1&return=%2F');
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await expect(page.locator('#openapi-import-modal')).toContainText(locale === 'ru' ? 'Импорт OpenAPI' : 'Import OpenAPI');
|
||||
await uploadPreview(page, representativeOpenApi(suffix));
|
||||
|
||||
// Import preview, atomic apply of multiple candidates, and full report are
|
||||
// all exercised against the real import API.
|
||||
await expect(page.locator('#openapi-import-groups')).toContainText(/list.?rates/i);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
const importContextRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/import-context$/.test(r.url()));
|
||||
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
|
||||
await expect(page.locator('#openapi-import-result')).toBeVisible();
|
||||
|
||||
const registration = await importContextRequest;
|
||||
expect(registration.postDataJSON()).toMatchObject({
|
||||
application_idempotency_key: expect.any(String),
|
||||
plan_digest: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
expected_revision: expect.any(Number),
|
||||
});
|
||||
expect(await registration.response().then((response) => response.ok())).toBe(true);
|
||||
|
||||
// Reload while the import context is still pending, then recover the full
|
||||
// immutable report and every selectable/non-selectable outcome from GET.
|
||||
await page.reload();
|
||||
const checklistAfterReload = page.getByTestId('onboarding-checklist');
|
||||
if (!await checklistAfterReload.isVisible()) await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(page.getByTestId('onboarding-import-context')).toContainText(/list.?rates/i);
|
||||
await page.getByTestId('onboarding-openapi-path').click();
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-result')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcomes')).toContainText(/list.?rates/i);
|
||||
const pendingContext = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
|
||||
expect(pendingContext.import_context.report.outcomes.length).toBeGreaterThan(1);
|
||||
expect(pendingContext.import_context.selected_operation_id).toBeNull();
|
||||
expect(pendingContext.import_context.selected_operation_version).toBeNull();
|
||||
expect(pendingContext.import_context.choices).toHaveLength(2);
|
||||
expect(pendingContext.import_context.choices.every((choice) => choice.selectable)).toBe(true);
|
||||
expect(pendingContext.import_context.report.outcomes.map((outcome) => outcome.outcome).sort()).toEqual(['created', 'created']);
|
||||
const selectedChoice = pendingContext.import_context.choices.find((choice) => /list.?rates/i.test(choice.name));
|
||||
expect(selectedChoice).toBeTruthy();
|
||||
|
||||
const chooser = page.getByTestId('onboarding-import-draft-choice');
|
||||
await expect(chooser).toBeVisible();
|
||||
const draftChoice = chooser.locator('.onboarding-import-draft-choice-list .onboarding-import-draft-option-row')
|
||||
.filter({ hasText: /list.?rates/i }).getByRole('button');
|
||||
await expect(draftChoice).toBeVisible();
|
||||
const selectDraftRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/select-draft$/.test(r.url()));
|
||||
const selectedVersionResponse = page.waitForResponse((r) => r.request().method() === 'GET'
|
||||
&& r.url().includes(`/operations/${selectedChoice.operation_id}/versions/${selectedChoice.version}`));
|
||||
await draftChoice.click();
|
||||
const selection = await selectDraftRequest;
|
||||
const loadedVersion = await selectedVersionResponse;
|
||||
expect(loadedVersion.ok()).toBe(true);
|
||||
const importedVersion = await loadedVersion.json();
|
||||
expect(importedVersion.snapshot.target).toMatchObject({ kind: 'rest', method: 'GET', path_template: '/rates', base_url: 'http://127.0.0.1:3310' });
|
||||
expect(selection.postDataJSON()).toMatchObject({
|
||||
application_idempotency_key: registration.postDataJSON().application_idempotency_key,
|
||||
plan_digest: registration.postDataJSON().plan_digest,
|
||||
operation_id: expect.any(String),
|
||||
operation_version: expect.any(Number),
|
||||
expected_revision: expect.any(Number),
|
||||
});
|
||||
|
||||
await page.waitForFunction(() => window.CrankWizardReady === true && window.currentStep === 1);
|
||||
await expect(page.locator('[data-testid="wizard-protocol-rest"]')).toBeVisible();
|
||||
const selectedOperationId = selection.postDataJSON().operation_id;
|
||||
const selectedVersion = selection.postDataJSON().operation_version;
|
||||
await expect(page).toHaveURL(new RegExp(`operationId=${selectedOperationId}`));
|
||||
expect(new URL(page.url()).searchParams.get('operationVersion')).toBe(String(selectedVersion));
|
||||
await expect(page.locator('#tool-name')).toHaveValue(/list.?rates/i);
|
||||
const operationWrites = [];
|
||||
page.on('request', (r) => {
|
||||
const path = new URL(r.url()).pathname;
|
||||
const createsOperation = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations$/.test(path);
|
||||
const updatesOperation = r.method() === 'PATCH' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+$/.test(path);
|
||||
const createsVersion = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+\/versions$/.test(path);
|
||||
if (createsOperation || updatesOperation || createsVersion) operationWrites.push({ method: r.method(), url: r.url() });
|
||||
});
|
||||
// The selected imported Draft is edited in normal wizard edit mode. A
|
||||
// no-op lifecycle save must retain its exact version without creating a
|
||||
// duplicate, then test and publish that same version.
|
||||
const testedVersions = [];
|
||||
const publishedVersions = [];
|
||||
page.on('request', (r) => {
|
||||
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`)) {
|
||||
testedVersions.push(r.postDataJSON().version);
|
||||
}
|
||||
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`)) {
|
||||
publishedVersions.push(r.postDataJSON().version);
|
||||
}
|
||||
});
|
||||
const testResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`));
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
|
||||
await page.locator('#wizard-run-test').click();
|
||||
const tested = await testResponse;
|
||||
expect(tested.ok(), await tested.text()).toBe(true);
|
||||
const testResult = await tested.json();
|
||||
expect(testResult.ok, JSON.stringify(testResult)).toBe(true);
|
||||
await expect.poll(() => testedVersions).toEqual([selectedVersion]);
|
||||
await expect(page.locator('#wizard-test-request-id')).not.toHaveText('');
|
||||
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
const qualityResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes('/operations/analyze-quality'));
|
||||
const publishResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`));
|
||||
await page.locator('#wizard-publish-operation').click();
|
||||
const quality = await qualityResponse;
|
||||
expect(quality.ok(), await quality.text()).toBe(true);
|
||||
expect((await publishResponse).ok()).toBe(true);
|
||||
await expect.poll(() => publishedVersions).toEqual([selectedVersion]);
|
||||
expect(operationWrites).toEqual([]);
|
||||
|
||||
const agentPage = `/agents?onboarding=1&action=create&operationId=${encodeURIComponent(selectedOperationId)}&operationVersion=${selectedVersion}`;
|
||||
await page.goto(agentPage);
|
||||
await expect(page.locator('.drawer')).toHaveClass(/open/);
|
||||
const identityInputs = page.locator('.drawer-section').first().locator('input.form-input');
|
||||
await identityInputs.nth(0).fill('OpenAPI onboarding Agent');
|
||||
await identityInputs.nth(1).fill(agentSlug);
|
||||
await page.locator('.drawer-section').first().locator('textarea').fill('Agent created from an explicitly selected OpenAPI Draft.');
|
||||
await expect(page.locator('.ops-picker-item.selected')).toContainText(/list.?rates/i);
|
||||
const createAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/agents$/.test(r.url()));
|
||||
const bindAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/bindings$/.test(r.url()));
|
||||
const publishAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/publish$/.test(r.url()));
|
||||
await page.locator('.drawer-footer .btn-primary-sm').click();
|
||||
const agentResponse = await createAgentResponse;
|
||||
expect(agentResponse.ok(), await agentResponse.text()).toBe(true);
|
||||
expect((await bindAgentResponse).ok()).toBe(true);
|
||||
expect((await publishAgentResponse).ok()).toBe(true);
|
||||
const agentId = (await agentResponse.json()).agent_id;
|
||||
|
||||
await page.goto(`/api-keys?onboarding=1&action=create&agentId=${encodeURIComponent(agentId)}`);
|
||||
await expect(page.locator('#agent-select')).toHaveValue(agentId);
|
||||
await expect(page.locator('#modal-create')).toHaveClass(/open/);
|
||||
await page.locator('#new-key-name').fill(uniqueName('openapi_onboarding_key'));
|
||||
const keyResponsePromise = page.waitForResponse((r) => r.request().method() === 'POST' && /\/platform-api-keys$/.test(r.url()));
|
||||
await page.locator('#modal-confirm-btn').click();
|
||||
const keyResponse = await keyResponsePromise;
|
||||
expect(keyResponse.ok(), await keyResponse.text()).toBe(true);
|
||||
const keyBody = await keyResponse.json();
|
||||
const rawKey = await page.locator('#reveal-key-value').textContent();
|
||||
const keyId = keyBody.api_key.id || keyBody.api_key.api_key.id;
|
||||
const endpoint = await page.locator('#onboarding-connection-clients > code').textContent();
|
||||
expect(rawKey).toMatch(/^crk_/);
|
||||
await expect(page.locator('body')).not.toContainText(SECRET_CANARY);
|
||||
|
||||
// An unauthorized public call must not advance the authoritative checklist.
|
||||
const denied = await mcpPost(request, endpoint, SECRET_CANARY, {
|
||||
jsonrpc: '2.0', id: 90, method: 'tools/call', params: { name: 'unavailable', arguments: {} },
|
||||
});
|
||||
expect([401, 403]).toContain(denied.status());
|
||||
const beforeSuccessfulCall = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
|
||||
expect(beforeSuccessfulCall.status).not.toBe('complete');
|
||||
expect(beforeSuccessfulCall.first_call).toBeNull();
|
||||
|
||||
const initialize = await mcpPost(request, endpoint, rawKey, {
|
||||
jsonrpc: '2.0', id: 1, method: 'initialize', params: {
|
||||
protocolVersion: '2025-06-18', capabilities: {},
|
||||
clientInfo: { name: 'crank-openapi-onboarding-playwright', version: '1.0.0' },
|
||||
},
|
||||
});
|
||||
const initializeBody = await parseMcpResponse(initialize);
|
||||
expect(initialize.ok(), JSON.stringify(initializeBody)).toBe(true);
|
||||
const sessionId = initialize.headers()['mcp-session-id'];
|
||||
expect(sessionId).toBeTruthy();
|
||||
const initialized = await mcpPost(request, endpoint, rawKey, {
|
||||
jsonrpc: '2.0', method: 'notifications/initialized', params: {},
|
||||
}, sessionId);
|
||||
expect([200, 202]).toContain(initialized.status());
|
||||
const listed = await mcpPost(request, endpoint, rawKey, {
|
||||
jsonrpc: '2.0', id: 2, method: 'tools/list', params: {},
|
||||
}, sessionId);
|
||||
expect(listed.ok()).toBe(true);
|
||||
const listedBody = await parseMcpResponse(listed);
|
||||
const selectedTool = listedBody.result.tools.find((tool) => /list.?rates/i.test(tool.name));
|
||||
expect(selectedTool).toBeTruthy();
|
||||
const toolName = selectedTool.name;
|
||||
const called = await mcpPost(request, endpoint, rawKey, {
|
||||
jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: toolName, arguments: {} },
|
||||
}, sessionId);
|
||||
expect(called.ok()).toBe(true);
|
||||
const calledBody = await parseMcpResponse(called);
|
||||
expect(calledBody.error).toBeUndefined();
|
||||
expect(calledBody.result.isError).not.toBe(true);
|
||||
|
||||
const progress = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
|
||||
expect(progress.status).toBe('complete');
|
||||
expect(progress.operation_id).toBe(selectedOperationId);
|
||||
expect(progress.operation_version).toBe(selectedVersion);
|
||||
expect(progress.agent_id).toBe(agentId);
|
||||
expect(progress.platform_api_key_id).toBe(keyId);
|
||||
expect(progress.first_call.agent_id).toBe(agentId);
|
||||
expect(progress.first_call.key_id).toBe(keyId);
|
||||
expect(progress.first_call.operation_id).toBe(selectedOperationId);
|
||||
expect(progress.first_call.operation_version).toBe(selectedVersion);
|
||||
expect(progress.first_call.tool_name).toBe(toolName);
|
||||
expect(progress.first_call.request_id).toBeTruthy();
|
||||
expect(progress.first_call.trace_id).toMatch(/^[0-9a-f]{32}$/);
|
||||
|
||||
await page.goto('/');
|
||||
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
await expect(page.getByTestId('onboarding-completion')).toContainText(toolName);
|
||||
await expect(page.getByTestId('onboarding-completion')).toContainText(progress.first_call.request_id);
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await expect(page.getByTestId('onboarding-completion')).toBeVisible();
|
||||
await page.reload();
|
||||
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
|
||||
});
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,273 @@
|
||||
// Operator-run AC-11 evidence against a Reference Deployment. This spec is
|
||||
// intentionally separate from the local/mocked Playwright matrix.
|
||||
const fs = require('node:fs');
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { localized, login } = require('./helpers');
|
||||
|
||||
// Remote operator credentials must not enter retry artifacts or failure captures.
|
||||
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
|
||||
test.describe.configure({ retries: 0 });
|
||||
|
||||
const referenceBaseUrl = process.env.PLAYWRIGHT_BASE_URL;
|
||||
const SAMPLE_COUNT = 20;
|
||||
const OPERATION_COUNT = 2000;
|
||||
const MAX_UPLOAD_BYTES = 256 * 1024;
|
||||
const MAX_P95_MS = 2000;
|
||||
|
||||
function openApiDocument(operationCount) {
|
||||
const lines = [
|
||||
'openapi: 3.0.3',
|
||||
'info:',
|
||||
' title: Crank Reference Preview Benchmark',
|
||||
' version: "1.0.0"',
|
||||
'servers:',
|
||||
' - url: https://api.example.test',
|
||||
'paths:',
|
||||
];
|
||||
|
||||
for (let index = 0; index < operationCount; index += 1) {
|
||||
lines.push(` /op-${index}:`);
|
||||
lines.push(' get:');
|
||||
lines.push(' responses:');
|
||||
lines.push(' "200":');
|
||||
lines.push(' description: OK');
|
||||
}
|
||||
|
||||
return Buffer.from(lines.join('\n') + '\n', 'utf8');
|
||||
}
|
||||
|
||||
function percentile95(samples) {
|
||||
const sorted = [...samples].sort((left, right) => left - right);
|
||||
return sorted[Math.ceil(sorted.length * 0.95) - 1];
|
||||
}
|
||||
|
||||
function safeReferenceOrigin(rawUrl) {
|
||||
const url = new URL(rawUrl);
|
||||
if (!['http:', 'https:'].includes(url.protocol)) {
|
||||
throw new Error('PLAYWRIGHT_BASE_URL must use http or https');
|
||||
}
|
||||
if (url.username || url.password || url.search || url.hash) {
|
||||
throw new Error('PLAYWRIGHT_BASE_URL must not contain credentials, query parameters, or fragments');
|
||||
}
|
||||
if (['localhost', '127.0.0.1', '::1'].includes(url.hostname)) {
|
||||
throw new Error('AC-11 Reference benchmark requires a remote PLAYWRIGHT_BASE_URL');
|
||||
}
|
||||
return url.origin;
|
||||
}
|
||||
|
||||
function readReferenceManifest(manifestPath) {
|
||||
if (!manifestPath) {
|
||||
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON is required when PLAYWRIGHT_BASE_URL is set');
|
||||
}
|
||||
|
||||
let manifest;
|
||||
try {
|
||||
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
} catch (_error) {
|
||||
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON must point to a readable valid JSON manifest');
|
||||
}
|
||||
|
||||
const deployment = manifest && manifest.deployment;
|
||||
const loadGenerator = manifest && manifest.load_generator;
|
||||
const browser = manifest && manifest.browser;
|
||||
const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
|
||||
const finiteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const versionHasMajor = (value, major) => nonempty(value) && new RegExp(`^${major}(?:\\.|$)`).test(value.trim());
|
||||
|
||||
if (!deployment || !loadGenerator || !browser) {
|
||||
throw new Error('Reference manifest requires deployment, load_generator, and browser objects');
|
||||
}
|
||||
for (const [name, host] of [['deployment', deployment], ['load_generator', loadGenerator], ['browser', browser]]) {
|
||||
if (!nonempty(host.host_id)) throw new Error(`Reference manifest ${name}.host_id is required`);
|
||||
}
|
||||
if (deployment.host_id.trim() === loadGenerator.host_id.trim()
|
||||
|| deployment.host_id.trim() === browser.host_id.trim()) {
|
||||
throw new Error('Reference manifest requires deployment and load generator/browser on separate hosts');
|
||||
}
|
||||
if (!nonempty(deployment.cpu_model) || !nonempty(deployment.storage_type)
|
||||
|| deployment.storage_type.trim().toLowerCase() !== 'ssd'
|
||||
|| !finiteNumber(deployment.cpu_cores)
|
||||
|| !finiteNumber(deployment.ram_gib) || !finiteNumber(deployment.ssd_iops)
|
||||
|| !finiteNumber(deployment.ssd_throughput_mb_s) || !finiteNumber(deployment.ssd_capacity_gb)
|
||||
|| !finiteNumber(deployment.lan_mbps)
|
||||
|| !versionHasMajor(deployment.postgres_version, 16)
|
||||
|| !versionHasMajor(deployment.valkey_version, 8)) {
|
||||
throw new Error('Reference manifest is missing valid CPU, RAM, database, SSD, or LAN fields');
|
||||
}
|
||||
if (deployment.cpu_cores !== 4 || deployment.ram_gib !== 8
|
||||
|| deployment.ssd_capacity_gb < 100 || deployment.ssd_iops < 3000
|
||||
|| deployment.ssd_throughput_mb_s < 100
|
||||
|| deployment.lan_mbps < 1000) {
|
||||
throw new Error('Reference deployment must meet 4 CPU / 8 GiB RAM, SSD 3000 IOPS / 100 MB/s, and 1 Gbit LAN');
|
||||
}
|
||||
if (!finiteNumber(loadGenerator.cpu_cores) || !finiteNumber(loadGenerator.ram_gib)
|
||||
|| loadGenerator.cpu_cores !== 4 || loadGenerator.ram_gib !== 8) {
|
||||
throw new Error('Reference load_generator must have 4 CPU and 8 GiB RAM');
|
||||
}
|
||||
|
||||
// Emit only the fields needed for benchmark interpretation. Do not copy
|
||||
// arbitrary manifest keys (which could contain credentials) into reports.
|
||||
return {
|
||||
provenance: 'operator_manifest',
|
||||
deployment: {
|
||||
cpu_model: deployment.cpu_model.trim(),
|
||||
cpu_cores: deployment.cpu_cores,
|
||||
ram_gib: deployment.ram_gib,
|
||||
postgres_version: deployment.postgres_version.trim(),
|
||||
valkey_version: deployment.valkey_version.trim(),
|
||||
storage_type: 'SSD',
|
||||
ssd_capacity_gb: deployment.ssd_capacity_gb,
|
||||
ssd_iops: deployment.ssd_iops,
|
||||
ssd_throughput_mb_s: deployment.ssd_throughput_mb_s,
|
||||
lan_mbps: deployment.lan_mbps,
|
||||
},
|
||||
load_generator: { cpu_cores: loadGenerator.cpu_cores, ram_gib: loadGenerator.ram_gib },
|
||||
browser_host_separate_from_deployment: true,
|
||||
};
|
||||
}
|
||||
|
||||
test('[P1][reference] AC-11 measures 20 real 2000-operation preview round trips', async ({ page }, testInfo) => {
|
||||
test.skip(!referenceBaseUrl, 'Set PLAYWRIGHT_BASE_URL to a Reference Deployment to run AC-11 evidence');
|
||||
test.setTimeout(300_000);
|
||||
|
||||
expect(process.env.PLAYWRIGHT_SKIP_WEB_SERVER).toBe('1');
|
||||
const referenceOrigin = safeReferenceOrigin(referenceBaseUrl);
|
||||
const referenceManifest = readReferenceManifest(process.env.CRANK_AC11_REFERENCE_ENV_JSON);
|
||||
const yaml = openApiDocument(OPERATION_COUNT);
|
||||
expect(yaml.byteLength).toBeLessThan(MAX_UPLOAD_BYTES);
|
||||
|
||||
await login(page);
|
||||
await page.waitForFunction(() => Boolean(document.querySelector('[data-testid="onboarding-dismiss"]')));
|
||||
await page.locator('[data-testid="onboarding-dismiss"]').click();
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await expect(page.locator('#openapi-import-modal')).toBeVisible();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'reference-preview-2000.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: yaml,
|
||||
});
|
||||
|
||||
const previewButton = page.locator('#openapi-import-preview');
|
||||
const createButton = page.locator('#openapi-import-create');
|
||||
const rows = page.locator('.openapi-import-operation');
|
||||
const samplesMs = [];
|
||||
let browserEnvironment;
|
||||
|
||||
// Warm the preview once before timing. Warm-up still uses the real remote
|
||||
// preview API.
|
||||
const warmupResponsePromise = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/preview'),
|
||||
);
|
||||
await previewButton.click();
|
||||
const warmupResponse = await warmupResponsePromise;
|
||||
expect(warmupResponse.status(), 'warm-up preview status').toBe(200);
|
||||
expect(new URL(warmupResponse.url()).origin).toBe(referenceOrigin);
|
||||
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
|
||||
await expect(createButton).toBeEnabled();
|
||||
|
||||
const previewResponses = [];
|
||||
page.on('response', (response) => {
|
||||
if (response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview')) {
|
||||
previewResponses.push({ status: response.status(), url: response.url() });
|
||||
}
|
||||
});
|
||||
|
||||
for (let sampleIndex = 0; sampleIndex < SAMPLE_COUNT; sampleIndex += 1) {
|
||||
await expect(previewButton).toBeEnabled();
|
||||
await page.evaluate((index) => {
|
||||
const measurements = window.__ac11Measurements || (window.__ac11Measurements = []);
|
||||
const sample = { start: null, elapsed: null };
|
||||
measurements[index] = sample;
|
||||
const ready = () => {
|
||||
const panel = document.querySelector('#openapi-import-preview-panel');
|
||||
const button = document.querySelector('#openapi-import-preview');
|
||||
const status = document.querySelector('[data-testid="openapi-import-page-status"]');
|
||||
const create = document.querySelector('#openapi-import-create');
|
||||
const rowCount = document.querySelectorAll('.openapi-import-operation').length;
|
||||
if (sample.start === null || !button || button.disabled || !panel || panel.hidden
|
||||
|| !status || !status.textContent.includes('2000') || !create || create.disabled
|
||||
|| rowCount < 1 || rowCount > 100) return;
|
||||
sample.elapsed = Number((performance.now() - sample.start).toFixed(3));
|
||||
observer.disconnect();
|
||||
};
|
||||
const observer = new MutationObserver(ready);
|
||||
observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
|
||||
document.addEventListener('click', (event) => {
|
||||
if (event.target.closest('#openapi-import-preview')) sample.start = performance.now();
|
||||
}, { capture: true, once: true });
|
||||
}, sampleIndex);
|
||||
const responsePromise = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/preview'),
|
||||
);
|
||||
await previewButton.click();
|
||||
const previewResponse = await responsePromise;
|
||||
expect(previewResponse.status(), `preview sample ${sampleIndex + 1} status`).toBe(200);
|
||||
expect(new URL(previewResponse.url()).origin).toBe(referenceOrigin);
|
||||
|
||||
await page.waitForFunction((index) => {
|
||||
const sample = window.__ac11Measurements && window.__ac11Measurements[index];
|
||||
return sample && sample.elapsed !== null;
|
||||
}, sampleIndex, { polling: 'raf' });
|
||||
const elapsed = await page.evaluate((index) => window.__ac11Measurements[index].elapsed, sampleIndex);
|
||||
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
|
||||
await expect(rows.first()).toBeVisible();
|
||||
expect(await rows.count()).toBeGreaterThan(0);
|
||||
expect(await rows.count()).toBeLessThanOrEqual(100);
|
||||
await expect(createButton).toBeEnabled();
|
||||
|
||||
samplesMs.push(elapsed);
|
||||
browserEnvironment = await page.evaluate(() => ({
|
||||
user_agent: navigator.userAgent,
|
||||
platform: navigator.platform,
|
||||
language: navigator.language,
|
||||
hardware_concurrency: navigator.hardwareConcurrency || null,
|
||||
viewport: { width: innerWidth, height: innerHeight },
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
}));
|
||||
}
|
||||
|
||||
expect(previewResponses).toHaveLength(SAMPLE_COUNT);
|
||||
expect(previewResponses.every((item) => item.status === 200)).toBe(true);
|
||||
const p95Ms = percentile95(samplesMs);
|
||||
const report = {
|
||||
benchmark: 'story-2.12-ac-11-reference-preview',
|
||||
generated_at: new Date().toISOString(),
|
||||
result: { sample_count: samplesMs.length, p95_ms: p95Ms, threshold_ms: MAX_P95_MS },
|
||||
workload: {
|
||||
operations: OPERATION_COUNT,
|
||||
yaml_bytes: yaml.byteLength,
|
||||
max_yaml_bytes: MAX_UPLOAD_BYTES,
|
||||
preview_http_statuses: previewResponses.map((item) => item.status),
|
||||
rendered_operation_rows: await rows.count(),
|
||||
max_rendered_operation_rows: 100,
|
||||
enabled_interaction: 'Create button enabled after preview',
|
||||
interaction_enabled: true,
|
||||
measurement_scope: 'click through real HTTP request, parsing, populated first page, and enabled Create button',
|
||||
},
|
||||
samples_ms: samplesMs,
|
||||
environment: {
|
||||
reference_origin: referenceOrigin,
|
||||
playwright_base_url_configured: true,
|
||||
playwright_skip_web_server: process.env.PLAYWRIGHT_SKIP_WEB_SERVER === '1',
|
||||
node_version: process.version,
|
||||
os_platform: process.platform,
|
||||
os_arch: process.arch,
|
||||
browser: browserEnvironment,
|
||||
reference_manifest: referenceManifest,
|
||||
},
|
||||
};
|
||||
|
||||
const rawReport = JSON.stringify(report, null, 2);
|
||||
await testInfo.attach('ac11-reference-preview-report.json', {
|
||||
body: Buffer.from(rawReport),
|
||||
contentType: 'application/json',
|
||||
});
|
||||
console.log('AC11_REFERENCE_PREVIEW_REPORT ' + JSON.stringify(report));
|
||||
expect(p95Ms, 'Reference preview p95 must be at most 2 seconds').toBeLessThanOrEqual(MAX_P95_MS);
|
||||
});
|
||||
@@ -0,0 +1,979 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
|
||||
|
||||
const operationKey = 'get:/protected';
|
||||
const profileId = 'auth_profile_safe_bearer';
|
||||
const secretCanary = 'SECRET_CANARY_do_not_render_or_store';
|
||||
|
||||
function securityPreview() {
|
||||
return {
|
||||
job_id: 'job_security_mapping_atdd',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
preview: {
|
||||
source: { servers: ['https://api.example.test'] },
|
||||
findings: [],
|
||||
groups: [{
|
||||
title: 'protected operations',
|
||||
operations: [{
|
||||
key: operationKey,
|
||||
method: 'GET',
|
||||
path: '/protected',
|
||||
suggested_name: 'protected_operation',
|
||||
suggested_display_name: 'Protected operation',
|
||||
input_fields: 0,
|
||||
output_fields: 0,
|
||||
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
|
||||
findings: [{
|
||||
code: 'unsupported_security_scheme',
|
||||
severity: 'warning',
|
||||
message: 'Unsupported scheme details are intentionally opaque',
|
||||
construct_id: 'security_scheme_unsupported',
|
||||
location: { path: '/paths/~1protected/get/security' },
|
||||
operation_key: operationKey,
|
||||
}],
|
||||
security_requirements: {
|
||||
source: 'document',
|
||||
alternatives: [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: [], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
],
|
||||
},
|
||||
}],
|
||||
}],
|
||||
},
|
||||
security_profile_choices: [
|
||||
{
|
||||
operation_key: operationKey,
|
||||
alternative_index: 0,
|
||||
schemes: ['bearerAuth'],
|
||||
profiles: [{ id: profileId, name: 'Production bearer', kind: 'bearer' }],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function protectedOperation(key, suggestedName, alternatives) {
|
||||
return {
|
||||
key,
|
||||
method: 'GET',
|
||||
path: '/' + key.split('/').pop(),
|
||||
suggested_name: suggestedName,
|
||||
suggested_display_name: suggestedName,
|
||||
input_fields: 0,
|
||||
output_fields: 0,
|
||||
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
|
||||
findings: [],
|
||||
security_requirements: { source: 'document', alternatives },
|
||||
};
|
||||
}
|
||||
|
||||
function previewWith(operations, choices) {
|
||||
return {
|
||||
job_id: 'job_security_multi_atdd',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
preview: {
|
||||
source: { servers: ['https://api.example.test'] },
|
||||
findings: [],
|
||||
groups: [{ title: 'protected operations', operations }],
|
||||
},
|
||||
security_profile_choices: choices,
|
||||
};
|
||||
}
|
||||
|
||||
async function dismissOnboardingIfOpen(page) {
|
||||
// Same harness hygiene as openapi-import-plan.spec.js and operations.spec.js:
|
||||
// the overlay intercepts pointer events on a fresh E2E stack.
|
||||
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
|
||||
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
|
||||
await page.evaluate(() => {
|
||||
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
|
||||
if (dismiss) dismiss.click();
|
||||
});
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
}
|
||||
|
||||
async function openSecurityPreview(page, locale = 'en', previewPayload = securityPreview()) {
|
||||
// Register the preview boundary before navigation so the upload is deterministic.
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(previewPayload),
|
||||
});
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
}
|
||||
|
||||
function actionablePlan(decision) {
|
||||
return {
|
||||
plan_reference: 'plan_security_mapping_atdd',
|
||||
plan_digest: 'c'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: 'protected_operation',
|
||||
state: 'actionable',
|
||||
action: decision.action,
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index,
|
||||
reason: null,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
function containsCredentialField(value) {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
return Object.entries(value).some(([key, nested]) =>
|
||||
/^(password|access_token|refresh_token|secret_value|credential_value|raw_credentials?)$/i.test(key)
|
||||
|| containsCredentialField(nested));
|
||||
}
|
||||
|
||||
test('[P1] AC-1 sends the selected OR alternative and Auth Profile, then renders API authority', async ({ page }) => {
|
||||
// Given an OpenAPI preview with OR security choices and safe workspace profile metadata
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await openSecurityPreview(page);
|
||||
|
||||
// When an administrator selects a supported alternative and its compatible profile
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
// Then the existing plan API receives only the typed profile reference and alternative index
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({
|
||||
operation_key: operationKey,
|
||||
auth_profile_id: profileId,
|
||||
security_alternative_index: 0,
|
||||
});
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
|
||||
expect(JSON.stringify(planRequests[0])).not.toContain(secretCanary);
|
||||
expect(containsCredentialField(planRequests[0])).toBe(false);
|
||||
});
|
||||
|
||||
test('[P1] AC-2 replaces a prior resolved plan with a blocker after profile revalidation fails', async ({ page }) => {
|
||||
// Given an API-confirmed resolved plan for a profile that becomes unavailable before revalidation
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
if (planRequests.length === 1) {
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page);
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
// When the API first confirms the selection and then rejects the stale profile
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
|
||||
await page.locator('#openapi-import-plan-back').click();
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
// Then the old resolved value is replaced by the exact API-authoritative blocker state
|
||||
await expect.poll(() => planRequests.length).toBe(2);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({ auth_profile_id: profileId, security_alternative_index: 0 });
|
||||
});
|
||||
|
||||
test('[P1] AC-3 shows safe security guidance in RU and EN without exposing error or secret canaries', async ({ page }) => {
|
||||
// Given safe profile metadata and an unsupported AND alternative in the preview
|
||||
let previewCalls = 0;
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
previewCalls += 1;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(securityPreview()) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_security_alternative_required', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
|
||||
// When the administrator inspects both locales, the unsupported AND alternative is visible but disabled
|
||||
// Native option elements are not visually visible inside a select; the safe
|
||||
// metadata must be present and selectable.
|
||||
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).locator('option[value="' + profileId + '"]')).toBeAttached();
|
||||
await expect(page.getByLabel(localized('Security alternative', 'Вариант безопасности')).locator('option[value="2"]')).toHaveAttribute('disabled', '');
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
await expect.poll(() => previewCalls).toBe(2);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
// A fresh preview resets the selection, so the operation is required again,
|
||||
// never a leftover unresolved/resolved binding from the rejected plan.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(
|
||||
localized('Authentication required', 'Требуется аутентификация'),
|
||||
);
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
const exposed = await page.evaluate(() => ({
|
||||
html: document.documentElement.innerText,
|
||||
local: JSON.stringify(localStorage),
|
||||
session: JSON.stringify(sessionStorage),
|
||||
}));
|
||||
expect(JSON.stringify(exposed)).not.toContain(secretCanary);
|
||||
});
|
||||
|
||||
/* ── Mandatory matrix branches (green phase) ─────────────────────────── */
|
||||
|
||||
test('[P1] anonymous alternative submits only the OR index, never an unrequested profile', async ({ page }) => {
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
const decision = payload.decisions[0];
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({
|
||||
action: decision.action,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
|
||||
})),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
// The anonymous (empty-scheme) alternative is selectable; selecting it must
|
||||
// keep the profile unbound.
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
await alternative.selectOption('1');
|
||||
// The anonymous alternative must not offer any Auth Profile control.
|
||||
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
const decision = planRequests[0].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
// A confirmed anonymous alternative is no-auth, never a resolved auth binding.
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
|
||||
expect(JSON.stringify(planRequests[0])).not.toContain(profileId);
|
||||
});
|
||||
|
||||
test('[P1] changing the alternative clears the profile and invalidates a prior plan', async ({ page }) => {
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
const decision = payload.decisions[0];
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({
|
||||
action: decision.action,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
|
||||
})),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await alternative.selectOption('0');
|
||||
await profile.selectOption(profileId);
|
||||
|
||||
// A confirmed plan exists for (alternative 0, profile).
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
// Back to editing: the selection survives, the plan does not.
|
||||
await page.locator('#openapi-import-plan-back').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
|
||||
// Switching the alternative drops the bound profile; the anonymous choice
|
||||
// hides the profile control entirely and the new plan carries only the index.
|
||||
await alternative.selectOption('1');
|
||||
await expect(profile).toHaveCount(0);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect.poll(() => planRequests.length).toBe(2);
|
||||
|
||||
const decision = planRequests[1].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
|
||||
});
|
||||
|
||||
test('[P1] empty compatible-profile list keeps the selection safe and the API blocker authoritative', async ({ page }) => {
|
||||
const emptyPreview = securityPreview();
|
||||
emptyPreview.security_profile_choices = [];
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
// Actual public contract: a 200 plan whose candidate is blocked with the
|
||||
// safe reason the API owns, not a synthesized top-level error code.
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_empty_profiles_atdd',
|
||||
plan_digest: 'f'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 1 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: 'protected_operation',
|
||||
state: 'blocked',
|
||||
action: 'create',
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
security_alternative_index: 0,
|
||||
reason: 'auth_profile_required',
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', emptyPreview);
|
||||
|
||||
// The empty compatible-profile list disables the profile control and shows
|
||||
// safe localized guidance instead of offering an arbitrary error payload.
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await expect(profileSelect.locator('option')).toHaveCount(1);
|
||||
await alternative.selectOption('0');
|
||||
await expect(profileSelect).toBeDisabled();
|
||||
await expect(page.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({
|
||||
operation_key: operationKey,
|
||||
security_alternative_index: 0,
|
||||
});
|
||||
expect(planRequests[0].decisions[0]).not.toHaveProperty('auth_profile_id');
|
||||
// The API candidate is authoritative: blocked, with safe translated guidance.
|
||||
await expect(page.locator('.openapi-import-security-op-status')).toHaveText('Blocked');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
await expect(page.locator('.openapi-import-plan-reason')).toHaveText(
|
||||
'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.');
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
});
|
||||
|
||||
test('[P2] security controls keep accessible names, keyboard focus and a live status', async ({ page }) => {
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await expect(alternative).toBeEditable();
|
||||
await expect(profile).toBeEditable();
|
||||
|
||||
// Keyboard-only selection: focus the native select and change it with keys,
|
||||
// never programmatically.
|
||||
await alternative.focus();
|
||||
expect(await alternative.evaluate((el) => el === document.activeElement)).toBe(true);
|
||||
await alternative.press('ArrowDown');
|
||||
await expect(alternative).toHaveValue('0');
|
||||
await profile.focus();
|
||||
expect(await profile.evaluate((el) => el === document.activeElement)).toBe(true);
|
||||
await profile.press('ArrowDown');
|
||||
await expect(profile).toHaveValue(profileId);
|
||||
|
||||
const status = page.getByTestId('openapi-security-status');
|
||||
await expect(status).toHaveAttribute('role', 'status');
|
||||
await expect(status).toHaveAttribute('aria-live', 'polite');
|
||||
const opStatus = page.locator('.openapi-import-security-op-status');
|
||||
await expect(opStatus).toHaveAttribute('role', 'status');
|
||||
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
|
||||
|
||||
await page.locator('body').press('Escape');
|
||||
await expect(page.locator('#openapi-import-modal')).toBeHidden();
|
||||
});
|
||||
|
||||
test('[P1] a delayed preview response cannot restore state after the user cancelled', async ({ page }) => {
|
||||
let releasePreview;
|
||||
const previewReleased = new Promise((resolve) => {
|
||||
releasePreview = resolve;
|
||||
});
|
||||
let previewFulfilled = false;
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await previewReleased;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(securityPreview()),
|
||||
});
|
||||
previewFulfilled = true;
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
const previewRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && request.url().includes('/imports/openapi/preview'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await previewRequest;
|
||||
await page.locator('#openapi-import-cancel').click();
|
||||
|
||||
// Release the stale response and wait for the handler to settle instead of a
|
||||
// fixed timeout, then prove it could not restore the panel.
|
||||
releasePreview();
|
||||
await expect.poll(() => previewFulfilled).toBe(true);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
|
||||
await expect(page.locator('#openapi-import-cancel')).toBeHidden();
|
||||
});
|
||||
|
||||
/* ── Per-operation authority and selection lifecycle ────────────────── */
|
||||
|
||||
test('[P1] offers only profiles compatible with the chosen OR alternative and hides them for anonymous', async ({ page }) => {
|
||||
const key = 'get:/multi';
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'multi_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['basicAuth'], supported: true, findings: [] },
|
||||
{ schemes: [], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
|
||||
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
|
||||
]));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'multi_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
|
||||
// Profile-first selection may offer the safe union while no alternative is chosen.
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
|
||||
await expect(alternative.locator('option[value="3"]')).toHaveAttribute('disabled', '');
|
||||
|
||||
await alternative.selectOption('0');
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toHaveCount(0);
|
||||
|
||||
await alternative.selectOption('1');
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toHaveCount(0);
|
||||
|
||||
// An anonymous alternative must offer no profile control at all.
|
||||
await alternative.selectOption('2');
|
||||
await expect(row.locator('.openapi-import-security-controls select')).toHaveCount(1);
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('[P1] reports per-operation resolved and blocked authority for a mixed plan', async ({ page }) => {
|
||||
const keyA = 'get:/alpha';
|
||||
const keyB = 'get:/beta';
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_multi_mixed_atdd',
|
||||
plan_digest: 'd'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 2, excluded: 0, actionable: 1, blocked: 1 },
|
||||
candidates: [
|
||||
{ key: keyA, name: 'alpha_operation', state: 'actionable', action: 'create', auth_profile_id: 'prof_a', security_alternative_index: 0, reason: null },
|
||||
{ key: keyB, name: 'beta_operation', state: 'blocked', action: 'create', auth_profile_id: 'prof_b', security_alternative_index: 0, reason: 'auth_profile_required' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(keyA, 'alpha_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
protectedOperation(keyB, 'beta_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
], [
|
||||
{ operation_key: keyA, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_a', name: 'A profile', kind: 'bearer' }] },
|
||||
{ operation_key: keyB, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_b', name: 'B profile', kind: 'bearer' }] },
|
||||
]));
|
||||
|
||||
// Before the plan both protected operations require an explicit binding.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
|
||||
|
||||
const rowA = page.locator('.openapi-import-operation').filter({ hasText: 'alpha_operation' });
|
||||
const rowB = page.locator('.openapi-import-operation').filter({ hasText: 'beta_operation' });
|
||||
await rowA.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await rowA.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_a');
|
||||
await rowB.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await rowB.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_b');
|
||||
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + keyA + '"]')).toHaveText('Resolved');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + keyB + '"]')).toHaveText('Blocked');
|
||||
// The summary must surface the blocked operation, not mask it behind a resolved one.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
});
|
||||
|
||||
test('[P1] editing the alternative after an authoritative blocker clears the blocked authority', async ({ page }) => {
|
||||
const key = 'get:/reset';
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'reset_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['basicAuth'], supported: true, findings: [] },
|
||||
]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
|
||||
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
|
||||
]));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'reset_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_bearer');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Blocked');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
|
||||
// Editing must void the blocked authority and clear the bound profile.
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('1');
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveValue('');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Authentication required');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
});
|
||||
|
||||
test('[P1] binding then choosing skip removes the auth fields from the plan payload', async ({ page }) => {
|
||||
const suggestedName = 'protected_operation';
|
||||
const planRequests = [];
|
||||
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
items: [{ id: 'op_skip_target', name: suggestedName, protocol: 'rest', status: 'draft' }],
|
||||
page: 1,
|
||||
page_size: 1,
|
||||
total: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_skip_atdd',
|
||||
plan_digest: 'e'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 0 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: suggestedName,
|
||||
state: 'excluded',
|
||||
action: 'skip',
|
||||
target_operation_id: 'op_skip_target',
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
security_alternative_index: null,
|
||||
reason: 'skipped',
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: suggestedName });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
await row.locator('[data-openapi-decision-action]').selectOption('skip');
|
||||
await expect(row.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
const decision = planRequests[0].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, action: 'skip', target_operation_id: 'op_skip_target' });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
expect(decision).not.toHaveProperty('security_alternative_index');
|
||||
});
|
||||
|
||||
test('[P1] language change during a pending Apply keeps security controls disabled', async ({ page }) => {
|
||||
let releaseApply;
|
||||
const applyHeld = new Promise((resolve) => {
|
||||
releaseApply = resolve;
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
await applyHeld;
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_digest: 'c'.repeat(64),
|
||||
counts: { created: 1 },
|
||||
outcomes: [{ key: operationKey, name: 'protected_operation', status: 'created' }],
|
||||
}),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The context change aborts the request; it must not update the modal.
|
||||
}
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await alternative.selectOption('0');
|
||||
await profile.selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect(alternative).toBeDisabled();
|
||||
// A language change while Apply is in flight must not re-render and re-enable
|
||||
// the security controls.
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
await expect(alternative).toBeDisabled();
|
||||
await expect(profile).toBeDisabled();
|
||||
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
|
||||
releaseApply();
|
||||
});
|
||||
|
||||
test('[P1] a rejected Apply clears a previously resolved security authority', async ({ page }) => {
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary }, recovery: 'repreview_required' }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
// The rejected Apply must not retain the prior resolved authority.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
});
|
||||
|
||||
test('[P1] a delayed plan response cannot restore authority after cancel', async ({ page }) => {
|
||||
let releasePlan;
|
||||
const planHeld = new Promise((resolve) => {
|
||||
releasePlan = resolve;
|
||||
});
|
||||
let planFulfilled = false;
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await planHeld;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
|
||||
});
|
||||
planFulfilled = true;
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
const planRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await planRequest;
|
||||
await page.locator('#openapi-import-cancel').click();
|
||||
|
||||
releasePlan();
|
||||
await expect.poll(() => planFulfilled).toBe(true);
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
});
|
||||
|
||||
test('[P1] a quoted or backslash operation key cannot break per-operation status', async ({ page }) => {
|
||||
const key = 'get:/quoted"path\\segment';
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_quoted_key_atdd',
|
||||
plan_digest: 'a'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
|
||||
candidates: [{
|
||||
key,
|
||||
name: 'quoted_operation',
|
||||
state: 'actionable',
|
||||
action: 'create',
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: profileId,
|
||||
security_alternative_index: 0,
|
||||
reason: null,
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'quoted_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: profileId, name: 'Bearer profile', kind: 'bearer' }] },
|
||||
]));
|
||||
|
||||
// Rendering a CSS-hostile key must not throw and the preview must render.
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'quoted_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0].operation_key).toBe(key);
|
||||
// Status is matched by dataset value, never by interpolating the key into CSS.
|
||||
await expect(row.locator('.openapi-import-security-op-status')).toHaveText('Resolved');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
});
|
||||
|
||||
test('[P1] localizes unsupported findings and empty-profile guidance in RU and EN', async ({ page }) => {
|
||||
const key = 'get:/locale';
|
||||
await openSecurityPreview(page, 'ru', previewWith([
|
||||
protectedOperation(key, 'locale_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
]),
|
||||
], []));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'locale_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
|
||||
// RU: exact unsupported finding copy and empty-profile guidance.
|
||||
await expect(row.locator('.openapi-import-security-findings')).toContainText(
|
||||
'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.');
|
||||
await alternative.selectOption('0');
|
||||
await expect(profile).toBeDisabled();
|
||||
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.');
|
||||
const opStatus = row.locator('.openapi-import-security-op-status');
|
||||
await expect(opStatus).toHaveAttribute('role', 'status');
|
||||
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
|
||||
|
||||
// EN: switching language invalidates an unconfirmed preview, so re-preview
|
||||
// and assert the exact translated copy in the second locale.
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await expect(row.locator('.openapi-import-security-findings')).toContainText(
|
||||
'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.');
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toBeDisabled();
|
||||
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
|
||||
});
|
||||
|
||||
test('[P1] a stale security plan cannot restore authority after a language or workspace change', async ({ page }) => {
|
||||
const releases = [];
|
||||
let planReleased = 0;
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await new Promise((resolve) => releases.push(resolve));
|
||||
planReleased += 1;
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The context change aborts the request; it must not update the modal.
|
||||
}
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
async function bindSelection() {
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
}
|
||||
async function startPlan() {
|
||||
const request = page.waitForRequest((r) => r.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(r.url()));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await request;
|
||||
await expect.poll(() => releases.length).toBeGreaterThanOrEqual(1);
|
||||
}
|
||||
|
||||
// 1) Language change while a security plan is pending.
|
||||
await bindSelection();
|
||||
await startPlan();
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
releases.shift()();
|
||||
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(1);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
|
||||
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
|
||||
// 2) Workspace change while a security plan is pending.
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await bindSelection();
|
||||
await startPlan();
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'ws-stale-security' } }));
|
||||
});
|
||||
releases.shift()();
|
||||
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(2);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
|
||||
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
|
||||
});
|
||||
|
||||
/* ── Real API evidence ───────────────────────────────────────────────── */
|
||||
|
||||
test('[P1][api] real preview/plan round-trip resolves a typed reference (real secret + bearer profile)', async ({ page }) => {
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const prefix = uniqueName('secmap');
|
||||
const secretValue = 'secmap-bearer-' + prefix;
|
||||
const secret = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
|
||||
{ name: prefix + '_secret', kind: 'token', value: secretValue },
|
||||
);
|
||||
let profile = null;
|
||||
try {
|
||||
profile = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
|
||||
{
|
||||
name: prefix + '_profile',
|
||||
kind: 'bearer',
|
||||
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
|
||||
},
|
||||
);
|
||||
expect(String(profile.id)).toMatch(/^auth_/);
|
||||
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping-real.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from([
|
||||
'openapi: 3.0.3',
|
||||
'info: { title: Security mapping real, version: "1" }',
|
||||
'servers: [{ url: "https://api.example.test" }]',
|
||||
'paths:',
|
||||
' /' + prefix + ':',
|
||||
' get:',
|
||||
' operationId: ' + prefix + '_operation',
|
||||
' security:',
|
||||
' - bearerAuth: []',
|
||||
' - {}',
|
||||
' responses:',
|
||||
' \'200\': { description: OK }',
|
||||
'components:',
|
||||
' securitySchemes:',
|
||||
' bearerAuth: { type: http, scheme: bearer }',
|
||||
].join('\n')),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
|
||||
await bearerOption.waitFor({ state: 'attached' });
|
||||
const bearerIndex = await bearerOption.getAttribute('value');
|
||||
expect(bearerIndex).toMatch(/^\d+$/); // option value, not the select's current value
|
||||
await alternative.selectOption(bearerIndex);
|
||||
const realProfileOption = profileSelect.locator('option[value="' + profile.id + '"]');
|
||||
await expect(realProfileOption).toBeAttached();
|
||||
await profileSelect.selectOption(profile.id);
|
||||
|
||||
const planRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()),
|
||||
);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
const sent = await planRequest;
|
||||
const response = await sent.response();
|
||||
|
||||
// Happy path is deterministic: the created profile matches the bearer
|
||||
// scheme, so the real API must accept the typed reference.
|
||||
expect(response.status()).toBe(200);
|
||||
const payload = await sent.postDataJSON();
|
||||
const planDecision = (payload.decisions || [])[0];
|
||||
expect(planDecision).toMatchObject({ auth_profile_id: profile.id, security_alternative_index: Number(bearerIndex) });
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
await expect(page.locator('body')).not.toContainText(secretValue);
|
||||
} finally {
|
||||
// Best-effort cleanup. The Secret is guarded (409) while the live profile
|
||||
// references it; the referenced Auth Profile has no delete endpoint, so we
|
||||
// only attempt to release the Secret and never widen the backend surface.
|
||||
try {
|
||||
await browserJson(
|
||||
page,
|
||||
'DELETE',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets/${encodeURIComponent(secret.id)}`,
|
||||
[],
|
||||
[404, 409],
|
||||
);
|
||||
} catch (_error) {}
|
||||
}
|
||||
});
|
||||
@@ -11,6 +11,48 @@ async function dismissOnboardingIfOpen(page) {
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
}
|
||||
|
||||
function planResponse(payload, planReference) {
|
||||
const decisions = payload.decisions || [];
|
||||
return {
|
||||
plan_reference: planReference,
|
||||
plan_digest: 'c'.repeat(64),
|
||||
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
selection_mode: payload.selection_mode,
|
||||
counts: { selected: decisions.length, excluded: 0, actionable: decisions.length, blocked: 0 },
|
||||
candidates: decisions.map((decision) => ({
|
||||
key: decision.operation_key,
|
||||
name: decision.confirmed_name || decision.operation_key,
|
||||
state: 'actionable',
|
||||
action: decision.action,
|
||||
target_operation_id: decision.target_operation_id || null,
|
||||
confirmed_name: decision.confirmed_name || null,
|
||||
auth_profile_id: null,
|
||||
reason: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function applyResponse(payload, names) {
|
||||
const outcomes = (payload.outcomes || []).map((outcome) => ({
|
||||
key: outcome.key,
|
||||
name: names && names[outcome.key] || outcome.name || outcome.key,
|
||||
status: outcome.status || 'created',
|
||||
}));
|
||||
return {
|
||||
counts: { created: outcomes.filter((outcome) => outcome.status === 'created').length },
|
||||
outcomes,
|
||||
};
|
||||
}
|
||||
|
||||
async function mockEmptyOperationsList(page) {
|
||||
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('operations page shows demo catalog and filter works', async ({ page }) => {
|
||||
await login(page);
|
||||
await expect(page.locator('.page-heading')).toHaveText(localized('Operations', 'Операции'));
|
||||
@@ -100,7 +142,9 @@ paths:
|
||||
const request = await previewRequest;
|
||||
expect(request.headers()['content-type']).toMatch(/^multipart\/form-data; boundary=/i);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await expect(page.locator('.openapi-import-document-findings')).toContainText(/base URL/i);
|
||||
const documentFindings = page.locator('.openapi-import-document-findings');
|
||||
await documentFindings.locator('summary').click();
|
||||
await expect(documentFindings).toContainText(/base URL/i);
|
||||
await expect(page.locator('.openapi-import-group').filter({ hasText: 'currency' })).toBeVisible();
|
||||
const importedOperation = page.locator('.openapi-import-operation').filter({ hasText: 'Получить курсы валют' });
|
||||
await expect(importedOperation).toBeVisible();
|
||||
@@ -118,6 +162,7 @@ paths:
|
||||
await page.locator('#openapi-import-search').fill('status');
|
||||
await expect(page.locator('.openapi-import-operation:visible')).toHaveCount(1);
|
||||
await expect(page.locator('.openapi-import-operation:visible').filter({ hasText: 'Проверить статус' })).toBeVisible();
|
||||
await page.locator('#openapi-import-partial-mode').check();
|
||||
await page.locator('#openapi-import-clear-visible').click();
|
||||
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 1', 'Выбрано: 1'));
|
||||
await page.locator('#openapi-import-search').fill('');
|
||||
@@ -127,18 +172,21 @@ paths:
|
||||
await page.locator('#openapi-import-method-filter').selectOption('');
|
||||
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import result', 'Результат импорта'));
|
||||
await expect(page.locator('.openapi-import-result-table')).toBeVisible();
|
||||
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText('POST /v1/rates/{date}');
|
||||
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
|
||||
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('Fix in wizard', 'Исправить в мастере'));
|
||||
await expect(page.locator('.openapi-import-primary-result a')).toHaveAttribute(
|
||||
'href',
|
||||
/\/wizard\/\?mode=edit&operationId=op_/
|
||||
);
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect(page.locator('#openapi-import-result')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import plan result', 'Результат плана импорта'));
|
||||
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText(operationId);
|
||||
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText('POST /v1/rates/{date}');
|
||||
const operationFindings = importedOperation.locator('.openapi-import-findings');
|
||||
await operationFindings.locator('summary').click();
|
||||
await expect(operationFindings).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
|
||||
await expect(page.locator('tbody')).toContainText(new RegExp(operationId, 'i'));
|
||||
await expect(page.locator('tbody')).not.toContainText(new RegExp(statusOperationId, 'i'));
|
||||
await expect(page.locator('body')).not.toContainText(sourceCanary);
|
||||
await page.locator('[data-openapi-close]').last().click();
|
||||
await page.locator('tbody tr').filter({ hasText: operationId }).locator('.row-btn-edit').click();
|
||||
await expect(page).toHaveURL(/\/wizard\/\?mode=edit&operationId=op_/);
|
||||
});
|
||||
|
||||
test('OpenAPI upload rejects invalid files locally and restores focus after Escape', async ({ page }) => {
|
||||
@@ -230,7 +278,7 @@ test('OpenAPI upload recovers from pagehide and a preview server error', async (
|
||||
buffer: Buffer.from('openapi: 3.0.3'),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading and parsing', 'Загружаю и разбираю'));
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading the document', 'Загружаю документ'));
|
||||
|
||||
await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })));
|
||||
await expect(page.locator('#openapi-import-status')).toHaveText('');
|
||||
@@ -246,6 +294,7 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await mockEmptyOperationsList(page);
|
||||
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await route.fulfill({
|
||||
@@ -269,11 +318,18 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
|
||||
});
|
||||
|
||||
const requests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(planResponse(payload, 'plan_retry_same_authority')),
|
||||
});
|
||||
});
|
||||
let releaseFirst;
|
||||
const firstRequest = new Promise((resolve) => {
|
||||
releaseFirst = resolve;
|
||||
});
|
||||
await page.route('**/imports/openapi/*/create', async (route) => {
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
requests.push({ url: route.request().url(), body: route.request().postData() });
|
||||
if (requests.length === 1) await firstRequest;
|
||||
if (requests.length === 3) {
|
||||
@@ -287,12 +343,9 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
created: [{
|
||||
operation_key: 'get:/retry', name: 'renamed_after_conflict', operation_id: 'op_retry', version: 1,
|
||||
}],
|
||||
skipped: [], findings: [],
|
||||
}),
|
||||
body: JSON.stringify(applyResponse({ outcomes: [{
|
||||
key: 'get:/retry', name: 'renamed_after_conflict', status: 'created',
|
||||
}] })),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The first request is deliberately aborted by the browser.
|
||||
@@ -305,23 +358,25 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect.poll(() => requests.length).toBe(1);
|
||||
await page.locator('#openapi-import-cancel').click();
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(localized('may have completed', 'мог завершиться'));
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await page.locator('[data-openapi-close]').last().click();
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
|
||||
await expect.poll(() => requests.length).toBe(2);
|
||||
// Let the cancelled first attempt answer after the retry. Its stale response
|
||||
// must not overwrite or unlock the newer attempt's state.
|
||||
releaseFirst();
|
||||
await page.waitForTimeout(50);
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
|
||||
expect(requests[0].url).toContain('/imports/openapi/job_retry_same_authority/create');
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
|
||||
expect(requests[0].url).toContain('/imports/openapi/plan_retry_same_authority/apply');
|
||||
expect(requests[1].url).toBe(requests[0].url);
|
||||
expect(requests[1].body).toBe(requests[0].body);
|
||||
|
||||
@@ -334,17 +389,20 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect.poll(() => requests.length).toBe(3);
|
||||
await expect(page.locator('#openapi-import-file-select')).toBeEnabled();
|
||||
await expect(page.locator('#openapi-import-reset')).toBeEnabled();
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_apply_replay_v1'))).toBeNull();
|
||||
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_plan_apply_replay_v2'))).toBeNull();
|
||||
});
|
||||
|
||||
test('OpenAPI apply preserves job authority after language or workspace changes', async ({ page }) => {
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await mockEmptyOperationsList(page);
|
||||
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await route.fulfill({
|
||||
@@ -368,16 +426,21 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
|
||||
});
|
||||
const releases = [];
|
||||
const applyRequests = [];
|
||||
await page.route('**/imports/openapi/*/create', async (route) => {
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_active_apply')),
|
||||
});
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
applyRequests.push({ url: route.request().url(), body: route.request().postData() });
|
||||
await new Promise((resolve) => releases.push(resolve));
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
created: [{ operation_key: 'get:/active', name: 'active', operation_id: 'op_active', version: 1 }],
|
||||
skipped: [], findings: [],
|
||||
}),
|
||||
body: JSON.stringify(applyResponse({ outcomes: [{
|
||||
key: 'get:/active', name: 'active', status: 'created',
|
||||
}] })),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The invalidation aborts a request that must not update the modal afterwards.
|
||||
@@ -394,6 +457,8 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect(page.locator('#openapi-import-cancel')).toBeVisible();
|
||||
await expect.poll(() => releases.length).toBeGreaterThan(0);
|
||||
}
|
||||
@@ -402,14 +467,14 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
|
||||
// Exercise the actual UI language switcher path: it updates storage,
|
||||
// re-renders translations and dispatches crank:langchange in one action.
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
|
||||
releases.shift()();
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
await expect.poll(() => releases.length).toBeGreaterThan(0);
|
||||
releases.shift()();
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('GET /active');
|
||||
await expect(page.locator('#openapi-import-result')).toContainText('get:/active');
|
||||
expect(applyRequests[1].url).toBe(applyRequests[0].url);
|
||||
expect(applyRequests[1].body).toBe(applyRequests[0].body);
|
||||
|
||||
@@ -419,7 +484,7 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'workspace-after-apply' } }));
|
||||
});
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
|
||||
releases.shift()();
|
||||
@@ -516,6 +581,7 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await mockEmptyOperationsList(page);
|
||||
const sourceCanary = 'do-not-render-openapi-source-canary';
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'safe.yaml',
|
||||
@@ -590,14 +656,30 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
|
||||
});
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
let createRequests = 0;
|
||||
await page.route('**/imports/openapi/*/create', async (route) => {
|
||||
createRequests += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ created: [], skipped: [], findings: [] }) });
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_ui_evidence')),
|
||||
});
|
||||
});
|
||||
let applyRequests = 0;
|
||||
let releaseApply;
|
||||
const applyResponseHeld = new Promise((resolve) => { releaseApply = resolve; });
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
applyRequests += 1;
|
||||
await applyResponseHeld;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(applyResponse({ outcomes: [{ key: 'get:/health', name: 'health', status: 'created' }] })),
|
||||
});
|
||||
});
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await page.locator('#openapi-import-create').evaluate((button) => button.click());
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('Created: 0; skipped: 0.');
|
||||
expect(createRequests).toBe(1);
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
const applyButton = page.locator('#openapi-import-plan-apply');
|
||||
await applyButton.dblclick();
|
||||
await expect.poll(() => applyRequests).toBe(1);
|
||||
await expect(applyButton).toBeDisabled();
|
||||
releaseApply();
|
||||
await expect(page.locator('#openapi-import-status')).toContainText('Import plan applied.');
|
||||
expect(applyRequests).toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { login } = require('./helpers');
|
||||
|
||||
test('delayed new-upstream autofocus must not steal focus from the URL field', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/wizard/');
|
||||
await page.waitForFunction(() => window.CrankWizardReady === true);
|
||||
|
||||
await page.locator('[data-testid="wizard-protocol-rest"]').click();
|
||||
await page.locator('#btn-continue').click();
|
||||
await expect(page.locator('#upstream-new-trigger')).toBeVisible();
|
||||
|
||||
// Take manual control of page time before the new-upstream form is opened so
|
||||
// the deferred autofocus timer scheduled by startNewUpstream cannot fire on
|
||||
// its own while Playwright fills the two fields.
|
||||
const installTime = new Date('2026-05-01T12:00:00.000Z');
|
||||
await page.clock.install({ time: installTime });
|
||||
await page.clock.pauseAt(new Date(installTime.getTime() + 1000));
|
||||
|
||||
await page.locator('#upstream-new-trigger').click();
|
||||
|
||||
await page.locator('#new-upstream-name').fill('focus-red-upstream');
|
||||
await page.locator('#new-upstream-url').fill('http://127.0.0.1:3310');
|
||||
|
||||
// Both values landed exactly and focus is explicitly on the URL field before
|
||||
// the deferred autofocus runs.
|
||||
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
|
||||
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310');
|
||||
await expect(page.locator('#new-upstream-url')).toBeFocused();
|
||||
|
||||
// Explicitly execute the old 50ms autofocus timer.
|
||||
await page.clock.runFor(100);
|
||||
|
||||
// The delayed autofocus must not move focus back to the name field.
|
||||
await expect(page.locator('#new-upstream-url')).toBeFocused();
|
||||
|
||||
// Correct field still receives text after the timer ran; no network mutation.
|
||||
await page.keyboard.insertText('-probe');
|
||||
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310-probe');
|
||||
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { getCurrentWorkspace, login } = require('./helpers');
|
||||
|
||||
function draftSnapshot(operationId) {
|
||||
return {
|
||||
id: operationId,
|
||||
name: operationId,
|
||||
display_name: 'Imported rates',
|
||||
category: 'general',
|
||||
protocol: 'rest',
|
||||
target: {
|
||||
kind: 'rest',
|
||||
base_url: 'https://api.example.test',
|
||||
method: 'GET',
|
||||
path_template: '/rates',
|
||||
static_headers: {},
|
||||
},
|
||||
input_schema: {
|
||||
type: 'object',
|
||||
description: null,
|
||||
required: false,
|
||||
nullable: false,
|
||||
default_value: null,
|
||||
fields: {},
|
||||
items: null,
|
||||
enum_values: [],
|
||||
variants: [],
|
||||
},
|
||||
output_schema: {
|
||||
type: 'object',
|
||||
description: null,
|
||||
required: false,
|
||||
nullable: false,
|
||||
default_value: null,
|
||||
fields: {},
|
||||
items: null,
|
||||
enum_values: [],
|
||||
variants: [],
|
||||
},
|
||||
input_mapping: { rules: [] },
|
||||
output_mapping: {
|
||||
rules: [
|
||||
{ source: '$.response.body', target: '$.output', required: true },
|
||||
{ source: '$.response.body.rate', target: '$.output.rate', required: true },
|
||||
],
|
||||
},
|
||||
execution_config: {
|
||||
timeout_ms: 10000,
|
||||
retry_policy: null,
|
||||
auth_profile_ref: null,
|
||||
headers: {},
|
||||
approval_policy: null,
|
||||
},
|
||||
tool_description: { title: 'Imported rates', description: 'Get rates.', tags: [], examples: [] },
|
||||
wizard_state: { input_sample: {}, output_sample: {}, test_input: {}, import_findings: [] },
|
||||
};
|
||||
}
|
||||
|
||||
test('edit wizard skips no-op saves and refreshes its baseline after a real edit', async ({ page }) => {
|
||||
await login(page);
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const operationId = 'imported_rates_noop';
|
||||
const operationPath = `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/operations/${operationId}`;
|
||||
const versionPath = `${operationPath}/versions/*`;
|
||||
let version = 4;
|
||||
let updateCount = 0;
|
||||
const testedVersions = [];
|
||||
const publishedVersions = [];
|
||||
const analyzedPayloads = [];
|
||||
|
||||
await page.route(operationPath, async (route) => {
|
||||
if (route.request().method() === 'PATCH') {
|
||||
updateCount += 1;
|
||||
version += 1;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ operation_id: operationId, workspace_id: workspace.id, version, status: 'draft' }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
id: operationId,
|
||||
workspace_id: workspace.id,
|
||||
name: operationId,
|
||||
display_name: 'Imported rates',
|
||||
category: 'general',
|
||||
protocol: 'rest',
|
||||
status: 'draft',
|
||||
current_draft_version: version,
|
||||
draft_version_ref: { version, status: 'draft' },
|
||||
published_version_ref: null,
|
||||
agent_refs: [],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route(versionPath, async (route) => {
|
||||
const requestedVersion = Number(new URL(route.request().url()).pathname.split('/').pop());
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
operation_id: operationId,
|
||||
workspace_id: workspace.id,
|
||||
version: requestedVersion,
|
||||
status: 'draft',
|
||||
snapshot: draftSnapshot(operationId),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route(`**/operations/${operationId}/test-runs`, async (route) => {
|
||||
testedVersions.push(route.request().postDataJSON().version);
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, errors: [] }) });
|
||||
});
|
||||
await page.route('**/operations/analyze-quality', async (route) => {
|
||||
analyzedPayloads.push(route.request().postDataJSON());
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ blocking: false, findings: [] }) });
|
||||
});
|
||||
await page.route(`**/operations/${operationId}/publish`, async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
publishedVersions.push(payload.version);
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ published_version: payload.version }) });
|
||||
});
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
|
||||
await page.goto(`/wizard/?mode=edit&operationId=${operationId}`);
|
||||
await expect(page.locator('#tool-display-name')).toHaveValue('Imported rates');
|
||||
|
||||
const loadedOutputMapping = await page.evaluate(() => (
|
||||
window.jsyaml.load(document.getElementById('tool-output-mapping').value)
|
||||
));
|
||||
expect(loadedOutputMapping['$.output']).toBe('$.response.body');
|
||||
expect(loadedOutputMapping.rate).toBe('$.response.body.rate');
|
||||
expect(JSON.stringify(loadedOutputMapping)).not.toContain('$.response.body.$.output');
|
||||
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
|
||||
|
||||
await page.locator('#wizard-run-test').click();
|
||||
await expect.poll(() => testedVersions).toEqual([4]);
|
||||
expect(updateCount).toBe(0);
|
||||
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
|
||||
await page.locator('#tool-display-name').fill('Edited rates');
|
||||
await page.locator('.btn-save-draft').click();
|
||||
await expect.poll(() => updateCount).toBe(1);
|
||||
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
|
||||
await page.locator('#wizard-run-test').click();
|
||||
await expect.poll(() => testedVersions).toEqual([4, 5]);
|
||||
expect(updateCount).toBe(1);
|
||||
|
||||
await page.locator('#wizard-publish-operation').click();
|
||||
await expect.poll(() => publishedVersions).toEqual([5]);
|
||||
expect(updateCount).toBe(1);
|
||||
|
||||
const publishedRules = analyzedPayloads[analyzedPayloads.length - 1].output_mapping.rules;
|
||||
expect(publishedRules).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ source: '$.response.body', target: '$.output' }),
|
||||
expect.objectContaining({ source: '$.response.body.rate', target: '$.output.rate' }),
|
||||
]));
|
||||
expect(JSON.stringify(publishedRules)).not.toContain('$.response.body.$.output');
|
||||
});
|
||||
@@ -193,7 +193,7 @@ test('wizard builds visual request mappings from JSON sample and path params', a
|
||||
|
||||
await page.goto('/wizard/');
|
||||
await page.locator('[data-testid="wizard-protocol-rest"]').click();
|
||||
await page.evaluate(() => window.CrankWizardShell.goToStep(2));
|
||||
await page.locator('#btn-continue').click();
|
||||
await expect(page.locator('#step-panel-2')).toBeVisible();
|
||||
await page.locator('#endpoint-path').fill('/rates/{date}');
|
||||
await page.evaluate(() => window.CrankWizardShell.goToStep(3));
|
||||
@@ -881,10 +881,12 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
|
||||
await expect(page.locator('#approval-risk-level')).toHaveCount(0);
|
||||
await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180');
|
||||
await expect(page.locator('#approval-payload-preview-mode')).toHaveCount(0);
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
|
||||
await page.locator('#tool-display-name').fill('Frankfurter latest rate edited');
|
||||
await page.locator('.btn-save-draft').click();
|
||||
await expect.poll(() => updatePayload).not.toBeNull();
|
||||
|
||||
expect(updatePayload.display_name).toBe('Frankfurter latest rate');
|
||||
expect(updatePayload.display_name).toBe('Frankfurter latest rate edited');
|
||||
expect(updatePayload.target).toEqual({
|
||||
kind: 'rest',
|
||||
base_url: 'https://api.frankfurter.app',
|
||||
|
||||
@@ -16,16 +16,22 @@ pub enum ProductEventKind {
|
||||
OnboardingDismissed,
|
||||
OnboardingAbandoned,
|
||||
OnboardingCompleted,
|
||||
OnboardingImportEligible,
|
||||
OnboardingImportPublished,
|
||||
OnboardingAgentActivated,
|
||||
}
|
||||
|
||||
impl ProductEventKind {
|
||||
pub const ALL: [Self; 6] = [
|
||||
pub const ALL: [Self; 9] = [
|
||||
Self::OnboardingEligible,
|
||||
Self::OnboardingStarted,
|
||||
Self::OnboardingResumed,
|
||||
Self::OnboardingDismissed,
|
||||
Self::OnboardingAbandoned,
|
||||
Self::OnboardingCompleted,
|
||||
Self::OnboardingImportEligible,
|
||||
Self::OnboardingImportPublished,
|
||||
Self::OnboardingAgentActivated,
|
||||
];
|
||||
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
@@ -36,8 +42,23 @@ impl ProductEventKind {
|
||||
Self::OnboardingDismissed => "onboarding_dismissed",
|
||||
Self::OnboardingAbandoned => "onboarding_abandoned",
|
||||
Self::OnboardingCompleted => "onboarding_completed",
|
||||
Self::OnboardingImportEligible => "onboarding_import_eligible",
|
||||
Self::OnboardingImportPublished => "onboarding_import_published",
|
||||
Self::OnboardingAgentActivated => "onboarding_agent_activated",
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-owned import funnel milestones are never part of the closed
|
||||
/// client-presentation vocabulary, so Admin must reject them on the
|
||||
/// public event endpoint.
|
||||
pub const fn is_server_owned_import_milestone(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::OnboardingImportEligible
|
||||
| Self::OnboardingImportPublished
|
||||
| Self::OnboardingAgentActivated
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -101,7 +122,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn vocabulary_is_closed_and_stable() {
|
||||
assert_eq!(ProductEventKind::ALL.len(), 6);
|
||||
assert_eq!(ProductEventKind::ALL.len(), 9);
|
||||
assert_eq!(
|
||||
ProductEventKind::OnboardingCompleted.as_str(),
|
||||
"onboarding_completed"
|
||||
|
||||
@@ -13,5 +13,6 @@ crank-schema = { path = "../crank-schema" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
url.workspace = true
|
||||
@@ -0,0 +1,650 @@
|
||||
//! Bounded, no-materialization preflight for JSON/YAML source documents.
|
||||
//!
|
||||
//! `serde_yaml` materializes alias expansions into owned `Value` trees, so the
|
||||
//! existing post-decode `validate_value_limits` runs too late: a small source
|
||||
//! with few aliases can expand to many MiB before the limit is observed. This
|
||||
//! module walks the same logical, alias-expanded structure with a
|
||||
//! `serde::de::Visitor` that stores no values, strings, keys or collection
|
||||
//! entries, charging an aggregate expanded string/key budget as it goes.
|
||||
//!
|
||||
//! Semantics preserved:
|
||||
//! - the preflight is permissive about duplicate mapping keys, non-finite
|
||||
//! numbers, tags and non-standard keys; the existing strict/legacy
|
||||
//! materializers decide those (so their errors are unchanged);
|
||||
//! - each JSON or YAML parse attempt uses fresh per-document counters, while
|
||||
//! the shared aggregate budget is not reset and is committed only after a
|
||||
//! document fully passes, so an abandoned fallback attempt cannot be
|
||||
//! charged twice;
|
||||
//! - a budget failure is reported as `ImportParseError::LimitExceeded`, while
|
||||
//! syntax/duplicate/conversion failures stay `InvalidDocument`.
|
||||
|
||||
use serde::de::{
|
||||
self, DeserializeSeed, Deserializer, EnumAccess, IgnoredAny, MapAccess, SeqAccess,
|
||||
VariantAccess, Visitor,
|
||||
};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::model::{ExternalDocumentSnapshot, NormalizationConfig};
|
||||
use super::normalize::ImportParseError;
|
||||
|
||||
/// Internal hard ceiling for expanded string/key bytes in one document set.
|
||||
/// This is deliberately not a `NormalizationConfig` field.
|
||||
const HARD_EXPANDED_BYTES_CAP: u64 = 64 * 1024 * 1024;
|
||||
/// Aggregate allowance per unit of the applicable raw byte limit.
|
||||
const EXPANSION_FACTOR: u64 = 16;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ShapeLimits {
|
||||
pub max_nodes: u64,
|
||||
pub max_depth: u64,
|
||||
pub max_collection_items: u64,
|
||||
pub max_scalar_bytes: u64,
|
||||
}
|
||||
|
||||
impl ShapeLimits {
|
||||
pub(super) fn from_config(config: &NormalizationConfig) -> Self {
|
||||
Self {
|
||||
max_nodes: config.max_nodes as u64,
|
||||
max_depth: config.max_depth as u64,
|
||||
max_collection_items: config.max_collection_items as u64,
|
||||
max_scalar_bytes: config.max_scalar_bytes as u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `min(16 * max(raw_limit, max_scalar_bytes), 64 MiB)` with checked overflow.
|
||||
pub(super) fn allowance(
|
||||
raw_limit: usize,
|
||||
max_scalar_bytes: usize,
|
||||
) -> Result<u64, ImportParseError> {
|
||||
let base = (raw_limit as u64).max(max_scalar_bytes as u64);
|
||||
match base.checked_mul(EXPANSION_FACTOR) {
|
||||
Some(value) => Ok(value.min(HARD_EXPANDED_BYTES_CAP)),
|
||||
None => Err(ImportParseError::LimitExceeded),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared expanded-byte budget across one document set. `used` is only
|
||||
/// advanced after a document passes preflight.
|
||||
pub(super) struct AggregateBudget {
|
||||
limit: u64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
impl AggregateBudget {
|
||||
pub(super) fn empty() -> Self {
|
||||
Self { limit: 0, used: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn reserve(&mut self, allowance: u64) -> Result<(), ImportParseError> {
|
||||
self.limit = self
|
||||
.limit
|
||||
.checked_add(allowance)
|
||||
.ok_or(ImportParseError::LimitExceeded)?
|
||||
.min(HARD_EXPANDED_BYTES_CAP);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
bytes: u64,
|
||||
nodes: u64,
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn new(shape: ShapeLimits, allowance: u64) -> Self {
|
||||
Self {
|
||||
shape,
|
||||
allowance,
|
||||
bytes: 0,
|
||||
nodes: 0,
|
||||
exceeded: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preflight_document(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Result<(), ImportParseError> {
|
||||
match attempt_json(document, shape, allowance, aggregate) {
|
||||
Attempt::Ok => return Ok(()),
|
||||
Attempt::Budget => return Err(ImportParseError::LimitExceeded),
|
||||
Attempt::Syntax => {}
|
||||
}
|
||||
match attempt_yaml(document, shape, allowance, aggregate) {
|
||||
Attempt::Ok => Ok(()),
|
||||
Attempt::Budget => Err(ImportParseError::LimitExceeded),
|
||||
Attempt::Syntax => Err(ImportParseError::InvalidDocument),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preflight_single(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
raw_limit: usize,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let allowance = allowance(raw_limit, shape.max_scalar_bytes as usize)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(allowance)?;
|
||||
preflight_document(document, shape, allowance, &mut aggregate)
|
||||
}
|
||||
|
||||
/// Preflights a primary document using `config.max_bytes`.
|
||||
pub(super) fn preflight_primary(
|
||||
document: &str,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
preflight_single(document, ShapeLimits::from_config(config), config.max_bytes)
|
||||
}
|
||||
|
||||
/// Preflights a primary document and its supplied external snapshots as one
|
||||
/// set with a shared aggregate budget. Raw byte/alias guards remain the
|
||||
/// caller's responsibility.
|
||||
pub(super) fn preflight_bundle(
|
||||
primary: &str,
|
||||
snapshots: &[ExternalDocumentSnapshot],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let shape = ShapeLimits::from_config(config);
|
||||
let primary_allowance = allowance(config.max_bytes, config.max_scalar_bytes)?;
|
||||
let external_allowance =
|
||||
allowance(config.max_external_document_bytes, config.max_scalar_bytes)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(primary_allowance)?;
|
||||
for _ in snapshots {
|
||||
aggregate.reserve(external_allowance)?;
|
||||
}
|
||||
preflight_document(primary, shape, primary_allowance, &mut aggregate)?;
|
||||
for snapshot in snapshots {
|
||||
preflight_document(
|
||||
&snapshot.document,
|
||||
shape,
|
||||
external_allowance,
|
||||
&mut aggregate,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Preflights a raw bundle where every document shares `config.max_bytes`.
|
||||
pub(super) fn preflight_raw_bundle(
|
||||
documents: &[&str],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let shape = ShapeLimits::from_config(config);
|
||||
let allowance = allowance(config.max_bytes, config.max_scalar_bytes)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
for _ in documents {
|
||||
aggregate.reserve(allowance)?;
|
||||
}
|
||||
for document in documents {
|
||||
preflight_document(document, shape, allowance, &mut aggregate)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum Attempt {
|
||||
Ok,
|
||||
Budget,
|
||||
Syntax,
|
||||
}
|
||||
|
||||
fn attempt_json(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Attempt {
|
||||
let mut state = State::new(shape, allowance);
|
||||
let mut de = serde_json::Deserializer::from_str(document);
|
||||
let seed = Seed {
|
||||
state: &mut state,
|
||||
aggregate,
|
||||
depth: 0,
|
||||
mode: Mode::Value,
|
||||
};
|
||||
let result = match seed.deserialize(&mut de) {
|
||||
Ok(()) => de.end(),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
finish(result, &state, aggregate)
|
||||
}
|
||||
|
||||
fn attempt_yaml(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Attempt {
|
||||
let mut state = State::new(shape, allowance);
|
||||
let seed = Seed {
|
||||
state: &mut state,
|
||||
aggregate,
|
||||
depth: 0,
|
||||
mode: Mode::Value,
|
||||
};
|
||||
let result = seed.deserialize(serde_yaml::Deserializer::from_str(document));
|
||||
finish(result, &state, aggregate)
|
||||
}
|
||||
|
||||
fn finish<E>(result: Result<(), E>, state: &State, aggregate: &mut AggregateBudget) -> Attempt {
|
||||
if result.is_err() {
|
||||
return if state.exceeded {
|
||||
Attempt::Budget
|
||||
} else {
|
||||
Attempt::Syntax
|
||||
};
|
||||
}
|
||||
match aggregate.used.checked_add(state.bytes) {
|
||||
Some(total) if total <= aggregate.limit => {
|
||||
aggregate.used = total;
|
||||
Attempt::Ok
|
||||
}
|
||||
_ => Attempt::Budget,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Value,
|
||||
Key,
|
||||
}
|
||||
|
||||
struct Seed<'a> {
|
||||
state: &'a mut State,
|
||||
aggregate: &'a mut AggregateBudget,
|
||||
depth: u64,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl<'de, 'a> DeserializeSeed<'de> for Seed<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(Probe {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth,
|
||||
mode: self.mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Probe<'a> {
|
||||
state: &'a mut State,
|
||||
aggregate: &'a mut AggregateBudget,
|
||||
depth: u64,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl<'a> Probe<'a> {
|
||||
fn fail<E: de::Error>(&mut self) -> E {
|
||||
self.state.exceeded = true;
|
||||
E::custom("normalization decode budget exceeded")
|
||||
}
|
||||
|
||||
/// Charges expanded string/key bytes and the per-scalar limit. Returns an
|
||||
/// internal error that the caller turns into `fail()`.
|
||||
fn charge(&mut self, len: u64) -> Result<(), ()> {
|
||||
if len > self.state.shape.max_scalar_bytes {
|
||||
return Err(());
|
||||
}
|
||||
self.state.bytes = self.state.bytes.checked_add(len).ok_or(())?;
|
||||
if self.state.bytes > self.state.allowance {
|
||||
return Err(());
|
||||
}
|
||||
let total = self
|
||||
.aggregate
|
||||
.used
|
||||
.checked_add(self.state.bytes)
|
||||
.ok_or(())?;
|
||||
if total > self.aggregate.limit {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn enter_value<E: de::Error>(&mut self) -> Result<(), E> {
|
||||
if self.depth > self.state.shape.max_depth {
|
||||
return Err(self.fail());
|
||||
}
|
||||
match self.state.nodes.checked_add(1) {
|
||||
Some(nodes) => self.state.nodes = nodes,
|
||||
None => return Err(self.fail()),
|
||||
}
|
||||
if self.state.nodes > self.state.shape.max_nodes {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounds depth for composite keys without counting a value node, so
|
||||
/// ordinary scalar mapping keys keep their existing accounting.
|
||||
fn check_depth<E: de::Error>(&mut self) -> Result<(), E> {
|
||||
if self.depth > self.state.shape.max_depth {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn charge_scalar<E: de::Error>(&mut self, len: usize) -> Result<(), E> {
|
||||
if self.charge(len as u64).is_err() {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn value_or_scalar<E: de::Error>(&mut self, len: Option<usize>) -> Result<(), E> {
|
||||
if self.mode == Mode::Value {
|
||||
self.enter_value::<E>()?;
|
||||
}
|
||||
match len {
|
||||
Some(len) => self.charge_scalar::<E>(len),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a> Visitor<'de> for Probe<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON- or YAML-compatible value")
|
||||
}
|
||||
|
||||
fn visit_bool<E: de::Error>(mut self, _value: bool) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_i64<E: de::Error>(mut self, _value: i64) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_u64<E: de::Error>(mut self, _value: u64) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_i128<E: de::Error>(mut self, _value: i128) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_u128<E: de::Error>(mut self, _value: u128) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_f64<E: de::Error>(mut self, _value: f64) -> Result<(), E> {
|
||||
// Non-finite numbers are deliberately accepted here; the materializer
|
||||
// decides their validity.
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_char<E: de::Error>(mut self, value: char) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len_utf8()))
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(mut self, value: &str) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(mut self, value: String) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_bytes<E: de::Error>(mut self, value: &[u8]) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_byte_buf<E: de::Error>(mut self, value: Vec<u8>) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_unit<E: de::Error>(mut self) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(mut self) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth,
|
||||
mode: self.mode,
|
||||
}
|
||||
.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: self.mode,
|
||||
}
|
||||
.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_seq<A>(mut self, mut seq: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
match self.mode {
|
||||
Mode::Value => self.enter_value::<A::Error>()?,
|
||||
Mode::Key => self.check_depth::<A::Error>()?,
|
||||
}
|
||||
let collection_limit = self.state.shape.max_collection_items;
|
||||
if seq
|
||||
.size_hint()
|
||||
.is_some_and(|hint| hint as u64 > collection_limit)
|
||||
{
|
||||
return Err(self.fail());
|
||||
}
|
||||
let mut count: u64 = 0;
|
||||
while seq
|
||||
.next_element_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Value,
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
count += 1;
|
||||
if count > self.state.shape.max_collection_items {
|
||||
return Err(self.fail());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_map<A>(mut self, mut map: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
match self.mode {
|
||||
Mode::Value => self.enter_value::<A::Error>()?,
|
||||
Mode::Key => self.check_depth::<A::Error>()?,
|
||||
}
|
||||
let collection_limit = self.state.shape.max_collection_items;
|
||||
if map
|
||||
.size_hint()
|
||||
.is_some_and(|hint| hint as u64 > collection_limit)
|
||||
{
|
||||
return Err(self.fail());
|
||||
}
|
||||
let mut count: u64 = 0;
|
||||
while map
|
||||
.next_key_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Key,
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
count += 1;
|
||||
if count > self.state.shape.max_collection_items {
|
||||
return Err(self.fail());
|
||||
}
|
||||
map.next_value_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Value,
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_enum<A>(self, data: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: EnumAccess<'de>,
|
||||
{
|
||||
// Tagged values are traversed permissively and bounded; the
|
||||
// materializer keeps the final say on tag semantics.
|
||||
let (_variant, variant) = data.variant_seed(PhantomData::<IgnoredAny>)?;
|
||||
variant.newtype_variant_seed(Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: self.mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn shape(
|
||||
max_nodes: u64,
|
||||
max_depth: u64,
|
||||
max_collection_items: u64,
|
||||
max_scalar_bytes: u64,
|
||||
) -> ShapeLimits {
|
||||
ShapeLimits {
|
||||
max_nodes,
|
||||
max_depth,
|
||||
max_collection_items,
|
||||
max_scalar_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn wide() -> ShapeLimits {
|
||||
shape(1_000, 64, 1_000, 1_000)
|
||||
}
|
||||
|
||||
fn run(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
limit: u64,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.limit = limit;
|
||||
preflight_document(document, shape, allowance, &mut aggregate)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_aggregate_boundary_is_inclusive() {
|
||||
let shape = wide();
|
||||
assert!(run("\"abc\"", shape, 3, 3).is_ok());
|
||||
assert_eq!(
|
||||
run("\"abc\"", shape, 2, 3),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_depth_collection_and_node_limits_fail_before_materialization() {
|
||||
let scalar = shape(1_000, 64, 1_000, 2);
|
||||
assert_eq!(
|
||||
run("\"abc\"", scalar, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let depth = shape(1_000, 1, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":{\"b\":1}}", depth, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let collection = shape(1_000, 64, 1, 1_000);
|
||||
assert_eq!(
|
||||
run("[1,2]", collection, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let nodes = shape(1, 64, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":1}", nodes, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_keys_do_not_consume_value_nodes() {
|
||||
let node_limited = shape(3, 64, 1_000, 1_000);
|
||||
assert!(run("{\"a\":1,\"b\":2}", node_limited, 1_000, 1_000).is_ok());
|
||||
let stricter = shape(2, 64, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":1,\"b\":2}", stricter, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_mapping_keys_are_depth_bounded() {
|
||||
// A mapping used as a mapping key, whose own key is again a mapping,
|
||||
// must not evade `max_depth`; the fix increases key-child depth.
|
||||
let document = "? {? {a: b}: c}\n: value\n";
|
||||
let shallow = shape(1_000, 1, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run(document, shallow, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
let deep = shape(1_000, 64, 1_000, 1_000);
|
||||
assert!(run(document, deep, 1_000, 1_000).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_aggregate_is_not_reset_between_documents() {
|
||||
let shape = wide();
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.limit = 7;
|
||||
assert!(preflight_document("\"abcd\"", shape, 5, &mut aggregate).is_ok());
|
||||
assert_eq!(
|
||||
preflight_document("\"efgh\"", shape, 5, &mut aggregate),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserve_caps_and_allowance_is_overflow_safe() {
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(HARD_EXPANDED_BYTES_CAP).unwrap();
|
||||
aggregate.reserve(HARD_EXPANDED_BYTES_CAP).unwrap();
|
||||
assert_eq!(aggregate.limit, HARD_EXPANDED_BYTES_CAP);
|
||||
assert_eq!(
|
||||
allowance(usize::MAX, usize::MAX),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,6 @@ pub(super) fn invalid_path_item() -> ImportFinding {
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
@@ -127,8 +127,10 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
status: String::new(),
|
||||
source_location: operation.source_location.clone(),
|
||||
security_requirements: Default::default(),
|
||||
security_schemes: Default::default(),
|
||||
security_schemes: BTreeMap::new(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
suggested_name: name,
|
||||
suggested_display_name: display_name,
|
||||
|
||||
@@ -1,70 +1,444 @@
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, SourceLocation},
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn collect_secret_like_examples(
|
||||
value: &Value,
|
||||
pub(super) const REDACTED_LITERAL: &str = "[REDACTED]";
|
||||
|
||||
/// Redacts credential-like literals before they enter the normalized tree,
|
||||
/// while retaining stable source locations for review findings.
|
||||
pub(super) fn redact_secret_like_literals(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
inside_example: bool,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
let declared_names = credential_names(std::iter::once(&*value));
|
||||
redact_secret_like_literals_with_names(value, pointer, &declared_names, findings, locations);
|
||||
}
|
||||
|
||||
pub(super) fn redact_secret_like_literals_with_names(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
declared_names: &CredentialNames,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
visit(
|
||||
value,
|
||||
pointer,
|
||||
VisitContext {
|
||||
in_secret_example: false,
|
||||
sensitive_parameter_schema: false,
|
||||
force_redact: false,
|
||||
declared_names,
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CredentialNames {
|
||||
header: BTreeSet<String>,
|
||||
query: BTreeSet<String>,
|
||||
cookie: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct VisitContext<'a> {
|
||||
in_secret_example: bool,
|
||||
sensitive_parameter_schema: bool,
|
||||
force_redact: bool,
|
||||
declared_names: &'a CredentialNames,
|
||||
}
|
||||
|
||||
impl CredentialNames {
|
||||
fn contains(&self, location: &str, name: &str) -> bool {
|
||||
let names = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => &self.header,
|
||||
"query" => &self.query,
|
||||
"cookie" => &self.cookie,
|
||||
_ => return false,
|
||||
};
|
||||
names.contains(&name.to_ascii_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn credential_names<'a>(roots: impl IntoIterator<Item = &'a Value>) -> CredentialNames {
|
||||
let mut names = CredentialNames::default();
|
||||
for root in roots {
|
||||
collect_credential_names(root, &mut names);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn collect_credential_names(value: &Value, names: &mut CredentialNames) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
if fields.get("type").and_then(Value::as_str) == Some("apiKey")
|
||||
&& let (Some(location), Some(name)) = (
|
||||
fields.get("in").and_then(Value::as_str),
|
||||
fields.get("name").and_then(Value::as_str),
|
||||
)
|
||||
{
|
||||
let destination = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => Some(&mut names.header),
|
||||
"query" => Some(&mut names.query),
|
||||
"cookie" => Some(&mut names.cookie),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(destination) = destination {
|
||||
destination.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
for child in fields.values() {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for child in items {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
context: VisitContext<'_>,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
if context.force_redact
|
||||
|| value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, context.declared_names))
|
||||
|| (context.in_secret_example && value.as_str() == Some(REDACTED_LITERAL))
|
||||
|| (context.in_secret_example && scalar_looks_secret(value))
|
||||
{
|
||||
redact(value, context.force_redact, context.declared_names);
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"В исходном документе обнаружено значение, похожее на секрет; оно удалено из импортируемых данных.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let sensitive_parameter =
|
||||
fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| {
|
||||
["header", "query", "cookie"]
|
||||
.iter()
|
||||
.any(|allowed| location.eq_ignore_ascii_case(allowed))
|
||||
})
|
||||
&& fields
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|name| {
|
||||
is_sensitive_name(name)
|
||||
|| fields.get("in").and_then(Value::as_str).is_some_and(
|
||||
|location| context.declared_names.contains(location, name),
|
||||
)
|
||||
});
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
collect_secret_like_examples(
|
||||
let key_lower = key.to_ascii_lowercase();
|
||||
let in_example = context.in_secret_example
|
||||
|| matches!(
|
||||
key_lower.as_str(),
|
||||
"default"
|
||||
| "example"
|
||||
| "examples"
|
||||
| "x-example"
|
||||
| "x-examples"
|
||||
| "bearerformat"
|
||||
| "x-format-hint"
|
||||
);
|
||||
let sensitive_header_definition = pointer.ends_with("/headers")
|
||||
&& (is_sensitive_name(key) || context.declared_names.contains("header", key));
|
||||
let parameter_value = (sensitive_parameter || sensitive_header_definition)
|
||||
&& matches!(
|
||||
key_lower.as_str(),
|
||||
"example" | "examples" | "x-example" | "x-examples"
|
||||
);
|
||||
let parameter_schema = context.sensitive_parameter_schema
|
||||
|| sensitive_header_definition
|
||||
|| (sensitive_parameter && key_lower == "schema");
|
||||
let parent_is_secret_property =
|
||||
pointer.rsplit('/').next().is_some_and(is_sensitive_name);
|
||||
// Names in schema/scheme maps and security requirements are
|
||||
// identifiers, not credential values. Traverse their metadata
|
||||
// and redact the actual defaults/examples instead.
|
||||
let identifier_map = (child.is_object()
|
||||
&& (pointer.ends_with("/properties")
|
||||
|| pointer.ends_with("/headers")
|
||||
|| pointer == "/components/schemas"
|
||||
|| pointer == "/definitions"
|
||||
|| pointer == "/components/securitySchemes"
|
||||
|| pointer == "/securityDefinitions"))
|
||||
|| (child.is_array()
|
||||
&& pointer.rsplit_once('/').is_some_and(|(parent, index)| {
|
||||
parent.ends_with("/security") && index.parse::<usize>().is_ok()
|
||||
}));
|
||||
let force_child = (is_sensitive_name(key) && !identifier_map)
|
||||
|| (matches!(key_lower.as_str(), "default" | "example" | "examples")
|
||||
&& parent_is_secret_property)
|
||||
|| parameter_value
|
||||
|| (sensitive_parameter
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"))
|
||||
|| (parameter_schema
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"));
|
||||
visit(
|
||||
child,
|
||||
&child_pointer,
|
||||
inside_example || matches!(key.as_str(), "example" | "examples"),
|
||||
VisitContext {
|
||||
in_secret_example: in_example,
|
||||
sensitive_parameter_schema: parameter_schema,
|
||||
force_redact: force_child,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter().enumerate() {
|
||||
collect_secret_like_examples(
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
visit(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
inside_example,
|
||||
VisitContext {
|
||||
force_redact: false,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
fn is_sensitive_name(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if lower.starts_with('/')
|
||||
|| matches!(
|
||||
lower.as_str(),
|
||||
"url"
|
||||
| "tokenurl"
|
||||
| "authorizationurl"
|
||||
| "refreshurl"
|
||||
| "openidconnecturl"
|
||||
| "clientcredentials"
|
||||
| "authorizationcode"
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let compact = lower.replace(['-', '_'], "");
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"apikey",
|
||||
"accesskey",
|
||||
"ciphertext",
|
||||
"privatekey",
|
||||
"passwd",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| compact.contains(marker))
|
||||
}
|
||||
|
||||
fn scalar_looks_secret(value: &Value) -> bool {
|
||||
let Value::String(value) = value else {
|
||||
return false;
|
||||
};
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
.any(|marker| value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
|| looks_like_jwt(&value)
|
||||
}
|
||||
|
||||
fn looks_like_jwt(value: &str) -> bool {
|
||||
let mut segments = value.split('.');
|
||||
let (Some(header), Some(payload), Some(signature), None) = (
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
header.starts_with("eyj")
|
||||
&& !payload.is_empty()
|
||||
&& signature.len() >= 8
|
||||
&& [header, payload, signature].iter().all(|segment| {
|
||||
segment
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn url_has_secret(value: &str) -> bool {
|
||||
url_has_secret_named(value, &CredentialNames::default())
|
||||
}
|
||||
|
||||
fn url_has_secret_named(value: &str, declared_names: &CredentialNames) -> bool {
|
||||
url_userinfo(value).is_some()
|
||||
|| query_has_secret_parameter(value, &declared_names.query)
|
||||
|| fragment_has_secret_parameter(value)
|
||||
}
|
||||
|
||||
fn fragment_has_secret_parameter(value: &str) -> bool {
|
||||
let Some((_, fragment)) = value.split_once('#') else {
|
||||
return false;
|
||||
};
|
||||
if fragment.starts_with('/') {
|
||||
return false;
|
||||
}
|
||||
url::form_urlencoded::parse(fragment.as_bytes()).any(|(name, _)| is_sensitive_name(&name))
|
||||
}
|
||||
|
||||
fn redact_url_fragment(value: &str) -> String {
|
||||
let Some((base, fragment)) = value.split_once('#') else {
|
||||
return value.to_owned();
|
||||
};
|
||||
if fragment.starts_with('/') || !fragment.contains('=') {
|
||||
return value.to_owned();
|
||||
}
|
||||
let redacted = fragment
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, parameter_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name) {
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={parameter_value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{base}#{redacted}")
|
||||
}
|
||||
|
||||
fn url_userinfo(value: &str) -> Option<(&str, &str, &str)> {
|
||||
let (scheme, rest) = value
|
||||
.split_once("://")
|
||||
.or_else(|| value.strip_prefix("//").map(|rest| ("", rest)))?;
|
||||
let (authority, suffix) = rest
|
||||
.find(['/', '?', '#'])
|
||||
.map_or((rest, ""), |index| (&rest[..index], &rest[index..]));
|
||||
let (userinfo, host) = authority.split_once('@')?;
|
||||
if userinfo.is_empty() || host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((scheme, host, suffix))
|
||||
}
|
||||
|
||||
fn query_has_secret_parameter(value: &str, declared_query_names: &BTreeSet<String>) -> bool {
|
||||
let Some((_, query)) = value.split_once('?') else {
|
||||
return false;
|
||||
};
|
||||
let query = query.split('#').next().unwrap_or(query);
|
||||
url::form_urlencoded::parse(query.as_bytes()).any(|(name, _)| {
|
||||
is_sensitive_name(&name) || declared_query_names.contains(&name.to_ascii_lowercase())
|
||||
})
|
||||
}
|
||||
|
||||
fn redact(value: &mut Value, force: bool, declared_names: &CredentialNames) {
|
||||
if force
|
||||
|| !value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, declared_names))
|
||||
{
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
return;
|
||||
}
|
||||
if let Value::String(text) = value {
|
||||
if force {
|
||||
*text = REDACTED_LITERAL.to_owned();
|
||||
return;
|
||||
}
|
||||
let mut sanitized = text.clone();
|
||||
if let Some((scheme, host, suffix)) = url_userinfo(&sanitized) {
|
||||
sanitized = if scheme.is_empty() {
|
||||
format!("//{host}{suffix}")
|
||||
} else {
|
||||
format!("{scheme}://{host}{suffix}")
|
||||
};
|
||||
}
|
||||
if query_has_secret_parameter(&sanitized, &declared_names.query)
|
||||
&& let Some((base, query)) = sanitized.split_once('?')
|
||||
{
|
||||
let (query, fragment) = query
|
||||
.split_once('#')
|
||||
.map_or((query, None), |(query, fragment)| (query, Some(fragment)));
|
||||
let redacted = query
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name)
|
||||
|| declared_names
|
||||
.query
|
||||
.contains(&decoded_name.to_ascii_lowercase())
|
||||
{
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
sanitized = match fragment {
|
||||
Some(fragment) => format!("{base}?{redacted}#{fragment}"),
|
||||
None => format!("{base}?{redacted}"),
|
||||
};
|
||||
}
|
||||
*text = redact_url_fragment(&sanitized);
|
||||
} else {
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,39 @@
|
||||
mod decode_budget;
|
||||
mod http_methods;
|
||||
mod legacy_mapping;
|
||||
mod legacy_payload;
|
||||
mod legacy_schema;
|
||||
mod mapping;
|
||||
mod metadata_findings;
|
||||
pub mod model;
|
||||
mod naming;
|
||||
mod normalize;
|
||||
mod normalize_coverage;
|
||||
mod normalize_finding_validation;
|
||||
mod normalize_limits;
|
||||
mod normalize_preview;
|
||||
mod normalize_projection;
|
||||
mod normalize_schema;
|
||||
mod normalize_security;
|
||||
mod openapi3;
|
||||
mod openapi3_findings;
|
||||
mod openapi3_legacy;
|
||||
mod parser_findings;
|
||||
mod payload;
|
||||
mod recommendations;
|
||||
mod reference;
|
||||
mod reference_budget;
|
||||
mod schema;
|
||||
mod security;
|
||||
mod security_literals;
|
||||
mod source_safety;
|
||||
mod strict_decode;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
mod swagger2_legacy;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportOperationCandidate,
|
||||
ImportPreview, ImportSourcePreview, NORMALIZER_VERSION, NormalizationConfig, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedReference,
|
||||
NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportNameConflict,
|
||||
ImportOperationCandidate, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedReference, NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
NormalizedSchemaConstraints, NormalizedSchemaKind, NormalizedSecurityRequirements,
|
||||
NormalizedSecurityScheme, NormalizedSecuritySchemeKind, PROJECTION_VERSION,
|
||||
ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate,
|
||||
@@ -42,7 +45,9 @@ pub use model::{
|
||||
pub use normalize::{
|
||||
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
||||
normalize_verified_document, preview_document, preview_document_legacy_v1, preview_from_ir,
|
||||
reference_uris, validate_normalized_ir,
|
||||
reference_uris, validate_document_source_safe, validate_normalized_ir,
|
||||
};
|
||||
pub use payload::operation_draft_from_candidate;
|
||||
pub use security_literals::{SecretLiteralFinding, scan_secret_literals};
|
||||
pub use source_safety::{
|
||||
validate_document_bundle_source_safe, validate_resolved_bundle_source_safe,
|
||||
};
|
||||
@@ -10,7 +10,7 @@ use serde_json::Value;
|
||||
/// deliberately travel with an import job: changing either contract must not
|
||||
/// silently reinterpret a pending preview.
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v5";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v5";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v6";
|
||||
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
@@ -496,6 +496,10 @@ pub struct ImportFinding {
|
||||
pub message: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub operation_key: Option<String>,
|
||||
/// RFC 6901 source pointer of the finding. Optional so preview payloads
|
||||
/// persisted before this field was introduced still deserialize.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -514,6 +518,17 @@ pub struct ImportPreview {
|
||||
pub groups: Vec<ImportGroupPreview>,
|
||||
#[serde(default)]
|
||||
pub findings: Vec<ImportFinding>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub conflicts: Vec<ImportNameConflict>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ImportNameConflict {
|
||||
pub operation_key: String,
|
||||
pub conflict_type: String,
|
||||
pub proposed_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -528,6 +543,13 @@ pub struct ImportOperationCandidate {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
/// Workspace-aware readiness is attached by the API after immutable replay.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub status: String,
|
||||
/// RFC 6901 pointer of the source operation. Optional so preview payloads
|
||||
/// persisted before this field was introduced still deserialize.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
@@ -583,6 +605,10 @@ pub struct RestImportOperation {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
/// Authoritative RFC 6901 pointer of the operation when it was produced by
|
||||
/// the normalizer. Parser state only; never persisted.
|
||||
#[serde(skip)]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::rest::{
|
||||
openapi3, swagger2,
|
||||
};
|
||||
|
||||
use super::decode_budget;
|
||||
use super::normalize_coverage;
|
||||
use super::normalize_limits;
|
||||
|
||||
@@ -61,9 +62,9 @@ pub fn external_reference_uris(
|
||||
pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, ImportParseError> {
|
||||
let root = decode_legacy_v1(document)?;
|
||||
let mut parsed = match root.get("openapi") {
|
||||
Some(_) => super::openapi3_legacy::parse_document_legacy_v1(&root)?,
|
||||
Some(_) => openapi3::parse_document_legacy_v1(&root)?,
|
||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||
super::swagger2_legacy::parse_document_legacy_v1(&root)?
|
||||
swagger2::parse_document_legacy_v1(&root)?
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
@@ -80,7 +81,7 @@ pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, Impor
|
||||
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
}
|
||||
Ok(super::normalize_preview::preview_from_document(parsed))
|
||||
Ok(preview_from_document(parsed))
|
||||
}
|
||||
|
||||
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
@@ -90,6 +91,7 @@ fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_primary(document, &config)?;
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, &config)?;
|
||||
Ok(root)
|
||||
@@ -103,6 +105,39 @@ pub fn normalize_verified_document(
|
||||
normalize_verified_bundle(document, digest, &[], config)
|
||||
}
|
||||
|
||||
/// Rejects source documents containing credential-like literals before a
|
||||
/// caller persists their original bytes. Accepted source bytes remain verbatim.
|
||||
pub fn validate_document_source_safe(
|
||||
document: &str,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_primary(document, config)?;
|
||||
let mut root =
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
super::metadata_findings::redact_secret_like_literals(
|
||||
&mut root,
|
||||
"",
|
||||
&mut findings,
|
||||
&mut locations,
|
||||
);
|
||||
if findings.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ImportParseError::InvalidDocument)
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalizes a verified primary document together with immutable external
|
||||
/// snapshots. This function is pure: callers must perform all URL policy,
|
||||
/// fetching, artifact persistence and digest verification beforehand.
|
||||
@@ -120,12 +155,24 @@ pub fn normalize_verified_bundle(
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
if snapshots.len() > config.max_reference_documents {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes
|
||||
|| normalize_limits::alias_count(&snapshot.document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_bundle(document, snapshots, config)?;
|
||||
let source_syntax = if serde_json::from_str::<Value>(document).is_ok() {
|
||||
SourceSyntax::Json
|
||||
} else {
|
||||
SourceSyntax::Yaml
|
||||
};
|
||||
let root = decode(document)?;
|
||||
let root =
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes {
|
||||
@@ -136,7 +183,14 @@ pub fn normalize_verified_bundle(
|
||||
let mut root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let redacted_literals = super::security_literals::inspect_and_redact(&mut root);
|
||||
let mut literal_findings = Vec::new();
|
||||
let mut literal_locations = Vec::new();
|
||||
super::metadata_findings::redact_secret_like_literals(
|
||||
&mut root,
|
||||
"",
|
||||
&mut literal_findings,
|
||||
&mut literal_locations,
|
||||
);
|
||||
|
||||
let mut parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
||||
@@ -146,15 +200,8 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
for literal in redacted_literals {
|
||||
parsed.findings.push(super::recommendations::document_finding(
|
||||
"secret_literal_redacted",
|
||||
"Документ содержит literal credential; значение удалено из normalized representation.",
|
||||
));
|
||||
parsed
|
||||
.internal_finding_locations
|
||||
.push(Some(literal.location));
|
||||
}
|
||||
parsed.findings.extend(literal_findings);
|
||||
parsed.internal_finding_locations.extend(literal_locations);
|
||||
|
||||
if parsed.operations.is_empty()
|
||||
&& !parsed
|
||||
@@ -176,7 +223,11 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
|
||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
super::normalize_preview::preview_from_ir(ir)
|
||||
super::normalize_projection::preview_from_ir(ir)
|
||||
}
|
||||
|
||||
fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
super::normalize_projection::preview_from_document(document)
|
||||
}
|
||||
|
||||
pub(super) fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||
@@ -205,7 +256,6 @@ fn canonicalize(
|
||||
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
||||
resolution_findings: Vec<NormalizedFinding>,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
let security_schemes = document.security_schemes.clone();
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
@@ -505,8 +555,6 @@ fn canonicalize(
|
||||
key: operation.key,
|
||||
method: operation.method,
|
||||
path: operation.path,
|
||||
security_requirements: operation.security_requirements,
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id,
|
||||
summary: operation.summary,
|
||||
description: operation.description,
|
||||
@@ -517,6 +565,8 @@ fn canonicalize(
|
||||
request_body_variants,
|
||||
response_variants,
|
||||
servers: operation.servers,
|
||||
security_requirements: operation.security_requirements,
|
||||
security_schemes: document.security_schemes.clone(),
|
||||
findings: operation_findings,
|
||||
})
|
||||
})
|
||||
@@ -708,11 +758,11 @@ fn canonicalize(
|
||||
}
|
||||
|
||||
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
if !((ir.normalizer_version == NORMALIZER_VERSION
|
||||
&& ir.projection_version == PROJECTION_VERSION)
|
||||
|| (ir.normalizer_version == crate::rest::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == crate::rest::model::HISTORICAL_PROJECTION_VERSION))
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
validate_reference_graph(ir)?;
|
||||
|
||||
@@ -4,9 +4,9 @@ use serde_json::Value;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, CoverageDisposition, CoverageEntry,
|
||||
ImportSourcePreview, NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath,
|
||||
NormalizedReference, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
SourceLocation,
|
||||
HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION, ImportSourcePreview,
|
||||
NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath, NormalizedReference,
|
||||
NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION, SourceLocation,
|
||||
};
|
||||
|
||||
use super::ImportParseError;
|
||||
@@ -16,11 +16,11 @@ pub(super) use super::normalize_schema::{
|
||||
};
|
||||
|
||||
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
if !((ir.normalizer_version == NORMALIZER_VERSION
|
||||
&& ir.projection_version == PROJECTION_VERSION)
|
||||
|| (ir.normalizer_version == HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == HISTORICAL_PROJECTION_VERSION))
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
let mut source_nodes = BTreeMap::new();
|
||||
@@ -98,15 +98,17 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
.flat_map(|operation| &operation.findings),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
if findings.iter().any(|finding| {
|
||||
is_security_finding_code(&finding.code)
|
||||
&& !super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
}) {
|
||||
for finding in &findings {
|
||||
let source_match =
|
||||
super::normalize_finding_validation::matches_source(finding, ir, &source_nodes);
|
||||
if matches!(
|
||||
finding.code.as_str(),
|
||||
"path_parameter_not_declared" | "unsupported_compound_default"
|
||||
) && !source_match
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
for finding in &findings {
|
||||
if super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
&& finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
if source_match && finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
{
|
||||
insert_real_expected(
|
||||
&mut expected,
|
||||
@@ -155,20 +157,6 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_security_finding_code(code: &str) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes"
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct ExpectedCoverage {
|
||||
location: SourceLocation,
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, ImportFindingSeverity, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedSecuritySchemeKind, SecurityRequirementsSource,
|
||||
NormalizedIr,
|
||||
};
|
||||
|
||||
pub(super) fn matches_source(
|
||||
@@ -48,164 +48,184 @@ pub(super) fn matches_source(
|
||||
finding.operation_key.as_deref() == Some(operation.key.as_str())
|
||||
&& matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(name)) if !operation.path.contains(&format!("{{{name}}}"))))
|
||||
}),
|
||||
"path_parameter_not_declared" if is_error => {
|
||||
path_parameter_missing_in_source(finding, ir, node, nodes)
|
||||
}
|
||||
"unsupported_compound_default" if is_error => {
|
||||
pointer.ends_with("/default")
|
||||
&& matches!(node.value, CanonicalSourceValue::Object(_) | CanonicalSourceValue::Array(_))
|
||||
}
|
||||
"unsupported_schema_keyword" if is_error => schema_keyword(pointer, node),
|
||||
"unsupported_schema_enum" if is_error => {
|
||||
pointer.ends_with("/enum")
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::String(_))))
|
||||
}
|
||||
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
|
||||
matches!(&node.value, CanonicalSourceValue::String(value)
|
||||
if secret_like(pointer, value)
|
||||
|| super::metadata_findings::url_has_secret(value)
|
||||
|| (pointer.ends_with("/url") && !value.contains('@'))
|
||||
|| value == super::metadata_findings::REDACTED_LITERAL
|
||||
|| sanitized_secret_url(value))
|
||||
}
|
||||
"secret_literal_redacted" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
matches!(&node.value, CanonicalSourceValue::String(value) if value == "[REDACTED]")
|
||||
}
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes" => security_finding(finding, ir, nodes),
|
||||
"invalid_server" if is_error => invalid_server(pointer, node),
|
||||
_ => false,
|
||||
"unsupported_security_requirement" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.is_empty())
|
||||
|| invalid_security_requirement(pointer, node)
|
||||
}
|
||||
"invalid_security_requirements" if is_error => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Array(_))
|
||||
|| matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::Object(_))))
|
||||
}
|
||||
|
||||
fn security_finding(
|
||||
finding: &NormalizedFinding,
|
||||
ir: &NormalizedIr,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
let Some(operation) = ir
|
||||
"invalid_security_requirement" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
"unsupported_security_requirements" if is_error => ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(requirements_pointer) = requirements_pointer(operation) else {
|
||||
return false;
|
||||
};
|
||||
let pointer = finding.location.pointer.as_str();
|
||||
let node = nodes.get(pointer).copied();
|
||||
|
||||
match finding.code.as_str() {
|
||||
"invalid_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}
|
||||
"invalid_security_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer).is_some_and(|_| {
|
||||
node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
})
|
||||
}
|
||||
"unresolved_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer)
|
||||
.is_some_and(|name| node.is_some() && !ir.security_schemes.contains_key(name))
|
||||
}
|
||||
"unsupported_security_and_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer)
|
||||
.is_some_and(|alternative| alternative.schemes.len() > 1)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
}
|
||||
"unsupported_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer).is_some_and(|name| {
|
||||
let Some(scheme) = ir.security_schemes.get(name) else {
|
||||
return false;
|
||||
};
|
||||
node.is_some()
|
||||
&& matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
| NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: crate::rest::model::SecurityParameterLocation::Cookie,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
"unsupported_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& !operation.security_requirements.alternatives.is_empty()
|
||||
.is_some_and(|operation| {
|
||||
!operation.security_requirements.alternatives.is_empty()
|
||||
&& operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}),
|
||||
"unsupported_security_and_requirement"
|
||||
if finding.severity == ImportFindingSeverity::Warning =>
|
||||
{
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if fields.len() > 1)
|
||||
}
|
||||
"invalid_security_scopes" | "unexpected_security_scopes" => {
|
||||
if finding.severity != ImportFindingSeverity::Warning {
|
||||
return false;
|
||||
"unsupported_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
|
||||
|| matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::ApiKey { location: crate::rest::model::SecurityParameterLocation::Cookie, .. })
|
||||
}) && matches!(&node.value, CanonicalSourceValue::Array(_))
|
||||
}
|
||||
let Some(name) = scheme_at(operation, pointer) else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = node else {
|
||||
return false;
|
||||
};
|
||||
let valid_scopes = matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
if finding.code == "invalid_security_scopes" {
|
||||
!valid_scopes
|
||||
} else {
|
||||
let nonempty = matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty() && items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
let oauth_scoped = ir.security_schemes.get(name).is_some_and(|scheme| {
|
||||
matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some(scheme_type)
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
"unsupported_security_scheme_definition"
|
||||
if finding.severity == ImportFindingSeverity::Warning =>
|
||||
{
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
|
||||
}) && matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
"unresolved_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
!ir.security_schemes.contains_key(&scheme_name)
|
||||
}
|
||||
"invalid_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))))
|
||||
}
|
||||
"unexpected_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
let supports_scopes = ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { scheme_type: Some(kind) } if matches!(kind.as_str(), "oauth2" | "openIdConnect"))
|
||||
});
|
||||
nonempty && !oauth_scoped
|
||||
}
|
||||
!supports_scopes
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty())
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn requirements_pointer(operation: &NormalizedOperation) -> Option<String> {
|
||||
match operation.security_requirements.source {
|
||||
SecurityRequirementsSource::Document => Some("/security".to_owned()),
|
||||
SecurityRequirementsSource::Operation => {
|
||||
Some(format!("{}/security", operation.location.pointer))
|
||||
fn path_placeholders(path: &str) -> Vec<String> {
|
||||
let mut placeholders = Vec::new();
|
||||
let mut remaining = path;
|
||||
while let Some(open) = remaining.find('{') {
|
||||
let after_open = &remaining[open + 1..];
|
||||
let Some(close) = after_open.find('}') else {
|
||||
break;
|
||||
};
|
||||
if close > 0 {
|
||||
placeholders.push(after_open[..close].to_owned());
|
||||
}
|
||||
SecurityRequirementsSource::None => None,
|
||||
remaining = &after_open[close + 1..];
|
||||
}
|
||||
placeholders
|
||||
}
|
||||
|
||||
fn alternative_at<'a>(
|
||||
operation: &'a NormalizedOperation,
|
||||
pointer: &str,
|
||||
) -> Option<&'a crate::rest::model::SecurityRequirementAlternative> {
|
||||
operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.find(|alternative| {
|
||||
alternative
|
||||
.source_location
|
||||
.as_ref()
|
||||
.is_some_and(|location| location.pointer == pointer)
|
||||
fn path_parameter_missing_in_source(
|
||||
finding: &NormalizedFinding,
|
||||
ir: &NormalizedIr,
|
||||
operation_node: &CanonicalSourceNode,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
let pointer = finding.location.pointer.as_str();
|
||||
let segments = pointer.split('/').collect::<Vec<_>>();
|
||||
if segments.len() != 4 || segments[1] != "paths" {
|
||||
return false;
|
||||
}
|
||||
let path = segments[2].replace("~1", "/").replace("~0", "~");
|
||||
let method = segments[3];
|
||||
let expected_key = format!("{} {path}", method.to_uppercase());
|
||||
let Some(operation) = ir.operations.iter().find(|operation| {
|
||||
operation.key == expected_key
|
||||
&& operation.path == path
|
||||
&& operation.location.pointer == pointer
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
let Some(path_item) = nodes.get(&format!("/paths/{}", segments[2])).copied() else {
|
||||
return false;
|
||||
};
|
||||
let has_declared_parameter = |owner: &CanonicalSourceNode, name: &str| {
|
||||
let CanonicalSourceValue::Object(fields) = &owner.value else {
|
||||
return false;
|
||||
};
|
||||
let Some(CanonicalSourceNode {
|
||||
value: CanonicalSourceValue::Array(parameters),
|
||||
..
|
||||
}) = fields.get("parameters")
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
parameters.iter().any(|parameter| {
|
||||
let CanonicalSourceValue::Object(fields) = ¶meter.value else {
|
||||
return false;
|
||||
};
|
||||
if fields.contains_key("$ref") {
|
||||
return false;
|
||||
}
|
||||
matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if value == name)
|
||||
&& matches!(fields.get("in").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if value == "path")
|
||||
})
|
||||
};
|
||||
path_placeholders(&operation.path).into_iter().any(|name| {
|
||||
!has_declared_parameter(path_item, &name)
|
||||
&& !has_declared_parameter(operation_node, &name)
|
||||
&& !operation.parameters.iter().any(|parameter| {
|
||||
parameter.name == name
|
||||
&& parameter.location == crate::rest::model::RestParameterLocation::Path
|
||||
})
|
||||
}) && finding.operation_key.as_deref() == Some(expected_key.as_str())
|
||||
}
|
||||
|
||||
fn scheme_at<'a>(operation: &'a NormalizedOperation, pointer: &str) -> Option<&'a str> {
|
||||
let (alternative_pointer, scheme) = pointer.rsplit_once('/')?;
|
||||
let alternative = alternative_at(operation, alternative_pointer)?;
|
||||
let name = scheme.replace("~1", "/").replace("~0", "~");
|
||||
alternative
|
||||
.schemes
|
||||
.iter()
|
||||
.find(|candidate| **candidate == name)
|
||||
.map(String::as_str)
|
||||
fn sanitized_secret_url(value: &str) -> bool {
|
||||
value.contains("=[REDACTED]")
|
||||
|| ((value.contains("://") || value.starts_with("//")) && !value.contains('@'))
|
||||
}
|
||||
|
||||
fn parameter_style(
|
||||
@@ -348,6 +368,31 @@ fn secret_like(pointer: &str, value: &str) -> bool {
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
|
||||
/// Accepts malformed `security` shapes at their scoped source location only:
|
||||
/// the document `security` member, an operation `security` member, or a
|
||||
/// non-object item of the corresponding security array. An object is valid
|
||||
/// only as an array item, including the empty `{}` public alternative.
|
||||
fn invalid_security_requirement(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
const METHODS: &[&str] = &[
|
||||
"get", "post", "put", "patch", "delete", "head", "options", "trace", "connect",
|
||||
];
|
||||
let is_index = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
|
||||
let segments: Vec<&str> = pointer.split('/').collect();
|
||||
match segments.as_slice() {
|
||||
["", "security"] => true,
|
||||
["", "security", index] => {
|
||||
is_index(index) && !matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
["", "paths", _, method, "security"] => METHODS.contains(method),
|
||||
["", "paths", _, method, "security", index] => {
|
||||
METHODS.contains(method)
|
||||
&& is_index(index)
|
||||
&& !matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_server(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
if pointer == "/host" {
|
||||
return !matches!(&node.value, CanonicalSourceValue::String(host) if !host.is_empty() && !host.contains('@') && !host.chars().any(char::is_whitespace));
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, ImportGroupPreview, ImportPreview, ImportSourcePreview, NormalizedIr,
|
||||
NormalizedSecurityScheme, RestImportDocument,
|
||||
};
|
||||
|
||||
pub(super) fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(super::normalize_projection::operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(
|
||||
&ir.source,
|
||||
&ir.security_schemes,
|
||||
operations.iter(),
|
||||
findings,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(
|
||||
&source,
|
||||
&document.security_schemes,
|
||||
document.operations.iter(),
|
||||
document.findings,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
legacy: bool,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in operations {
|
||||
let candidate = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
super::payload::candidate_from_operation(
|
||||
operation,
|
||||
security_schemes,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
super::normalize::sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,115 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind, NormalizedSchema,
|
||||
NormalizedSchemaKind, RestImportOperation, RestImportParameter, RestRequestBodyVariant,
|
||||
RestResponseVariant,
|
||||
ImportFinding, ImportGroupPreview, ImportOperationCandidate, ImportPreview,
|
||||
ImportSourcePreview, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind,
|
||||
NormalizedSchema, NormalizedSchemaKind, NormalizedSecurityScheme, RestImportDocument,
|
||||
RestImportOperation, RestImportParameter, RestRequestBodyVariant, RestResponseVariant,
|
||||
};
|
||||
|
||||
pub(super) fn preview_from_ir(ir: &crate::rest::model::NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
source_location: Some(finding.location.clone()),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(
|
||||
&ir.source,
|
||||
operations.iter(),
|
||||
findings,
|
||||
&ir.security_schemes,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
let security_schemes = document.security_schemes.clone();
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(
|
||||
&source,
|
||||
document.operations.iter(),
|
||||
document.findings,
|
||||
&security_schemes,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
operations: impl Iterator<Item = &'a RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
legacy: bool,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in operations {
|
||||
let candidate = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
crate::rest::payload::candidate_from_operation(
|
||||
operation,
|
||||
security_schemes,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::<ImportOperationCandidate>::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
super::normalize_security::attach_operation_findings(&mut groups, &findings);
|
||||
super::normalize::sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
conflicts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
||||
RestImportOperation {
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
source_location: Some(operation.location.clone()),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
summary: operation.summary.clone(),
|
||||
@@ -68,6 +165,7 @@ pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> Rest
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
source_location: Some(finding.location.clone()),
|
||||
})
|
||||
.collect(),
|
||||
internal_finding_locations: Vec::new(),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Attaches document-level findings to their affected operation candidates.
|
||||
|
||||
use super::model::{ImportFinding, ImportFindingSeverity, ImportGroupPreview};
|
||||
|
||||
pub(super) fn attach_operation_findings(
|
||||
groups: &mut std::collections::BTreeMap<String, ImportGroupPreview>,
|
||||
findings: &[ImportFinding],
|
||||
) {
|
||||
for group in groups.values_mut() {
|
||||
for candidate in &mut group.operations {
|
||||
let additions = findings
|
||||
.iter()
|
||||
.filter(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& finding.operation_key.as_deref() == Some(candidate.key.as_str())
|
||||
&& !candidate.findings.iter().any(|existing| {
|
||||
existing.code == finding.code
|
||||
&& existing.severity == finding.severity
|
||||
&& existing.message == finding.message
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
candidate.findings.extend(additions);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use crank_core::HttpMethod;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::parser_findings::append_unused_security_scheme_findings as append_unused;
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
@@ -15,6 +16,7 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
|
||||
}
|
||||
|
||||
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let security_schemes = super::security::schemes(root, false);
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
@@ -25,21 +27,16 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
let servers = parse_servers(root.get("servers"), "/servers");
|
||||
let security_schemes = super::security::schemes(root, false);
|
||||
append_findings_with_locations(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
servers.findings,
|
||||
);
|
||||
super::parser_findings::append_located(&mut findings, &mut locations, servers.findings);
|
||||
let servers = servers.servers;
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: String::new(),
|
||||
}));
|
||||
} else if servers.len() > 1 {
|
||||
@@ -47,7 +44,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: "/servers".to_owned(),
|
||||
}));
|
||||
}
|
||||
@@ -61,7 +58,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
for (path, path_item) in paths {
|
||||
if !path_item.is_object() {
|
||||
findings.push(super::http_methods::invalid_path_item());
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||
}));
|
||||
continue;
|
||||
@@ -72,7 +69,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"unsupported_http_method",
|
||||
format!("Метод {method_name} для пути {path} пока не поддерживается."),
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"/paths/{}/{}",
|
||||
path.replace('~', "~0").replace('/', "~1"),
|
||||
@@ -86,17 +83,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
path_parameters.findings,
|
||||
);
|
||||
let path_parameters = path_parameters.parameters;
|
||||
let path_servers =
|
||||
parse_servers(path_item.get("servers"), &format!("{path_pointer}/servers"));
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
path_servers.findings,
|
||||
);
|
||||
let path_servers = path_servers.servers;
|
||||
@@ -109,7 +106,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"invalid_operation",
|
||||
"Операция имеет неверную структуру и не была интерпретирована.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"/paths/{}/{}",
|
||||
path.replace('~', "~0").replace('/', "~1"),
|
||||
@@ -128,9 +125,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("parameters"),
|
||||
&format!("{path_pointer}/{method_name}/parameters"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
parsed_parameters.findings,
|
||||
);
|
||||
operation_parameters.extend(parsed_parameters.parameters);
|
||||
@@ -139,9 +136,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("servers"),
|
||||
&format!("{operation_pointer}/servers"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
operation_servers.findings,
|
||||
);
|
||||
let operation_servers = operation_servers.servers;
|
||||
@@ -149,27 +146,24 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("tags"),
|
||||
&format!("{operation_pointer}/tags"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
tags.findings,
|
||||
);
|
||||
super::parser_findings::append_located(&mut findings, &mut locations, tags.findings);
|
||||
|
||||
let mut located_operation_findings =
|
||||
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
let (security_requirements, security_findings) =
|
||||
super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
located_operation_findings.extend(security_findings);
|
||||
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
&operation_pointer,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
let (operation_findings, locations) = located_operation_findings.into_iter().unzip();
|
||||
let response_schema = (method != HttpMethod::Head)
|
||||
.then(|| response_schema(operation_value, &operation_pointer))
|
||||
.flatten();
|
||||
@@ -177,6 +171,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
@@ -209,11 +204,11 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_servers
|
||||
},
|
||||
findings: operation_findings,
|
||||
internal_finding_locations,
|
||||
internal_finding_locations: locations,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
append_unused(root, &security_schemes, &mut findings, &mut locations);
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
@@ -222,7 +217,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
security_schemes,
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations,
|
||||
internal_finding_locations: locations,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,6 +228,231 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
parameters.reverse();
|
||||
}
|
||||
|
||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = legacy_servers(root.get("servers"));
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
} else if servers.len() > 1 {
|
||||
findings.push(document_finding(
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema: legacy_request_body_schema(root, operation),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: legacy_servers(operation.get("servers")),
|
||||
findings: legacy_operation_findings(operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
||||
.map(|url| url.trim_end_matches('/').to_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let location = match item.get("in").and_then(Value::as_str)? {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!("{base_pointer}/{index}"),
|
||||
},
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
||||
let content = body.get("content")?.as_object()?;
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||
continue;
|
||||
};
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
if let Some(schema) = content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||
if operation.get("requestBody").is_some()
|
||||
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
||||
{
|
||||
vec![document_finding(
|
||||
"unsupported_request_body",
|
||||
"У метода есть requestBody, но JSON schema не найдена.",
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct ParsedParameters {
|
||||
parameters: Vec<RestImportParameter>,
|
||||
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
@@ -488,17 +708,6 @@ fn parameter_blocker(
|
||||
)
|
||||
}
|
||||
|
||||
fn append_findings_with_locations(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
|
||||
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in parameter_findings {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
fn request_body_schema(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
|
||||
@@ -299,6 +299,17 @@ pub(super) fn schema_findings(
|
||||
pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
if schema
|
||||
.get("default")
|
||||
.is_some_and(|value| value.is_object() || value.is_array())
|
||||
{
|
||||
push(
|
||||
findings,
|
||||
"unsupported_compound_default",
|
||||
"Object и array schema defaults не поддерживаются executable import contract.",
|
||||
&format!("{pointer}/default"),
|
||||
);
|
||||
}
|
||||
if let Some(types) = schema.get("type").and_then(Value::as_array) {
|
||||
let concrete = types
|
||||
.iter()
|
||||
@@ -389,8 +400,9 @@ pub(super) fn schema_findings(
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
let mut findings = parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
@@ -415,7 +427,39 @@ pub(super) fn path_parameters(
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
.collect::<Vec<_>>();
|
||||
for name in path_placeholders(path) {
|
||||
if !parameters.iter().any(|parameter| {
|
||||
parameter.location == RestParameterLocation::Path && parameter.name == name
|
||||
}) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"path_parameter_not_declared",
|
||||
format!("Path placeholder {name} не объявлен как path parameter."),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: operation_pointer.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn path_placeholders(path: &str) -> Vec<String> {
|
||||
let mut placeholders = Vec::new();
|
||||
let mut remaining = path;
|
||||
while let Some(open) = remaining.find('{') {
|
||||
let after_open = &remaining[open + 1..];
|
||||
let Some(close) = after_open.find('}') else {
|
||||
break;
|
||||
};
|
||||
if close > 0 {
|
||||
placeholders.push(after_open[..close].to_owned());
|
||||
}
|
||||
remaining = &after_open[close + 1..];
|
||||
}
|
||||
placeholders
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation,
|
||||
},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn parse_document_legacy_v1(
|
||||
root: &Value,
|
||||
) -> Result<RestImportDocument, ImportParseError> {
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = legacy_servers(root.get("servers"));
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
} else if servers.len() > 1 {
|
||||
findings.push(document_finding(
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema: legacy_request_body_schema(root, operation),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: legacy_servers(operation.get("servers")),
|
||||
findings: legacy_operation_findings(operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
||||
.map(|url| url.trim_end_matches('/').to_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let location = match item.get("in").and_then(Value::as_str)? {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!("{base_pointer}/{index}"),
|
||||
},
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
||||
let content = body.get("content")?.as_object()?;
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||
continue;
|
||||
};
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
if let Some(schema) = content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||
if operation.get("requestBody").is_some()
|
||||
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
||||
{
|
||||
vec![document_finding(
|
||||
"unsupported_request_body",
|
||||
"У метода есть requestBody, но JSON schema не найдена.",
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::rest::model::NormalizedSecurityScheme;
|
||||
use crate::rest::model::{ImportFinding, SourceLocation};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) fn append_located(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
entries: Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in entries {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn append_unused_security_scheme_findings(
|
||||
root: &Value,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
append_located(
|
||||
findings,
|
||||
locations,
|
||||
super::security::unused_unsupported_scheme_findings(root, schemes),
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,7 @@ use serde_json::json;
|
||||
use crate::rest::{
|
||||
mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping},
|
||||
model::{
|
||||
ImportOperationCandidate, NormalizedSecurityScheme, RestImportCandidate,
|
||||
RestImportOperation, RestParameterLocation,
|
||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||
},
|
||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||
recommendations::{candidate_recommendations, operation_recommendations},
|
||||
@@ -22,7 +21,7 @@ use crate::rest::{
|
||||
|
||||
pub fn candidate_from_operation(
|
||||
operation: &RestImportOperation,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
security_schemes: &BTreeMap<String, crate::rest::model::NormalizedSecurityScheme>,
|
||||
document_servers: &[String],
|
||||
used_names: &mut BTreeSet<String>,
|
||||
) -> ImportOperationCandidate {
|
||||
@@ -156,6 +155,8 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
status: String::new(),
|
||||
source_location: operation.source_location.clone(),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
|
||||
@@ -8,6 +8,7 @@ pub fn document_finding(code: &str, message: impl Into<String>) -> ImportFinding
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: message.into(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +18,7 @@ pub fn document_blocker(code: &str, message: impl Into<String>) -> ImportFinding
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: message.into(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +32,7 @@ pub fn operation_finding(
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: message.into(),
|
||||
operation_key: Some(operation_key.to_owned()),
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ pub fn operation_info(
|
||||
severity: ImportFindingSeverity::Info,
|
||||
message: message.into(),
|
||||
operation_key: Some(operation_key.to_owned()),
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +129,7 @@ pub fn operation_recommendations(operation: &RestImportOperation) -> Vec<ImportF
|
||||
),
|
||||
));
|
||||
}
|
||||
findings
|
||||
with_operation_location(findings, operation)
|
||||
}
|
||||
|
||||
pub fn candidate_recommendations(
|
||||
@@ -179,6 +183,18 @@ pub fn candidate_recommendations(
|
||||
));
|
||||
}
|
||||
|
||||
with_operation_location(findings, operation)
|
||||
}
|
||||
|
||||
fn with_operation_location(
|
||||
mut findings: Vec<ImportFinding>,
|
||||
operation: &RestImportOperation,
|
||||
) -> Vec<ImportFinding> {
|
||||
for finding in &mut findings {
|
||||
if finding.source_location.is_none() {
|
||||
finding.source_location = operation.source_location.clone();
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::rest::model::{
|
||||
SourceLocation,
|
||||
};
|
||||
|
||||
use super::{ImportParseError, normalize_coverage::escape_pointer};
|
||||
use super::reference_budget::{CopyBudget, count_branch_bytes, count_copy_bytes, merge_object};
|
||||
use super::{ImportParseError, decode_budget, normalize_coverage::escape_pointer};
|
||||
|
||||
pub(super) struct ResolutionResult {
|
||||
pub root: Value,
|
||||
@@ -61,6 +62,11 @@ fn reference_uris_with_max_bytes(
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_single(
|
||||
document,
|
||||
decode_budget::ShapeLimits::from_config(config),
|
||||
max_bytes,
|
||||
)?;
|
||||
let root = decode_snapshot(document)?;
|
||||
super::normalize::validate_value_limits(&root, config)?;
|
||||
let mut uris = BTreeSet::new();
|
||||
@@ -95,6 +101,7 @@ struct Resolver<'a> {
|
||||
findings: Vec<NormalizedFinding>,
|
||||
references: usize,
|
||||
expanded_nodes: usize,
|
||||
copy_budget: CopyBudget,
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
@@ -139,6 +146,10 @@ pub(super) fn resolve(
|
||||
root,
|
||||
});
|
||||
}
|
||||
let copy_limit = decode_budget::allowance(
|
||||
config.max_bytes.max(config.max_external_document_bytes),
|
||||
config.max_scalar_bytes,
|
||||
)?;
|
||||
let mut resolver = Resolver {
|
||||
config,
|
||||
documents,
|
||||
@@ -150,7 +161,10 @@ pub(super) fn resolve(
|
||||
findings: Vec::new(),
|
||||
references: 0,
|
||||
expanded_nodes: 0,
|
||||
copy_budget: CopyBudget::new(copy_limit),
|
||||
};
|
||||
let primary_copy_bytes = count_copy_bytes(&resolver.documents[0].root);
|
||||
resolver.copy_budget.charge(primary_copy_bytes)?;
|
||||
let root = resolver.documents[0].root.clone();
|
||||
let root = resolver.expand_value(
|
||||
0,
|
||||
@@ -320,7 +334,7 @@ impl Resolver<'_> {
|
||||
return Ok(Value::Object(source_object));
|
||||
}
|
||||
let Some((target_document, target_pointer)) = target.ok().flatten() else {
|
||||
let external = reference.starts_with("http://") || reference.starts_with("https://");
|
||||
let external = is_external_http_scheme(reference);
|
||||
let code = if external {
|
||||
if self.config.external_references_enabled {
|
||||
"external_reference_unavailable"
|
||||
@@ -360,6 +374,18 @@ impl Resolver<'_> {
|
||||
// producing an opaque object for the finite preview projection.
|
||||
return Ok(Value::Object(Map::new()));
|
||||
}
|
||||
let Some(target_bytes) = self.documents[target_document]
|
||||
.root
|
||||
.pointer(&target_pointer)
|
||||
.map(count_copy_bytes)
|
||||
else {
|
||||
self.push_finding(
|
||||
"reference_target_missing",
|
||||
&format!("{}/$ref", location.projection),
|
||||
);
|
||||
return Ok(Value::Object(source_object));
|
||||
};
|
||||
self.copy_budget.charge(target_bytes)?;
|
||||
let Some(target_value) = self.documents[target_document]
|
||||
.root
|
||||
.pointer(&target_pointer)
|
||||
@@ -471,6 +497,8 @@ impl Resolver<'_> {
|
||||
return Ok(Value::Object(object));
|
||||
}
|
||||
};
|
||||
let branch_bytes = count_branch_bytes(&branches);
|
||||
self.copy_budget.charge(branch_bytes)?;
|
||||
let original = branches.clone();
|
||||
for branch in branches {
|
||||
let Some(fields) = branch.as_object() else {
|
||||
@@ -478,7 +506,7 @@ impl Resolver<'_> {
|
||||
self.push_finding("all_of_conflict", &format!("{pointer}/allOf"));
|
||||
return Ok(Value::Object(object));
|
||||
};
|
||||
if !merge_object(&mut object, fields) {
|
||||
if !merge_object(&mut object, fields, &mut self.copy_budget)? {
|
||||
object.insert("allOf".to_owned(), Value::Array(original));
|
||||
self.push_finding("all_of_conflict", &format!("{pointer}/allOf"));
|
||||
return Ok(Value::Object(object));
|
||||
@@ -517,122 +545,6 @@ impl Resolver<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_object(target: &mut Map<String, Value>, source: &Map<String, Value>) -> bool {
|
||||
for (key, value) in source {
|
||||
match key.as_str() {
|
||||
"properties" => {
|
||||
let Some(source_properties) = value.as_object() else {
|
||||
return false;
|
||||
};
|
||||
let properties = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(target_properties) = properties.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
for (name, schema) in source_properties {
|
||||
if let Some(existing) = target_properties.get(name) {
|
||||
let (Some(existing), Some(schema)) =
|
||||
(existing.as_object(), schema.as_object())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let mut merged = existing.clone();
|
||||
if !merge_object(&mut merged, schema) {
|
||||
return false;
|
||||
}
|
||||
target_properties.insert(name.clone(), Value::Object(merged));
|
||||
} else {
|
||||
target_properties.insert(name.clone(), schema.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
"required" => {
|
||||
let Some(source_required) = value.as_array() else {
|
||||
return false;
|
||||
};
|
||||
let required = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
let Some(target_required) = required.as_array_mut() else {
|
||||
return false;
|
||||
};
|
||||
target_required.extend(source_required.iter().cloned());
|
||||
target_required.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
|
||||
target_required.dedup();
|
||||
}
|
||||
"minimum" | "maximum" => {
|
||||
let Some(source_value) = value.as_f64() else {
|
||||
return false;
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_f64).is_none() {
|
||||
return false;
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_f64)) {
|
||||
("minimum", Some(current)) => current.max(source_value),
|
||||
("maximum", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
let Some(number) = serde_json::Number::from_f64(merged) else {
|
||||
return false;
|
||||
};
|
||||
target.insert(key.clone(), Value::Number(number));
|
||||
if constraint_contradiction(target, "minimum", "maximum") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
"minLength" | "maxLength" => {
|
||||
let Some(source_value) = value.as_u64() else {
|
||||
return false;
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_u64).is_none() {
|
||||
return false;
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_u64)) {
|
||||
("minLength", Some(current)) => current.max(source_value),
|
||||
("maxLength", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
target.insert(key.clone(), Value::Number(merged.into()));
|
||||
if integer_constraint_contradiction(target, "minLength", "maxLength") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if target.get(key).is_some_and(|existing| existing != value) {
|
||||
return false;
|
||||
}
|
||||
target.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn constraint_contradiction(target: &Map<String, Value>, minimum: &str, maximum: &str) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_f64),
|
||||
target.get(maximum).and_then(Value::as_f64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_constraint_contradiction(
|
||||
target: &Map<String, Value>,
|
||||
minimum: &str,
|
||||
maximum: &str,
|
||||
) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_u64),
|
||||
target.get(maximum).and_then(Value::as_u64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn edge_key(edge: &ResolvedReferenceEdge) -> (&str, &str, &str, &str, bool) {
|
||||
(
|
||||
edge.source.snapshot_digest.as_str(),
|
||||
@@ -644,12 +556,7 @@ fn edge_key(edge: &ResolvedReferenceEdge) -> (&str, &str, &str, &str, bool) {
|
||||
}
|
||||
|
||||
fn decode_snapshot(document: &str) -> Result<Value, ImportParseError> {
|
||||
if let Ok(value) = serde_json::from_str(document) {
|
||||
return Ok(value);
|
||||
}
|
||||
let yaml: serde_yaml::Value =
|
||||
serde_yaml::from_str(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
serde_json::to_value(yaml).map_err(|_| ImportParseError::InvalidDocument)
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)
|
||||
}
|
||||
|
||||
fn is_oas31(root: &Value) -> bool {
|
||||
@@ -774,14 +681,37 @@ fn canonical_authority(authority: &str, scheme: &str) -> String {
|
||||
"https" => Some("443"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(default_port) = default_port
|
||||
let authority = if let Some(default_port) = default_port
|
||||
&& let Some((host, port)) = authority.rsplit_once(':')
|
||||
&& port == default_port
|
||||
&& (!host.contains(':') || host.ends_with(']'))
|
||||
{
|
||||
return host.to_owned();
|
||||
}
|
||||
host.to_owned()
|
||||
} else {
|
||||
authority
|
||||
};
|
||||
punycode_authority(authority, scheme)
|
||||
}
|
||||
|
||||
/// Applies the same IDNA/punycode host identity that the external-snapshot
|
||||
/// materializer gets from `url::Url`, so a Unicode `$ref` and the stored
|
||||
/// punycode `canonical_uri` resolve to the same snapshot. ASCII-only
|
||||
/// authorities (including IPv6 literals) and authorities with userinfo keep the
|
||||
/// previous ASCII-lowercase rendering, preserving RFC 3986 behavior.
|
||||
fn punycode_authority(authority: String, scheme: &str) -> String {
|
||||
if authority.is_ascii() || !matches!(scheme, "http" | "https") || authority.contains('@') {
|
||||
return authority;
|
||||
}
|
||||
let Ok(parsed) = url::Url::parse(&format!("{scheme}://{authority}")) else {
|
||||
return authority;
|
||||
};
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return authority;
|
||||
};
|
||||
match parsed.port() {
|
||||
Some(port) => format!("{host}:{port}"),
|
||||
None => host.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_uri_scheme(value: &str) -> bool {
|
||||
@@ -790,6 +720,14 @@ fn has_uri_scheme(value: &str) -> bool {
|
||||
.is_some_and(|(candidate, _)| is_uri_scheme(candidate))
|
||||
}
|
||||
|
||||
/// URI schemes are case-insensitive (RFC 3986 §3.1), so the failed-target
|
||||
/// classification must not depend on the literal case of `http`/`https`.
|
||||
fn is_external_http_scheme(reference: &str) -> bool {
|
||||
reference.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
|
||||
})
|
||||
}
|
||||
|
||||
fn is_uri_scheme(candidate: &str) -> bool {
|
||||
let Some(first) = candidate.as_bytes().first() else {
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Aggregate copy budget for string/key payloads allocated while resolving
|
||||
//! `$ref`s and merging `allOf` branches (Gitea #88).
|
||||
//!
|
||||
//! The budget is shared by the whole `resolve` call and never reset, so many
|
||||
//! individually small copies cannot multiply without bound. Checked arithmetic
|
||||
//! maps overflow to `ImportParseError::LimitExceeded`. `merge_object` charges
|
||||
//! every borrowed schema/required/value/key before it is cloned, so budget
|
||||
//! exhaustion is reported as `LimitExceeded` and never replaced by an
|
||||
//! `all_of_conflict` finding.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::normalize::ImportParseError;
|
||||
|
||||
pub(super) struct CopyBudget {
|
||||
limit: u64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
impl CopyBudget {
|
||||
pub(super) fn new(limit: u64) -> Self {
|
||||
Self { limit, used: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn charge(&mut self, bytes: u64) -> Result<(), ImportParseError> {
|
||||
self.used = self
|
||||
.used
|
||||
.checked_add(bytes)
|
||||
.ok_or(ImportParseError::LimitExceeded)?;
|
||||
if self.used > self.limit {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sums the UTF-8 bytes of every string and object key in a borrowed value,
|
||||
/// mirroring the payload a later `clone` allocates.
|
||||
pub(super) fn count_copy_bytes(value: &Value) -> u64 {
|
||||
match value {
|
||||
Value::String(text) => text.len() as u64,
|
||||
Value::Array(items) => items.iter().fold(0u64, |total, item| {
|
||||
total.saturating_add(count_copy_bytes(item))
|
||||
}),
|
||||
Value::Object(object) => count_object_copy_bytes(object),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn count_object_copy_bytes(object: &Map<String, Value>) -> u64 {
|
||||
object.iter().fold(0u64, |total, (key, item)| {
|
||||
total
|
||||
.saturating_add(key.len() as u64)
|
||||
.saturating_add(count_copy_bytes(item))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn count_branch_bytes(branches: &[Value]) -> u64 {
|
||||
branches.iter().fold(0u64, |total, branch| {
|
||||
total.saturating_add(count_copy_bytes(branch))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn merge_object(
|
||||
target: &mut Map<String, Value>,
|
||||
source: &Map<String, Value>,
|
||||
budget: &mut CopyBudget,
|
||||
) -> Result<bool, ImportParseError> {
|
||||
for (key, value) in source {
|
||||
match key.as_str() {
|
||||
"properties" => {
|
||||
let Some(source_properties) = value.as_object() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
let properties = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(target_properties) = properties.as_object_mut() else {
|
||||
return Ok(false);
|
||||
};
|
||||
for (name, schema) in source_properties {
|
||||
budget.charge(name.len() as u64)?;
|
||||
if let Some(existing) = target_properties.get(name) {
|
||||
let (Some(existing), Some(schema)) =
|
||||
(existing.as_object(), schema.as_object())
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(count_object_copy_bytes(existing))?;
|
||||
let mut merged = existing.clone();
|
||||
if !merge_object(&mut merged, schema, budget)? {
|
||||
return Ok(false);
|
||||
}
|
||||
target_properties.insert(name.clone(), Value::Object(merged));
|
||||
} else {
|
||||
budget.charge(count_copy_bytes(schema))?;
|
||||
target_properties.insert(name.clone(), schema.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
"required" => {
|
||||
let Some(source_required) = value.as_array() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
let required = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
let Some(target_required) = required.as_array_mut() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(count_branch_bytes(source_required))?;
|
||||
target_required.extend(source_required.iter().cloned());
|
||||
target_required.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
|
||||
target_required.dedup();
|
||||
}
|
||||
"minimum" | "maximum" => {
|
||||
let Some(source_value) = value.as_f64() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_f64).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_f64)) {
|
||||
("minimum", Some(current)) => current.max(source_value),
|
||||
("maximum", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
let Some(number) = serde_json::Number::from_f64(merged) else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
target.insert(key.clone(), Value::Number(number));
|
||||
if constraint_contradiction(target, "minimum", "maximum") {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
"minLength" | "maxLength" => {
|
||||
let Some(source_value) = value.as_u64() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_u64).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_u64)) {
|
||||
("minLength", Some(current)) => current.max(source_value),
|
||||
("maxLength", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
target.insert(key.clone(), Value::Number(merged.into()));
|
||||
if integer_constraint_contradiction(target, "minLength", "maxLength") {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
_ => match target.get(key) {
|
||||
Some(existing) if existing != value => return Ok(false),
|
||||
// Equal value already present: skip the redundant copy.
|
||||
Some(_) => {}
|
||||
None => {
|
||||
budget.charge(key.len() as u64)?;
|
||||
budget.charge(count_copy_bytes(value))?;
|
||||
target.insert(key.clone(), value.clone());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn constraint_contradiction(target: &Map<String, Value>, minimum: &str, maximum: &str) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_f64),
|
||||
target.get(maximum).and_then(Value::as_f64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_constraint_contradiction(
|
||||
target: &Map<String, Value>,
|
||||
minimum: &str,
|
||||
maximum: &str,
|
||||
) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_u64),
|
||||
target.get(maximum).and_then(Value::as_u64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn object(value: Value) -> Map<String, Value> {
|
||||
value.as_object().cloned().expect("object")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_object_charges_existing_property_object_copy() {
|
||||
// The target already has the property, so merging clones the whole
|
||||
// existing property object. With a small remaining quota this must be
|
||||
// rejected by the budget, not silently allocated.
|
||||
let mut target = object(json!({
|
||||
"properties": { "id": { "type": "string", "description": "x".repeat(64) } }
|
||||
}));
|
||||
let source = object(json!({
|
||||
"properties": { "id": { "type": "number" } }
|
||||
}));
|
||||
let mut budget = CopyBudget::new(16);
|
||||
assert_eq!(
|
||||
merge_object(&mut target, &source, &mut budget),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_object_charges_required_extension_copy() {
|
||||
let mut target = object(json!({ "required": ["x"] }));
|
||||
let source = object(json!({
|
||||
"required": ["aaaaaaaa", "bbbbbbbb", "cccccccc", "dddddddd"]
|
||||
}));
|
||||
let mut budget = CopyBudget::new(16);
|
||||
assert_eq!(
|
||||
merge_object(&mut target, &source, &mut budget),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,28 @@
|
||||
//! Typed security scheme extraction and effective requirement
|
||||
//! classification for OpenAPI 3.x and Swagger 2.0 documents.
|
||||
//!
|
||||
//! The module is pure: it never reads Auth Profiles or Secrets and never
|
||||
//! captures credential values. Requirements are classified alternative by
|
||||
//! alternative (OR semantics preserved): a supported single-scheme
|
||||
//! alternative stays resolvable via a compatible Auth Profile; malformed
|
||||
//! requirements, unresolvable schemes and AND combinations mark the
|
||||
//! affected alternative as unsupported; an operation is blocked only when
|
||||
//! none of its alternatives is selectable.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::{
|
||||
NormalizedSecurityRequirements, NormalizedSecurityScheme, NormalizedSecuritySchemeKind,
|
||||
SecurityParameterLocation, SecurityRequirementAlternative, SecurityRequirementsSource,
|
||||
SourceLocation,
|
||||
ImportFinding, NormalizedSecurityRequirements, NormalizedSecurityScheme,
|
||||
NormalizedSecuritySchemeKind, SecurityParameterLocation, SecurityRequirementAlternative,
|
||||
SecurityRequirementsSource, SourceLocation,
|
||||
};
|
||||
use super::recommendations::{document_blocker, document_finding};
|
||||
|
||||
/// Extracts typed schema metadata from `components.securitySchemes`
|
||||
/// (OpenAPI) or `securityDefinitions` (Swagger 2.0). Only scheme names,
|
||||
/// kinds, locations and safe format hints are preserved; credential values
|
||||
/// are never captured.
|
||||
pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, NormalizedSecurityScheme> {
|
||||
let (container, prefix) = if swagger {
|
||||
(root.get("securityDefinitions"), "/securityDefinitions")
|
||||
@@ -84,6 +98,56 @@ pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, Normalize
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reports unsupported scheme definitions that are never used by a security
|
||||
/// requirement. They still need manual configuration, but cannot affect an
|
||||
/// operation that does not select them.
|
||||
pub(super) fn unused_unsupported_scheme_findings(
|
||||
root: &Value,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
collect_requirement_names(root.get("security"), &mut used);
|
||||
if let Some(paths) = root.get("paths").and_then(Value::as_object) {
|
||||
for path_item in paths.values().filter_map(Value::as_object) {
|
||||
for operation in path_item.values().filter_map(Value::as_object) {
|
||||
collect_requirement_names(operation.get("security"), &mut used);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
schemes
|
||||
.iter()
|
||||
.filter_map(|(name, scheme)| {
|
||||
if used.contains(name)
|
||||
|| !matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
document_finding(
|
||||
"unsupported_security_scheme_definition",
|
||||
format!(
|
||||
"Объявленная схема {name} пока не поддерживается и не используется операциями; настройте authentication вручную, если она потребуется."
|
||||
),
|
||||
),
|
||||
scheme.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn collect_requirement_names(value: Option<&Value>, used: &mut std::collections::BTreeSet<String>) {
|
||||
let Some(alternatives) = value.and_then(Value::as_array) else {
|
||||
return;
|
||||
};
|
||||
for alternative in alternatives.iter().filter_map(Value::as_object) {
|
||||
used.extend(alternative.keys().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKind {
|
||||
let location = match definition.get("in").and_then(Value::as_str) {
|
||||
Some("header") => Some(SecurityParameterLocation::Header),
|
||||
@@ -92,7 +156,8 @@ fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKi
|
||||
_ => None,
|
||||
};
|
||||
match (location, definition.get("name").and_then(Value::as_str)) {
|
||||
(Some(location), Some(parameter_name)) => NormalizedSecuritySchemeKind::ApiKey {
|
||||
(Some(location), Some(parameter_name)) if !parameter_name.is_empty() => {
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location,
|
||||
parameter_name: parameter_name.to_owned(),
|
||||
format_hint: definition
|
||||
@@ -100,7 +165,8 @@ fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKi
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| safe_format_hint(value) && !looks_secret_hint(value))
|
||||
.map(ToOwned::to_owned),
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some("apiKey".to_owned()),
|
||||
},
|
||||
@@ -124,6 +190,11 @@ fn looks_secret_hint(value: &str) -> bool {
|
||||
|| value.starts_with("bearer ")
|
||||
}
|
||||
|
||||
/// Computes the effective requirement for one operation: the operation
|
||||
/// `security` member wins over the document root; a missing member means no
|
||||
/// requirement. Every array item is one OR alternative and is classified
|
||||
/// independently, so a single unsupported alternative never collapses
|
||||
/// supported siblings into a false AND.
|
||||
pub(super) fn effective_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
@@ -146,19 +217,16 @@ pub(super) fn effective_requirements(
|
||||
"/security".to_owned(),
|
||||
)
|
||||
} else {
|
||||
(None, SecurityRequirementsSource::None, String::new())
|
||||
};
|
||||
let mut findings = Vec::new();
|
||||
let Some(value) = value else {
|
||||
return (
|
||||
NormalizedSecurityRequirements {
|
||||
source,
|
||||
source: SecurityRequirementsSource::None,
|
||||
alternatives: Vec::new(),
|
||||
},
|
||||
findings,
|
||||
Vec::new(),
|
||||
);
|
||||
};
|
||||
let Some(alternatives) = value.as_array() else {
|
||||
let mut findings = Vec::new();
|
||||
let Some(alternatives) = value.and_then(Value::as_array) else {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"invalid_security_requirements",
|
||||
@@ -176,24 +244,27 @@ pub(super) fn effective_requirements(
|
||||
};
|
||||
let mut projected = Vec::new();
|
||||
let mut supported_alternatives = 0usize;
|
||||
let mut has_malformed_alternative = false;
|
||||
for (alternative_index, alternative) in alternatives.iter().enumerate() {
|
||||
let alternative_pointer = format!("{pointer}/{alternative_index}");
|
||||
let Some(requirement) = alternative.as_object() else {
|
||||
let source_location = SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
};
|
||||
has_malformed_alternative = true;
|
||||
findings.push((
|
||||
document_finding(
|
||||
"invalid_security_requirement",
|
||||
"Security alternative имеет неверную структуру и недоступна для выбора.",
|
||||
),
|
||||
source_location.clone(),
|
||||
SourceLocation {
|
||||
pointer: alternative_pointer.clone(),
|
||||
},
|
||||
));
|
||||
projected.push(SecurityRequirementAlternative {
|
||||
schemes: Vec::new(),
|
||||
supported: false,
|
||||
findings: vec!["invalid_security_requirement".to_owned()],
|
||||
source_location: Some(source_location),
|
||||
source_location: Some(SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
@@ -212,7 +283,10 @@ pub(super) fn effective_requirements(
|
||||
"Security scopes должны быть массивом строк; эта альтернатива недоступна для выбора.",
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
},
|
||||
));
|
||||
} else if scopes.is_some_and(|scopes| !scopes.is_empty())
|
||||
@@ -225,7 +299,10 @@ pub(super) fn effective_requirements(
|
||||
format!("Схема {name} не поддерживает OAuth scopes; непустой список блокирует эту alternative."),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -259,7 +336,7 @@ pub(super) fn effective_requirements(
|
||||
},
|
||||
));
|
||||
}
|
||||
if let Some((_unsupported, message)) = names.iter().find_map(|name| {
|
||||
if let Some((unsupported, message)) = names.iter().find_map(|name| {
|
||||
schemes.get(name).and_then(|scheme| match &scheme.kind {
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. } => Some((
|
||||
name,
|
||||
@@ -277,12 +354,12 @@ pub(super) fn effective_requirements(
|
||||
}) {
|
||||
alternative_findings.push("unsupported_security_scheme".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unsupported_security_scheme",
|
||||
message,
|
||||
),
|
||||
document_finding("unsupported_security_scheme", message),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(_unsupported)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(unsupported)
|
||||
),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -299,11 +376,19 @@ pub(super) fn effective_requirements(
|
||||
}),
|
||||
});
|
||||
}
|
||||
if !projected.is_empty() && supported_alternatives == 0 {
|
||||
if has_malformed_alternative || (!projected.is_empty() && supported_alternatives == 0) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"unsupported_security_requirements",
|
||||
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован.",
|
||||
if has_malformed_alternative {
|
||||
"invalid_security_requirements"
|
||||
} else {
|
||||
"unsupported_security_requirements"
|
||||
},
|
||||
if has_malformed_alternative {
|
||||
"Security requirements содержат malformed alternative и блокируют импорт операции."
|
||||
} else {
|
||||
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован."
|
||||
},
|
||||
),
|
||||
SourceLocation { pointer },
|
||||
));
|
||||
@@ -317,17 +402,19 @@ pub(super) fn effective_requirements(
|
||||
)
|
||||
}
|
||||
|
||||
/// Convenience wrapper keeping the parser call site short. The operation
|
||||
/// value must be the method object (`paths.{path}.{method}`); pointers use
|
||||
/// the same JSON-pointer escaping as the rest of the importer.
|
||||
pub(super) fn collect_operation_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
pointer: &str,
|
||||
operation_pointer: &str,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
findings: &mut Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) -> NormalizedSecurityRequirements {
|
||||
let (requirements, security_findings) =
|
||||
effective_requirements(root, operation, pointer, schemes);
|
||||
findings.extend(security_findings);
|
||||
requirements
|
||||
) -> (
|
||||
NormalizedSecurityRequirements,
|
||||
Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
effective_requirements(root, operation, operation_pointer, schemes)
|
||||
}
|
||||
|
||||
fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||
@@ -338,3 +425,38 @@ fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn empty_api_key_parameter_name_is_unsupported() {
|
||||
for swagger in [false, true] {
|
||||
let definition = json!({ "type": "apiKey", "in": "header", "name": "" });
|
||||
let root = if swagger {
|
||||
json!({ "securityDefinitions": { "Key": definition } })
|
||||
} else {
|
||||
json!({ "components": { "securitySchemes": { "Key": definition } } })
|
||||
};
|
||||
let schemes = schemes(&root, swagger);
|
||||
assert!(matches!(
|
||||
schemes["Key"].kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
));
|
||||
let (requirements, findings) = effective_requirements(
|
||||
&root,
|
||||
&json!({ "security": [{ "Key": [] }] }),
|
||||
"/paths/~1secure/get",
|
||||
&schemes,
|
||||
);
|
||||
assert!(!requirements.alternatives[0].supported);
|
||||
assert!(
|
||||
findings
|
||||
.iter()
|
||||
.any(|(finding, _)| { finding.code == "unsupported_security_requirements" })
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::SourceLocation;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SecretLiteralFinding {
|
||||
pub location: SourceLocation,
|
||||
}
|
||||
|
||||
/// Scans UTF-8 JSON or YAML and returns source locations without literal values.
|
||||
pub fn scan_secret_literals(
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<SecretLiteralFinding>, super::normalize::ImportParseError> {
|
||||
let document = std::str::from_utf8(bytes)
|
||||
.map_err(|_| super::normalize::ImportParseError::InvalidDocument)?;
|
||||
let mut root = super::normalize::decode(document)?;
|
||||
Ok(inspect_and_redact(&mut root))
|
||||
}
|
||||
|
||||
pub(super) fn inspect_and_redact(root: &mut Value) -> Vec<SecretLiteralFinding> {
|
||||
let mut findings = Vec::new();
|
||||
walk(root, "", false, false, &mut findings, true, false);
|
||||
findings
|
||||
}
|
||||
|
||||
fn walk(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
sensitive_context: bool,
|
||||
example_context: bool,
|
||||
findings: &mut Vec<SecretLiteralFinding>,
|
||||
redact: bool,
|
||||
cookie_context: bool,
|
||||
) {
|
||||
if example_context
|
||||
&& value
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.keys().any(|key| is_jwt(key)))
|
||||
{
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let header_parameter = fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| location.eq_ignore_ascii_case("header"));
|
||||
let parameter_name = fields.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
let named_sensitive_parameter =
|
||||
sensitive_key(parameter_name) && fields.get("in").and_then(Value::as_str).is_some();
|
||||
let named_cookie_header = is_cookie_header(parameter_name);
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
let property_definition = (pointer.contains("/properties/")
|
||||
|| pointer.ends_with("/properties"))
|
||||
&& !key.to_ascii_lowercase().starts_with("x-");
|
||||
let sensitive = sensitive_context
|
||||
|| (sensitive_key(key)
|
||||
&& !property_definition
|
||||
&& !is_oauth_flow_name(pointer, key));
|
||||
let example = example_context
|
||||
|| matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let header_example = header_parameter
|
||||
&& matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let named_header = is_cookie_header(key);
|
||||
let credential_example = matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
) && (named_sensitive_parameter
|
||||
|| (cookie_context && !property_definition)
|
||||
|| (named_cookie_header && !property_definition));
|
||||
walk(
|
||||
child,
|
||||
&child_pointer,
|
||||
sensitive || header_example || credential_example,
|
||||
example,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context || named_cookie_header || named_header,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
walk(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
sensitive_context,
|
||||
example_context,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(string) => {
|
||||
let userinfo = url_userinfo_range(string);
|
||||
let query_secret = sensitive_query_value(string);
|
||||
let likely_example_secret = (example_context
|
||||
&& (looks_secret_like(pointer, string) || is_jwt(string)))
|
||||
|| looks_secret_value(string)
|
||||
|| ((pointer.ends_with("/bearerFormat") || pointer.ends_with("/x-format-hint"))
|
||||
&& looks_secret_like(pointer, string));
|
||||
if sensitive_context || likely_example_secret || userinfo.is_some() || query_secret {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
if query_secret {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
} else if let Some((start, end)) = userinfo {
|
||||
string.replace_range(start..end, "[REDACTED]");
|
||||
} else {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Number(_) | Value::Bool(_) if sensitive_context => {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn sensitive_key(key: &str) -> bool {
|
||||
let mut normalized = String::new();
|
||||
let mut previous_lower = false;
|
||||
for ch in key.chars() {
|
||||
if ch.is_ascii_uppercase() && previous_lower {
|
||||
normalized.push('_');
|
||||
}
|
||||
if ch == '-' || ch == ' ' {
|
||||
normalized.push('_');
|
||||
} else {
|
||||
normalized.push(ch.to_ascii_lowercase());
|
||||
}
|
||||
previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
|
||||
}
|
||||
let key = normalized;
|
||||
if matches!(key.as_str(), "authorization_url" | "token_url") {
|
||||
return false;
|
||||
}
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"secret_hash",
|
||||
"secrethash",
|
||||
"password",
|
||||
"password_hash",
|
||||
"passwordhash",
|
||||
"passwd",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
"credential",
|
||||
"credentials",
|
||||
"access_key",
|
||||
"private_key",
|
||||
"privatekey",
|
||||
"ciphertext",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| {
|
||||
key == *marker
|
||||
|| key.ends_with(&format!("_{marker}"))
|
||||
|| key.starts_with(&format!("{marker}_"))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_oauth_flow_name(parent_pointer: &str, key: &str) -> bool {
|
||||
if !parent_pointer.ends_with("/flows") {
|
||||
return false;
|
||||
}
|
||||
let compact_key: String = key
|
||||
.chars()
|
||||
.filter(|character| character.is_ascii_alphanumeric())
|
||||
.map(|character| character.to_ascii_lowercase())
|
||||
.collect();
|
||||
matches!(
|
||||
compact_key.as_str(),
|
||||
"implicit" | "password" | "clientcredentials" | "authorizationcode"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_cookie_header(value: &str) -> bool {
|
||||
value.eq_ignore_ascii_case("cookie") || value.eq_ignore_ascii_case("set-cookie")
|
||||
}
|
||||
|
||||
fn is_jwt(value: &str) -> bool {
|
||||
let mut parts = value.split('.');
|
||||
let Some(header) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(payload) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(signature) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
parts.next().is_none()
|
||||
&& header.starts_with("eyJ")
|
||||
&& payload.starts_with("eyJ")
|
||||
&& header.len() >= 8
|
||||
&& payload.len() >= 16
|
||||
&& signature.len() >= 12
|
||||
&& [header, payload, signature].iter().all(|part| {
|
||||
!part.is_empty()
|
||||
&& part
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
|
||||
})
|
||||
}
|
||||
|
||||
fn sensitive_query_value(value: &str) -> bool {
|
||||
let Some(query_start) = value.find('?') else {
|
||||
return false;
|
||||
};
|
||||
value[query_start + 1..]
|
||||
.split('#')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split(['&', ';'])
|
||||
.any(|pair| {
|
||||
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
!value.is_empty() && sensitive_key(key)
|
||||
})
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn looks_secret_value(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.starts_with("bearer ") || value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn url_userinfo_range(value: &str) -> Option<(usize, usize)> {
|
||||
let scheme_end = value.find("://")? + 3;
|
||||
let authority_end = value[scheme_end..]
|
||||
.find('/')
|
||||
.map(|index| scheme_end + index)
|
||||
.unwrap_or(value.len());
|
||||
let authority = &value[scheme_end..authority_end];
|
||||
let at = authority.find('@')?;
|
||||
(at > 0).then_some((scheme_end, scheme_end + at))
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use crate::rest::model::{ExternalDocumentSnapshot, SourceDigest};
|
||||
|
||||
use super::model::NormalizationConfig;
|
||||
use super::{
|
||||
decode_budget, metadata_findings,
|
||||
normalize::{ImportParseError, decode, validate_value_limits},
|
||||
normalize_limits, reference,
|
||||
};
|
||||
|
||||
/// Rejects a source bundle containing credential-like literals before any
|
||||
/// primary or dependency bytes are persisted. Credential names are collected
|
||||
/// across all raw documents so split `$ref` targets receive the same checks.
|
||||
pub fn validate_document_bundle_source_safe(
|
||||
documents: &[&str],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if config
|
||||
.max_reference_documents
|
||||
.checked_add(1)
|
||||
.is_some_and(|cap| documents.len() > cap)
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for document in documents {
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_raw_bundle(documents, config)?;
|
||||
let mut roots = Vec::with_capacity(documents.len());
|
||||
for document in documents {
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
roots.push(root);
|
||||
}
|
||||
let declared_names = metadata_findings::credential_names(roots.iter());
|
||||
for mut root in roots {
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
metadata_findings::redact_secret_like_literals_with_names(
|
||||
&mut root,
|
||||
"",
|
||||
&declared_names,
|
||||
&mut findings,
|
||||
&mut locations,
|
||||
);
|
||||
if !findings.is_empty() {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates the resolved source tree with the same security-aware traversal
|
||||
/// used by normalization, before a caller persists any bytes in the bundle.
|
||||
pub fn validate_resolved_bundle_source_safe(
|
||||
document: &str,
|
||||
digest: SourceDigest,
|
||||
snapshots: &[ExternalDocumentSnapshot],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
if snapshots.len() > config.max_reference_documents {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes
|
||||
|| normalize_limits::alias_count(&snapshot.document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_bundle(document, snapshots, config)?;
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
let resolution = reference::resolve(root, digest, snapshots, config)?;
|
||||
let mut root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
metadata_findings::redact_secret_like_literals(&mut root, "", &mut findings, &mut locations);
|
||||
if !findings.is_empty() {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use serde::de::{self, MapAccess, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// Decodes JSON or YAML into a JSON value while rejecting duplicate mapping
|
||||
/// keys at every depth. This is used for new primary documents and immutable
|
||||
/// external snapshots; the isolated legacy v1 decoder keeps its old behavior.
|
||||
pub(super) fn decode(document: &str) -> Result<Value, ()> {
|
||||
let value = serde_json::from_str::<StrictValue>(document)
|
||||
.or_else(|_| serde_yaml::from_str::<StrictValue>(document))
|
||||
.map_err(|_| ())?;
|
||||
Ok(value.0)
|
||||
}
|
||||
|
||||
struct StrictValue(Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for StrictValue {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(StrictValueVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct StrictValueVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for StrictValueVisitor {
|
||||
type Value = StrictValue;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON-compatible value without duplicate object keys")
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Bool(value)))
|
||||
}
|
||||
|
||||
fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Number(value.into())))
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Number(value.into())))
|
||||
}
|
||||
|
||||
fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
serde_json::Number::from_f64(value)
|
||||
.map(Value::Number)
|
||||
.map(StrictValue)
|
||||
.ok_or_else(|| E::custom("value contains a non-finite number"))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::String(value.to_owned())))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::String(value)))
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Null))
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Null))
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
StrictValue::deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
let mut values = Vec::new();
|
||||
while let Some(value) = sequence.next_element::<StrictValue>()? {
|
||||
values.push(value.0);
|
||||
}
|
||||
Ok(StrictValue(Value::Array(values)))
|
||||
}
|
||||
|
||||
fn visit_map<A>(self, mut mapping: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
let mut values = Map::new();
|
||||
while let Some(key) = mapping.next_key::<String>()? {
|
||||
if values.contains_key(&key) {
|
||||
return Err(de::Error::custom("duplicate object key"));
|
||||
}
|
||||
let value = mapping.next_value::<StrictValue>()?;
|
||||
values.insert(key, value.0);
|
||||
}
|
||||
Ok(StrictValue(Value::Object(values)))
|
||||
}
|
||||
}
|
||||
@@ -15,16 +15,16 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
|
||||
}
|
||||
|
||||
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let security_schemes = super::security::schemes(root, true);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let security_schemes = super::security::schemes(root, true);
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
super::swagger2_findings::servers(root),
|
||||
@@ -74,7 +74,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
path_parameters.findings,
|
||||
@@ -114,7 +114,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("tags"),
|
||||
&format!("{path_pointer}/{method_name}/tags"),
|
||||
);
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
tags.findings,
|
||||
@@ -147,17 +147,19 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut located_operation_findings =
|
||||
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
let (security_requirements, security_findings) =
|
||||
super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
located_operation_findings.extend(security_findings);
|
||||
located_operation_findings.extend(parsed_parameter_findings);
|
||||
located_operation_findings.extend(super::swagger2_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
&operation_pointer,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
@@ -168,6 +170,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
@@ -203,6 +206,12 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
}
|
||||
}
|
||||
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
super::security::unused_unsupported_scheme_findings(root, &security_schemes),
|
||||
);
|
||||
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
@@ -222,7 +231,204 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
parameters.reverse();
|
||||
}
|
||||
|
||||
pub(super) fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
}
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema,
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: Vec::new(),
|
||||
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
let Some(host) = root.get("host").and_then(Value::as_str) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -467,17 +673,6 @@ fn parameter_blocker(
|
||||
)
|
||||
}
|
||||
|
||||
fn append_parameter_findings(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
|
||||
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in parameter_findings {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(schema.clone());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||
model::{ImportFinding, RestImportParameter, SourceLocation},
|
||||
recommendations::{document_blocker, operation_finding},
|
||||
};
|
||||
|
||||
@@ -175,33 +175,9 @@ pub(super) fn legacy_operation(path: &str, operation: &Value) -> Vec<ImportFindi
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
let finding = if !parameter.required {
|
||||
Some((
|
||||
"path_parameter_not_required",
|
||||
format!("Path parameter {} должен быть required.", parameter.name),
|
||||
))
|
||||
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||
Some((
|
||||
"path_parameter_placeholder_missing",
|
||||
format!(
|
||||
"Path parameter {} не имеет placeholder в пути.",
|
||||
parameter.name
|
||||
),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}?;
|
||||
Some((
|
||||
document_blocker(finding.0, finding.1),
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
super::openapi3_findings::path_parameters(path, parameters, operation_pointer)
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::swagger2::swagger_servers;
|
||||
use crate::rest::{
|
||||
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn parse_document_legacy_v1(
|
||||
root: &Value,
|
||||
) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
}
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema,
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: Vec::new(),
|
||||
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,962 @@
|
||||
//! Offline regression gates for the versioned OpenAPI support matrix and corpus.
|
||||
use crank_import::rest::model::CoverageDisposition;
|
||||
use crank_import::rest::model::{CanonicalSourceNode, CanonicalSourceValue};
|
||||
use crank_import::rest::{
|
||||
ImportParseError, NormalizationConfig, SourceDigest, normalize_verified_document,
|
||||
preview_from_ir, validate_normalized_ir,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[path = "corpus/matrix.rs"]
|
||||
mod matrix;
|
||||
|
||||
fn tests_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")
|
||||
}
|
||||
fn hex(bytes: impl AsRef<[u8]>) -> String {
|
||||
Sha256::digest(bytes)
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
fn canonical_json(value: &Value) -> Vec<u8> {
|
||||
serde_json::to_vec(value).expect("JSON values serialize")
|
||||
}
|
||||
fn escape_pointer(value: &str) -> String {
|
||||
value.replace('~', "~0").replace('/', "~1")
|
||||
}
|
||||
fn source_ledger(
|
||||
value: &Value,
|
||||
pointer: &str,
|
||||
ledger: &mut std::collections::BTreeMap<String, Value>,
|
||||
) {
|
||||
assert!(ledger.insert(pointer.to_owned(), value.clone()).is_none());
|
||||
match value {
|
||||
Value::Array(items) => {
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
source_ledger(item, &format!("{pointer}/{index}"), ledger);
|
||||
}
|
||||
}
|
||||
Value::Object(fields) => {
|
||||
for (key, item) in fields {
|
||||
source_ledger(item, &format!("{pointer}/{}", escape_pointer(key)), ledger);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn canonical_source_ledger(
|
||||
node: &CanonicalSourceNode,
|
||||
ledger: &mut std::collections::BTreeMap<String, Value>,
|
||||
) -> Value {
|
||||
let value = match &node.value {
|
||||
CanonicalSourceValue::Null => Value::Null,
|
||||
CanonicalSourceValue::Boolean(value) => json!(value),
|
||||
CanonicalSourceValue::Number(value) => {
|
||||
serde_json::from_str(value).expect("canonical number")
|
||||
}
|
||||
CanonicalSourceValue::String(value) => json!(value),
|
||||
CanonicalSourceValue::Array(items) => Value::Array(
|
||||
items
|
||||
.iter()
|
||||
.map(|item| canonical_source_ledger(item, ledger))
|
||||
.collect(),
|
||||
),
|
||||
CanonicalSourceValue::Object(items) => {
|
||||
let mut fields = serde_json::Map::new();
|
||||
for (key, item) in items {
|
||||
fields.insert(key.clone(), canonical_source_ledger(item, ledger));
|
||||
}
|
||||
Value::Object(fields)
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
ledger
|
||||
.insert(node.location.pointer.clone(), value.clone())
|
||||
.is_none()
|
||||
);
|
||||
value
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Manifest {
|
||||
corpus_version: String,
|
||||
matrix_version: String,
|
||||
compatibility_impact: String,
|
||||
documents: Vec<Document>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Document {
|
||||
id: String,
|
||||
file: String,
|
||||
sha256: String,
|
||||
canonical_digest: Option<String>,
|
||||
origin: String,
|
||||
license: String,
|
||||
specification_version: String,
|
||||
classification: String,
|
||||
expected_preview: Value,
|
||||
}
|
||||
fn manifest() -> Manifest {
|
||||
serde_json::from_slice(
|
||||
&fs::read(tests_root().join("corpus/manifest.json")).expect("manifest exists"),
|
||||
)
|
||||
.expect("manifest JSON is valid")
|
||||
}
|
||||
fn normalize(source: &str) -> Result<crank_import::rest::NormalizedIr, ImportParseError> {
|
||||
let source_digest = SourceDigest::parse(hex(source.as_bytes())).expect("sha256 is valid");
|
||||
normalize_verified_document(source, source_digest, &NormalizationConfig::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
let manifest = manifest();
|
||||
assert_eq!(manifest.corpus_version, "1.0.4");
|
||||
assert_eq!(manifest.matrix_version, "1.0.3");
|
||||
assert!(!manifest.compatibility_impact.trim().is_empty());
|
||||
assert!(manifest.documents.len() >= 50);
|
||||
let root = tests_root().join("corpus");
|
||||
let mut versions = std::collections::BTreeSet::new();
|
||||
let mut representative_count = 0;
|
||||
for document in &manifest.documents {
|
||||
assert!(!document.id.is_empty());
|
||||
assert!(
|
||||
document.origin.starts_with("synthetic:"),
|
||||
"{} lacks provenance",
|
||||
document.id
|
||||
);
|
||||
assert!(
|
||||
document.license.contains("CC0"),
|
||||
"{} lacks license",
|
||||
document.id
|
||||
);
|
||||
assert_eq!(document.sha256.len(), 64);
|
||||
versions.insert(document.specification_version.as_str());
|
||||
let source = fs::read(root.join(&document.file))
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", document.file));
|
||||
assert_eq!(
|
||||
hex(&source),
|
||||
document.sha256,
|
||||
"checksum mismatch for {}",
|
||||
document.file
|
||||
);
|
||||
if let Ok(value) = serde_json::from_slice::<Value>(&source) {
|
||||
let digest = hex(canonical_json(&value));
|
||||
assert_eq!(
|
||||
document.canonical_digest.as_deref(),
|
||||
Some(digest.as_str()),
|
||||
"canonical digest mismatch for {}",
|
||||
document.file
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
document.canonical_digest.is_none(),
|
||||
"malformed JSON has no canonical digest"
|
||||
);
|
||||
}
|
||||
if document.classification == "representative" {
|
||||
representative_count += 1;
|
||||
let text = std::str::from_utf8(&source).expect("fixtures are UTF-8");
|
||||
let ir =
|
||||
normalize(text).unwrap_or_else(|e| panic!("{} failed parser: {e}", document.file));
|
||||
validate_normalized_ir(&ir).expect("normalized IR has explicit source coverage");
|
||||
let preview = preview_from_ir(&ir);
|
||||
let repeated_preview =
|
||||
preview_from_ir(&normalize(text).expect("repeat normalization succeeds"));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&preview).unwrap(),
|
||||
serde_json::to_value(&repeated_preview).unwrap(),
|
||||
"deterministic preview diff for {}:\nexpected={}\nactual={}",
|
||||
document.file,
|
||||
serde_json::to_string_pretty(&preview).unwrap(),
|
||||
serde_json::to_string_pretty(&repeated_preview).unwrap(),
|
||||
);
|
||||
let candidates = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|g| &g.operations)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
candidates.len(),
|
||||
document.expected_preview["operation_count"]
|
||||
.as_u64()
|
||||
.unwrap() as usize,
|
||||
"operation count in {}",
|
||||
document.file
|
||||
);
|
||||
assert_eq!(
|
||||
candidates.len(),
|
||||
1,
|
||||
"corpus fixtures are single-operation exact oracles"
|
||||
);
|
||||
let expected = &document.expected_preview["operations"][0];
|
||||
let mut actual_candidate = serde_json::to_value(candidates[0]).unwrap();
|
||||
// Corpus snapshots freeze the pre-location semantic candidate.
|
||||
// Source provenance is covered by dedicated preview assertions.
|
||||
actual_candidate
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("source_location");
|
||||
for finding in actual_candidate["findings"].as_array_mut().unwrap() {
|
||||
finding.as_object_mut().unwrap().remove("source_location");
|
||||
}
|
||||
assert_eq!(
|
||||
actual_candidate,
|
||||
expected["candidate"],
|
||||
"frozen candidate diff for {}:\nexpected={}\nactual={}",
|
||||
document.file,
|
||||
serde_json::to_string_pretty(&expected["candidate"]).unwrap(),
|
||||
serde_json::to_string_pretty(&actual_candidate).unwrap(),
|
||||
);
|
||||
let blocking_codes = candidates[0]
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| {
|
||||
finding.severity == crank_import::rest::ImportFindingSeverity::Error
|
||||
})
|
||||
.map(|finding| finding.code.clone())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(json!(blocking_codes), expected["blocker_codes"]);
|
||||
assert_eq!(
|
||||
blocking_codes.is_empty(),
|
||||
expected["actionable"].as_bool().unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
hex(canonical_json(&actual_candidate)),
|
||||
expected["candidate_digest"],
|
||||
"candidate canonical digest in {}",
|
||||
document.file
|
||||
);
|
||||
let mut actual_preview = serde_json::to_value(&preview).unwrap();
|
||||
for group in actual_preview["groups"].as_array_mut().unwrap() {
|
||||
for candidate in group["operations"].as_array_mut().unwrap() {
|
||||
candidate.as_object_mut().unwrap().remove("source_location");
|
||||
for finding in candidate["findings"].as_array_mut().unwrap() {
|
||||
finding.as_object_mut().unwrap().remove("source_location");
|
||||
}
|
||||
}
|
||||
}
|
||||
for finding in actual_preview["findings"].as_array_mut().unwrap() {
|
||||
finding.as_object_mut().unwrap().remove("source_location");
|
||||
}
|
||||
assert_eq!(
|
||||
hex(canonical_json(&actual_preview)),
|
||||
document.expected_preview["canonical_preview_digest"],
|
||||
"preview canonical digest in {}",
|
||||
document.file
|
||||
);
|
||||
assert_eq!(
|
||||
actual_preview,
|
||||
document.expected_preview["canonical_preview"],
|
||||
"frozen readable preview diff for {}:\nexpected={}\nactual={}",
|
||||
document.file,
|
||||
serde_json::to_string_pretty(&document.expected_preview["canonical_preview"])
|
||||
.unwrap(),
|
||||
serde_json::to_string_pretty(&actual_preview).unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(candidates[0].method).unwrap().as_str(),
|
||||
expected["method"].as_str()
|
||||
);
|
||||
assert_eq!(candidates[0].path, expected["path"].as_str().unwrap());
|
||||
assert_eq!(
|
||||
candidates[0].operation_id.as_deref(),
|
||||
expected["operation_id"].as_str()
|
||||
);
|
||||
assert!(
|
||||
preview.findings.is_empty(),
|
||||
"unexpected preview findings in {}: {:?}",
|
||||
document.file,
|
||||
preview.findings
|
||||
);
|
||||
let mut actual_findings = candidates[0]
|
||||
.findings
|
||||
.iter()
|
||||
.map(|f| f.code.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
let mut expected_findings = document.expected_preview["finding_codes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
actual_findings.sort_unstable();
|
||||
expected_findings.sort_unstable();
|
||||
assert_eq!(
|
||||
actual_findings, expected_findings,
|
||||
"finding codes in {}",
|
||||
document.file
|
||||
);
|
||||
} else {
|
||||
assert_eq!(document.classification, "hostile");
|
||||
let text = std::str::from_utf8(&source).unwrap();
|
||||
let parsed = normalize(text);
|
||||
assert_eq!(
|
||||
parsed,
|
||||
normalize(text),
|
||||
"hostile parser result changed on deterministic rerun for {}",
|
||||
document.file
|
||||
);
|
||||
if [
|
||||
"hostile-empty.json",
|
||||
"hostile-malformed.json",
|
||||
"hostile-oversized.json",
|
||||
"hostile-deep.json",
|
||||
"hostile-aliases.yaml",
|
||||
]
|
||||
.contains(&document.file.as_str())
|
||||
{
|
||||
if [
|
||||
"hostile-oversized.json",
|
||||
"hostile-deep.json",
|
||||
"hostile-aliases.yaml",
|
||||
]
|
||||
.contains(&document.file.as_str())
|
||||
{
|
||||
assert!(
|
||||
matches!(parsed, Err(ImportParseError::LimitExceeded)),
|
||||
"{} must fail within configured bounds: {parsed:?}",
|
||||
document.file
|
||||
);
|
||||
} else {
|
||||
assert!(parsed.is_err(), "{} must be rejected", document.file);
|
||||
}
|
||||
} else if document.file == "hostile-trace.json" {
|
||||
let ir = parsed.expect("TRACE is reported instead of silently discarded");
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.any(|f| f.code == "unsupported_http_method")
|
||||
);
|
||||
assert!(ir.coverage.iter().any(|c| c.construct_id.contains("trace")
|
||||
&& c.disposition == CoverageDisposition::Finding));
|
||||
} else if document.file == "hostile-xml.json" {
|
||||
let ir = parsed.expect("XML is represented by an explicit finding");
|
||||
let preview = preview_from_ir(&ir);
|
||||
let codes = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|g| &g.operations)
|
||||
.flat_map(|o| &o.findings)
|
||||
.map(|f| f.code.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
codes
|
||||
.iter()
|
||||
.any(|code| code.contains("xml") || code.contains("media")),
|
||||
"XML findings: {codes:?}"
|
||||
);
|
||||
} else if document.file == "hostile-secret.json" {
|
||||
let ir = parsed.expect("secret-like examples remain inspectable");
|
||||
let evidence = serde_json::to_string(&preview_from_ir(&ir)).unwrap();
|
||||
assert!(
|
||||
!evidence.contains("sk_test_corpus_secret_canary"),
|
||||
"secret canary leaked into preview evidence"
|
||||
);
|
||||
} else {
|
||||
let ir = parsed.unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"{} must have an explicit finding or bounded rejection: {error}",
|
||||
document.file
|
||||
)
|
||||
});
|
||||
validate_normalized_ir(&ir).expect("hostile construct coverage remains explicit");
|
||||
assert!(
|
||||
!ir.coverage.is_empty(),
|
||||
"{} has no construct ledger",
|
||||
document.file
|
||||
);
|
||||
let preview = preview_from_ir(&ir);
|
||||
match document.file.as_str() {
|
||||
"hostile-cycle.json" => {
|
||||
assert_eq!(
|
||||
ir.operations.len(),
|
||||
1,
|
||||
"recursive schema must not drop the source operation"
|
||||
);
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.chain(ir.operations.iter().flat_map(|op| &op.findings))
|
||||
.all(|finding| {
|
||||
finding.severity
|
||||
!= crank_import::rest::ImportFindingSeverity::Error
|
||||
}),
|
||||
"bounded cycle policy must not yield an unexplained blocker: {:?} {:?}",
|
||||
ir.findings,
|
||||
ir.operations.iter().map(|op| &op.findings)
|
||||
);
|
||||
assert!(
|
||||
ir.unresolved_references.is_empty(),
|
||||
"resolved recursion must not be reported as unresolvable: {:?}",
|
||||
ir.unresolved_references
|
||||
);
|
||||
let cycle_edge = |recursive: bool| {
|
||||
ir.reference_graph.edges.iter().any(|edge| {
|
||||
edge.recursive == recursive
|
||||
&& edge.source.location.pointer
|
||||
== "/components/schemas/Node/properties/next/$ref"
|
||||
&& edge.target.location.pointer == "/components/schemas/Node"
|
||||
})
|
||||
};
|
||||
assert!(
|
||||
cycle_edge(false) && cycle_edge(true),
|
||||
"Node.next must resolve through both bounded and recursive edges: {:?}",
|
||||
ir.reference_graph.edges
|
||||
);
|
||||
let response = ir.operations[0]
|
||||
.response_variants
|
||||
.iter()
|
||||
.find(|variant| variant.status_code == 200)
|
||||
.expect("200 response is retained");
|
||||
assert!(
|
||||
matches!(
|
||||
&response.schema,
|
||||
Some(schema) if matches!(
|
||||
&schema.kind,
|
||||
crank_import::rest::NormalizedSchemaKind::Object {
|
||||
properties, ..
|
||||
} if properties.contains_key("next")
|
||||
)
|
||||
),
|
||||
"recursive node schema must be projected: {:?}",
|
||||
response.schema
|
||||
);
|
||||
assert!(
|
||||
ir.coverage.iter().any(|entry| {
|
||||
entry.location.pointer
|
||||
== "/components/schemas/Node/properties/next/properties/next"
|
||||
&& entry.disposition == CoverageDisposition::Mapped
|
||||
}),
|
||||
"bounded recursion must remain Mapped in the resolved source ledger: {:?}",
|
||||
ir.coverage
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["mapped_recursive_pointer"].as_str(),
|
||||
Some("/components/schemas/Node/properties/next/properties/next")
|
||||
);
|
||||
assert_eq!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.map(|f| (f.code.clone(), f.severity.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(
|
||||
"missing_servers".to_owned(),
|
||||
crank_import::rest::ImportFindingSeverity::Warning
|
||||
)],
|
||||
"cycle fixture must expose only the exact bounded warning set: {:?}",
|
||||
ir.findings
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["operation_count"].as_u64(),
|
||||
Some(1)
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["recursive_edge"]["source"].as_str(),
|
||||
Some("/components/schemas/Node/properties/next/$ref")
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["recursive_edge"]["target"].as_str(),
|
||||
Some("/components/schemas/Node")
|
||||
);
|
||||
assert_eq!(document.expected_preview["blocker_findings"], json!([]));
|
||||
assert_eq!(
|
||||
document.expected_preview["unresolved_references"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["warning_findings"],
|
||||
json!([{"code":"missing_servers","severity":"Warning","operation_key":null}])
|
||||
);
|
||||
}
|
||||
"hostile-external-ref.json" => assert!(
|
||||
ir.findings.iter()
|
||||
.chain(ir.operations.iter().flat_map(|op| &op.findings))
|
||||
.any(|finding| finding.code == "external_reference_disabled"
|
||||
&& finding.location.pointer == "/paths/~1hostile/get/responses/200/content/application~1json/schema/$ref"),
|
||||
"external ref must be denied at its source: {:?}",
|
||||
ir.findings
|
||||
),
|
||||
"hostile-duplicate-ids.json" => assert_eq!(
|
||||
ir.operations.len(),
|
||||
2,
|
||||
"duplicate IDs must not drop a source operation"
|
||||
),
|
||||
"hostile-composition-conflict.json" => {
|
||||
assert_eq!(
|
||||
ir.operations.len(),
|
||||
1,
|
||||
"conflicting allOf must keep the source operation explicit"
|
||||
);
|
||||
let conflict = ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "all_of_conflict")
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"allOf conflict must be named: {:?}",
|
||||
ir.operations[0].findings
|
||||
)
|
||||
});
|
||||
assert_eq!(
|
||||
conflict.severity,
|
||||
crank_import::rest::ImportFindingSeverity::Error,
|
||||
"allOf conflict must block the candidate: {:?}",
|
||||
conflict
|
||||
);
|
||||
assert_eq!(
|
||||
conflict.operation_key.as_deref(),
|
||||
Some("GET /hostile"),
|
||||
"conflict must belong to the affected candidate: {:?}",
|
||||
conflict
|
||||
);
|
||||
assert_eq!(
|
||||
conflict.location.pointer,
|
||||
"/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf",
|
||||
"conflict must point at the conflicting allOf: {:?}",
|
||||
conflict
|
||||
);
|
||||
assert!(
|
||||
ir.coverage
|
||||
.iter()
|
||||
.any(|entry| {
|
||||
entry.location
|
||||
.pointer
|
||||
== "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"
|
||||
})
|
||||
&& ir
|
||||
.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "all_of_conflict"
|
||||
&& finding.location.pointer
|
||||
== "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"),
|
||||
"conflicting allOf must stay in the source ledger bound to the explicit finding: {:?}",
|
||||
ir.coverage
|
||||
);
|
||||
let response = ir.operations[0]
|
||||
.response_variants
|
||||
.iter()
|
||||
.find(|variant| variant.status_code == 200)
|
||||
.expect("200 response is retained");
|
||||
assert!(
|
||||
matches!(
|
||||
&response.schema,
|
||||
Some(schema) if matches!(
|
||||
&schema.kind,
|
||||
crank_import::rest::NormalizedSchemaKind::Composition {
|
||||
operator, variants
|
||||
} if operator == "allOf" && variants.len() == 2
|
||||
)
|
||||
),
|
||||
"conflict branches must be preserved verbatim: {:?}",
|
||||
response.schema
|
||||
);
|
||||
assert_eq!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.map(|f| (f.code.clone(), f.severity.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(
|
||||
"missing_servers".to_owned(),
|
||||
crank_import::rest::ImportFindingSeverity::Warning
|
||||
)],
|
||||
"composition conflict fixture must keep the exact warning set: {:?}",
|
||||
ir.findings
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["operation_count"].as_u64(),
|
||||
Some(1)
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["blocker_findings"],
|
||||
json!([{"code":"all_of_conflict","severity":"Error",
|
||||
"operation_key":"GET /hostile",
|
||||
"location":"/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"}])
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["composition"],
|
||||
json!({"operator":"allOf","branch_count":2})
|
||||
);
|
||||
assert_eq!(
|
||||
document.expected_preview["warning_findings"],
|
||||
json!([{"code":"missing_servers","severity":"Warning","operation_key":null}])
|
||||
);
|
||||
}
|
||||
"hostile-security-scope.json" => {
|
||||
assert_eq!(
|
||||
ir.operations.len(),
|
||||
2,
|
||||
"security-scope fixture must keep both candidates explicit: {:?}",
|
||||
ir.operations.iter().map(|op| &op.key).collect::<Vec<_>>()
|
||||
);
|
||||
let requirements = ir.findings.iter().filter(|finding| {
|
||||
finding.code == "unsupported_security_requirements"
|
||||
}).collect::<Vec<_>>();
|
||||
assert!(requirements.is_empty(), "supported inherited basic requirement must remain selectable: {:?}", ir.findings);
|
||||
let secured_operation = ir.operations.iter().find(|operation| operation.key == "GET /secure").unwrap();
|
||||
assert!(secured_operation.security_requirements.alternatives[0].supported);
|
||||
assert_eq!(secured_operation.security_requirements.alternatives[0].source_location.as_ref().unwrap().pointer, "/security/0");
|
||||
let mut by_key = std::collections::BTreeMap::new();
|
||||
for group in &preview.groups {
|
||||
for candidate in &group.operations {
|
||||
by_key.insert(candidate.key.clone(), candidate);
|
||||
}
|
||||
}
|
||||
let public = by_key.get("GET /public").expect("public candidate present");
|
||||
assert!(
|
||||
public.findings.iter().all(|finding| finding.severity
|
||||
!= crank_import::rest::ImportFindingSeverity::Error),
|
||||
"public operation with security: [] must stay actionable: {:?}",
|
||||
public.findings
|
||||
);
|
||||
assert!(by_key.get("GET /secure").expect("secured candidate present").findings.iter().all(|finding| {
|
||||
finding.severity != crank_import::rest::ImportFindingSeverity::Error
|
||||
}), "supported security must remain selectable before API binding: {:?}", by_key.get("GET /secure").unwrap().findings);
|
||||
assert!(
|
||||
preview
|
||||
.findings
|
||||
.iter()
|
||||
.all(|finding| finding.operation_key.is_some()),
|
||||
"no document-global blocker may be produced: {:?}",
|
||||
preview.findings
|
||||
);
|
||||
assert!(
|
||||
ir.coverage
|
||||
.iter()
|
||||
.any(|entry| entry.location.pointer == "/security/0"
|
||||
&& entry.disposition == CoverageDisposition::Mapped),
|
||||
"inherited requirement must stay mapped in the source ledger: {:?}",
|
||||
ir.coverage
|
||||
);
|
||||
let mut actual_operation_keys = preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.map(|op| op.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
actual_operation_keys.sort();
|
||||
assert_eq!(
|
||||
json!(actual_operation_keys),
|
||||
document.expected_preview["operation_keys"],
|
||||
"security-scope operation oracle for {}",
|
||||
document.file
|
||||
);
|
||||
let actual_blockers = requirements
|
||||
.iter()
|
||||
.map(|finding| {
|
||||
json!({"code": finding.code.clone(), "severity": "Error",
|
||||
"operation_key": finding.operation_key.clone(),
|
||||
"location": finding.location.pointer.clone()})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
actual_blockers,
|
||||
document.expected_preview["blocker_findings"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
"security-scope blocker oracle for {}: actual {actual_blockers:?}",
|
||||
document.file
|
||||
);
|
||||
let actual_warnings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| {
|
||||
finding.severity
|
||||
== crank_import::rest::ImportFindingSeverity::Warning
|
||||
})
|
||||
.map(|finding| {
|
||||
json!({"code": finding.code.clone(), "severity": "Warning",
|
||||
"operation_key": finding.operation_key.clone()})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
actual_warnings,
|
||||
document.expected_preview["warning_findings"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
"security-scope warning oracle for {}: actual {actual_warnings:?}",
|
||||
document.file
|
||||
);
|
||||
}
|
||||
_ => unreachable!("hostile fixture must have a dedicated expectation"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Exact file set: manifest rows are unique and every corpus data file is
|
||||
// accounted exactly once, so duplicates or orphan fixtures cannot inflate
|
||||
// or hide coverage.
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
let mut files = std::collections::BTreeSet::new();
|
||||
for document in &manifest.documents {
|
||||
assert!(
|
||||
ids.insert(document.id.clone()),
|
||||
"duplicate manifest document id {}",
|
||||
document.id
|
||||
);
|
||||
assert!(
|
||||
files.insert(document.file.clone()),
|
||||
"duplicate manifest file {}",
|
||||
document.file
|
||||
);
|
||||
}
|
||||
let expected_files = files
|
||||
.into_iter()
|
||||
.chain(std::iter::once("manifest.json".to_owned()))
|
||||
.chain(std::iter::once("matrix.rs".to_owned()))
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let actual_files = fs::read_dir(&root)
|
||||
.expect("corpus directory exists")
|
||||
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
actual_files, expected_files,
|
||||
"corpus directory must equal the manifest file set exactly"
|
||||
);
|
||||
assert_eq!(representative_count, 50);
|
||||
assert!(
|
||||
versions
|
||||
.iter()
|
||||
.any(|version| version.starts_with("OpenAPI 3.0"))
|
||||
&& versions
|
||||
.iter()
|
||||
.any(|version| version.starts_with("OpenAPI 3.1"))
|
||||
&& versions.contains("Swagger 2.0")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac_3_evidence_reports_actionable_denominator_exclusions_and_zero_silent_loss() {
|
||||
let manifest = manifest();
|
||||
let mut denominator = 0_u64;
|
||||
let mut actionable_count = 0_u64;
|
||||
let mut operation_count = 0_u64;
|
||||
let mut source_construct_count = 0_u64;
|
||||
let mut covered_source_construct_count = 0_u64;
|
||||
let mut semantic_coverage_count = 0_u64;
|
||||
let mut silent_loss = Vec::new();
|
||||
let mut exclusions = Vec::new();
|
||||
let mut finding_count = 0_u64;
|
||||
for document in &manifest.documents {
|
||||
if document.classification != "representative" {
|
||||
continue;
|
||||
}
|
||||
let source_bytes = fs::read(tests_root().join("corpus").join(&document.file)).unwrap();
|
||||
let source: Value =
|
||||
serde_json::from_slice(&source_bytes).expect("representative corpus source is JSON");
|
||||
let mut raw_ledger = std::collections::BTreeMap::new();
|
||||
source_ledger(&source, "", &mut raw_ledger);
|
||||
let source_text = std::str::from_utf8(&source_bytes).unwrap();
|
||||
let ir = normalize(source_text).unwrap();
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
let mut normalized_ledger = std::collections::BTreeMap::new();
|
||||
let _ = canonical_source_ledger(&ir.source_tree, &mut normalized_ledger);
|
||||
assert_eq!(
|
||||
normalized_ledger, raw_ledger,
|
||||
"normalizer source-tree ledger differs from raw document for {}",
|
||||
document.file
|
||||
);
|
||||
source_construct_count += raw_ledger.len() as u64;
|
||||
let coverage_by_id = ir
|
||||
.coverage
|
||||
.iter()
|
||||
.map(|entry| (entry.construct_id.as_str(), entry))
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
for pointer in raw_ledger.keys() {
|
||||
let source_id = format!("source:{pointer}");
|
||||
match coverage_by_id.get(source_id.as_str()) {
|
||||
Some(entry)
|
||||
if entry.location.pointer == *pointer
|
||||
&& entry.disposition == CoverageDisposition::Mapped =>
|
||||
{
|
||||
covered_source_construct_count += 1;
|
||||
}
|
||||
_ => silent_loss.push(json!({"document":document.id,"source_pointer":pointer,"coverage_id":source_id})),
|
||||
}
|
||||
}
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.chain(
|
||||
ir.operations
|
||||
.iter()
|
||||
.flat_map(|operation| &operation.findings),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
for entry in ir
|
||||
.coverage
|
||||
.iter()
|
||||
.filter(|entry| !entry.construct_id.starts_with("source:"))
|
||||
{
|
||||
semantic_coverage_count += 1;
|
||||
assert!(
|
||||
raw_ledger.contains_key(&entry.location.pointer),
|
||||
"coverage {} points outside raw source tree for {}",
|
||||
entry.construct_id,
|
||||
document.file
|
||||
);
|
||||
match entry.disposition {
|
||||
CoverageDisposition::Mapped => {}
|
||||
CoverageDisposition::Finding => assert!(
|
||||
findings
|
||||
.iter()
|
||||
.any(|finding| finding.construct_id == entry.construct_id
|
||||
&& finding.location == entry.location),
|
||||
"finding coverage {} has no matching finding in {}",
|
||||
entry.construct_id,
|
||||
document.file
|
||||
),
|
||||
}
|
||||
}
|
||||
for operation in &ir.operations {
|
||||
denominator += 1;
|
||||
operation_count += 1;
|
||||
if operation
|
||||
.findings
|
||||
.iter()
|
||||
.all(|f| f.severity != crank_import::rest::ImportFindingSeverity::Error)
|
||||
{
|
||||
actionable_count += 1;
|
||||
} else {
|
||||
exclusions.push(json!({"document":document.id,"operation":operation.key,"reason":"blocking_finding","findings":operation.findings.iter().map(|f| &f.code).collect::<Vec<_>>()}));
|
||||
}
|
||||
}
|
||||
finding_count += ir.findings.len() as u64;
|
||||
}
|
||||
assert!(denominator > 0);
|
||||
assert!(
|
||||
actionable_count * 100 >= denominator * 95,
|
||||
"actionable {actionable_count}/{denominator}; exclusions={exclusions:?}"
|
||||
);
|
||||
let silent_loss_count = silent_loss.len() as u64;
|
||||
assert_eq!(
|
||||
source_construct_count, covered_source_construct_count,
|
||||
"independently enumerated raw source constructs lack coverage: {silent_loss:?}"
|
||||
);
|
||||
let mut reversed_counts = (0_u64, 0_u64, 0_u64);
|
||||
for document in manifest
|
||||
.documents
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|document| document.classification == "representative")
|
||||
{
|
||||
let source = fs::read_to_string(tests_root().join("corpus").join(&document.file)).unwrap();
|
||||
let ir = normalize(&source).unwrap();
|
||||
reversed_counts.0 += ir.operations.len() as u64;
|
||||
reversed_counts.1 += ir
|
||||
.operations
|
||||
.iter()
|
||||
.filter(|operation| {
|
||||
operation.findings.iter().all(|finding| {
|
||||
finding.severity != crank_import::rest::ImportFindingSeverity::Error
|
||||
})
|
||||
})
|
||||
.count() as u64;
|
||||
reversed_counts.2 += ir.findings.len() as u64;
|
||||
}
|
||||
assert_eq!(
|
||||
reversed_counts,
|
||||
(operation_count, actionable_count, finding_count),
|
||||
"aggregate evidence must not depend on manifest order"
|
||||
);
|
||||
let manifest_bytes = fs::read(tests_root().join("corpus/manifest.json")).unwrap();
|
||||
let manifest_digest = hex(&manifest_bytes);
|
||||
let matrix_bytes = fs::read(tests_root().join("support-matrix.yaml")).unwrap();
|
||||
let matrix_digest = hex(&matrix_bytes);
|
||||
let matrix_value: serde_yaml::Value = serde_yaml::from_slice(&matrix_bytes).unwrap();
|
||||
let matrix_row_count = matrix_value["constructs"].as_sequence().unwrap().len();
|
||||
let evidence_identity = hex(format!(
|
||||
"{}\n{}\n{}\n{}",
|
||||
manifest.corpus_version, manifest.matrix_version, manifest_digest, matrix_digest
|
||||
));
|
||||
let mut evidence = json!({
|
||||
"evidence_version":"1.0.0", "corpus_version":manifest.corpus_version, "matrix_version":manifest.matrix_version,
|
||||
"evidence_identity":evidence_identity,
|
||||
"content_digest_algorithm":"sha256",
|
||||
"content_digest_definition":"SHA-256 of compact key-sorted JSON before the content_digest field is added.",
|
||||
"manifest_digest":manifest_digest,
|
||||
"matrix_digest":matrix_digest,
|
||||
"denominator":denominator, "actionable_count":actionable_count, "exclusions":exclusions,
|
||||
"raw_counts":{"documents":manifest.documents.len(),"representative_operations":operation_count,"findings":finding_count,"source_constructs":source_construct_count,"covered_source_constructs":covered_source_construct_count,"semantic_coverage_entries":semantic_coverage_count},
|
||||
"matrix_contract":{"construct_rows":matrix_row_count,"semantic_probes":"AC-1 runs a generated normalizer probe for every matrix row, including every 2xx status in all three formats."},
|
||||
"uncovered_source_constructs":silent_loss,
|
||||
"silent_loss_count":silent_loss_count,
|
||||
"method":"real normalize_verified_document + preview_from_ir; every NormalizedIr passed validate_normalized_ir"
|
||||
});
|
||||
let content_digest = hex(canonical_json(&evidence));
|
||||
evidence["content_digest"] = json!(content_digest);
|
||||
let artifact = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!(
|
||||
"target/openapi-corpus/evidence-{evidence_identity}.json"
|
||||
));
|
||||
let target_dir = artifact.parent().unwrap();
|
||||
fs::create_dir_all(target_dir).unwrap();
|
||||
let bytes = serde_json::to_vec_pretty(&evidence).unwrap();
|
||||
// Each process needs its own temp file: concurrent corpus runs must not
|
||||
// truncate each other's pending evidence before atomic publication.
|
||||
let mut nonce = 0u32;
|
||||
let (publish, mut file) = loop {
|
||||
let path = target_dir.join(format!(
|
||||
"evidence.json.tmp-{}-{}-{nonce}",
|
||||
&evidence_identity[..16],
|
||||
std::process::id()
|
||||
));
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)
|
||||
{
|
||||
Ok(file) => break (path, file),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && nonce < 1024 => {
|
||||
nonce += 1;
|
||||
}
|
||||
Err(error) => panic!(
|
||||
"cannot create evidence temp file {}: {error}",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
};
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&bytes).unwrap();
|
||||
file.sync_all().unwrap();
|
||||
}
|
||||
// hard_link fails atomically when the final identity already exists.
|
||||
// Rename would silently overwrite after an exists-check race, while
|
||||
// create_new on the final path would expose partial bytes after a crash.
|
||||
let published = match fs::hard_link(&publish, &artifact) {
|
||||
Ok(()) => true,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,
|
||||
Err(error) => panic!(
|
||||
"cannot publish immutable evidence artifact {}: {error}",
|
||||
artifact.display()
|
||||
),
|
||||
};
|
||||
fs::remove_file(&publish).ok();
|
||||
if !published {
|
||||
let existing = fs::read(&artifact).unwrap();
|
||||
assert_eq!(
|
||||
existing,
|
||||
bytes,
|
||||
"immutable evidence identity {evidence_identity} already has conflicting contents at {}",
|
||||
artifact.display()
|
||||
);
|
||||
}
|
||||
if let Ok(directory) = fs::File::open(target_dir) {
|
||||
let _ = directory.sync_all();
|
||||
}
|
||||
let reread: Value = serde_json::from_slice(&fs::read(artifact).unwrap()).unwrap();
|
||||
assert_eq!(reread, evidence);
|
||||
assert_eq!(reread["silent_loss_count"], 0);
|
||||
assert_eq!(source_construct_count, covered_source_construct_count);
|
||||
assert_eq!(reread["denominator"], denominator);
|
||||
assert_eq!(reread["actionable_count"], actionable_count);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
openapi: 3.1.0
|
||||
info: {title: Aliases, version: 1}
|
||||
paths: {}
|
||||
x-anchor: &anchor {type: string}
|
||||
x-aliases: [*anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor]
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Hostile generated",
|
||||
"version": "1"
|
||||
},
|
||||
"paths": {
|
||||
"/hostile": {
|
||||
"get": {
|
||||
"operationId": "hostileOperation",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "ok",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user