[skip ci] wip: preserve Hermes crank development checkpoint

Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

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}");
}
}
}
+4
View File
@@ -1,4 +1,8 @@
mod unit {
mod prompt;
mod prompt_composition;
mod resource_drafts;
mod resource_template;
mod tool_catalog;
mod tool_quality;
}
+353
View File
@@ -0,0 +1,353 @@
use crank_core::prompt::{
PromptDefinition, PromptDraft, PromptError, PromptMessage, PromptRole, PromptSensitivity,
PromptStatus,
};
use serde_json::{Map, json};
fn definition() -> serde_json::Value {
json!({
"name": "welcome",
"description": "Greeting",
"arguments": [
{"name":"name", "schema":{"type":"string"}, "required":true},
{"name":"tone", "schema":{"type":"string", "enum":["warm","plain"]}, "required":false, "default":"warm"}
],
"messages": [
{"role":"system", "content":"Be {{tone}}."},
{"role":"user", "content":"Welcome {{name}}."}
]
})
}
#[test]
fn story312_prompt_draft_preserves_roles_order_and_typed_rendering() {
let prompt = PromptDefinition::parse(&definition()).unwrap();
let args = Map::from_iter([("name".into(), json!("Ada"))]);
assert_eq!(
prompt.preview(&args).unwrap(),
vec![
PromptMessage {
role: PromptRole::System,
content: "Be warm.".into(),
resource_refs: vec![],
},
PromptMessage {
role: PromptRole::User,
content: "Welcome Ada.".into(),
resource_refs: vec![],
},
]
);
assert_eq!(
prompt.preview(&args).unwrap(),
prompt.preview(&args).unwrap()
);
}
#[test]
fn story312_optional_argument_without_default_is_not_required() {
let mut value = definition();
value["arguments"][1]
.as_object_mut()
.unwrap()
.remove("default");
let prompt = PromptDefinition::parse(&value).unwrap();
let args = Map::from_iter([("name".into(), json!("Ada"))]);
assert_eq!(prompt.preview(&args).unwrap()[0].content, "Be .");
}
#[test]
fn story312_prompt_draft_has_typed_identity_lifecycle_and_snapshot() {
let draft = PromptDraft::new(
crank_core::ids::PromptId::new("prm_example"),
PromptSensitivity::Internal,
PromptDefinition::parse(&definition()).unwrap(),
);
assert_eq!(draft.prompt_id().as_str(), "prm_example");
assert_eq!(draft.version(), 1);
assert_eq!(draft.status(), PromptStatus::Draft);
assert_eq!(draft.sensitivity(), PromptSensitivity::Internal);
let published = draft.published_snapshot();
assert_eq!(published.prompt_id().as_str(), "prm_example");
assert_eq!(published.version(), 1);
assert_eq!(published.definition().name(), "welcome");
}
#[test]
fn story313_published_snapshot_keeps_the_v1_value_when_a_second_draft_version_exists() {
let v1_definition = PromptDefinition::parse(&definition()).unwrap();
let snapshot = PromptDraft::from_parts(
crank_core::ids::PromptId::new("prm_story313"),
1,
PromptStatus::Draft,
PromptSensitivity::Internal,
v1_definition.clone(),
)
.unwrap()
.published_snapshot();
let mut edited = definition();
edited["description"] = json!("Edited after publication");
edited["arguments"][0]["required"] = json!(false);
edited["messages"][1]["content"] = json!("Count {{name}}.");
let next_draft = PromptDraft::from_parts(
crank_core::ids::PromptId::new("prm_story313"),
2,
PromptStatus::Draft,
PromptSensitivity::Internal,
PromptDefinition::parse(&edited).unwrap(),
)
.unwrap();
// Опубликованный value-снимок сохраняет точное значение v1 …
assert_eq!(snapshot.version(), 1);
assert_eq!(snapshot.definition(), &v1_definition);
assert_eq!(snapshot.definition().description(), "Greeting");
assert!(snapshot.definition().arguments()[0].required());
assert_eq!(
snapshot.definition().arguments()[1].default(),
Some(&json!("warm"))
);
assert_eq!(
snapshot.definition().messages()[1].content,
"Welcome {{name}}."
);
// … а новая Draft-версия несёт уже изменённое значение.
assert_eq!(next_draft.version(), 2);
assert_ne!(next_draft.definition(), snapshot.definition());
assert_eq!(
next_draft.definition().messages()[1].content,
"Count {{name}}."
);
}
#[test]
fn story312_integer_arguments_are_rendered_as_scalar_values() {
let mut value = definition();
value["arguments"][0]["schema"]["type"] = json!("integer");
value["messages"][1]["content"] = json!("Count {{name}}.");
let prompt = PromptDefinition::parse(&value).unwrap();
let args = Map::from_iter([("name".into(), json!(7))]);
assert_eq!(prompt.preview(&args).unwrap()[1].content, "Count 7.");
}
#[test]
fn story312_boolean_and_number_arguments_render_as_json_scalars() {
let mut value = definition();
value["arguments"][0]["schema"]["type"] = json!("number");
value["arguments"].as_array_mut().unwrap().push(json!({
"name":"enabled", "schema":{"type":"boolean"}, "required":true
}));
value["messages"][1]["content"] = json!("Value={{name}}, enabled={{enabled}}");
let prompt = PromptDefinition::parse(&value).unwrap();
let args = Map::from_iter([("name".into(), json!(2.5)), ("enabled".into(), json!(true))]);
assert_eq!(
prompt.preview(&args).unwrap()[1].content,
"Value=2.5, enabled=true"
);
}
#[test]
fn story312_rejects_malformed_enum_schema_instead_of_dropping_constraint() {
let mut value = definition();
value["arguments"][1]["schema"]["enum"] = json!("not-an-array");
assert_eq!(
PromptDefinition::parse(&value),
Err(PromptError::InvalidDefinition)
);
let mut value = definition();
value["arguments"][1]["schema"]["enum"] = json!(["valid", 42]);
assert_eq!(
PromptDefinition::parse(&value),
Err(PromptError::InvalidDefinition)
);
let mut value = definition();
value["arguments"][1]["schema"]["maxLength"] = json!(8);
assert_eq!(
PromptDefinition::parse(&value),
Err(PromptError::InvalidDefinition)
);
}
#[test]
fn story312_preview_bounds_final_rendered_output() {
let mut value = definition();
value["messages"][0]["content"] = json!("{{name}}{{name}}");
let prompt = PromptDefinition::parse(&value).unwrap();
let args = Map::from_iter([("name".into(), json!("x".repeat(9_000)))]);
assert_eq!(prompt.preview(&args), Err(PromptError::InvalidTemplate));
}
#[test]
fn story312_invalid_args_fail_before_any_rendered_messages() {
let prompt = PromptDefinition::parse(&definition()).unwrap();
assert_eq!(
prompt.preview(&Map::new()),
Err(PromptError::MissingArgument("name".into()))
);
let mut args = Map::from_iter([("name".into(), json!("Ada")), ("extra".into(), json!(1))]);
assert_eq!(
prompt.preview(&args),
Err(PromptError::UnknownArgument("extra".into()))
);
args.remove("extra");
args.insert("tone".into(), json!("loud"));
assert_eq!(
prompt.preview(&args),
Err(PromptError::InvalidArgument("tone".into()))
);
}
#[test]
fn story312_rejects_duplicate_arguments_unknown_roles_and_executable_templates() {
let mut value = definition();
value["arguments"]
.as_array_mut()
.unwrap()
.push(json!({"name":"name","schema":{"type":"string"},"required":true}));
assert!(PromptDefinition::parse(&value).is_err());
let mut value = definition();
value["messages"][0]["role"] = json!("developer");
assert!(PromptDefinition::parse(&value).is_err());
let mut value = definition();
value["messages"][0]["content"] = json!("{{= dangerous() }}");
assert!(PromptDefinition::parse(&value).is_err());
}
fn defaulted(default: serde_json::Value) -> serde_json::Value {
json!({
"name": "welcome",
"description": "Greeting",
"arguments": [{"name":"tone","schema":{"type":"string"},"required":false,"default":default}],
"messages": [{"role":"user","content":"{{tone}}"}]
})
}
#[test]
fn story312_default_values_fit_the_stored_json_text_size() {
// Storage keeps `octet_length(default_value::text) <= 16384`; JSON adds the
// surrounding quotes, so 16382 bytes of plain text is the exact ceiling.
let at_limit = defaulted(json!("a".repeat(16_382)));
let prompt =
PromptDefinition::parse(&at_limit).expect("the exact storage boundary is accepted");
let rendered = prompt
.preview(&Map::new())
.expect("bounded default previews");
assert_eq!(rendered[0].content.len(), 16_382);
assert_eq!(
PromptDefinition::parse(&defaulted(json!("a".repeat(16_383)))),
Err(PromptError::InvalidDefinition)
);
// Escaped content costs more than one byte per character in PostgreSQL.
assert!(PromptDefinition::parse(&defaulted(json!("\"".repeat(8_190)))).is_ok());
assert_eq!(
PromptDefinition::parse(&defaulted(json!("\"".repeat(8_192)))),
Err(PromptError::InvalidDefinition)
);
assert!(PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_730)))).is_ok());
assert_eq!(
PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_731)))),
Err(PromptError::InvalidDefinition)
);
}
#[test]
fn story312_short_escape_defaults_match_the_postgres_jsonb_text_size() {
// PostgreSQL writes LF/TAB/CR/BS/FF as two-byte short escapes, while other
// control characters stay six-byte `\u00XX`, so both fit differently.
for (label, unit) in [
("lf", '\n'),
("tab", '\t'),
("cr", '\r'),
("backspace", '\u{8}'),
("formfeed", '\u{c}'),
] {
let at_limit = unit.to_string().repeat(8_191);
let prompt = PromptDefinition::parse(&defaulted(json!(at_limit))).unwrap_or_else(|error| {
panic!("{label} at the exact boundary must be accepted: {error:?}")
});
assert_eq!(
prompt.preview(&Map::new()).unwrap()[0].content,
unit.to_string().repeat(8_191),
"{label} defaults must preview the original text"
);
assert_eq!(
PromptDefinition::parse(&defaulted(json!(unit.to_string().repeat(8_192)))),
Err(PromptError::InvalidDefinition),
"{label} beyond the boundary is rejected"
);
}
// A multiline default stays well inside the guard even though it is long.
assert!(PromptDefinition::parse(&defaulted(json!("\n\t".repeat(4_000)))).is_ok());
// 0x01 still costs six bytes, so only 2730 of them fit.
assert!(PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_730)))).is_ok());
assert_eq!(
PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_731)))),
Err(PromptError::InvalidDefinition)
);
}
#[test]
fn story312_rejects_nul_before_storage_for_every_stored_string() {
// PostgreSQL refuses U+0000 in `text` ("null character not permitted") and in
// `jsonb` ("\\u0000 cannot be converted to text"), so it must fail as a
// structured definition error before any SQL runs.
assert_eq!(
PromptDefinition::parse(&defaulted(json!("a\u{0}b"))),
Err(PromptError::InvalidDefinition)
);
let mut enum_value = definition();
enum_value["arguments"][1]["schema"]["enum"] = json!(["warm", "a\u{0}b"]);
assert_eq!(
PromptDefinition::parse(&enum_value),
Err(PromptError::InvalidDefinition),
"an enum value is stored as jsonb and must not carry U+0000"
);
for (label, mutate) in [
(
"name",
Box::new(|value: &mut serde_json::Value| value["name"] = json!("a\u{0}b"))
as Box<dyn Fn(&mut serde_json::Value)>,
),
(
"description",
Box::new(|value: &mut serde_json::Value| value["description"] = json!("a\u{0}b")),
),
(
"argument name",
Box::new(|value: &mut serde_json::Value| {
value["arguments"][0]["name"] = json!("a\u{0}b")
}),
),
(
"message content",
Box::new(|value: &mut serde_json::Value| {
value["messages"][0]["content"] = json!("a\u{0}b")
}),
),
] {
let mut value = definition();
mutate(&mut value);
assert_eq!(
PromptDefinition::parse(&value),
Err(PromptError::InvalidDefinition),
"{label} is stored as text and must not carry U+0000"
);
}
}
#[test]
fn story312_enumeration_values_fit_the_stored_json_text_size() {
let mut value = defaulted(serde_json::Value::Null);
value["arguments"][0]["default"] = json!("x");
value["arguments"][0]["schema"]["enum"] = json!(["x"]);
assert!(PromptDefinition::parse(&value).is_ok());
value["arguments"][0]["schema"]["enum"] = json!(["x", "a".repeat(16_383)]);
assert_eq!(
PromptDefinition::parse(&value),
Err(PromptError::InvalidDefinition)
);
value["arguments"][0]["schema"]["enum"] = json!(["x", "a".repeat(16_382)]);
assert!(PromptDefinition::parse(&value).is_ok());
}
@@ -0,0 +1,280 @@
//! ATDD (RED) для Story 3.16, AC-группы 1, 2 и 5 на уровне чистого домена.
//!
//! Источники: `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-prompt-composition/contract.md`
//! §1–§3, `epics.md`:2920–2986 (FR-18), `docs/acceptance-test-plan.md` AT-3.16-01/02/05/10.
//!
//! Состояние на момент написания: `PromptDefinition` не знает `dependencies` и `resource_refs`,
//! поэтому каждый RED ниже — поведенческое расхождение `parse`/`as_json` на реальном публичном
//! API `crank-core` (rед принимает точную ссылку → сегодня `Err(InvalidDefinition)`), а не ошибка
//! компиляции или setup. Контроли `*_rejects_*` фиксируют инварианты, которые обязаны сохраниться
//! после реализации; сегодня часть из них проходит вакуумно (любая dependency отклоняется) —
//! это указано в имени/комментарии каждого такого теста.
//!
//! Фильтр запуска: `cargo test -p crank-core --test unit prompt_composition`.
use crank_core::prompt::{PromptDefinition, PromptError};
use serde_json::{Value, json};
/// Минимальное корректное определение с одной точной dependency.
fn composed(dependencies: Value, resource_refs: Option<Value>) -> Value {
let mut message = json!({"role": "user", "content": "Channel: {{channel}}"});
if let Some(refs) = resource_refs {
message["resource_refs"] = refs;
}
json!({
"name": "release-notes",
"description": "Summarise the pinned changelog",
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
message
],
"dependencies": dependencies
})
}
fn exact_dependency(index: u32) -> Value {
json!({"resource_id": format!("res_exact_{index:02}"), "version": 3})
}
/// AT-3.16-01: точная опубликованная ссылка входит в definition без потери полей.
///
/// RED сегодня: `parse` отклоняет неизвестный ключ `dependencies`.
#[test]
fn at_3_16_01_definition_accepts_exact_pinned_dependency() {
let definition = PromptDefinition::parse(&composed(
json!([{"resource_id": "res_exact_01", "version": 3}]),
Some(json!([0])),
))
.expect("an exact pinned dependency must be a valid definition");
let serialized = definition.as_json();
assert_eq!(
serialized["dependencies"],
json!([{"resource_id": "res_exact_01", "version": 3}]),
"the exact reference must round-trip unchanged"
);
assert_eq!(
serialized["messages"][1]["resource_refs"],
json!([0]),
"the declared insertion point must round-trip unchanged"
);
assert_eq!(serialized["messages"][0]["role"], json!("system"));
assert_eq!(definition.messages().len(), 2, "messages are unchanged");
}
/// AT-3.16-01: mutable/foreign-адресация невыразима.
///
/// NC-vacuous: сегодня проходит потому, что любая dependency отклоняется. После реализации
/// каждый вариант обязан отклоняться именно как `InvalidDefinition`.
#[test]
fn at_3_16_01_definition_rejects_mutable_and_foreign_reference_shapes() {
for rejected in [
// mutable: URI вместо точной идентичности
json!([{"uri": "crank://resources/changelog"}]),
// mutable: плавающий указатель версии
json!([{"resource_id": "res_exact_01", "version": "latest"}]),
json!([{"resource_id": "res_exact_01", "version": "*"}]),
// точная, но недопустимая версия
json!([{"resource_id": "res_exact_01", "version": 0}]),
// identity не задаётся клиентом: workspace приходит из URL/сессии
json!([{"resource_id": "res_exact_01", "version": 3, "workspace_id": "ws_foreign"}]),
// лишние/подменяющие поля
json!([{"resource_id": "res_exact_01", "version": 3, "digest": "00"}]),
json!([{"resource_id": 7, "version": 3}]),
json!([{"resource_id": "res_exact_01"}]),
json!(["res_exact_01@3"]),
] {
assert_eq!(
PromptDefinition::parse(&composed(rejected.clone(), None)).err(),
Some(PromptError::InvalidDefinition),
"a mutable/foreign shaped reference must be rejected: {rejected}"
);
}
}
/// AT-3.16-02: count bound и уникальность целей.
///
/// RED в части «16 принимаются»; отказ на 17-й и на дубле — инвариант, который обязан
/// сохраниться (сегодня тоже отказ, вакуумно).
#[test]
fn at_3_16_02_definition_bounds_dependency_count_and_uniqueness() {
let accepted: Vec<Value> = (1..=16).map(exact_dependency).collect();
let dependencies = Value::Array(accepted);
assert!(
PromptDefinition::parse(&composed(dependencies.clone(), None)).is_ok(),
"16 dependencies are inside the documented bound (contract §1)"
);
let mut too_many: Vec<Value> = (1..=17).map(exact_dependency).collect();
assert_eq!(
PromptDefinition::parse(&composed(Value::Array(too_many.clone()), None)).err(),
Some(PromptError::InvalidDefinition),
"17 dependencies exceed MAX_PROMPT_DEPENDENCIES"
);
too_many.truncate(2);
too_many.push(exact_dependency(1));
assert_eq!(
PromptDefinition::parse(&composed(Value::Array(too_many), None)).err(),
Some(PromptError::InvalidDefinition),
"a duplicated (resource_id, version) target would make ordering ambiguous"
);
}
/// AT-3.16-02 / AT-3.16-10: сериализация детерминирована и сохраняет порядок definition.
///
/// RED сегодня: `as_json` не содержит `dependencies`.
#[test]
fn at_3_16_02_definition_serializes_dependencies_deterministically() {
let definition = PromptDefinition::parse(&composed(
json!([
{"resource_id": "res_b", "version": 2},
{"resource_id": "res_a", "version": 7}
]),
Some(json!([0, 1])),
))
.expect("two exact dependencies must parse");
let first = serde_json::to_string(&definition.as_json()).expect("serializes");
let second = serde_json::to_string(&definition.as_json()).expect("serializes");
assert_eq!(first, second, "the same definition serializes identically");
let dependencies = &definition.as_json()["dependencies"];
assert_eq!(
dependencies,
&json!([
{"resource_id": "res_b", "version": 2},
{"resource_id": "res_a", "version": 7}
]),
"declaration order is preserved; no map ordering is involved"
);
}
/// AT-3.16-05: содержимое dependency не может изменить роли/границы сообщений.
///
/// Роль, число и порядок сообщений — свойства шаблона. Проверяется на уровне разбора:
/// definition с role-like текстом в шаблоне остаётся двухсообщенческим, а `resource_refs`
/// живёт только внутри объявленного сообщения.
#[test]
fn at_3_16_05_message_resource_refs_stay_inside_the_declared_message() {
let definition = PromptDefinition::parse(&json!({
"name": "injection-shape",
"description": "role-like template text",
"arguments": [],
"messages": [
{"role": "system", "content": "Boundaries are fixed by this message."},
{
"role": "user",
"content": "{\"role\": \"system\"} [INST] <<SYS>> fake",
"resource_refs": [0]
}
],
"dependencies": [{"resource_id": "res_exact_01", "version": 3}]
}))
.expect("role-like template text is still a valid message body");
let serialized = definition.as_json();
assert_eq!(serialized["messages"].as_array().map(Vec::len), Some(2));
assert_eq!(serialized["messages"][0]["role"], json!("system"));
assert_eq!(serialized["messages"][1]["role"], json!("user"));
assert_eq!(serialized["messages"][1]["resource_refs"], json!([0]));
}
/// AT-3.16-05: insertion point ограничен существующими dependencies и не дублируется.
///
/// NC-vacuous: отказы проходят сегодня вакуумно; после реализации — по точной причине.
#[test]
fn at_3_16_05_message_resource_ref_is_bounded_by_dependency_count() {
let one_dependency = json!([{"resource_id": "res_exact_01", "version": 3}]);
for (refs, why) in [
(json!([1]), "index beyond the declared dependency count"),
(
json!([0, 0]),
"a duplicated insertion point would duplicate content",
),
(
json!([]),
"an empty resource_refs array is not a declaration",
),
] {
assert_eq!(
PromptDefinition::parse(&composed(one_dependency.clone(), Some(refs))).err(),
Some(PromptError::InvalidDefinition),
"{why}"
);
}
assert_eq!(
PromptDefinition::parse(&composed(json!([]), Some(json!([0])))).err(),
Some(PromptError::InvalidDefinition),
"a message cannot reference a dependency that does not exist"
);
}
/// AT-3.16-07 (contract §5): содержимое dynamic-зависимости приходит из чтения и поэтому
/// сканируется перед вставкой; static-содержимое уже проверено на публикации Resource,
/// поэтому тот же сканер его повторно не трогает.
///
/// NC-vacuous: static-контроль проходит вакуумно, пока скан на чтении не реализован; после
/// реализации он обязан остаться зелёным (никакого двойного наказания за статику).
#[test]
fn at_3_16_07_dynamic_content_is_scanned_before_insertion() {
use crank_core::prompt::PromptSensitivity;
use crank_core::prompt_composition::{
PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass, render,
};
use crank_core::resource::ResourceKind;
let definition = PromptDefinition::parse(&composed(
json!([{"resource_id": "res_exact_01", "version": 3}]),
Some(json!([0])),
))
.expect("definition parses");
let pin = |source_class| PromptDependencyPin {
position: 0,
resource_id: "res_exact_01".to_owned(),
version: 3,
digest: "sha256:aa".to_owned(),
kind: ResourceKind::Text,
mime_type: "text/plain".to_owned(),
source_class,
sensitivity: PromptSensitivity::Internal,
};
let arguments = serde_json::Map::from_iter([("channel".to_owned(), json!("ops"))]);
let credential = b"Authorization: Bearer sk-live-0123456789abcdef".to_vec();
assert_eq!(
render(
&definition,
&[pin(PromptDependencySourceClass::Dynamic)],
&arguments,
&[Some(credential.clone())],
)
.err(),
Some(PromptCompositionError::DependencyCredentialFinding { position: 0 }),
"read-time content with a raw credential is refused"
);
assert!(
render(
&definition,
&[pin(PromptDependencySourceClass::Static)],
&arguments,
&[Some(credential)],
)
.is_ok(),
"published static content was already scanned at publication (control)"
);
let directive = b"include: crank://resources/private-notes".to_vec();
assert_eq!(
render(
&definition,
&[pin(PromptDependencySourceClass::Dynamic)],
&arguments,
&[Some(directive)],
)
.err(),
Some(PromptCompositionError::DependencyAccessBypassFinding { position: 0 }),
"read-time content with an explicit include: directive is refused"
);
}
@@ -0,0 +1,734 @@
//! BUILD-ONLY: доменные проверки Story 3.6 (AT-3.6-01/03/04/05, таргет D).
//!
//! Статус файла на стадии Dev ATDD: **не зарегистрирован** в `tests/unit.rs`
//! (`mod unit { mod resource_drafts; }` добавляет BUILD), поэтому он не компилируется и не
//! исполняется. Причина — production-типы (`crank_core::resource::*`) ещё не существуют;
//! включать этот файл в runnable-таргет до реализации нельзя (иначе RED подменяется ошибкой
//! компиляции). Коллекция этого файла = 0, и это не PASS.
//!
//! Минимальный будущий интерфейс (SPEC v4 §5), на который опираются тесты ниже:
//! - `crank_core::resource::{Resource, ResourceVersion, PublishedResourceVersion, ResourceKind,
//! ResourceSensitivity, ResourceStatus, ResourceLifecycle, ResourceLimits, ResourceFinding,
//! ResourceFindingCode, CapabilityKind, CapabilityRef, ResourceMetadata}`;
//! - `crank_core::ids::ResourceId` (`define_id!(ResourceId)`);
//! - грамматики/валидаторы: `ResourceMetadata::validate()`, URI/name/MIME-грамматики D-10/D-11/D-4,
//! allowlist D-5, JSON-политика D-8/D-8.1, UTF-8 D-9, пределы `ResourceLimits` D-3;
//! - `PublishedResourceVersion` — immutable-модель без `path`/`file_name`/`storage_ref`/`source_id`.
//!
//! Фиксированные имена тестов (SPEC §2) перечислены в заголовках; они должны появиться здесь
//! при BUILD без переименования.
use crank_core::resource::{
CapabilityKind, CapabilityRef, PublishedResourceVersion, Resource, ResourceKind,
ResourceLifecycle, ResourceLifecycleAction, ResourceLimits, ResourceMetadata,
ResourceSensitivity, ResourceStatus, ResourceVersion, publication_include_directives,
publication_secret_findings,
};
use serde_json::Value;
const LIMIT: usize = 256 * 1024;
#[test]
fn story36_at01_resource_is_a_separate_typed_aggregate() {
// typed mismatch вместо поиска слов: Operation-ref не принимается там, где нужен Resource-ref.
let reference = CapabilityRef::Resource(crank_core::ids::ResourceId::new("res_story36_draft"));
assert_eq!(reference.kind(), CapabilityKind::Resource);
let resource = Resource::draft(
crank_core::ids::ResourceId::new("res_story36_draft"),
ResourceMetadata {
uri: "crank://docs/readme".to_owned(),
name: "readme_page".to_owned(),
description: String::new(),
kind: ResourceKind::Text,
mime_type: "text/plain".to_owned(),
sensitivity: ResourceSensitivity::Internal,
},
);
assert_eq!(resource.status(), ResourceStatus::Draft);
assert_eq!(resource.current_draft_version(), 1);
// serde roundtrip typed полей: wire-значения D-2 не меняются.
let encoded = serde_json::to_value(&resource).expect("resource must serialize");
assert_eq!(encoded["kind"], serde_json::json!("text"));
assert_eq!(encoded["status"], serde_json::json!("draft"));
assert_eq!(encoded["sensitivity"], serde_json::json!("internal"));
let decoded: Resource = serde_json::from_value(encoded).expect("resource must deserialize");
assert_eq!(decoded, resource);
}
#[test]
fn story36_at01_published_version_is_immutable_after_draft_edit() {
let draft = ResourceVersion::draft(
1,
ResourceKind::Json,
"application/json".to_owned(),
12,
"a".repeat(64),
);
let published = PublishedResourceVersion::from_draft(&draft);
let published_bytes = serde_json::to_value(&published).expect("published must serialize");
// «Редактирование» черновика: новая версия других bytes/metadata. Опубликованный снимок
// обязан держать собственные данные и не меняться от появления/изменения черновика.
let edited = ResourceVersion::draft(
2,
ResourceKind::Binary,
"image/png".to_owned(),
34,
"b".repeat(64),
);
assert_eq!(
serde_json::to_value(&published).expect("published must serialize"),
published_bytes
);
// Published-модель конструируется только из Draft и не имеет мутирующих методов.
let _: &PublishedResourceVersion = &published;
assert_ne!(published.version(), edited.version());
assert_ne!(published.digest(), edited.digest());
}
#[test]
fn story36_at01_invalid_lifecycle_transition_is_rejected() {
// архив/публикация в 3.6 не реализуются, но модель обязана отвергать недопустимый переход.
assert!(ResourceStatus::Draft.can_transition_to(ResourceStatus::Published));
assert!(!ResourceStatus::Archived.can_transition_to(ResourceStatus::Draft));
// R-D: проверяется настоящий вызов перехода, а не только таблица допустимости:
// допустимые пары возвращают проверенный переход, недопустимые — фиксированную ошибку.
for (from, action, to) in [
(
ResourceStatus::Draft,
ResourceLifecycleAction::Publish,
ResourceStatus::Published,
),
(
ResourceStatus::Draft,
ResourceLifecycleAction::Archive,
ResourceStatus::Archived,
),
(
ResourceStatus::Published,
ResourceLifecycleAction::Revert,
ResourceStatus::Draft,
),
(
ResourceStatus::Published,
ResourceLifecycleAction::Archive,
ResourceStatus::Archived,
),
] {
let transition = ResourceLifecycle::transition(from, action)
.unwrap_or_else(|error| panic!("{from} -> {action:?} must be allowed: {error:?}"));
assert_eq!(transition.from, from);
assert_eq!(transition.action, action);
assert_eq!(transition.to(), to);
}
for (from, action, to) in [
(
ResourceStatus::Archived,
ResourceLifecycleAction::Publish,
ResourceStatus::Published,
),
(
ResourceStatus::Archived,
ResourceLifecycleAction::Revert,
ResourceStatus::Draft,
),
(
ResourceStatus::Archived,
ResourceLifecycleAction::Archive,
ResourceStatus::Archived,
),
] {
let error = ResourceLifecycle::transition(from, action)
.expect_err("an archived Resource must not transition anywhere in 3.6");
assert_eq!(error.code(), "resource_lifecycle_invalid");
assert_eq!(
error,
crank_core::resource::ResourceError::InvalidLifecycleTransition { from, to },
"the refusal must name the exact transition that was attempted"
);
}
}
#[test]
fn story36_at02_metadata_grammar_accepts_and_rejects_exact_boundaries() {
let uri_192 = format!("crank://{}", "a".repeat(192));
let uri_193 = format!("crank://{}", "a".repeat(193));
for (label, uri, expected) in [
("min-10", "crank://ab".to_owned(), true),
("max-200", uri_192, true),
("inner-underscore", "crank://a_b".to_owned(), true),
("double-dot-segment", "crank://a..b".to_owned(), true),
("too-short", "crank://a".to_owned(), false),
("too-long", uri_193, false),
("trailing-underscore", "crank://a_".to_owned(), false),
("empty-segment", "crank://a//b".to_owned(), false),
("uppercase-scheme", "CRANK://a".to_owned(), false),
("percent-encoding", "crank://a%2Fb".to_owned(), false),
] {
assert_eq!(
ResourceMetadata::uri_is_valid(&uri),
expected,
"URI grammar boundary `{label}`"
);
}
}
#[test]
fn story36_at03_published_serializer_has_no_path_filename_or_source_id() {
let draft = ResourceVersion::draft(
1,
ResourceKind::Text,
"text/plain".to_owned(),
5,
"c".repeat(64),
);
let published = serde_json::to_value(PublishedResourceVersion::from_draft(&draft))
.expect("published must serialize");
let serialized = published.to_string();
for forbidden in [
"path",
"file_name",
"storage_ref",
"source_id",
"artifact_ref",
] {
assert!(
!serialized.contains(forbidden),
"published contract must not expose `{forbidden}` (D-12): {serialized}"
);
}
}
#[test]
fn story36_at04_json_semantics_preserved_byte_exact() {
let document = "{\"b\":1,\"a\":[1,2,3],\"дубликат\":1,\"дубликат\":2,\"nested\":{\"n\":1e308}}";
let validation = ResourceMetadata::validate_json(document.as_bytes(), LIMIT);
assert!(
validation.is_ok(),
"valid JSON must be accepted: {validation:?}"
);
// Oracle — байты, а не разобранное `Value`: порядок ключей и дубликаты сохраняются.
assert_eq!(
validation.expect("accepted").as_slice(),
document.as_bytes()
);
}
#[test]
fn story36_at04_numeric_policy_of_selected_parser() {
// D-8.1: точные границы фактического парсера (serde_json 1.0.150 без features).
for accepted in ["1e308", "1.7e308", "18446744073709551616", "1e-400", "-0"] {
assert!(
ResourceMetadata::validate_json(accepted.as_bytes(), LIMIT).is_ok(),
"`{accepted}` must be accepted by the locked parser"
);
}
for rejected in ["1e309", "9e308", "1.8e308", "1e1000000000000000000000"] {
let error = ResourceMetadata::validate_json(rejected.as_bytes(), LIMIT)
.expect_err("out-of-range number must be rejected as invalid JSON");
assert_eq!(error.code(), "resource_content_invalid_json");
}
}
#[test]
fn story36_at05_utf8_boundary_and_truncation_are_rejected() {
let valid = "Привет 🚀\nвторая строка".as_bytes();
let accepted = ResourceMetadata::validate_text(valid, LIMIT).expect("valid UTF-8 must pass");
assert_eq!(
accepted.as_slice(),
valid,
"text bytes and checksum stay byte-exact"
);
for invalid in [
vec![0xFF],
vec![0xC3, 0x28],
vec![0xC0, 0xAF],
vec![0x80],
vec![0xF0, 0x9F, 0x92],
] {
let error = ResourceMetadata::validate_text(&invalid, LIMIT)
.expect_err("invalid UTF-8 must be rejected without replacement");
assert_eq!(error.code(), "resource_content_invalid_utf8");
}
// Границы L-1/L/L+1: многобайтовый символ не обрезается.
let l_minus_one = vec![b'a'; LIMIT - 1];
let l = vec![b'a'; LIMIT];
let l_plus_one = vec![b'a'; LIMIT + 1];
assert!(ResourceMetadata::validate_text(&l_minus_one, LIMIT).is_ok());
assert!(
ResourceMetadata::validate_text(&l, LIMIT).is_ok(),
"L is inclusive"
);
assert_eq!(
ResourceMetadata::validate_text(&l_plus_one, LIMIT)
.expect_err("L+1 must be rejected as a whole")
.code(),
"resource_content_too_large"
);
// Многобайтовый символ РОВНО на границе: целиком в лимите — принят байт-в-байт,
// не помещается — отвергнут целиком (D-9), а не усечён до префикса.
let mut multibyte_at_limit = vec![b'a'; LIMIT - 2];
multibyte_at_limit.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(multibyte_at_limit.len(), LIMIT);
let accepted = ResourceMetadata::validate_text(&multibyte_at_limit, LIMIT)
.expect("a multibyte char that fits within L must be accepted");
assert_eq!(
accepted.as_slice(),
multibyte_at_limit.as_slice(),
"no truncation and no replacement may occur at the boundary"
);
let mut multibyte_over_limit = vec![b'a'; LIMIT - 1];
multibyte_over_limit.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(multibyte_over_limit.len(), LIMIT + 1);
assert_eq!(
ResourceMetadata::validate_text(&multibyte_over_limit, LIMIT)
.expect_err("a multibyte char that does not fit must be rejected as a whole")
.code(),
"resource_content_too_large"
);
}
#[test]
fn story36_at06_unknown_or_unsupported_mime_is_a_safe_finding() {
let limits = ResourceLimits::default();
assert_eq!(limits.effective_limit(ResourceKind::Text), LIMIT);
let finding = ResourceMetadata::mime_finding("application/zip", ResourceKind::Binary, &limits);
assert_eq!(finding.code(), "resource_mime_not_allowed");
// Метаданные не отдают `Value`, только фиксированный finding без bytes.
let json_finding = ResourceMetadata::json_finding(b"{", &limits);
assert_eq!(json_finding.code(), "resource_content_invalid_json");
let _: Value = serde_json::to_value(json_finding).expect("findings must serialize");
}
// ---------------------------------------------------------------------------
// P5 (affected ATDD до исправления): полная числовая/структурная политика,
// configured small-L и типизированная несовместимость capability-ссылок.
// ---------------------------------------------------------------------------
#[test]
fn story36_at04_numeric_policy_full_selected_parser_matrix() {
// D-8.1: точные границы фактического locked-парсера (serde_json без features).
// Oracle каждого принятого числа — побайтовое чтение исходного лексема.
let accepted = [
"0",
"-0",
"9007199254740993",
"18446744073709551615",
"18446744073709551616",
"-9223372036854775808",
"-9223372036854775809",
"0.1000000000000000000000001",
"1.000000000000000000000000000000001",
"123456789012345678901234567890",
"1e308",
"1.7e308",
"1e-309",
"1e-400",
"1e-1000000000000000000000",
"0e1000000000000000000000",
];
for document in accepted {
let readback = ResourceMetadata::validate_json(document.as_bytes(), LIMIT)
.unwrap_or_else(|error| panic!("`{document}` must be accepted (D-8.1): {error:?}"));
assert_eq!(
readback.as_slice(),
document.as_bytes(),
"an accepted numeric lexeme must be stored byte-exact, not re-serialized (D-8)"
);
}
let mut long_integer = String::from("1");
long_integer.push_str(&"0".repeat(400));
let rejected = [
"1e309",
"-1e309",
"9e308",
"1.8e308",
"1e1000000000000000000000",
long_integer.as_str(),
];
for document in rejected {
let error = ResourceMetadata::validate_json(document.as_bytes(), LIMIT).expect_err(
"a number outside f64 representability must be rejected as invalid JSON (D-8.1)",
);
assert_eq!(error.code(), "resource_content_invalid_json");
assert_eq!(error.field(), Some("content"));
}
}
#[test]
fn story36_at04_top_level_values_and_recursion_depth_policy() {
// D-8: top-level — любое валидное значение; bytes хранятся дословно.
for document in [
"null",
"true",
"false",
"0",
"-1",
"\"text\"",
"123",
"[]",
"{}",
"{\"ключ\":\"значение\"}",
"\"\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442\"",
// Литеральный (не escape-формы) Unicode: кириллица, эмодзи и комбинирующая
// последовательность обязаны читаться обратно байт-в-байт (R-D).
"{\"привет\":\"мир\"}",
"{\"emoji\":\"🚀🦀\"}",
"\"e\\u0301\"",
"[\"Привет\",\"🚀\",null,false]",
] {
let readback = ResourceMetadata::validate_json(document.as_bytes(), LIMIT)
.unwrap_or_else(|error| panic!("top-level `{document}` must be accepted: {error:?}"));
assert_eq!(
readback.as_slice(),
document.as_bytes(),
"accepted JSON must be stored byte-exact, including literal Unicode (D-8)"
);
}
let nested_ok = format!("{}1{}", "[".repeat(100), "]".repeat(100));
assert!(
ResourceMetadata::validate_json(nested_ok.as_bytes(), LIMIT).is_ok(),
"nesting below the parser recursion limit must be accepted"
);
let nested_over = format!("{}1{}", "[".repeat(300), "]".repeat(300));
let error = ResourceMetadata::validate_json(nested_over.as_bytes(), LIMIT)
.expect_err("nesting above the parser recursion limit must be rejected (D-8)");
assert_eq!(error.code(), "resource_content_invalid_json");
}
#[test]
fn story36_at05_configured_small_limit_boundaries_per_kind() {
let small = ResourceLimits::uniform(8).expect("8 bytes is inside the storage ceiling");
assert_eq!(small.effective_limit(ResourceKind::Text), 8);
assert_eq!(small.effective_limit(ResourceKind::Json), 8);
assert_eq!(small.effective_limit(ResourceKind::Binary), 8);
// text: L-1 и L приняты байт-в-байт, L+1 отвергнут целиком (D-3/D-9).
let text = |bytes: &[u8]| {
ResourceMetadata::validate_content(ResourceKind::Text, "text/plain", bytes, &small)
};
assert!(text(&[b'a'; 7]).is_ok(), "text L-1 must be accepted");
let accepted = text(&[b'a'; 8]).expect("text L must be accepted inclusively");
assert_eq!(accepted.len(), 8);
assert_eq!(
text(&[b'a'; 9])
.expect_err("text L+1 must be rejected as a whole")
.code(),
"resource_content_too_large"
);
// Многобайтовый символ ровно на границе малого L не обрезается.
let mut multibyte_fits = vec![b'a'; 6];
multibyte_fits.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(multibyte_fits.len(), 8);
assert!(text(&multibyte_fits).is_ok());
let mut multibyte_over = vec![b'a'; 7];
multibyte_over.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(multibyte_over.len(), 9);
assert_eq!(
text(&multibyte_over)
.expect_err("a multibyte char above small L must reject the whole body")
.code(),
"resource_content_too_large"
);
// json: границы и отдельный код для malformed внутри лимита.
let json = |bytes: &[u8]| {
ResourceMetadata::validate_content(ResourceKind::Json, "application/json", bytes, &small)
};
assert!(json(b"[1,2,3]").is_ok(), "json L-1 must be accepted");
assert!(json(b"[1,2,34]").is_ok(), "json L must be accepted");
assert_eq!(
json(b"[1,2,345]")
.expect_err("json L+1 must be rejected")
.code(),
"resource_content_too_large"
);
assert_eq!(
json(b"{1,2,34}")
.expect_err("malformed json inside the limit keeps its own code")
.code(),
"resource_content_invalid_json"
);
// binary: любые байты (в т.ч. не-UTF8) в пределах L.
let binary = |bytes: &[u8]| {
ResourceMetadata::validate_content(
ResourceKind::Binary,
"application/octet-stream",
bytes,
&small,
)
};
assert!(binary(&[0x00, 0xFF, 0x80, 0xC3, 0x28, 0x01, 0x02]).is_ok());
assert!(binary(&[0x00; 8]).is_ok());
assert_eq!(
binary(&[0x00; 9])
.expect_err("binary L+1 must be rejected")
.code(),
"resource_content_too_large"
);
// Пустое содержимое отвергается для всех kinds при любом configured L (D-7).
for (kind, mime) in [
(ResourceKind::Text, "text/plain"),
(ResourceKind::Json, "application/json"),
(ResourceKind::Binary, "application/octet-stream"),
] {
assert_eq!(
ResourceMetadata::validate_content(kind, mime, b"", &small)
.expect_err("empty content must be rejected for every kind")
.code(),
"resource_content_empty"
);
}
// Configured L выше storage ceiling отвергается при конфигурации (D-3).
assert!(ResourceLimits::uniform(262_145).is_err());
let mixed = ResourceLimits::new(4, 8, 16).expect("mixed limits inside the ceiling");
assert_eq!(mixed.effective_limit(ResourceKind::Text), 4);
assert_eq!(mixed.effective_limit(ResourceKind::Json), 8);
assert_eq!(mixed.effective_limit(ResourceKind::Binary), 16);
}
#[test]
fn story36_at01_capability_refs_are_type_disjoint() {
let resource_id = crank_core::ids::ResourceId::new("res_story36_ref");
let resource_ref = CapabilityRef::Resource(resource_id.clone());
assert_eq!(
serde_json::to_value(&resource_ref).expect("resource ref must serialize"),
serde_json::json!({ "kind": "resource", "id": "res_story36_ref" })
);
assert_eq!(
resource_ref
.as_resource()
.expect("resource ref must unwrap"),
&resource_id
);
let mismatch = resource_ref
.as_operation()
.expect_err("a Resource ref must not be accepted where an Operation ref is required");
assert_eq!(mismatch.expected, CapabilityKind::Operation);
assert_eq!(mismatch.actual, CapabilityKind::Resource);
let operation_id = crank_core::ids::OperationId::new("op_story36_ref");
let operation_ref = CapabilityRef::Operation(operation_id.clone());
assert_eq!(
operation_ref
.as_operation()
.expect("operation ref must unwrap"),
&operation_id
);
let mismatch = operation_ref
.as_resource()
.expect_err("an Operation ref must not be accepted where a Resource ref is required");
assert_eq!(mismatch.expected, CapabilityKind::Resource);
assert_eq!(mismatch.actual, CapabilityKind::Operation);
}
// ---------------------------------------------------------------------------
// BUILD obligations, которые этот файл НЕ подтверждает (не считать покрытием
// по именам тестов выше — названы явно, чтобы BUILD не упустил их)
// ---------------------------------------------------------------------------
// - реальное редактирование черновика на уровне агрегата (`Resource` + `ResourceVersion`
// в одном объекте, смена текущей версии) и отсутствие мутирующих API у published-модели:
// здесь проверяется только неизменность сериализованного снимка, полного lifecycle-покрытия нет;
// настоящий переход (`ResourceLifecycle::transition`) проверен ниже в
// `story36_at01_invalid_lifecycle_transition_is_rejected`, но публикация/архивация — 3.7;
// - typed mismatch между Operation-ref и Resource-ref (здесь проверен только `kind()` у
// `CapabilityRef::Resource`) — нужен настоящий отказ функции, принимающей Resource-ref;
// - PG-атомарность/rollback postconditions и fault-matrix — таргет P
// (`crates/crank-registry/tests/integration/resource_drafts.rs`), не этот файл;
// - числовая политика D-8.1 — фактическая проверка возможна только на Rust-интерфейсе
// (Python-модель из SPEC §3 п.6 не является исполнением продукта);
// - полный набор невалидных UTF-8 последовательностей и границы `ResourceLimits` для
// не-default L проверяются здешними кейсами лишь частично; configured small-L — BUILD.
// ---------------------------------------------------------------------------
// Story 3.7 / AC02: publication secret policy и explicit include directives.
// Синтетические неправдоподобные значения; ни один реальный credential не
// используется, и проверяется поведение детектора, а не совпадение с фикстурой.
// ---------------------------------------------------------------------------
#[test]
fn story37_at02_structural_private_keys_are_detected() {
for label in [
"RSA PRIVATE KEY",
"PRIVATE KEY",
"EC PRIVATE KEY",
"OPENSSH PRIVATE KEY",
"ENCRYPTED PRIVATE KEY",
] {
let content =
format!("-----BEGIN {label}-----\nc3ludGhldGljLWtleS1ib2R5\n-----END {label}-----\n");
assert_eq!(
publication_secret_findings(content.as_bytes()),
Some("private_key"),
"structural PEM block `{label}` must be rejected"
);
}
assert_eq!(
publication_secret_findings(
b"-----BEGIN PUBLIC KEY-----\nc3ludGhldGlj\n-----END PUBLIC KEY-----\n"
),
None,
"a public key is not private key material"
);
}
#[test]
fn story37_at02_raw_credentials_are_detected() {
assert_eq!(
publication_secret_findings(
b"aws_access_key_id = AKIAIOSFODNN7EXAMPLE\naws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"
),
Some("raw_credential")
);
assert_eq!(
publication_secret_findings(br#"{"password": "synthetic-password-42"}"#),
Some("raw_credential")
);
assert_eq!(
publication_secret_findings(b"api_key: synthetic-api-key-0123456789\n"),
Some("raw_credential")
);
assert_eq!(
publication_secret_findings(b"Authorization: Bearer synthetic0token1234567890\n"),
Some("raw_credential")
);
// F2: raw credential распознаётся независимо от позиции ключа в JSON.
assert_eq!(
publication_secret_findings(br#"{"name":"config","password":"synthetic-password-42"}"#),
Some("raw_credential"),
"a credential key in a later JSON position must not be skipped"
);
// F2: JSON-экранирование ключа не скрывает credential.
assert_eq!(
publication_secret_findings(br#"{"pass\u0077ord":"synthetic-password-42"}"#),
Some("raw_credential"),
"an escaped credential key must be decoded before the policy check"
);
// F2: bare token assignment и короткое неплейсхолдерное значение.
assert_eq!(
publication_secret_findings(b"token = synthetic-value-42\n"),
Some("raw_credential"),
"a bare `token` assignment is a raw credential"
);
assert_eq!(
publication_secret_findings(b"password = abc123\n"),
Some("raw_credential"),
"an arbitrary minimal value length must not waive the policy"
);
// F2: digit-free Bearer — тот же raw credential.
assert_eq!(
publication_secret_findings(b"Bearer abcdefghijklmnopqrstuvwx\n"),
Some("raw_credential"),
"the presence of a digit is not required to recognise a Bearer token"
);
}
/// F1: malformed/не-закрытый PEM-подобный префикс не паникует на многобайтовом
/// символе и не выдумывает private key; настоящий structural block по-прежнему
/// блокируется (`story37_at02_structural_private_keys_are_detected`).
#[test]
fn story37_at02_malformed_private_key_prefix_is_safe_to_inspect() {
for malformed in [
format!("-----BEGIN a{}", "я".repeat(60)),
"-----BEGIN ".to_owned(),
format!("prefix -----BEGIN {}", "ключ".repeat(40)),
"-----BEGIN PUBLIC KEY----- яяя".to_owned(),
"-----BEGIN".to_owned(),
"-----".to_owned(),
] {
assert_eq!(
publication_secret_findings(malformed.as_bytes()),
None,
"a bounded non-key/malformed prefix must be inspected without panic: {malformed:?}"
);
}
}
#[test]
fn story37_at02_ordinary_text_and_placeholders_are_not_secrets() {
for benign in [
"Инструкция: не коммитьте private key в репозиторий, используйте secret manager и переменные окружения.\n",
"See https://example.com/docs about private keys, tokens and secrets.\n",
"password = <ваш пароль>\n",
"token: ${CRANK_TOKEN}\n",
"Use `Bearer <token>` in the Authorization header.\n",
// F3: полная заглушка в реальной assignment-форме.
"Authorization: Bearer ***\n",
"authorization: Bearer <token>\n",
"token: YOUR_TOKEN\n",
"password: null\n",
// Обычная проза: слово категории без присвоения.
"The token is required in the Authorization header; see docs.\n",
// Публичный ключ публикуем.
"-----BEGIN PUBLIC KEY-----\nsynthetic\n-----END PUBLIC KEY-----\n",
] {
assert_eq!(
publication_secret_findings(benign.as_bytes()),
None,
"ordinary text must stay publishable: {benign}"
);
}
}
#[test]
fn story37_at02_repeated_bearer_prefixes_are_inspected_without_amplification() {
// R2-F1: цепочка scheme-префиксов в допустимых stored bytes — обычная
// заглушка. Разбор не должен держать копию каждого остатка (квадратичная
// память) и не должен расти по глубине стека.
let chain = ["authorization: ", &"Bearer ".repeat(30_000), "***"].concat();
assert!(
chain.len() <= LIMIT,
"the synthetic bounded input must stay within stored limits: {}",
chain.len()
);
assert_eq!(
publication_secret_findings(chain.as_bytes()),
None,
"a placeholder Bearer chain must stay publishable"
);
// Короткие формы сохраняют прежнюю семантику: заглушка и raw token.
assert_eq!(
publication_secret_findings(b"Authorization: Bearer ***"),
None
);
assert_eq!(
publication_secret_findings(b"Authorization: Bearer synthe...90\n"),
Some("raw_credential")
);
}
#[test]
fn story37_at02_include_directives_are_explicit_only() {
assert_eq!(
publication_include_directives(b"include: crank://docs/shared-reference\n"),
vec!["crank://docs/shared-reference".to_owned()]
);
assert!(
publication_include_directives(
b"See https://example.com/docs and include: this prose is not a directive target\n"
)
.is_empty(),
"an inline mention must not become a directive"
);
assert!(
publication_include_directives(b"ordinary text\nsecond line\n").is_empty(),
"ordinary content has no directives"
);
}
@@ -0,0 +1,151 @@
//! UNIT Story 3.10 (FR-16): typed source contract и single-sourced policy bounds.
//!
//! Build-only шов: тип определения шаблона существует только с этим build, поэтому
//! HTTP-уровень проверяется отдельно (`admin-api`/`template*.rs`), а здесь —
//! serde-контракт (unknown fields denied, exact operation version обязателен) и
//! exported cache/failure пределы, которыми пользуются validator и API.
use crank_core::resource::template::{
MAX_TEMPLATE_CACHE_BYTES, MAX_TEMPLATE_CACHE_TTL_MS, TEMPLATE_CACHE_SCOPE, TemplateCache,
TemplateFindingCode, TemplateSource, cache_policy_findings,
};
use serde_json::{Value, json};
use std::collections::BTreeSet;
fn source_value() -> Value {
json!({
"operation_id": "op_story310",
"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 story310_at01_source_contract_denies_unknown_fields_and_draft_state() {
let parsed = TemplateSource::parse(&source_value()).expect("typed source must parse");
assert_eq!(parsed.operation_id, "op_story310");
assert_eq!(parsed.operation_version, 1);
assert_eq!(parsed.parameters[0].input_path, "input.order_id");
// Arbitrary URL/inline request definition не представимы: любой неизвестный
// ключ на любом уровне — структурный отказ.
for (path, value) in [
(vec!["url"], json!("https://evil.example/orders")),
(vec!["request"], json!({ "url": "https://evil.example" })),
(vec!["method"], json!("POST")),
(
vec!["parameters", "0", "url"],
json!("https://evil.example"),
),
(vec!["cache", "scope"], json!("workspace")),
] {
let mut source = source_value();
let mut cursor = &mut source;
for step in &path[..path.len() - 1] {
cursor = match step.parse::<usize>() {
Ok(index) => &mut cursor[index],
Err(_) => &mut cursor[*step],
};
}
cursor[path[path.len() - 1]] = value;
assert!(
TemplateSource::parse(&source).is_err(),
"unknown field must be denied: {path:?}"
);
}
// «latest alias»/Draft state не выражаются: версия обязательна и явная.
let mut without_version = source_value();
without_version
.as_object_mut()
.expect("object")
.remove("operation_version");
assert!(TemplateSource::parse(&without_version).is_err());
let mut latest = source_value();
latest["operation_version"] = json!("latest");
assert!(TemplateSource::parse(&latest).is_err());
}
#[test]
fn story310_at04_policy_bounds_are_single_sourced() {
assert_eq!(MAX_TEMPLATE_CACHE_TTL_MS, 86_400_000);
assert_eq!(MAX_TEMPLATE_CACHE_BYTES, 262_144);
assert_eq!(TEMPLATE_CACHE_SCOPE, "workspace_agent_auth");
let names: BTreeSet<&str> = ["order_id"].into_iter().collect();
let cache = |ttl_ms: u64, vary: Vec<&str>, max_bytes: u64| TemplateCache {
ttl_ms,
vary: vary.into_iter().map(str::to_owned).collect(),
max_bytes,
};
// Значения ровно на границе принимаются.
assert!(
cache_policy_findings(
&cache(
MAX_TEMPLATE_CACHE_TTL_MS,
vec!["order_id"],
MAX_TEMPLATE_CACHE_BYTES
),
&names
)
.is_empty()
);
// MAX+1 и 0 — те же exported границы, что использует публикация.
for (ttl_ms, max_bytes, expected) in [
(
MAX_TEMPLATE_CACHE_TTL_MS + 1,
MAX_TEMPLATE_CACHE_BYTES,
TemplateFindingCode::CacheTtlInvalid,
),
(
0,
MAX_TEMPLATE_CACHE_BYTES,
TemplateFindingCode::CacheTtlInvalid,
),
(
MAX_TEMPLATE_CACHE_TTL_MS,
MAX_TEMPLATE_CACHE_BYTES + 1,
TemplateFindingCode::CacheSizeInvalid,
),
(
MAX_TEMPLATE_CACHE_TTL_MS,
0,
TemplateFindingCode::CacheSizeInvalid,
),
] {
let findings = cache_policy_findings(&cache(ttl_ms, vec!["order_id"], max_bytes), &names);
assert!(
findings.iter().any(|finding| finding.code == expected),
"expected {expected:?} for ttl={ttl_ms} bytes={max_bytes}: {findings:?}"
);
}
// vary: чужое имя, повтор и пропуск объявленного параметра.
for (vary, expected) in [
(
vec!["order_id", "tenant_id"],
TemplateFindingCode::VaryUnknown,
),
(
vec!["order_id", "order_id"],
TemplateFindingCode::VaryDuplicate,
),
(vec![], TemplateFindingCode::VaryIncomplete),
] {
let findings = cache_policy_findings(&cache(60_000, vary, 65_536), &names);
assert!(
findings.iter().any(|finding| finding.code == expected),
"expected {expected:?}: {findings:?}"
);
}
}