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.
992 lines
35 KiB
Rust
992 lines
35 KiB
Rust
//! AT-3.6-02/06: guard-пути Resource Drafts на настоящем HTTP (TL review run101, R-A).
|
||
//!
|
||
//! Источник: SPEC v4 §2 (AT-3.6-02 guards), §6/§7 (AT-3.6-06 отказы без утечки),
|
||
//! TL review run101:39 (R-A) и FINAL-DISPOSITION run99:47 (разрешённая test-only
|
||
//! composition fixture). Проверяется то, что раньше было `BUILD-only GAP`: отказ,
|
||
//! выданный настоящим middleware-ом (`require_session`, `require_workspace_session`,
|
||
//! `require_csrf_for_browser_mutations`, `enforce_browser_security`), не доходит до
|
||
//! физических точек хранилища и не оставляет принятого состояния.
|
||
//!
|
||
//! Наблюдения: `crate::service::resources::counters` (реальные точки
|
||
//! `put_registered`/`load_content`) и публичное чтение реестра через composition fixture.
|
||
//! Ни один production API/проверка границ здесь не меняется: fixture собирается только
|
||
//! под `cfg(test)`.
|
||
//!
|
||
//! Канонический прогон: `cargo test -p admin-api --lib
|
||
//! service::resources::tests::guard_path::story36_ -- --test-threads=1`.
|
||
|
||
use reqwest::StatusCode;
|
||
use serial_test::serial;
|
||
|
||
use super::counters;
|
||
use crate::app::resource_test_support::{
|
||
FOREIGN_WORKSPACE_ID, GuardHarness, GuardOptions, LoginOptions, OWNER_EMAIL, OWNER_PASSWORD,
|
||
VIEWER_EMAIL, VIEWER_PASSWORD, anonymous_client, created_resource_id, draft_metadata,
|
||
draft_updated_at, error_signature, get_raw, login_client, post_draft, put_draft,
|
||
update_metadata,
|
||
};
|
||
|
||
/// Неизменяемая метафизика теста: содержимое, которое никогда не должно просочиться.
|
||
const SEED_CONTENT: &[u8] = b"guard-path-seed-payload";
|
||
|
||
fn seed_metadata(uri: &str, name: &str) -> serde_json::Value {
|
||
draft_metadata(uri, name, "text", "text/plain", "internal")
|
||
}
|
||
|
||
/// Session-клиент Owner `ws_default` с валидным CSRF.
|
||
async fn owner_client(harness: &GuardHarness) -> reqwest::Client {
|
||
login_client(
|
||
&harness.root_url,
|
||
OWNER_EMAIL,
|
||
OWNER_PASSWORD,
|
||
LoginOptions::with_csrf(),
|
||
)
|
||
.await
|
||
}
|
||
|
||
/// Создаёт Draft через реальный HTTP и возвращает его идентификатор.
|
||
async fn seed_draft(
|
||
harness: &GuardHarness,
|
||
client: &reqwest::Client,
|
||
uri: &str,
|
||
name: &str,
|
||
) -> String {
|
||
let (status, _traceable, text, body) = post_draft(
|
||
client,
|
||
&harness.resources_url(),
|
||
&seed_metadata(uri, name),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"positive control: an authorized create must succeed ({}); observed {}",
|
||
uri,
|
||
error_signature(status, &body)
|
||
);
|
||
assert!(
|
||
!text.contains("guard-path-seed-payload"),
|
||
"a successful card response must not echo content bytes: {text}"
|
||
);
|
||
created_resource_id(&body)
|
||
}
|
||
|
||
/// Набор Resource-маршрутов, к которым применяется guard: card/preview/content.
|
||
fn read_routes(harness: &GuardHarness, resource_id: &str) -> [String; 3] {
|
||
[
|
||
harness.resource_url(resource_id),
|
||
harness.nested_url(resource_id, "preview"),
|
||
harness.nested_url(resource_id, "content"),
|
||
]
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_anonymous_refuses_every_resource_route() {
|
||
let harness = GuardHarness::spawn("anon").await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(&harness, &owner, "crank://guard/anon", "guard_anon").await;
|
||
|
||
// Метрика физических точек сбрасывается уже после сева: дальше считается только отказ.
|
||
counters::reset();
|
||
let anonymous = anonymous_client();
|
||
|
||
let (status, _traceable, _text, body) = post_draft(
|
||
&anonymous,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/anon/denied", "guard_anon_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"an anonymous create must be refused by the session guard; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
0,
|
||
"a session-guard refusal must not reach the byte-registration point"
|
||
);
|
||
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&anonymous,
|
||
&harness.resource_url(&existing),
|
||
&seed_metadata("crank://guard/anon/denied", "guard_anon_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"an anonymous update must be refused before content work; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
|
||
let (status, _headers, _text, body) = get_raw(&anonymous, &harness.resources_url()).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"list: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
|
||
for route in read_routes(&harness, &existing) {
|
||
let (status, _headers, text, body) = get_raw(&anonymous, &route).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"anonymous read of `{route}` must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert!(
|
||
!text.contains("guard-path-seed-payload"),
|
||
"a refusal must never carry stored bytes: {text}"
|
||
);
|
||
}
|
||
assert_eq!(
|
||
counters::artifact_reads(),
|
||
0,
|
||
"a session-guard refusal must not reach the physical byte-read point"
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
0,
|
||
"no anonymous write may register bytes"
|
||
);
|
||
assert_eq!(
|
||
harness.accepted_drafts().await.len(),
|
||
1,
|
||
"only the seeded Draft may exist; the refused create must leave no accepted row"
|
||
);
|
||
|
||
// Положительный контроль: та же сущность и тот же маршрут с валидной сессией работают.
|
||
let (status, _headers, _text, body) = get_raw(&owner, &harness.resource_url(&existing)).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"the same card must be readable by an authorized session: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["resource"]["name"], serde_json::json!("guard_anon"));
|
||
let (status, headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(
|
||
headers
|
||
.get("content-type")
|
||
.and_then(|value| value.to_str().ok()),
|
||
Some("application/octet-stream"),
|
||
"downloads keep the octet-stream policy (D-6)"
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_reads(),
|
||
1,
|
||
"the authorized download is the positive control for the zero above"
|
||
);
|
||
let (status, _headers, _text, body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "preview")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
// Для kind=text preview по D-6 отдаёт ровно сохранённые bytes как инертный `text`
|
||
// (положительный контроль: тот же payload наблюдается только на разрешённом чтении).
|
||
assert_eq!(
|
||
body["preview"]["text"],
|
||
serde_json::json!("guard-path-seed-payload"),
|
||
"a permitted preview of a text Resource returns the stored bytes as inert text"
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_expired_session_cannot_reach_resource_routes() {
|
||
let expired = GuardHarness::spawn_with(
|
||
"expired",
|
||
GuardOptions {
|
||
session_ttl_hours: 0,
|
||
..GuardOptions::default()
|
||
},
|
||
)
|
||
.await;
|
||
let valid = GuardHarness::spawn_with("expired_control", GuardOptions::default()).await;
|
||
|
||
let valid_owner = owner_client(&valid).await;
|
||
let existing = seed_draft(
|
||
&valid,
|
||
&valid_owner,
|
||
"crank://guard/expired",
|
||
"guard_expired",
|
||
)
|
||
.await;
|
||
|
||
// Логин проходит (сессия выдаётся), но её срок жизни уже истёк.
|
||
let expired_client = login_client(
|
||
&expired.root_url,
|
||
OWNER_EMAIL,
|
||
OWNER_PASSWORD,
|
||
LoginOptions::with_csrf(),
|
||
)
|
||
.await;
|
||
counters::reset();
|
||
|
||
let (status, _headers, _text, body) = get_raw(&expired_client, &expired.resources_url()).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"an expired session must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
|
||
|
||
for route in read_routes(&expired, &existing) {
|
||
let (status, _headers, _text, body) = get_raw(&expired_client, &route).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"expired read `{route}`: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
}
|
||
let (status, _t, _text, body) = post_draft(
|
||
&expired_client,
|
||
&expired.resources_url(),
|
||
&seed_metadata("crank://guard/expired/denied", "guard_expired_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"expired create: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
assert!(
|
||
expired.accepted_drafts().await.is_empty(),
|
||
"an expired session must not accept any Draft"
|
||
);
|
||
|
||
// PUT (мутация существующей сущности) обязан быть отвергнут тем же guard-ом ДО
|
||
// разрешения Resource и до любой работы с bytes (R-A: недостающий applicable PUT).
|
||
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&expired_client,
|
||
&expired.resource_url(&existing),
|
||
&metadata,
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNAUTHORIZED,
|
||
"an expired update must be refused by the session guard, not by entity resolution: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
|
||
// Положительный контроль: та же последовательность при валидном сроке жизни.
|
||
let (status, _headers, _text, body) =
|
||
get_raw(&valid_owner, &valid.resource_url(&existing)).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"the same request with a live session must succeed: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_reads(),
|
||
0,
|
||
"card reading must not touch bytes"
|
||
);
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&valid_owner, &valid.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(counters::artifact_reads(), 1);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_workspace_without_access_cannot_read_existing_foreign_resource() {
|
||
let harness = GuardHarness::spawn_with(
|
||
"foreign",
|
||
GuardOptions {
|
||
foreign_workspace: true,
|
||
foreign_workspace_owner: true,
|
||
..GuardOptions::default()
|
||
},
|
||
)
|
||
.await;
|
||
|
||
let owner_a = owner_client(&harness).await;
|
||
let owner_b = login_client(
|
||
&harness.root_url,
|
||
crate::app::resource_test_support::FOREIGN_OWNER_EMAIL,
|
||
crate::app::resource_test_support::FOREIGN_OWNER_PASSWORD,
|
||
LoginOptions::with_csrf(),
|
||
)
|
||
.await;
|
||
|
||
// Существующий ResourceB в чужом для A workspace: он реально создан и читается своим владельцем.
|
||
let foreign_base = harness.foreign_resources_url();
|
||
let (status, _t, _text, body) = post_draft(
|
||
&owner_b,
|
||
&foreign_base,
|
||
&seed_metadata("crank://guard/foreign", "guard_foreign"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"the foreign workspace owner must create ResourceB: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
let resource_b = created_resource_id(&body);
|
||
|
||
counters::reset();
|
||
|
||
let (status, _headers, _text, body) =
|
||
get_raw(&owner_a, &format!("{foreign_base}/{resource_b}")).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a workspace without access must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
|
||
for suffix in ["", "/preview", "/content"] {
|
||
let (status, _headers, text, _body) =
|
||
get_raw(&owner_a, &format!("{foreign_base}/{resource_b}{suffix}")).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"denied foreign read `{suffix}` must stay forbidden"
|
||
);
|
||
assert!(
|
||
!text.contains("guard-path-seed-payload"),
|
||
"a forbidden response must not carry foreign bytes: {text}"
|
||
);
|
||
}
|
||
let (status, _t, _text, body) = post_draft(
|
||
&owner_a,
|
||
&foreign_base,
|
||
&seed_metadata("crank://guard/foreign/denied", "guard_foreign_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a mutation in a workspace without access must be refused: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
0,
|
||
"a workspace-guard refusal must not register bytes"
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_reads(),
|
||
0,
|
||
"a workspace-guard refusal must not read bytes"
|
||
);
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner_a,
|
||
&format!("{foreign_base}/{resource_b}"),
|
||
&seed_metadata("crank://guard/foreign", "guard_foreign"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a denied update must be refused before content work: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
|
||
// Положительный контроль 1: ResourceB существует и читается в своём workspace.
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner_b, &format!("{foreign_base}/{resource_b}/content")).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"ResourceB must be readable inside its own workspace"
|
||
);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(counters::artifact_reads(), 1);
|
||
|
||
// Положительный контроль 2: та же самая отказанная сессия A работает в своём workspace.
|
||
let own = seed_draft(&harness, &owner_a, "crank://guard/own", "guard_own").await;
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner_a, &harness.nested_url(&own, "content")).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"the same denied session must still act in its own workspace"
|
||
);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(counters::artifact_reads(), 2);
|
||
assert_eq!(
|
||
harness
|
||
.registry
|
||
.list_resource_drafts(FOREIGN_WORKSPACE_ID, 100)
|
||
.await
|
||
.expect("foreign drafts must be readable")
|
||
.len(),
|
||
1,
|
||
"the refused create must leave exactly the seeded ResourceB in the foreign workspace"
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_viewer_reads_but_never_mutates() {
|
||
let harness = GuardHarness::spawn_with(
|
||
"viewer",
|
||
GuardOptions {
|
||
viewer_membership: true,
|
||
..GuardOptions::default()
|
||
},
|
||
)
|
||
.await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(&harness, &owner, "crank://guard/viewer", "guard_viewer").await;
|
||
let viewer = login_client(
|
||
&harness.root_url,
|
||
VIEWER_EMAIL,
|
||
VIEWER_PASSWORD,
|
||
LoginOptions::with_csrf(),
|
||
)
|
||
.await;
|
||
|
||
counters::reset();
|
||
|
||
let (status, _t, _text, body) = post_draft(
|
||
&viewer,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/viewer/denied", "guard_viewer_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a non-Owner mutation must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&viewer,
|
||
&harness.resource_url(&existing),
|
||
&seed_metadata("crank://guard/viewer", "guard_viewer"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a non-Owner update must be refused before content work: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
0,
|
||
"an ownership refusal must not register bytes"
|
||
);
|
||
assert_eq!(
|
||
harness.accepted_drafts().await.len(),
|
||
1,
|
||
"a refused mutation must not add accepted rows"
|
||
);
|
||
|
||
// Положительный контроль: тот же Viewer на той же сессии читает разрешённые маршруты.
|
||
let (status, _headers, _text, body) = get_raw(&viewer, &harness.resource_url(&existing)).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"a Viewer must be able to read the card: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&viewer, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(counters::artifact_reads(), 1);
|
||
let (status, _headers, _text, body) = get_raw(&viewer, &harness.resources_url()).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"a Viewer must be able to list the workspace Resources: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_missing_csrf_blocks_before_any_byte_work() {
|
||
let harness = GuardHarness::spawn("csrf").await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(&harness, &owner, "crank://guard/csrf", "guard_csrf").await;
|
||
// Тот же аккаунт, та же сессия, но без заголовка `x-csrf-token`.
|
||
let without_csrf = login_client(
|
||
&harness.root_url,
|
||
OWNER_EMAIL,
|
||
OWNER_PASSWORD,
|
||
LoginOptions::default(),
|
||
)
|
||
.await;
|
||
|
||
counters::reset();
|
||
|
||
let (status, _t, _text, body) = post_draft(
|
||
&without_csrf,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/csrf/denied", "guard_csrf_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a browser mutation without CSRF must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&without_csrf,
|
||
&harness.resource_url(&existing),
|
||
&seed_metadata("crank://guard/csrf", "guard_csrf"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a CSRF-less update must be refused: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
assert_eq!(
|
||
harness.accepted_drafts().await.len(),
|
||
1,
|
||
"no accepted row may appear without a valid CSRF token"
|
||
);
|
||
|
||
// Положительный контроль: тот же аккаунт с валидным CSRF проходит тот же POST.
|
||
let (status, _t, _text, body) = post_draft(
|
||
&owner,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/csrf/ok", "guard_csrf_ok"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"the same request with a CSRF token must succeed: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
1,
|
||
"the accepted create is the positive control for the zero above"
|
||
);
|
||
assert_eq!(harness.accepted_drafts().await.len(), 2);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_cross_origin_blocks_mutation_and_read() {
|
||
let harness = GuardHarness::spawn("origin").await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(&harness, &owner, "crank://guard/origin", "guard_origin").await;
|
||
let cross_origin = login_client(
|
||
&harness.root_url,
|
||
OWNER_EMAIL,
|
||
OWNER_PASSWORD,
|
||
LoginOptions::cross_origin(),
|
||
)
|
||
.await;
|
||
|
||
counters::reset();
|
||
|
||
let (status, _t, _text, body) = post_draft(
|
||
&cross_origin,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/origin/denied", "guard_origin_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a cross-origin browser mutation must be refused; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
|
||
for route in read_routes(&harness, &existing) {
|
||
let (status, _headers, text, _body) = get_raw(&cross_origin, &route).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a cross-origin admin request must be refused even on `{route}`"
|
||
);
|
||
assert!(!text.contains("guard-path-seed-payload"));
|
||
}
|
||
|
||
// PUT из чужого Origin: отказ браузерной защиты до любых bytes и без изменения состояния.
|
||
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&cross_origin,
|
||
&harness.resource_url(&existing),
|
||
&metadata,
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a cross-origin update must be refused: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
assert_eq!(harness.accepted_drafts().await.len(), 1);
|
||
|
||
// Положительный контроль: тот же аккаунт без чужого Origin проходит те же маршруты.
|
||
let (status, _t, _text, body) = post_draft(
|
||
&owner,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/origin/ok", "guard_origin_ok"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"the same account without a foreign Origin must succeed: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 1);
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
|
||
assert_eq!(counters::artifact_reads(), 1);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at04_stale_precondition_registers_no_bytes_through_real_http() {
|
||
let harness = GuardHarness::spawn("stale").await;
|
||
let owner = owner_client(&harness).await;
|
||
counters::reset();
|
||
let existing = seed_draft(&harness, &owner, "crank://guard/stale", "guard_stale").await;
|
||
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
let first = draft_updated_at(&card);
|
||
|
||
// Положительный контроль 1: свежий precondition действительно регистрирует bytes через HTTP.
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", &first),
|
||
b"second body",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"a fresh precondition must update the Draft: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(
|
||
counters::artifact_puts(),
|
||
2,
|
||
"seed + accepted update must be the two real byte-registration points"
|
||
);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
|
||
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
let second = draft_updated_at(&card);
|
||
assert_ne!(
|
||
first, second,
|
||
"an accepted update must move the precondition"
|
||
);
|
||
|
||
// Отказ F: stale precondition. Принятый контракт P2 — «428 до put/read», поэтому сначала
|
||
// читается только счётчик, а состояние наблюдается после него.
|
||
counters::reset();
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", &first),
|
||
b"third body",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::PRECONDITION_REQUIRED,
|
||
"a stale precondition must be refused: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("resource_stale"));
|
||
let puts_after_stale = counters::artifact_puts();
|
||
let reads_after_stale = counters::artifact_reads();
|
||
|
||
// Состояние не изменилось: bytes победителя читаются, третьей версии нет.
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), b"second body");
|
||
assert_eq!(
|
||
harness.accepted_drafts().await[0].version.version,
|
||
2,
|
||
"a stale rejection must not create a version"
|
||
);
|
||
assert_eq!(
|
||
reads_after_stale, 0,
|
||
"a stale rejection must not perform a physical read"
|
||
);
|
||
assert_eq!(
|
||
puts_after_stale, 0,
|
||
"the accepted contract (P2) decides resource_stale before byte registration; \
|
||
the observed counter proves bytes were registered for a refused update"
|
||
);
|
||
|
||
// Положительный контроль 2: свежий precondition после отказов снова проходит.
|
||
counters::reset();
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", &second),
|
||
b"third body",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"a fresh precondition must still work after the stale refusals: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 1);
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), b"third body");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at04_stale_precondition_precedes_content_validation_through_http() {
|
||
let harness = GuardHarness::spawn("stale_utf8").await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(
|
||
&harness,
|
||
&owner,
|
||
"crank://guard/staleutf8",
|
||
"guard_staleutf8",
|
||
)
|
||
.await;
|
||
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
let first = draft_updated_at(&card);
|
||
|
||
// Принятое обновление делает `first` настоящим (ранее валидным, теперь stale) precondition.
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", &first),
|
||
b"second body",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"the accepted update is the control for the stale case: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
|
||
// F побеждает G: stale precondition + невалидная кодировка → 428 resource_stale, не 422.
|
||
let (status, _headers, text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", &first),
|
||
&[0xC3, 0x28],
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::PRECONDITION_REQUIRED,
|
||
"the stale precondition must win over content validation (D-20 F); observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("resource_stale"));
|
||
assert_eq!(
|
||
body["error"]["context"]["field"],
|
||
serde_json::json!("expected_updated_at")
|
||
);
|
||
|
||
// Состояние не изменилось, свежий precondition продолжает работать.
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), b"second body");
|
||
let current = second_precondition(&owner, &harness, &existing).await;
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&owner,
|
||
&harness.resource_url(&existing),
|
||
&update_metadata("", "text/plain", "internal", ¤t),
|
||
b"third body",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"a fresh precondition must still work after the stale rejection: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
let (status, _headers, bytes, _body) =
|
||
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(bytes.as_bytes(), b"third body");
|
||
}
|
||
|
||
/// Текущее значение precondition карточки Draft.
|
||
async fn second_precondition(
|
||
owner: &reqwest::Client,
|
||
harness: &GuardHarness,
|
||
resource_id: &str,
|
||
) -> String {
|
||
let (status, _headers, _text, card) = get_raw(owner, &harness.resource_url(resource_id)).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
draft_updated_at(&card)
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// R-A (TL run103:47): чужой CSRF-токен — отдельный однофакторный негатив, а не
|
||
// повтор «отсутствующего» токена.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at06_guard_wrong_csrf_token_blocks_before_any_byte_work() {
|
||
let harness = GuardHarness::spawn("wrong_csrf").await;
|
||
let owner = owner_client(&harness).await;
|
||
let existing = seed_draft(
|
||
&harness,
|
||
&owner,
|
||
"crank://guard/wrongcsrf",
|
||
"guard_wrongcsrf",
|
||
)
|
||
.await;
|
||
// Та же валидная сессия и валидный Origin, но подпись CSRF-токена не совпадает.
|
||
let wrong_csrf = login_client(
|
||
&harness.root_url,
|
||
OWNER_EMAIL,
|
||
OWNER_PASSWORD,
|
||
LoginOptions::with_wrong_csrf(),
|
||
)
|
||
.await;
|
||
|
||
counters::reset();
|
||
|
||
let (status, _t, _text, body) = post_draft(
|
||
&wrong_csrf,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/wrongcsrf/denied", "guard_wrongcsrf_denied"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a wrong CSRF token must be refused like a missing one; observed {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
|
||
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
|
||
let (status, _headers, _text, body) = put_draft(
|
||
&wrong_csrf,
|
||
&harness.resource_url(&existing),
|
||
&metadata,
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::FORBIDDEN,
|
||
"a wrong CSRF token must also block the update path: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
|
||
assert_eq!(counters::artifact_puts(), 0);
|
||
assert_eq!(counters::artifact_reads(), 0);
|
||
let drafts = harness.accepted_drafts().await;
|
||
assert_eq!(
|
||
drafts.len(),
|
||
1,
|
||
"a wrong CSRF token must not accept a draft or change state"
|
||
);
|
||
assert_eq!(drafts[0].version.version, 1);
|
||
|
||
// Положительный контроль: тот же аккаунт с настоящим токеном проходит тот же POST.
|
||
let (status, _t, _text, body) = post_draft(
|
||
&owner,
|
||
&harness.resources_url(),
|
||
&seed_metadata("crank://guard/wrongcsrf/ok", "guard_wrongcsrf_ok"),
|
||
SEED_CONTENT,
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"the same account with the real token must succeed: {}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(counters::artifact_puts(), 1);
|
||
assert_eq!(harness.accepted_drafts().await.len(), 2);
|
||
}
|