Files
crank/crates/crank-core/src/resource/publication.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

290 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Story 3.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
}