Files
crank/crates/crank-core/src/resource/template.rs
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08:22 +00:00

611 lines
23 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Story 3.10 (FR-16) — REST-backed Resource template definition.
//!
//! Шаблон не исполняет REST: он фиксирует точную Published версию Operation,
//! форму собственного `crank://` URI, typed параметры, cache/failure policy.
//! Здесь живёт только доменный контракт (типы, грамматика, пределы, коды
//! findings); типизация `schema` через `crank_schema` и сверка с pinned
//! Operation Version выполняются в admin-api, где этот wire-тип уже доступен.
//!
//! Структурная проверка (`parse`) возвращает точное поле отказа: wire-код
//! `resource_source_invalid` назначает admin-api.
//!
//! Инварианты безопасности:
//! - `uri_template` — отдельный `crank://` URI, authority всегда литерал;
//! host/scheme/query/fragment/userinfo/port невозможны;
//! - произвольные URL/inline request/headers/body в определении отсутствуют;
//! - cache scope фиксирован сервером (`workspace_agent_auth`), клиент его не задаёт;
//! - failure outcome — только `error` (никакого fallback-содержимого).
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::resource::{MAX_RESOURCE_URI_BYTES, RESOURCE_STORAGE_CEILING};
/// Верхняя граница cache TTL шаблона (24 h): предел устаревания данных заказа.
pub const MAX_TEMPLATE_CACHE_TTL_MS: u64 = 24 * 60 * 60 * 1000;
/// Предел рендеренного ответа = существующий storage ceiling (второй лимит не вводится).
pub const MAX_TEMPLATE_CACHE_BYTES: u64 = RESOURCE_STORAGE_CEILING as u64;
/// Нормализованный (серверный) cache scope: workspace + Agent + auth/credential identity.
pub const TEMPLATE_CACHE_SCOPE: &str = "workspace_agent_auth";
/// Та же граница, что у static URI (D-10): шаблон не длиннее обычного Resource URI.
pub const MAX_TEMPLATE_URI_BYTES: usize = MAX_RESOURCE_URI_BYTES;
/// Верхняя граница идентификатора Operation в ссылке шаблона.
pub const MAX_TEMPLATE_OPERATION_ID_BYTES: usize = 128;
const URI_PREFIX: &str = "crank://";
const SOURCE_FIELDS: [&str; 6] = [
"operation_id",
"operation_version",
"uri_template",
"parameters",
"cache",
"failure",
];
const PARAMETER_FIELDS: [&str; 3] = ["name", "input_path", "schema"];
const CACHE_FIELDS: [&str; 3] = ["ttl_ms", "vary", "max_bytes"];
/// Сохранённое определение шаблона. Порядок полей фиксирован, поэтому
/// канонический JSON и digest определения детерминированы.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TemplateSource {
pub operation_id: String,
pub operation_version: u32,
pub uri_template: String,
pub parameters: Vec<TemplateParameter>,
pub cache: TemplateCache,
pub failure: TemplateFailure,
}
/// Параметр шаблона: имя placeholder, адрес поля pinned `input_schema` и typed schema.
/// `schema` остаётся каноническим JSON: типизация выполняется shared `crank_schema`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TemplateParameter {
pub name: String,
pub input_path: String,
pub schema: Value,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TemplateCache {
pub ttl_ms: u64,
pub vary: Vec<String>,
pub max_bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TemplateFailure {
pub outcome: TemplateFailureOutcome,
}
/// Только `error`: arbitrary fallback-содержимого у шаблона нет (fail closed).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TemplateFailureOutcome {
Error,
}
/// Структурный отказ определения: точное поле, которое называет wire-ответ.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TemplateSourceError {
field: &'static str,
}
impl TemplateSourceError {
const fn new(field: &'static str) -> Self {
Self { field }
}
pub fn field(&self) -> &'static str {
self.field
}
}
impl TemplateSource {
/// Структурный разбор `metadata.source`. Любой неизвестный ключ (включая
/// URL/inline request/headers/body и расширяющие cache scope поля) — отказ.
pub fn parse(value: &Value) -> Result<Self, TemplateSourceError> {
let object = value
.as_object()
.ok_or_else(|| TemplateSourceError::new("source"))?;
for key in object.keys() {
if !SOURCE_FIELDS.contains(&key.as_str()) {
return Err(TemplateSourceError::new(top_level_unknown_field(key)));
}
}
let operation_id = object
.get("operation_id")
.and_then(Value::as_str)
.filter(|value| !value.is_empty() && value.len() <= MAX_TEMPLATE_OPERATION_ID_BYTES)
.ok_or_else(|| TemplateSourceError::new("source.operation_id"))?
.to_owned();
let operation_version = object
.get("operation_version")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.filter(|value| *value >= 1)
.ok_or_else(|| TemplateSourceError::new("source.operation_version"))?;
let uri_template = object
.get("uri_template")
.and_then(Value::as_str)
.ok_or_else(|| TemplateSourceError::new("source.uri_template"))?;
parse_uri_template(uri_template)
.map_err(|_| TemplateSourceError::new("source.uri_template"))?;
let parameters = parse_parameters(object.get("parameters"))?;
let cache = parse_cache(object.get("cache"))?;
let failure = parse_failure(object.get("failure"))?;
Ok(Self {
operation_id,
operation_version,
uri_template: uri_template.to_owned(),
parameters,
cache,
failure,
})
}
/// Имена параметров шаблона (для сверки с placeholders/vary).
pub fn parameter_names(&self) -> BTreeSet<&str> {
self.parameters
.iter()
.map(|parameter| parameter.name.as_str())
.collect()
}
}
/// Cache policy findings (AC4): TTL/size bounded exported constants, `vary`
/// обязан покрывать каждый параметр ровно один раз и не содержать чужих имён.
/// Чистая функция: same rules для preview и publish, без обращения к Operation.
pub fn cache_policy_findings(
cache: &TemplateCache,
parameter_names: &BTreeSet<&str>,
) -> Vec<TemplateFinding> {
let mut findings = Vec::new();
if cache.ttl_ms == 0 || cache.ttl_ms > MAX_TEMPLATE_CACHE_TTL_MS {
findings.push(TemplateFinding::new(
TemplateFindingCode::CacheTtlInvalid,
"source.cache.ttl_ms",
));
}
if cache.max_bytes == 0 || cache.max_bytes > MAX_TEMPLATE_CACHE_BYTES {
findings.push(TemplateFinding::new(
TemplateFindingCode::CacheSizeInvalid,
"source.cache.max_bytes",
));
}
let mut seen = BTreeSet::new();
for name in &cache.vary {
if !seen.insert(name.as_str()) {
findings.push(TemplateFinding::new(
TemplateFindingCode::VaryDuplicate,
"source.cache.vary",
));
} else if !parameter_names.contains(name.as_str()) {
findings.push(TemplateFinding::new(
TemplateFindingCode::VaryUnknown,
"source.cache.vary",
));
}
}
if parameter_names.iter().any(|name| !seen.contains(name)) {
findings.push(TemplateFinding::new(
TemplateFindingCode::VaryIncomplete,
"source.cache.vary",
));
}
findings
}
fn top_level_unknown_field(key: &str) -> &'static str {
match key {
"agent_scope" => "source.agent_scope",
"auth_independent" => "source.auth_independent",
_ => "source",
}
}
fn parse_parameters(value: Option<&Value>) -> Result<Vec<TemplateParameter>, TemplateSourceError> {
let items = value
.and_then(Value::as_array)
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?;
let mut parameters = Vec::with_capacity(items.len());
for item in items {
let object = item
.as_object()
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?;
require_only_fields(object, &PARAMETER_FIELDS, "source.parameters")?;
let name = object
.get("name")
.and_then(Value::as_str)
.filter(|value| parameter_name_is_valid(value))
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
.to_owned();
let input_path = object
.get("input_path")
.and_then(Value::as_str)
.filter(|value| input_path_is_valid(value))
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
.to_owned();
let schema = object
.get("schema")
.filter(|value| value.is_object())
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
.clone();
parameters.push(TemplateParameter {
name,
input_path,
schema,
});
}
Ok(parameters)
}
fn parse_cache(value: Option<&Value>) -> Result<TemplateCache, TemplateSourceError> {
let object = value
.and_then(Value::as_object)
.ok_or_else(|| TemplateSourceError::new("source.cache"))?;
for key in object.keys() {
if !CACHE_FIELDS.contains(&key.as_str()) {
return Err(TemplateSourceError::new(cache_unknown_field(key)));
}
}
let ttl_ms = object
.get("ttl_ms")
.and_then(Value::as_u64)
.ok_or_else(|| TemplateSourceError::new("source.cache.ttl_ms"))?;
let max_bytes = object
.get("max_bytes")
.and_then(Value::as_u64)
.ok_or_else(|| TemplateSourceError::new("source.cache.max_bytes"))?;
let vary = object
.get("vary")
.and_then(Value::as_array)
.ok_or_else(|| TemplateSourceError::new("source.cache.vary"))?
.iter()
.map(|item| {
item.as_str()
.map(str::to_owned)
.ok_or_else(|| TemplateSourceError::new("source.cache.vary"))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(TemplateCache {
ttl_ms,
vary,
max_bytes,
})
}
fn cache_unknown_field(key: &str) -> &'static str {
match key {
"scope" => "source.cache.scope",
"shared" => "source.cache.shared",
"cross_workspace" => "source.cache.cross_workspace",
"agent_scope" => "source.cache.agent_scope",
"auth_independent" => "source.cache.auth_independent",
_ => "source.cache",
}
}
fn parse_failure(value: Option<&Value>) -> Result<TemplateFailure, TemplateSourceError> {
let object = value
.and_then(Value::as_object)
.ok_or_else(|| TemplateSourceError::new("source.failure"))?;
require_only_fields(object, &["outcome"], "source.failure")?;
let outcome = object
.get("outcome")
.and_then(Value::as_str)
.ok_or_else(|| TemplateSourceError::new("source.failure"))?;
if outcome != "error" {
return Err(TemplateSourceError::new("source.failure.outcome"));
}
Ok(TemplateFailure {
outcome: TemplateFailureOutcome::Error,
})
}
fn require_only_fields(
object: &Map<String, Value>,
allowed: &[&str],
field: &'static str,
) -> Result<(), TemplateSourceError> {
if object.keys().any(|key| !allowed.contains(&key.as_str())) {
return Err(TemplateSourceError::new(field));
}
Ok(())
}
/// Отказ грамматики `crank://`-шаблона (поле называет wire-ответ).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InvalidUriTemplate;
impl std::fmt::Display for InvalidUriTemplate {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("resource uri template is invalid")
}
}
impl std::error::Error for InvalidUriTemplate {}
/// Грамматика `crank://<authority>/<path>`: authority — фиксированный литерал,
/// placeholders только целым path-сегментом. Возвращает имена placeholders в порядке
/// появления. Любая другая схема/хост-инъекция/query/fragment — отказ.
pub fn parse_uri_template(value: &str) -> Result<Vec<String>, InvalidUriTemplate> {
if value.len() > MAX_TEMPLATE_URI_BYTES {
return Err(InvalidUriTemplate);
}
let rest = value.strip_prefix(URI_PREFIX).ok_or(InvalidUriTemplate)?;
if rest.contains('?') || rest.contains('#') {
return Err(InvalidUriTemplate);
}
let (authority, path) = rest.split_once('/').ok_or(InvalidUriTemplate)?;
if !authority_is_valid(authority) || path.is_empty() {
return Err(InvalidUriTemplate);
}
let mut placeholders = Vec::new();
for segment in path.split('/') {
if segment.is_empty() {
return Err(InvalidUriTemplate);
}
if segment.contains('{') || segment.contains('}') {
let name = segment
.strip_prefix('{')
.and_then(|value| value.strip_suffix('}'))
.ok_or(InvalidUriTemplate)?;
if !parameter_name_is_valid(name) {
return Err(InvalidUriTemplate);
}
placeholders.push(name.to_owned());
continue;
}
if !literal_segment_is_valid(segment) {
return Err(InvalidUriTemplate);
}
}
Ok(placeholders)
}
fn authority_is_valid(authority: &str) -> bool {
let bytes = authority.as_bytes();
if bytes.is_empty() || bytes.len() > 63 {
return false;
}
let first = bytes[0] as char;
let last = bytes[bytes.len() - 1] as char;
let edge = |value: char| value.is_ascii_lowercase() || value.is_ascii_digit();
edge(first)
&& edge(last)
&& bytes
.iter()
.all(|byte| matches!(*byte as char, 'a'..='z' | '0'..='9' | '.' | '-'))
}
fn literal_segment_is_valid(segment: &str) -> bool {
segment != ".."
&& segment
.chars()
.all(|value| value.is_ascii_alphanumeric() || matches!(value, '.' | '_' | '~' | '-'))
}
/// Имя placeholder/параметра: `[a-z][a-z0-9_]{0,63}`.
pub fn parameter_name_is_valid(value: &str) -> bool {
let mut chars = value.chars();
match chars.next() {
Some(first) if first.is_ascii_lowercase() => {}
_ => return false,
}
value.len() <= 64
&& chars.all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == '_')
}
/// `input_path` адресует поле pinned `input_schema`: `<root>.<field>[.<field>...]`.
pub fn input_path_is_valid(value: &str) -> bool {
let mut segments = value.split('.');
let root = segments.next().unwrap_or_default();
if root != "input" {
return false;
}
let mut count = 0;
for segment in segments {
if segment.is_empty()
|| !segment
.chars()
.all(|item| item.is_ascii_alphanumeric() || item == '_')
{
return false;
}
count += 1;
}
count > 0
}
/// Blocker finding публикации шаблона: стабильный код и поле.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TemplateFinding {
pub code: TemplateFindingCode,
pub field: &'static str,
}
impl TemplateFinding {
pub fn new(code: TemplateFindingCode, field: &'static str) -> Self {
Self { code, field }
}
pub fn code(&self) -> &'static str {
self.code.as_str()
}
}
/// Blocker-коды публикации/предпросмотра шаблона (wire-строки).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TemplateFindingCode {
#[serde(rename = "resource_source_not_read_safe")]
NotReadSafe,
#[serde(rename = "resource_source_parameter_unknown")]
ParameterUnknown,
#[serde(rename = "resource_source_parameter_unmapped")]
ParameterUnmapped,
#[serde(rename = "resource_source_parameter_duplicate")]
ParameterDuplicate,
#[serde(rename = "resource_source_parameter_type_mismatch")]
ParameterTypeMismatch,
#[serde(rename = "resource_source_parameter_default_invalid")]
ParameterDefaultInvalid,
#[serde(rename = "resource_source_parameter_optional_without_default")]
ParameterOptionalWithoutDefault,
#[serde(rename = "resource_source_cache_ttl_invalid")]
CacheTtlInvalid,
#[serde(rename = "resource_source_cache_size_invalid")]
CacheSizeInvalid,
#[serde(rename = "resource_source_vary_unknown")]
VaryUnknown,
#[serde(rename = "resource_source_vary_duplicate")]
VaryDuplicate,
#[serde(rename = "resource_source_vary_incomplete")]
VaryIncomplete,
}
impl TemplateFindingCode {
pub fn as_str(self) -> &'static str {
match self {
Self::NotReadSafe => "resource_source_not_read_safe",
Self::ParameterUnknown => "resource_source_parameter_unknown",
Self::ParameterUnmapped => "resource_source_parameter_unmapped",
Self::ParameterDuplicate => "resource_source_parameter_duplicate",
Self::ParameterTypeMismatch => "resource_source_parameter_type_mismatch",
Self::ParameterDefaultInvalid => "resource_source_parameter_default_invalid",
Self::ParameterOptionalWithoutDefault => {
"resource_source_parameter_optional_without_default"
}
Self::CacheTtlInvalid => "resource_source_cache_ttl_invalid",
Self::CacheSizeInvalid => "resource_source_cache_size_invalid",
Self::VaryUnknown => "resource_source_vary_unknown",
Self::VaryDuplicate => "resource_source_vary_duplicate",
Self::VaryIncomplete => "resource_source_vary_incomplete",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn valid_source() -> Value {
json!({
"operation_id": "op_demo",
"operation_version": 1,
"uri_template": "crank://orders/{order_id}",
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "format": "uuid" }
}],
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
})
}
#[test]
fn typed_source_roundtrips_and_keeps_schema_facts() {
let value = valid_source();
let parsed = TemplateSource::parse(&value).expect("valid source must parse");
assert_eq!(parsed.operation_version, 1);
assert_eq!(parsed.parameters[0].schema["format"], json!("uuid"));
let encoded = serde_json::to_value(&parsed).expect("source must serialize");
assert_eq!(
encoded, value,
"canonical definition must roundtrip without loss"
);
}
#[test]
fn unknown_fields_and_inline_request_are_denied() {
for (field, value) in [
("url", json!("https://evil.example")),
("base_url", json!("https://evil.example")),
("host", json!("evil.example")),
("method", json!("POST")),
("headers", json!({ "authorization": "x" })),
("body", json!({ "a": 1 })),
("request", json!({ "url": "https://evil.example" })),
] {
let mut source = valid_source();
source[field] = value;
let error = TemplateSource::parse(&source).expect_err("unknown field must fail");
assert_eq!(error.field(), "source", "field `{field}`");
}
let mut nested = valid_source();
nested["cache"]["headers"] = json!({ "host": "evil.example" });
assert_eq!(
TemplateSource::parse(&nested)
.expect_err("nested unknown")
.field(),
"source.cache"
);
}
#[test]
fn widening_scope_keys_are_named_in_the_rejection() {
for (key, expected) in [
("scope", "source.cache.scope"),
("shared", "source.cache.shared"),
("cross_workspace", "source.cache.cross_workspace"),
("agent_scope", "source.cache.agent_scope"),
("auth_independent", "source.cache.auth_independent"),
] {
let mut source = valid_source();
source["cache"][key] = json!(true);
assert_eq!(
TemplateSource::parse(&source)
.expect_err("widening")
.field(),
expected
);
}
let mut source = valid_source();
source["agent_scope"] = json!("any");
assert_eq!(
TemplateSource::parse(&source)
.expect_err("widening")
.field(),
"source.agent_scope"
);
}
#[test]
fn policy_constants_are_single_sourced_and_bounded() {
assert_eq!(MAX_TEMPLATE_CACHE_TTL_MS, 86_400_000);
assert_eq!(MAX_TEMPLATE_CACHE_BYTES, RESOURCE_STORAGE_CEILING as u64);
assert_eq!(TEMPLATE_CACHE_SCOPE, "workspace_agent_auth");
}
#[test]
fn uri_template_grammar_rejects_host_scheme_and_traversal() {
assert_eq!(
parse_uri_template("crank://orders/{order_id}/items/{item}"),
Ok(vec!["order_id".to_owned(), "item".to_owned()])
);
for rejected in [
"https://evil.example/orders/{order_id}",
"//evil.example/orders/{order_id}",
"crank://user@{order_id}/orders",
"crank://host:8080/orders/{order_id}",
"crank://host/orders?q={order_id}",
"crank://host/orders/{order_id}#fragment",
"crank://host/../{order_id}",
"crank://host//orders/{order_id}",
"crank://ho{st}/orders/{order_id}",
"crank://host/orders/{Order_ID}",
"crank://host/orders/{order_id",
"CRANK://host/orders/{order_id}",
] {
assert!(parse_uri_template(rejected).is_err(), "{rejected}");
}
}
}