story 2-13-importplan-re-import: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
c562d5368d
commit
f69c36fa65
66 files changed
+11366
-686
No files matched your search
@@ -0,0 +1,664 @@
|
||||
use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
|
||||
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_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,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
};
|
||||
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_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,
|
||||
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,
|
||||
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");
|
||||
}
|
||||
@@ -0,0 +1,952 @@
|
||||
use super::*;
|
||||
|
||||
#[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();
|
||||
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.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());
|
||||
// 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 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.reason.as_deref(), Some("not_selected"));
|
||||
|
||||
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-v1");
|
||||
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");
|
||||
}
|
||||
|
||||
#[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 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 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",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(auth_profile.id.as_str()),
|
||||
)],
|
||||
),
|
||||
)
|
||||
.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()
|
||||
);
|
||||
// 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())
|
||||
);
|
||||
|
||||
// An unknown profile reference fails closed in the workspace scope check.
|
||||
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,
|
||||
Some("auth_missing_profile"),
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("an unknown auth profile reference must be rejected");
|
||||
assert_error_code(&error, "operation_auth_profile_invalid");
|
||||
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))
|
||||
.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));
|
||||
}
|
||||
|
||||
#[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,163 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
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 validation;
|
||||
@@ -0,0 +1,275 @@
|
||||
use super::*;
|
||||
|
||||
#[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()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user