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

+2
View File
@@ -58,6 +58,8 @@ define_id!(InvocationLogId);
define_id!(ProductEventId);
define_id!(AuditEventId);
define_id!(SecretId);
define_id!(ResourceId);
define_id!(PromptId);
#[cfg(test)]
mod tests {
+5 -2
View File
@@ -12,7 +12,10 @@ pub mod observability;
pub mod onboarding;
pub mod operation;
pub mod product_event;
pub mod prompt;
pub mod prompt_composition;
pub mod protocol;
pub mod resource;
pub mod secret;
pub mod tool_catalog;
pub mod tool_quality;
@@ -47,8 +50,8 @@ pub mod domain {
};
pub use crate::ids::{
AgentId, ApprovalRequestId, AuditEventId, AuthProfileId, DescriptorId, InvitationId,
InvocationLogId, OperationId, PlatformApiKeyId, ProductEventId, SampleId, SecretId, ToolId,
UserId, UserSessionId, WorkspaceId,
InvocationLogId, OperationId, PlatformApiKeyId, ProductEventId, ResourceId, SampleId,
SecretId, ToolId, UserId, UserSessionId, WorkspaceId,
};
pub use crate::observability::{
INVOCATION_PREVIEW_MAX_BYTES, InvocationLevel, InvocationLog, InvocationSource,
+621
View File
@@ -0,0 +1,621 @@
use std::collections::{BTreeMap, BTreeSet};
use serde::Serialize;
use serde_json::{Map, Value};
const MAX_ARGUMENTS: usize = 32;
const MAX_MESSAGES: usize = 64;
const MAX_PROMPT_DEPENDENCIES: usize = 16;
/// Upper bound of one argument value / rendered message content. Public because the MCP
/// `prompts/get` boundary reports an oversized argument separately from a type mismatch
/// (AT-3.14-02) while the renderer below stays the single validator.
pub const MAX_TEXT_BYTES: usize = 16_384;
/// Storage guard for `prompt_arguments.default_value`/`enumeration` (jsonb):
/// PostgreSQL keeps `octet_length(default_value::text) <= 16384`.
const MAX_JSON_TEXT_BYTES: usize = 16_384;
use crate::ids::PromptId;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptStatus {
Draft,
Published,
Archived,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptSensitivity {
Public,
Internal,
Secret,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptDraft {
prompt_id: PromptId,
version: u32,
status: PromptStatus,
sensitivity: PromptSensitivity,
definition: PromptDefinition,
}
/// Immutable value snapshot; its fields are private and there are no mutation APIs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PublishedPromptVersion {
prompt_id: PromptId,
version: u32,
sensitivity: PromptSensitivity,
definition: PromptDefinition,
}
impl PromptDraft {
pub fn new(
prompt_id: PromptId,
sensitivity: PromptSensitivity,
definition: PromptDefinition,
) -> Self {
Self {
prompt_id,
version: 1,
status: PromptStatus::Draft,
sensitivity,
definition,
}
}
pub fn from_parts(
prompt_id: PromptId,
version: u32,
status: PromptStatus,
sensitivity: PromptSensitivity,
definition: PromptDefinition,
) -> Result<Self, PromptError> {
if version == 0 {
return Err(PromptError::InvalidDefinition);
}
Ok(Self {
prompt_id,
version,
status,
sensitivity,
definition,
})
}
pub fn prompt_id(&self) -> &PromptId {
&self.prompt_id
}
pub fn version(&self) -> u32 {
self.version
}
pub fn status(&self) -> PromptStatus {
self.status
}
pub fn sensitivity(&self) -> PromptSensitivity {
self.sensitivity
}
pub fn definition(&self) -> &PromptDefinition {
&self.definition
}
pub fn published_snapshot(&self) -> PublishedPromptVersion {
PublishedPromptVersion {
prompt_id: self.prompt_id.clone(),
version: self.version,
sensitivity: self.sensitivity,
definition: self.definition.clone(),
}
}
}
impl PublishedPromptVersion {
pub fn prompt_id(&self) -> &PromptId {
&self.prompt_id
}
pub fn version(&self) -> u32 {
self.version
}
pub fn sensitivity(&self) -> PromptSensitivity {
self.sensitivity
}
pub fn definition(&self) -> &PromptDefinition {
&self.definition
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PromptDefinition {
name: String,
description: String,
arguments: Vec<PromptArgument>,
messages: Vec<PromptMessage>,
dependencies: Vec<PromptDependency>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PromptDependency {
pub resource_id: String,
pub version: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PromptArgument {
name: String,
kind: ArgumentKind,
required: bool,
default: Option<Value>,
enumeration: Vec<Value>,
}
impl PromptArgument {
pub fn name(&self) -> &str {
&self.name
}
pub fn kind(&self) -> ArgumentKind {
self.kind
}
pub fn required(&self) -> bool {
self.required
}
pub fn default(&self) -> Option<&Value> {
self.default.as_ref()
}
pub fn enumeration(&self) -> &[Value] {
&self.enumeration
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ArgumentKind {
String,
Number,
Integer,
Boolean,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PromptMessage {
pub role: PromptRole,
pub content: String,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub resource_refs: Vec<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptRole {
System,
User,
Assistant,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PromptError {
InvalidDefinition,
MissingArgument(String),
UnknownArgument(String),
InvalidArgument(String),
InvalidTemplate,
}
impl PromptDefinition {
pub fn name(&self) -> &str {
&self.name
}
pub fn description(&self) -> &str {
&self.description
}
pub fn arguments(&self) -> &[PromptArgument] {
&self.arguments
}
pub fn messages(&self) -> &[PromptMessage] {
&self.messages
}
pub fn dependencies(&self) -> &[PromptDependency] {
&self.dependencies
}
pub fn as_json(&self) -> Value {
let messages: Vec<Value> = self
.messages
.iter()
.map(|message| {
let mut m = serde_json::json!({
"role": match message.role {
PromptRole::System => "system",
PromptRole::User => "user",
PromptRole::Assistant => "assistant",
},
"content": message.content,
});
if !message.resource_refs.is_empty() {
m["resource_refs"] = serde_json::json!(message.resource_refs);
}
m
})
.collect();
let mut out = serde_json::json!({
"name": self.name,
"description": self.description,
"arguments": self.arguments_json(),
"messages": messages,
});
if !self.dependencies.is_empty() {
let deps: Vec<Value> = self
.dependencies
.iter()
.map(|d| serde_json::json!({"resource_id": d.resource_id, "version": d.version}))
.collect();
out["dependencies"] = Value::Array(deps);
}
out
}
/// Typed argument metadata of this definition: the single source of the MCP
/// `prompts/list` argument shape (Story 3.14) and of the admin API shape.
pub fn arguments_json(&self) -> Vec<Value> {
self.arguments
.iter()
.map(|argument| {
let mut schema = serde_json::Map::from_iter([(
"type".to_owned(),
Value::String(
match argument.kind {
ArgumentKind::String => "string",
ArgumentKind::Number => "number",
ArgumentKind::Integer => "integer",
ArgumentKind::Boolean => "boolean",
}
.to_owned(),
),
)]);
if !argument.enumeration.is_empty() {
schema.insert(
"enum".to_owned(),
Value::Array(argument.enumeration.clone()),
);
}
let mut item = serde_json::Map::from_iter([
("name".to_owned(), Value::String(argument.name.clone())),
("required".to_owned(), Value::Bool(argument.required)),
("schema".to_owned(), Value::Object(schema)),
]);
if let Some(default) = &argument.default {
item.insert("default".to_owned(), default.clone());
}
Value::Object(item)
})
.collect()
}
pub fn parse(value: &Value) -> Result<Self, PromptError> {
let o = value.as_object().ok_or(PromptError::InvalidDefinition)?;
if o.keys().any(|key| {
!matches!(
key.as_str(),
"name" | "description" | "arguments" | "messages" | "dependencies"
)
}) {
return Err(PromptError::InvalidDefinition);
}
let name = bounded_string(o.get("name"))?;
let description = bounded_string(o.get("description"))?;
let raw_args = o
.get("arguments")
.and_then(Value::as_array)
.ok_or(PromptError::InvalidDefinition)?;
let raw_msgs = o
.get("messages")
.and_then(Value::as_array)
.ok_or(PromptError::InvalidDefinition)?;
if raw_args.len() > MAX_ARGUMENTS || raw_msgs.is_empty() || raw_msgs.len() > MAX_MESSAGES {
return Err(PromptError::InvalidDefinition);
}
// Parse exact pinned dependencies (resource_id + version).
let dependencies = match o.get("dependencies") {
None => Vec::new(),
Some(Value::Array(arr)) => {
if arr.len() > MAX_PROMPT_DEPENDENCIES {
return Err(PromptError::InvalidDefinition);
}
let mut out = Vec::with_capacity(arr.len());
let mut seen = BTreeSet::new();
for item in arr {
let obj = item.as_object().ok_or(PromptError::InvalidDefinition)?;
if obj
.keys()
.any(|k| !matches!(k.as_str(), "resource_id" | "version"))
{
return Err(PromptError::InvalidDefinition);
}
let rid = bounded_string(obj.get("resource_id"))?;
let ver = obj
.get("version")
.and_then(Value::as_u64)
.ok_or(PromptError::InvalidDefinition)?;
if ver == 0 || ver > u32::MAX as u64 {
return Err(PromptError::InvalidDefinition);
}
let ver = ver as u32;
if !seen.insert((rid.clone(), ver)) {
return Err(PromptError::InvalidDefinition);
}
out.push(PromptDependency {
resource_id: rid,
version: ver,
});
}
out
}
Some(_) => return Err(PromptError::InvalidDefinition),
};
let mut names = BTreeMap::new();
let mut arguments = Vec::new();
for raw in raw_args {
let a = raw.as_object().ok_or(PromptError::InvalidDefinition)?;
if a.keys()
.any(|key| !matches!(key.as_str(), "name" | "schema" | "required" | "default"))
{
return Err(PromptError::InvalidDefinition);
}
let name = bounded_string(a.get("name"))?;
let schema = a
.get("schema")
.and_then(Value::as_object)
.ok_or(PromptError::InvalidDefinition)?;
let kind = match schema.get("type").and_then(Value::as_str) {
Some("string") => ArgumentKind::String,
Some("number") => ArgumentKind::Number,
Some("integer") => ArgumentKind::Integer,
Some("boolean") => ArgumentKind::Boolean,
_ => return Err(PromptError::InvalidDefinition),
};
let required = a
.get("required")
.and_then(Value::as_bool)
.ok_or(PromptError::InvalidDefinition)?;
let default = a.get("default").cloned();
if schema
.keys()
.any(|key| !matches!(key.as_str(), "type" | "enum"))
{
return Err(PromptError::InvalidDefinition);
}
let enumeration = match schema.get("enum") {
Some(Value::Array(values)) => values.clone(),
Some(_) => return Err(PromptError::InvalidDefinition),
None => Vec::new(),
};
if enumeration.len() > 64
|| (schema.contains_key("enum") && enumeration.is_empty())
|| enumeration
.iter()
.any(|value| !valid(kind, value) || !bounded_json(value))
|| (required && default.is_some())
|| (default.as_ref().is_some_and(|v| {
!valid(kind, v)
|| !bounded_json(v)
|| (!enumeration.is_empty() && !enumeration.contains(v))
}))
{
return Err(PromptError::InvalidDefinition);
}
if names
.insert(
name.clone(),
(kind, required, default.clone(), enumeration.clone()),
)
.is_some()
{
return Err(PromptError::InvalidDefinition);
}
arguments.push(PromptArgument {
name,
kind,
required,
default,
enumeration,
});
}
let mut messages = Vec::new();
for raw in raw_msgs {
let m = raw.as_object().ok_or(PromptError::InvalidDefinition)?;
if m.keys()
.any(|key| !matches!(key.as_str(), "role" | "content" | "resource_refs"))
{
return Err(PromptError::InvalidDefinition);
}
let role = match m.get("role").and_then(Value::as_str) {
Some("system") => PromptRole::System,
Some("user") => PromptRole::User,
Some("assistant") => PromptRole::Assistant,
_ => return Err(PromptError::InvalidDefinition),
};
let content = bounded_string(m.get("content"))?;
// resource_refs: non-empty unique indices into dependencies.
let mut resource_refs: Vec<usize> = Vec::new();
if let Some(raw_refs) = m.get("resource_refs") {
let arr = raw_refs.as_array().ok_or(PromptError::InvalidDefinition)?;
if arr.is_empty() {
return Err(PromptError::InvalidDefinition);
}
let mut seen = BTreeSet::new();
for v in arr {
let idx = v.as_u64().ok_or(PromptError::InvalidDefinition)? as usize;
if idx >= dependencies.len() || !seen.insert(idx) {
return Err(PromptError::InvalidDefinition);
}
resource_refs.push(idx);
}
}
for (_, key) in placeholders(&content)? {
if !names.contains_key(&key) {
return Err(PromptError::InvalidTemplate);
}
}
messages.push(PromptMessage {
role,
content,
resource_refs,
});
}
Ok(Self {
name,
description,
arguments,
messages,
dependencies,
})
}
pub fn preview(
&self,
supplied: &Map<String, Value>,
) -> Result<Vec<PromptMessage>, PromptError> {
let mut values = BTreeMap::<String, Value>::new();
for key in supplied.keys() {
if !self.arguments.iter().any(|a| &a.name == key) {
return Err(PromptError::UnknownArgument(key.clone()));
}
}
for arg in &self.arguments {
let Some(value) = supplied.get(&arg.name).or(arg.default.as_ref()) else {
if arg.required {
return Err(PromptError::MissingArgument(arg.name.clone()));
}
values.insert(arg.name.clone(), Value::String(String::new()));
continue;
};
if !valid(arg.kind, value)
|| (!arg.enumeration.is_empty() && !arg.enumeration.contains(value))
|| value
.as_str()
.is_some_and(|text| text.len() > MAX_TEXT_BYTES)
{
return Err(PromptError::InvalidArgument(arg.name.clone()));
}
values.insert(arg.name.clone(), value.clone());
}
let mut rendered = Vec::with_capacity(self.messages.len());
let mut total_bytes = 0usize;
for message in &self.messages {
let mut content = String::new();
let mut cursor = 0;
for (start, key) in placeholders(&message.content)? {
content.push_str(&message.content[cursor..start]);
let end = start + key.len() + 4;
let value = values
.get(key.as_str())
.ok_or(PromptError::InvalidTemplate)?;
content.push_str(&scalar_text(value).ok_or(PromptError::InvalidTemplate)?);
cursor = end;
if content.len() > MAX_TEXT_BYTES {
return Err(PromptError::InvalidTemplate);
}
}
content.push_str(&message.content[cursor..]);
total_bytes = total_bytes
.checked_add(content.len())
.filter(|size| *size <= MAX_TEXT_BYTES)
.ok_or(PromptError::InvalidTemplate)?;
rendered.push(PromptMessage {
role: message.role,
content,
resource_refs: message.resource_refs.clone(),
});
}
Ok(rendered)
}
}
fn scalar_text(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(_) | Value::Bool(_) => Some(value.to_string()),
Value::Null | Value::Array(_) | Value::Object(_) => None,
}
}
fn bounded_string(value: Option<&Value>) -> Result<String, PromptError> {
value
.and_then(Value::as_str)
// PostgreSQL text/jsonb cannot store U+0000, so it must never reach SQL.
.filter(|s| !s.is_empty() && s.len() <= MAX_TEXT_BYTES && !s.contains('\0'))
.map(str::to_owned)
.ok_or(PromptError::InvalidDefinition)
}
fn valid(kind: ArgumentKind, v: &Value) -> bool {
match kind {
ArgumentKind::String => v.is_string(),
ArgumentKind::Number => v.as_f64().is_some(),
ArgumentKind::Integer => v.as_i64().is_some() || v.as_u64().is_some(),
ArgumentKind::Boolean => v.is_boolean(),
}
}
/// Whether the stored `jsonb::text` form of a scalar stays inside the storage guard.
fn bounded_json(value: &Value) -> bool {
jsonb_text_len(value).is_some_and(|size| size <= MAX_JSON_TEXT_BYTES)
}
/// Byte length of the `jsonb::text` form PostgreSQL produces for a scalar value:
/// quoted strings with `"`/`\` doubled and control characters as `\u00XX`,
/// except the short escapes PostgreSQL writes for LF/TAB/CR/BS/FF.
fn jsonb_text_len(value: &Value) -> Option<usize> {
match value {
Value::String(text) => {
let mut size = 2;
for ch in text.chars() {
size += match ch {
// PostgreSQL jsonb rejects `\u0000` ("cannot be converted to text").
'\0' => return None,
'"' | '\\' => 2,
'\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
_ if (ch as u32) < 0x20 => 6,
_ => ch.len_utf8(),
};
}
Some(size)
}
Value::Number(number) => Some(number.to_string().len()),
Value::Bool(true) => Some(4),
Value::Bool(false) => Some(5),
Value::Null => Some(4),
Value::Array(_) | Value::Object(_) => None,
}
}
fn placeholders(s: &str) -> Result<Vec<(usize, String)>, PromptError> {
let mut out = Vec::new();
let mut pos = 0;
while let Some(rel) = s[pos..].find("{{") {
let start = pos + rel;
let inner = start + 2;
let close = s[inner..]
.find("}}")
.map(|n| inner + n)
.ok_or(PromptError::InvalidTemplate)?;
let key = &s[inner..close];
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return Err(PromptError::InvalidTemplate);
}
out.push((start, key.to_owned()));
pos = close + 2;
if !s[pos..].contains("{{") {
break;
}
}
if s.matches("{{").count() != out.len() || s.matches("}}").count() != out.len() {
return Err(PromptError::InvalidTemplate);
}
Ok(out)
}
+234
View File
@@ -0,0 +1,234 @@
//! Story 3.16 (FR-18): pure composition of a Prompt with its pinned Resource dependencies.
//!
//! One renderer serves the admin preview and MCP `prompts/get`: the accepted typed renderer
//! (`PromptDefinition::preview`) validates arguments and renders the template text first, then the
//! pinned content of every declared `resource_refs` index is appended to the message the author
//! declared. Message count, order and roles come from the published template only — dependency
//! content can never add, remove or re-role a message. There is no tool dispatch and no code path
//! that interprets dependency content, so a `{"tool_calls": …}` block stays inert text.
//!
//! Failures are typed and total: the caller receives a reason and a position/source path, never a
//! partially composed message list and never the matched secret text.
use serde_json::{Map, Value};
use crate::prompt::{
MAX_TEXT_BYTES, PromptDefinition, PromptError, PromptMessage, PromptSensitivity,
};
use crate::resource::{ResourceKind, publication_include_directives, publication_secret_findings};
/// Bound of the `dependencies` array (contract §1, `MAX_PROMPT_DEPENDENCIES`).
pub const MAX_PROMPT_DEPENDENCIES: usize = 16;
/// Wire values of `dependencies[i].source_class` (contract §4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PromptDependencySourceClass {
Static,
Dynamic,
}
impl PromptDependencySourceClass {
pub fn as_str(self) -> &'static str {
match self {
Self::Static => "static",
Self::Dynamic => "dynamic",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"static" => Some(Self::Static),
"dynamic" => Some(Self::Dynamic),
_ => None,
}
}
}
/// One resolved pin of a published dependency: the exact version the Prompt was published with,
/// plus the metadata the provenance block reports. It carries no content.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptDependencyPin {
pub position: usize,
pub resource_id: String,
pub version: u32,
pub digest: String,
pub kind: ResourceKind,
pub mime_type: String,
pub source_class: PromptDependencySourceClass,
pub sensitivity: PromptSensitivity,
}
impl PromptDependencyPin {
/// Provenance row of the preview contract (§7): declaration order, no content.
pub fn provenance_json(pin: &Self) -> Value {
serde_json::json!({
"position": pin.position,
"resource_id": pin.resource_id,
"version": pin.version,
"digest": pin.digest,
"kind": pin.kind.as_str(),
"mime_type": pin.mime_type,
"source_class": pin.source_class.as_str(),
"sensitivity": pin.sensitivity,
})
}
}
/// Ordered provenance block of a composed result.
pub fn provenance_json(pins: &[PromptDependencyPin]) -> Vec<Value> {
pins.iter()
.map(PromptDependencyPin::provenance_json)
.collect()
}
/// Typed refusal of the composition boundary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PromptCompositionError {
/// A dependency no message references: pinning content that is never delivered (contract §1).
DependencyUnused {
position: usize,
resource_id: String,
version: u32,
},
/// The pinned exact version cannot be resolved/read right now (revoked, archived, foreign).
DependencyUnavailable { position: usize },
/// `binary` has no negotiated message representation (contract §4).
DependencyRepresentationUnsupported { position: usize },
/// The template text itself carries a raw credential.
CredentialFinding { source_path: String },
/// The template text itself carries an explicit `include:` access-bypass directive.
AccessBypassFinding { source_path: String },
/// Read-time content of a dynamic dependency carries a raw credential.
DependencyCredentialFinding { position: usize },
/// Read-time content of a dynamic dependency carries an `include:` directive.
DependencyAccessBypassFinding { position: usize },
/// The accepted renderer refused the template/arguments.
Template(PromptError),
}
impl From<PromptError> for PromptCompositionError {
fn from(error: PromptError) -> Self {
Self::Template(error)
}
}
/// Strictest-sensitivity fold: `effective = max(local, every pinned dependency)` (contract §3).
pub fn effective_sensitivity(
local: PromptSensitivity,
pins: &[PromptDependencyPin],
) -> PromptSensitivity {
pins.iter().fold(local, |strictest, pin| {
if rank(pin.sensitivity) > rank(strictest) {
pin.sensitivity
} else {
strictest
}
})
}
fn rank(sensitivity: PromptSensitivity) -> u8 {
match sensitivity {
PromptSensitivity::Public => 0,
PromptSensitivity::Internal => 1,
PromptSensitivity::Secret => 2,
}
}
/// The first dependency (declaration order) that no message references.
pub fn unused_dependency(definition: &PromptDefinition) -> Option<usize> {
(0..definition.dependencies().len()).find(|position| {
!definition
.messages()
.iter()
.any(|message| message.resource_refs.contains(position))
})
}
/// Bounded scan of the Prompt template text (messages, contract §5).
pub fn scan_template(definition: &PromptDefinition) -> Result<(), PromptCompositionError> {
for (position, message) in definition.messages().iter().enumerate() {
let bytes = message.content.as_bytes();
if publication_secret_findings(bytes).is_some() {
return Err(PromptCompositionError::CredentialFinding {
source_path: format!("messages[{position}].content"),
});
}
if !publication_include_directives(bytes).is_empty() {
return Err(PromptCompositionError::AccessBypassFinding {
source_path: format!("messages[{position}].content"),
});
}
}
Ok(())
}
/// Bounded scan of dynamic dependency content, fetched at read time (contract §5).
pub fn scan_dependency_content(
position: usize,
bytes: &[u8],
) -> Result<(), PromptCompositionError> {
if publication_secret_findings(bytes).is_some() {
return Err(PromptCompositionError::DependencyCredentialFinding { position });
}
if !publication_include_directives(bytes).is_empty() {
return Err(PromptCompositionError::DependencyAccessBypassFinding { position });
}
Ok(())
}
/// Content of every dependency, indexed by declaration position.
///
/// `None` means the exact pinned version could not be read now; a dependency that is absent from
/// this slice is treated the same way, so composition is total and never silently short.
pub fn render(
definition: &PromptDefinition,
pins: &[PromptDependencyPin],
arguments: &Map<String, Value>,
contents: &[Option<Vec<u8>>],
) -> Result<Vec<PromptMessage>, PromptCompositionError> {
let mut messages = definition.preview(arguments)?;
for message in &mut messages {
for index in &message.resource_refs {
let Some(Some(bytes)) = contents.get(*index) else {
return Err(PromptCompositionError::DependencyUnavailable { position: *index });
};
let pin = pins
.iter()
.find(|pin| pin.position == *index)
.ok_or(PromptCompositionError::DependencyUnavailable { position: *index })?;
let text = match pin.kind {
ResourceKind::Text | ResourceKind::Json => {
std::str::from_utf8(bytes).map_err(|_| {
PromptCompositionError::DependencyRepresentationUnsupported {
position: *index,
}
})?
}
ResourceKind::Binary => {
return Err(
PromptCompositionError::DependencyRepresentationUnsupported {
position: *index,
},
);
}
};
// Contract §5: dynamic content is fetched at read time and was never scanned at
// publication, so it is scanned here — one call site for preview and `prompts/get`.
if pin.source_class == PromptDependencySourceClass::Dynamic {
scan_dependency_content(*index, text.as_bytes())?;
}
if !message.content.is_empty() {
message.content.push_str("\n\n");
}
message.content.push_str(text);
// shortcut: one composed message keeps the accepted 16 KiB text bound; a larger
// composed message is refused instead of silently truncated.
if message.content.len() > MAX_TEXT_BYTES {
return Err(PromptCompositionError::Template(
PromptError::InvalidTemplate,
));
}
}
}
Ok(messages)
}
+915
View File
@@ -0,0 +1,915 @@
//! Typed static Resource drafts (Story 3.6): domain contract for `Resource`.
//!
//! `Resource` — отдельный typed aggregate с собственными ID/version/lifecycle,
//! sensitivity и неизменяемой published-моделью; он не является подтипом
//! `Operation` и не «универсальный JSON blob» (AD-1/AD-2).
//!
//! Здесь же живут грамматики и валидаторы контракта:
//! - D-3 — пределы содержимого (`ResourceLimits`, storage ceiling);
//! - D-4 — синтаксис MIME (наследуется из существующего DB CHECK V12);
//! - D-5 — закрытый allowlist MIME по kind (content sniffing отсутствует);
//! - D-7 — пустое содержимое отвергается;
//! - D-8 — JSON валидируется locked-парсером `serde_json` и хранится дословно;
//! - D-9 — UTF-8 без replacement и без «успешного префикса»;
//! - D-10 — грамматика URI;
//! - D-11 — грамматика name;
//! - D-14 — стабильные коды/поля отказов (`ResourceError`).
//!
//! Коды отказа — контракт wire-уровня: HTTP-статус и envelope формирует
//! admin-api (`error.rs`), а домен отвечает только за `code`/`field`.
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::ids::{OperationId, ResourceId};
/// Storage ceiling одного blob-а (`MAX_ARTIFACT_BYTES`) и DB CHECK
/// `artifact_blobs_size_check`. Это не новый продуктовый порог: default
/// `ResourceLimits` равен этому потолку (D-3).
pub const RESOURCE_STORAGE_CEILING: usize = 256 * 1024;
/// Верхняя граница `description` в байтах (D-20, DB CHECK `resources_description_len`).
pub const MAX_RESOURCE_DESCRIPTION_BYTES: usize = 1024;
/// Нижняя и верхняя границы URI в байтах; следуют из грамматики UR-2 (D-10).
pub const MIN_RESOURCE_URI_BYTES: usize = 10;
pub const MAX_RESOURCE_URI_BYTES: usize = 200;
/// Верхняя граница `name` в символах (ASCII-грамматика D-11).
pub const MAX_RESOURCE_NAME_BYTES: usize = 64;
const URI_SCHEME: &str = "crank://";
const TEXT_MIME_TYPES: &[&str] = &["text/plain", "text/markdown", "text/csv"];
const JSON_MIME_TYPES: &[&str] = &["application/json"];
const BINARY_MIME_TYPES: &[&str] = &[
"application/octet-stream",
"application/pdf",
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/svg+xml",
"text/html",
];
/// Общий typed контракт capability (AD-2): Operation, Resource (и будущий Prompt).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CapabilityKind {
Operation,
Resource,
}
/// Typed ссылка на capability. Варианты несовместимы по типу: Operation-ref не
/// принимается там, где нужен Resource-ref (AT-3.6-01).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "kind", content = "id")]
pub enum CapabilityRef {
Operation(OperationId),
Resource(ResourceId),
}
impl fmt::Display for CapabilityKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Operation => "operation",
Self::Resource => "resource",
})
}
}
/// Ошибка несовместимости typed-ссылки на capability.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("capability reference is a {actual}, expected a {expected}")]
pub struct CapabilityKindMismatch {
pub expected: CapabilityKind,
pub actual: CapabilityKind,
}
impl CapabilityRef {
pub fn kind(&self) -> CapabilityKind {
match self {
Self::Operation(_) => CapabilityKind::Operation,
Self::Resource(_) => CapabilityKind::Resource,
}
}
/// Resource-ref или типизированный отказ — «поиск слов» вместо проверки типа не используется.
pub fn as_resource(&self) -> Result<&ResourceId, CapabilityKindMismatch> {
match self {
Self::Resource(resource_id) => Ok(resource_id),
Self::Operation(_) => Err(CapabilityKindMismatch {
expected: CapabilityKind::Resource,
actual: CapabilityKind::Operation,
}),
}
}
pub fn as_operation(&self) -> Result<&OperationId, CapabilityKindMismatch> {
match self {
Self::Operation(operation_id) => Ok(operation_id),
Self::Resource(_) => Err(CapabilityKindMismatch {
expected: CapabilityKind::Operation,
actual: CapabilityKind::Resource,
}),
}
}
}
/// Wire-значения `ResourceKind` (D-2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResourceKind {
Text,
Json,
Binary,
}
impl ResourceKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Text => "text",
Self::Json => "json",
Self::Binary => "binary",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"text" => Some(Self::Text),
"json" => Some(Self::Json),
"binary" => Some(Self::Binary),
_ => None,
}
}
/// kind, для которого MIME входит в закрытый allowlist D-5.
pub fn for_mime(mime_type: &str) -> Option<Self> {
if TEXT_MIME_TYPES.contains(&mime_type) {
Some(Self::Text)
} else if JSON_MIME_TYPES.contains(&mime_type) {
Some(Self::Json)
} else if BINARY_MIME_TYPES.contains(&mime_type) {
Some(Self::Binary)
} else {
None
}
}
pub fn allows_mime_type(self, mime_type: &str) -> bool {
Self::for_mime(mime_type) == Some(self)
}
}
/// Wire-значения `ResourceStatus` (D-2); отдельный тип, форма как у `OperationStatus`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResourceStatus {
Draft,
Published,
Archived,
}
impl ResourceStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Draft => "draft",
Self::Published => "published",
Self::Archived => "archived",
}
}
/// Допустимый lifecycle-переход. Publish/archive реализуются в 3.7, но модель
/// обязана отвергать недопустимый переход уже в 3.6.
pub fn can_transition_to(self, next: Self) -> bool {
matches!(
(self, next),
(Self::Draft, Self::Published | Self::Archived)
| (Self::Published, Self::Draft | Self::Archived)
)
}
}
impl fmt::Display for ResourceKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl fmt::Display for ResourceStatus {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
/// Действия lifecycle Resource (описательная часть контракта).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResourceLifecycleAction {
Publish,
Revert,
Archive,
}
impl ResourceLifecycleAction {
pub fn target(self) -> ResourceStatus {
match self {
Self::Publish => ResourceStatus::Published,
Self::Revert => ResourceStatus::Draft,
Self::Archive => ResourceStatus::Archived,
}
}
}
/// Проверенный lifecycle-переход; `ResourceLifecycle::transition` возвращает его
/// только для допустимой пары состояний.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ResourceLifecycle {
pub from: ResourceStatus,
pub action: ResourceLifecycleAction,
}
impl ResourceLifecycle {
pub fn transition(
from: ResourceStatus,
action: ResourceLifecycleAction,
) -> Result<Self, ResourceError> {
let to = action.target();
if !from.can_transition_to(to) {
return Err(ResourceError::InvalidLifecycleTransition { from, to });
}
Ok(Self { from, action })
}
pub fn to(self) -> ResourceStatus {
self.action.target()
}
}
/// Wire-значения sensitivity совпадают с существующим CHECK V12 (D-13).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResourceSensitivity {
Public,
Internal,
Secret,
}
impl ResourceSensitivity {
pub fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::Internal => "internal",
Self::Secret => "secret",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"public" => Some(Self::Public),
"internal" => Some(Self::Internal),
"secret" => Some(Self::Secret),
_ => None,
}
}
}
/// Задаваемые атрибуты Draft (D-16): URI/name/kind неизменяемы после создания.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceMetadata {
pub uri: String,
pub name: String,
pub description: String,
pub kind: ResourceKind,
pub mime_type: String,
pub sensitivity: ResourceSensitivity,
}
impl ResourceMetadata {
/// D-10 UR-1..UR-3: литерал `crank://`, ASCII charset 10..=200 байт, непустые
/// сегменты без `.`/`..` и без trailing `/`.
pub fn uri_is_valid(uri: &str) -> bool {
let Some(path) = uri.strip_prefix(URI_SCHEME) else {
return false;
};
if uri.len() < MIN_RESOURCE_URI_BYTES || uri.len() > MAX_RESOURCE_URI_BYTES {
return false;
}
// UR-2: после литерала схемы ровно `1 + 0..190 + 1` символов, то есть
// вся ссылка 10..=200 байт включительно.
const MAX_PATH_BYTES: usize = MAX_RESOURCE_URI_BYTES - URI_SCHEME.len();
if path.is_empty() || path.len() > MAX_PATH_BYTES {
return false;
}
let bytes = path.as_bytes();
let Some((first, rest)) = bytes.split_first() else {
return false;
};
let Some((last, middle)) = rest.split_last() else {
return false;
};
let edge = |byte: u8| byte.is_ascii_alphanumeric();
if !edge(*first) || !edge(*last) {
return false;
}
if !middle.iter().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'~' | b'/' | b'-')
}) {
return false;
}
if path.ends_with('/') {
return false;
}
path.split('/')
.all(|segment| !segment.is_empty() && segment != "." && segment != "..")
}
/// D-11: `^[a-z][a-z0-9_-]{0,63}$`.
pub fn name_is_valid(name: &str) -> bool {
let bytes = name.as_bytes();
if bytes.is_empty() || bytes.len() > MAX_RESOURCE_NAME_BYTES {
return false;
}
let Some((first, rest)) = bytes.split_first() else {
return false;
};
first.is_ascii_lowercase()
&& rest.iter().all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
})
}
/// D-4: bare `type/subtype` без параметров; грамматика наследуется из V12.
pub fn mime_syntax_is_valid(mime_type: &str) -> bool {
let Some((kind, subtype)) = mime_type.split_once('/') else {
return false;
};
if kind.is_empty()
|| subtype.is_empty()
|| mime_type.len() > 255
|| mime_type.len() < 3
|| subtype.contains('/')
{
return false;
}
let token_is_valid = |token: &str| {
token.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
)
})
};
token_is_valid(kind) && token_is_valid(subtype)
}
pub fn description_is_valid(description: &str) -> bool {
description.len() <= MAX_RESOURCE_DESCRIPTION_BYTES
}
/// D-20 шаг E: фиксированный порядок uri → name → description → kind/mime.
pub fn validate(&self) -> Result<(), ResourceError> {
if !Self::uri_is_valid(&self.uri) {
return Err(ResourceError::UriInvalid);
}
if !Self::name_is_valid(&self.name) {
return Err(ResourceError::NameInvalid);
}
if !Self::description_is_valid(&self.description) {
return Err(ResourceError::DescriptionInvalid);
}
self.validate_mime()
}
/// Правило MIME в одном месте (D-20 шаг E): синтаксис → allowlist → совместимость с kind.
pub fn validate_mime(&self) -> Result<(), ResourceError> {
if !Self::mime_syntax_is_valid(&self.mime_type) {
return Err(ResourceError::MimeSyntaxInvalid);
}
match ResourceKind::for_mime(&self.mime_type) {
None => Err(ResourceError::MimeNotAllowed),
Some(owner) if owner != self.kind => Err(ResourceError::KindMismatch),
Some(_) => Ok(()),
}
}
/// D-9/D-3: text-kind; L inclusive, L+1 отвергается целиком, без U+FFFD и усечения.
pub fn validate_text(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
if bytes.len() > limit {
return Err(ResourceError::ContentTooLarge);
}
if bytes.is_empty() {
return Err(ResourceError::ContentEmpty);
}
if std::str::from_utf8(bytes).is_err() {
return Err(ResourceError::ContentInvalidUtf8);
}
Ok(bytes.to_vec())
}
/// D-8: валидация locked-парсером `serde_json` без features; bytes хранятся дословно.
pub fn validate_json(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
if bytes.len() > limit {
return Err(ResourceError::ContentTooLarge);
}
if bytes.is_empty() {
return Err(ResourceError::ContentEmpty);
}
if serde_json::from_slice::<serde_json::Value>(bytes).is_err() {
return Err(ResourceError::ContentInvalidJson);
}
Ok(bytes.to_vec())
}
/// Проверка содержимого по typed kind (без content sniffing).
pub fn validate_content(
kind: ResourceKind,
mime_type: &str,
bytes: &[u8],
limits: &ResourceLimits,
) -> Result<Vec<u8>, ResourceError> {
let limit = limits.effective_limit(kind);
match kind {
ResourceKind::Text => Self::validate_text(bytes, limit),
ResourceKind::Json => Self::validate_json(bytes, limit),
ResourceKind::Binary => {
if bytes.len() > limit {
return Err(ResourceError::ContentTooLarge);
}
if bytes.is_empty() {
return Err(ResourceError::ContentEmpty);
}
let _ = mime_type;
Ok(bytes.to_vec())
}
}
}
/// Безопасный finding для непригодного MIME (bytes не раскрываются).
pub fn mime_finding(
mime_type: &str,
kind: ResourceKind,
limits: &ResourceLimits,
) -> ResourceFinding {
let _ = limits;
if !Self::mime_syntax_is_valid(mime_type) {
return ResourceFinding::rejected(ResourceFindingCode::MimeSyntaxInvalid, "mime_type");
}
match ResourceKind::for_mime(mime_type) {
None => ResourceFinding::rejected(ResourceFindingCode::MimeNotAllowed, "mime_type"),
Some(owner) if owner != kind => {
ResourceFinding::rejected(ResourceFindingCode::KindMismatch, "kind")
}
Some(_) => ResourceFinding::accepted(),
}
}
/// Безопасный finding для невалидного JSON-документа.
pub fn json_finding(bytes: &[u8], limits: &ResourceLimits) -> ResourceFinding {
match Self::validate_json(bytes, limits.effective_limit(ResourceKind::Json)) {
Ok(_) => ResourceFinding::accepted(),
Err(error) => {
ResourceFinding::rejected(error.finding_code(), error.field_or("content"))
}
}
}
}
/// Пределы содержимого по kind. Значение выше storage ceiling отвергается при
/// конфигурации; новый env-ключ не вводится (D-3).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ResourceLimits {
text: usize,
json: usize,
binary: usize,
}
impl Default for ResourceLimits {
fn default() -> Self {
Self {
text: RESOURCE_STORAGE_CEILING,
json: RESOURCE_STORAGE_CEILING,
binary: RESOURCE_STORAGE_CEILING,
}
}
}
impl ResourceLimits {
pub const STORAGE_CEILING: usize = RESOURCE_STORAGE_CEILING;
/// Конфигурация пределов; значения выше потолка не принимаются (D-3).
pub fn new(text: usize, json: usize, binary: usize) -> Result<Self, ResourceError> {
if [text, json, binary]
.into_iter()
.any(|limit| limit == 0 || limit > RESOURCE_STORAGE_CEILING)
{
return Err(ResourceError::InvalidLimits);
}
Ok(Self { text, json, binary })
}
/// Один предел на все три kind — форма, используемая сервисом и тестами.
pub fn uniform(limit: usize) -> Result<Self, ResourceError> {
Self::new(limit, limit, limit)
}
pub fn effective_limit(&self, kind: ResourceKind) -> usize {
match kind {
ResourceKind::Text => self.text,
ResourceKind::Json => self.json,
ResourceKind::Binary => self.binary,
}
}
}
/// Коды findings (те же строки, что и stable `error.code`, D-14).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResourceFindingCode {
#[serde(rename = "resource_content_empty")]
ContentEmpty,
#[serde(rename = "resource_content_too_large")]
ContentTooLarge,
#[serde(rename = "resource_content_invalid_utf8")]
ContentInvalidUtf8,
#[serde(rename = "resource_content_invalid_json")]
ContentInvalidJson,
#[serde(rename = "resource_mime_syntax_invalid")]
MimeSyntaxInvalid,
#[serde(rename = "resource_mime_not_allowed")]
MimeNotAllowed,
#[serde(rename = "resource_kind_mismatch")]
KindMismatch,
/// Служебное значение «нарушений нет»; в ответах `findings` пуст на успехе,
/// поэтому этот код на wire не попадает.
#[serde(rename = "resource_finding_accepted")]
Accepted,
}
impl ResourceFindingCode {
pub fn as_str(self) -> &'static str {
match self {
Self::ContentEmpty => "resource_content_empty",
Self::ContentTooLarge => "resource_content_too_large",
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
Self::ContentInvalidJson => "resource_content_invalid_json",
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
Self::MimeNotAllowed => "resource_mime_not_allowed",
Self::KindMismatch => "resource_kind_mismatch",
Self::Accepted => "resource_finding_accepted",
}
}
}
/// Finding не содержит bytes содержимого: только стабильный код и поле.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceFinding {
code: ResourceFindingCode,
field: &'static str,
}
impl ResourceFinding {
pub fn rejected(code: ResourceFindingCode, field: &'static str) -> Self {
Self { code, field }
}
/// «Нарушений нет» — служебное значение, не являющееся rejection.
pub fn accepted() -> Self {
Self {
code: ResourceFindingCode::Accepted,
field: "",
}
}
pub fn code(&self) -> &'static str {
self.code.as_str()
}
pub fn field(&self) -> &'static str {
self.field
}
pub fn is_rejection(&self) -> bool {
!self.field.is_empty()
}
}
/// Стабильные коды/поля отказов Resource (D-14) без HTTP-статусов: статус
/// назначает admin-api по коду.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ResourceError {
#[error("resource content must not be empty")]
ContentEmpty,
/// Story 3.9: форма переносимого envelope не распознана (неизвестные/недостающие
/// ключи, неподдержанная версия, синтаксис base64/hex, `source`). Транспортный
/// контракт envelope живёт в admin-api; здесь только стабильный wire-код.
#[error("resource portability envelope is invalid")]
PortabilityEnvelopeInvalid,
#[error("resource content exceeds the configured limit")]
ContentTooLarge,
#[error("resource content is not valid UTF-8")]
ContentInvalidUtf8,
#[error("resource content is not valid JSON")]
ContentInvalidJson,
#[error("resource mime type syntax is invalid")]
MimeSyntaxInvalid,
#[error("resource mime type is not allowed for this kind")]
MimeNotAllowed,
#[error("resource mime type is incompatible with the declared kind")]
KindMismatch,
#[error("resource uri is invalid")]
UriInvalid,
#[error("resource name is invalid")]
NameInvalid,
#[error("resource description is invalid")]
DescriptionInvalid,
/// Значение поля метаданных вне набора (`kind`/`sensitivity`): форма запроса, а не
/// доменный код (D-20 B/E). `code()` отдаёт принятый для этого отказа generic-код,
/// а admin-api выводит его без Resource-специфичного контекста.
#[error("resource metadata field `{field}` has an unknown value")]
UnknownMetadataValue { field: &'static str },
#[error("resource uri already exists in this workspace")]
UriDuplicate,
#[error("resource name already exists in this workspace")]
NameDuplicate,
#[error("resource field {field} is immutable")]
FieldImmutable { field: &'static str },
#[error("resource changed since it was read")]
Stale,
#[error("resource was not found in this workspace")]
NotFound,
/// Story 3.8: необратимый security-revoke закрыл Resource целиком. Это не
/// lifecycle-состояние: archive/редактирование его не снимают, а новые
/// публикации и привязки запрещены.
#[error("resource has been revoked")]
Revoked,
#[error("resource artifact integrity verification failed")]
ArtifactIntegrity,
/// Публикация отклонена secret-policy: содержимое содержит структурный private key,
/// raw credential assignment либо explicit access-bypassing reference. Наружу отдаётся
/// только общая категория, никогда не совпавший текст (TL decision 4).
#[error("resource content contains secret material or an access-bypassing reference")]
SecretFindings,
#[error("resource storage is unavailable")]
StorageUnavailable,
#[error("resource content limits are invalid")]
InvalidLimits,
#[error("resource lifecycle transition from {from} to {to} is not allowed")]
InvalidLifecycleTransition {
from: ResourceStatus,
to: ResourceStatus,
},
/// Story 3.10: структурно неверное определение REST-шаблона (wire
/// `resource_source_invalid`); `field` — конкретное поле отказа.
#[error("resource source definition is invalid")]
SourceInvalid { field: &'static str },
/// Story 3.10: Operation/версия не найдена в этом workspace (чужой workspace
/// неотличим от отсутствующего — без раскрытия).
#[error("resource source operation was not found in this workspace")]
SourceNotFound,
/// Story 3.10: версия существует, но не Published.
#[error("resource source operation version is not published")]
SourceNotPublished,
/// Story 3.10: публикацию блокируют findings шаблона.
#[error("resource source definition has blocking findings")]
SourceBlocked {
findings: Vec<crate::resource::template::TemplateFinding>,
},
/// Story 3.10: определение шаблона не переносимо (export/content).
#[error("resource source definition is not portable")]
SourceNotPortable,
}
impl ResourceError {
pub fn code(&self) -> &'static str {
match self {
Self::ContentEmpty => "resource_content_empty",
Self::PortabilityEnvelopeInvalid => "resource_portability_envelope_invalid",
Self::ContentTooLarge => "resource_content_too_large",
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
Self::ContentInvalidJson => "resource_content_invalid_json",
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
Self::MimeNotAllowed => "resource_mime_not_allowed",
Self::KindMismatch => "resource_kind_mismatch",
Self::UriInvalid => "resource_uri_invalid",
Self::NameInvalid => "resource_name_invalid",
Self::DescriptionInvalid => "resource_description_invalid",
// D-20 B/E: у этого отказа нет Resource-специфичного кода.
Self::UnknownMetadataValue { .. } => "validation_error",
Self::UriDuplicate => "resource_uri_duplicate",
Self::NameDuplicate => "resource_name_duplicate",
Self::FieldImmutable { .. } => "resource_field_immutable",
Self::Stale => "resource_stale",
Self::NotFound => "resource_not_found",
Self::Revoked => "resource_revoked",
Self::ArtifactIntegrity => "resource_artifact_integrity",
Self::SecretFindings => "resource_secret_findings",
Self::StorageUnavailable => "resource_storage_unavailable",
Self::InvalidLimits => "resource_limits_invalid",
Self::InvalidLifecycleTransition { .. } => "resource_lifecycle_invalid",
Self::SourceInvalid { .. } => "resource_source_invalid",
Self::SourceNotFound => "resource_source_not_found",
Self::SourceNotPublished => "resource_source_not_published",
Self::SourceBlocked { .. } => "resource_source_blocked",
Self::SourceNotPortable => "resource_source_not_portable",
}
}
pub fn field(&self) -> Option<&'static str> {
match self {
Self::ContentEmpty
| Self::ContentTooLarge
| Self::ContentInvalidUtf8
| Self::ContentInvalidJson
| Self::ArtifactIntegrity
| Self::SecretFindings => Some("content"),
Self::PortabilityEnvelopeInvalid => Some("envelope"),
Self::MimeSyntaxInvalid | Self::MimeNotAllowed => Some("mime_type"),
Self::KindMismatch => Some("kind"),
Self::UriInvalid | Self::UriDuplicate => Some("uri"),
Self::NameInvalid | Self::NameDuplicate => Some("name"),
Self::DescriptionInvalid => Some("description"),
Self::FieldImmutable { field } => Some(field),
Self::Stale => Some("expected_updated_at"),
Self::NotFound | Self::Revoked => Some("resource_id"),
Self::StorageUnavailable
| Self::InvalidLimits
| Self::UnknownMetadataValue { .. }
| Self::InvalidLifecycleTransition { .. } => None,
Self::SourceInvalid { field } => Some(field),
Self::SourceNotFound => Some("source.operation_id"),
Self::SourceNotPublished => Some("source.operation_version"),
Self::SourceBlocked { .. } | Self::SourceNotPortable => Some("source"),
}
}
fn field_or(&self, fallback: &'static str) -> &'static str {
self.field().unwrap_or(fallback)
}
fn finding_code(&self) -> ResourceFindingCode {
match self {
Self::ContentEmpty => ResourceFindingCode::ContentEmpty,
Self::ContentTooLarge => ResourceFindingCode::ContentTooLarge,
Self::ContentInvalidUtf8 => ResourceFindingCode::ContentInvalidUtf8,
Self::MimeSyntaxInvalid => ResourceFindingCode::MimeSyntaxInvalid,
Self::MimeNotAllowed => ResourceFindingCode::MimeNotAllowed,
Self::KindMismatch => ResourceFindingCode::KindMismatch,
_ => ResourceFindingCode::ContentInvalidJson,
}
}
}
/// Typed Resource aggregate. Published-модель существует отдельным типом
/// (`PublishedResourceVersion`) и не содержит внутренних ссылок (D-12).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Resource {
pub resource_id: ResourceId,
pub uri: String,
pub name: String,
pub description: String,
pub kind: ResourceKind,
pub mime_type: String,
pub sensitivity: ResourceSensitivity,
pub status: ResourceStatus,
pub current_draft_version: u32,
pub created_at: time::OffsetDateTime,
pub updated_at: time::OffsetDateTime,
}
impl Resource {
/// Новый Draft: ровно одна текущая черновая версия (D-15).
pub fn draft(resource_id: ResourceId, metadata: ResourceMetadata) -> Self {
let now = time::OffsetDateTime::now_utc();
Self {
resource_id,
uri: metadata.uri,
name: metadata.name,
description: metadata.description,
kind: metadata.kind,
mime_type: metadata.mime_type,
sensitivity: metadata.sensitivity,
status: ResourceStatus::Draft,
current_draft_version: 1,
created_at: now,
updated_at: now,
}
}
pub fn status(&self) -> ResourceStatus {
self.status
}
pub fn current_draft_version(&self) -> u32 {
self.current_draft_version
}
pub fn metadata(&self) -> ResourceMetadata {
ResourceMetadata {
uri: self.uri.clone(),
name: self.name.clone(),
description: self.description.clone(),
kind: self.kind,
mime_type: self.mime_type.clone(),
sensitivity: self.sensitivity,
}
}
}
/// Черновая версия Resource: exact digest и metadata, без filesystem path,
/// filename и mutable external reference (D-12).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceVersion {
pub version: u32,
pub kind: ResourceKind,
pub mime_type: String,
pub size_bytes: u64,
pub digest: String,
pub created_at: time::OffsetDateTime,
pub superseded_at: Option<time::OffsetDateTime>,
}
impl ResourceVersion {
pub fn draft(
version: u32,
kind: ResourceKind,
mime_type: String,
size_bytes: u64,
digest: String,
) -> Self {
Self {
version,
kind,
mime_type,
size_bytes,
digest,
created_at: time::OffsetDateTime::now_utc(),
superseded_at: None,
}
}
pub fn version(&self) -> u32 {
self.version
}
pub fn digest(&self) -> &str {
&self.digest
}
pub fn size_bytes(&self) -> u64 {
self.size_bytes
}
pub fn is_current(&self) -> bool {
self.superseded_at.is_none()
}
}
/// Immutable published-модель версии: конструируется только из Draft, мутирующих
/// методов нет, внутренние ссылки не публикуются (D-12).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublishedResourceVersion {
version: u32,
kind: ResourceKind,
mime_type: String,
size_bytes: u64,
digest: String,
}
impl PublishedResourceVersion {
pub fn from_draft(draft: &ResourceVersion) -> Self {
Self {
version: draft.version,
kind: draft.kind,
mime_type: draft.mime_type.clone(),
size_bytes: draft.size_bytes,
digest: draft.digest.clone(),
}
}
pub fn version(&self) -> u32 {
self.version
}
pub fn digest(&self) -> &str {
&self.digest
}
pub fn size_bytes(&self) -> u64 {
self.size_bytes
}
}
pub mod publication;
pub mod template;
pub use publication::{publication_include_directives, publication_secret_findings};
pub use template::{
MAX_TEMPLATE_CACHE_BYTES, MAX_TEMPLATE_CACHE_TTL_MS, TEMPLATE_CACHE_SCOPE, TemplateCache,
TemplateFailure, TemplateFailureOutcome, TemplateFinding, TemplateFindingCode,
TemplateParameter, TemplateSource, TemplateSourceError, cache_policy_findings,
parse_uri_template,
};
@@ -0,0 +1,289 @@
//! Story 3.7 / AC02: publication policy детерминированно проверяет сохранённые
//! bounded bytes — structural private keys, raw credential assignments и explicit
//! `include:` reference directives. Никакой сети, расширения или исполнения
//! содержимого и никакого универсального сканера.
//!
//! Модуль вынесен из `resource.rs`, чтобы файл оставался в пределах health-лимита
//! (1000 строк) после добавления публикационной политики.
use serde_json::Value;
/// Структурная secret-находка в сохранённых bytes: только общая категория,
/// никогда не совпавший фрагмент. `None` — нарушений нет.
///
/// Любые bounded bytes безопасны для проверки: malformed/не-UTF-8 содержимое не
/// паникует и не превращается в отказ хранилища (AC02).
pub fn publication_secret_findings(bytes: &[u8]) -> Option<&'static str> {
let text = String::from_utf8_lossy(bytes);
if contains_private_key_block(&text) {
return Some("private_key");
}
if contains_raw_credential_assignment(&text)
|| contains_json_raw_credential(&text)
|| contains_bearer_token(&text)
{
return Some("raw_credential");
}
None
}
/// Explicit `include: <target>` директивы статического содержимого. Директива
/// возвращается как цель; разрешение (workspace-local, только published metadata)
/// выполняет вызывающая сторона. Обычные ссылки/проза директивами не являются.
pub fn publication_include_directives(bytes: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(bytes);
let mut directives = Vec::new();
for line in text.lines() {
let line = line.trim_start();
let Some(rest) = line.strip_prefix("include:") else {
continue;
};
let target = rest.split_whitespace().next().unwrap_or_default();
directives.push(target.to_owned());
}
directives
}
/// PEM-подобный private key block: `-----BEGIN <label>-----`, где label содержит
/// `PRIVATE KEY` (RSA/EC/DSA/OPENSSH/ENCRYPTED/PGP-варианты).
///
/// Label ограничивается `MAX_LABEL_BYTES` **по границе UTF-8**: malformed
/// содержимое без закрывающего маркера не паникует на многобайтовом символе.
fn contains_private_key_block(text: &str) -> bool {
const MARKER: &str = "-----BEGIN ";
const MAX_LABEL_BYTES: usize = 96;
let mut remaining = text;
while let Some(index) = remaining.find(MARKER) {
let after = &remaining[index + MARKER.len()..];
let label_end = after
.find("-----")
.unwrap_or_else(|| bounded_prefix_len(after, MAX_LABEL_BYTES));
let label = after[..label_end].to_ascii_uppercase();
if label.contains("PRIVATE KEY") {
return true;
}
remaining = &after[label_end..];
}
false
}
/// Длина префикса не больше `max_bytes`, оканчивающаяся на границе UTF-8.
fn bounded_prefix_len(text: &str, max_bytes: usize) -> usize {
let mut end = text.len().min(max_bytes);
while end > 0 && !text.is_char_boundary(end) {
end -= 1;
}
end
}
const CREDENTIAL_KEYS: &[&str] = &[
"password",
"passwd",
"passphrase",
"api_key",
"apikey",
"api_secret",
"secret_key",
"client_secret",
"credentials",
"credential",
"bearer_token",
"token",
"aws_access_key_id",
"aws_secret_access_key",
"aws_session_token",
"access_token",
"refresh_token",
"auth_token",
"authorization",
"private_key",
];
/// Raw credential assignment: `<credential-name> = <non-placeholder value>`
/// (также `:` и JSON-форма `"name": "value"`). Слова категорий без значения,
/// обычные ссылки и проза не являются нарушением. Минимальный размер значения и
/// наличие цифры не освобождают от проверки: неплейсхолдерное значение считается
/// сырым credential (TL F2).
fn contains_raw_credential_assignment(text: &str) -> bool {
text.lines().any(|line| {
let Some((key, value)) = split_assignment(line) else {
return false;
};
if !is_credential_key(&normalize_assignment_key(key)) {
return false;
}
let value = normalize_assignment_value(value);
!value.is_empty() && !is_placeholder_value(&value)
})
}
/// Семантический JSON: ключ распознаётся независимо от позиции в объекте и от
/// JSON-экранирования (`"pass\u0077ord"`), значения — по декодированным строкам.
/// Обычный текст и невалидный JSON сюда не попадают.
fn contains_json_raw_credential(text: &str) -> bool {
let trimmed = text.trim();
if !trimmed.starts_with(['{', '[']) {
return false;
}
let Ok(value) = serde_json::from_str::<Value>(trimmed) else {
return false;
};
json_value_has_raw_credential(&value)
}
fn json_value_has_raw_credential(value: &Value) -> bool {
match value {
Value::Object(map) => map.iter().any(|(key, value)| {
if is_credential_key(&normalize_assignment_key(key))
&& let Value::String(raw) = value
{
let raw = normalize_assignment_value(raw);
return !raw.is_empty() && !is_placeholder_value(&raw);
}
json_value_has_raw_credential(value)
}),
Value::Array(items) => items.iter().any(json_value_has_raw_credential),
_ => false,
}
}
fn split_assignment(line: &str) -> Option<(&str, &str)> {
let trimmed = line.trim();
if trimmed.is_empty()
|| trimmed.starts_with("http://")
|| trimmed.starts_with("https://")
|| trimmed.starts_with("crank://")
{
return None;
}
let equals = trimmed.find('=');
let colon = trimmed.find(':');
let index = match (equals, colon) {
(Some(equals), Some(colon)) => equals.min(colon),
(Some(equals), None) => equals,
(None, Some(colon)) => colon,
(None, None) => return None,
};
let (key, value) = trimmed.split_at(index);
Some((key, &value[1..]))
}
fn normalize_assignment_key(key: &str) -> String {
key.trim()
.trim_start_matches(|character: char| {
matches!(character, '{' | '[' | '"' | '\'' | '-' | ' ' | '\t')
})
.trim_end_matches(|character: char| {
matches!(character, '"' | '\'' | ' ' | '\t' | ',' | ';')
})
.replace(['-', '.'], "_")
.to_ascii_lowercase()
}
fn is_credential_key(key: &str) -> bool {
CREDENTIAL_KEYS.contains(&key)
|| [
"_password",
"_passwd",
"_secret",
"_token",
"_api_key",
"_access_key",
]
.iter()
.any(|suffix| key.ends_with(suffix))
}
fn normalize_assignment_value(value: &str) -> String {
value
.trim()
.trim_start_matches(['"', '\'', ' '])
.trim_end_matches(|character: char| {
matches!(character, '"' | '\'' | ',' | '}' | ']' | ';' | ' ' | '\t')
})
.to_owned()
}
/// Схема `Bearer ` без учёта ASCII-регистра. Возвращает остаток срезом, без
/// копии значения: вызывающей стороне нужен bounded разбор без аллокаций.
fn strip_bearer_scheme(value: &str) -> Option<&str> {
const SCHEME: &str = "bearer ";
let head = value.get(..SCHEME.len())?;
head.eq_ignore_ascii_case(SCHEME)
.then(|| &value[SCHEME.len()..])
}
fn is_placeholder_value(value: &str) -> bool {
// R2-F1: повторяющиеся scheme-префиксы разбираются итеративно и срезами, а
// lowercase-копия создаётся один раз после цикла. Рекурсивный вариант держал
// копию каждого остатка и рос квадратично по памяти и глубине стека на
// предельных stored bytes; здесь разбор линеен и не зависит от вложенности.
let mut current = value;
loop {
if current.is_empty() {
return true;
}
// Маска/многоточие/прочерк без единого алфавитно-цифрового символа — заглушка.
if !current.chars().any(char::is_alphanumeric) {
return true;
}
// `Authorization: Bearer ***` — заглушка того же вида с префиксом схемы.
match strip_bearer_scheme(current) {
Some(rest) => current = rest.trim(),
None => break,
}
}
let lowered = current.to_ascii_lowercase();
lowered.starts_with('<')
|| lowered.starts_with("${")
|| lowered.starts_with("{{")
|| lowered.starts_with("your-")
|| lowered.starts_with("your_")
|| matches!(
lowered.as_str(),
"null"
| "none"
| "undefined"
| "changeme"
| "change_me"
| "placeholder"
| "redacted"
| "..."
| "***"
| "password"
| "secret"
| "token"
| "example"
| "your-password"
| "your_password"
| "your-token"
| "your_token"
| "your-api-key"
| "your_api_key"
)
}
/// `Bearer <token>` с token-алфавитом и достаточной длиной; обычная прозаическая
/// фраза «Bearer token» не является нарушением. Наличие цифры не требуется: raw
/// credential без цифр — тот же raw credential (TL F2/F3).
fn contains_bearer_token(text: &str) -> bool {
let lowered = text.to_ascii_lowercase();
let mut offset = 0;
while let Some(index) = lowered[offset..].find("bearer ") {
let start = offset + index + "bearer ".len();
let token = text[start..].split_whitespace().next().unwrap_or_default();
let token =
token.trim_matches(|character: char| matches!(character, '"' | '\'' | ',' | ';'));
if token.len() >= 16
&& token.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'.' | b'_' | b'~' | b'+' | b'/' | b'-' | b'=')
})
&& !is_placeholder_value(token)
{
return true;
}
offset = start;
}
false
}
+610
View File
@@ -0,0 +1,610 @@
//! 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}");
}
}
}