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.
735 lines
31 KiB
Rust
735 lines
31 KiB
Rust
//! 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"
|
|
);
|
|
}
|