fix(import): подтвердить обязательные гарантии второго эпика
CI / Rust Checks (pull_request) Successful in 24m43s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 9m5s
CI / Frontend E2E (pull_request) Successful in 12m43s
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-10 13:25:05 +03:00
1 parent 31f6f00d3b
commit ad23cd9a46
33 files changed
+3328 -18

No files matched your search

@@ -1,11 +1,17 @@
use super::super::common::test_service_with_external_references;
mod isolation;
use super::*;
use axum::{Router, routing::get};
use admin_api::error::ApiError;
use axum::{Router, body::to_bytes, http::StatusCode, response::IntoResponse, routing::get};
use crank_artifacts::ArtifactStore;
use crank_core::{Workspace, WorkspaceStatus};
use crank_registry::{ArtifactSourceId, CreateWorkspaceRequest, RegistryError};
use sha2::{Digest, Sha256};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use time::OffsetDateTime;
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет Line truncated
@@ -43,12 +49,14 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_snapshot");
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_external_snapshot"),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let foreign_workspace_id = create_workspace(&registry, "ws_external_snapshot_foreign").await;
let upload = OpenApiUpload {
bytes: format!(
r#"
@@ -97,6 +105,60 @@ paths:
2
);
// The preview response contains only the normalized result. Ownership
// envelopes, storage digests, and remote origins stay in the persisted
// job payload and are verified through the workspace-scoped registry API.
let public_preview = serde_json::to_string(&preview).unwrap();
assert!(!public_preview.contains("src_openapi_dep_"));
assert!(!public_preview.contains(&origin));
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
for dependency in dependencies {
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
let digest = dependency["digest"].as_str().unwrap();
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
let source = registry
.get_artifact_source(&workspace_id, &source_id)
.await
.unwrap();
assert_eq!(source.workspace_id, workspace_id);
assert_eq!(source.blob.artifact_ref.as_str(), digest);
let verified = registry
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
.await
.unwrap();
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
let expected_bytes = if canonical_uri.ends_with("/root.yaml") {
b"Item: { $ref: './child.yaml#/Item' }".as_slice()
} else {
assert!(canonical_uri.ends_with("/child.yaml"));
b"Item: { type: object, required: [id], properties: { id: { type: string } } }"
.as_slice()
};
assert_eq!(verified.bytes, expected_bytes);
let foreign_read = registry
.read_artifact_source(Arc::clone(&store), &foreign_workspace_id, &source_id)
.await
.expect_err("foreign workspace must not read an owned snapshot");
let unknown_source_id = ArtifactSourceId::new("src_unknown_scope_probe");
let unknown_read = registry
.read_artifact_source(
Arc::clone(&store),
&foreign_workspace_id,
&unknown_source_id,
)
.await
.expect_err("unknown source must have the same scoped outcome");
let foreign_body = source_not_found_body(foreign_read).await;
let unknown_body = source_not_found_body(unknown_read).await;
assert_eq!(foreign_body, unknown_body);
let rendered_body = foreign_body.to_string();
assert!(!rendered_body.contains(digest));
assert!(!rendered_body.contains(canonical_uri));
assert!(!rendered_body.contains(source_id.as_str()));
}
let applied = service
.create_openapi_import(
&workspace_id,
@@ -122,6 +184,59 @@ paths:
assert_eq!(active_sources, 0);
}
fn external_upload(origin: &str) -> OpenApiUpload {
OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: Scoped external snapshot }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content:
application/json:
schema: {{ $ref: '{origin}/schema.yaml#/Item' }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
async fn create_workspace(registry: &crank_registry::PostgresRegistry, id: &str) -> WorkspaceId {
let workspace_id = WorkspaceId::new(id);
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: id.replace('_', "-"),
display_name: id.to_owned(),
status: WorkspaceStatus::Active,
settings: serde_json::json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
workspace_id
}
async fn source_not_found_body(error: RegistryError) -> serde_json::Value {
assert!(matches!(&error, RegistryError::SourceNotFound { .. }));
let response = ApiError::from(error).into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
serde_json::from_slice(&body).unwrap()
}
#[tokio::test]
#[serial]
async fn external_secret_document_is_rejected_before_blob_registration() {