Files
bsodfather e93de7015a
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
feat(import): complete OpenAPI onboarding and verify delivery
2026-10-09 17:50:38 +03:00

263 lines
8.6 KiB
Rust

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(&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);
}
#[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(&registry, &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(&registry, &workspace_id).await,
0,
"profile lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &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(&registry, &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(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave attached sources"
);
}