story 2-12-preview-partial-mode: implemented and reviewed via bmad-loop

This commit is contained in:
bsodfather committed 2026-10-03 15:04:15 +03:00
1 parent d1ba0bd0e4
commit ab35d67177
56 files changed
+5801 -376

No files matched your search

@@ -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
@@ -987,3 +987,4 @@ async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
mod corpus_hostile;
mod security_source;
mod support_matrix;
@@ -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.1");
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()
);
}
@@ -16,6 +16,134 @@ paths:
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() {
@@ -31,6 +159,7 @@ async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation(
.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)
@@ -77,6 +206,11 @@ async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation(
.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.2");
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"],
@@ -98,6 +232,21 @@ async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation(
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
@@ -154,6 +303,18 @@ async fn partial_plan_counts_selection_and_rejects_invalid_request_material() {
.expect("the excluded candidate is listed for confirmation");
assert_eq!(excluded.state, "excluded");
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,
"reason": "not_selected",
}])
);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
@@ -351,7 +512,7 @@ async fn client_supplied_candidate_material_has_no_authority() {
stored.payload["selection"]["all"],
json!(["GET /v2/latest"])
);
assert_eq!(stored.payload["schema_version"], "import-plan-v1");
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
assert!(stored.digest.len() == 64 && stored.digest.bytes().all(|b| b.is_ascii_hexdigit()));
}
@@ -403,6 +564,11 @@ async fn plan_creation_is_workspace_scoped() {
.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")]
@@ -161,6 +161,7 @@ fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
}
mod creation;
mod route_get;
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
mod security_availability;
mod security_binding;
@@ -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);
}
@@ -119,6 +119,7 @@ async fn auth_profile_references_are_validated_stored_and_inherited() {
.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()
@@ -648,7 +649,7 @@ async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_app
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision],
vec![query_decision.clone()],
),
)
.await
@@ -664,7 +665,7 @@ async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_app
Some(query_profile.id.as_str())
);
for (plan, expected_profile, idempotency_key) in [
for (index, (plan, expected_profile, idempotency_key)) in [
(
&basic_plan,
basic_profile.id.as_str(),
@@ -675,7 +676,44 @@ async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_app
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,
@@ -1,5 +1,80 @@
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() {
@@ -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"
);
}
@@ -0,0 +1,140 @@
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,
}
}
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(&registry, &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(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &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(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &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(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &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(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &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(&registry, &workspace_id).await, before);
}
@@ -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);
}