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

+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),
}
}
}