feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user