feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s

Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

+70
View File
@@ -45,6 +45,17 @@ use crate::{
get_operation_version, list_operations, publish_operation, run_test, update_operation,
upload_input_json, upload_output_json,
},
prompts::{
create_prompt_draft, export_prompt_draft, export_prompt_version, get_prompt_draft,
import_prompt, list_prompt_drafts, preview_prompt_draft, prompt_action,
update_prompt_draft,
},
resources::{
archive_resource, create_resource, download_resource, download_resource_version,
export_resource, export_resource_version, get_resource, get_resource_version,
import_resource, list_resources, preview_resource, publish_resource, revoke_resource,
test_resource, update_resource,
},
secrets::{create_secret, delete_secret, get_secret, list_secrets, rotate_secret},
upstreams::{create_upstream, list_upstreams, update_upstream},
workspaces::{get_workspace, list_workspaces, update_workspace},
@@ -55,6 +66,60 @@ use crate::{
pub fn build_app(state: AppState) -> Router {
let workspace_router = Router::new()
.route("/operations", get(list_operations).post(create_operation))
.route(
"/resources",
get(list_resources)
.post(create_resource)
.layer(DefaultBodyLimit::max(MAX_ARTIFACT_BYTES + 32 * 1024)),
)
.route(
"/prompts",
get(list_prompt_drafts).post(create_prompt_draft),
)
.route(
"/prompts/{prompt_id}",
get(get_prompt_draft)
.put(update_prompt_draft)
.post(prompt_action),
)
.route("/prompts/{prompt_id}/preview", post(preview_prompt_draft))
.route("/prompts/import", post(import_prompt))
.route("/prompts/{prompt_id}/export", get(export_prompt_draft))
.route(
"/prompts/{prompt_id}/versions/{version}/export",
get(export_prompt_version),
)
.route(
"/resources/{resource_id}",
get(get_resource)
.put(update_resource)
.layer(DefaultBodyLimit::max(MAX_ARTIFACT_BYTES + 32 * 1024)),
)
.route("/resources/{resource_id}/preview", get(preview_resource))
.route("/resources/{resource_id}/test-runs", post(test_resource))
.route("/resources/{resource_id}/content", get(download_resource))
.route("/resources/{resource_id}/export", get(export_resource))
.route(
"/resources/import",
post(import_resource).layer(DefaultBodyLimit::max(
crate::service::resources::portability::MAX_IMPORT_BODY_BYTES,
)),
)
.route("/resources/{resource_id}/publish", post(publish_resource))
.route("/resources/{resource_id}/archive", post(archive_resource))
.route("/resources/{resource_id}/revoke", post(revoke_resource))
.route(
"/resources/{resource_id}/versions/{version}",
get(get_resource_version),
)
.route(
"/resources/{resource_id}/versions/{version}/content",
get(download_resource_version),
)
.route(
"/resources/{resource_id}/versions/{version}/export",
get(export_resource_version),
)
.route(
"/imports/openapi/preview",
post(preview_openapi_import)
@@ -250,3 +315,8 @@ pub fn build_app(state: AppState) -> Router {
}
use crate::routes::operations::import_operation;
/// AT-3.6-02/06: приватная тестовая composition fixture (FINAL-DISPOSITION run99:47).
/// Собирается только в `cfg(test)`: non-test сборка `admin-api` модуль не видит.
#[cfg(test)]
pub(crate) mod resource_test_support;
@@ -0,0 +1,960 @@
//! AT-3.6-02/06: приватная `#[cfg(test)]` composition fixture для HTTP guard-путей Story 3.6.
//!
//! Источник полномочий: FINAL-DISPOSITION run99:47 (Q1) — принимается рекомендованный ARC
//! test-only composition fixture **вне** сервиса: точный путь
//! `apps/admin-api/src/app/resource_test_support.rs`, регистрация `#[cfg(test)] pub(crate)
//! mod resource_test_support;` в `app.rs`. TL review run101 R-A требует: fixture возвращает
//! готовый `PostgresRegistry`/изолированный router context (не raw pool в сервисе), а
//! драйвер/миграция/SQL-наблюдения состояния живут только здесь, в composition root.
//!
//! Модуль собирается исключительно для `cfg(test)`: в non-test сборке `admin-api` его нет
//! (регистрация в `app.rs` под тем же `cfg`), поэтому production API и boundary-проверки
//! не меняются. Пять исходных service-счётчиков `service::resources::tests` остаются
//! отдельным, неизменённым набором; этот файл даёт **реальный HTTP** поверх настоящих
//! middleware-ов (`require_session`, `require_workspace_session`,
//! `require_csrf_for_browser_mutations`, `enforce_browser_security`), поэтому отказ,
//! случившийся до сервиса, наблюдается как нулевые счётчики put/read физического хранилища.
//!
//! Проверки, которые опираются на этот fixture, лежат рядом с ним:
//! `crate::service::resources::tests::guard_path`.
#![allow(dead_code)]
use std::{
net::SocketAddr,
path::PathBuf,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use axum::Router;
use crank_core::{MembershipRole, Workspace, WorkspaceId, WorkspaceStatus};
use crank_registry::{
CreateWorkspaceRequest, MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate,
PostgresRegistry,
};
use crank_runtime::SecretCrypto;
use reqwest::StatusCode;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::multipart::{Form, Part};
use serde_json::{Value, json};
use sqlx::Row as _;
use tokio::net::{TcpListener, TcpStream};
use crate::{
app::build_app,
auth::{AuthSettings, BootstrapAdminConfig, hash_password},
service::AdminServiceBuilder,
state::AppState,
};
pub(crate) const DEFAULT_WORKSPACE_ID: &str = "ws_default";
pub(crate) const OWNER_EMAIL: &str = "owner@crank.local";
pub(crate) const OWNER_PASSWORD: &str = "test-password";
/// Синтетическое WorkspaceB без членства вызывающего пользователя (workspace-негатив).
pub(crate) const FOREIGN_WORKSPACE_ID: &str = "ws_story36_guard_foreign";
/// Synthetic Viewer в `ws_default`: доступ на чтение есть, мутация запрещена (Owner-only).
pub(crate) const VIEWER_EMAIL: &str = "story36_guard_viewer@crank.local";
pub(crate) const VIEWER_PASSWORD: &str = "story36-guard-viewer-password";
/// Owner чужого WorkspaceB: создаёт и читает существующий ResourceB в своём workspace.
pub(crate) const FOREIGN_OWNER_EMAIL: &str = "story36_guard_foreign_owner@crank.local";
pub(crate) const FOREIGN_OWNER_PASSWORD: &str = "story36-guard-foreign-password";
const PASSWORD_PEPPER: &str = "test-password-pepper";
const SESSION_SECRET: &str = "test-session-secret";
const MASTER_KEY: &str = "test-master-key-00000000000000000000000000000000";
const FOREIGN_ORIGIN: &str = "http://evil.example.test";
const FOREIGN_HOST: &str = "evil.example.test";
/// Однофакторные вариации стенда: срок жизни сессии, Viewer-членство, чужое workspace,
/// настраиваемый предел содержимого.
#[derive(Clone, Copy, Debug)]
pub(crate) struct GuardOptions {
pub session_ttl_hours: i64,
pub viewer_membership: bool,
pub foreign_workspace: bool,
/// Owner-членство отдельного аккаунта в чужом WorkspaceB (существующий ResourceB).
pub foreign_workspace_owner: bool,
/// Настроенный предел содержимого Resource (`ResourceLimits::uniform`); `None` — default.
pub resource_limit: Option<usize>,
}
impl Default for GuardOptions {
fn default() -> Self {
Self {
session_ttl_hours: 24,
viewer_membership: false,
foreign_workspace: false,
foreign_workspace_owner: false,
resource_limit: None,
}
}
}
/// Изолированный стенд: собственная PG-схема на тест, приватный artifact root, реальный router.
pub(crate) struct GuardHarness {
pub registry: PostgresRegistry,
pub auth: AuthSettings,
/// Корень API без workspace-префикса — точка входа `/api/auth/login`.
pub root_url: String,
/// Workspace-scoped база `ws_default` — точка входа `/resources...`.
pub base_url: String,
/// Loopback-адрес стенда: нужен для настоящих фрагментированных HTTP-запросов
/// (chunked/absent Content-Length), которые нельзя выразить `reqwest`-клиентом.
pub addr: SocketAddr,
/// Приватный artifact root стенда: по нему проверяются физические отказы чтения.
pub storage_root: PathBuf,
shutdown: Option<tokio::sync::oneshot::Sender<()>>,
handle: Option<tokio::task::JoinHandle<()>>,
}
impl Drop for GuardHarness {
fn drop(&mut self) {
let shutdown = self.shutdown.take();
let handle = self.handle.take();
tokio::task::block_in_place(|| {
if let Some(shutdown) = shutdown {
let _ = shutdown.send(());
}
if let Some(handle) = handle {
let _ = tokio::runtime::Handle::current().block_on(handle);
}
});
}
}
impl GuardHarness {
/// Стенд по умолчанию: 24-часовые сессии, только Owner-членство, без чужого workspace.
pub(crate) async fn spawn(name: &str) -> Self {
Self::spawn_with(name, GuardOptions::default()).await
}
pub(crate) async fn spawn_with(name: &str, options: GuardOptions) -> Self {
let (database_url, pool) = resource_schema(&format!("story36_guard_{name}")).await;
crank_registry::MigrationAuthority::apply(&pool)
.await
.expect("real V16 migrations must apply to the isolated schema");
drop(pool);
let registry = PostgresRegistry::connect(&database_url)
.await
.expect("fixture registry must connect");
let secret_crypto = SecretCrypto::new(MASTER_KEY).expect("static master key must be valid");
registry
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
epoch: secret_crypto.master_key_epoch(),
fingerprint: secret_crypto.master_key_fingerprint(),
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
observed_at: &time::OffsetDateTime::now_utc(),
})
.await
.expect("master key identity must be registered");
seed_owner(&registry).await;
if options.viewer_membership {
seed_viewer(&registry).await;
}
if options.foreign_workspace {
create_foreign_workspace(&registry).await;
}
if options.foreign_workspace_owner {
seed_foreign_owner(&registry).await;
}
let auth = AuthSettings {
session_secret: SESSION_SECRET.to_owned(),
password_pepper: PASSWORD_PEPPER.to_owned(),
session_ttl_hours: options.session_ttl_hours,
cookie_secure: false,
bootstrap_admin: BootstrapAdminConfig {
email: OWNER_EMAIL.to_owned(),
password: OWNER_PASSWORD.to_owned(),
display_name: "Story 3.6 Guard Owner".to_owned(),
},
};
let storage_root = private_storage_root(name);
let runtime = crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build();
let mut builder = AdminServiceBuilder::new(
registry.clone(),
storage_root.clone(),
auth.clone(),
secret_crypto,
runtime,
);
if let Some(limit) = options.resource_limit {
builder = builder.with_resource_limits(
crank_core::resource::ResourceLimits::uniform(limit)
.expect("the configured test limit must stay inside the storage ceiling"),
);
}
let service = builder.build();
let app = build_app(AppState {
service,
api_rate_limiter: crank_runtime::RequestRateLimiter::new(
crank_runtime::RequestRateLimitConfig::new(10_000, 10_000)
.expect("static rate limit config"),
),
trusted_proxy_ips: Vec::new(),
});
let (root_url, base_url, addr, shutdown, handle) = serve(app).await;
Self {
registry,
auth,
root_url,
base_url,
addr,
storage_root,
shutdown: Some(shutdown),
handle: Some(handle),
}
}
/// Session-клиент реального synthetic-аккаунта без CSRF-заголовка.
pub(crate) async fn session_client(&self, email: &str, password: &str) -> reqwest::Client {
login_client(&self.root_url, email, password, LoginOptions::default()).await
}
/// Адрес workspace-сокращённого Resource-маршрута.
pub(crate) fn resources_url(&self) -> String {
format!("{}/resources", self.base_url)
}
pub(crate) fn resource_url(&self, resource_id: &str) -> String {
format!("{}/resources/{resource_id}", self.base_url)
}
pub(crate) fn nested_url(&self, resource_id: &str, suffix: &str) -> String {
format!("{}/resources/{resource_id}/{suffix}", self.base_url)
}
/// URL чужого workspace в том же router: доступ к маршруту есть, прав нет.
pub(crate) fn foreign_resources_url(&self) -> String {
let root = self
.base_url
.split("/api/admin/workspaces/")
.next()
.expect("workspace base url keeps the admin prefix");
format!("{root}/api/admin/workspaces/{FOREIGN_WORKSPACE_ID}/resources")
}
/// Принятые черновики `ws_default` через публичное чтение реестра (composition root).
pub(crate) async fn accepted_drafts(
&self,
) -> Vec<crank_registry::model::resource::ResourceDraftRecord> {
self.registry
.list_resource_drafts(DEFAULT_WORKSPACE_ID, 100)
.await
.expect("accepted drafts must be readable")
}
}
/// Параметры логина: наличие CSRF-заголовка и подменённый `Origin`/`Host`.
#[derive(Clone, Copy, Default)]
pub(crate) struct LoginOptions {
pub csrf: bool,
/// Явное значение заголовка `x-csrf-token` вместо настоящего токена сессии
/// (R-A: недостающий **и чужой** CSRF проверяются отдельно).
pub csrf_token: Option<&'static str>,
pub foreign_origin: bool,
/// `None` — валидный Origin реального адреса стенда (`http://127.0.0.1:<port>`).
pub origin: Option<&'static str>,
/// `Some(value)` — подменённый `Host`, с которым сравнивается `Origin`.
pub host: Option<&'static str>,
}
impl LoginOptions {
pub(crate) fn with_csrf() -> Self {
Self {
csrf: true,
..Self::default()
}
}
/// Тот же аккаунт, но с заведомо чужим значением CSRF-заголовка.
pub(crate) fn with_wrong_csrf() -> Self {
Self {
csrf: true,
csrf_token: Some("story36-not-the-session-token"),
..Self::default()
}
}
/// Cross-origin запрос: чужой `Origin` при настоящем `Host` стенда.
///
/// `Host` намеренно НЕ подменяется: иначе authority совпала бы с `Origin` и запрос
/// перестал бы быть cross-origin (проверка `enforce_browser_security`).
pub(crate) fn cross_origin() -> Self {
Self {
csrf: true,
origin: Some(FOREIGN_ORIGIN),
host: None,
..Self::default()
}
}
}
/// Логин реального аккаунта через `/api/auth/login` и сборка клиента с cookie jar.
pub(crate) async fn login_client(
root_url: &str,
email: &str,
password: &str,
options: LoginOptions,
) -> reqwest::Client {
let cookie_jar = Arc::new(reqwest::cookie::Jar::default());
let login_client = reqwest::Client::builder()
.cookie_provider(Arc::clone(&cookie_jar))
.build()
.expect("login client");
let response = login_client
.post(format!("{root_url}/api/auth/login"))
.json(&json!({ "email": email, "password": password }))
.send()
.await
.expect("login request must complete");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
StatusCode::OK,
"synthetic account `{email}` must log in: status={status} body={body}"
);
let mut headers = HeaderMap::new();
if options.csrf {
let token = match options.csrf_token {
Some(token) => token,
None => body["csrf_token"]
.as_str()
.expect("successful login must return csrf_token"),
};
headers.insert(
"x-csrf-token",
HeaderValue::from_str(token).expect("csrf header value"),
);
}
if let Some(origin) = options.origin {
headers.insert(
reqwest::header::ORIGIN,
HeaderValue::from_str(origin).expect("origin header value"),
);
}
if let Some(host) = options.host {
headers.insert(
reqwest::header::HOST,
HeaderValue::from_str(host).expect("host header value"),
);
}
reqwest::Client::builder()
.cookie_provider(cookie_jar)
.default_headers(headers)
.build()
.expect("session client")
}
/// Клиент без сессии (реальный anonymous HTTP-запрос через те же middleware).
pub(crate) fn anonymous_client() -> reqwest::Client {
reqwest::Client::builder()
.build()
.expect("anonymous client")
}
// ---------------------------------------------------------------------------
// Multipart Draft flow (та же форма, что у UI и integration-набора)
// ---------------------------------------------------------------------------
pub(crate) fn draft_metadata(
uri: &str,
name: &str,
kind: &str,
mime: &str,
sensitivity: &str,
) -> Value {
json!({
"uri": uri,
"name": name,
"description": "",
"kind": kind,
"mime_type": mime,
"sensitivity": sensitivity,
})
}
pub(crate) fn draft_form(metadata: &Value, content: &[u8], filename: &str, mime: &str) -> Form {
Form::new()
.part(
"metadata",
Part::bytes(serde_json::to_vec(metadata).expect("metadata must serialize"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("json part mime"),
)
.part(
"content",
Part::bytes(content.to_vec())
.file_name(filename.to_owned())
.mime_str(mime)
.expect("content part mime"),
)
}
/// Метаданные обновления Draft: изменяемые поля + precondition, без immutable-ключей (D-16).
pub(crate) fn update_metadata(
description: &str,
mime: &str,
sensitivity: &str,
expected_updated_at: &str,
) -> Value {
json!({
"description": description,
"mime_type": mime,
"sensitivity": sensitivity,
"expected_updated_at": expected_updated_at,
})
}
/// Значение precondition `expected_updated_at` из карточки Draft.
pub(crate) fn draft_updated_at(card: &Value) -> String {
card.pointer("/resource/updated_at")
.or_else(|| card.pointer("/version/updated_at"))
.and_then(Value::as_str)
.expect("a Draft card must expose the precondition timestamp")
.to_owned()
}
/// POST Draft: статус, наличие `x-trace-id`, текст тела, разобранный JSON.
pub(crate) async fn post_draft(
client: &reqwest::Client,
url: &str,
metadata: &Value,
content: &[u8],
mime: &str,
) -> (StatusCode, bool, String, Value) {
let response = client
.post(url)
.multipart(draft_form(metadata, content, "draft.bin", mime))
.send()
.await
.expect("draft POST must complete");
let status = response.status();
let traceable = response.headers().contains_key("x-trace-id");
let text = response.text().await.unwrap_or_default();
let body = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
(status, traceable, text, body)
}
/// PUT Draft: статус, заголовки, текст тела, разобранный JSON.
pub(crate) async fn put_draft(
client: &reqwest::Client,
url: &str,
metadata: &Value,
content: &[u8],
mime: &str,
) -> (StatusCode, HeaderMap, String, Value) {
let response = client
.put(url)
.multipart(draft_form(metadata, content, "draft.bin", mime))
.send()
.await
.expect("draft PUT must complete");
let status = response.status();
let headers = response.headers().clone();
let text = response.text().await.unwrap_or_default();
let body = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
(status, headers, text, body)
}
/// GET: статус, заголовки, текст тела, разобранный JSON.
pub(crate) async fn get_raw(
client: &reqwest::Client,
url: &str,
) -> (StatusCode, HeaderMap, String, Value) {
let response = client.get(url).send().await.expect("GET must complete");
let status = response.status();
let headers = response.headers().clone();
let text = response.text().await.unwrap_or_default();
let body = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
(status, headers, text, body)
}
/// Полная подпись отказа: статус + стабильные `error.code`/`error.context.field`.
pub(crate) fn error_signature(status: StatusCode, body: &Value) -> String {
let code = body["error"]["code"].as_str().unwrap_or("<absent>");
let field = body["error"]["context"]["field"]
.as_str()
.unwrap_or("<absent>");
let message = body["error"]["message"].as_str().unwrap_or("<absent>");
format!("status={status} code={code} field={field} message={message}")
}
/// Идентификатор созданного Draft в ответе 201.
pub(crate) fn created_resource_id(body: &Value) -> String {
body["resource"]["resource_id"]
.as_str()
.or_else(|| body["resource"]["id"].as_str())
.expect("201 response must carry the created Resource identifier")
.to_owned()
}
// ---------------------------------------------------------------------------
// Сев аккаунтов и приватных корней
// ---------------------------------------------------------------------------
async fn seed_owner(registry: &PostgresRegistry) {
let password_hash = hash_password(OWNER_PASSWORD, PASSWORD_PEPPER).expect("owner hash");
let user_id = registry
.upsert_bootstrap_user(OWNER_EMAIL, "Story 3.6 Guard Owner", &password_hash)
.await
.expect("owner account");
registry
.ensure_membership(
&WorkspaceId::new(DEFAULT_WORKSPACE_ID),
&user_id,
MembershipRole::Owner,
)
.await
.expect("owner membership in ws_default");
}
async fn seed_viewer(registry: &PostgresRegistry) {
let password_hash = hash_password(VIEWER_PASSWORD, PASSWORD_PEPPER).expect("viewer hash");
let user_id = registry
.upsert_bootstrap_user(VIEWER_EMAIL, "Story 3.6 Guard Viewer", &password_hash)
.await
.expect("viewer account");
registry
.ensure_membership(
&WorkspaceId::new(DEFAULT_WORKSPACE_ID),
&user_id,
MembershipRole::Viewer,
)
.await
.expect("viewer membership in ws_default");
}
/// Owner чужого WorkspaceB: создаёт и читает существующий ResourceB в своём workspace.
async fn seed_foreign_owner(registry: &PostgresRegistry) {
let password_hash =
hash_password(FOREIGN_OWNER_PASSWORD, PASSWORD_PEPPER).expect("foreign owner hash");
let user_id = registry
.upsert_bootstrap_user(
FOREIGN_OWNER_EMAIL,
"Story 3.6 Guard Foreign Owner",
&password_hash,
)
.await
.expect("foreign owner account");
registry
.ensure_membership(
&WorkspaceId::new(FOREIGN_WORKSPACE_ID),
&user_id,
MembershipRole::Owner,
)
.await
.expect("foreign owner membership in WorkspaceB");
}
async fn create_foreign_workspace(registry: &PostgresRegistry) {
let now = time::OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: WorkspaceId::new(FOREIGN_WORKSPACE_ID),
slug: "story36-guard-foreign".to_owned(),
display_name: "Story 3.6 Guard Foreign".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("foreign workspace must be created");
}
fn private_storage_root(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"crank_admin_api_guard_{name}_{}_{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock after epoch")
.as_nanos()
));
std::fs::create_dir_all(&root).expect("guard artifact root must be creatable");
#[cfg(unix)]
std::fs::set_permissions(&root, std::os::unix::fs::PermissionsExt::from_mode(0o700))
.expect("guard artifact root must be private");
root
}
// ---------------------------------------------------------------------------
// Настоящий фрагментированный запрос (chunked, без Content-Length) и наблюдения
// durable-артефакта: обычным `reqwest`-клиентом это не выражается, а SQL и файловые
// наблюдения обязаны жить в composition root, а не в сервисных тестах (R-A/R-D).
// ---------------------------------------------------------------------------
/// Сессия стенда в виде, пригодном для рукописного HTTP-запроса на сокете.
pub(crate) struct RawSession {
pub cookie: String,
pub csrf: String,
}
/// Логин без cookie-jar: cookie и CSRF-токен извлекаются напрямую.
pub(crate) async fn raw_session(root_url: &str, email: &str, password: &str) -> RawSession {
let client = reqwest::Client::builder()
.build()
.expect("raw login client");
let response = client
.post(format!("{root_url}/api/auth/login"))
.json(&json!({ "email": email, "password": password }))
.send()
.await
.expect("raw login must complete");
assert_eq!(
response.status(),
StatusCode::OK,
"the raw session login must succeed"
);
let cookie = response
.headers()
.get_all(reqwest::header::SET_COOKIE)
.iter()
.filter_map(|value| value.to_str().ok())
.filter_map(|value| value.split(';').next())
.collect::<Vec<_>>()
.join("; ");
let body: Value = response.json().await.unwrap_or(Value::Null);
let csrf = body["csrf_token"].as_str().unwrap_or_default().to_owned();
assert!(
!cookie.is_empty() && !csrf.is_empty(),
"a raw session must carry both the cookie and the CSRF token"
);
RawSession { cookie, csrf }
}
/// Ответ рукописного HTTP-запроса: статус-код и тело.
pub(crate) struct RawHttpResponse {
pub status: u16,
/// Голова ответа как её прислал сервер (нужна для диагностики отказов);
/// значения чувствительных заголовков отредактированы.
pub head: String,
pub body: String,
/// Отправленная голова запроса: без неё отказ не отличить от ошибки харнесса.
/// Хранится уже с отредактированными чувствительными заголовками (F5).
pub request_head: String,
/// Ошибка записи фрагмента (сервер мог ответить и закрыть соединение) — наблюдение.
pub write_error: Option<String>,
/// Ошибка дочитывания ответа; пустое тело при `Some` — не «нет ответа», а обрыв.
pub read_error: Option<String>,
}
impl RawHttpResponse {
/// Компактная подпись для сообщений об отказе.
pub(crate) fn signature(&self) -> String {
format!(
"status={} write_error={:?} read_error={:?} response_head={} request_head={} body={}",
self.status,
self.write_error,
self.read_error,
self.head.replace('\r', "").replace('\n', " | "),
self.request_head.replace('\r', "").replace('\n', " | "),
self.body
)
}
}
/// Настоящий chunked-запрос: тело уходит несколькими фрагментами, `Content-Length`
/// отсутствует, `Transfer-Encoding: chunked` объявлен явно.
pub(crate) async fn send_chunked_multipart(
addr: SocketAddr,
path: &str,
session: &RawSession,
boundary: &str,
chunks: &[Vec<u8>],
) -> RawHttpResponse {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let mut stream = TcpStream::connect(addr)
.await
.expect("the raw loopback socket must connect");
let head_request = format!(
"POST {path} HTTP/1.1\r\nHost: {addr}\r\nCookie: {}\r\nX-CSRF-Token: {}\r\n\
Content-Type: multipart/form-data; boundary={boundary}\r\n\
Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n",
session.cookie, session.csrf
);
stream
.write_all(head_request.as_bytes())
.await
.expect("the request head must be written");
// Запись фрагментов может прерваться, если сервер уже ответил и закрыл соединение
// (например, ранний отказ guard-а или отказ по лимиту). Это наблюдение, а не ошибка
// теста: ответ всё равно дочитывается ниже и попадает в assertions.
let mut write_error: Option<std::io::Error> = None;
for chunk in chunks {
let size = format!("{:x}\r\n", chunk.len());
let fragment = [
stream.write_all(size.as_bytes()).await,
stream.write_all(chunk).await,
stream.write_all(b"\r\n").await,
];
if let Some(error) = fragment.into_iter().find_map(Result::err) {
write_error = Some(error);
break;
}
stream.flush().await.expect("a fragment must be flushed");
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
if write_error.is_none() {
let _ = stream.write_all(b"0\r\n\r\n").await;
}
let _ = stream.flush().await;
let mut raw = Vec::new();
let read_error = stream.read_to_end(&mut raw).await.err();
let text = String::from_utf8_lossy(&raw).into_owned();
let (head, body) = text.clone().split_once("\r\n\r\n").map_or_else(
|| (String::new(), String::new()),
|(head, body)| (head.to_owned(), body.to_owned()),
);
let status = head
.split_whitespace()
.nth(1)
.and_then(|code| code.parse::<u16>().ok())
.unwrap_or(0);
RawHttpResponse {
status,
// Обе головы сохраняются уже отредактированными: ни request-, ни response-голова
// не должны уносить session/CSRF-значения в авторский raw-журнал (F5).
head: redact_sensitive_headers(&head),
body,
request_head: redact_sensitive_headers(&head_request),
write_error: write_error.map(|error| error.to_string()),
read_error: read_error.map(|error| error.to_string()),
}
}
/// Наблюдаемая идентичность durable-артефакта версии Resource (blob + версия + owning ref).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArtifactIdentity {
pub blob_digest: String,
pub blob_size_bytes: i64,
pub blob_artifact_ref: String,
pub blob_lifecycle: String,
pub version_digest: String,
pub version_size_bytes: i64,
pub version_mime_type: String,
pub version_sensitivity: String,
pub source_id: String,
pub source_mime_type: String,
pub source_sensitivity: String,
pub source_lifecycle: String,
pub source_detached_at: Option<time::OffsetDateTime>,
}
/// Однофакторные мутации metadata, от которых зависит сверка чтения Resource (§6).
///
/// Расхождение `artifact_blobs.artifact_ref` с digest не входит в матрицу: его
/// структурно запрещает CHECK `artifact_blobs_ref_check (artifact_ref = 'sha256:' || digest)`,
/// поэтому такой вектор был бы недостижимым, а не «пропущенным дефектом».
#[derive(Clone, Copy, Debug)]
pub(crate) enum ArtifactMutation {
BlobSize,
BlobStorageLifecycle,
VersionDigest,
VersionSize,
VersionMimeType,
VersionSensitivity,
SourceMimeType,
SourceLifecycle,
}
impl ArtifactMutation {
pub(crate) const ALL: [Self; 8] = [
Self::BlobSize,
Self::BlobStorageLifecycle,
Self::VersionDigest,
Self::VersionSize,
Self::VersionMimeType,
Self::VersionSensitivity,
Self::SourceMimeType,
Self::SourceLifecycle,
];
pub(crate) fn label(self) -> &'static str {
match self {
Self::BlobSize => "blob-size",
Self::BlobStorageLifecycle => "blob-storage-lifecycle",
Self::VersionDigest => "version-digest",
Self::VersionSize => "version-size",
Self::VersionMimeType => "version-mime-type",
Self::VersionSensitivity => "version-sensitivity",
Self::SourceMimeType => "source-mime-type",
Self::SourceLifecycle => "source-lifecycle",
}
}
fn statement(self) -> &'static str {
match self {
Self::BlobSize => "update artifact_blobs set size_bytes = size_bytes + 1",
Self::BlobStorageLifecycle => {
"update artifact_blobs set storage_lifecycle = 'unavailable'"
}
Self::VersionDigest => "update resource_versions set digest = repeat('0', 64)",
Self::VersionSize => "update resource_versions set size_bytes = size_bytes + 1",
Self::VersionMimeType => "update resource_versions set mime_type = 'text/html'",
Self::VersionSensitivity => "update resource_versions set sensitivity = 'public'",
Self::SourceMimeType => "update artifact_sources set mime_type = 'text/html'",
Self::SourceLifecycle => {
"update artifact_sources set lifecycle = 'detached', detached_at = updated_at"
}
}
}
}
/// Текущая идентичность артефакта workspace (ровно одна текущая версия в тестах).
pub(crate) async fn observe_artifact_identity(
pool: &sqlx::PgPool,
workspace_id: &str,
) -> ArtifactIdentity {
let row = sqlx::query(
"select b.digest as blob_digest, b.size_bytes as blob_size_bytes,
b.artifact_ref as blob_artifact_ref, b.storage_lifecycle as blob_lifecycle,
v.digest as version_digest, v.size_bytes as version_size_bytes,
v.mime_type as version_mime_type, v.sensitivity as version_sensitivity,
s.source_id, s.mime_type as source_mime_type,
s.sensitivity as source_sensitivity, s.lifecycle as source_lifecycle,
s.detached_at as source_detached_at
from artifact_blobs b
join artifact_sources s on s.blob_digest = b.digest
join resource_versions v
on v.workspace_id = s.workspace_id and v.artifact_source_id = s.source_id
where s.workspace_id = $1
order by s.source_id
limit 1",
)
.bind(workspace_id)
.fetch_one(pool)
.await
.expect("the durable artifact identity must be observable");
ArtifactIdentity {
blob_digest: row.get("blob_digest"),
blob_size_bytes: row.get("blob_size_bytes"),
blob_artifact_ref: row.get("blob_artifact_ref"),
blob_lifecycle: row.get("blob_lifecycle"),
version_digest: row.get("version_digest"),
version_size_bytes: row.get("version_size_bytes"),
version_mime_type: row.get("version_mime_type"),
version_sensitivity: row.get("version_sensitivity"),
source_id: row.get("source_id"),
source_mime_type: row.get("source_mime_type"),
source_sensitivity: row.get("source_sensitivity"),
source_lifecycle: row.get("source_lifecycle"),
source_detached_at: row.get("source_detached_at"),
}
}
/// Применяет одну однофакторную мутацию metadata (SQL только в composition root).
pub(crate) async fn apply_artifact_mutation(
pool: &sqlx::PgPool,
mutation: ArtifactMutation,
) -> Result<(), sqlx::Error> {
sqlx::raw_sql(sqlx::AssertSqlSafe(mutation.statement().to_owned()))
.execute(pool)
.await
.map(|_| ())
}
/// Возвращает зафиксированные значения байт-в-байт (не «похожие»).
pub(crate) async fn restore_artifact_identity(
pool: &sqlx::PgPool,
workspace_id: &str,
identity: &ArtifactIdentity,
) -> Result<(), sqlx::Error> {
sqlx::query(
"update artifact_blobs
set digest = $1, size_bytes = $2, artifact_ref = $3, storage_lifecycle = $4
where digest = $1",
)
.bind(&identity.blob_digest)
.bind(identity.blob_size_bytes)
.bind(&identity.blob_artifact_ref)
.bind(&identity.blob_lifecycle)
.execute(pool)
.await?;
sqlx::query(
"update resource_versions
set digest = $1, size_bytes = $2, mime_type = $3, sensitivity = $4
where workspace_id = $5 and artifact_source_id = $6",
)
.bind(&identity.version_digest)
.bind(identity.version_size_bytes)
.bind(&identity.version_mime_type)
.bind(&identity.version_sensitivity)
.bind(workspace_id)
.bind(&identity.source_id)
.execute(pool)
.await?;
sqlx::query(
"update artifact_sources
set mime_type = $1, sensitivity = $2, lifecycle = $3, detached_at = $4
where workspace_id = $5 and source_id = $6",
)
.bind(&identity.source_mime_type)
.bind(&identity.source_sensitivity)
.bind(&identity.source_lifecycle)
.bind(identity.source_detached_at)
.bind(workspace_id)
.bind(&identity.source_id)
.execute(pool)
.await?;
Ok(())
}
// ---------------------------------------------------------------------------
// Подмодуль наблюдений: редактирование заголовков (F5), composition-стенд сервисных
// проверок чтения (F3), SQL/файловые наблюдения. Разделён по health-правилу 1000 строк;
// границы и регистрация модуля не меняются.
// ---------------------------------------------------------------------------
mod observations;
pub(crate) use observations::{
ResourceServiceHarness, artifact_files, redact_sensitive_headers, resource_row_counts,
resource_schema,
};
/// Поднимает реальный router на loopback и возвращает URL-ы, адрес и ручки остановки.
async fn serve(
app: Router,
) -> (
String,
String,
SocketAddr,
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
) {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("ephemeral loopback port");
let address: SocketAddr = listener.local_addr().expect("listener address");
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let handle = tokio::spawn(async move {
axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
.expect("guard harness server must serve");
});
(
format!("http://{address}"),
format!("http://{address}/api/admin/workspaces/{DEFAULT_WORKSPACE_ID}"),
address,
shutdown_tx,
handle,
)
}
@@ -0,0 +1,136 @@
//! Наблюдения и composition-часть приватного ATDD-стенда Story 3.6.
//!
//! Подмодуль того же приватного `#[cfg(test)]` фикстура
//! `crate::app::resource_test_support` (регистрация в `app.rs` не меняется): физическое
//! разделение выполнено только потому, что health-правило репозитория ограничивает файл
//! 1000 строками (`scripts/check-rust-code-health.sh`), а базовая часть модуля уже
//! содержит HTTP-стенд guard-проверок. Здесь находятся:
//!
//! * редактирование чувствительных заголовков рукописной диагностики (F5, TL run105);
//! * composition-стенд сервисных проверок чтения Resource (F3/F4, TL run105);
//! * SQL-наблюдение итогов строк V16 и файловые наблюдения содержимого.
//!
//! Границы те же, что у корневого файла: `cfg(test)`-only, никакого production API.
use std::{path::PathBuf, sync::Arc};
use crank_artifacts::ArtifactStore;
use crank_core::resource::ResourceLimits;
use crank_registry::PostgresRegistry;
use crate::service::resources::ResourcesService;
// ---------------------------------------------------------------------------
// F5: диагностика не несёт значения чувствительных заголовков
// ---------------------------------------------------------------------------
/// Значения этих заголовков не попадают в диагностику даже синтетического стенда.
const SENSITIVE_HEADERS: [&str; 4] = ["cookie", "set-cookie", "x-csrf-token", "authorization"];
/// Редактирует значения чувствительных заголовков (AGENTS: credentials не в журналах).
///
/// Редактирование выполняется **до** сохранения головы, а не при печати (TL run105 F5);
/// метод, путь, структура заголовков и статус сохраняются, иначе отказ не отличить от
/// ошибки харнесса.
pub(crate) fn redact_sensitive_headers(head: &str) -> String {
head.split("\r\n")
.map(|line| match line.split_once(':') {
Some((name, _value))
if SENSITIVE_HEADERS.contains(&name.trim().to_ascii_lowercase().as_str()) =>
{
format!("{name}: <redacted-sensitive-header>")
}
_ => line.to_owned(),
})
.collect::<Vec<_>>()
.join("\r\n")
}
// ---------------------------------------------------------------------------
// F3/F4: composition-стенд сервисных проверок чтения Resource
// ---------------------------------------------------------------------------
/// Изолированная PG-схема вместе с соединением к ней.
///
/// Конкретный драйвер допускается только в composition root (`cfg(test)`-фикстура
/// вне `service/**`): сервисные тест-модули получают готовые registry/service и
/// не называют адаптер хранилища сами (TL run105 F3, FINAL-DISPOSITION run99:47).
pub(crate) async fn resource_schema(prefix: &str) -> (String, sqlx::PgPool) {
let url = crank_test_support::postgres_schema_url(prefix).await;
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(2)
.connect(&url)
.await
.expect("the isolated test schema must accept connections");
(url, pool)
}
/// Приватный стенд сервисных проверок чтения Resource: изолированная PG-схема V16,
/// приватный artifact root и **готовый** `ResourcesService`.
///
/// Драйвер, миграция и сборка store/service живут в composition root, а не в сервисном
/// тест-модуле (TL run105 F3; FINAL-DISPOSITION run99:47).
pub(crate) struct ResourceServiceHarness {
pub service: ResourcesService,
pub registry: PostgresRegistry,
/// Приватный root содержимого: по нему наблюдаются физические отказы чтения.
pub root: PathBuf,
}
impl ResourceServiceHarness {
pub(crate) async fn spawn(name: &str, limit: usize) -> Self {
let (database_url, pool) = resource_schema(&format!("story36_integrity_{name}")).await;
crank_registry::MigrationAuthority::apply(&pool)
.await
.expect("V16 must be applicable");
drop(pool);
let registry = PostgresRegistry::connect(&database_url)
.await
.expect("fixture registry must connect");
let root = super::private_storage_root(&format!("integrity_{name}"));
let store = ArtifactStore::open(&root).expect("private artifact store must open");
let limits = ResourceLimits::uniform(limit)
.expect("the configured test limit must stay inside the storage ceiling");
Self {
service: ResourcesService::new(registry.clone(), Arc::new(store), limits),
registry,
root,
}
}
}
// ---------------------------------------------------------------------------
// SQL/файловые наблюдения состояния (только composition root)
// ---------------------------------------------------------------------------
/// Итоги строк V16 `(resources, resource_versions, artifact_sources, artifact_blobs)` —
/// наблюдение «отказ без побочных эффектов» (SQL только в composition root).
pub(crate) async fn resource_row_counts(pool: &sqlx::PgPool) -> (i64, i64, i64, i64) {
sqlx::query_as(
"select (select count(*) from resources), (select count(*) from resource_versions),
(select count(*) from artifact_sources), (select count(*) from artifact_blobs)",
)
.fetch_one(pool)
.await
.expect("V16 relations must be countable")
}
/// Физические файлы содержимого под приватным artifact root.
pub(crate) fn artifact_files(root: &std::path::Path) -> Vec<PathBuf> {
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
let entries = std::fs::read_dir(&dir).expect("the private artifact root must be readable");
for entry in entries {
let entry = entry.expect("an artifact entry must be readable");
let path = entry.path();
if path.is_dir() {
pending.push(path);
} else {
files.push(path);
}
}
}
files.sort();
files
}
+41 -3
View File
@@ -195,6 +195,22 @@ pub struct ToolSearchPreviewPayload {
pub tool_selection_policy: ToolSelectionPolicy,
}
/// Точная Published Resource Version в Config-форме `POST .../bindings`
/// (Story 3.7 AC04): положительный exact integer, не `latest`.
#[derive(Clone, Debug, Deserialize)]
pub struct AgentResourceBindingPayload {
pub resource_id: String,
pub resource_version: u32,
}
/// Точная Published Prompt Version в Config-форме `POST .../bindings`
/// (Story 3.13 AC2): положительный exact integer, не `latest`.
#[derive(Clone, Debug, Deserialize)]
pub struct AgentPromptBindingPayload {
pub prompt_id: String,
pub prompt_version: u32,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum AgentCatalogPayload {
@@ -202,17 +218,39 @@ pub enum AgentCatalogPayload {
Config {
bindings: Vec<AgentBindingPayload>,
tool_selection_policy: ToolSelectionPolicy,
/// Отсутствие поля сохраняет прежние Resource bindings, `[]` очищает,
/// список заменяет их в Draft (TL interface decision 1).
#[serde(default)]
resource_bindings: Option<Vec<AgentResourceBindingPayload>>,
/// Tri-state exact Prompt bindings (Story 3.13): absent сохраняет,
/// `[]` очищает, список заменяет.
#[serde(default)]
prompt_bindings: Option<Vec<AgentPromptBindingPayload>>,
},
}
type AgentCatalogParts = (
Vec<AgentBindingPayload>,
Option<ToolSelectionPolicy>,
Option<Vec<AgentResourceBindingPayload>>,
Option<Vec<AgentPromptBindingPayload>>,
);
impl AgentCatalogPayload {
pub fn into_parts(self) -> (Vec<AgentBindingPayload>, Option<ToolSelectionPolicy>) {
pub fn into_parts(self) -> AgentCatalogParts {
match self {
Self::Bindings(bindings) => (bindings, None),
Self::Bindings(bindings) => (bindings, None, None, None),
Self::Config {
bindings,
tool_selection_policy,
} => (bindings, Some(tool_selection_policy)),
resource_bindings,
prompt_bindings,
} => (
bindings,
Some(tool_selection_policy),
resource_bindings,
prompt_bindings,
),
}
}
}
+92 -1
View File
@@ -62,6 +62,11 @@ pub enum ApiError {
context: Option<Value>,
},
#[error("{message}")]
ServiceUnavailable {
message: String,
context: Option<Value>,
},
#[error("{message}")]
Internal {
message: String,
context: Option<Value>,
@@ -202,6 +207,16 @@ impl ApiError {
}
}
pub(crate) fn service_unavailable_with_context(
message: impl Into<String>,
context: Value,
) -> Self {
Self::ServiceUnavailable {
message: message.into(),
context: Some(context),
}
}
pub(crate) fn validation_with_context(message: impl Into<String>, context: Value) -> Self {
Self::Validation {
message: message.into(),
@@ -261,6 +276,7 @@ impl ApiError {
Self::PayloadTooLarge { .. } => StatusCode::PAYLOAD_TOO_LARGE,
Self::PreconditionRequired { .. } => StatusCode::PRECONDITION_REQUIRED,
Self::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
Self::ServiceUnavailable { .. } => StatusCode::SERVICE_UNAVAILABLE,
Self::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
@@ -283,6 +299,7 @@ impl ApiError {
Self::PayloadTooLarge { .. } => "payload_too_large",
Self::PreconditionRequired { .. } => "precondition_required",
Self::RateLimited { .. } => "rate_limited",
Self::ServiceUnavailable { .. } => "service_unavailable",
Self::Internal { .. } => "internal_error",
}
}
@@ -306,7 +323,8 @@ impl IntoResponse for ApiError {
| Self::Conflict { .. }
| Self::PayloadTooLarge { .. }
| Self::PreconditionRequired { .. }
| Self::RateLimited { .. } => {
| Self::RateLimited { .. }
| Self::ServiceUnavailable { .. } => {
warn!(
name: "admin.response.rejected",
error_code = self.code(),
@@ -350,6 +368,7 @@ impl ApiError {
| Self::PayloadTooLarge { context, .. }
| Self::PreconditionRequired { context, .. }
| Self::RateLimited { context, .. }
| Self::ServiceUnavailable { context, .. }
| Self::Internal { context, .. } => context.as_ref(),
}
}
@@ -359,6 +378,15 @@ impl ApiError {
}
}
/// Стабильные коды/поля Resource (D-14) живут в `error/resource.rs`: `error.rs`
/// держим в пределах лимита размера файла.
mod prompt;
mod resource;
pub(crate) use prompt::{
dependency_finding, representation_unsupported, template_finding, unavailable, unused,
};
impl From<RegistryError> for ApiError {
fn from(value: RegistryError) -> Self {
match value {
@@ -467,6 +495,21 @@ impl From<RegistryError> for ApiError {
format!("operation {operation_id} is archived"),
json!({ "operation_id": operation_id, "error_code": "operation_archived" }),
),
RegistryError::ResourceArchived { resource_id } => Self::conflict_with_context(
format!("resource {resource_id} is archived"),
json!({
"resource_id": resource_id,
"error_code": "resource_archived",
"recovery": "reload"
}),
),
RegistryError::ResourceRevoked { resource_id } => Self::conflict_with_context(
format!("resource {resource_id} is revoked"),
json!({
"resource_id": resource_id,
"error_code": "resource_revoked"
}),
),
RegistryError::OperationStaleVersion {
operation_id,
expected,
@@ -798,6 +841,54 @@ impl From<RegistryError> for ApiError {
"repreview_required": true
}),
),
RegistryError::PromptNotFound { prompt_id } => Self::not_found_with_context(
format!("prompt {prompt_id} was not found"),
json!({ "prompt_id": prompt_id, "error_code": "prompt_not_found" }),
),
RegistryError::PromptNotDraft { prompt_id } => Self::conflict_with_context(
"only a Draft prompt can be edited",
json!({ "prompt_id": prompt_id, "error_code": "prompt_not_draft", "recovery": "reload" }),
),
RegistryError::PromptStaleRevision { prompt_id } => Self::conflict_with_context(
"prompt changed since it was loaded",
json!({ "prompt_id": prompt_id, "error_code": "prompt_stale_revision", "recovery": "reload" }),
),
RegistryError::PromptArchived { prompt_id } => Self::conflict_with_context(
"archived prompt cannot receive new Agent bindings",
json!({ "prompt_id": prompt_id, "error_code": "prompt_archived", "recovery": "reload" }),
),
RegistryError::PromptPublicationNotFound { prompt_id } => Self::not_found_with_context(
format!("published prompt version for {prompt_id} was not found"),
json!({ "prompt_id": prompt_id, "error_code": "prompt_publication_not_found" }),
),
RegistryError::PromptPublicationConflict { prompt_id } => Self::conflict_with_context(
"prompt version is already published",
json!({ "prompt_id": prompt_id, "error_code": "prompt_publication_conflict", "recovery": "reload" }),
),
RegistryError::PromptVersionOverflow { .. } | RegistryError::PromptCorrupt { .. } => {
Self::internal("registry operation failed")
}
RegistryError::PromptDependencyUnresolved {
position,
resource_id,
version,
..
} => prompt::unresolved(resource_id, version, position),
RegistryError::PromptDependencyRepresentationUnsupported {
position,
resource_id,
version,
..
} => prompt::representation_unsupported(resource_id, version, position),
RegistryError::PromptDependencyUnused {
position,
resource_id,
version,
..
} => prompt::unused(resource_id, version, position),
RegistryError::PromptDependencyUnavailable { position, .. } => {
prompt::unavailable(position)
}
RegistryError::SourceNotFound { .. } => Self::not_found_with_context(
"artifact source was not found",
json!({
+78
View File
@@ -0,0 +1,78 @@
//! Stable error surface of Story 3.16 (FR-18): pinned Prompt dependencies.
//!
//! Every refusal names only the code, the exact `source_path` of the definition array and the
//! pinned identity (`resource_id`, `version`) — never content, name or workspace.
use serde_json::json;
use super::ApiError;
const UNRESOLVED: &str = "prompt_dependency_unresolved";
const UNSUPPORTED: &str = "prompt_dependency_representation_unsupported";
const UNUSED: &str = "prompt_dependency_unused";
const UNAVAILABLE: &str = "prompt_dependency_unavailable";
pub(crate) fn unresolved(resource_id: String, version: u32, position: usize) -> ApiError {
ApiError::conflict_with_context(
"a pinned prompt dependency cannot be resolved",
json!({
"error_code": UNRESOLVED,
"source_path": source_path(position),
"resource_id": resource_id,
"version": version,
}),
)
}
pub(crate) fn representation_unsupported(
resource_id: String,
version: u32,
position: usize,
) -> ApiError {
ApiError::validation_with_context(
"a pinned prompt dependency has no message representation",
json!({
"error_code": UNSUPPORTED,
"source_path": source_path(position),
"resource_id": resource_id,
"version": version,
}),
)
}
pub(crate) fn unused(resource_id: String, version: u32, position: usize) -> ApiError {
ApiError::validation_with_context(
"a pinned prompt dependency is not referenced by any message",
json!({
"error_code": UNUSED,
"source_path": source_path(position),
"resource_id": resource_id,
"version": version,
}),
)
}
pub(crate) fn unavailable(position: usize) -> ApiError {
ApiError::service_unavailable_with_context(
"a pinned prompt dependency is unavailable",
json!({ "error_code": UNAVAILABLE, "source_path": source_path(position) }),
)
}
/// Exact definition path of one pinned dependency (`dependencies[i]`).
pub(crate) fn source_path(position: usize) -> String {
format!("dependencies[{position}]")
}
/// Template-level finding of the bounded scan (contract §5): the matched text is never carried.
pub(crate) fn template_finding(code: &'static str, source_path: String) -> ApiError {
ApiError::validation_with_context(
"the prompt template text is refused by the bounded scan",
json!({ "error_code": code, "source_path": source_path }),
)
}
/// Read-time finding inside dynamic dependency content (contract §5).
pub(crate) fn dependency_finding(code: &'static str, position: usize) -> ApiError {
template_finding(code, source_path(position))
}
+165
View File
@@ -0,0 +1,165 @@
//! Отображение ошибок Resource в HTTP-ответ admin-api (D-14).
//!
//! Домен отдаёт только стабильные `code`/`field`; HTTP-статус и конверт
//! собираются здесь, поэтому `error.rs` не разрастается и остаётся в пределах
//! лимита размера файла.
use super::ApiError;
use crank_core::resource::ResourceError;
use serde_json::{Value, json};
/// Стабильные коды/поля Resource (D-14): `context.error_code` наблюдаем как
/// `error.code`, `context.field` — как `error.context.field`. Сообщения
/// фиксированные и никогда не содержат bytes содержимого или текст хранилища.
impl From<ResourceError> for ApiError {
fn from(value: ResourceError) -> Self {
let code = value.code();
let mut context = json!({ "error_code": code });
if let Some(field) = value.field() {
context["field"] = Value::String(field.to_owned());
}
if value == ResourceError::Stale {
context["recovery"] = Value::String("reload".to_owned());
}
// Story 3.10: блокирующие findings уходят в существующее поле конверта
// `error.context.findings[]` (`code` + `field`), без текста определения.
if let ResourceError::SourceBlocked { findings } = &value {
context["findings"] = json!(findings);
}
let message = resource_error_message(&value);
match value {
ResourceError::ContentEmpty
| ResourceError::ContentInvalidUtf8
| ResourceError::ContentInvalidJson
| ResourceError::ArtifactIntegrity
| ResourceError::SecretFindings => Self::Unprocessable {
message,
context: Some(context),
},
ResourceError::SourceNotPublished | ResourceError::SourceBlocked { .. } => {
Self::Unprocessable {
message,
context: Some(context),
}
}
ResourceError::ContentTooLarge => Self::PayloadTooLarge {
message,
context: Some(context),
},
ResourceError::UriDuplicate | ResourceError::NameDuplicate => Self::Conflict {
message,
context: Some(context),
},
// Story 3.10: definition-only Resource не переносим (export/content).
ResourceError::SourceNotPortable => Self::Conflict {
message,
context: Some(context),
},
ResourceError::SourceNotFound => Self::NotFound {
message,
context: Some(context),
},
ResourceError::Stale => Self::PreconditionRequired {
message,
context: Some(context),
},
ResourceError::NotFound => Self::NotFound {
message,
context: Some(context),
},
// Story 3.8: отозванный Resource — обычный конфликт с устойчивым кодом;
// сообщение и контекст не раскрывают content/URI/digest.
ResourceError::Revoked => Self::Conflict {
message,
context: Some(context),
},
ResourceError::StorageUnavailable | ResourceError::InvalidLimits => Self::Internal {
message: "internal server error".to_owned(),
context: Some(context),
},
// Lifecycle-отказ — обычный клиентский конфликт, а не внутренняя ошибка:
// код остаётся существующим (`resource_lifecycle_invalid`), сообщение
// фиксированное и не раскрывает from/to.
ResourceError::InvalidLifecycleTransition { .. } => Self::Conflict {
message,
context: Some(context),
},
ResourceError::MimeSyntaxInvalid
| ResourceError::MimeNotAllowed
| ResourceError::KindMismatch
| ResourceError::UriInvalid
| ResourceError::NameInvalid
| ResourceError::DescriptionInvalid
| ResourceError::PortabilityEnvelopeInvalid
| ResourceError::SourceInvalid { .. }
| ResourceError::FieldImmutable { .. } => Self::Validation {
message,
context: Some(context),
},
// D-20 B/E: значение поля вне набора — форма запроса. Отказ выводится как
// generic `validation_error` без Resource-специфичного кода и без поля.
ResourceError::UnknownMetadataValue { .. } => Self::Validation {
message,
context: None,
},
}
}
}
fn resource_error_message(error: &ResourceError) -> String {
match error {
ResourceError::ContentEmpty => "resource content must not be empty".to_owned(),
ResourceError::PortabilityEnvelopeInvalid => {
"resource portability envelope is invalid".to_owned()
}
ResourceError::ContentTooLarge => {
"resource content exceeds the configured limit".to_owned()
}
ResourceError::ContentInvalidUtf8 => "resource content is not valid UTF-8".to_owned(),
ResourceError::ContentInvalidJson => "resource content is not valid JSON".to_owned(),
ResourceError::MimeSyntaxInvalid => "resource mime type syntax is invalid".to_owned(),
ResourceError::MimeNotAllowed => {
"resource mime type is not allowed for this kind".to_owned()
}
ResourceError::KindMismatch => {
"resource mime type is incompatible with the declared kind".to_owned()
}
ResourceError::UriInvalid => "resource uri is invalid".to_owned(),
ResourceError::NameInvalid => "resource name is invalid".to_owned(),
ResourceError::DescriptionInvalid => "resource description is invalid".to_owned(),
ResourceError::UnknownMetadataValue { field } => {
format!("resource metadata field `{field}` has an unknown value")
}
ResourceError::UriDuplicate => "resource uri already exists in this workspace".to_owned(),
ResourceError::NameDuplicate => "resource name already exists in this workspace".to_owned(),
ResourceError::FieldImmutable { field } => {
format!("resource field {field} is immutable")
}
ResourceError::Stale => "resource changed since it was read".to_owned(),
ResourceError::NotFound => "resource was not found in this workspace".to_owned(),
ResourceError::Revoked => "resource has been revoked".to_owned(),
ResourceError::ArtifactIntegrity => {
"resource artifact integrity verification failed".to_owned()
}
ResourceError::SecretFindings => {
"resource content contains secret material or an access-bypassing reference".to_owned()
}
ResourceError::StorageUnavailable | ResourceError::InvalidLimits => {
"internal server error".to_owned()
}
ResourceError::InvalidLifecycleTransition { .. } => {
"resource lifecycle transition is not allowed".to_owned()
}
ResourceError::SourceInvalid { .. } => "resource source definition is invalid".to_owned(),
ResourceError::SourceNotFound => {
"resource source operation was not found in this workspace".to_owned()
}
ResourceError::SourceNotPublished => {
"resource source operation version is not published".to_owned()
}
ResourceError::SourceBlocked { .. } => {
"resource source definition has blocking findings".to_owned()
}
ResourceError::SourceNotPortable => "resource source definition is not portable".to_owned(),
}
}
+5
View File
@@ -35,8 +35,13 @@ pub async fn apply_request_context(mut request: Request, next: Next) -> Response
.get::<MatchedPath>()
.map_or("unmatched", MatchedPath::as_str)
.to_owned();
// Explicit root: a contextual span would inherit whatever OTel context happens to be
// current on this worker thread, and a telemetry-suppressed ambient context makes the
// span non-recording, so the request trace is silently dropped before the exporter.
// The inbound `traceparent` parent is installed right below on the span builder.
let span = info_span!(
target: "crank::trace",
parent: None,
"http.request",
request_id = %request_id,
trace_id = tracing::field::Empty,
+2
View File
@@ -7,6 +7,8 @@ pub mod imports;
pub mod observability;
pub mod onboarding;
pub mod operations;
pub mod prompts;
pub mod resources;
pub mod secrets;
pub mod upstreams;
pub mod workspaces;
+214
View File
@@ -0,0 +1,214 @@
use axum::{
Extension, Json,
extract::{Path, Query, State, rejection::JsonRejection},
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use crank_core::{WorkspaceId, ids::PromptId};
use serde::Deserialize;
use serde_json::Value;
use crate::{error::ApiError, request_context::RequestContext, state::AppState};
#[derive(Deserialize)]
pub struct WorkspacePath {
workspace_id: String,
}
#[derive(Deserialize)]
pub struct PromptPath {
workspace_id: String,
prompt_id: String,
}
#[derive(Deserialize)]
pub struct PromptVersionPath {
workspace_id: String,
prompt_id: String,
version: u32,
}
#[derive(Deserialize)]
pub struct PromptQuery {
version: Option<u32>,
}
pub async fn list_prompt_drafts(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.list_prompt_drafts(&WorkspaceId::new(path.workspace_id))
.await?,
))
}
pub async fn create_prompt_draft(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<(StatusCode, Json<Value>), ApiError> {
let prompt = state
.service
.create_prompt_draft(&WorkspaceId::new(path.workspace_id), body)
.await?;
Ok((StatusCode::CREATED, Json(prompt)))
}
pub async fn get_prompt_draft(
Path(path): Path<PromptPath>,
Query(query): Query<PromptQuery>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.get_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
query.version,
)
.await?,
))
}
pub async fn prompt_action(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.prompt_action(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
)
.await?,
))
}
pub async fn update_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.update_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
)
.await?,
))
}
pub async fn preview_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.preview_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
&request_context.correlation,
)
.await?,
))
}
/// Story 3.15: экспорт текущего Draft. Ответ всегда JSON + `attachment` + `nosniff`,
/// поэтому переносимый definition никогда не рендерится как документ браузера.
pub async fn export_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let (envelope, filename) = state
.service
.export_prompt_draft_envelope(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
)
.await?;
portable_response(&envelope, &filename)
}
/// Story 3.15: экспорт точной Published Version (immutable snapshot этой ревизии).
pub async fn export_prompt_version(
Path(path): Path<PromptVersionPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let (envelope, filename) = state
.service
.export_published_prompt_envelope(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
path.version,
)
.await?;
portable_response(&envelope, &filename)
}
/// Story 3.15: импорт envelope как **нового** Draft текущего владельца (201 + item view).
///
/// Target workspace берётся только из URL, владелец — только из session; envelope не
/// может задать ни ownership, ни lifecycle, ни идентичность Prompt.
pub async fn import_prompt(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Result<Response, ApiError> {
let envelope = body.map_err(import_body_error)?;
let imported = state
.service
.import_prompt_envelope(&WorkspaceId::new(path.workspace_id), envelope.0)
.await?;
Ok((StatusCode::CREATED, Json(imported)).into_response())
}
fn portable_response(envelope: &Value, filename: &str) -> Result<Response, ApiError> {
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
headers.insert(
header::HeaderName::from_static("x-content-type-options"),
HeaderValue::from_static("nosniff"),
);
// Filename выведен из `name` (ASCII alnum/-/_) с фиксированным суффиксом: CR/LF и
// traversal структурно невозможны.
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
.map_err(|_| ApiError::internal("invalid prompt portability export filename"))?,
);
let body = serde_json::to_vec(envelope)
.map_err(|_| ApiError::internal("invalid prompt portability envelope"))?;
Ok((headers, body).into_response())
}
/// Отказ разбора тела импорта: не JSON — 400 стабильный `prompt_portability_envelope_invalid`,
/// а не generic framework rejection.
fn import_body_error(rejection: JsonRejection) -> ApiError {
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
ApiError::PayloadTooLarge {
message: "prompt portability import body is too large".to_owned(),
context: Some(serde_json::json!({
"error_code": "prompt_portability_envelope_invalid"
})),
}
} else {
ApiError::validation_with_context(
"prompt portability envelope is invalid",
serde_json::json!({ "error_code": "prompt_portability_envelope_invalid" }),
)
}
}
+704
View File
@@ -0,0 +1,704 @@
//! Admin API Story 3.6: typed static Resource Drafts (D-16).
//!
//! Один режим просмотра (D-6): `GET .../preview` отдаёт metadata + findings +
//! инертный `text` только для text/JSON; `GET .../content` отдаёт bytes **всегда**
//! как `application/octet-stream` + `attachment` + CSP `sandbox`, поэтому
//! заявленный MIME никогда не становится HTTP content type.
//!
//! Порядок проверок D-20 обеспечивается разбором частей multipart и порядком
//! вызовов сервиса: метаданные (E) и разрешение Resource (C) обрабатываются до
//! содержимого (G) — содержимое только буферизуется, но не оценивается.
use axum::{
Extension, Json,
extract::{Multipart, Path, State, multipart::MultipartRejection, rejection::JsonRejection},
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use crank_core::resource::ResourceKind;
use crank_registry::model::resource::RevokeResourceRequest;
use serde::Deserialize;
use serde_json::{Map, Value, json};
use crate::{
auth::AuthenticatedSession,
error::ApiError,
request_context::RequestContext,
service::resources::{
ArchiveResource, DraftMetadata, ImmutableField, NewDraft, PublishResource, UpdateDraft,
portability,
template::{NewTemplateDraft, TemplateIdentity, UpdateTemplateDraft},
},
state::AppState,
};
/// Тело ответа Draft нельзя превысить: часть содержимого — bounded bytes.
#[derive(Deserialize)]
pub struct ResourceWorkspacePath {
pub workspace_id: String,
}
#[derive(Deserialize)]
pub struct ResourcePath {
pub workspace_id: String,
pub resource_id: String,
}
#[derive(Deserialize)]
pub struct ResourceVersionPath {
pub workspace_id: String,
pub resource_id: String,
pub version: u32,
}
pub async fn create_resource(
Path(path): Path<ResourceWorkspacePath>,
State(state): State<AppState>,
multipart: Result<Multipart, MultipartRejection>,
) -> Result<Response, ApiError> {
let (metadata, content) = read_draft_multipart(multipart).await?;
// Story 3.10: `metadata.source` ⇒ template Draft без части `content`.
if metadata.contains_key("source") {
let source = content_absent(metadata.get("source"), content)?;
let created = state
.service
.resources()
.create_template_draft(NewTemplateDraft {
workspace_id: path.workspace_id.as_str().into(),
metadata: create_metadata(&metadata)?,
source,
})
.await?;
let card = state
.service
.resources()
.card(&path.workspace_id.as_str().into(), &created.resource_id)
.await?;
return Ok((StatusCode::CREATED, Json(json!(card))).into_response());
}
let metadata = create_metadata(&metadata)?;
let bytes = content.ok_or_else(malformed_multipart)?;
let created = state
.service
.resources()
.create_draft(NewDraft {
workspace_id: path.workspace_id.as_str().into(),
metadata,
bytes,
})
.await?;
let card = state
.service
.resources()
.card(&path.workspace_id.as_str().into(), &created.resource_id)
.await?;
Ok((StatusCode::CREATED, Json(json!(card))).into_response())
}
pub async fn list_resources(
Path(path): Path<ResourceWorkspacePath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
let listed = state
.service
.resources()
.list(&path.workspace_id.as_str().into())
.await?;
Ok(Json(json!(listed)))
}
pub async fn get_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
let card = state
.service
.resources()
.card(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
)
.await?;
Ok(Json(json!(card)))
}
pub async fn update_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
multipart: Result<Multipart, MultipartRejection>,
) -> Result<Json<Value>, ApiError> {
let (metadata, content) = read_draft_multipart(multipart).await?;
// Story 3.10: template Draft редактируется определением, без части `content`.
if metadata.contains_key("source") {
let source = content_absent(metadata.get("source"), content)?;
let update =
update_template_draft(&path.workspace_id, &path.resource_id, &metadata, source)?;
let card = state
.service
.resources()
.update_template_draft(update)
.await?;
return Ok(Json(json!(card)));
}
if state
.service
.resources()
.is_template_draft(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
)
.await?
{
// Сохранённый template Draft без нового определения: не превращаем его в static.
return Err(crank_core::resource::ResourceError::SourceInvalid { field: "source" }.into());
}
let bytes = content.ok_or_else(malformed_multipart)?;
let update = update_draft(&path.workspace_id, &path.resource_id, &metadata, bytes)?;
let card = state.service.resources().update_draft(update).await?;
Ok(Json(json!(card)))
}
pub async fn test_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
let result = state
.service
.test_resource_read(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
body,
&request_context.correlation,
)
.await?;
Ok(Json(result))
}
pub async fn preview_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
let preview = state
.service
.resources()
.preview(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
)
.await?;
Ok(Json(json!(preview)))
}
/// Публикация проверенного Draft в immutable Published Version (Story 3.7).
///
/// Тело — `{ "expected_updated_at": "<точное значение карточки>" }`. Отсутствие и
/// `null` означают «precondition не задан» и дают 428 `resource_stale` (как PUT);
/// значение другого JSON-типа — отказ формы запроса (400).
pub async fn publish_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
let expected_updated_at = lifecycle_precondition(&body)?;
let published = state
.service
.resources()
.publish(PublishResource {
workspace_id: path.workspace_id.as_str().into(),
resource_id: path.resource_id.as_str().into(),
expected_updated_at,
})
.await?;
Ok(Json(json!(published)))
}
/// Архив проверенного Resource (Story 3.7 AC05/AC06).
///
/// Тело — `{ "expected_updated_at": "<точное значение карточки>" }`; семантика
/// precondition/428 полностью совпадает с publish, а archived-отказ отдаётся
/// существующим domain-кодом `resource_lifecycle_invalid` (409).
pub async fn archive_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
let expected_updated_at = lifecycle_precondition(&body)?;
let archived = state
.service
.resources()
.archive(ArchiveResource {
workspace_id: path.workspace_id.as_str().into(),
resource_id: path.resource_id.as_str().into(),
expected_updated_at,
})
.await?;
Ok(Json(json!(archived)))
}
/// Отзыв Resource (Story 3.8, owner decision A): 204 без тела, без payload.
///
/// Actor берётся только из authenticated session, request/trace — из серверного
/// RequestContext; middleware workspace_router уже обеспечивает session/Owner/
/// CSRF/origin/rate guards. Повтор существующего отзыва — снова 204 без нового
/// события. Archive/immutable bytes/административное чтение не меняются.
pub async fn revoke_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
Extension(session): Extension<AuthenticatedSession>,
Extension(request_context): Extension<RequestContext>,
) -> Result<StatusCode, ApiError> {
state
.service
.resources()
.revoke(RevokeResourceRequest {
workspace_id: path.workspace_id.as_str().into(),
resource_id: path.resource_id.as_str().into(),
actor_user_id: session.user.id.as_str().to_owned(),
request_id: request_context.request_id().to_owned(),
trace_id: request_context.trace_id().to_owned(),
revoked_at: time::OffsetDateTime::now_utc(),
})
.await?;
Ok(StatusCode::NO_CONTENT)
}
/// Story 3.9: экспорт текущего Draft как bounded portability envelope.
///
/// Ответ всегда `application/json` + `attachment` + `nosniff`: заявленный MIME
/// Resource остаётся внутри envelope и никогда не становится HTTP content type.
pub async fn export_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let envelope = state
.service
.resources()
.export_draft_envelope(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
)
.await?;
portable_response(&envelope)
}
/// Story 3.9: экспорт точной Published Version (immutable snapshot этой ревизии).
pub async fn export_resource_version(
Path(path): Path<ResourceVersionPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let envelope = state
.service
.resources()
.export_published_envelope(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
path.version,
)
.await?;
portable_response(&envelope)
}
/// Story 3.9: импорт envelope как **нового** Draft текущего владельца (201 + карточка).
///
/// Target workspace берётся только из URL, владелец — только из session; envelope не
/// может задать ни ownership, ни lifecycle. Превышение тела — тот же безопасный JSON-конверт.
pub async fn import_resource(
Path(path): Path<ResourceWorkspacePath>,
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Result<Response, ApiError> {
let envelope = body.map_err(import_body_error)?;
let import = portability::parse_portable_envelope(&envelope.0)?;
let card = state
.service
.resources()
.import_envelope(path.workspace_id.as_str().into(), import)
.await?;
Ok((StatusCode::CREATED, Json(json!(card))).into_response())
}
fn portable_response(envelope: &portability::PortableEnvelope) -> Result<Response, ApiError> {
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
headers.insert(
header::HeaderName::from_static("x-content-type-options"),
HeaderValue::from_static("nosniff"),
);
// Filename выведен из `name` (ASCII alnum/-/_) с фиксированным суффиксом: CR/LF и
// traversal структурно невозможны.
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&format!(
"attachment; filename=\"{}\"",
portability::export_filename(&envelope.resource.name)
))
.map_err(|_| ApiError::internal("invalid portability export filename"))?,
);
let body = serde_json::to_vec(envelope)
.map_err(|_| ApiError::internal("invalid portability envelope"))?;
Ok((headers, body).into_response())
}
/// Отказ разбора тела импорта: реальное превышение размера — 413 с Resource-кодом,
/// остальное — 400 `resource_portability_envelope_invalid`, а не generic framework rejection.
fn import_body_error(rejection: JsonRejection) -> ApiError {
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
ApiError::from(crank_core::resource::ResourceError::ContentTooLarge)
} else {
ApiError::from(crank_core::resource::ResourceError::PortabilityEnvelopeInvalid)
}
}
/// Точная Published Version: девять публичных metadata полей.
pub async fn get_resource_version(
Path(path): Path<ResourceVersionPath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
let version = state
.service
.resources()
.published_version(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
path.version,
)
.await?;
Ok(Json(json!(version)))
}
/// Байты точной Published Version: та же inert-политика, что и у Draft download.
pub async fn download_resource_version(
Path(path): Path<ResourceVersionPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let download = state
.service
.resources()
.read_published_content_for_download(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
path.version,
)
.await?;
Ok(download_response(&download))
}
fn download_response(download: &crate::service::resources::ResourceDownload) -> Response {
let filename = crate::service::resources::derived_filename(&download.name, &download.mime_type);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox"),
);
// `filename` выведен из `name` и заявленного MIME: raw upload filename не
// сохраняется вообще, поэтому CR/LF и traversal структурно невозможны (D-12).
match HeaderValue::from_str(&format!(
"attachment; filename=\"{filename}\"; filename*=UTF-8''{filename}"
)) {
Ok(value) => {
headers.insert(header::CONTENT_DISPOSITION, value);
(headers, download.bytes.clone()).into_response()
}
Err(_) => ApiError::internal("invalid resource download filename").into_response(),
}
}
fn lifecycle_precondition(body: &Value) -> Result<Option<String>, ApiError> {
let object = body
.as_object()
.ok_or_else(|| ApiError::validation("resource lifecycle body must be a JSON object"))?;
match object.get("expected_updated_at") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(ApiError::validation(
"resource field `expected_updated_at` must be a JSON string",
)),
}
}
pub async fn download_resource(
Path(path): Path<ResourcePath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let download = state
.service
.resources()
.read_content_for_download(
&path.workspace_id.as_str().into(),
&path.resource_id.as_str().into(),
)
.await?;
let filename = crate::service::resources::derived_filename(&download.name, &download.mime_type);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox"),
);
// `filename` выведен из `name` и заявленного MIME: raw upload filename не
// сохраняется вообще, поэтому CR/LF и traversal структурно невозможны (D-12).
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&format!(
"attachment; filename=\"{filename}\"; filename*=UTF-8''{filename}"
))
.map_err(|_| ApiError::internal("invalid resource download filename"))?,
);
Ok((headers, download.bytes).into_response())
}
/// Разбор multipart: часть `metadata` (JSON-объект) + часть `content` (сырые bytes).
///
/// Содержимое **не** оценивается здесь: превышение предела фиксируется лимитом
/// фреймворка, а стабильные коды (метаданные → precondition → содержимое)
/// назначает сервис в порядке D-20. Оборванное тело внутри окна лимита — отказ
/// формы запроса (400), а не «превышение размера»: иначе клиент получал бы
/// неверный код за запрос, который просто не дочитан (P2).
async fn read_draft_multipart(
multipart: Result<Multipart, MultipartRejection>,
) -> Result<(Map<String, Value>, Option<Vec<u8>>), ApiError> {
let mut multipart = multipart.map_err(multipart_rejection)?;
let mut metadata: Option<Map<String, Value>> = None;
let mut content: Option<Vec<u8>> = None;
while let Some(field) = multipart.next_field().await.map_err(multipart_error)? {
match field.name() {
Some("metadata") => {
if metadata.is_some() {
return Err(malformed_multipart());
}
let bytes = field.bytes().await.map_err(multipart_error)?;
let value: Value = serde_json::from_slice(&bytes)
.map_err(|_| ApiError::validation("invalid resource metadata"))?;
metadata = Some(value.as_object().cloned().ok_or_else(|| {
ApiError::validation("resource metadata must be a JSON object")
})?);
}
Some("content") => {
if content.is_some() {
return Err(malformed_multipart());
}
let bytes = field.bytes().await.map_err(multipart_error)?;
content = Some(bytes.to_vec());
}
_ => return Err(malformed_multipart()),
}
}
let metadata = metadata.ok_or_else(malformed_multipart)?;
// Story 3.10: часть `content` необязательна только для template Draft; обязательность
// для static Resource проверяет вызывающий маршрут.
Ok((metadata, content))
}
/// `metadata.source` присутствует ⇒ часть `content` обязана отсутствовать.
fn content_absent(source: Option<&Value>, content: Option<Vec<u8>>) -> Result<Value, ApiError> {
if content.is_some() {
return Err(crank_core::resource::ResourceError::SourceInvalid { field: "content" }.into());
}
source.cloned().ok_or_else(|| {
crank_core::resource::ResourceError::SourceInvalid { field: "source" }.into()
})
}
/// Обновление template Draft: `source` адресует pinned `input_schema`, а
/// identity-поля (`uri`/`name`/`kind`) принимаются только без изменения значения.
fn update_template_draft(
workspace_id: &str,
resource_id: &str,
metadata: &Map<String, Value>,
source: Value,
) -> Result<UpdateTemplateDraft, ApiError> {
Ok(UpdateTemplateDraft {
workspace_id: workspace_id.into(),
resource_id: resource_id.into(),
description: default_text(metadata, "description")?,
mime_type: required_text(metadata, "mime_type")?,
sensitivity: required_text(metadata, "sensitivity")?,
expected_updated_at: optional_timestamp(metadata, "expected_updated_at")?,
identity: template_identity(metadata)?,
source: Some(source),
})
}
fn template_identity(metadata: &Map<String, Value>) -> Result<TemplateIdentity, ApiError> {
let kind = optional_text(metadata, "kind")?;
if kind
.as_deref()
.is_some_and(|value| ResourceKind::parse(value).is_none())
{
return Err(unknown_enum("kind"));
}
Ok(TemplateIdentity {
uri: optional_text(metadata, "uri")?,
name: optional_text(metadata, "name")?,
kind,
})
}
fn optional_text(metadata: &Map<String, Value>, key: &str) -> Result<Option<String>, ApiError> {
match metadata.get(key) {
None => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(wrong_json_type(key)),
}
}
/// Метаданные создания: шаг B (форма запроса) + шаг E (поля) в порядке D-20.
///
/// Здесь проверяется только то, что относится к форме запроса (шаг B): неизвестный
/// `kind` и типы полей. Поля метаданных и значение `sensitivity` проверяются сервисом
/// на их собственном шаге E в порядке `uri → name → description → kind → mime_type →
/// sensitivity`, поэтому неизвестная `sensitivity` не может опередить более раннее поле.
fn create_metadata(metadata: &Map<String, Value>) -> Result<DraftMetadata, ApiError> {
let kind = required_text(metadata, "kind")?;
if ResourceKind::parse(&kind).is_none() {
return Err(unknown_enum("kind"));
}
Ok(DraftMetadata {
uri: required_text(metadata, "uri")?,
name: required_text(metadata, "name")?,
description: default_text(metadata, "description")?,
kind,
mime_type: required_text(metadata, "mime_type")?,
sensitivity: required_text(metadata, "sensitivity")?,
})
}
/// Обновление Draft: `uri`/`name`/`kind` не принимаются как изменяемые значения —
/// их **присутствие** уже нарушение неизменяемости (D-16), включая `null`.
///
/// Здесь проверяется форма запроса (шаг B): типы immutable-ключей и обязательных
/// полей, а неизвестный `kind` — тоже B. Само присутствие immutable-ключа — шаг D,
/// который исполняет сервис. Значение `sensitivity` (шаг E, последнее поле) сервис
/// проверяет уже после разрешения Resource (C) и шага D, поэтому неизвестная
/// `sensitivity` не может ни опередить C/D, ни превратиться во внутреннюю ошибку.
fn update_draft(
workspace_id: &str,
resource_id: &str,
metadata: &Map<String, Value>,
bytes: Vec<u8>,
) -> Result<UpdateDraft, ApiError> {
let description = default_text(metadata, "description")?;
let mime_type = required_text(metadata, "mime_type")?;
let sensitivity = required_text(metadata, "sensitivity")?;
let expected_updated_at = optional_timestamp(metadata, "expected_updated_at")?;
let immutable_fields = immutable_fields(metadata)?;
Ok(UpdateDraft {
workspace_id: workspace_id.into(),
resource_id: resource_id.into(),
description,
mime_type,
sensitivity,
expected_updated_at,
immutable_fields,
bytes,
})
}
/// Присутствие immutable-ключей (D-16) с шагом B для их неверного JSON-типа.
fn immutable_fields(metadata: &Map<String, Value>) -> Result<Vec<ImmutableField>, ApiError> {
let mut fields = Vec::new();
for (key, field) in [
("uri", ImmutableField::Uri),
("name", ImmutableField::Name),
("kind", ImmutableField::Kind),
] {
match metadata.get(key) {
// Ключа нет — валидное обновление изменяемых полей.
None => {}
// Присутствие ключа — уже нарушение неизменяемости, значение не важно.
Some(Value::Null) => fields.push(field),
Some(Value::String(value)) => {
// Неизвестный `kind` — отказ формы запроса (D-20 B), а не шаг D;
// известный `kind` остаётся нарушением неизменяемости (D).
if field == ImmutableField::Kind && ResourceKind::parse(value).is_none() {
return Err(unknown_enum("kind"));
}
fields.push(field);
}
// Значение другого JSON-типа — форма запроса не распознана (D-20 B).
Some(_) => return Err(wrong_json_type(key)),
}
}
Ok(fields)
}
/// Обязательное поле метаданных: отсутствующее или не-строковое — шаг B.
fn required_text(metadata: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
match metadata.get(key) {
Some(Value::String(value)) => Ok(value.clone()),
_ => Err(wrong_json_type(key)),
}
}
/// Необязательное текстовое поле: отсутствие — значение по умолчанию `""`.
fn default_text(metadata: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
match metadata.get(key) {
None => Ok(String::new()),
Some(Value::String(value)) => Ok(value.clone()),
Some(_) => Err(wrong_json_type(key)),
}
}
/// Необязательный precondition: отсутствие и `null` — «не задан» (шаг F даёт 428).
fn optional_timestamp(
metadata: &Map<String, Value>,
key: &str,
) -> Result<Option<String>, ApiError> {
match metadata.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(wrong_json_type(key)),
}
}
fn unknown_enum(key: &str) -> ApiError {
ApiError::validation(format!(
"resource metadata field `{key}` has an unknown value"
))
}
fn wrong_json_type(key: &str) -> ApiError {
ApiError::validation(format!(
"resource metadata field `{key}` must be a JSON string"
))
}
fn malformed_multipart() -> ApiError {
// Шаг B порядка D-20: расхождение формы запроса — generic validation_error
// без Resource-специфичного кода.
ApiError::validation("invalid resource multipart upload")
}
fn content_too_large() -> ApiError {
ApiError::from(crank_core::resource::ResourceError::ContentTooLarge)
}
/// Отказ чтения части multipart: реальное превышение размера остаётся 413,
/// оборванное или нечитаемое тело — клиентская ошибка формы (400).
fn multipart_error(error: axum::extract::multipart::MultipartError) -> ApiError {
if error.status() == StatusCode::PAYLOAD_TOO_LARGE {
content_too_large()
} else {
malformed_multipart()
}
}
fn multipart_rejection(rejection: MultipartRejection) -> ApiError {
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
content_too_large()
} else {
malformed_multipart()
}
}
+40 -3
View File
@@ -42,6 +42,8 @@ mod observability;
mod onboarding;
mod operation_validation;
mod operations;
mod prompts;
pub(crate) mod resources;
mod samples;
mod secrets;
mod upstreams;
@@ -61,6 +63,7 @@ use operation_validation::{
pub struct AdminService {
registry: PostgresRegistry,
artifact_store: Arc<ArtifactStore>,
resources: resources::ResourcesService,
runtime: RuntimeExecutor,
storage: LocalArtifactStorage,
auth_settings: AuthSettings,
@@ -80,6 +83,7 @@ pub struct AdminServiceBuilder {
registry: PostgresRegistry,
storage_root: PathBuf,
artifact_store: Option<Arc<ArtifactStore>>,
resource_limits: crank_core::resource::ResourceLimits,
auth_settings: AuthSettings,
secret_crypto: SecretCrypto,
runtime: RuntimeExecutor,
@@ -205,6 +209,24 @@ impl AdminService {
pub fn capability_profile(&self) -> &Arc<dyn CapabilityProfile> {
&self.capability_profile
}
/// Сервис typed static Resource Drafts (Story 3.6): create/list/get/update/
/// preview/content внутри выделенного модуля.
pub(crate) fn resources(&self) -> &resources::ResourcesService {
&self.resources
}
pub(crate) async fn test_resource_read(
&self,
workspace_id: &WorkspaceId,
resource_id: &crank_core::ids::ResourceId,
body: serde_json::Value,
correlation: &crank_core::CorrelationContext,
) -> Result<serde_json::Value, ApiError> {
self.resources
.execute_template_test(self, workspace_id, resource_id, body, correlation)
.await
}
}
fn runtime_credential_error_code(error: &RuntimeError) -> &'static str {
@@ -248,6 +270,7 @@ impl AdminServiceBuilder {
registry,
storage_root,
artifact_store: None,
resource_limits: crank_core::resource::ResourceLimits::default(),
auth_settings,
secret_crypto,
runtime,
@@ -312,6 +335,13 @@ impl AdminServiceBuilder {
self
}
/// Пределы содержимого Resource (D-3): значение выше storage ceiling отвергается,
/// нового env-ключа не вводится.
pub fn with_resource_limits(mut self, limits: crank_core::resource::ResourceLimits) -> Self {
self.resource_limits = limits;
self
}
pub fn with_public_base_url(mut self, public_base_url: String) -> Self {
self.public_base_url = public_base_url.trim_end_matches('/').to_owned();
self
@@ -339,11 +369,18 @@ impl AdminServiceBuilder {
}
pub fn build(self) -> AdminService {
let artifact_store = self
.artifact_store
.unwrap_or_else(|| Arc::new(ArtifactStore::new(&self.storage_root)));
let resources = resources::ResourcesService::new(
self.registry.clone(),
Arc::clone(&artifact_store),
self.resource_limits,
);
AdminService {
registry: self.registry,
artifact_store: self
.artifact_store
.unwrap_or_else(|| Arc::new(ArtifactStore::new(&self.storage_root))),
artifact_store,
resources,
runtime: self.runtime,
storage: LocalArtifactStorage::new(self.storage_root),
auth_settings: self.auth_settings,
+156 -14
View File
@@ -1,12 +1,14 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use crank_core::ids::{PromptId, ResourceId};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, OperationId, SearchableTool,
ToolAccessMode, ToolSelectionPolicy, UsagePeriod, WorkspaceId, search_tool_catalog,
};
use crank_registry::{
AgentStateExpectation, AgentVersionRecord, CreateAgentRequest, PublishAgentRequest,
SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket, UsageQuery,
AgentResourceBinding, AgentStateExpectation, AgentVersionRecord, CreateAgentRequest,
PublishAgentRequest, SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket,
UsageQuery, model::AgentPromptBinding,
};
use serde_json::json;
use sha2::{Digest, Sha256};
@@ -474,7 +476,8 @@ impl AdminService {
let current_version = self
.get_agent_version(workspace_id, agent_id, agent.current_draft_version)
.await?;
let (payload, requested_policy) = payload.into_parts();
let (payload, requested_policy, requested_resource_bindings, requested_prompt_bindings) =
payload.into_parts();
let bindings = payload
.into_iter()
.map(|binding| AgentOperationBinding {
@@ -486,28 +489,64 @@ impl AdminService {
enabled: binding.enabled,
})
.collect::<Vec<_>>();
// Tri-state additive-поля: отсутствие сохраняет прежние Resource bindings,
// `[]` очищает, список заменяет их в Draft.
let resource_bindings = match requested_resource_bindings {
Some(items) => items
.into_iter()
.map(|binding| AgentResourceBinding {
resource_id: ResourceId::new(binding.resource_id),
resource_version: binding.resource_version,
})
.collect::<Vec<_>>(),
None => current_version.resource_bindings.clone(),
};
validate_resource_binding_shape(&resource_bindings)?;
// Tri-state exact Prompt bindings: отсутствие сохраняет, `[]` очищает,
// список заменяет (Story 3.13 AC2).
let prompt_bindings = match requested_prompt_bindings {
Some(items) => items
.into_iter()
.map(|binding| AgentPromptBinding {
prompt_id: PromptId::new(binding.prompt_id),
prompt_version: binding.prompt_version,
})
.collect::<Vec<_>>(),
None => current_version.prompt_bindings.clone(),
};
validate_prompt_binding_shape(&prompt_bindings)?;
self.validate_exact_published_agent_bindings(workspace_id, &bindings)
.await?;
self.validate_exact_published_resource_bindings(workspace_id, &resource_bindings)
.await?;
self.validate_exact_published_prompt_bindings(workspace_id, &prompt_bindings)
.await?;
let tool_selection_policy = requested_policy
.unwrap_or_else(|| current_version.snapshot.tool_selection_policy.clone());
validate_tool_selection_policy(&tool_selection_policy, &bindings)?;
let saved_version = self
.registry
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
workspace_id,
agent_id,
agent_version: current_version.version,
bindings: &bindings,
tool_selection_policy: &tool_selection_policy,
expected_state,
})
.save_agent_catalog_config_editable_with_prompts(
SaveAgentCatalogConfigRequest {
workspace_id,
agent_id,
agent_version: current_version.version,
bindings: &bindings,
tool_selection_policy: &tool_selection_policy,
resource_bindings: &resource_bindings,
expected_state,
},
&prompt_bindings,
)
.await?;
info!(
name: "admin.agent.bindings_saved",
agent_id = %agent_id.as_str(),
version = saved_version,
binding_count = bindings.len(),
resource_binding_count = resource_bindings.len(),
prompt_binding_count = prompt_bindings.len(),
"agent bindings saved"
);
@@ -531,25 +570,36 @@ impl AdminService {
&agent_version.bindings,
)?;
// Resource-only Agent валиден: публикация требует хотя бы один enabled Tool
// ИЛИ хотя бы один exact Resource binding.
if agent_version
.bindings
.iter()
.filter(|binding| binding.enabled)
.count()
== 0
&& agent_version.resource_bindings.is_empty()
{
return Err(ApiError::conflict_with_context(
"agent cannot be published without published enabled tools",
"agent cannot be published without published enabled tools or Resource bindings",
json!({
"agent_id": agent_id.as_str(),
"version": version,
"binding_count": agent_version.bindings.len()
"binding_count": agent_version.bindings.len(),
"resource_binding_count": agent_version.resource_bindings.len()
}),
));
}
self.validate_exact_published_agent_bindings(workspace_id, &agent_version.bindings)
.await?;
self.validate_exact_published_resource_bindings(
workspace_id,
&agent_version.resource_bindings,
)
.await?;
self.validate_exact_published_prompt_bindings(workspace_id, &agent_version.prompt_bindings)
.await?;
let published_at = OffsetDateTime::now_utc();
@@ -639,6 +689,47 @@ impl AdminService {
Ok(())
}
/// Точная published Resource Version обязана существовать в этом workspace.
/// Чужая/неопубликованная/отсутствующая версии дают один и тот же sanitized 404
/// без раскрытия существования.
async fn validate_exact_published_resource_bindings(
&self,
workspace_id: &WorkspaceId,
bindings: &[AgentResourceBinding],
) -> Result<(), ApiError> {
let unresolved = self
.registry
.unresolved_published_resource_versions(workspace_id, bindings)
.await?;
if unresolved.is_empty() {
return Ok(());
}
Err(ApiError::not_found_with_context(
"published resource version was not found for Agent binding",
json!({ "error_code": "agent_resource_binding_not_found" }),
))
}
/// Exact Published Prompt Version обязана существовать в этом workspace;
/// отсутствующая, чужая и неопубликованная версии неразличимы снаружи.
async fn validate_exact_published_prompt_bindings(
&self,
workspace_id: &WorkspaceId,
bindings: &[AgentPromptBinding],
) -> Result<(), ApiError> {
let unresolved = self
.registry
.unresolved_published_prompt_versions(workspace_id, bindings)
.await?;
if unresolved.is_empty() {
return Ok(());
}
Err(ApiError::not_found_with_context(
"published prompt version was not found for Agent binding",
json!({ "error_code": "agent_prompt_binding_not_found" }),
))
}
#[instrument(skip(self), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str()))]
pub async fn unpublish_agent(
&self,
@@ -690,6 +781,57 @@ impl AdminService {
}
}
fn validate_resource_binding_shape(bindings: &[AgentResourceBinding]) -> Result<(), ApiError> {
let mut seen = BTreeSet::new();
for binding in bindings {
if binding.resource_version == 0 {
return Err(ApiError::validation_with_context(
"resource_version must be a positive exact integer",
json!({
"field": "resource_bindings.resource_version",
"resource_id": binding.resource_id.as_str(),
}),
));
}
if !seen.insert((binding.resource_id.as_str(), binding.resource_version)) {
return Err(ApiError::validation_with_context(
"duplicate exact Resource binding is not allowed",
json!({
"field": "resource_bindings",
"resource_id": binding.resource_id.as_str(),
"resource_version": binding.resource_version,
}),
));
}
}
Ok(())
}
fn validate_prompt_binding_shape(bindings: &[AgentPromptBinding]) -> Result<(), ApiError> {
let mut seen = BTreeSet::new();
for binding in bindings {
if binding.prompt_version == 0 {
return Err(ApiError::validation_with_context(
"prompt_version must be a positive exact integer",
json!({
"field": "prompt_bindings.prompt_version",
"prompt_id": binding.prompt_id.as_str(),
}),
));
}
if !seen.insert(binding.prompt_id.as_str()) {
return Err(ApiError::validation_with_context(
"duplicate exact Prompt binding is not allowed",
json!({
"field": "prompt_bindings",
"prompt_id": binding.prompt_id.as_str(),
}),
));
}
}
Ok(())
}
fn validate_tool_selection_policy(
policy: &ToolSelectionPolicy,
bindings: &[AgentOperationBinding],
+402
View File
@@ -0,0 +1,402 @@
use crank_core::{
WorkspaceId,
ids::{PromptId, ResourceId},
prompt::{PromptDefinition, PromptError, PromptSensitivity, PromptStatus},
prompt_composition::{
self, PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass,
effective_sensitivity, provenance_json,
},
};
use crank_registry::model::{
ArchivePromptRequest, CreatePromptDraftRequest, PromptDraftRecord, PromptPublicationRecord,
PublishPromptRequest, UpdatePromptDraftRequest,
};
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Uuid;
use crate::{error::ApiError, service::AdminService};
pub(crate) mod portability;
const CREDENTIAL_FINDING: &str = "prompt_credential_finding";
const ACCESS_BYPASS_FINDING: &str = "prompt_access_bypass_finding";
const DEPENDENCY_CREDENTIAL_FINDING: &str = "prompt_dependency_credential_finding";
const DEPENDENCY_ACCESS_BYPASS_FINDING: &str = "prompt_dependency_access_bypass_finding";
impl AdminService {
pub(crate) async fn list_prompt_drafts(
&self,
workspace_id: &WorkspaceId,
) -> Result<Value, ApiError> {
let prompts = self.registry.list_prompt_drafts(workspace_id).await?;
Ok(json!({ "items": prompts.into_iter().map(prompt_view).collect::<Vec<_>>() }))
}
pub(crate) async fn get_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
version: Option<u32>,
) -> Result<Value, ApiError> {
match version {
Some(version) => Ok(json!(publication_view(
self.registry
.get_published_prompt_version(workspace_id, prompt_id, version)
.await?
))),
None => Ok(json!(prompt_view(
self.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?
))),
}
}
/// `action: publish|archive` на существующем item route.
pub(crate) async fn prompt_action(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let action = object
.get("action")
.and_then(Value::as_str)
.ok_or_else(invalid_body)?;
if action != "publish" && action != "archive" {
return Err(invalid_body());
}
let expected_updated_at = object
.get("expected_updated_at")
.and_then(Value::as_str)
.ok_or_else(|| {
ApiError::precondition_required_with_context(
"expected_updated_at is required for a prompt lifecycle action",
json!({
"error_code": "prompt_precondition_required",
"recovery": "reload"
}),
)
})?
.parse_timestamp()?;
let now = truncate_to_micros(OffsetDateTime::now_utc());
let record = match action {
"publish" => {
// Шаблон не проходит Resource-публикацию, поэтому bounded scan стоит до
// публикации: непригодный текст не должен стать Published Prompt (AC7).
let draft = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
scan_prompt_template(draft.prompt.definition())?;
self.registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
expected_updated_at,
published_at: now,
})
.await?
}
_ => {
self.registry
.archive_prompt_draft(ArchivePromptRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
expected_updated_at,
archived_at: now,
})
.await?
}
};
Ok(json!(prompt_view(record)))
}
pub(crate) async fn create_prompt_draft(
&self,
workspace_id: &WorkspaceId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let definition = parse_definition_body(&body)?;
let sensitivity = parse_sensitivity(object.get("sensitivity").and_then(Value::as_str))?;
let request = CreatePromptDraftRequest {
workspace_id: workspace_id.clone(),
prompt_id: PromptId::new(format!("prm_{}", Uuid::now_v7().simple())),
sensitivity,
definition,
created_at: truncate_to_micros(OffsetDateTime::now_utc()),
};
Ok(json!(prompt_view(
self.registry.create_prompt_draft(request).await?
)))
}
pub(crate) async fn update_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let expected_updated_at = object
.get("expected_updated_at")
.and_then(Value::as_str)
.ok_or_else(invalid_body)?
.parse_timestamp()?;
let sensitivity = parse_sensitivity(object.get("sensitivity").and_then(Value::as_str))?;
let definition = parse_definition_body(&body)?;
let updated_at = truncate_to_micros(OffsetDateTime::now_utc());
let record = self
.registry
.update_prompt_draft(UpdatePromptDraftRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
sensitivity,
definition,
expected_updated_at,
updated_at,
})
.await?;
Ok(json!(prompt_view(record)))
}
/// Preview одного Draft: рендер шаблона + вставка точных pinned-версий (contract §7).
pub(crate) async fn preview_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
correlation: &crank_core::CorrelationContext,
) -> Result<Value, ApiError> {
let arguments = body
.as_object()
.and_then(|object| object.get("arguments"))
.and_then(Value::as_object)
.cloned()
.ok_or_else(invalid_body)?;
let record = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
let definition = record.prompt.definition();
scan_prompt_template(definition)?;
let contents = self
.prompt_dependency_contents(workspace_id, &record.dependencies, correlation)
.await;
let messages =
prompt_composition::render(definition, &record.dependencies, &arguments, &contents)
.map_err(map_composition_error)?;
Ok(json!({
"status": "draft",
"version": record.prompt.version(),
"effective_sensitivity": effective_sensitivity(
record.prompt.sensitivity(),
&record.dependencies,
),
"messages": messages,
"dependencies": provenance_json(&record.dependencies),
}))
}
/// Content of every pinned dependency by declaration position; `None` = not readable now.
///
/// The pinned version is re-checked at read time (AC6/AC8): a revoked Resource never falls
/// back to stale content, and a static version is read through the single digest-verified
/// artifact path. A dynamic (template) dependency is read by the Story 3.11 runtime contract.
async fn prompt_dependency_contents(
&self,
workspace_id: &WorkspaceId,
pins: &[PromptDependencyPin],
correlation: &crank_core::CorrelationContext,
) -> Vec<Option<Vec<u8>>> {
let mut contents = Vec::with_capacity(pins.len());
for pin in pins {
let resource_id = ResourceId::new(pin.resource_id.clone());
let readable = match self
.registry
.resource_is_revoked(workspace_id, &resource_id)
.await
{
Ok(false) => match pin.source_class {
PromptDependencySourceClass::Static => self
.resources
.load_published_content(workspace_id, &resource_id, pin.version)
.await
.map(|(bytes, _)| bytes)
.ok(),
// Динамическая (template) зависимость читается контрактом Resource 3.11:
// определение не содержит bytes, поэтому исполняется объявленная read
// Operation с параметрами самого шаблона (значения по умолчанию).
PromptDependencySourceClass::Dynamic => {
self.resources
.read_pinned_template_content(
self,
workspace_id,
&resource_id,
pin.version,
correlation,
)
.await
}
},
Ok(true) | Err(_) => None,
};
contents.push(readable);
}
contents
}
}
/// Bounded scan of the Prompt template text: a raw credential or an explicit `include:`
/// directive blocks preview and publication with the exact `messages[i].content` path.
fn scan_prompt_template(definition: &PromptDefinition) -> Result<(), ApiError> {
prompt_composition::scan_template(definition).map_err(map_composition_error)
}
fn map_composition_error(error: PromptCompositionError) -> ApiError {
use crate::error as api_error;
match error {
PromptCompositionError::DependencyUnavailable { position } => {
api_error::unavailable(position)
}
PromptCompositionError::DependencyUnused {
position,
resource_id,
version,
} => api_error::unused(resource_id, version, position),
PromptCompositionError::DependencyRepresentationUnsupported { position } => {
api_error::representation_unsupported(String::new(), 0, position)
}
PromptCompositionError::CredentialFinding { source_path } => {
api_error::template_finding(CREDENTIAL_FINDING, source_path)
}
PromptCompositionError::AccessBypassFinding { source_path } => {
api_error::template_finding(ACCESS_BYPASS_FINDING, source_path)
}
PromptCompositionError::DependencyCredentialFinding { position } => {
api_error::dependency_finding(DEPENDENCY_CREDENTIAL_FINDING, position)
}
PromptCompositionError::DependencyAccessBypassFinding { position } => {
api_error::dependency_finding(DEPENDENCY_ACCESS_BYPASS_FINDING, position)
}
PromptCompositionError::Template(error) => map_prompt_error(error),
}
}
trait ParseTimestamp {
fn parse_timestamp(&self) -> Result<OffsetDateTime, ApiError>;
}
impl ParseTimestamp for str {
fn parse_timestamp(&self) -> Result<OffsetDateTime, ApiError> {
OffsetDateTime::parse(self, &Rfc3339)
.map(truncate_to_micros)
.map_err(|_| invalid_body())
}
}
fn prompt_view(record: PromptDraftRecord) -> Value {
let effective = effective_sensitivity(record.prompt.sensitivity(), &record.dependencies);
// Публикация показывает действующую политику; Draft — локальное редактируемое значение.
let sensitivity = match record.prompt.status() {
PromptStatus::Published => effective,
PromptStatus::Draft | PromptStatus::Archived => record.prompt.sensitivity(),
};
let prompt = record.prompt;
json!({
"prompt_id": prompt.prompt_id().as_str(),
"name": prompt.definition().name(),
"description": prompt.definition().description(),
"version": prompt.version(),
"current_draft_version": prompt.version(),
"latest_published_version": record.latest_published_version,
"status": prompt.status(),
"sensitivity": sensitivity,
"effective_sensitivity": effective,
"updated_at": record.updated_at.format(&Rfc3339).unwrap_or_default(),
"created_at": record.created_at.format(&Rfc3339).unwrap_or_default(),
"definition": prompt.definition().as_json(),
})
}
fn publication_view(record: PromptPublicationRecord) -> Value {
let published_at = record.published_at.format(&Rfc3339).unwrap_or_default();
json!({
"prompt_id": record.prompt_id.as_str(),
"name": record.name,
"description": record.description,
"version": record.version,
"current_draft_version": record.version,
"latest_published_version": record.version,
"status": "published",
"sensitivity": record.sensitivity,
"effective_sensitivity": record.sensitivity,
"updated_at": published_at,
"created_at": published_at,
"definition": record.definition.as_json(),
})
}
fn parse_definition_body(body: &Value) -> Result<PromptDefinition, ApiError> {
let mut value = body.as_object().cloned().ok_or_else(invalid_body)?;
value.remove("sensitivity");
value.remove("expected_updated_at");
PromptDefinition::parse(&Value::Object(value)).map_err(map_prompt_error)
}
fn parse_sensitivity(value: Option<&str>) -> Result<PromptSensitivity, ApiError> {
match value {
Some("public") => Ok(PromptSensitivity::Public),
Some("internal") => Ok(PromptSensitivity::Internal),
Some("secret") => Ok(PromptSensitivity::Secret),
_ => Err(invalid_body()),
}
}
fn map_prompt_error(error: PromptError) -> ApiError {
let (message, field, code) = match error {
PromptError::InvalidDefinition => (
"prompt definition is invalid",
"definition".to_owned(),
"prompt_invalid_definition",
),
PromptError::MissingArgument(name) => (
"required prompt argument is missing",
name,
"prompt_missing_argument",
),
PromptError::UnknownArgument(name) => (
"unknown prompt argument was supplied",
name,
"prompt_unknown_argument",
),
PromptError::InvalidArgument(name) => (
"prompt argument has an invalid value",
name,
"prompt_invalid_argument",
),
PromptError::InvalidTemplate => (
"prompt template cannot be rendered safely",
"messages".to_owned(),
"prompt_invalid_template",
),
};
ApiError::validation_with_context(message, json!({ "field": field, "error_code": code }))
}
fn invalid_body() -> ApiError {
ApiError::validation_with_context(
"prompt request is invalid",
json!({ "error_code": "prompt_invalid_request" }),
)
}
fn truncate_to_micros(value: OffsetDateTime) -> OffsetDateTime {
let nanos = value.nanosecond();
value
.replace_nanosecond(nanos - nanos % 1_000)
.unwrap_or(value)
}
@@ -0,0 +1,203 @@
//! Story 3.15: bounded portability envelope шаблона сообщений (Prompt) — экспорт
//! текущего Draft / точной Published Version и импорт как **нового** Draft
//! текущего владельца.
//!
//! Транспортный контракт (строгий allowlist ключей, формат/версия, `source` как
//! только provenance) живёт здесь, в admin-api; домен `crank-core` не меняется:
//! `arguments`/`messages` передаются **тем же** JSON, который принимает
//! `PromptDefinition::parse`/`as_json`, поэтому роли, типы, `enum`, `required` и
//! `default` переносятся без преобразований. Импорт не восстанавливает
//! идентичность: новый `prompt_id`, `current_draft_version = 1`, `status = draft`,
//! публикации нет. Владелец берётся из authenticated session, target workspace —
//! из URL, никогда из envelope.
use crank_core::{
WorkspaceId,
ids::PromptId,
prompt::{PromptDefinition, PromptSensitivity},
};
use serde_json::{Map, Value, json};
use crate::{error::ApiError, service::AdminService};
/// Единственный поддерживаемый формат переносимого документа.
pub(crate) const ENVELOPE_FORMAT: &str = "crank-prompt-portability";
pub(crate) const ENVELOPE_VERSION: u64 = 1;
const ROOT_KEYS: [&str; 4] = ["format", "version", "prompt", "source"];
const PROMPT_KEYS: [&str; 5] = [
"name",
"description",
"sensitivity",
"arguments",
"messages",
];
const SOURCE_KEYS: [&str; 2] = ["kind", "version"];
impl AdminService {
/// Экспорт текущего Draft: definition и его ревизия читаются одним exact-геттером.
pub(crate) async fn export_prompt_draft_envelope(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
) -> Result<(Value, String), ApiError> {
let record = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
Ok(portable_document(
record.prompt.definition(),
record.prompt.sensitivity(),
"draft",
record.prompt.version(),
))
}
/// Экспорт **точной** Published Version: immutable snapshot этой ревизии.
pub(crate) async fn export_published_prompt_envelope(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
version: u32,
) -> Result<(Value, String), ApiError> {
let record = self
.registry
.get_published_prompt_version(workspace_id, prompt_id, version)
.await?;
Ok(portable_document(
&record.definition,
record.sensitivity,
"published",
record.version,
))
}
/// Импорт envelope: строгая форма → принятый `create_prompt_draft` (новый Draft).
/// Никакого upsert существующего Prompt этот путь не открывает.
pub(crate) async fn import_prompt_envelope(
&self,
workspace_id: &WorkspaceId,
body: Value,
) -> Result<Value, ApiError> {
let body = parse_envelope(&body)?;
// В контексте переноса любой отказ принятого парсера — стабильный
// `prompt_invalid_definition` (типы, лимиты, роли, плейсхолдеры, дубли имён);
// сообщение фиксированное, definition не эхо.
super::parse_definition_body(&body).map_err(|_| invalid_definition())?;
self.create_prompt_draft(workspace_id, body).await
}
}
fn portable_document(
definition: &PromptDefinition,
sensitivity: PromptSensitivity,
kind: &str,
version: u32,
) -> (Value, String) {
let definition = definition.as_json();
let name = definition["name"].as_str().unwrap_or_default();
let envelope = json!({
"format": ENVELOPE_FORMAT,
"version": ENVELOPE_VERSION,
"prompt": {
"name": definition["name"],
"description": definition["description"],
"sensitivity": sensitivity,
"arguments": definition["arguments"],
"messages": definition["messages"],
},
"source": { "kind": kind, "version": version },
});
(envelope, export_filename(name))
}
/// Разбор envelope со **строгим** allowlist: любой неизвестный ключ (в том числе
/// `prompt_id`, `workspace_id`, `owner`, `status`, `path`) — отказ формы.
///
/// Содержимое definition здесь не оценивается: невалидные роли/типы/лимиты/
/// плейсхолдеры отклоняет принятый парсер в `import_prompt_envelope`
/// (стабильный код `prompt_invalid_definition`).
fn parse_envelope(body: &Value) -> Result<Value, ApiError> {
let root = block(body, &ROOT_KEYS)?;
if root["format"].as_str() != Some(ENVELOPE_FORMAT) {
return Err(envelope_invalid());
}
if root["version"].as_u64() != Some(ENVELOPE_VERSION) {
return Err(envelope_invalid());
}
let prompt = block(&root["prompt"], &PROMPT_KEYS)?;
let name = text(prompt, "name")?;
let description = text(prompt, "description")?;
let sensitivity = match prompt["sensitivity"].as_str() {
Some("public") => json!("public"),
Some("internal") => json!("internal"),
Some("secret") => json!("secret"),
_ => return Err(envelope_invalid()),
};
let source = block(&root["source"], &SOURCE_KEYS)?;
match source["kind"].as_str() {
Some("draft") | Some("published") => {}
_ => return Err(envelope_invalid()),
}
// `source.version` — только provenance: проверяется по форме (целое ≥ 1) и
// ничего не восстанавливает.
source["version"]
.as_u64()
.filter(|value| (1..=u32::MAX as u64).contains(value))
.ok_or_else(envelope_invalid)?;
Ok(json!({
"name": name,
"description": description,
"sensitivity": sensitivity,
"arguments": prompt["arguments"],
"messages": prompt["messages"],
}))
}
/// `<sanitized name>.crank-prompt.json` — только ASCII, без CR/LF и traversal.
pub(crate) fn export_filename(name: &str) -> String {
let stem: String = name
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
.take(64)
.collect();
let stem = if stem.is_empty() {
"prompt"
} else {
stem.as_str()
};
format!("{stem}.crank-prompt.json")
}
/// Ровно объявленный набор ключей: объект, ни одного лишнего, ни одного недостающего.
fn block<'a>(value: &'a Value, keys: &[&str]) -> Result<&'a Map<String, Value>, ApiError> {
let object = value.as_object().ok_or_else(envelope_invalid)?;
if object.len() != keys.len() || object.keys().any(|key| !keys.contains(&key.as_str())) {
return Err(envelope_invalid());
}
Ok(object)
}
fn text(object: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
object[key]
.as_str()
.map(str::to_owned)
.ok_or_else(envelope_invalid)
}
fn envelope_invalid() -> ApiError {
ApiError::validation_with_context(
"prompt portability envelope is invalid",
json!({ "error_code": "prompt_portability_envelope_invalid" }),
)
}
fn invalid_definition() -> ApiError {
ApiError::validation_with_context(
"prompt definition is invalid",
json!({ "field": "definition", "error_code": "prompt_invalid_definition" }),
)
}
+884
View File
@@ -0,0 +1,884 @@
//! Story 3.6: сервис typed static Resource Drafts.
//!
//! Здесь живёт продуктовый pipeline D-20 в фиксированном порядке:
//! B (разбор multipart/метаданных) → C (разрешение Resource) → D (неизменяемость)
//! → E (поля метаданных, MIME) → F (precondition) → G (содержимое) → H/I (запись
//! bytes и транзакция реестра). Метаданные побеждают содержимое, разрешение
//! Resource побеждает содержимое — именно в этом порядке проверки вызываются.
//!
//! Точки наблюдения счётчиков (D-19) стоят вплотную к реальным вызовам:
//! `counters::note_artifact_put()` перед `ArtifactStore::put_registered` и
//! `counters::note_artifact_read()` перед физическим чтением байт в
//! `load_content`. В production-сборке кода счётчиков нет.
use std::sync::Arc;
use crate::error::ApiError;
use crank_artifacts::{ArtifactError, ArtifactStore};
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::{
ResourceError, ResourceKind, ResourceLimits, ResourceMetadata, ResourceSensitivity,
ResourceStatus,
};
use crank_registry::PostgresRegistry;
use crank_registry::model::resource::{
ArchiveResourceRequest, CreateResourceDraftRequest, PublishResourceVersionRequest,
ResourceDraftRecord, ResourcePublicationRecord, ResourceVersionRecord,
UpdateResourceDraftRequest,
};
use serde::Serialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
const MAX_PAGE_SIZE: u32 = 100;
const DEFAULT_DOWNLOAD_FILENAME: &str = "resource";
/// Inline-счётчики реальных точек (D-19): отдельного production-модуля и
/// публичного probe нет — весь код под `#[cfg(test)]`.
#[cfg(test)]
pub(crate) mod counters {
use std::sync::atomic::{AtomicU64, Ordering};
static ARTIFACT_PUTS: AtomicU64 = AtomicU64::new(0);
static ARTIFACT_READS: AtomicU64 = AtomicU64::new(0);
pub(crate) fn note_artifact_put() {
ARTIFACT_PUTS.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn note_artifact_read() {
ARTIFACT_READS.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn artifact_puts() -> u64 {
ARTIFACT_PUTS.load(Ordering::SeqCst)
}
pub(crate) fn artifact_reads() -> u64 {
ARTIFACT_READS.load(Ordering::SeqCst)
}
pub(crate) fn reset() {
ARTIFACT_PUTS.store(0, Ordering::SeqCst);
ARTIFACT_READS.store(0, Ordering::SeqCst);
}
}
/// BUILD-only детерминированный шов (P3, TL F05): ровно одна точка между
/// разрешением версии и физическим чтением байт в `load_content`.
///
/// Тест ставит сюда controlled concurrent update того же Resource и получает
/// детерминированное чередование без гонки. Ровно один вызов на установленный
/// шаг; в production-сборке модуля и вызова нет.
#[cfg(test)]
pub(crate) mod interleave {
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
type Hook = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;
static HOOK: Mutex<Option<Hook>> = Mutex::new(None);
static AFTER_RESOLVE: Mutex<Option<Hook>> = Mutex::new(None);
/// Устанавливает шаг, который будет исполнен один раз на следующей точке.
pub(crate) fn install(hook: Hook) {
*HOOK.lock().expect("interleave hook lock must not poison") = Some(hook);
}
/// Исполняет установленный шаг (если он есть) и снимает его.
pub(crate) async fn fire() {
let hook = HOOK
.lock()
.expect("interleave hook lock must not poison")
.take();
if let Some(hook) = hook {
hook().await;
}
}
/// Второй BUILD-only шов (F6, TL run109): точка **после** разрешения версии и
/// **до** физического чтения байт. Нужен, чтобы наблюдать окно, которое первый
/// шов (`fire`, до разрешения) поймать не может: одновременное обновление,
/// случившееся уже после pinned-разрешения, не должно менять ответ.
pub(crate) fn install_after_resolve(hook: Hook) {
*AFTER_RESOLVE
.lock()
.expect("interleave hook lock must not poison") = Some(hook);
}
/// Исполняет установленный после-разрешения шаг (если он есть) и снимает его.
pub(crate) async fn fire_after_resolve() {
let hook = AFTER_RESOLVE
.lock()
.expect("interleave hook lock must not poison")
.take();
if let Some(hook) = hook {
hook().await;
}
}
}
/// Метаданные Draft в форме multipart-части (D-16).
#[derive(Clone, Debug)]
pub(crate) struct DraftMetadata {
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub sensitivity: String,
}
/// Новый Draft вместе с его bytes.
#[derive(Clone, Debug)]
pub(crate) struct NewDraft {
pub workspace_id: WorkspaceId,
pub metadata: DraftMetadata,
pub bytes: Vec<u8>,
}
/// Результат создания Draft.
#[derive(Clone, Debug)]
pub(crate) struct CreatedDraft {
pub resource_id: ResourceId,
}
/// Идентификатор неизменяемого поля Draft (D-16). Присутствие ключа в запросе
/// обновления — уже нарушение, независимо от его значения (включая `null`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ImmutableField {
Uri,
Name,
Kind,
}
impl ImmutableField {
fn wire_name(self) -> &'static str {
match self {
Self::Uri => "uri",
Self::Name => "name",
Self::Kind => "kind",
}
}
}
/// Обновление существующего Draft. `uri`/`name`/`kind` в payload не принимаются:
/// переданное значение — уже нарушение (D-16).
#[derive(Clone, Debug)]
pub(crate) struct UpdateDraft {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub description: String,
pub mime_type: String,
pub sensitivity: String,
pub expected_updated_at: Option<String>,
pub immutable_fields: Vec<ImmutableField>,
pub bytes: Vec<u8>,
}
/// Публикация текущего Draft (Story 3.7). Precondition — точное `updated_at` карточки,
/// как у существующего PUT; отсутствие/расхождение — `resource_stale`.
#[derive(Clone, Debug)]
pub(crate) struct PublishResource {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub expected_updated_at: Option<String>,
}
/// Архив Resource (Story 3.7 AC05/AC06). Тот же precondition, что у publish/PUT;
/// archived-переход не удаляет artifacts/publications и не меняет Agent snapshots.
#[derive(Clone, Debug)]
pub(crate) struct ArchiveResource {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub expected_updated_at: Option<String>,
}
/// Сервис Resource Drafts: реестр + content-addressed store + пределы содержимого.
#[derive(Clone)]
pub(crate) struct ResourcesService {
registry: PostgresRegistry,
store: Arc<ArtifactStore>,
limits: ResourceLimits,
}
impl ResourcesService {
pub(crate) fn new(
registry: PostgresRegistry,
store: Arc<ArtifactStore>,
limits: ResourceLimits,
) -> Self {
Self {
registry,
store,
limits,
}
}
/// Создание Draft: E (метаданные) → G (содержимое) → put bytes → одна транзакция.
pub(crate) async fn create_draft(
&self,
draft: NewDraft,
) -> Result<CreatedDraft, ResourceError> {
let metadata = parse_metadata(&draft.metadata)?;
let bytes = ResourceMetadata::validate_content(
metadata.kind,
&metadata.mime_type,
&draft.bytes,
&self.limits,
)?;
let resource_id = generate_resource_id();
let now = truncate_to_micros(OffsetDateTime::now_utc());
let artifact = self.put_registered(&bytes).await?;
let record = self
.registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: draft.workspace_id,
resource_id: resource_id.clone(),
uri: metadata.uri,
name: metadata.name,
description: metadata.description,
kind: metadata.kind.as_str().to_owned(),
mime_type: metadata.mime_type,
sensitivity: metadata.sensitivity.as_str().to_owned(),
artifact,
created_at: now,
})
.await?;
Ok(CreatedDraft {
resource_id: record.resource.resource_id,
})
}
/// Обновление Draft в порядке C → D → E → F → G → H/I.
pub(crate) async fn update_draft(
&self,
update: UpdateDraft,
) -> Result<ResourceCardResponse, ResourceError> {
// C: разрешение Resource до любой работы с содержимым.
let current = self
.registry
.get_resource_draft(update.workspace_id.as_str(), &update.resource_id)
.await?;
// D: uri/name/kind неизменяемы — присутствие любого из них уже нарушение.
if let Some(field) = update.immutable_fields.first() {
return Err(ResourceError::FieldImmutable {
field: field.wire_name(),
});
}
// E: только изменяемые поля метаданных.
let current_kind = parse_kind(&current.resource.kind)?;
if !ResourceMetadata::description_is_valid(&update.description) {
return Err(ResourceError::DescriptionInvalid);
}
if !ResourceMetadata::mime_syntax_is_valid(&update.mime_type) {
return Err(ResourceError::MimeSyntaxInvalid);
}
match ResourceKind::for_mime(&update.mime_type) {
None => return Err(ResourceError::MimeNotAllowed),
Some(owner) if owner != current_kind => {
return Err(ResourceError::KindMismatch);
}
Some(_) => {}
}
let sensitivity = parse_sensitivity(&update.sensitivity)?;
// F: precondition решается до любой работы с содержимым (D-20 F→G→H).
// Сравнение идёт с только что прочитанным `updated_at` этого Resource;
// авторитетный CAS под блокировкой строки остаётся в реестре и ловит
// настоящую гонку между двумя одновременными запросами.
let expected_updated_at = update
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
// Актуальный CAS на уже архивном Resource — lifecycle-отказ (409), не 500:
// Archived -> Draft недопустим, карточка больше не редактируется.
if current.resource.status == ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: ResourceStatus::Draft,
});
}
// G: содержимое.
let bytes = ResourceMetadata::validate_content(
current_kind,
&update.mime_type,
&update.bytes,
&self.limits,
)?;
let artifact = self.put_registered(&bytes).await?;
self.registry
.update_resource_draft(UpdateResourceDraftRequest {
workspace_id: update.workspace_id.clone(),
resource_id: update.resource_id.clone(),
description: update.description,
mime_type: update.mime_type,
sensitivity: sensitivity.as_str().to_owned(),
expected_updated_at,
artifact,
})
.await?;
self.card(&update.workspace_id, &update.resource_id).await
}
/// Публикация проверенного Draft в immutable Published Version (AT-3.7-02/03).
///
/// Порядок: C (разрешение Resource) → F (точный precondition) → E (повторная проверка
/// сохранённых metadata) → G (bounded bytes, digest/integrity, secret-policy) →
/// CAS-транзакция реестра со сверкой version/digest/size под row-lock.
pub(crate) async fn publish(
&self,
request: PublishResource,
) -> Result<PublishedVersionResponse, ResourceError> {
let current = self
.registry
.get_resource_draft(request.workspace_id.as_str(), &request.resource_id)
.await?;
// Story 3.10: template Draft публикуется по definition-контракту, без bytes.
if current.version.source_kind == "template" {
return self.publish_template(request, current).await;
}
// F: precondition решается до любой работы с содержимым (как в существующем PUT).
let expected_updated_at = request
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
// Актуальный CAS на уже архивном Resource — lifecycle-отказ (409): публикация
// архивной карточки недопустима, immutable history при этом не меняется.
if current.resource.status == ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: ResourceStatus::Published,
});
}
// E: сохранённые metadata проверяются заново (defense-in-depth) до чтения bytes:
// повреждённая/устаревшая грамматика обязана дать стабильный 400, а не integrity-отказ.
let kind = parse_kind(&current.resource.kind)?;
let metadata = ResourceMetadata {
uri: current.resource.uri.clone(),
name: current.resource.name.clone(),
description: current.resource.description.clone(),
kind,
mime_type: current.version.mime_type.clone(),
sensitivity: parse_sensitivity(&current.version.sensitivity)?,
};
metadata.validate()?;
let limit = self.limits.effective_limit(kind);
if usize::try_from(current.version.size_bytes)
.map(|size| size > limit)
.unwrap_or(true)
{
return Err(ResourceError::ContentTooLarge);
}
// Один снимок metadata/bytes: resolved-версия служит источником bytes и
// подтверждения digest для publish-транзакции (TOCTOU закрывается CAS/сверкой).
let (bytes, resolved) = self
.load_content(&request.workspace_id, &request.resource_id)
.await?;
let snapshot = &resolved.snapshot;
// G: повторная проверка семантики сохранённых bytes.
ResourceMetadata::validate_content(kind, &metadata.mime_type, &bytes, &self.limits)?;
self.validate_publication_policy(&request.workspace_id, &metadata, &bytes)
.await?;
let artifact = self.put_registered(&bytes).await?;
let published_at = truncate_to_micros(OffsetDateTime::now_utc());
let publication = self
.registry
.publish_resource_version(PublishResourceVersionRequest {
workspace_id: request.workspace_id.clone(),
resource_id: request.resource_id.clone(),
expected_updated_at,
expected_version: snapshot.version.version,
expected_digest: snapshot.version.digest.clone(),
expected_size_bytes: snapshot.version.size_bytes,
artifact,
published_at,
})
.await?;
let card = self
.card(&request.workspace_id, &request.resource_id)
.await?;
Ok(PublishedVersionResponse {
resource: card,
published_version: PublishedVersionView::from_record(&publication),
})
}
/// Архив Resource: C (разрешение) → F (точный precondition) → транзакция архива.
///
/// Archived-отказ с актуальным CAS — существующий domain-код
/// `resource_lifecycle_invalid` (409). Artifacts/publications/Agent snapshots не
/// затрагиваются: меняются только lifecycle и ревизия карточки.
pub(crate) async fn archive(
&self,
request: ArchiveResource,
) -> Result<ResourceCardResponse, ResourceError> {
let current = self
.registry
.get_resource_draft(request.workspace_id.as_str(), &request.resource_id)
.await?;
let expected_updated_at = request
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
// Старый CAS обязан дать stale даже для уже архивного Resource: порядок
// «precondition → lifecycle» сохраняет принятую 428-семантику повторов.
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
self.registry
.archive_resource(ArchiveResourceRequest {
workspace_id: request.workspace_id.clone(),
resource_id: request.resource_id.clone(),
expected_updated_at,
archived_at: truncate_to_micros(OffsetDateTime::now_utc()),
})
.await?;
self.card(&request.workspace_id, &request.resource_id).await
}
/// Точная Published Version: metadata снимка, без owning-ссылки/raw filename.
pub(crate) async fn published_version(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<PublishedVersionView, ResourceError> {
match self
.registry
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
.await
{
Ok(resolved) => Ok(PublishedVersionView::from_record(&resolved.publication)),
// Story 3.10: definition-only версия живёт без artifact-ссылки.
Err(ResourceError::NotFound) => {
self.published_template_view(workspace_id, resource_id, version)
.await
}
Err(error) => Err(error),
}
}
/// Байты точной Published Version для inert download (политику заголовков задаёт роут).
pub(crate) async fn read_published_content_for_download(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<ResourceDownload, ResourceError> {
// Story 3.10: определение шаблона не является содержимым и не скачивается.
if self
.publication_is_template(workspace_id, resource_id, version)
.await?
{
return Err(ResourceError::SourceNotPortable);
}
let (bytes, publication) = self
.load_published_content(workspace_id, resource_id, version)
.await?;
Ok(ResourceDownload {
bytes,
mime_type: publication.mime_type,
name: publication.name,
})
}
/// Единственная точка чтения bytes точной Published Version: один pinned-снимок
/// публикации, физическое чтение через store и проверка digest/size.
///
/// Story 3.9 использует тот же путь для экспорта точной версии, поэтому второго
/// обращения к `ArtifactStore` не появляется.
pub(crate) async fn load_published_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<
(
Vec<u8>,
crank_registry::model::resource::ResourcePublicationRecord,
),
ResourceError,
> {
let resolved = self
.registry
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
.await?;
let publication = resolved.publication;
let artifact_ref = resolved.artifact_ref;
let store = Arc::clone(&self.store);
#[cfg(test)]
counters::note_artifact_read();
let bytes = tokio::task::spawn_blocking(move || store.read(&artifact_ref))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)?;
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != publication.size_bytes
|| sha256_hex(&bytes) != publication.digest
{
return Err(ResourceError::ArtifactIntegrity);
}
Ok((bytes, publication))
}
/// Secret-policy публикации: структурные raw secrets и explicit `include:` директивы.
/// Все отказы одинаково generic; текст/цель никогда не раскрываются.
async fn validate_publication_policy(
&self,
workspace_id: &WorkspaceId,
metadata: &ResourceMetadata,
bytes: &[u8],
) -> Result<(), ResourceError> {
if self
.publication_findings(workspace_id, metadata, bytes)
.await?
.is_empty()
{
Ok(())
} else {
Err(ResourceError::SecretFindings)
}
}
/// Publication-policy findings на тех же pinned bytes, что и публикация: единый
/// scanner/validator для preview (AC01) и publish, только стабильный domain-код
/// `resource_secret_findings`; совпавший текст и цель ссылки не раскрываются.
async fn publication_findings(
&self,
workspace_id: &WorkspaceId,
metadata: &ResourceMetadata,
bytes: &[u8],
) -> Result<Vec<ResourceError>, ResourceError> {
if crank_core::resource::publication_secret_findings(bytes).is_some() {
return Ok(vec![ResourceError::SecretFindings]);
}
for target in crank_core::resource::publication_include_directives(bytes) {
// Ссылка разрешается только внутри этого workspace и только по уже
// опубликованной metadata; неразрешённая/чужая/невалидная цель — тот же отказ.
if !ResourceMetadata::uri_is_valid(&target) {
return Ok(vec![ResourceError::SecretFindings]);
}
let Some(published) = self
.registry
.published_resource_sensitivity_by_uri(workspace_id.as_str(), &target)
.await?
else {
return Ok(vec![ResourceError::SecretFindings]);
};
let referenced = parse_sensitivity(&published)?;
if sensitivity_rank(referenced) > sensitivity_rank(metadata.sensitivity) {
return Ok(vec![ResourceError::SecretFindings]);
}
}
Ok(Vec::new())
}
/// Карточка Draft.
pub(crate) async fn card(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<ResourceCardResponse, ResourceError> {
let record = self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await?;
let mut card = ResourceCardResponse::from_record(&record);
// Story 3.10: template-карточка несёт source view и blocker findings
// сохранённого определения; static wire не меняется (source отсутствует).
if record.version.source_kind == "template" {
let (source, findings) = self
.template_card(workspace_id, resource_id, record.version.version)
.await?;
card.source = Some(source);
card.findings = findings;
}
Ok(card)
}
pub(crate) async fn list(
&self,
workspace_id: &WorkspaceId,
) -> Result<ResourceListResponse, ResourceError> {
let records = self
.registry
.list_resource_drafts(workspace_id.as_str(), MAX_PAGE_SIZE)
.await?;
Ok(ResourceListResponse {
items: records
.iter()
.map(ResourceCardResponse::from_record)
.collect(),
})
}
/// Байты текущей версии: единственная физическая точка чтения (D-19).
///
/// Вход для in-crate проверок чтения (counter/integrity): production отдаёт
/// bytes через `read_content_for_download`, и оба идут через один `load_content`,
/// поэтому второго пути чтения не появляется. В production-сборке метода нет.
#[cfg(test)]
pub(crate) async fn read_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<Vec<u8>, ResourceError> {
let (bytes, _) = self.load_content(workspace_id, resource_id).await?;
Ok(bytes)
}
/// Байты текущей версии для ответа-скачивания (политику заголовков задаёт маршрут).
///
/// MIME и имя Resource берутся из того же pinned-разрешения, что и bytes:
/// отдельного чтения card-строки здесь нет (P3).
pub(crate) async fn read_content_for_download(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<ResourceDownload, ResourceError> {
// Story 3.10: у template Draft нет файла содержимого.
let record = self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await?;
if record.version.source_kind == "template" {
return Err(ResourceError::SourceNotPortable);
}
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
Ok(ResourceDownload {
bytes,
mime_type: resolved.snapshot.version.mime_type,
name: resolved.snapshot.resource.name,
})
}
async fn load_content(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<
(
Vec<u8>,
crank_registry::model::resource::ResolvedResourceVersion,
),
ResourceError,
> {
// C + metadata-сверки: чужой/несуществующий Resource и рассинхронизация
// metadata отсекаются до чтения байт.
//
// BUILD-only тестовая точка чередования (P3): единственное место, где
// одновременное обновление того же Resource попадает между источником
// metadata и физическим чтением bytes. Дальше версия разрешается **один**
// раз и обслуживает весь ответ, поэтому metadata версии N и bytes версии
// N+1 в одном ответе невозможны.
#[cfg(test)]
interleave::fire().await;
let resolved = self
.registry
.resolve_current_resource_version(workspace_id.as_str(), resource_id)
.await?;
// F6 (TL run109): второй шов стоит **после** pinned-разрешения: он позволяет
// наблюдать, что позднее обновление того же Resource не подменяет ни metadata,
// ни bytes уже разрешённого ответа.
#[cfg(test)]
interleave::fire_after_resolve().await;
let artifact_ref = resolved.artifact_ref.clone();
let store = Arc::clone(&self.store);
#[cfg(test)]
counters::note_artifact_read();
let bytes = tokio::task::spawn_blocking(move || store.read(&artifact_ref))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)?;
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != resolved.snapshot.version.size_bytes {
return Err(ResourceError::ArtifactIntegrity);
}
if sha256_hex(&bytes) != resolved.snapshot.version.digest {
return Err(ResourceError::ArtifactIntegrity);
}
Ok((bytes, resolved))
}
async fn put_registered(
&self,
bytes: &[u8],
) -> Result<crank_artifacts::RegisteredArtifact, ResourceError> {
let store = Arc::clone(&self.store);
let owned = bytes.to_vec();
#[cfg(test)]
counters::note_artifact_put();
// Точка регистрации durable содержимого; bounded bytes уже провалидированы.
tokio::task::spawn_blocking(move || store.put_registered(&owned))
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.map_err(map_artifact_error)
}
}
/// Ответ скачивания: bytes, заявленный MIME и имя Resource (для derived filename).
pub(crate) struct ResourceDownload {
pub bytes: Vec<u8>,
pub mime_type: String,
pub name: String,
}
/// Имя файла выводится из `name` и заявленного MIME; raw upload filename не
/// сохраняется вообще (D-12), поэтому header injection и traversal невозможны.
pub(crate) fn derived_filename(name: &str, mime_type: &str) -> String {
let extension = match mime_type {
"application/json" => "json",
"text/plain" => "txt",
"text/markdown" => "md",
"text/csv" => "csv",
"application/pdf" => "pdf",
"image/png" => "png",
"image/jpeg" => "jpg",
"image/gif" => "gif",
"image/webp" => "webp",
"image/svg+xml" => "svg",
"text/html" => "html",
_ => "bin",
};
let stem: String = name
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
.take(64)
.collect();
let stem = if stem.is_empty() {
DEFAULT_DOWNLOAD_FILENAME
} else {
stem.as_str()
};
format!("{stem}.{extension}")
}
fn parse_metadata(metadata: &DraftMetadata) -> Result<ResourceMetadata, ResourceError> {
// Неизвестный `kind` не достижим через HTTP: маршрут отвергает его как generic
// `validation_error` (D-20 шаг B) до вызова сервиса. Здесь он маппится в ближайший
// существующий код, чтобы не расширять wire-контракт.
let kind = ResourceKind::parse(&metadata.kind).ok_or(ResourceError::KindMismatch)?;
let mut parsed = ResourceMetadata {
uri: metadata.uri.clone(),
name: metadata.name.clone(),
description: metadata.description.clone(),
kind,
mime_type: metadata.mime_type.clone(),
// Заполняется последним шагом E (см. ниже) и до этого не наблюдается.
sensitivity: ResourceSensitivity::Internal,
};
// D-20 шаг E: поля проверяются в порядке uri → name → description → kind → mime_type,
// и только затем значение `sensitivity`: её неизвестное значение — форма запроса
// (generic 400), поэтому оно не может опережать более ранние поля.
parsed.validate()?;
parsed.sensitivity = parse_sensitivity(&metadata.sensitivity)?;
Ok(parsed)
}
fn parse_sensitivity(value: &str) -> Result<ResourceSensitivity, ResourceError> {
ResourceSensitivity::parse(value).ok_or(ResourceError::UnknownMetadataValue {
field: "sensitivity",
})
}
/// Порядок строгости sensitivity для проверки `include:` (понижение запрещено).
fn sensitivity_rank(value: ResourceSensitivity) -> u8 {
match value {
ResourceSensitivity::Public => 0,
ResourceSensitivity::Internal => 1,
ResourceSensitivity::Secret => 2,
}
}
fn parse_kind(value: &str) -> Result<ResourceKind, ResourceError> {
ResourceKind::parse(value).ok_or(ResourceError::ArtifactIntegrity)
}
fn parse_timestamp(value: &str) -> Result<OffsetDateTime, ResourceError> {
OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339)
.map(truncate_to_micros)
.map_err(|_| ResourceError::Stale)
}
/// Микросекундная точность: Postgres `timestamptz` и RFC3339 round-trip
/// optimistic-precondition не должны расходиться из-за наносекунд.
fn truncate_to_micros(value: OffsetDateTime) -> OffsetDateTime {
let nanos = value.nanosecond();
value
.replace_nanosecond(nanos - nanos % 1_000)
.unwrap_or(value)
}
fn format_timestamp(value: OffsetDateTime) -> String {
value
.format(&time::format_description::well_known::Rfc3339)
.unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_owned())
}
fn generate_resource_id() -> ResourceId {
ResourceId::new(format!("res_{}", uuid::Uuid::now_v7().simple()))
}
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn map_artifact_error(error: ArtifactError) -> ResourceError {
match error {
ArtifactError::NotFound | ArtifactError::Integrity => ResourceError::ArtifactIntegrity,
ArtifactError::EmptySource | ArtifactError::SourceTooLarge => {
ResourceError::ArtifactIntegrity
}
_ => ResourceError::StorageUnavailable,
}
}
#[cfg(test)]
#[path = "resources/tests.rs"]
mod tests;
#[path = "resources/preview.rs"]
mod preview;
#[path = "resources/revocation.rs"]
mod revocation;
#[path = "resources/portability.rs"]
pub(crate) mod portability;
#[path = "resources/template.rs"]
pub(crate) mod template;
#[path = "resources/test_read.rs"]
mod test_read;
#[path = "resources/views.rs"]
mod views;
pub(crate) use views::*;
@@ -0,0 +1,297 @@
//! Story 3.9: bounded portability envelope — экспорт текущего Draft / точной
//! Published Version и импорт как **нового** Draft текущего владельца.
//!
//! Транспортный контракт (allowlist ключей, base64, digest) живёт здесь, в admin-api:
//! домен (`crank-core`) отвечает только за стабильный код отказа
//! `resource_portability_envelope_invalid`. Импорт не восстанавливает идентичность:
//! `source` — только provenance, новый Resource всегда получает новый `resource_id`,
//! `current_draft_version = 1` и не публикуется. Владелец и target workspace берутся
//! из authenticated session и URL, никогда из envelope.
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::{ResourceError, ResourceKind};
use serde::Serialize;
use serde_json::{Map, Value};
use super::{DraftMetadata, NewDraft, ResourcesService};
/// Единственный поддерживаемый формат переносимого документа.
pub(crate) const ENVELOPE_FORMAT: &str = "crank-resource-portability";
pub(crate) const ENVELOPE_VERSION: u64 = 1;
/// Предел тела импорта: base64-накладные расходы (`MAX_ARTIFACT_BYTES / 3 * 4`) плюс
/// 64 KiB на metadata оболочки. Равен 415 060 байт; лимит содержимого не меняется.
pub(crate) const MAX_IMPORT_BODY_BYTES: usize =
crank_artifacts::MAX_ARTIFACT_BYTES / 3 * 4 + 64 * 1024;
const ROOT_KEYS: [&str; 5] = ["format", "version", "resource", "source", "content"];
const RESOURCE_KEYS: [&str; 6] = [
"uri",
"name",
"description",
"kind",
"mime_type",
"sensitivity",
];
const SOURCE_KEYS: [&str; 2] = ["kind", "version"];
const CONTENT_KEYS: [&str; 3] = ["size_bytes", "digest", "base64"];
/// Переносимый документ в wire-форме (экспорт и разобранный импорт).
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PortableEnvelope {
pub format: &'static str,
pub version: u64,
pub resource: PortableResourceBlock,
pub source: PortableSourceBlock,
pub content: PortableContentBlock,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PortableResourceBlock {
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub sensitivity: String,
}
/// `source` — только provenance: `draft` с ревизией содержимого либо `published`
/// с номером точной версии. Импорт по нему ничего не восстанавливает.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PortableSourceBlock {
pub kind: String,
pub version: u32,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PortableContentBlock {
pub size_bytes: i64,
pub digest: String,
pub base64: String,
}
/// Разобранный envelope импорта: metadata + уже декодированные bytes.
pub(crate) struct PortableImport {
pub resource: PortableResourceBlock,
pub bytes: Vec<u8>,
pub size_bytes: i64,
pub digest: String,
}
impl ResourcesService {
/// Экспорт текущего содержимого Draft: metadata и bytes берутся из **одного**
/// pinned-разрешения версии, второй путь чтения не открывается.
pub(crate) async fn export_draft_envelope(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<PortableEnvelope, ResourceError> {
// Story 3.10: definition-only Resource не переносим (нет content envelope).
if self.is_template_draft(workspace_id, resource_id).await? {
return Err(ResourceError::SourceNotPortable);
}
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
let snapshot = resolved.snapshot;
Ok(PortableEnvelope {
format: ENVELOPE_FORMAT,
version: ENVELOPE_VERSION,
resource: PortableResourceBlock {
uri: snapshot.resource.uri,
name: snapshot.resource.name,
description: snapshot.resource.description,
kind: snapshot.resource.kind,
mime_type: snapshot.version.mime_type,
sensitivity: snapshot.version.sensitivity,
},
source: PortableSourceBlock {
kind: "draft".to_owned(),
version: snapshot.version.version,
},
content: content_block(&bytes),
})
}
/// Экспорт **точной** Published Version: immutable snapshot и его bytes из одного
/// разрешения; существующие revoke/read/integrity semantics сохраняются, второго
/// пути чтения `ArtifactStore` не открывается.
pub(crate) async fn export_published_envelope(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<PortableEnvelope, ResourceError> {
// Story 3.10: опубликованное определение шаблона не экспортируется как content.
if self
.publication_is_template(workspace_id, resource_id, version)
.await?
{
return Err(ResourceError::SourceNotPortable);
}
let (bytes, publication) = self
.load_published_content(workspace_id, resource_id, version)
.await?;
Ok(PortableEnvelope {
format: ENVELOPE_FORMAT,
version: ENVELOPE_VERSION,
resource: PortableResourceBlock {
uri: publication.uri,
name: publication.name,
description: publication.description,
kind: publication.kind,
mime_type: publication.mime_type,
sensitivity: publication.sensitivity,
},
source: PortableSourceBlock {
kind: "published".to_owned(),
version: publication.version,
},
content: content_block(&bytes),
})
}
/// Импорт envelope: integrity/bounded-проверки → существующий `create_draft`.
///
/// Никакого upsert/update: при занятых uri/name реестр отвечает существующими
/// `resource_uri_duplicate` / `resource_name_duplicate` (409). Публикации нет.
pub(crate) async fn import_envelope(
&self,
workspace_id: WorkspaceId,
import: PortableImport,
) -> Result<super::ResourceCardResponse, ResourceError> {
let PortableImport {
resource,
bytes,
size_bytes,
digest,
} = import;
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != size_bytes
|| super::sha256_hex(&bytes) != digest
{
return Err(ResourceError::ArtifactIntegrity);
}
let kind = ResourceKind::parse(&resource.kind).ok_or(ResourceError::KindMismatch)?;
if bytes.len() > self.limits.effective_limit(kind) {
return Err(ResourceError::ContentTooLarge);
}
let created = self
.create_draft(NewDraft {
workspace_id: workspace_id.clone(),
metadata: DraftMetadata {
uri: resource.uri,
name: resource.name,
description: resource.description,
kind: resource.kind,
mime_type: resource.mime_type,
sensitivity: resource.sensitivity,
},
bytes,
})
.await?;
self.card(&workspace_id, &created.resource_id).await
}
}
/// Разбор envelope со **строгим** allowlist: любой неизвестный ключ (в том числе
/// `artifact`, `owner`, `workspace_id`, `resource_id`, `status`, `path`) — отказ формы.
pub(crate) fn parse_portable_envelope(value: &Value) -> Result<PortableImport, ResourceError> {
let root = block(value, &ROOT_KEYS)?;
if root["format"].as_str() != Some(ENVELOPE_FORMAT) {
return Err(envelope_invalid());
}
if root["version"].as_u64() != Some(ENVELOPE_VERSION) {
return Err(envelope_invalid());
}
let resource = block(&root["resource"], &RESOURCE_KEYS)?;
let resource = PortableResourceBlock {
uri: text(resource, "uri")?,
name: text(resource, "name")?,
description: text(resource, "description")?,
kind: text(resource, "kind")?,
mime_type: text(resource, "mime_type")?,
sensitivity: text(resource, "sensitivity")?,
};
let source = block(&root["source"], &SOURCE_KEYS)?;
match source["kind"].as_str() {
Some("draft") | Some("published") => {}
_ => return Err(envelope_invalid()),
}
// `source.version` — только provenance: проверяется по форме (целое ≥ 1) и не
// восстанавливает ни ревизию, ни идентичность импортируемого Draft.
source["version"]
.as_u64()
.filter(|value| (1..=u32::MAX as u64).contains(value))
.ok_or_else(envelope_invalid)?;
let content = block(&root["content"], &CONTENT_KEYS)?;
let size_bytes = content["size_bytes"]
.as_i64()
.filter(|value| *value >= 0)
.ok_or_else(envelope_invalid)?;
let digest = text(content, "digest")?;
let digest_is_lowercase_hex = digest.len() == 64
&& digest
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
if !digest_is_lowercase_hex {
return Err(envelope_invalid());
}
let encoded = text(content, "base64")?;
let bytes = BASE64
.decode(encoded.as_bytes())
.map_err(|_| envelope_invalid())?;
Ok(PortableImport {
resource,
bytes,
size_bytes,
digest,
})
}
/// `<sanitized name>.crank-resource.json` — только ASCII, без CR/LF и traversal.
pub(crate) fn export_filename(name: &str) -> String {
let stem: String = name
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
.take(64)
.collect();
let stem = if stem.is_empty() {
"resource"
} else {
stem.as_str()
};
format!("{stem}.crank-resource.json")
}
fn content_block(bytes: &[u8]) -> PortableContentBlock {
PortableContentBlock {
size_bytes: i64::try_from(bytes.len()).unwrap_or(i64::MAX),
digest: super::sha256_hex(bytes),
base64: BASE64.encode(bytes),
}
}
/// Ровно объявленный набор ключей: объект, ни одного лишнего, ни одного недостающего.
fn block<'a>(value: &'a Value, keys: &[&str]) -> Result<&'a Map<String, Value>, ResourceError> {
let object = value.as_object().ok_or_else(envelope_invalid)?;
if object.len() != keys.len() || object.keys().any(|key| !keys.contains(&key.as_str())) {
return Err(envelope_invalid());
}
Ok(object)
}
fn text(object: &Map<String, Value>, key: &str) -> Result<String, ResourceError> {
object[key]
.as_str()
.map(str::to_owned)
.ok_or_else(envelope_invalid)
}
fn envelope_invalid() -> ResourceError {
ResourceError::PortabilityEnvelopeInvalid
}
@@ -0,0 +1,93 @@
//! Preview-снимок Resource: metadata, безопасные findings и инертный `text` (D-6, AC01).
//!
//! Вынесено из `service/resources.rs` ради health-лимита 1000 строк: preview —
//! единственный второй читатель pinned-снимка, и его findings обязаны считаться теми
//! же validators/scanner, что и публикация.
use super::*;
impl ResourcesService {
/// Preview: метаданные + findings + инертный `text` только для text/json (D-6).
///
/// Metadata и bytes относятся к **одному** разрешению версии: второй запрос за
/// card-строкой смешал бы metadata версии N с bytes версии N+1 при одновременном
/// обновлении (P3, TL F05).
pub(crate) async fn preview(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<ResourcePreviewResponse, ResourceError> {
// Story 3.10: template Draft не имеет bytes — preview отдаёт findings и text=null,
// не обращаясь ни к artifact store, ни к REST.
let record = self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await?;
if record.version.source_kind == "template" {
let (source, findings) = self
.template_card(workspace_id, resource_id, record.version.version)
.await?;
let card = ResourceCardResponse::from_record(&record);
return Ok(ResourcePreviewResponse {
resource: card.resource,
version: card.version,
findings,
preview: ResourcePreviewView { text: None },
source: Some(source),
});
}
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
let card = ResourceCardResponse::from_record(&resolved.snapshot);
let kind = card.kind()?;
let text = match kind {
ResourceKind::Text | ResourceKind::Json => Some(
String::from_utf8(bytes.clone()).map_err(|_| ResourceError::ContentInvalidUtf8)?,
),
// Для binary bytes не возвращаются вообще.
ResourceKind::Binary => None,
};
let findings = self
.preview_findings(workspace_id, &card, kind, &bytes)
.await?;
Ok(ResourcePreviewResponse {
resource: card.resource,
version: card.version,
findings,
preview: ResourcePreviewView { text },
source: None,
})
}
/// Findings preview (AC01): те же validators/scanner, что и у публикации, на тех же
/// pinned bytes. Наружу уходят только стабильные `code`/`field`; bytes содержимого,
/// совпавший фрагмент и цель `include:` никогда не попадают в ответ.
async fn preview_findings(
&self,
workspace_id: &WorkspaceId,
card: &ResourceCardResponse,
kind: ResourceKind,
bytes: &[u8],
) -> Result<Vec<PreviewFinding>, ResourceError> {
let mut findings = Vec::new();
let metadata = ResourceMetadata {
uri: card.resource.uri.clone(),
name: card.resource.name.clone(),
description: card.resource.description.clone(),
kind,
mime_type: card.version.mime_type.clone(),
sensitivity: parse_sensitivity(&card.version.sensitivity)?,
};
if let Err(error) =
ResourceMetadata::validate_content(kind, &metadata.mime_type, bytes, &self.limits)
{
findings.push(PreviewFinding::from_error(&error));
}
for error in self
.publication_findings(workspace_id, &metadata, bytes)
.await?
{
findings.push(PreviewFinding::from_error(&error));
}
Ok(findings)
}
}
@@ -0,0 +1,17 @@
//! Отзыв Resource (Story 3.8): отдельная security-команда, не lifecycle-переход.
//!
//! Слой Admin не решает, что значит отзыв: он передаёт actor/корреляцию из
//! серверной сессии и `RequestContext`, а единственную транзакцию и tombstone
//! создаёт реестр. Archive, immutable bytes и защищённое административное чтение
//! этой командой не меняются.
use crank_core::resource::ResourceError;
use crank_registry::model::resource::RevokeResourceRequest;
use super::ResourcesService;
impl ResourcesService {
pub(crate) async fn revoke(&self, request: RevokeResourceRequest) -> Result<(), ResourceError> {
self.registry.revoke_resource(request).await
}
}
@@ -0,0 +1,701 @@
//! Story 3.10 (FR-16): admin-api контракт REST-backed Resource template.
//!
//! Здесь живёт всё, что требует pinned Operation Version: structural-разбор
//! `metadata.source`, типизация параметров через shared `crank_schema`, blocker
//! findings (read-safety/parameters/cache) и view публикации. Домен (`crank-core`)
//! отвечает за типы/грамматику/пределы, persistence (`crank-registry`) — за
//! byte-less version-keyed хранение; сетевых вызовов здесь нет.
//!
//! Порядок create: metadata (форма) → source (структура/грамматика) → pinned
//! Published версия того же workspace → запись. Preview/publish пересчитывают
//! findings по **сохранённому** определению и заново разрешают pinned версию, поэтому
//! правка сохранённой ссылки не публикует небезопасную операцию.
use std::collections::BTreeSet;
use crank_core::WorkspaceId;
use crank_core::ids::{OperationId, ResourceId};
use crank_core::operation::{
OperationApprovalPolicy, OperationSafetyClass, OperationSafetyPolicy, OperationStatus, Target,
};
use crank_core::protocol::HttpMethod;
use crank_core::resource::template::{
TEMPLATE_CACHE_SCOPE, TemplateFinding, TemplateFindingCode, TemplateSource,
cache_policy_findings, parse_uri_template,
};
use crank_core::resource::{ResourceError, ResourceKind, ResourceMetadata};
use crank_registry::OperationVersionRecord;
use crank_registry::model::resource::{
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
ResourcePublicationRecord, ResourceTemplateSourceRecord, UpdateResourceTemplateDraftRequest,
};
use crank_schema::{Schema, SchemaKind};
use serde::Serialize;
use serde_json::Value;
use time::OffsetDateTime;
const MAX_TEMPLATE_DEFINITION_BYTES: usize = 65_536;
use super::{
CreatedDraft, DraftMetadata, PreviewFinding, PublishedVersionResponse, PublishedVersionView,
ResourceCardResponse, ResourcesService, generate_resource_id, parse_kind, parse_metadata,
parse_sensitivity, parse_timestamp, sha256_hex, truncate_to_micros,
};
/// Новый template Draft: `metadata` без части `content` + source-объект.
pub(crate) struct NewTemplateDraft {
pub workspace_id: WorkspaceId,
pub metadata: DraftMetadata,
pub source: Value,
}
/// Обновление template Draft: изменяемые metadata + новое определение.
pub(crate) struct UpdateTemplateDraft {
pub workspace_id: WorkspaceId,
pub resource_id: ResourceId,
pub description: String,
pub mime_type: String,
pub sensitivity: String,
pub expected_updated_at: Option<String>,
pub identity: TemplateIdentity,
pub source: Option<Value>,
}
/// Identity-поля template Draft: неизменяемы, но могут быть повторены в PUT-форме
/// (значение обязано совпадать с сохранённым).
#[derive(Clone, Debug, Default)]
pub(crate) struct TemplateIdentity {
pub uri: Option<String>,
pub name: Option<String>,
pub kind: Option<String>,
}
/// Каноническое определение + типизированные схемы параметров.
pub(crate) struct TemplateDefinition {
pub source: TemplateSource,
pub schemas: Vec<Schema>,
pub json: String,
pub digest: String,
}
impl TemplateDefinition {
pub(crate) fn parse(value: &Value) -> Result<Self, ResourceError> {
let source =
TemplateSource::parse(value).map_err(|error| ResourceError::SourceInvalid {
field: error.field(),
})?;
let mut schemas = Vec::with_capacity(source.parameters.len());
for parameter in &source.parameters {
let schema: Schema =
serde_json::from_value(parameter.schema.clone()).map_err(|_| {
ResourceError::SourceInvalid {
field: "source.parameters",
}
})?;
schemas.push(schema);
}
let json = serde_json::to_string(&source)
.map_err(|_| ResourceError::SourceInvalid { field: "source" })?;
if json.len() > MAX_TEMPLATE_DEFINITION_BYTES {
return Err(ResourceError::SourceInvalid { field: "source" });
}
let digest = sha256_hex(json.as_bytes());
Ok(Self {
source,
schemas,
json,
digest,
})
}
/// Сохранённое определение: parse + сверка digest (повреждение = integrity).
pub(crate) fn from_stored(
stored: &ResourceTemplateSourceRecord,
) -> Result<Self, ResourceError> {
let value: Value = serde_json::from_str(&stored.definition_json)
.map_err(|_| ResourceError::ArtifactIntegrity)?;
let definition = Self::parse(&value)?;
if definition.digest != stored.definition_digest {
return Err(ResourceError::ArtifactIntegrity);
}
Ok(definition)
}
}
/// `source` в карточке/публикации: факты без потерь + read-safety/access pinned версии.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct TemplateSourceView {
pub operation_id: String,
pub operation_version: u32,
pub uri_template: String,
pub parameters: Vec<Value>,
pub cache: TemplateCacheView,
pub failure: TemplateFailureView,
pub read_safety: TemplateReadSafetyView,
pub access: TemplateAccessView,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct TemplateCacheView {
pub ttl_ms: u64,
pub vary: Vec<String>,
pub max_bytes: u64,
/// Нормализованная серверная policy (клиент не может её задать).
pub scope: &'static str,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct TemplateFailureView {
pub outcome: &'static str,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct TemplateReadSafetyView {
pub method: HttpMethod,
pub safety_class: Option<OperationSafetyClass>,
pub read_safe: bool,
pub approval_required: bool,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct TemplateAccessView {
pub security_level: Value,
pub auth_profile_ref: Option<String>,
}
impl ResourcesService {
/// Story 3.10: текущий Draft является template-определением (без bytes).
pub(crate) async fn is_template_draft(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
) -> Result<bool, ResourceError> {
match self
.registry
.get_resource_draft(workspace_id.as_str(), resource_id)
.await
{
Ok(record) => Ok(record.version.source_kind == "template"),
Err(ResourceError::NotFound) => Ok(false),
Err(error) => Err(error),
}
}
/// Создание template Draft: source обязан ссылаться на exact same-workspace
/// Published версию; блocker findings на этом шаге не запрещают сохранение.
pub(crate) async fn create_template_draft(
&self,
draft: NewTemplateDraft,
) -> Result<CreatedDraft, ResourceError> {
let metadata = parse_metadata(&draft.metadata)?;
let definition = TemplateDefinition::parse(&draft.source)?;
self.pinned_version(&draft.workspace_id, &definition.source)
.await?;
let resource_id = generate_resource_id();
let now = truncate_to_micros(OffsetDateTime::now_utc());
let record = self
.registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: draft.workspace_id,
resource_id: resource_id.clone(),
uri: metadata.uri,
name: metadata.name,
description: metadata.description,
kind: metadata.kind.as_str().to_owned(),
mime_type: metadata.mime_type,
sensitivity: metadata.sensitivity.as_str().to_owned(),
definition_json: definition.json,
definition_digest: definition.digest,
created_at: now,
})
.await?;
Ok(CreatedDraft {
resource_id: record.snapshot.resource.resource_id,
})
}
/// Обновление template Draft: те же immutable-поля/precondition, новое определение.
pub(crate) async fn update_template_draft(
&self,
update: UpdateTemplateDraft,
) -> Result<ResourceCardResponse, ResourceError> {
let current = self
.registry
.get_resource_draft(update.workspace_id.as_str(), &update.resource_id)
.await?;
if current.version.source_kind != "template" {
return Err(ResourceError::SourceInvalid { field: "source" });
}
if update
.identity
.uri
.as_deref()
.is_some_and(|uri| uri != current.resource.uri)
{
return Err(ResourceError::FieldImmutable { field: "uri" });
}
if update
.identity
.name
.as_deref()
.is_some_and(|name| name != current.resource.name)
{
return Err(ResourceError::FieldImmutable { field: "name" });
}
if update
.identity
.kind
.as_deref()
.is_some_and(|kind| kind != current.resource.kind)
{
return Err(ResourceError::FieldImmutable { field: "kind" });
}
let current_kind = parse_kind(&current.resource.kind)?;
if !ResourceMetadata::description_is_valid(&update.description) {
return Err(ResourceError::DescriptionInvalid);
}
if !ResourceMetadata::mime_syntax_is_valid(&update.mime_type) {
return Err(ResourceError::MimeSyntaxInvalid);
}
match ResourceKind::for_mime(&update.mime_type) {
None => return Err(ResourceError::MimeNotAllowed),
Some(owner) if owner != current_kind => return Err(ResourceError::KindMismatch),
Some(_) => {}
}
let sensitivity = parse_sensitivity(&update.sensitivity)?;
let expected_updated_at = update
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: crank_core::resource::ResourceStatus::Draft,
});
}
let source = update
.source
.ok_or(ResourceError::SourceInvalid { field: "source" })?;
let definition = TemplateDefinition::parse(&source)?;
self.pinned_version(&update.workspace_id, &definition.source)
.await?;
self.registry
.update_resource_template_draft(UpdateResourceTemplateDraftRequest {
workspace_id: update.workspace_id.clone(),
resource_id: update.resource_id.clone(),
description: update.description,
mime_type: update.mime_type,
sensitivity: sensitivity.as_str().to_owned(),
expected_updated_at,
definition_json: definition.json,
definition_digest: definition.digest,
})
.await?;
self.card(&update.workspace_id, &update.resource_id).await
}
/// Публикация template Draft: сохранённое определение перепроверяется целиком,
/// затем reference разрешается заново (tampering не проходит), и только после
/// этого создаётся immutable publication snapshot.
pub(crate) async fn publish_template(
&self,
request: super::PublishResource,
current: crank_registry::model::resource::ResourceDraftRecord,
) -> Result<PublishedVersionResponse, ResourceError> {
let expected_updated_at = request
.expected_updated_at
.as_deref()
.map(parse_timestamp)
.transpose()?
.ok_or(ResourceError::Stale)?;
if expected_updated_at != current.resource.updated_at {
return Err(ResourceError::Stale);
}
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
return Err(ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: crank_core::resource::ResourceStatus::Published,
});
}
let stored = self
.registry
.get_resource_template_source(
request.workspace_id.as_str(),
&request.resource_id,
current.version.version,
)
.await?;
let definition = TemplateDefinition::from_stored(&stored)?;
let pinned = self
.pinned_version(&request.workspace_id, &definition.source)
.await?;
let findings = template_findings(&definition, &pinned);
if !findings.is_empty() {
return Err(ResourceError::SourceBlocked { findings });
}
let (publication, source) = self
.registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: request.workspace_id.clone(),
resource_id: request.resource_id.clone(),
expected_updated_at,
expected_version: current.version.version,
expected_digest: definition.digest,
published_at: truncate_to_micros(OffsetDateTime::now_utc()),
})
.await?;
let card = self
.card(&request.workspace_id, &request.resource_id)
.await?;
Ok(PublishedVersionResponse {
resource: card,
published_version: published_template_view(&publication, &source, &pinned)?,
})
}
/// Карточка template Draft: source view + blocker findings сохранённого определения.
pub(crate) async fn template_card(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<(TemplateSourceView, Vec<PreviewFinding>), ResourceError> {
let stored = self
.registry
.get_resource_template_source(workspace_id.as_str(), resource_id, version)
.await?;
let definition = TemplateDefinition::from_stored(&stored)?;
let pinned = self
.pinned_version(workspace_id, &definition.source)
.await?;
let findings = template_findings(&definition, &pinned)
.into_iter()
.map(|finding| PreviewFinding {
code: finding.code(),
field: finding.field,
})
.collect();
Ok((source_view(&definition, &pinned), findings))
}
/// Exact Published Version шаблона (definition-only, без artifact-чтения).
pub(crate) async fn published_template_view(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<PublishedVersionView, ResourceError> {
let (publication, source) = self
.registry
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
.await?;
let definition = TemplateDefinition::from_stored(&source)?;
let pinned = self
.pinned_version(workspace_id, &definition.source)
.await?;
published_template_view(&publication, &source, &pinned)
}
/// Точная Published версия является template-определением (без bytes).
pub(crate) async fn publication_is_template(
&self,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
) -> Result<bool, ResourceError> {
match self
.registry
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
.await
{
Ok(_) => Ok(false),
Err(ResourceError::NotFound) => match self
.registry
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
.await
{
Ok(_) => Ok(true),
Err(ResourceError::NotFound) => Err(ResourceError::NotFound),
Err(error) => Err(error),
},
Err(error) => Err(error),
}
}
async fn pinned_version(
&self,
workspace_id: &WorkspaceId,
source: &TemplateSource,
) -> Result<OperationVersionRecord, ResourceError> {
let operation_id: OperationId = source.operation_id.as_str().into();
let record = self
.registry
.get_operation_version(workspace_id, &operation_id, source.operation_version)
.await
.map_err(|_| ResourceError::StorageUnavailable)?
.ok_or(ResourceError::SourceNotFound)?;
if record.status != OperationStatus::Published {
return Err(ResourceError::SourceNotPublished);
}
Ok(record)
}
}
/// Blockers шаблона на pinned версии: read-safety, mapping параметров, cache policy.
pub(crate) fn template_findings(
definition: &TemplateDefinition,
pinned: &OperationVersionRecord,
) -> Vec<TemplateFinding> {
let source = &definition.source;
let snapshot = &pinned.snapshot;
let Target::Rest(target) = &snapshot.target;
let safety: Option<&OperationSafetyPolicy> = snapshot.execution_config.safety.as_ref();
let approval: Option<&OperationApprovalPolicy> =
snapshot.execution_config.approval_policy.as_ref();
let approval_required = approval.is_some_and(|policy| policy.required);
let read_safe = matches!(target.method, HttpMethod::Get | HttpMethod::Head)
&& safety.is_some_and(|policy| policy.class == OperationSafetyClass::Read)
&& !approval_required;
let mut findings = Vec::new();
if !read_safe {
findings.push(TemplateFinding::new(
TemplateFindingCode::NotReadSafe,
"source.operation_id",
));
}
let placeholders = parse_uri_template(&source.uri_template).unwrap_or_default();
let placeholder_set: BTreeSet<&str> = placeholders.iter().map(String::as_str).collect();
let names: BTreeSet<&str> = source
.parameters
.iter()
.map(|parameter| parameter.name.as_str())
.collect();
if names.len() != source.parameters.len() || placeholder_set.len() != placeholders.len() {
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterDuplicate,
"source.parameters",
));
}
let mut input_paths = BTreeSet::new();
if source
.parameters
.iter()
.any(|parameter| !input_paths.insert(parameter.input_path.as_str()))
{
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterDuplicate,
"source.parameters",
));
}
for parameter in &source.parameters {
if !placeholder_set.contains(parameter.name.as_str()) {
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterUnknown,
"source.parameters",
));
}
}
for placeholder in &placeholders {
if !names.contains(placeholder.as_str()) {
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterUnmapped,
"source.uri_template",
));
}
}
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
match resolve_input_field(&snapshot.input_schema, &parameter.input_path) {
Some(pinned_field) => {
findings.extend(parameter_mismatches(schema, pinned_field));
findings.extend(parameter_default_findings(schema, pinned_field));
}
None => findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterUnmapped,
"source.parameters",
)),
}
}
findings.extend(cache_policy_findings(&source.cache, &names));
findings
}
fn parameter_mismatches(schema: &Schema, pinned: &Schema) -> Vec<TemplateFinding> {
let mut findings = Vec::new();
let incompatible = matches!(
schema.kind,
SchemaKind::Object | SchemaKind::Array | SchemaKind::Oneof
) || schema.kind != pinned.kind
|| schema
.format
.as_ref()
.is_some_and(|format| pinned.format.as_ref() != Some(format))
|| (!schema.enum_values.is_empty()
&& schema
.enum_values
.iter()
.any(|value| !pinned.enum_values.contains(value)));
if incompatible {
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterTypeMismatch,
"source.parameters",
));
}
findings
}
fn parameter_default_findings(schema: &Schema, pinned: &Schema) -> Vec<TemplateFinding> {
let mut findings = Vec::new();
match &schema.default_value {
Some(default) => {
let enum_violation =
[&schema.enum_values, &pinned.enum_values]
.into_iter()
.any(|values| {
!values.is_empty()
&& default
.as_str()
.is_none_or(|value| !values.iter().any(|item| item == value))
});
if enum_violation
|| !default_matches_schema(schema, default)
|| !default_matches_schema(pinned, default)
{
findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterDefaultInvalid,
"source.parameters",
));
}
}
None if !schema.required => findings.push(TemplateFinding::new(
TemplateFindingCode::ParameterOptionalWithoutDefault,
"source.parameters",
)),
None => {}
}
findings
}
/// Соответствие default объявленному `crank_schema::Schema` (definition-time).
///
/// Runtime schema-shape validation намеренно не вызывается: admin-api находится
/// за execution boundary (никаких runtime execute/mapping/validation вызовов в
/// этом слое). Здесь используются только типовые факты уже разобранной схемы;
/// новых языков схем не вводится.
fn default_matches_schema(schema: &Schema, default: &Value) -> bool {
if default.is_null() {
return schema.nullable || schema.kind == SchemaKind::Null;
}
match schema.kind {
SchemaKind::Object => default.is_object(),
SchemaKind::Array => default.is_array(),
SchemaKind::String => default.is_string(),
SchemaKind::Integer => default.is_i64() || default.is_u64(),
SchemaKind::Number => default.is_number(),
SchemaKind::Boolean => default.is_boolean(),
SchemaKind::Enum => default
.as_str()
.is_some_and(|value| schema.enum_values.iter().any(|item| item == value)),
SchemaKind::Null => false,
SchemaKind::Oneof => schema
.variants
.iter()
.any(|variant| default_matches_schema(variant, default)),
}
}
/// `input.order_id` → поле pinned `input_schema` (не `request.path`).
fn resolve_input_field<'a>(input_schema: &'a Schema, input_path: &str) -> Option<&'a Schema> {
let mut segments = input_path.split('.');
if segments.next()? != "input" {
return None;
}
let mut current = input_schema;
let mut matched = false;
for segment in segments {
current = current.field(segment)?;
matched = true;
}
matched.then_some(current)
}
fn source_view(
definition: &TemplateDefinition,
pinned: &OperationVersionRecord,
) -> TemplateSourceView {
let source = &definition.source;
let snapshot = &pinned.snapshot;
let Target::Rest(target) = &snapshot.target;
let safety = snapshot.execution_config.safety.as_ref();
let approval_required = snapshot
.execution_config
.approval_policy
.as_ref()
.is_some_and(|policy| policy.required);
let read_safe = matches!(target.method, HttpMethod::Get | HttpMethod::Head)
&& safety.is_some_and(|policy| policy.class == OperationSafetyClass::Read)
&& !approval_required;
TemplateSourceView {
operation_id: source.operation_id.clone(),
operation_version: source.operation_version,
uri_template: source.uri_template.clone(),
parameters: source
.parameters
.iter()
.map(|parameter| {
serde_json::json!({
"name": parameter.name,
"input_path": parameter.input_path,
"schema": parameter.schema,
})
})
.collect(),
cache: TemplateCacheView {
ttl_ms: source.cache.ttl_ms,
vary: source.cache.vary.clone(),
max_bytes: source.cache.max_bytes,
scope: TEMPLATE_CACHE_SCOPE,
},
failure: TemplateFailureView { outcome: "error" },
read_safety: TemplateReadSafetyView {
method: target.method,
safety_class: safety.map(|policy| policy.class),
read_safe,
approval_required,
},
access: TemplateAccessView {
security_level: serde_json::to_value(snapshot.security_level).unwrap_or(Value::Null),
auth_profile_ref: snapshot
.execution_config
.auth_profile_ref
.as_ref()
.map(|profile| profile.as_str().to_owned()),
},
}
}
fn published_template_view(
publication: &ResourcePublicationRecord,
source: &ResourceTemplateSourceRecord,
pinned: &OperationVersionRecord,
) -> Result<PublishedVersionView, ResourceError> {
let definition = TemplateDefinition::from_stored(source)?;
Ok(PublishedVersionView {
version: publication.version,
uri: publication.uri.clone(),
name: publication.name.clone(),
description: publication.description.clone(),
kind: publication.kind.clone(),
mime_type: publication.mime_type.clone(),
size_bytes: publication.size_bytes,
digest: publication.digest.clone(),
sensitivity: publication.sensitivity.clone(),
source: Some(source_view(&definition, pinned)),
})
}
@@ -0,0 +1,389 @@
use super::*;
use base64::Engine as _;
impl ResourcesService {
async fn test_resource_read(
&self,
admin: &super::super::AdminService,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
body: Value,
correlation: &crank_core::CorrelationContext,
) -> Result<Value, ApiError> {
let object = body
.as_object()
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
if object.len() != 4
|| !["version", "digest", "updated_at", "parameters"]
.iter()
.all(|key| object.contains_key(*key))
{
return Err(ApiError::validation("invalid resource test request"));
}
let version = object
.get("version")
.and_then(Value::as_u64)
.and_then(|v| u32::try_from(v).ok())
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
let digest = object
.get("digest")
.and_then(Value::as_str)
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
let updated_at = object
.get("updated_at")
.and_then(Value::as_str)
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
let values = object
.get("parameters")
.and_then(Value::as_object)
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
let current = admin.resources.card(workspace_id, resource_id).await?;
if current.resource.updated_at != updated_at
|| current.version.version != version
|| current.version.digest != digest
{
return Err(ApiError::conflict_with_context(
"Resource changed; reload before testing",
json!({"error_code":"resource_stale","recovery":"reload"}),
));
}
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
return Err(
crank_core::resource::ResourceError::InvalidLifecycleTransition {
from: current.resource.status,
to: crank_core::resource::ResourceStatus::Draft,
}
.into(),
);
}
let stored = admin
.registry
.get_resource_template_source(workspace_id.as_str(), resource_id, version)
.await?;
let definition = template::TemplateDefinition::from_stored(&stored)?;
let source = &definition.source;
let operation_id: crank_core::OperationId = source.operation_id.as_str().into();
let operation = admin
.registry
.get_operation_version(workspace_id, &operation_id, source.operation_version)
.await?
.ok_or(crank_core::resource::ResourceError::SourceNotFound)?;
if operation.status != crank_core::operation::OperationStatus::Published {
return Err(crank_core::resource::ResourceError::SourceNotPublished.into());
}
let operation_detail = admin.get_operation(workspace_id, &operation_id).await?;
if operation_detail.status == crank_core::operation::OperationStatus::Archived {
return Err(crank_core::resource::ResourceError::SourceNotPublished.into());
}
let findings = template::template_findings(&definition, &operation);
if !findings.is_empty() {
return Err(crank_core::resource::ResourceError::SourceBlocked { findings }.into());
}
if values.keys().any(|name| {
!source
.parameters
.iter()
.any(|parameter| &parameter.name == name)
}) {
return Err(ApiError::validation(
"resource parameters do not match the saved definition",
));
}
let mut input = serde_json::Map::new();
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
let value = values
.get(&parameter.name)
.or(schema.default_value.as_ref())
.ok_or_else(|| {
ApiError::validation("resource parameters do not match the saved definition")
})?;
let parameter_schema: crank_schema::Schema =
serde_json::from_value(parameter.schema.clone()).map_err(|_| {
ApiError::validation("saved resource parameter schema is invalid")
})?;
crank_runtime::validate_resource_template_parameter(&parameter_schema, value).map_err(
|_| ApiError::validation("resource parameter does not match the saved definition"),
)?;
// Validate the narrower Resource contract before assembling input; the runtime
// separately validates the pinned Operation contract before outbound dispatch.
if !set_resource_input_path(&mut input, &parameter.input_path, value.clone()) {
return Err(ApiError::validation(
"saved resource parameter mapping is invalid",
));
}
}
let runtime = crank_runtime::RuntimeOperation::from(operation.snapshot.clone());
let context = crank_runtime::RuntimeRequestContext::from_correlation(correlation)
.with_metering_context(
workspace_id.clone(),
None,
crank_core::InvocationSource::AdminTestRun,
);
let request_id = context.request_id.as_str().to_owned();
let trace_id = context.trace_context.trace_id().to_string();
let auth = admin
.resolve_operation_auth(workspace_id, &runtime.execution_config, None)
.await
.map_err(|_| {
ApiError::unprocessable_with_context(
"operation authorization is unavailable",
json!({"error_code":"resource_test_authorization_failed"}),
)
})?;
let deadline = std::time::Instant::now()
+ std::time::Duration::from_millis(runtime.execution_config.timeout_ms.max(1));
let input = Value::Object(input);
let resource_guard = admin
.registry
.begin_authorized_resource_test_read(
workspace_id.as_str(),
resource_id,
version,
digest,
)
.await?;
let execution = crank_runtime::RuntimeExecutionRequest::try_new(
workspace_id,
crank_core::ExecutionOrigin::AdminDraft,
None,
&runtime,
&input,
crank_runtime::ExecutionAuthorization::Authorized,
auth.as_ref(),
&context,
deadline,
)
.map_err(|_| ApiError::validation("resource test request is invalid"))?;
let started_at = std::time::Instant::now();
let execution_result = admin.runtime.execute_outcome(execution).await;
resource_guard.commit().await?;
let duration_ms = u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
match execution_result {
Ok(success) => {
let kind = crank_core::resource::ResourceKind::parse(&current.resource.kind)
.ok_or_else(|| ApiError::unprocessable_with_context("saved Resource kind is invalid", json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id})))?;
if !kind.allows_mime_type(&current.version.mime_type) {
return Err(ApiError::unprocessable_with_context(
"saved Resource representation is invalid",
json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id}),
));
}
let representation = match kind {
crank_core::resource::ResourceKind::Text => success.output.as_str().map(str::as_bytes).map(Vec::from),
crank_core::resource::ResourceKind::Json if !success.output.is_null() => serde_json::to_vec(&success.output).ok(),
crank_core::resource::ResourceKind::Binary => success
.output
.as_object()
.filter(|object| object.len() == 1 && object.contains_key("data_base64"))
.and_then(|object| object.get("data_base64"))
.and_then(Value::as_str)
.and_then(|encoded| base64::engine::general_purpose::STANDARD.decode(encoded).ok()),
_ => None,
}.filter(|bytes| !bytes.is_empty() && bytes.len() as u64 <= source.cache.max_bytes)
.ok_or_else(|| ApiError::unprocessable_with_context(
"test read output does not match the saved Resource contract",
json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id}),
))?;
let _representation = representation;
let response_preview = crank_core::sanitize_invocation_preview(&success.output);
admin
.record_invocation(super::super::InvocationRecordRequest {
workspace_id,
agent_id: None,
operation: &operation.snapshot,
request_id: Some(&request_id),
trace_id: Some(&trace_id),
source: crank_core::InvocationSource::AdminTestRun,
level: crank_core::InvocationLevel::Info,
status: crank_core::InvocationStatus::Ok,
message: "administrative Resource test read completed".to_owned(),
status_code: None,
error_kind: None,
execution_stage: Some(crank_core::ExecutionStage::Runtime),
execution_error_code: None,
retryability: Some(crank_core::Retryability::Never),
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
duration_ms,
request_preview: success.request_preview.clone(),
response_preview: response_preview.clone(),
})
.await;
Ok(
json!({"ok":true,"request_id":request_id,"trace_id":trace_id,"output":response_preview}),
)
}
Err(failure) => {
admin
.record_invocation(super::super::InvocationRecordRequest {
workspace_id,
agent_id: None,
operation: &operation.snapshot,
request_id: Some(&request_id),
trace_id: Some(&trace_id),
source: crank_core::InvocationSource::AdminTestRun,
level: crank_core::InvocationLevel::Error,
status: crank_core::InvocationStatus::Error,
message: "administrative Resource test read failed".to_owned(),
status_code: failure.upstream_status(),
error_kind: Some(failure.error_code().as_str().to_owned()),
execution_stage: Some(failure.stage()),
execution_error_code: Some(failure.error_code()),
retryability: Some(failure.retryability()),
outcome_certainty: Some(failure.outcome_certainty()),
duration_ms,
request_preview: Value::Null,
response_preview: Value::Null,
})
.await;
Ok(
json!({"ok":false,"request_id":request_id,"trace_id":trace_id,"error":crate::error::execution_test_failure_localized(&failure, crank_core::ExecutionLocale::En)}),
)
}
}
}
pub(crate) async fn execute_template_test(
&self,
admin: &super::super::AdminService,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
body: Value,
correlation: &crank_core::CorrelationContext,
) -> Result<Value, ApiError> {
self.test_resource_read(admin, workspace_id, resource_id, body, correlation)
.await
}
/// Story 3.16 §4: pinned content of a dynamic (template) dependency.
///
/// The Prompt dependency names only the exact `(resource_id, version)` of the template, so the
/// declared read Operation is executed through the same 3.11 runtime (authorization, outbound,
/// size and live revocation gate) with the template's own parameter defaults. A parameter
/// without a default cannot be supplied by a Prompt, and every failure stays `None` — the
/// caller turns that into `prompt_dependency_unavailable` instead of substituting definition
/// text or stale content.
pub(crate) async fn read_pinned_template_content(
&self,
admin: &super::super::AdminService,
workspace_id: &WorkspaceId,
resource_id: &ResourceId,
version: u32,
correlation: &crank_core::CorrelationContext,
) -> Option<Vec<u8>> {
let (publication, stored) = admin
.registry
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
.await
.ok()?;
let kind = crank_core::resource::ResourceKind::parse(&publication.kind)?;
if !kind.allows_mime_type(&publication.mime_type) {
return None;
}
let definition = template::TemplateDefinition::from_stored(&stored).ok()?;
let source = &definition.source;
let operation_id: crank_core::OperationId = source.operation_id.as_str().into();
let operation = admin
.registry
.get_operation_version(workspace_id, &operation_id, source.operation_version)
.await
.ok()??;
if operation.status != crank_core::operation::OperationStatus::Published {
return None;
}
let detail = admin
.get_operation(workspace_id, &operation_id)
.await
.ok()?;
if detail.status == crank_core::operation::OperationStatus::Archived {
return None;
}
if !template::template_findings(&definition, &operation).is_empty() {
return None;
}
let mut input = serde_json::Map::new();
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
let value = schema.default_value.as_ref()?;
let parameter_schema: crank_schema::Schema =
serde_json::from_value(parameter.schema.clone()).ok()?;
crank_runtime::validate_resource_template_parameter(&parameter_schema, value).ok()?;
if !set_resource_input_path(&mut input, &parameter.input_path, value.clone()) {
return None;
}
}
let runtime = crank_runtime::RuntimeOperation::from(operation.snapshot.clone());
let context = crank_runtime::RuntimeRequestContext::from_correlation(correlation)
.with_metering_context(
workspace_id.clone(),
None,
crank_core::InvocationSource::AdminTestRun,
);
let auth = admin
.resolve_operation_auth(workspace_id, &runtime.execution_config, None)
.await
.ok()?;
let deadline = std::time::Instant::now()
+ std::time::Duration::from_millis(runtime.execution_config.timeout_ms.max(1));
let input = Value::Object(input);
let guard = admin
.registry
.begin_authorized_resource_template_read(
workspace_id.as_str(),
resource_id,
publication.version,
)
.await
.ok()?;
let request = crank_runtime::RuntimeExecutionRequest::try_new(
workspace_id,
crank_core::ExecutionOrigin::AdminDraft,
None,
&runtime,
&input,
crank_runtime::ExecutionAuthorization::Authorized,
auth.as_ref(),
&context,
deadline,
)
.ok()?;
let success = admin.runtime.execute_outcome(request).await.ok()?;
guard.commit().await.ok()?;
let max_bytes = usize::try_from(source.cache.max_bytes).unwrap_or(usize::MAX);
match kind {
crank_core::resource::ResourceKind::Text => {
success.output.as_str().map(str::as_bytes).map(Vec::from)
}
crank_core::resource::ResourceKind::Json if !success.output.is_null() => {
serde_json::to_vec(&success.output).ok()
}
_ => None,
}
.filter(|bytes| !bytes.is_empty() && bytes.len() <= max_bytes)
}
}
fn set_resource_input_path(
root: &mut serde_json::Map<String, Value>,
path: &str,
value: Value,
) -> bool {
let Some((prefix, tail)) = path.split_once('.') else {
return false;
};
if prefix != "input" {
return false;
}
let mut current = root;
let mut parts = tail.split('.').peekable();
while let Some(part) = parts.next() {
if parts.peek().is_none() {
return current.insert(part.to_owned(), value).is_none();
}
let entry = current.entry(part.to_owned()).or_insert_with(|| json!({}));
let Some(object) = entry.as_object_mut() else {
return false;
};
current = object;
}
false
}
@@ -0,0 +1,403 @@
//! BUILD-ONLY: in-crate counter harness Story 3.6 (D-19, пять именованных проверок).
//!
//! Статус на стадии Dev ATDD: **не зарегистрирован**. Файл лежит по пути, который BUILD
//! объявит из production-модуля:
//! ```text
//! // apps/admin-api/src/service/resources.rs
//! #[cfg(test)] pub(crate) mod counters { /* inline: note_artifact_put/read, artifact_puts/reads, reset */ }
//! #[cfg(test)] #[path = "resources/tests.rs"] mod tests;
//! ```
//! Сегодня `apps/admin-api/src/service/resources.rs` не существует, поэтому файл не компилируется
//! и не исполняется (нулевая коллекция — не PASS). Ранняя регистрация запрещена: счётчики живут
//! внутри production-модуля, а production-код на стадии ATDD не пишется.
//!
//! Минимальный будущий интерфейс, на который опираются тесты (объявляется в
//! `service/resources.rs`, отдельного production `tests_support`-модуля не требуется):
//! ```text
//! pub(crate) struct DraftMetadata { pub uri: String, pub name: String, pub description: String,
//! pub kind: String, pub mime_type: String, pub sensitivity: String }
//! pub(crate) struct NewDraft { pub workspace_id: WorkspaceId, pub metadata: DraftMetadata,
//! pub bytes: Vec<u8> }
//! pub(crate) struct CreatedDraft { pub resource_id: ResourceId }
//! impl ResourcesService {
//! pub(crate) fn for_tests(registry: PostgresRegistry, limit: usize) -> Self;
//! pub(crate) async fn create_draft(&self, draft: NewDraft) -> Result<CreatedDraft, ResourceError>;
//! pub(crate) async fn read_content(&self, workspace_id: &WorkspaceId, resource_id: &ResourceId)
//! -> Result<Vec<u8>, ResourceError>;
//! }
//! ```
//! Фикстуры собираются локально в этом файле (`text_draft`/`text_draft_in`), поэтому production
//! обязан остаться без тестового `tests_support`-модуля и без публичного API ради тестов.
//!
//! Что именно должен доказать harness (D-19): счётчики стоят на реальных точках —
//! `ArtifactStore::put_registered` (перед регистрацией bytes) и физического чтения байт в
//! приватном `read_resource_content()`. «0» доказывается только вместе с положительным
//! контролем, а duplicate/DB-rollback проверяются по отсутствию принятых строк, а не по put.
//! Запуск после BUILD (фильтр обязан содержать сегмент `tests::`):
//! `cargo test -p admin-api --lib service::resources::tests::story36_ -- --list`
//! и затем `... -- --test-threads=1` (каждый тест предваряется `counters::reset()`).
use super::ResourcesService;
use super::counters;
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use crank_registry::model::resource::ResourceDraftRecord;
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery, PostgresRegistry};
use serial_test::serial;
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const FOREIGN_WORKSPACE_ID: &str = "ws_story36_counters_other";
struct Harness {
service: ResourcesService,
registry: PostgresRegistry,
}
/// Изолированный стенд: своя PG-схема на каждый тест (иначе счётчики делят строки между тестами).
///
/// Драйвер, миграция и сборка store/service выполняются composition-фикстурой
/// `crate::app::resource_test_support::ResourceServiceHarness`: сервисный тест-модуль
/// получает готовый сервис и реестр, а не сырой pool (TL run105 F3, Q1).
async fn harness(name: &str) -> Harness {
let ResourceServiceHarness {
service, registry, ..
} = ResourceServiceHarness::spawn(name, LIMIT).await;
Harness { service, registry }
}
/// Принятые черновики workspace через продуктовое чтение: raw SQL в
/// `apps/admin-api/src/service/**` запрещён execution-boundary правилом, поэтому
/// «0 принятых строк» наблюдается на том же публичном чтении, что и UI.
async fn accepted_drafts(harness: &Harness) -> Vec<ResourceDraftRecord> {
harness
.registry
.list_resource_drafts(WORKSPACE_ID, 100)
.await
.expect("accepted resource drafts must be readable")
}
/// Активные owning-ссылки workspace (учёт владения bytes, AD-10).
async fn active_owning_refs(harness: &Harness) -> usize {
let workspace_id = WorkspaceId::new(WORKSPACE_ID);
let page = harness
.registry
.list_artifact_sources(ListArtifactSourcesQuery {
workspace_id: &workspace_id,
cursor: None,
limit: 100,
})
.await
.expect("artifact sources must be readable");
page.items
.iter()
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
.count()
}
/// Локальная фикстура: Draft в `ws_default` (никакого production `tests_support`).
fn text_draft(uri: &str, name: &str, bytes: &[u8]) -> NewDraftFixture {
text_draft_in(&WorkspaceId::new(WORKSPACE_ID), uri, name, bytes)
}
/// Та же фикстура с явным workspace (нужна для «чужого» Resource).
fn text_draft_in(
workspace_id: &WorkspaceId,
uri: &str,
name: &str,
bytes: &[u8],
) -> NewDraftFixture {
super::NewDraft {
workspace_id: workspace_id.clone(),
metadata: super::DraftMetadata {
uri: uri.to_owned(),
name: name.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
type NewDraftFixture = super::NewDraft;
/// Второй workspace (никаких прав/членства у него нет: здесь проверяется только адресация).
async fn create_other_workspace(registry: &PostgresRegistry) -> WorkspaceId {
use crank_core::{Workspace, WorkspaceStatus};
use crank_registry::CreateWorkspaceRequest;
use serde_json::json;
let now = time::OffsetDateTime::now_utc();
let workspace_id = WorkspaceId::new(FOREIGN_WORKSPACE_ID);
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: "story36-counters-other".to_owned(),
display_name: "Story 3.6 Counters Other".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("the second workspace must be created");
workspace_id
}
// Детерминизм счётчиков: счётчики D-19 — процессные статики, поэтому все проверки,
// которые их наблюдают (включая guard-пути), сериализуются атрибутом планировщика.
// Сами ассерты и тела тестов не изменены.
#[tokio::test]
#[serial]
async fn story36_counter_authorized_create_puts_once() {
let harness = harness("create_puts").await;
counters::reset();
let created = harness
.service
.create_draft(text_draft("crank://counter/put", "counter_put", b"payload"))
.await
.expect("authorized create must succeed");
assert_eq!(
counters::artifact_puts(),
1,
"an authorized create must hit the real byte-registration point exactly once"
);
assert_eq!(counters::artifact_reads(), 0);
// Положительный контроль: счётчик отражает настоящую запись, а не переменную теста.
let stored = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("stored content must be readable");
assert_eq!(stored.as_slice(), b"payload");
}
#[tokio::test]
#[serial]
async fn story36_counter_authorized_read_reads_once() {
let harness = harness("read_reads").await;
let created = harness
.service
.create_draft(text_draft(
"crank://counter/read",
"counter_read",
b"payload",
))
.await
.expect("authorized create must succeed");
counters::reset();
let stored = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("authorized read must succeed");
assert_eq!(stored.as_slice(), b"payload");
assert_eq!(
counters::artifact_reads(),
1,
"an authorized read must hit the real byte-read point exactly once"
);
}
#[tokio::test]
#[serial]
async fn story36_counter_denied_create_puts_zero() {
let harness = harness("denied_create").await;
counters::reset();
// Конкретный доменный отказ до регистрации bytes: kind=text + text/plain + C3 28.
let draft = text_draft("crank://counter/denied", "counter_denied", &[0xC3, 0x28]);
let error = harness
.service
.create_draft(draft)
.await
.expect_err("invalid UTF-8 must be rejected before bytes are registered");
assert_eq!(error.code(), "resource_content_invalid_utf8");
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
assert!(
accepted_drafts(&harness).await.is_empty(),
"a refused create must not accept any resource row"
);
}
#[tokio::test]
#[serial]
async fn story36_counter_denied_foreign_resource_reads_zero() {
let harness = harness("foreign_read").await;
let foreign_workspace = create_other_workspace(&harness.registry).await;
// Реальный Resource в другом workspace: он существует, но не в ws_default.
let created = harness
.service
.create_draft(text_draft_in(
&foreign_workspace,
"crank://counter/foreign",
"counter_foreign",
b"foreign payload",
))
.await
.expect("create in the owning workspace must succeed");
counters::reset();
let error = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect_err("a Resource of another workspace must not be readable here");
assert_eq!(error.code(), "resource_not_found");
assert_eq!(counters::artifact_reads(), 0);
assert_eq!(counters::artifact_puts(), 0);
// Положительный контроль: тот же существующий Resource читается в своём workspace,
// поэтому «0» выше — наблюдение, а не отсутствие реализации.
let stored = harness
.service
.read_content(&foreign_workspace, &created.resource_id)
.await
.expect("the owning workspace must read its own Resource");
assert_eq!(stored.as_slice(), b"foreign payload");
assert_eq!(counters::artifact_reads(), 1);
}
#[tokio::test]
#[serial]
async fn story36_counter_duplicate_conflict_accepted_rows_zero() {
let harness = harness("duplicate").await;
counters::reset();
harness
.service
.create_draft(text_draft("crank://counter/dup", "counter_dup", b"payload"))
.await
.expect("first create must succeed");
let duplicate = text_draft("crank://counter/dup", "counter_other", b"payload");
let error = harness
.service
.create_draft(duplicate)
.await
.expect_err("duplicate uri must be rejected");
assert_eq!(error.code(), "resource_uri_duplicate");
// Значение put здесь НЕ утверждается: bytes регистрируются до конфликта, осиротевшие
// bytes допустимы (AD-10). Доказывается отсутствие принятых строк: у принятого
// черновика ровно одна текущая версия, а живая owning-ссылка ровно одна.
let accepted = accepted_drafts(&harness).await;
assert_eq!(accepted.len(), 1, "only the first create is accepted");
assert_eq!(
accepted[0].version.version, 1,
"the accepted draft keeps exactly one current version"
);
harness
.registry
.resolve_current_resource_version(WORKSPACE_ID, &accepted[0].resource.resource_id)
.await
.expect("the accepted draft must expose its current version");
assert_eq!(
active_owning_refs(&harness).await,
1,
"only the accepted draft keeps an active owning reference"
);
}
// Регистрация подмодулей guard-путей (TL review run101, R-A): тот же in-crate набор,
// отдельные файлы, потому что inline-модуль такого объёма запрещён health-правилом.
//
// Три HTTP-модуля лежат в тестовом пути `tests/integration/resources/in_crate/`
// (TL run111): их содержимое использует прямой HTTP-клиент, а `apps/admin-api/src/service/**`
// по execution-boundary правилу не может содержать такую зависимость даже в тестах.
// Модули остаются in-crate тестами библиотеки — import-путь `service::resources::tests::<модуль>`
// и все test IDs сохраняются, внешний integration-бинарь их не регистрирует.
#[path = "../../../tests/integration/resources/in_crate/guard_path.rs"]
mod guard_path;
#[path = "../../../tests/integration/resources/in_crate/guard_telemetry.rs"]
mod guard_telemetry;
#[path = "../../../tests/integration/resources/in_crate/limits.rs"]
mod limits;
#[path = "tests/read_integrity.rs"]
mod read_integrity;
// P3 (TL F05): детерминированная проверка единого снимка версии и bytes.
#[path = "tests/snapshot.rs"]
mod snapshot;
#[path = "tests/snapshot_after_resolve.rs"]
mod snapshot_after_resolve;
// F5 (TL run105): контроль редактирования чувствительных заголовков в диагностике
// рукописного запроса — отдельный файл по тому же health-правилу.
#[path = "tests/diagnostics.rs"]
mod diagnostics;
// Story 3.7 / AC03 (TL CODE-REVIEW): детерминированный race «публикация vs Draft
// update» через уже принятый BUILD-only шов `interleave`.
#[path = "tests/publication_race.rs"]
mod publication_race;
// BUILD obligations, которые этот harness НЕ подтверждает:
// - session/Owner/CSRF/origin guard-ы (это HTTP-уровень, таргет A);
// - DB-rollback при update после шага пометки (таргет P, `story36_at03_update_rollback_*`);
// - захват logs/spans/metrics (см. `apps/admin-api/tests/integration/resources/telemetry.rs`).
// Измерение принятых строк идёт через публичное чтение реестра (`list_resource_drafts`,
// `list_artifact_sources`), а не через прямой SQL-драйвер: execution-boundary запрещает
// зависимость от драйвера хранилища в `apps/admin-api/src/service/**`. Поведенческое
// ожидание сохранено: на отказе не появляется ни принятый черновик, ни его текущая версия,
// ни активная owning-ссылка.
// ---------------------------------------------------------------------------
// Story 3.7 / AC02: configure lower limit демонстрирует 413-путь публикации,
// недостижимый через persisted state (DB CHECK = storage ceiling).
// ---------------------------------------------------------------------------
#[tokio::test]
async fn story37_at02_configured_lower_limit_refuses_publication_before_writes() {
use std::sync::Arc;
use crank_artifacts::ArtifactStore;
use crank_core::resource::{ResourceError, ResourceLimits};
let wide = ResourceServiceHarness::spawn("story37_publish_limit", LIMIT).await;
let bytes = b"0123456789abcdef0123456789abcdef";
let created = wide
.service
.create_draft(text_draft("crank://story37/limit", "limit_doc", bytes))
.await
.expect("draft must be created under the default limit");
let card = wide
.service
.card(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("draft card must be readable");
// Тот же registry/store, но сконфигурированный ниже сохранённого размера: публикация
// обязана отказать до любых записей (413-путь).
let store = Arc::new(ArtifactStore::open(&wide.root).expect("shared store must open"));
let narrow = ResourcesService::new(
wide.registry.clone(),
store,
ResourceLimits::uniform(8).expect("lower limit must stay inside the ceiling"),
);
let error = narrow
.publish(super::PublishResource {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
resource_id: created.resource_id.clone(),
expected_updated_at: Some(card.resource.updated_at),
})
.await
.expect_err("a stored content above the configured limit must be refused");
assert_eq!(error, ResourceError::ContentTooLarge);
let drafts = accepted_drafts(&Harness {
service: wide.service,
registry: wide.registry,
})
.await;
assert_eq!(drafts.len(), 1, "a refused publication must keep the Draft");
assert_eq!(
drafts[0].resource.status,
crank_core::resource::ResourceStatus::Draft
);
}
@@ -0,0 +1,126 @@
//! F5 (TL run105): диагностика рукописного фрагментированного запроса не несёт
//! session/CSRF-значения.
//!
//! Контроль **положительный и синтетический**: маркерные значения заведомо отправляются
//! реальным сокетным запросом, поэтому их отсутствие в подписи — результат редактирования,
//! а не пустая строка. Одновременно проверяется, что подпись сохраняет метод, путь,
//! `Transfer-Encoding` и статус: иначе отказ не отличить от ошибки харнесса.
//!
//! Размещение: in-crate сервисные тесты (`tests/**`) — корневой фикстур-файл ограничен
//! health-правилом 1000 строк, а сам контроль проверяет публичные (crate-private) шлюзы
//! composition-стенда.
//!
//! Канонический прогон: `cargo test -p admin-api --lib
//! service::resources::tests::diagnostics -- --test-threads=1`.
use serial_test::serial;
use crate::app::resource_test_support::{
GuardHarness, RawHttpResponse, RawSession, redact_sensitive_headers, send_chunked_multipart,
};
const MARKER_COOKIE: &str = "crank_session=C36-F5-MARKER-cookie";
const MARKER_CSRF: &str = "C36-F5-MARKER-csrf";
const MARKER_REPLY_COOKIE: &str = "C36-F5-MARKER-reply";
/// Прямой контроль шлюза: значения заменяются маркером, структура головы сохраняется.
#[test]
fn story36_at06_header_redaction_drops_sensitive_values_and_keeps_context() {
let request_head = format!(
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1\r\n\
Host: 127.0.0.1:1234\r\n\
Cookie: {MARKER_COOKIE}\r\n\
X-CSRF-Token: {MARKER_CSRF}\r\n\
Content-Type: multipart/form-data; boundary=story36\r\n\
Transfer-Encoding: chunked\r\n\
Connection: close\r\n\r\n"
);
let response_head = format!(
"HTTP/1.1 400 Bad Request\r\n\
content-type: application/json\r\n\
set-cookie: {MARKER_REPLY_COOKIE}; Path=/\r\n\r\n"
);
let response = RawHttpResponse {
status: 400,
head: redact_sensitive_headers(&response_head),
body: "{\"error\":{\"code\":\"validation_error\"}}".to_owned(),
request_head: redact_sensitive_headers(&request_head),
write_error: None,
read_error: None,
};
let signature = response.signature();
for marker in [MARKER_COOKIE, MARKER_CSRF, MARKER_REPLY_COOKIE] {
assert!(
!signature.contains(marker),
"raw session/CSRF values must never reach the diagnostics: marker `{marker}` \
present in `{signature}`"
);
}
for kept in [
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1",
"Cookie: <redacted-sensitive-header>",
"X-CSRF-Token: <redacted-sensitive-header>",
"Transfer-Encoding: chunked",
"status=400",
"400 Bad Request",
] {
assert!(
signature.contains(kept),
"redaction must keep the diagnostic context `{kept}`: {signature}"
);
}
}
/// Тот же контроль на **реальном** сокетном пути: маркерная сессия действительно
/// отправляется настоящим chunked-запросом, а сохранённая диагностика обязана быть
/// отредактированной (значения живут только в момент отправки).
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_real_chunked_diagnostics_carry_no_session_or_csrf_values() {
let harness = GuardHarness::spawn("redaction").await;
let session = RawSession {
cookie: MARKER_COOKIE.to_owned(),
csrf: MARKER_CSRF.to_owned(),
};
let boundary = "story36f5marker";
let body = format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n{{}}\r\n\
--{boundary}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"d.txt\"\r\n\r\n\
marker payload without a closing boundary"
);
let chunks = vec![body.into_bytes()];
let response = send_chunked_multipart(
harness.addr,
"/api/admin/workspaces/ws_default/resources",
&session,
boundary,
&chunks,
)
.await;
let signature = response.signature();
for marker in [MARKER_COOKIE, MARKER_CSRF] {
assert!(
!signature.contains(marker),
"a real chunked request must not store raw credentials: marker `{marker}` present \
in `{signature}`"
);
}
assert!(
!signature.contains("crank_session="),
"no stored head may carry a session value: {signature}"
);
for kept in [
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1",
"Cookie: <redacted-sensitive-header>",
"X-CSRF-Token: <redacted-sensitive-header>",
"Transfer-Encoding: chunked",
] {
assert!(
signature.contains(kept),
"the refused request must stay distinguishable from a harness error: `{kept}` \
missing in `{signature}`"
);
}
}
@@ -0,0 +1,170 @@
//! Story 3.7 / AC03: детерминированный race «публикация vs Draft update».
//!
//! TL CODE-REVIEW (F4/race): существующие registry-тесты доказывают последовательный
//! mismatch и stale-replay, но не само чередование. Здесь используется уже принятый
//! BUILD-only шов `interleave::fire_after_resolve`: обновление того же Resource
//! исполняется ровно один раз **после** разрешения версии/байт и **до** commit
//! публикации. Ожидание: публикация отвергается как stale (HTTP 428 по существующему
//! mapping), строк публикации/owning-ссылки не появляется, CAS не сдвигается, а
//! обновлённый Draft остаётся сохранённым. Новый harness не создаётся.
use super::super::{DraftMetadata, NewDraft, PublishResource, UpdateDraft, interleave};
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use crank_core::resource::{ResourceError, ResourceStatus};
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery};
use serial_test::serial;
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const PUBLISHED_CANDIDATE: &[u8] = b"{\"publication_race\":\"v1-candidate\"}";
const LATER_EDIT: &[u8] = b"{\"publication_race\":\"v2-after-update\"}";
fn text_draft(bytes: &[u8]) -> NewDraft {
NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: "crank://story37/publication-race".to_owned(),
name: "publication_race".to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
#[tokio::test]
#[serial]
async fn story37_at03_concurrent_draft_update_refuses_publication_without_writes() {
let harness = ResourceServiceHarness::spawn("story37_publication_race", LIMIT).await;
let service = harness.service.clone();
let workspace = WorkspaceId::new(WORKSPACE_ID);
let created = service
.create_draft(text_draft(PUBLISHED_CANDIDATE))
.await
.expect("the seed draft must be created");
let resource_id = created.resource_id;
let card = service
.card(&workspace, &resource_id)
.await
.expect("the seed card must be readable");
assert_eq!(card.version.version, 1);
let precondition = card.resource.updated_at.clone();
// Настоящее обновление того же Resource, исполняемое ровно один раз в окне
// «после разрешения версии/байт, до commit публикации».
let updating = service.clone();
let updated_id = resource_id.clone();
let updated_workspace = workspace.clone();
let update_precondition = precondition.clone();
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<(u32, String), String>>();
interleave::install_after_resolve(Box::new(move || {
Box::pin(async move {
let outcome = updating
.update_draft(UpdateDraft {
workspace_id: updated_workspace,
resource_id: updated_id,
description: "edited during publication".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: Some(update_precondition),
immutable_fields: Vec::new(),
bytes: LATER_EDIT.to_vec(),
})
.await
.map(|card| (card.version.version, card.resource.updated_at))
.map_err(|error| error.to_string());
let _ = sender.send(outcome);
})
}));
let error = service
.publish(PublishResource {
workspace_id: workspace.clone(),
resource_id: resource_id.clone(),
expected_updated_at: Some(precondition.clone()),
})
.await
.expect_err("a publication interleaved with a Draft update must be refused");
assert_eq!(
error,
ResourceError::Stale,
"the interleaved update must surface as the accepted stale taxonomy (428 at HTTP)"
);
let concurrent = receiver
.await
.expect("the interleaved update must report its outcome");
let (updated_version, updated_at) =
concurrent.expect("the interleaved Draft update must really be accepted");
assert_eq!(
updated_version, 2,
"the concurrent update must have produced a new Draft version"
);
// Отказ публикации не сдвинул CAS: карточка осталась той, которую записал update.
let after = service
.card(&workspace, &resource_id)
.await
.expect("the card must be readable after the refused publication");
assert_eq!(
after.resource.updated_at, updated_at,
"the refused publication must not advance the card revision"
);
assert_eq!(
after.version.version, 2,
"the updated Draft must stay the current version"
);
assert_eq!(
after.resource.status,
ResourceStatus::Draft,
"the card must stay a Draft after the refused publication"
);
assert_eq!(
service
.read_content(&workspace, &resource_id)
.await
.expect("the updated Draft must stay readable"),
LATER_EDIT.to_vec(),
"the updated Draft bytes must survive the refused publication"
);
// Ни одной Published Version не появилось (ни для прежней, ни для новой версии).
for version in [1, 2] {
let resolution = harness
.registry
.resolve_resource_publication(WORKSPACE_ID, &resource_id, version)
.await
.expect_err("a refused publication must not create a Published Version");
assert_eq!(
resolution,
ResourceError::NotFound,
"no publication row/owning source must exist for version {version}"
);
}
// Владение: единственная активная owning-ссылка — новая Draft-версия; publication
// source не вставлен отказом.
let page = harness
.registry
.list_artifact_sources(ListArtifactSourcesQuery {
workspace_id: &workspace,
cursor: None,
limit: 100,
})
.await
.expect("artifact sources must be readable");
let active: Vec<_> = page
.items
.iter()
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
.collect();
assert_eq!(
active.len(),
1,
"only the current Draft keeps an active owning reference: {active:?}"
);
}
@@ -0,0 +1,241 @@
//! R-D (P5): где именно срабатывает защита чтения Resource и как это наблюдается
//! счётчиками физических точек (AT-3.6-03/05).
//!
//! Источник: FINAL-DISPOSITION run99 (P5), TL review run103:35 (R-D): «однофакторная
//! integrity-матрица на durable seed-ах, metadata-denial до чтения против физического
//! отказа, который чтение уже выполнил».
//!
//! Наблюдения: `counters::artifact_reads` (реальная точка физического чтения) и точные
//! bytes/идентичность артефакта. SQL-мутации и файловые наблюдения живут в composition
//! fixture `crate::app::resource_test_support`, а не в сервисном коде.
//!
//! Канонический прогон: `cargo test -p admin-api --lib
//! service::resources::tests::read_integrity -- --test-threads=1`.
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
use crank_core::WorkspaceId;
use crank_registry::PostgresRegistry;
use serial_test::serial;
use super::super::{DraftMetadata, NewDraft, ResourcesService};
use super::counters;
use crate::app::resource_test_support::{
ArtifactIdentity, ArtifactMutation, ResourceServiceHarness, apply_artifact_mutation,
artifact_files, observe_artifact_identity, restore_artifact_identity,
};
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const CONTENT: &[u8] = b"integrity payload";
struct Harness {
service: ResourcesService,
registry: PostgresRegistry,
root: PathBuf,
}
/// Стенд с **известным** приватным artifact root: физический отказ можно наблюдать
/// только там, где тест владеет корнем хранилища (production-конструктор его скрывает).
///
/// Драйвер, миграция и сборка store/service выполняются в composition fixture
/// `crate::app::resource_test_support::ResourceServiceHarness` — сервисный тест-модуль
/// не создаёт SQL-адаптер и не держит raw pool (TL review run105 F3).
async fn harness(name: &str) -> Harness {
let ResourceServiceHarness {
service,
registry,
root,
} = ResourceServiceHarness::spawn(name, LIMIT).await;
Harness {
service,
registry,
root,
}
}
async fn seed(harness: &Harness, suffix: &str) -> crank_core::ids::ResourceId {
harness
.service
.create_draft(NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: format!("crank://integrity/{suffix}"),
name: format!("integrity_{suffix}"),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: CONTENT.to_vec(),
})
.await
.expect("the durable seed draft must be created")
.resource_id
}
/// Физические файлы содержимого (один blob на seed).
fn blob_files(harness: &Harness) -> Vec<PathBuf> {
let files = artifact_files(&harness.root);
assert_eq!(
files.len(),
1,
"exactly one durable blob is expected under the private root: {files:?}"
);
files
}
/// Запись файла содержимого в форме, которую принимает store (регулярный файл
/// владельца, одна ссылка, без прав записи) — создаёт файл заново при необходимости.
fn install_blob(path: &PathBuf, bytes: &[u8]) {
if path.exists() {
fs::remove_file(path).expect("the durable blob must be removable for the fault case");
}
fs::write(path, bytes).expect("the replacement blob must be writable");
fs::set_permissions(path, fs::Permissions::from_mode(0o444))
.expect("the replacement blob must lose its write bits");
}
#[tokio::test]
#[serial]
async fn story36_at03_metadata_denial_refuses_before_any_physical_read() {
let harness = harness("metadata_denial").await;
let resource_id = seed(&harness, "metadata").await;
// Позитивный контроль: durable seed действительно читается точными bytes.
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.expect("the durable seed must be readable"),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
let identity: ArtifactIdentity =
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await;
let mut observations: Vec<String> = Vec::new();
let mut mismatches: Vec<String> = Vec::new();
for mutation in ArtifactMutation::ALL {
let label = mutation.label();
apply_artifact_mutation(harness.registry.pool(), mutation)
.await
.unwrap_or_else(|error| panic!("mutation `{label}` must apply: {error}"));
assert_ne!(
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
identity,
"mutation `{label}` must really change the observed identity"
);
counters::reset();
let refusal = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let reads = counters::artifact_reads();
let observed = match &refusal {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// Metadata-сверка обязана отсечь рассинхронизацию ДО физического чтения.
if refusal.is_err() && observed == "resource_artifact_integrity" && reads == 0 {
observations.push(format!("{label}: {observed}, physical reads={reads}"));
} else {
mismatches.push(format!(
"{label}: expected resource_artifact_integrity with reads=0, observed \
{observed} with reads={reads}"
));
observations.push(format!("{label}: {observed}, physical reads={reads}"));
}
restore_artifact_identity(harness.registry.pool(), WORKSPACE_ID, &identity)
.await
.unwrap_or_else(|error| panic!("restoration after `{label}` must apply: {error}"));
assert_eq!(
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
identity,
"mutation `{label}` must be restored byte-exactly"
);
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.unwrap_or_else(|error| panic!("restore after `{label}` must resolve: {error:?}")),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
}
assert!(
mismatches.is_empty(),
"every metadata mismatch must be refused before the physical read point; observations: \
{observations:?}; mismatches: {mismatches:?}"
);
}
#[tokio::test]
#[serial]
async fn story36_at03_physical_failure_reads_once_and_returns_no_bytes() {
let harness = harness("physical_failure").await;
let resource_id = seed(&harness, "physical").await;
let mut files = blob_files(&harness);
let blob = files.remove(0);
// (1) Содержимое физически отсутствует: metadata-сверка проходит, чтение выполняется
// и падает — счётчик чтения равен 1, bytes не возвращаются.
fs::remove_file(&blob).expect("the durable blob must be removable");
counters::reset();
let missing = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let missing_reads = counters::artifact_reads();
let missing_code = match &missing {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// (2) Содержимое подменено на другую строку той же длины: чтение тоже выполняется,
// но расхождение digest обязано быть отказом без bytes.
install_blob(&blob, b"integrity payloaX");
counters::reset();
let corrupted = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let corrupted_reads = counters::artifact_reads();
let corrupted_code = match &corrupted {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// (3) Положительный контроль: возврат точных bytes восстанавливает чтение.
install_blob(&blob, CONTENT);
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.expect("the restored blob must be readable again"),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
assert!(
missing.is_err() && missing_code == "resource_artifact_integrity" && missing_reads == 1,
"a physically missing blob must fail after the read point with no bytes; observed \
{missing_code} with reads={missing_reads}"
);
assert!(
corrupted.is_err()
&& corrupted_code == "resource_artifact_integrity"
&& corrupted_reads == 1,
"a physically corrupted blob must fail closed after the read point with no bytes; \
observed {corrupted_code} with reads={corrupted_reads}"
);
}
@@ -0,0 +1,158 @@
//! P3 (AT-3.6-03/04): preview отдаёт metadata и bytes **одного** разрешения версии.
//!
//! Источник: CORRECTION-PACKAGE P3 (TL F05), SPEC v4 §3 D-6/D-19. Проверка
//! детерминированная: приватная точка `interleave` внутри `load_content` исполняет
//! настоящий concurrent update того же Resource в той же PG-схеме, поэтому окно
//! «между источником metadata и физическим чтением bytes» наблюдаемо без гонки.
//!
//! Ожидание одного снимка: версия/размер/MIME/digest/text в ответе относятся к
//! одной и той же версии, а не к metadata версии N и bytes версии N+1 (TL F05).
use super::super::{DraftMetadata, NewDraft, UpdateDraft, interleave};
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use serde_json::Value;
use serial_test::serial;
use sha2::{Digest, Sha256};
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const FIRST: &[u8] = b"{\"snapshot\":\"first\"}";
const SECOND: &[u8] = b"{\"snapshot\":\"second\",\"n\":2}";
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn text_draft(bytes: &[u8]) -> NewDraft {
NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: "crank://snapshot/draft".to_owned(),
name: "snapshot_draft".to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
#[tokio::test]
#[serial]
async fn story36_at04_preview_serves_one_pinned_resolution_snapshot() {
let harness = ResourceServiceHarness::spawn("snapshot", LIMIT).await;
let service = harness.service.clone();
let workspace = WorkspaceId::new(WORKSPACE_ID);
let created = service
.create_draft(text_draft(FIRST))
.await
.expect("the seed draft must be created");
let resource_id = created.resource_id;
let card = service
.card(&workspace, &resource_id)
.await
.expect("the seed card must be readable");
let precondition = card.resource.updated_at.clone();
// Controlled concurrent update того же Resource и той же схемы: шаг исполняется
// ровно один раз на приватной точке чередования.
let updating = service.clone();
let updated_id = resource_id.clone();
let updated_workspace = workspace.clone();
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<u32, String>>();
interleave::install(Box::new(move || {
Box::pin(async move {
let outcome = updating
.update_draft(UpdateDraft {
workspace_id: updated_workspace,
resource_id: updated_id,
description: "updated during interleave".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: Some(precondition),
immutable_fields: Vec::new(),
bytes: SECOND.to_vec(),
})
.await
.map(|card| card.version.version)
.map_err(|error| error.to_string());
let _ = sender.send(outcome);
})
}));
let preview = service
.preview(&workspace, &resource_id)
.await
.expect("preview must succeed");
let concurrent = receiver
.await
.expect("the interleave step must report its outcome");
// Положительный контроль чередования: одновременный update действительно принят,
// поэтому «один снимок» ниже — наблюдение, а не следствие того, что ничего не менялось.
assert_eq!(
concurrent,
Ok(2),
"the interleaved update must be accepted before the bytes of this response are read"
);
let digest_first = sha256_hex(FIRST);
let digest_second = sha256_hex(SECOND);
let expected_text = std::str::from_utf8(SECOND)
.expect("the fixture content must be UTF-8")
.to_owned();
let observed = format!(
"version={} digest={} size={} mime={} text={:?}",
preview.version.version,
preview.version.digest,
preview.version.size_bytes,
preview.version.mime_type,
preview.preview.text
);
// Все поля относятся к одному снимку: той версии, которую разрешил этот ответ.
assert_eq!(preview.version.version, 2, "single snapshot: {observed}");
assert_eq!(
preview.version.digest, digest_second,
"single snapshot: {observed}"
);
assert_eq!(
preview.version.size_bytes,
i64::try_from(SECOND.len()).expect("fixture size must fit i64"),
"single snapshot: {observed}"
);
assert_eq!(
preview.version.mime_type, "text/plain",
"single snapshot: {observed}"
);
assert_eq!(
preview.preview.text.as_deref(),
Some(expected_text.as_str()),
"single snapshot: the preview text must be the bytes of the same version: {observed}"
);
// Расхождение с metadata предыдущей версии — то, что было дефектом (материализация).
assert_ne!(
preview.version.digest, digest_first,
"the snapshot must not fall back to the pre-interleave version: {observed}"
);
assert!(
!preview.version.digest.is_empty() && preview.version.digest.len() == 64,
"the digest must be the pinned version digest, not a placeholder: {observed}"
);
assert_eq!(preview.resource.name, "snapshot_draft");
assert_eq!(preview.resource.uri, "crank://snapshot/draft");
assert_eq!(preview.resource.current_draft_version, 2);
let _: Value = serde_json::to_value(&preview).expect("the preview must serialize");
// Тот же Resource после ответа отдаёт содержимое новой версии: update настоящий,
// а не «виртуальный» только внутри тестового шага.
let served = service
.read_content(&workspace, &resource_id)
.await
.expect("content must be readable after the interleave");
assert_eq!(served, SECOND.to_vec());
}
@@ -0,0 +1,175 @@
//! F6 (TL run109 CODE-REVIEW): сохранность pinned-версии, когда обновление того же
//! Resource приходит **после** разрешения версии.
//!
//! Источник: CODE-REVIEW run109 F6. Существующая проверка `snapshot.rs` исполняет
//! чередование **до** `resolve_current_resource_version`, поэтому оба повторных
//! разрешения увидели бы уже новую версию и регресс «два разрешения в одном
//! ответе» такой тест не поймал бы. Здесь шаг стоит после разрешения и до
//! физического чтения байт: он либо ничего не меняет в наблюдаемом ответе
//! (honest existing GREEN для корректного кода), либо доказывает, что metadata и
//! bytes взяты из разных разрешений.
//!
//! Тест намеренно не требует RED: production-ветка уже обслуживает ответ одним
//! pinned-разрешением, а новое наблюдение — это preservation-проверка.
use super::super::{DraftMetadata, NewDraft, UpdateDraft, interleave};
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use serial_test::serial;
use sha2::{Digest, Sha256};
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const FIRST: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":1}";
const SECOND: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":2,\"late\":true}";
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn text_draft(bytes: &[u8]) -> NewDraft {
NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: "crank://snapshot/after-resolve".to_owned(),
name: "snapshot_after_resolve".to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
#[tokio::test]
#[serial]
async fn story36_at04_preview_stays_pinned_when_the_update_lands_after_resolution() {
let harness = ResourceServiceHarness::spawn("snapshot_after_resolve", LIMIT).await;
let service = harness.service.clone();
let workspace = WorkspaceId::new(WORKSPACE_ID);
let created = service
.create_draft(text_draft(FIRST))
.await
.expect("the seed draft must be created");
let resource_id = created.resource_id;
let precondition = service
.card(&workspace, &resource_id)
.await
.expect("the seed card must be readable")
.resource
.updated_at
.clone();
// Настоящее обновление того же Resource и той же PG-схемы, исполняемое ровно
// один раз в окне «после разрешения версии, до физического чтения байт».
let updating = service.clone();
let updated_id = resource_id.clone();
let updated_workspace = workspace.clone();
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<u32, String>>();
interleave::install_after_resolve(Box::new(move || {
Box::pin(async move {
let outcome = updating
.update_draft(UpdateDraft {
workspace_id: updated_workspace,
resource_id: updated_id,
description: "updated after resolution".to_owned(),
// MIME тоже меняется в рамках того же kind, поэтому ответ обязан
// остаться на MIME разрешённой версии, а не поздней (F6).
mime_type: "text/markdown".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: Some(precondition),
immutable_fields: Vec::new(),
bytes: SECOND.to_vec(),
})
.await
.map(|card| card.version.version)
.map_err(|error| error.to_string());
let _ = sender.send(outcome);
})
}));
let preview = service
.preview(&workspace, &resource_id)
.await
.expect("preview must succeed");
let concurrent = receiver
.await
.expect("the after-resolution step must report its outcome");
// Положительный контроль: позднее обновление действительно принято, поэтому
// «версия 1 в ответе» — наблюдение, а не следствие неудавшегося шага.
assert_eq!(
concurrent,
Ok(2),
"the update that landed after the resolution must really be accepted"
);
let digest_first = sha256_hex(FIRST);
let digest_second = sha256_hex(SECOND);
let expected_text = std::str::from_utf8(FIRST)
.expect("the fixture content must be UTF-8")
.to_owned();
let observed = format!(
"version={} digest={} size={} mime={} text={:?}",
preview.version.version,
preview.version.digest,
preview.version.size_bytes,
preview.version.mime_type,
preview.preview.text
);
// Весь ответ относится к версии, разрешённой до позднего обновления.
assert_eq!(
preview.version.version, 1,
"the answer must stay pinned to the version resolved before the late update: {observed}"
);
assert_eq!(
preview.version.digest, digest_first,
"the digest must belong to the resolved version: {observed}"
);
assert_eq!(
preview.version.size_bytes,
i64::try_from(FIRST.len()).expect("fixture size must fit i64"),
"the size must belong to the resolved version: {observed}"
);
assert_eq!(
preview.preview.text.as_deref(),
Some(expected_text.as_str()),
"the preview text must be the bytes of the resolved version: {observed}"
);
// Явный MIME-оракул: поздняя правка меняет именно MIME, поэтому ответ обязан
// показывать MIME разрешённой версии (F6).
assert_eq!(
preview.version.mime_type, "text/plain",
"the MIME must belong to the resolved version, not to the late update: {observed}"
);
assert_ne!(
preview.version.digest, digest_second,
"the response must not mix in bytes of the later version: {observed}"
);
assert_eq!(
preview.resource.current_draft_version, 1,
"the card metadata of this answer must not be re-read after the late update: {observed}"
);
// И валидный последующий запрос уже отдаёт версию 2 целиком: обновление настоящее.
let after = service
.card(&workspace, &resource_id)
.await
.expect("the card must be readable after the late update");
assert_eq!(after.version.version, 2, "the late update must be durable");
assert_eq!(after.version.digest, digest_second);
assert_eq!(
after.version.mime_type, "text/markdown",
"the late update's own MIME must be durable as well"
);
assert_eq!(
service
.read_content(&workspace, &resource_id)
.await
.expect("content must be readable after the late update"),
SECOND.to_vec()
);
}
@@ -0,0 +1,173 @@
//! Wire-view Resource (Story 3.6–3.10), вынесены из `service/resources.rs` под
//! лимит rust-code-health. Здесь только сериализация и снимок уже прочитанной
//! строки; второго чтения Resource или bytes не появляется.
use super::*;
/// Ответ публикации: существующая карточка Resource + immutable Published Version.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PublishedVersionResponse {
pub resource: ResourceCardResponse,
pub published_version: PublishedVersionView,
}
/// Публичные metadata точной Published Version (TL decision 2/3): ровно девять полей,
/// без owning-ссылки, хранилища, path и raw upload filename.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PublishedVersionView {
pub version: u32,
pub uri: String,
pub name: String,
pub description: String,
pub kind: String,
pub mime_type: String,
pub size_bytes: i64,
pub digest: String,
pub sensitivity: String,
/// Story 3.10: снимок определения шаблона; у static версии отсутствует.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<template::TemplateSourceView>,
}
impl PublishedVersionView {
pub(super) fn from_record(record: &ResourcePublicationRecord) -> Self {
Self {
version: record.version,
uri: record.uri.clone(),
name: record.name.clone(),
description: record.description.clone(),
kind: record.kind.clone(),
mime_type: record.mime_type.clone(),
size_bytes: record.size_bytes,
digest: record.digest.clone(),
sensitivity: record.sensitivity.clone(),
source: None,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourceListResponse {
pub items: Vec<ResourceCardResponse>,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourceCardResponse {
pub resource: ResourceView,
pub version: ResourceVersionView,
pub findings: Vec<PreviewFinding>,
/// Story 3.10: additive source-блок; у static Resource поле отсутствует.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<template::TemplateSourceView>,
}
impl ResourceCardResponse {
pub(super) fn from_record(record: &ResourceDraftRecord) -> Self {
Self {
resource: ResourceView::from_record(record),
version: ResourceVersionView::from_record(&record.version),
findings: Vec::new(),
source: None,
}
}
pub(super) fn kind(&self) -> Result<ResourceKind, ResourceError> {
parse_kind(&self.resource.kind)
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourcePreviewResponse {
pub resource: ResourceView,
pub version: ResourceVersionView,
pub findings: Vec<PreviewFinding>,
pub preview: ResourcePreviewView,
/// Story 3.10: template source view того же снимка; у static Resource отсутствует.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<template::TemplateSourceView>,
}
/// Безопасный finding preview: только стабильный код и поле, без bytes содержимого,
/// совпавшего фрагмента и цели `include:`.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct PreviewFinding {
pub code: &'static str,
pub field: &'static str,
}
impl PreviewFinding {
pub(super) fn from_error(error: &ResourceError) -> Self {
Self {
code: error.code(),
field: error.field().unwrap_or("content"),
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourcePreviewView {
/// Ровно сохранённые bytes как строка; `null` для kind=binary (D-6).
pub text: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourceView {
pub resource_id: String,
pub uri: String,
pub name: String,
pub description: String,
/// Wire-значение kind (`text`|`json`|`binary`).
pub kind: String,
pub status: crank_core::resource::ResourceStatus,
pub current_draft_version: u32,
/// Точная последняя Published версия (discovery-указатель), `null` если публикаций нет.
pub latest_published_version: Option<u32>,
pub created_at: String,
pub updated_at: String,
}
impl ResourceView {
pub(super) fn from_record(record: &ResourceDraftRecord) -> Self {
Self {
resource_id: record.resource.resource_id.as_str().to_owned(),
uri: record.resource.uri.clone(),
name: record.resource.name.clone(),
description: record.resource.description.clone(),
kind: record.resource.kind.clone(),
status: record.resource.status,
current_draft_version: record.resource.current_draft_version,
latest_published_version: record.resource.latest_published_version,
created_at: format_timestamp(record.resource.created_at),
updated_at: format_timestamp(record.resource.updated_at),
}
}
}
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ResourceVersionView {
pub version: u32,
/// Wire-значение kind версии (`text`|`json`|`binary`).
pub kind: String,
pub mime_type: String,
pub size_bytes: i64,
pub digest: String,
/// Wire-значение sensitivity (`public`|`internal`|`secret`).
pub sensitivity: String,
pub created_at: String,
pub superseded_at: Option<String>,
}
impl ResourceVersionView {
pub(super) fn from_record(record: &ResourceVersionRecord) -> Self {
Self {
version: record.version,
kind: record.kind.clone(),
mime_type: record.mime_type.clone(),
size_bytes: record.size_bytes,
digest: record.digest.clone(),
sensitivity: record.sensitivity.clone(),
created_at: format_timestamp(record.created_at),
superseded_at: record.superseded_at.map(format_timestamp),
}
}
}