diff --git a/docs/RECORDED_DELIVERY_OBSERVATIONS.md b/docs/RECORDED_DELIVERY_OBSERVATIONS.md new file mode 100644 index 000000000..926ee7983 --- /dev/null +++ b/docs/RECORDED_DELIVERY_OBSERVATIONS.md @@ -0,0 +1,118 @@ +# Recorded delivery observations (#959 → #1335) + +This is a pure contract proposal stacked on #1395, not a live writer or a change +in publication authority. `delivery_transaction::recorded_observations` is +currently **test-compiled only**. It adds no production command or default-binary +behavior, dead-code exception, transport, persistence, retry, credentials, clock, +finalizer or gate result. #1317/#1370/#1392/#1394 remain separate frozen owners. + +The pure `export_recorded_observations(ObservationInput)` boundary re-executes +#1013/#1014 validation through the existing #1393 source exporter. It returns that +original `RecordedReviewExport` unchanged, plus a separate machine observation +view. Judgment/plan original wire bytes and opaque imported CI are unchanged. +`replay_recorded_observations` independently derives and compares both objects; +repinning an altered output does not make it valid. + +## Admission and source binding + +The caller supplies an already admitted `PublicPlanInput`, exact prepared payload +bytes and SHA256, recorded stream bytes and SHA256, and independently retained +watermark bytes, SHA256 and requested name. Pins must not be learned from the +objects they authorize. Structural consistency does not authenticate transport +observations or supply posting permission. Source admission/classification, +receipt provenance, retained-pin authority and head-observation provenance remain +caller obligations. + +`ub-review.recorded-delivery-observations.v1` has a strict subject containing the +canonical judgment repository/spec/pass/lead-attempt, delivery repository/PR/head, +RevisionRef and original source/public-source/judgment/plan/payload digests. +Source and payload identities cannot be substituted by a same-head older pass. + +Prepared payload admission supports the existing COMMENT/body/inline-comments +wire subset. Every inline comment must match exactly one canonical plan delivery +location and body digest; duplicate, extra or missing inline comments fail. +Replies, suggestions, additional payload fields and partial inline reconciliation +are unsupported here. Canonical #1014 currently admits inline and summary +surfaces. **Summary body-to-payload correspondence remains unverified**; payload +summary text is not compared to the plan's summary reference. The view always +keeps whole-review delivery `not_qualified`, even when every inline is recorded +confirmed. Empty receipts cannot confirm summary or quiet silence. + +## Events and ordered-prefix watermark + +Each stream event is an original JSON byte vector. Its strict envelope carries a +one-based sequence, previous chain SHA256, distinct delivery-attempt ID, and one +observation: + +| Observation | Effect at the named prefix | +| --- | --- | +| prepared | Registers a new attempt; remote outcome remains unknown. | +| ambiguous | Retains local failure stage/receipt digest; remote outcome stays unknown. | +| confirmed_inline | Records a canonical complete inline reconciliation for that attempt. | +| superseded | Records a different observed head; existing and later confirmations are historical. | + +A retry has a new ID and an explicit predecessor with a recorded local failure or +inline confirmation. A second pending attempt without that predecessor, duplicate +attempt ID, repeated/conflicting observation, or new preparation after a recorded +head advance is rejected. Attempt uniqueness is checked within the admitted +history; an eventual producer must allocate stable globally appropriate IDs and +retain its history. No retry operation is executed by this module. + +An ambiguous receipt is the exact existing `DeliveryTransaction` wire object, +validated against source head, canonical planned inline subset, terminal local +failure state and stage. It may be failed or cleaned_up; neither proves no remote +side effects. Its reason bytes are hashed and retained in input but never copied +into the observation view. Confirmation uses existing `ObservedDelivery`, +`DeliveryReconciliation` and `DeliveryReceipt`, recomputes `reconcile_deliveries`, +and requires exact equality to the original receipt relationship. This subset +also requires canonical positive decimal physical GitHub IDs (no signs or leading +zero aliases). Reuse of an identical receipt +by a reconciled retry is allowed; one physical comment cannot acquire conflicting +review/claim/head/body metadata. Canonical legacy codecs are roundtrip-checked to +reject ignored nested unknown fields. + +The genesis hash domain is `ub-review.recorded-delivery-genesis.v1\0` followed by +canonical subject JSON. Each link hashes `ub-review.recorded-delivery-event.v1\0`, +the previous 64-byte hexadecimal hash, an eight-byte big-endian event-byte length, +and the exact original event bytes. It does not hash reserialized event/receipt +objects. `ub-review.recorded-delivery-watermark.v1` binds a name, nonzero prefix +count, chain SHA256 and observed head at that prefix. The requested name and its +byte pin must match independently retained expectations. + +Only the named prefix is semantically admitted. A bounded future suffix cannot +change an earlier view; it does not receive receipt validation until selected by +a later independently pinned watermark. Deletion, reordering, wrong links, +conflicting events or mismatched prefix/head/name/pin reject that view. An old +watermark intentionally selected for historical replay is valid; it cannot be +substituted for a different requested current watermark. This checks recorded +prefix consistency, **not append-only storage durability or remote authenticity**. +Historical currentness names the recorded watermark, not a live GitHub lookup. + +Bounds: payload/event/receipt ≤256KiB, stream/view ≤1MiB, watermark ≤4KiB, ≤128 +events and inline rows, body text ≤6000 bytes. Existing canonical source-export +bounds remain in force. No local failure is projected as remote absence; later +confirmation does not erase its earlier local failure or another ambiguous retry. + +## Remaining #1335 integration contract + +After independent contract review, #1335 must: + +1. Admit immutable recorded source files through its existing pinned intake and + source validators. Supply the original source identity even for historical + projection; use separately admitted remote-head evidence in the event stream. +2. Add explicit bounded regular-file pins for prepared payload, stream and named + watermark to the intake. Retain independent watermark name/digest expectations + and original receipt/event bytes; do not derive them from an exported view. +3. Promote this test-compiled module to the normal **pure** consumer build and + call the API from its nonpublishing export/replay path. Preserve the existing + source view and CI byte object; export observations as a separate view. Re-run + actual CLI negative/mutation controls and obtain fresh exact-head review/checks. +4. Keep source currentness, local failure, recorded remote inline facts and summary + uncertainty separate. No fabricated zero watermark, posted flag, CI result, + production finalizer replacement or live writer follows from this contract. + +A live append-only producer, authentication/retention, head observations, ambiguous +remote reconciliation, summary correspondence, reply admission and full +#959/#960/#1335 authority acceptance remain with their existing owners. Topic +source-file support remains excluded by #1395. Ancestor gate failures are not +waived by this test-compiled proposal. diff --git a/src/delivery_transaction.rs b/src/delivery_transaction.rs index 8bba24907..912598fe8 100644 --- a/src/delivery_transaction.rs +++ b/src/delivery_transaction.rs @@ -9,6 +9,10 @@ use anyhow::{Result, ensure}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; +// Pure recorded contract proposal; #1335 owns later consumer admission. +#[cfg(test)] +pub(crate) mod recorded_observations; + pub const DELIVERY_TRANSACTION_SCHEMA: &str = "ub-review.delivery_transaction.v1"; pub const DELIVERY_RECEIPT_SCHEMA: &str = "ub-review.delivery_receipt.v1"; pub const DELIVERY_RECONCILIATION_SCHEMA: &str = "ub-review.delivery_reconciliation.v1"; diff --git a/src/delivery_transaction/recorded_observations.rs b/src/delivery_transaction/recorded_observations.rs new file mode 100644 index 000000000..ef5043c8b --- /dev/null +++ b/src/delivery_transaction/recorded_observations.rs @@ -0,0 +1,492 @@ +//! Pure #959 recorded-observation contract for a later #1335 consumer. +//! Test-compiled until that owner admits the stream and its independent pins. +//! No transport, persistence, clock, publication permission or finalizer lives here. + +use super::*; +use crate::review_judgment::JudgmentSubject; +use crate::review_judgment::public_plan::recorded_export::{ + RecordedReviewExport, export_recorded_review, +}; +use crate::review_judgment::public_plan::{ + DeliverySubject, PublicDisposition, PublicItem, PublicPlanInput, +}; +use crate::{RevisionRef, sha256_hex}; +use serde::de::DeserializeOwned; + +pub(crate) const STREAM_SCHEMA: &str = "ub-review.recorded-delivery-observations.v1"; +pub(crate) const WATERMARK_SCHEMA: &str = "ub-review.recorded-delivery-watermark.v1"; +const BYTE_LIMIT: usize = 1024 * 1024; +const OBJECT_LIMIT: usize = 256 * 1024; +const ROW_LIMIT: usize = 128; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ObservationSubject { + pub(crate) judgment_subject: JudgmentSubject, + pub(crate) delivery_subject: DeliverySubject, + pub(crate) revision: RevisionRef, + pub(crate) source_manifest_digest: String, + pub(crate) public_source_digest: String, + pub(crate) judgment_digest: String, + pub(crate) plan_digest: String, + pub(crate) payload_sha256: String, +} + +/// Event bytes retain original receipt/event formatting. The independent named +/// watermark commits to an ordered prefix of these bytes, not reserialization. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ObservationStream { + pub(crate) schema: String, + pub(crate) subject: ObservationSubject, + pub(crate) events: Vec>, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ObservationWatermark { + pub(crate) schema: String, + pub(crate) name: String, + pub(crate) count: usize, + pub(crate) chain_sha256: String, + pub(crate) observed_head_sha: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ReceiptBytes { + pub(crate) sha256: String, + pub(crate) bytes: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub(crate) enum RecordedObservation { + Prepared { + retry_of: Option, + }, + /// Local failure is not evidence that the remote side did nothing. + Ambiguous { + stage: DeliveryFailureStage, + local_receipt: ReceiptBytes, + }, + /// Complete inline subset only; never confirms summary or whole review. + ConfirmedInline { + observed: Vec, + reconciliation: ReceiptBytes, + }, + /// An independently retained observation, not a live head lookup. + Superseded { + observed_head_sha: String, + }, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ObservationEvent { + pub(crate) sequence: usize, + pub(crate) previous_sha256: String, + pub(crate) attempt_id: String, + pub(crate) observation: RecordedObservation, +} + +pub(crate) struct ObservationInput<'a> { + pub(crate) source: PublicPlanInput<'a>, + pub(crate) payload: &'a [u8], + pub(crate) payload_sha256: &'a str, + pub(crate) stream: &'a [u8], + pub(crate) stream_sha256: &'a str, + pub(crate) watermark: &'a [u8], + pub(crate) watermark_sha256: &'a str, + pub(crate) watermark_name: &'a str, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct RecordedObservationExport { + pub(crate) source: RecordedReviewExport, + pub(crate) observation_json: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "outcome", rename_all = "snake_case")] +enum RemoteObservation { + Unknown, + ConfirmedInline { + reconciliation: DeliveryReconciliation, + receipt_sha256: String, + }, +} + +#[derive(Debug, Serialize)] +struct LocalFailure { + stage: DeliveryFailureStage, + receipt_sha256: String, +} + +#[derive(Debug, Serialize)] +struct AttemptView { + attempt_id: String, + retry_of: Option, + local_failure: Option, + remote: RemoteObservation, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Payload { + event: String, + body: String, + comments: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PayloadComment { + path: String, + line: u32, + side: String, + body: String, +} + +/// Canonical delivery codecs predate strict unknown-field admission. Compare +/// their typed roundtrip here so an ignored nested field cannot become authority. +fn strict(bytes: &[u8]) -> Result { + let typed: T = serde_json::from_slice(bytes)?; + ensure!( + serde_json::to_value(&typed)? == serde_json::from_slice::(bytes)?, + "unknown or noncanonical recorded field" + ); + Ok(typed) +} + +fn digest(bytes: &[u8], expected: &str, limit: usize) -> Result<()> { + ensure!( + !bytes.is_empty() && bytes.len() <= limit, + "recorded byte limit" + ); + ensure!( + expected.len() == 64 + && expected + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "invalid SHA256 pin" + ); + ensure!(sha256_hex(bytes) == expected, "recorded byte pin mismatch"); + Ok(()) +} + +fn id(value: &str) -> Result<()> { + ensure!( + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-.:".contains(&b)), + "invalid recorded identity" + ); + Ok(()) +} + +fn head(value: &str) -> Result<()> { + ensure!( + value.len() == 40 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "invalid recorded head" + ); + Ok(()) +} + +pub(crate) fn genesis(subject: &ObservationSubject) -> Result { + let mut bytes = b"ub-review.recorded-delivery-genesis.v1\0".to_vec(); + bytes.extend(serde_json::to_vec(subject)?); + Ok(sha256_hex(&bytes)) +} + +pub(crate) fn extend_chain(previous: &str, event: &[u8]) -> String { + let mut bytes = b"ub-review.recorded-delivery-event.v1\0".to_vec(); + bytes.extend(previous.as_bytes()); + bytes.extend((event.len() as u64).to_be_bytes()); + bytes.extend(event); + sha256_hex(&bytes) +} + +fn payload_matches_inline(payload: &[u8], planned: &[PlannedDelivery]) -> Result<()> { + let payload: Payload = serde_json::from_slice(payload)?; + ensure!( + payload.event == "COMMENT" + && payload.body.len() <= 6000 + && payload.comments.len() <= ROW_LIMIT, + "unsupported recorded payload" + ); + ensure!( + payload.comments.len() == planned.len(), + "payload inline count mismatch" + ); + let mut matched = BTreeSet::new(); + for comment in payload.comments { + ensure!(comment.body.len() <= 6000, "payload body limit"); + let item = planned + .iter() + .find(|p| p.location() == (comment.path.as_str(), comment.line, comment.side.as_str())) + .ok_or_else(|| anyhow::anyhow!("payload inline location mismatch"))?; + ensure!( + sha256_hex(comment.body.as_bytes()) == item.expected_body_digest(), + "payload inline body mismatch" + ); + ensure!( + matched.insert(DeliveryIdentity::from(item)), + "duplicate payload inline" + ); + } + Ok(()) +} + +/// Revalidate canonical sources first. Consume exactly the requested pinned +/// prefix; a later suffix cannot rewrite that historical view. Caller admission +/// authenticates observations and pins; internal consistency is not remote proof. +pub(crate) fn export_recorded_observations( + input: ObservationInput<'_>, +) -> Result { + digest(input.payload, input.payload_sha256, OBJECT_LIMIT)?; + digest(input.stream, input.stream_sha256, BYTE_LIMIT)?; + digest(input.watermark, input.watermark_sha256, 4096)?; + let subject = ObservationSubject { + judgment_subject: input.source.judgment_source.subject.clone(), + delivery_subject: input.source.public_source.delivery_subject.clone(), + revision: input.source.current_revision.revision_ref(), + source_manifest_digest: input.source.expected_source_digest.to_owned(), + public_source_digest: input.source.expected_public_source_digest.to_owned(), + judgment_digest: input + .source + .expected_answer_digest + .ok_or_else(|| anyhow::anyhow!("observation requires a lead"))? + .to_owned(), + plan_digest: input + .source + .expected_plan_digest + .ok_or_else(|| anyhow::anyhow!("observation requires a plan"))? + .to_owned(), + payload_sha256: input.payload_sha256.to_owned(), + }; + let source = export_recorded_review(input.source)?; + let source_view: serde_json::Value = serde_json::from_slice(&source.view_json)?; + ensure!( + source_view["public_plan"]["availability"] == "validated", + "observation source plan unavailable" + ); + let items: Vec = + serde_json::from_value(source_view["public_plan"]["plan"]["items"].clone())?; + let planned = items + .iter() + .filter_map(|item| match &item.disposition { + PublicDisposition::Inline { delivery, .. } => Some(delivery.clone()), + _ => None, + }) + .collect::>(); + payload_matches_inline(input.payload, &planned)?; + let stream: ObservationStream = strict(input.stream)?; + ensure!( + stream.schema == STREAM_SCHEMA && stream.subject == subject, + "observation source binding mismatch" + ); + ensure!( + stream.events.len() <= ROW_LIMIT + && stream + .events + .iter() + .all(|e| !e.is_empty() && e.len() <= OBJECT_LIMIT), + "observation event limit" + ); + let watermark: ObservationWatermark = strict(input.watermark)?; + id(&watermark.name)?; + ensure!( + watermark.schema == WATERMARK_SCHEMA && watermark.name == input.watermark_name, + "wrong named watermark" + ); + ensure!( + watermark.count > 0 && watermark.count <= stream.events.len(), + "missing watermark prefix" + ); + let mut chain = genesis(&subject)?; + let mut current_head = subject.delivery_subject.head_sha.clone(); + let mut historical = false; + let mut attempts: Vec = Vec::new(); + let mut physical = BTreeMap::::new(); + for (index, bytes) in stream.events.iter().take(watermark.count).enumerate() { + let event: ObservationEvent = strict(bytes)?; + ensure!( + event.sequence == index + 1 && event.previous_sha256 == chain, + "observation chain/order mismatch" + ); + id(&event.attempt_id)?; + let found = attempts + .iter() + .position(|a| a.attempt_id == event.attempt_id); + match event.observation { + RecordedObservation::Prepared { retry_of } => { + ensure!( + !historical && found.is_none(), + "duplicate or historical prepared attempt" + ); + match &retry_of { + None => ensure!(attempts.is_empty(), "retry requires predecessor"), + Some(previous) => { + let prior = attempts + .iter() + .find(|a| &a.attempt_id == previous) + .ok_or_else(|| anyhow::anyhow!("unknown retry predecessor"))?; + ensure!( + prior.local_failure.is_some() + || matches!( + prior.remote, + RemoteObservation::ConfirmedInline { .. } + ), + "retry predecessor still prepared" + ); + } + } + attempts.push(AttemptView { + attempt_id: event.attempt_id, + retry_of, + local_failure: None, + remote: RemoteObservation::Unknown, + }); + } + RecordedObservation::Ambiguous { + stage, + local_receipt, + } => { + let attempt = attempts + .get_mut(found.ok_or_else(|| anyhow::anyhow!("unprepared observation"))?) + .ok_or_else(|| anyhow::anyhow!("missing attempt"))?; + ensure!( + attempt.local_failure.is_none() + && matches!(attempt.remote, RemoteObservation::Unknown), + "conflicting local observation" + ); + digest(&local_receipt.bytes, &local_receipt.sha256, OBJECT_LIMIT)?; + let receipt: DeliveryTransaction = strict(&local_receipt.bytes)?; + ensure!( + receipt.exact_head_sha == subject.delivery_subject.head_sha + && receipt.planned + == canonical_planned_deliveries( + &subject.delivery_subject.head_sha, + planned.clone() + )? + && matches!( + receipt.state, + DeliveryTransactionState::Failed | DeliveryTransactionState::CleanedUp + ) + && receipt + .failure + .as_ref() + .is_some_and(|failure| failure.stage == stage), + "local transaction binding mismatch" + ); + attempt.local_failure = Some(LocalFailure { + stage, + receipt_sha256: local_receipt.sha256, + }); + } + RecordedObservation::ConfirmedInline { + observed, + reconciliation, + } => { + let attempt = attempts + .get_mut(found.ok_or_else(|| anyhow::anyhow!("unprepared observation"))?) + .ok_or_else(|| anyhow::anyhow!("missing attempt"))?; + ensure!( + matches!(attempt.remote, RemoteObservation::Unknown) + && !planned.is_empty() + && observed.len() <= ROW_LIMIT, + "conflicting or empty confirmation" + ); + digest(&reconciliation.bytes, &reconciliation.sha256, OBJECT_LIMIT)?; + let receipt: DeliveryReconciliation = strict(&reconciliation.bytes)?; + let derived = reconcile_deliveries( + &subject.delivery_subject.head_sha, + &receipt.review_id, + &planned, + &observed, + )?; + ensure!(receipt == derived, "recorded reconciliation mismatch"); + ensure!( + receipt + .review_id + .parse::() + .is_ok_and(|n| n > 0 && n.to_string() == receipt.review_id), + "invalid recorded review id" + ); + for item in &receipt.receipts { + ensure!( + item.comment_id + .parse::() + .is_ok_and(|n| n > 0 && n.to_string() == item.comment_id), + "invalid recorded comment id" + ); + ensure!( + physical + .get(&item.comment_id) + .is_none_or(|previous| previous == item), + "conflicting physical receipt" + ); + physical.insert(item.comment_id.clone(), item.clone()); + } + attempt.remote = RemoteObservation::ConfirmedInline { + reconciliation: receipt, + receipt_sha256: reconciliation.sha256, + }; + } + RecordedObservation::Superseded { observed_head_sha } => { + ensure!(found.is_some(), "unprepared head observation"); + head(&observed_head_sha)?; + ensure!( + observed_head_sha != subject.delivery_subject.head_sha + && observed_head_sha != current_head, + "invalid head advance" + ); + current_head = observed_head_sha; + historical = true; + } + } + chain = extend_chain(&chain, bytes); + } + ensure!( + watermark.chain_sha256 == chain && watermark.observed_head_sha == current_head, + "watermark prefix mismatch" + ); + let view = serde_json::json!({ + "schema":"ub-review.recorded-delivery-observation-view.v1", + "qualification":"shadow_recorded_only", "source_view_sha256":sha256_hex(&source.view_json), + "subject":subject, "watermark":watermark, "attempts":attempts, + "source_currentness":if historical { "historical_at_recorded_watermark" } else { "at_recorded_source_head" }, + "summary_payload_correspondence":if items.iter().any(|i| matches!(i.disposition, PublicDisposition::Summary { .. })) { "unverified" } else { "not_applicable" }, + "whole_review_delivery":"not_qualified" + }); + let mut observation_json = serde_json::to_vec(&view)?; + observation_json.push(b'\n'); + ensure!( + observation_json.len() <= BYTE_LIMIT, + "observation view byte limit" + ); + Ok(RecordedObservationExport { + source, + observation_json, + }) +} + +pub(crate) fn replay_recorded_observations( + input: ObservationInput<'_>, + recorded: &RecordedObservationExport, + expected_view_sha256: &str, +) -> Result<()> { + digest(&recorded.observation_json, expected_view_sha256, BYTE_LIMIT)?; + let derived = export_recorded_observations(input)?; + ensure!(derived == *recorded, "observation replay mismatch"); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/src/delivery_transaction/recorded_observations/tests.rs b/src/delivery_transaction/recorded_observations/tests.rs new file mode 100644 index 000000000..558297b8f --- /dev/null +++ b/src/delivery_transaction/recorded_observations/tests.rs @@ -0,0 +1,833 @@ +use super::*; +use crate::claim_graph::{ + ClaimGraph, ClaimNode, ClaimState, EvidenceClass, EvidenceRef, RelevanceKind, RelevancePath, +}; +use crate::review_judgment::public_plan::{ + MaterialClass, RecordedAnchor, RecordedMaterial, RecordedPublicSource, public_source_digest, +}; +use crate::review_judgment::{ + ImportedCi, RecordedEvidence, RecordedJudgmentSource, source_manifest_digest, +}; +use crate::revision_identity::{CommitTree, ReviewSemantics, RevisionIdentity}; +use serde_json::{Value, json}; + +const PATCH: &[u8] = b"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1 @@\n-safe();\n+danger();\n"; +const INLINE: &str = "The unchecked index can exceed the allocation."; +const SUMMARY: &str = "This summary remains material without an inline anchor."; + +struct Fixture { + identity: RevisionIdentity, + subject: JudgmentSubject, + delivery: DeliverySubject, + graph: ClaimGraph, + ci: Vec, +} +impl Fixture { + fn new() -> Result { + let head = CommitTree::new("head", &"a".repeat(40), &"b".repeat(40))?; + let identity = RevisionIdentity::new( + CommitTree::new("base", &"c".repeat(40), &"d".repeat(40))?, + head.clone(), + head, + None, + ReviewSemantics::CandidateHead, + &RevisionIdentity::changed_paths_digest(["src/lib.rs"]), + &RevisionIdentity::diff_digest(PATCH), + )?; + let mut graph = crate::build_active_claim_graph( + &"a".repeat(40), + &[], + &[], + &[], + &[], + &[], + &crate::absent_pr_thread_context(0), + ); + graph.revision = Some(identity.revision_ref()); + for claim in ["A", "B"] { + graph.claims.push(ClaimNode { + id: claim.to_owned(), + subject: "admitted claim".to_owned(), + source_lane: "recorded".to_owned(), + state: ClaimState::Confirmed, + supporting_evidence: vec![EvidenceRef { + class: EvidenceClass::ExactCitation, + reference: "fact#1".to_owned(), + detail: "citation".to_owned(), + }], + contradicting_evidence: vec![], + relevance: RelevancePath { + kind: RelevanceKind::ChangedLine, + explanation: "changed source".to_owned(), + }, + severity: "high".to_owned(), + }); + } + Ok(Self { + identity, + subject: JudgmentSubject { + repository: "owner/repo".to_owned(), + review_spec_digest: "e".repeat(64), + pass_id: "pass-1".to_owned(), + attempt_id: "lead-1".to_owned(), + }, + delivery: DeliverySubject { + repository: "owner/repo".to_owned(), + pull_number: 7, + head_sha: "a".repeat(40), + }, + graph, + ci: vec![0, 255, b' ', b'\n'], + }) + } + fn planned(&self) -> Result { + PlannedDelivery::new( + &self.delivery.head_sha, + "A", + DeliveryAction::Inline, + DeliveryLocation::new("src/lib.rs", 1, "RIGHT"), + None, + sha256_hex(INLINE.as_bytes()), + ) + } + fn with_source(&self, run: impl FnOnce(PublicPlanInput<'_>) -> Result) -> Result { + let evidence_hash = sha256_hex(b"citation"); + let evidence = [RecordedEvidence { + reference: "fact#1", + digest: &evidence_hash, + bytes: b"citation", + }]; + let canonical = self.identity.canonical_form(); + let ci_hash = sha256_hex(&self.ci); + let source = RecordedJudgmentSource { + subject: &self.subject, + revision_canonical: &canonical, + graph: &self.graph, + review_complete: true, + evidence: &evidence, + imported_ci: Some(ImportedCi { + digest: &ci_hash, + bytes: &self.ci, + }), + }; + let source_hash = source_manifest_digest(&source)?; + let inline_hash = sha256_hex(INLINE.as_bytes()); + let summary_hash = sha256_hex(SUMMARY.as_bytes()); + let line_hash = sha256_hex(b"danger();"); + let diff_hash = RevisionIdentity::diff_digest(PATCH); + let materials = [ + RecordedMaterial { + claim_id: "A", + body_ref: "body#A", + body_digest: &inline_hash, + class: MaterialClass::Public, + body: INLINE.as_bytes(), + }, + RecordedMaterial { + claim_id: "B", + body_ref: "body#B", + body_digest: &summary_hash, + class: MaterialClass::Public, + body: SUMMARY.as_bytes(), + }, + ]; + let anchors = [RecordedAnchor { + reference: "anchor#A", + claim_id: "A", + path: "src/lib.rs", + line: 1, + line_digest: &line_hash, + }]; + let public = RecordedPublicSource { + delivery_subject: &self.delivery, + diff_digest: &diff_hash, + diff_patch: PATCH, + materials: &materials, + anchors: &anchors, + }; + let public_hash = public_source_digest(&public)?; + let mut answer = serde_json::to_vec( + &json!({"schema":"ub-review.recorded-judgment.v1","subject":self.subject,"revision":self.identity.revision_ref(),"source_manifest_digest":source_hash, + "review_result":"findings","selections":[{"claim_id":"A","evidence_refs":["fact#1"]},{"claim_id":"B","evidence_refs":["fact#1"]}]}), + )?; + answer.push(b'\n'); + let answer_hash = sha256_hex(&answer); + let mut plan = serde_json::to_vec( + &json!({"schema":"ub-review.recorded-public-plan.v1","judgment_digest":answer_hash,"revision":self.identity.revision_ref(),"subject":self.subject,"delivery_subject":self.delivery, + "public_source_digest":public_hash,"quiet":false,"items":[{"claim_id":"A","disposition":{"kind":"inline","body_ref":"body#A","anchor_ref":"anchor#A","delivery":self.planned()?}}, + {"claim_id":"B","disposition":{"kind":"summary","body_ref":"body#B","body_digest":summary_hash}}]}), + )?; + plan.push(b'\n'); + let plan_hash = sha256_hex(&plan); + run(PublicPlanInput { + judgment_source: &source, + current_revision: &self.identity, + expected_source_digest: &source_hash, + answer: Some(&answer), + expected_answer_digest: Some(&answer_hash), + observed_ci: Some(&self.ci), + public_source: &public, + expected_public_source_digest: &public_hash, + plan: Some(&plan), + expected_plan_digest: Some(&plan_hash), + }) + } + fn payload(&self) -> Result> { + Ok(serde_json::to_vec( + &json!({"event":"COMMENT","body":"Summary correspondence is deliberately not admitted.","comments":[{"path":"src/lib.rs","line":1,"side":"RIGHT","body":INLINE}]}), + )?) + } + fn stream(&self, payload: &[u8]) -> Result { + self.with_source(|s| { + Ok(ObservationStream { + schema: STREAM_SCHEMA.to_owned(), + subject: ObservationSubject { + judgment_subject: self.subject.clone(), + delivery_subject: self.delivery.clone(), + revision: self.identity.revision_ref(), + source_manifest_digest: s.expected_source_digest.to_owned(), + public_source_digest: s.expected_public_source_digest.to_owned(), + judgment_digest: s.expected_answer_digest.unwrap_or_default().to_owned(), + plan_digest: s.expected_plan_digest.unwrap_or_default().to_owned(), + payload_sha256: sha256_hex(payload), + }, + events: vec![], + }) + }) + } + fn ambiguous(&self) -> Result { + let mut transaction = + DeliveryTransaction::new(&self.delivery.head_sha, vec![self.planned()?])?; + for state in [ + DeliveryTransactionState::PendingReviewCreated, + DeliveryTransactionState::CommentsCreated, + DeliveryTransactionState::CommentsReconciled, + DeliveryTransactionState::HeadRevalidated, + ] { + transaction.transition(state)?; + } + transaction.record_failure( + DeliveryFailureStage::Submission, + "lost response PRIVATE_SENTINEL", + true, + )?; + transaction.finish_cleanup(CleanupOutcome::Failed("already submitted".to_owned()))?; + let mut bytes = serde_json::to_vec(&transaction)?; + bytes.push(b'\n'); + Ok(RecordedObservation::Ambiguous { + stage: DeliveryFailureStage::Submission, + local_receipt: ReceiptBytes { + sha256: sha256_hex(&bytes), + bytes, + }, + }) + } + fn confirmation(&self, review: &str, comment: &str) -> Result { + let planned = self.planned()?; + let observed = vec![ObservedDelivery::new(comment, planned.clone())?]; + let receipt = reconcile_deliveries(&self.delivery.head_sha, review, &[planned], &observed)?; + let mut bytes = serde_json::to_vec(&receipt)?; + bytes.push(b'\n'); + Ok(RecordedObservation::ConfirmedInline { + observed, + reconciliation: ReceiptBytes { + sha256: sha256_hex(&bytes), + bytes, + }, + }) + } +} +fn append( + stream: &mut ObservationStream, + attempt: &str, + observation: RecordedObservation, +) -> Result<()> { + let mut chain = genesis(&stream.subject)?; + for event in &stream.events { + chain = extend_chain(&chain, event); + } + stream.events.push(serde_json::to_vec(&ObservationEvent { + sequence: stream.events.len() + 1, + previous_sha256: chain, + attempt_id: attempt.to_owned(), + observation, + })?); + Ok(()) +} +fn watermark(stream: &ObservationStream, count: usize, name: &str) -> Result> { + let mut chain = genesis(&stream.subject)?; + let mut head = stream.subject.delivery_subject.head_sha.clone(); + for bytes in stream.events.iter().take(count) { + let event: Value = serde_json::from_slice(bytes)?; + if event["observation"]["kind"] == "superseded" { + head = event["observation"]["observed_head_sha"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("fixture head missing"))? + .to_owned(); + } + chain = extend_chain(&chain, bytes); + } + Ok(serde_json::to_vec(&ObservationWatermark { + schema: WATERMARK_SCHEMA.to_owned(), + name: name.to_owned(), + count, + chain_sha256: chain, + observed_head_sha: head, + })?) +} +fn invoke( + f: &Fixture, + stream: &ObservationStream, + payload: &[u8], + wm: &[u8], + name: &str, +) -> Result { + let stream = serde_json::to_vec(stream)?; + invoke_bytes(f, &stream, payload, wm, name) +} +fn invoke_bytes( + f: &Fixture, + stream: &[u8], + payload: &[u8], + wm: &[u8], + name: &str, +) -> Result { + f.with_source(|source| { + export_recorded_observations(ObservationInput { + source, + payload, + payload_sha256: &sha256_hex(payload), + stream, + stream_sha256: &sha256_hex(stream), + watermark: wm, + watermark_sha256: &sha256_hex(wm), + watermark_name: name, + }) + }) +} + +fn prepared() -> RecordedObservation { + RecordedObservation::Prepared { retry_of: None } +} +fn lifecycle(f: &Fixture, payload: &[u8]) -> Result { + let mut stream = f.stream(payload)?; + append(&mut stream, "delivery-1", prepared())?; + append(&mut stream, "delivery-1", f.ambiguous()?)?; + append(&mut stream, "delivery-1", f.confirmation("987", "123")?)?; + append( + &mut stream, + "delivery-1", + RecordedObservation::Superseded { + observed_head_sha: "f".repeat(40), + }, + )?; + Ok(stream) +} +fn view(export: &RecordedObservationExport) -> Result { + Ok(serde_json::from_slice(&export.observation_json)?) +} + +#[test] +fn prefix_preserves_sources_and_local_failure_never_proves_remote_absence() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let stream = lifecycle(&f, &payload)?; + let original = f.with_source(export_recorded_review)?; + for count in 1..=4 { + let name = format!("cut-{count}"); + let wm = watermark(&stream, count, &name)?; + let exported = invoke(&f, &stream, &payload, &wm, &name)?; + let mut prefix = stream.clone(); + prefix.events.truncate(count); + assert_eq!(exported, invoke(&f, &prefix, &payload, &wm, &name)?); + let v = view(&exported)?; + assert_eq!(exported.source, original); + assert_eq!( + exported.source.imported_ci_bytes.as_deref(), + Some(f.ci.as_slice()) + ); + assert_eq!(v["watermark"]["count"], count); + assert_eq!(v["whole_review_delivery"], "not_qualified"); + assert_eq!(v["summary_payload_correspondence"], "unverified"); + assert_eq!( + v["attempts"][0]["remote"]["outcome"], + if count < 3 { + "unknown" + } else { + "confirmed_inline" + } + ); + assert_eq!( + v["source_currentness"], + if count == 4 { + "historical_at_recorded_watermark" + } else { + "at_recorded_source_head" + } + ); + assert!(!String::from_utf8_lossy(&exported.observation_json).contains("PRIVATE_SENTINEL")); + if count >= 2 { + assert_eq!(v["attempts"][0]["local_failure"]["stage"], "submission"); + } + if count >= 3 { + assert_eq!( + v["attempts"][0]["remote"]["reconciliation"]["receipts"][0]["confirmed_head_sha"], + "a".repeat(40) + ); + } + let bytes = serde_json::to_vec(&stream)?; + f.with_source(|source| { + replay_recorded_observations( + ObservationInput { + source, + payload: &payload, + payload_sha256: &sha256_hex(&payload), + stream: &bytes, + stream_sha256: &sha256_hex(&bytes), + watermark: &wm, + watermark_sha256: &sha256_hex(&wm), + watermark_name: &name, + }, + &exported, + &sha256_hex(&exported.observation_json), + ) + })?; + } + Ok(()) +} + +#[test] +fn retries_are_distinct_and_late_confirmation_remains_historical() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + append(&mut s, "delivery-1", f.ambiguous()?)?; + append( + &mut s, + "delivery-2", + RecordedObservation::Prepared { + retry_of: Some("delivery-1".to_owned()), + }, + )?; + append( + &mut s, + "delivery-2", + RecordedObservation::Superseded { + observed_head_sha: "f".repeat(40), + }, + )?; + append(&mut s, "delivery-2", f.confirmation("987", "123")?)?; + let v = view(&invoke( + &f, + &s, + &payload, + &watermark(&s, 5, "latest")?, + "latest", + )?)?; + assert_eq!(v["attempts"].as_array().map(Vec::len), Some(2)); + assert_eq!(v["attempts"][0]["remote"]["outcome"], "unknown"); + assert_eq!(v["attempts"][1]["remote"]["outcome"], "confirmed_inline"); + assert_eq!(v["attempts"][1]["retry_of"], "delivery-1"); + assert_eq!(v["source_currentness"], "historical_at_recorded_watermark"); + assert_eq!( + v["attempts"][1]["remote"]["reconciliation"]["exact_head_sha"], + "a".repeat(40) + ); + Ok(()) +} + +#[test] +fn deletion_reordering_and_previous_link_tampering_are_rejected() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let s = lifecycle(&f, &payload)?; + let mut deleted = s.clone(); + deleted.events.remove(1); + let mut reordered = s.clone(); + reordered.events.swap(1, 2); + let mut bad_link = s.clone(); + let mut e: Value = serde_json::from_slice(&bad_link.events[0])?; + e["previous_sha256"] = json!("0".repeat(64)); + bad_link.events[0] = serde_json::to_vec(&e)?; + for bad in [deleted, reordered, bad_link] { + let wm = watermark(&bad, bad.events.len(), "changed")?; + assert!(invoke(&f, &bad, &payload, &wm, "changed").is_err()); + } + let mut truncated = s.clone(); + truncated.events.pop(); + assert!( + invoke( + &f, + &truncated, + &payload, + &watermark(&s, 4, "latest")?, + "latest" + ) + .is_err() + ); + Ok(()) +} + +#[test] +fn canonical_subject_and_payload_bindings_survive_repinned_adversaries() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let s = lifecycle(&f, &payload)?; + let wm = watermark(&s, 4, "latest")?; + for field in [ + "repository", + "pull_number", + "head_sha", + "pass_id", + "attempt_id", + "review_spec_digest", + "source_manifest_digest", + "public_source_digest", + "judgment_digest", + "plan_digest", + "payload_sha256", + ] { + let mut bad = s.clone(); + let mut v = serde_json::to_value(&bad.subject)?; + match field { + "repository" | "pull_number" | "head_sha" => { + v["delivery_subject"][field] = if field == "pull_number" { + json!(8) + } else { + json!("wrong") + } + } + "pass_id" | "attempt_id" | "review_spec_digest" => { + v["judgment_subject"][field] = json!("wrong") + } + _ => v[field] = json!("0".repeat(64)), + } + bad.subject = serde_json::from_value(v)?; + assert!( + invoke(&f, &bad, &payload, &wm, "latest").is_err(), + "{field}" + ); + } + let mut fresh = Fixture::new()?; + fresh.subject.pass_id = "pass-2".to_owned(); + assert!(invoke(&fresh, &s, &payload, &wm, "latest").is_err()); + for field in ["body", "path", "line", "side"] { + let mut p: Value = serde_json::from_slice(&payload)?; + p["comments"][0][field] = if field == "line" { + json!(2) + } else { + json!("wrong") + }; + let p = serde_json::to_vec(&p)?; + let mut bad = f.stream(&p)?; + append(&mut bad, "delivery-1", prepared())?; + assert!( + invoke(&f, &bad, &p, &watermark(&bad, 1, "latest")?, "latest").is_err(), + "{field}" + ); + } + Ok(()) +} + +#[test] +fn forged_stale_watermarks_and_repinned_output_are_rejected() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let s = lifecycle(&f, &payload)?; + let wm = watermark(&s, 4, "latest")?; + assert!(invoke(&f, &s, &payload, &watermark(&s, 1, "old")?, "latest").is_err()); + for field in ["count", "chain_sha256", "observed_head_sha"] { + let mut w: Value = serde_json::from_slice(&wm)?; + w[field] = if field == "count" { + json!(3) + } else { + json!("0".repeat(64)) + }; + assert!( + invoke(&f, &s, &payload, &serde_json::to_vec(&w)?, "latest").is_err(), + "{field}" + ); + } + let bytes = serde_json::to_vec(&s)?; + assert!( + f.with_source(|source| export_recorded_observations(ObservationInput { + source, + payload: &payload, + payload_sha256: &sha256_hex(&payload), + stream: &bytes, + stream_sha256: &sha256_hex(&bytes), + watermark: &wm, + watermark_sha256: &"0".repeat(64), + watermark_name: "latest" + })) + .is_err() + ); + let mut exported = invoke(&f, &s, &payload, &wm, "latest")?; + let mut v = view(&exported)?; + v["whole_review_delivery"] = json!("confirmed"); + exported.observation_json = serde_json::to_vec(&v)?; + assert!( + f.with_source(|source| replay_recorded_observations( + ObservationInput { + source, + payload: &payload, + payload_sha256: &sha256_hex(&payload), + stream: &bytes, + stream_sha256: &sha256_hex(&bytes), + watermark: &wm, + watermark_sha256: &sha256_hex(&wm), + watermark_name: "latest" + }, + &exported, + &sha256_hex(&exported.observation_json) + )) + .is_err() + ); + Ok(()) +} + +#[test] +fn receipt_relationships_conflicting_events_and_physical_ids_are_rejected() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + for shape in [ + "wrong_body", + "wrong_comment", + "partial", + "wrong_head", + "forged_receipt", + ] { + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + let mut confirmation = f.confirmation("987", "123")?; + if let RecordedObservation::ConfirmedInline { + observed, + reconciliation, + } = &mut confirmation + { + match shape { + "wrong_body" => { + observed[0] = ObservedDelivery::new( + "123", + PlannedDelivery::new( + &f.delivery.head_sha, + "A", + DeliveryAction::Inline, + DeliveryLocation::new("src/lib.rs", 1, "RIGHT"), + None, + "0".repeat(64), + )?, + )? + } + "wrong_comment" => observed[0] = ObservedDelivery::new("456", f.planned()?)?, + "partial" => observed.clear(), + "wrong_head" => { + observed[0] = ObservedDelivery::new( + "123", + PlannedDelivery::new( + "f".repeat(40), + "A", + DeliveryAction::Inline, + DeliveryLocation::new("src/lib.rs", 1, "RIGHT"), + None, + sha256_hex(INLINE.as_bytes()), + )?, + )? + } + _ => { + let mut r: Value = serde_json::from_slice(&reconciliation.bytes)?; + r["receipts"][0]["path"] = json!("other.rs"); + reconciliation.bytes = serde_json::to_vec(&r)?; + reconciliation.sha256 = sha256_hex(&reconciliation.bytes); + } + } + } + append(&mut s, "delivery-1", confirmation)?; + assert!( + invoke(&f, &s, &payload, &watermark(&s, 2, "latest")?, "latest").is_err(), + "{shape}" + ); + } + for (review, comment) in [("0987", "123"), ("987", "00123"), ("+987", "123")] { + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + append(&mut s, "delivery-1", f.confirmation(review, comment)?)?; + assert!( + invoke(&f, &s, &payload, &watermark(&s, 2, "latest")?, "latest").is_err(), + "noncanonical physical id {review}/{comment}" + ); + } + for duplicate in [prepared(), f.ambiguous()?, f.confirmation("987", "123")?] { + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + append(&mut s, "delivery-1", f.ambiguous()?)?; + append(&mut s, "delivery-1", f.confirmation("987", "123")?)?; + append(&mut s, "delivery-1", duplicate)?; + assert!(invoke(&f, &s, &payload, &watermark(&s, 4, "latest")?, "latest").is_err()); + } + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + append(&mut s, "delivery-1", f.ambiguous()?)?; + append( + &mut s, + "delivery-2", + RecordedObservation::Prepared { + retry_of: Some("delivery-1".to_owned()), + }, + )?; + append(&mut s, "delivery-1", f.confirmation("987", "123")?)?; + append(&mut s, "delivery-2", f.confirmation("988", "123")?)?; + assert!(invoke(&f, &s, &payload, &watermark(&s, 5, "latest")?, "latest").is_err()); + Ok(()) +} + +#[test] +fn unknown_fields_and_size_limits_do_not_enter_recorded_authority() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + let wm = watermark(&s, 1, "latest")?; + let mut root = serde_json::to_value(&s)?; + root["authority"] = json!("posted"); + assert!(invoke_bytes(&f, &serde_json::to_vec(&root)?, &payload, &wm, "latest").is_err()); + let mut p: Value = serde_json::from_slice(&payload)?; + p["dispatch"] = json!(true); + let p = serde_json::to_vec(&p)?; + assert!(invoke(&f, &s, &p, &wm, "latest").is_err()); + let mut w: Value = serde_json::from_slice(&wm)?; + w["authority"] = json!(true); + assert!(invoke(&f, &s, &payload, &serde_json::to_vec(&w)?, "latest").is_err()); + let mut e: Value = serde_json::from_slice(&s.events[0])?; + e["authority"] = json!(true); + s.events[0] = serde_json::to_vec(&e)?; + assert!(invoke(&f, &s, &payload, &watermark(&s, 1, "latest")?, "latest").is_err()); + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + append(&mut s, "delivery-1", f.confirmation("987", "123")?)?; + let mut e: Value = serde_json::from_slice(&s.events[1])?; + e["observation"]["observed"][0]["delivery"]["authority"] = json!(true); + s.events[1] = serde_json::to_vec(&e)?; + assert!(invoke(&f, &s, &payload, &watermark(&s, 2, "latest")?, "latest").is_err()); + assert!(invoke_bytes(&f, &vec![b' '; BYTE_LIMIT + 1], &payload, &wm, "latest").is_err()); + Ok(()) +} + +#[test] +fn local_failure_receipts_and_nested_confirmation_fields_are_bound() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + for shape in [ + "stage", + "planned_body", + "transaction_unknown", + "receipt_unknown", + "receipt_pin", + ] { + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + let mut observation = if shape.starts_with("receipt") { + f.confirmation("987", "123")? + } else { + f.ambiguous()? + }; + match &mut observation { + RecordedObservation::Ambiguous { + stage, + local_receipt, + } => { + if shape == "stage" { + *stage = DeliveryFailureStage::ReceiptPersistence; + } else { + let mut transaction: Value = serde_json::from_slice(&local_receipt.bytes)?; + if shape == "planned_body" { + transaction["planned"][0]["expected_body_digest"] = json!("0".repeat(64)); + } else { + transaction["failure"]["authority"] = json!(true); + } + local_receipt.bytes = serde_json::to_vec(&transaction)?; + local_receipt.sha256 = sha256_hex(&local_receipt.bytes); + } + } + RecordedObservation::ConfirmedInline { reconciliation, .. } => { + if shape == "receipt_pin" { + reconciliation.sha256 = "0".repeat(64); + } else { + let mut receipt: Value = serde_json::from_slice(&reconciliation.bytes)?; + receipt["receipts"][0]["authority"] = json!(true); + reconciliation.bytes = serde_json::to_vec(&receipt)?; + reconciliation.sha256 = sha256_hex(&reconciliation.bytes); + } + } + _ => return Err(anyhow::anyhow!("fixture observation missing")), + } + append(&mut s, "delivery-1", observation)?; + assert!( + invoke(&f, &s, &payload, &watermark(&s, 2, "latest")?, "latest").is_err(), + "{shape}" + ); + } + Ok(()) +} + +#[test] +fn recorded_payload_body_and_comment_byte_boundaries() -> Result<()> { + for size in [6000, 6001] { + let body = "x".repeat(size); + let empty: Vec = vec![]; + let payload = serde_json::to_vec(&json!({"event":"COMMENT","body":body,"comments":[]}))?; + let result = payload_matches_inline(&payload, &empty); + if size == 6000 { + result?; + } else { + assert!( + result + .err() + .is_some_and(|e| e.to_string().contains("unsupported recorded payload")) + ); + } + let f = Fixture::new()?; + let planned = PlannedDelivery::new( + &f.delivery.head_sha, + "A", + DeliveryAction::Inline, + DeliveryLocation::new("src/lib.rs", 1, "RIGHT"), + None, + sha256_hex(body.as_bytes()), + )?; + let payload = serde_json::to_vec( + &json!({"event":"COMMENT","body":"","comments":[{"path":"src/lib.rs","line":1,"side":"RIGHT","body":body}]}), + )?; + let result = payload_matches_inline(&payload, &[planned]); + if size == 6000 { + result?; + } else { + assert!( + result + .err() + .is_some_and(|e| e.to_string().contains("payload body limit")) + ); + } + } + Ok(()) +} + +#[test] +fn recorded_stream_byte_boundary_accepts_valid_json_and_rejects_overflow() -> Result<()> { + let f = Fixture::new()?; + let payload = f.payload()?; + let mut s = f.stream(&payload)?; + append(&mut s, "delivery-1", prepared())?; + let wm = watermark(&s, 1, "latest")?; + let mut bytes = serde_json::to_vec(&s)?; + assert!(bytes.len() < BYTE_LIMIT); + bytes.resize(BYTE_LIMIT, b' '); + invoke_bytes(&f, &bytes, &payload, &wm, "latest")?; + bytes.push(b' '); + let error = invoke_bytes(&f, &bytes, &payload, &wm, "latest") + .err() + .ok_or_else(|| anyhow::anyhow!("oversized valid stream admitted"))?; + assert!(error.to_string().contains("recorded byte limit")); + Ok(()) +}