From 1eac46ffe07fa2bdb60c7ed02badf0b149ff2a4b Mon Sep 17 00:00:00 2001 From: jefftj86 Date: Mon, 26 Oct 2026 21:50:23 -0700 Subject: [PATCH] feat(integrations): add offline inspection Signed-off-by: jefftj86 --- README.md | 6 + crates/rangoon-integrations/src/lib.rs | 1 + .../src/lnsat_request_inspection.rs | 1297 +++++++++++++++++ .../tests/lnsat_request_inspection.rs | 404 +++++ docs/development.md | 18 + docs/lnsat-evidence-connector.md | 8 + 6 files changed, 1734 insertions(+) create mode 100644 crates/rangoon-integrations/src/lnsat_request_inspection.rs create mode 100644 crates/rangoon-integrations/tests/lnsat_request_inspection.rs diff --git a/README.md b/README.md index 7b89220..4fb9427 100644 --- a/README.md +++ b/README.md @@ -1013,3 +1013,9 @@ evidence remain open. See the [adapter contract](docs/model-cloud-adapter.md), The separate `rangoon.integrations.lnsat-request-record.v1` source profile inspects one caller-supplied, bounded synthetic request record from the selected LNSAT source contract at `35a41963ad698934c7ee00852c71355e329c34fa`. It distinguishes failed evaluation, unknown outcome, degraded evidence, generic read refusal and unavailable reads. Native completion remains a reported fact, not independently verified effect or execution authority. Requester identity and approval reasons are omitted; the separate summary contains fixed labels and counts, while host bytes retain sensitive correlation identifiers. The existing D3a runtime-composition decoder and its `f669181a` source pin remain unchanged. Neither decoder performs a live read, opens credentials, persists evidence, reconciles an outcome or dispatches an action. The new profile is unmounted and does not replace O1/O2, VUSL or any provider contract. The [implementation receipt](docs/development.md#offline-lnsat-request-record-decoder--october-26-2026) owns exact source/test/review evidence and remaining gates. This source work is not installed-runtime, platform, release or support qualification. + +### Pure offline inspection lifecycle + +The separate `lnsat_request_inspection` source slice places a pure host lifecycle around the request-record decoder. Its presentation boundary permits only the closed summary or fixed error envelope; raw bytes, complete selectors, host JSON, input digest and native correlation details stay host-side. One inspection is admitted at a time. Discard revokes delivery immediately and remains pending until the exact owned operation releases its data and the current presenter purge is acknowledged. Close is permanent; numeric generations never grant authority or wrap into renewed work. + +This is a source/synthetic contract boundary, with no file picker, renderer/IPC, workspace mount or live provider read. A logical delivery lease and cooperative purge acknowledgment do not prove memory zeroization, native cleanup, authentication or physical erasure. Summaries are privacy-minimized, not anonymous or approved for persistence. D3a, the underlying request decoder, O1/O2 and provider independence remain unchanged. The [source receipt](docs/development.md#offline-request-record-inspection-boundary--october-26-2026) records validation, independent review and later adoption gaps; it grants no reconciliation or execution authority. diff --git a/crates/rangoon-integrations/src/lib.rs b/crates/rangoon-integrations/src/lib.rs index 4eb2ce8..ec53893 100644 --- a/crates/rangoon-integrations/src/lib.rs +++ b/crates/rangoon-integrations/src/lib.rs @@ -5,6 +5,7 @@ mod descriptor; mod inspection; pub mod lnsat_evidence; +pub mod lnsat_request_inspection; pub mod lnsat_request_record; pub mod openshell_observation; pub mod openshell_runtime; diff --git a/crates/rangoon-integrations/src/lnsat_request_inspection.rs b/crates/rangoon-integrations/src/lnsat_request_inspection.rs new file mode 100644 index 0000000..2382547 --- /dev/null +++ b/crates/rangoon-integrations/src/lnsat_request_inspection.rs @@ -0,0 +1,1297 @@ +//! Pure host lifecycle for one offline decoded LNSAT request record. +#![forbid(unsafe_code)] +use crate::lnsat_request_record::{ + RequestRecordBody, RequestRecordError, RequestRecordInput, RequestRecordInspection, + inspect_request_record, +}; +use serde::{Deserialize, Serialize}; +use std::{ + fmt, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +pub const VIEW_SCHEMA: &str = "rangoon.inspection.lnsat-request-summary-view.v1"; +pub const MAX_PRESENTATION_BYTES: usize = 12_288; +const MAX_INPUT: usize = 65_536; +const MAX_SUMMARY: usize = 8_192; +const TERMINAL: u32 = u32::MAX; +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum InspectionState { + Empty, + Inspecting, + SummaryReady, + Rejected, + DiscardPending, + Discarded, + Closed, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum InspectionControlError { + Busy, + Closed, + StaleTicket, + PresentationUnavailable, +} +impl InspectionControlError { + pub const fn code(self) -> &'static str { + match self { + Self::Busy => "busy", + Self::Closed => "closed", + Self::StaleTicket => "stale_ticket", + Self::PresentationUnavailable => "presentation_unavailable", + } + } +} +impl fmt::Display for InspectionControlError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} +impl std::error::Error for InspectionControlError {} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CompletionDisposition { + Published, + Dropped, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PresentationError { + OutputLimit, + SerializationFailed, +} +impl fmt::Display for PresentationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::OutputLimit => "output_limit", + Self::SerializationFailed => "serialization_failed", + }) + } +} +impl std::error::Error for PresentationError {} +struct Owner(AtomicBool); +impl Owner { + fn released(&self) -> bool { + self.0.load(Ordering::Acquire) + } + fn release(&self) { + self.0.store(true, Ordering::Release) + } +} +#[derive(Default, Clone)] +struct Binding { + instance: Arc<()>, + view: Arc<()>, +} +impl Binding { + fn same(&self, x: &Self) -> bool { + Arc::ptr_eq(&self.instance, &x.instance) && Arc::ptr_eq(&self.view, &x.view) + } +} + +/// Move-only trusted input custody. No payload accessor exists. +pub struct InspectionWork { + binding: Binding, + epoch: u32, + owner: Option>, + input: Option, +} +impl fmt::Debug for InspectionWork { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("InspectionWork { input omitted }") + } +} +impl InspectionWork { + pub fn decode(self) -> InspectionCompletion { + self.decode_with(inspect_request_record) + } + fn decode_with( + mut self, + decoder: impl FnOnce(RequestRecordInput) -> Result, + ) -> InspectionCompletion { + let input = self.input.take().expect("owned input"); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decoder(input))) + .map(DecodeResult::Decoded) + .unwrap_or(DecodeResult::Panic); + InspectionCompletion { + binding: std::mem::take(&mut self.binding), + epoch: self.epoch, + owner: self.owner.take(), + result: Some(result), + } + } +} +impl Drop for InspectionWork { + fn drop(&mut self) { + drop(self.input.take()); + if let Some(owner) = self.owner.take() { + owner.release() + } + } +} +/// Move-only completed decoder custody. It retains decoder result until accepted or dropped. +pub struct InspectionCompletion { + binding: Binding, + epoch: u32, + owner: Option>, + result: Option, +} +impl fmt::Debug for InspectionCompletion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("InspectionCompletion { result omitted }") + } +} +impl Drop for InspectionCompletion { + fn drop(&mut self) { + drop(self.result.take()); + if let Some(owner) = self.owner.take() { + owner.release() + } + } +} +enum DecodeResult { + Decoded(Result), + Panic, +} +struct PurgeId; +struct Pending { + ticket: Arc, + owner: Option>, + ack: bool, +} +#[derive(Clone)] +pub struct PurgeTicket { + binding: Binding, + ticket: Arc, +} +impl fmt::Debug for PurgeTicket { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PurgeTicket { opaque: true }") + } +} + +pub struct RequestInspectionHost { + binding: Binding, + epoch: u32, + state: InspectionState, + closed: bool, + active: Option>, + presentation: Option, + pending: Option, +} +impl Default for RequestInspectionHost { + fn default() -> Self { + Self { + binding: Binding::default(), + epoch: 1, + state: InspectionState::Empty, + closed: false, + active: None, + presentation: None, + pending: None, + } + } +} +impl fmt::Debug for RequestInspectionHost { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RequestInspectionHost") + .field("state", &self.state) + .field("epoch", &self.epoch) + .finish() + } +} +impl RequestInspectionHost { + pub fn new() -> Self { + Self::default() + } + pub const fn state(&self) -> InspectionState { + self.state + } + pub const fn epoch(&self) -> u32 { + self.epoch + } + pub fn begin( + &mut self, + input: RequestRecordInput, + ) -> Result { + self.settle(); + if self.closed { + return Err(InspectionControlError::Closed); + } + if !matches!( + self.state, + InspectionState::Empty | InspectionState::Discarded + ) { + return Err(InspectionControlError::Busy); + } + if input_size(&input) > MAX_INPUT { + return Err(InspectionControlError::PresentationUnavailable); + } + let owner = Arc::new(Owner(AtomicBool::new(false))); + self.active = Some(owner.clone()); + self.presentation = None; + self.state = InspectionState::Inspecting; + Ok(InspectionWork { + binding: Binding { + instance: self.binding.instance.clone(), + view: self.binding.view.clone(), + }, + epoch: self.epoch, + owner: Some(owner), + input: Some(input), + }) + } + pub fn complete(&mut self, mut done: InspectionCompletion) -> CompletionDisposition { + let owner = done.owner.clone(); + let valid = owner.as_ref().is_some_and(|o| { + self.state == InspectionState::Inspecting + && self.epoch == done.epoch + && self.binding.same(&done.binding) + && self.active.as_ref().is_some_and(|a| Arc::ptr_eq(a, o)) + }); + let result = done.result.take(); + if !valid { + drop(result); + drop(done); + self.settle(); + return CompletionDisposition::Dropped; + } + let view = match result.expect("one result") { + DecodeResult::Decoded(Ok(inspection)) => { + match decode_summary(inspection.summary_json()) { + Ok(summary) => View::summary(self.epoch, summary), + Err(_) => View::integration(self.epoch, "summary_rejected"), + } + } + DecodeResult::Decoded(Err(error)) => View::decoder(self.epoch, error), + DecodeResult::Panic => View::integration(self.epoch, "inspection_failed"), + }; + self.presentation = Some(view); + self.active = None; + self.state = if self.presentation.as_ref().is_some_and(View::summary_ready) { + InspectionState::SummaryReady + } else { + InspectionState::Rejected + }; + drop(done); + CompletionDisposition::Published + } + pub fn discard(&mut self) -> Option { + // An already pending cycle may finish here, but this same call must not + // allocate a replacement cycle after observing its final owner release. + if self.pending.is_some() { + self.settle(); + return self.ticket(); + } + self.settle(); + if self.state == InspectionState::Closed { + return None; + } + if self.state != InspectionState::DiscardPending { + self.purge(false) + } + self.ticket() + } + pub fn close(&mut self) -> Option { + self.closed = true; + self.settle(); + match self.state { + InspectionState::Closed => None, + InspectionState::Discarded => { + self.state = InspectionState::Closed; + None + } + InspectionState::DiscardPending => self.ticket(), + _ => { + self.purge(true); + self.ticket() + } + } + } + pub fn acknowledge_purge(&mut self, t: PurgeTicket) -> Result<(), InspectionControlError> { + let Some(p) = self.pending.as_mut() else { + return Err(InspectionControlError::StaleTicket); + }; + if !self.binding.same(&t.binding) || !Arc::ptr_eq(&p.ticket, &t.ticket) { + return Err(InspectionControlError::StaleTicket); + } + p.ack = true; + self.settle(); + Ok(()) + } + pub fn refresh_cleanup(&mut self) { + self.settle() + } + pub fn presentation(&mut self) -> Result, InspectionControlError> { + self.settle(); + if !matches!( + self.state, + InspectionState::SummaryReady | InspectionState::Rejected + ) { + return Err(InspectionControlError::PresentationUnavailable); + } + Ok(PresentationLease { + view: self.presentation.as_ref().expect("visible view"), + }) + } + fn ticket(&self) -> Option { + self.pending.as_ref().map(|p| PurgeTicket { + binding: Binding { + instance: self.binding.instance.clone(), + view: self.binding.view.clone(), + }, + ticket: p.ticket.clone(), + }) + } + fn purge(&mut self, closing: bool) { + self.presentation = None; + if self.epoch >= TERMINAL - 1 { + self.epoch = TERMINAL; + self.closed = true + } else { + self.epoch += 1 + } + if closing { + self.closed = true + } + self.pending = Some(Pending { + ticket: Arc::new(PurgeId), + owner: self.active.take(), + ack: false, + }); + self.state = InspectionState::DiscardPending; + self.settle() + } + fn settle(&mut self) { + if self + .pending + .as_ref() + .is_some_and(|p| p.ack && p.owner.as_ref().is_none_or(|o| o.released())) + { + self.pending = None; + self.state = if self.closed { + InspectionState::Closed + } else { + InspectionState::Discarded + } + } + } +} +/// Borrowed view access serializes delivery against discard/close. No callback is invoked. +/// A caller cannot mutate the same host while it still uses the delivery lease. +/// Copied presentation bytes are outside this borrow and require cooperative purge. +/// +/// ```compile_fail,E0499 +/// use rangoon_integrations::lnsat_request_inspection::RequestInspectionHost; +/// let mut host = RequestInspectionHost::new(); +/// let lease = host.presentation().unwrap(); +/// host.discard(); +/// let _ = lease.json_bytes(); +/// ``` +pub struct PresentationLease<'a> { + view: &'a View, +} +impl PresentationLease<'_> { + pub fn json_bytes(&self) -> Result, PresentationError> { + checked_encode(self.view, MAX_PRESENTATION_BYTES) + } +} +impl fmt::Debug for PresentationLease<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PresentationLease { summary only }") + } +} +fn checked_encode(value: &T, limit: usize) -> Result, PresentationError> { + let bytes = serde_json::to_vec(value).map_err(|_| PresentationError::SerializationFailed)?; + if bytes.len() > limit { + Err(PresentationError::OutputLimit) + } else { + Ok(bytes) + } +} + +fn input_size(i: &RequestRecordInput) -> usize { + match &i.body { + RequestRecordBody::Body200(x) | RequestRecordBody::Refused403(x) => x.len(), + RequestRecordBody::ReadUnavailable(_) => 0, + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct View { + schema_version: &'static str, + epoch: u32, + state: InspectionState, + summary: Option, + error: Option, +} +impl View { + fn summary(epoch: u32, summary: Summary) -> Self { + Self { + schema_version: VIEW_SCHEMA, + epoch, + state: InspectionState::SummaryReady, + summary: Some(summary), + error: None, + } + } + fn decoder(epoch: u32, error: RequestRecordError) -> Self { + Self { + schema_version: VIEW_SCHEMA, + epoch, + state: InspectionState::Rejected, + summary: None, + error: Some(LocalError { + kind: Kind::Decoder, + code: error.code(), + truth: Truth::fixed(), + }), + } + } + fn integration(epoch: u32, code: &'static str) -> Self { + Self { + schema_version: VIEW_SCHEMA, + epoch, + state: InspectionState::Rejected, + summary: None, + error: Some(LocalError { + kind: Kind::Integration, + code, + truth: Truth::fixed(), + }), + } + } + fn summary_ready(&self) -> bool { + self.summary.is_some() + } +} +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +enum Kind { + Decoder, + Integration, +} +#[derive(Serialize)] +struct LocalError { + kind: Kind, + code: &'static str, + truth: Truth, +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct Summary { + schema_version: Schema, + record_availability: Availability, + reported_evaluation: ReportedEvaluation, + reported_policy: Policy, + read_failure: Option, + security_activity_touched: Option, + family_counts: Option, + truth: Truth, + omissions: Vec, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +enum Schema { + #[serde(rename = "rangoon.integrations.lnsat-request-summary.v1")] + V1, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Availability { + Complete, + Degraded, + ReadRejectedUnclassified, + ReadUnavailable, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum ReportedEvaluation { + PolicyRecorded, + EvaluationFailed, + EvaluationUnknown, + NotObserved, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Policy { + Allow, + Deny, + ApprovalRequired, + NotObserved, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum ReadFailure { + NativeReadRejectedUnclassified, + ReadNotConfigured, + ReadTransportUnavailable, + ReadCancelled, + ReadTimeout, + ReadUnauthenticated, + ReadUnsupportedTransport, +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Counts { + approvals: u64, + approval_decisions: u64, + authorization_attempts: u64, + authorizations: u64, + operations: u64, + consumptions: u64, + operation_attempts: u64, + receipts: u64, + reconciliations: u64, + states: u64, +} +impl Counts { + fn ok(&self) -> bool { + [ + self.approvals, + self.approval_decisions, + self.authorization_attempts, + self.authorizations, + self.operations, + self.consumptions, + self.operation_attempts, + self.receipts, + self.reconciliations, + self.states, + ] + .into_iter() + .all(|x| x <= 64) + } +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct Truth { + authenticity: Auth, + authority: Authority, + execution: Execution, + authoritative_outcome: Outcome, + independent_effect: Effect, + currentness: Current, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Auth { + Unverified, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Authority { + None, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Execution { + Unavailable, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Outcome { + Unknown, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Effect { + NotObserved, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Current { + Unverified, +} +impl Truth { + fn fixed() -> Self { + Self { + authenticity: Auth::Unverified, + authority: Authority::None, + execution: Execution::Unavailable, + authoritative_outcome: Outcome::Unknown, + independent_effect: Effect::NotObserved, + currentness: Current::Unverified, + } + } +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct Omission { + path: Path, + reason: Reason, + disposition: Disposition, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +enum Path { + #[serde(rename = "request.requester_ref")] + Requester, + #[serde(rename = "evidence.approval_decisions[*].reason")] + ApprovalReason, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +enum Reason { + #[serde(rename = "privacy_projection")] + Privacy, +} +#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] +enum Disposition { + #[serde(rename = "policy_omission_not_presence_claim")] + Policy, +} +fn omissions() -> Vec { + vec![ + Omission { + path: Path::Requester, + reason: Reason::Privacy, + disposition: Disposition::Policy, + }, + Omission { + path: Path::ApprovalReason, + reason: Reason::Privacy, + disposition: Disposition::Policy, + }, + ] +} +fn decode_summary(b: &[u8]) -> Result { + if b.len() > MAX_SUMMARY { + return Err(()); + } + NoDuplicate::new(b).check()?; + let s: Summary = serde_json::from_slice(b).map_err(|_| ())?; + if s.truth != Truth::fixed() + || s.omissions != omissions() + || !s.family_counts.as_ref().is_none_or(Counts::ok) + { + return Err(()); + } + match ( + &s.record_availability, + &s.reported_evaluation, + &s.reported_policy, + &s.read_failure, + &s.security_activity_touched, + &s.family_counts, + ) { + ( + Availability::Complete, + ReportedEvaluation::PolicyRecorded, + Policy::Allow | Policy::Deny | Policy::ApprovalRequired, + None, + Some(_), + Some(_), + ) + | ( + Availability::Complete, + ReportedEvaluation::EvaluationFailed | ReportedEvaluation::EvaluationUnknown, + Policy::NotObserved, + None, + Some(_), + None, + ) + | ( + Availability::Degraded, + ReportedEvaluation::EvaluationUnknown, + Policy::NotObserved, + None, + Some(_), + None, + ) + | ( + Availability::ReadRejectedUnclassified, + ReportedEvaluation::NotObserved, + Policy::NotObserved, + Some(ReadFailure::NativeReadRejectedUnclassified), + None, + None, + ) + | ( + Availability::ReadUnavailable, + ReportedEvaluation::NotObserved, + Policy::NotObserved, + Some( + ReadFailure::ReadNotConfigured + | ReadFailure::ReadTransportUnavailable + | ReadFailure::ReadCancelled + | ReadFailure::ReadTimeout + | ReadFailure::ReadUnauthenticated + | ReadFailure::ReadUnsupportedTransport, + ), + None, + None, + ) => Ok(s), + _ => Err(()), + } +} +struct NoDuplicate<'a> { + b: &'a [u8], + p: usize, + root_keys: Vec, +} +impl<'a> NoDuplicate<'a> { + fn new(b: &'a [u8]) -> Self { + Self { + b, + p: 0, + root_keys: Vec::new(), + } + } + fn check(mut self) -> Result<(), ()> { + self.ws(); + self.v(0)?; + self.ws(); + const FIELDS: [&str; 9] = [ + "schemaVersion", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "readFailure", + "securityActivityTouched", + "familyCounts", + "truth", + "omissions", + ]; + if self.p == self.b.len() + && self.root_keys.len() == FIELDS.len() + && FIELDS + .iter() + .all(|field| self.root_keys.iter().any(|key| key == field)) + { + Ok(()) + } else { + Err(()) + } + } + fn v(&mut self, d: u8) -> Result<(), ()> { + if d >= 16 { + return Err(()); + } + self.ws(); + match self.peek() { + Some(b'{') => self.obj(d + 1), + Some(b'[') => self.arr(d + 1), + Some(b'\"') => self.str().map(|_| ()), + Some(b't') => self.word(b"true"), + Some(b'f') => self.word(b"false"), + Some(b'n') => self.word(b"null"), + Some(b'-' | b'0'..=b'9') => { + let s = self.p; + while matches!( + self.peek(), + Some(b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') + ) { + self.p += 1 + } + serde_json::from_slice::(&self.b[s..self.p]) + .map(|_| ()) + .map_err(|_| ()) + } + _ => Err(()), + } + } + fn obj(&mut self, d: u8) -> Result<(), ()> { + self.p += 1; + let mut k = Vec::new(); + self.ws(); + if self.take(b'}') { + return Ok(()); + } + loop { + self.ws(); + let x = self.str()?; + if k.iter().any(|y: &String| y == &x) || k.len() >= 32 { + return Err(()); + } + k.push(x); + self.ws(); + if !self.take(b':') { + return Err(()); + } + self.v(d)?; + self.ws(); + if self.take(b'}') { + if d == 1 { + self.root_keys = k; + } + return Ok(()); + } + if !self.take(b',') { + return Err(()); + } + } + } + fn arr(&mut self, d: u8) -> Result<(), ()> { + self.p += 1; + let mut n = 0; + self.ws(); + if self.take(b']') { + return Ok(()); + } + loop { + n += 1; + if n > 64 { + return Err(()); + } + self.v(d)?; + self.ws(); + if self.take(b']') { + return Ok(()); + } + if !self.take(b',') { + return Err(()); + } + } + } + fn str(&mut self) -> Result { + let s = self.p; + if !self.take(b'\"') { + return Err(()); + } + let mut esc = false; + while let Some(x) = self.peek() { + self.p += 1; + if esc { + esc = false; + continue; + } + if x == b'\\' { + esc = true + } else if x == b'\"' { + let decoded: String = serde_json::from_slice(&self.b[s..self.p]).map_err(|_| ())?; + return if decoded.len() <= 4096 { + Ok(decoded) + } else { + Err(()) + }; + } else if x < 32 { + return Err(()); + } + } + Err(()) + } + fn word(&mut self, x: &[u8]) -> Result<(), ()> { + if self.b.get(self.p..self.p + x.len()) == Some(x) { + self.p += x.len(); + Ok(()) + } else { + Err(()) + } + } + fn ws(&mut self) { + while matches!(self.peek(), Some(b' ' | b'\n' | b'\r' | b'\t')) { + self.p += 1 + } + } + fn peek(&self) -> Option { + self.b.get(self.p).copied() + } + fn take(&mut self, x: u8) -> bool { + if self.peek() == Some(x) { + self.p += 1; + true + } else { + false + } + } +} + +#[cfg(test)] +mod contract_tests { + use super::*; + use crate::lnsat_request_record::ReadUnavailable; + use serde_json::{Value, json}; + fn input() -> RequestRecordInput { + RequestRecordInput { + installation_id: "sensitive-installation-canary".into(), + environment: "sensitive-environment-canary".into(), + selected_request_id: format!("arq_{:064x}", 1), + expected_project_ref: "project:secret".into(), + expected_resource_ref: "resource:secret".into(), + body: RequestRecordBody::ReadUnavailable(ReadUnavailable::Timeout), + read_at: None, + } + } + fn summary() -> Value { + json!({"schemaVersion":"rangoon.integrations.lnsat-request-summary.v1","recordAvailability":"read_unavailable","reportedEvaluation":"not_observed","reportedPolicy":"not_observed","readFailure":"read_timeout","securityActivityTouched":null,"familyCounts":null,"truth":{"authenticity":"unverified","authority":"none","execution":"unavailable","authoritativeOutcome":"unknown","independentEffect":"not_observed","currentness":"unverified"},"omissions":[{"path":"request.requester_ref","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"},{"path":"evidence.approval_decisions[*].reason","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"}]}) + } + fn valid(value: &Value) -> bool { + decode_summary(&serde_json::to_vec(value).unwrap()).is_ok() + } + fn counts(n: u64) -> Value { + json!({"approvals":n,"approval_decisions":n,"authorization_attempts":n,"authorizations":n,"operations":n,"consumptions":n,"operation_attempts":n,"receipts":n,"reconciliations":n,"states":n}) + } + fn policy() -> Value { + let mut v = summary(); + v["recordAvailability"] = json!("complete"); + v["reportedEvaluation"] = json!("policy_recorded"); + v["reportedPolicy"] = json!("allow"); + v["readFailure"] = Value::Null; + v["securityActivityTouched"] = json!(false); + v["familyCounts"] = counts(0); + v + } + + #[test] + fn i10_all_thirteen_typed_errors_have_exact_local_envelope() { + use RequestRecordError::*; + let table = [ + (InputLimit, "input_limit"), + (InvalidEncoding, "invalid_encoding"), + (InvalidJson, "invalid_json"), + (DuplicateField, "duplicate_field"), + (StructuralLimit, "structural_limit"), + (UnsupportedSchema, "unsupported_schema"), + (InvalidEnvelope, "invalid_envelope"), + (SelectionMismatch, "selection_mismatch"), + (ScopeMismatch, "scope_mismatch"), + (LineageConflict, "lineage_conflict"), + (UnsupportedState, "unsupported_state"), + (OutputLimit, "output_limit"), + (SerializationFailed, "serialization_failed"), + ]; + for (error, code) in table { + let v = View::decoder(7, error); + let actual: Value = + serde_json::from_slice(&checked_encode(&v, MAX_PRESENTATION_BYTES).unwrap()) + .unwrap(); + assert_eq!( + actual, + json!({"schemaVersion":VIEW_SCHEMA,"epoch":7,"state":"rejected","summary":null,"error":{"kind":"decoder","code":code,"truth":summary()["truth"]}}) + ); + let native: Value = serde_json::from_slice(&error.json_bytes()).unwrap(); + assert_eq!( + native, + json!({"schemaVersion":"rangoon.integrations.lnsat-request-error.v1","code":code,"truth":summary()["truth"]}) + ); + assert!(error.json_bytes().len() <= 1024); + } + } + #[test] + fn i11_exact_keys_required_nulls_duplicates_and_types() { + nested_duplicate_oracles(); + let base = summary(); + assert!(valid(&base)); + for key in base.as_object().unwrap().keys() { + let mut v = base.clone(); + v.as_object_mut().unwrap().remove(key); + assert!(!valid(&v), "missing {key}"); + } + for (key, value) in [ + ("schemaVersion", json!("unknown")), + ("recordAvailability", json!(false)), + ("reportedPolicy", json!("execute")), + ("readFailure", json!({})), + ("securityActivityTouched", json!(0)), + ("familyCounts", json!([])), + ] { + let mut v = base.clone(); + v[key] = value; + assert!(!valid(&v), "type {key}"); + } + let bytes = serde_json::to_string(&base).unwrap(); + for key in ["schemaVersion", "truth"] { + let value = serde_json::to_string(&base[key]).unwrap(); + let duplicate = format!("{{\"{key}\":{value},{}", &bytes[1..]); + assert!(decode_summary(duplicate.as_bytes()).is_err()); + } + let escaped = format!( + "{{\"\\u0073chemaVersion\":\"rangoon.integrations.lnsat-request-summary.v1\",{}", + &bytes[1..] + ); + assert!(decode_summary(escaped.as_bytes()).is_err()); + let mut v = base.clone(); + v["truth"]["unexpected"] = json!("secret"); + assert!(!valid(&v)); + let mut v = base; + v["unexpected"] = json!("secret"); + assert!(!valid(&v)); + } + // Continue I11 with nested duplicates: a lossy JSON map would accept these. + // The originals and duplicate spellings are constructed independently of + // the production parser, including JSON-escaped keys. + fn nested_duplicate_oracles() { + let original = serde_json::to_string(&policy()).unwrap(); + let cases = [ + (r#""truth":{"#, r#""truth":{"authority":"none","#), + (r#""truth":{"#, r#""truth":{"\u0061uthority":"none","#), + (r#""familyCounts":{"#, r#""familyCounts":{"approvals":0,"#), + ( + r#""familyCounts":{"#, + r#""familyCounts":{"\u0061pprovals":0,"#, + ), + ( + r#""omissions":[{"#, + r#""omissions":[{"path":"request.requester_ref","#, + ), + ( + r#""omissions":[{"#, + r#""omissions":[{"\u0070ath":"request.requester_ref","#, + ), + ]; + assert!(decode_summary(original.as_bytes()).is_ok()); + for (target, replacement) in cases { + assert!(original.contains(target)); + let duplicate = original.replacen(target, replacement, 1); + assert!( + decode_summary(duplicate.as_bytes()).is_err(), + "nested duplicate accepted" + ); + } + } + #[test] + fn i13_counts_truth_omissions_and_impossible_tuples() { + let base = policy(); + assert!(valid(&base)); + for n in [0, 64] { + let mut v = base.clone(); + v["familyCounts"] = counts(n); + assert!(valid(&v)); + } + for key in counts(0).as_object().unwrap().keys() { + for bad in [json!(65), json!(-1), json!(true), json!(1.0), Value::Null] { + let mut v = base.clone(); + v["familyCounts"][key] = bad; + assert!(!valid(&v)); + } + let mut v = base.clone(); + v["familyCounts"].as_object_mut().unwrap().remove(key); + assert!(!valid(&v)); + } + let mut v = base.clone(); + v["familyCounts"]["approvalDecisions"] = json!(0); + assert!(!valid(&v)); + let mut v = base.clone(); + v["familyCounts"] = Value::Null; + assert!(!valid(&v)); + let mut v = summary(); + v["familyCounts"] = counts(0); + assert!(!valid(&v)); + for key in summary()["truth"].as_object().unwrap().keys() { + let mut v = base.clone(); + v["truth"][key] = json!("verified"); + assert!(!valid(&v)); + } + for change in 0..5 { + let mut v = base.clone(); + match change { + 0 => v["omissions"].as_array_mut().unwrap().reverse(), + 1 => { + v["omissions"].as_array_mut().unwrap().pop(); + } + 2 => v["omissions"][0]["reason"] = json!("other"), + 3 => v["omissions"][0]["disposition"] = json!("present"), + _ => v["omissions"][0]["path"] = json!("other"), + }; + assert!(!valid(&v)); + } + for availability in ["degraded", "read_unavailable", "read_rejected_unclassified"] { + let mut v = base.clone(); + v["recordAvailability"] = json!(availability); + assert!(!valid(&v)); + } + let mut v = summary(); + v["readFailure"] = json!("native_read_rejected_unclassified"); + assert!(!valid(&v)); + } + #[test] + fn i14_exact_input_and_context_boundaries() { + for size in [65536, 65537] { + let mut h = RequestInspectionHost::new(); + let mut i = input(); + i.body = RequestRecordBody::Body200(vec![b' '; size]); + let admitted = h.begin(i); + assert_eq!(admitted.is_ok(), size == 65536); + } + for n in [128, 129] { + let mut h = RequestInspectionHost::new(); + let mut i = input(); + i.installation_id = "x".repeat(n); + let done = h.begin(i).unwrap().decode(); + h.complete(done); + let bytes = h.presentation().unwrap().json_bytes().unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + v["state"], + if n == 128 { + "summary_ready" + } else { + "rejected" + } + ); + } + } + #[test] + fn i15_summary_size_and_structural_limits() { + let bytes = serde_json::to_vec(&summary()).unwrap(); + let mut exact = bytes.clone(); + exact.resize(MAX_SUMMARY, b' '); + assert!(decode_summary(&exact).is_ok()); + exact.push(b' '); + assert!(decode_summary(&exact).is_err()); + let pretty = serde_json::to_vec_pretty(&summary()).unwrap(); + assert!(decode_summary(&pretty).is_ok()); + let mut v = summary(); + v["unexpected"] = json!("x".repeat(4097)); + assert!(!valid(&v)); + let deep = format!("{}0{}", "[".repeat(17), "]".repeat(17)); + assert!(decode_summary(deep.as_bytes()).is_err()); + let mut v = summary(); + v["omissions"] = json!([]); + assert!(!valid(&v)); + } + #[test] + fn i16_presentation_cap_and_serializer_failure() { + let exact = "x".repeat(MAX_PRESENTATION_BYTES - 2); + assert_eq!( + checked_encode(&exact, MAX_PRESENTATION_BYTES) + .unwrap() + .len(), + MAX_PRESENTATION_BYTES + ); + assert_eq!( + checked_encode(&(exact + "x"), MAX_PRESENTATION_BYTES).unwrap_err(), + PresentationError::OutputLimit + ); + struct Fail; + impl Serialize for Fail { + fn serialize(&self, _s: S) -> Result { + Err(serde::ser::Error::custom("sensitive serializer canary")) + } + } + let err = checked_encode(&Fail, MAX_PRESENTATION_BYTES).unwrap_err(); + assert_eq!(err, PresentationError::SerializationFailed); + assert!(!format!("{err:?} {err}").contains("canary")); + } + #[test] + fn i21_ack_cannot_release_held_completed_result_or_foreign_owner() { + let mut a = RequestInspectionHost::new(); + let own = a.begin(input()).unwrap().decode(); + let t = a.discard().unwrap(); + a.acknowledge_purge(t).unwrap(); + assert_eq!(a.state(), InspectionState::DiscardPending); + let mut b = RequestInspectionHost::new(); + let foreign = b.begin(input()).unwrap().decode(); + assert_eq!(a.complete(foreign), CompletionDisposition::Dropped); + assert_eq!(a.state(), InspectionState::DiscardPending); + drop(own); + a.refresh_cleanup(); + assert_eq!(a.state(), InspectionState::Discarded); + assert!(a.presentation().is_err()); + } + #[test] + fn i23_i24_exact_cycle_and_view_join() { + let mut h = RequestInspectionHost::new(); + let t = h.discard().unwrap(); + let repeated = h.discard().unwrap(); + assert!(Arc::ptr_eq(&t.ticket, &repeated.ticket)); + h.close(); + assert!(Arc::ptr_eq(&t.ticket, &h.ticket().unwrap().ticket)); + h.acknowledge_purge(t.clone()).unwrap(); + assert_eq!(h.state(), InspectionState::Closed); + let mut h = RequestInspectionHost::new(); + let old = h.discard().unwrap(); + h.acknowledge_purge(old.clone()).unwrap(); + let current = h.discard().unwrap(); + assert!(h.acknowledge_purge(old).is_err()); + assert_eq!(h.state(), InspectionState::DiscardPending); + let wrong_view = PurgeTicket { + binding: Binding { + instance: h.binding.instance.clone(), + view: Arc::new(()), + }, + ticket: current.ticket.clone(), + }; + assert!(h.acknowledge_purge(wrong_view).is_err()); + h.acknowledge_purge(current).unwrap(); + } + #[test] + fn i26_terminal_generation_reserve_does_not_wrap() { + let mut h = RequestInspectionHost::new(); + h.epoch = TERMINAL - 1; + let done = h.begin(input()).unwrap().decode(); + let t = h.discard().unwrap(); + assert_eq!(h.epoch(), TERMINAL); + assert_eq!( + h.begin(input()).unwrap_err(), + InspectionControlError::Closed + ); + h.acknowledge_purge(t).unwrap(); + assert_eq!(h.state(), InspectionState::DiscardPending); + assert_eq!(h.complete(done), CompletionDisposition::Dropped); + assert_eq!(h.state(), InspectionState::Closed); + assert_eq!(h.epoch(), TERMINAL); + } + #[test] + fn i27_decoder_panic_has_no_result_or_retry_authority() { + let mut h = RequestInspectionHost::new(); + let w = h.begin(input()).unwrap(); + let done = w.decode_with(|_| panic!("synthetic decoder failure")); + let t = h.discard().unwrap(); + h.acknowledge_purge(t).unwrap(); + assert_eq!(h.state(), InspectionState::DiscardPending); + h.complete(done); + assert_eq!(h.state(), InspectionState::Discarded); + assert!(h.presentation().is_err()); + let mut h = RequestInspectionHost::new(); + let done = h + .begin(input()) + .unwrap() + .decode_with(|_| panic!("synthetic decoder failure")); + h.complete(done); + let v: Value = + serde_json::from_slice(&h.presentation().unwrap().json_bytes().unwrap()).unwrap(); + assert_eq!(v["error"]["code"], "inspection_failed"); + assert!(v["summary"].is_null()); + assert_eq!(h.begin(input()).unwrap_err(), InspectionControlError::Busy); + } + #[test] + fn i19_retained_projection_is_cleared_immediately() { + let mut h = RequestInspectionHost::new(); + let done = h.begin(input()).unwrap().decode(); + h.complete(done); + assert!(h.presentation.is_some()); + let epoch = h.epoch(); + let _ticket = h.discard().unwrap(); + assert_eq!(h.epoch(), epoch + 1); + assert!(h.presentation.is_none()); + assert!(h.presentation().is_err()); + assert_eq!(h.state(), InspectionState::DiscardPending); + } + #[test] + fn i24_pending_completion_does_not_allocate_replacement_purge() { + let mut h = RequestInspectionHost::new(); + let held = h.begin(input()).unwrap(); + let t = h.discard().unwrap(); + let epoch = h.epoch(); + h.acknowledge_purge(t).unwrap(); + drop(held); + assert!(h.discard().is_none()); + assert_eq!(h.state(), InspectionState::Discarded); + assert_eq!(h.epoch(), epoch); + } + #[test] + fn i28_production_surface_remains_pure_and_unmounted() { + let source = include_str!("lnsat_request_inspection.rs") + .split("#[cfg(test)]") + .next() + .unwrap(); + for forbidden in [ + "std::fs", + "std::process", + "std::thread", + "std::net", + "std::env", + "SystemTime", + "Instant::now", + "pub fn decode_with", + "pub fn set_epoch", + "pub fn decode_summary", + ] { + assert!(!source.contains(forbidden), "unexpected port {forbidden}"); + } + assert!(source.contains("pub fn presentation(&mut self)")); + assert!(source.contains("owner.release()")); + } +} diff --git a/crates/rangoon-integrations/tests/lnsat_request_inspection.rs b/crates/rangoon-integrations/tests/lnsat_request_inspection.rs new file mode 100644 index 0000000..4174642 --- /dev/null +++ b/crates/rangoon-integrations/tests/lnsat_request_inspection.rs @@ -0,0 +1,404 @@ +//! Public synthetic inspection lifecycle. No I/O/provider/runtime. +use rangoon_domain::byte_digest; +use rangoon_integrations::lnsat_request_inspection::{ + CompletionDisposition, InspectionControlError, InspectionState, RequestInspectionHost, +}; +use rangoon_integrations::lnsat_request_record::{ + ReadUnavailable, RequestRecordBody, RequestRecordInput, +}; +use serde_json::{Value, json}; +const R: &str = "arq_0000000000000000000000000000000000000000000000000000000000000001"; +const P: &str = "project:synthetic"; +const X: &str = "resource:synthetic"; +const SECRET: &str = "requester-private-sentinel"; +fn id(p: &str, n: u8) -> String { + format!("{p}{n:064x}") +} +fn dg(n: u8) -> String { + format!("sha256:{n:064x}") +} +fn at(n: u8) -> String { + format!("2026-10-26T12:00:{n:02}.000Z") +} +fn cm(d: &str, x: Vec) -> String { + let b = serde_json::to_vec(&Value::Array(x)).unwrap(); + let mut m = d.as_bytes().to_vec(); + m.push(b'\n'); + m.extend(b); + format!("sha256:{}", byte_digest(&m)) +} +fn root() -> Value { + json!({"request_id":R,"requester_ref":SECRET,"project_ref":P,"resource_ref":X,"packet_id":"packet:synthetic","packet_sha256":dg(1),"action_digest":dg(2),"target_digest":dg(3),"configuration_digest":dg(4),"created_at":at(0),"evidence_digest":dg(5)}) +} +fn policy(d: &str) -> Value { + json!({"decision_id":id("pol_",1),"evaluated_at":at(0),"expires_at":at(59),"decision":d,"requires_approval":if d=="approval_required"{1}else{0}}) +} +fn evaluation(s: &str, p: Option, r: &str) -> Value { + let q = root(); + json!({"status":s,"policy_decision_id":p.clone(),"reason_code":r,"recorded_at":at(0),"evidence_digest":cm("lnsat.action_request.evaluation.v1",vec![json!(R),q["packet_id"].clone(),q["packet_sha256"].clone(),json!(P),json!(X),json!(s),p.map(Value::String).unwrap_or(Value::Null),json!(r),json!(at(0))])}) +} +fn evidence(d: &str) -> Value { + json!({"schema":"lnsat.action_request_linked_evidence.v1","policy":policy(d),"approvals":[],"approval_decisions":[],"authorization_attempts":[],"authorizations":[],"operations":[],"consumptions":[],"operation_attempts":[],"receipts":[],"reconciliations":[],"states":[]}) +} +fn complete(d: &str) -> Value { + json!({"schema":"lnsat.action_request_record.v1","status":"complete","request_id":R,"evaluation_state":"policy_recorded","request":root(),"evaluation":evaluation("recorded",Some(id("pol_",1)),"policy_recorded"),"observations":[],"evidence":evidence(d),"security_activity_touched":false}) +} +fn failed() -> Value { + json!({"schema":"lnsat.action_request_record.v1","status":"complete","request_id":R,"evaluation_state":"evaluation_failed","request":root(),"evaluation":evaluation("failed",None,"evaluation_rejected"),"observations":[],"evidence":null,"security_activity_touched":false}) +} +fn unknown() -> Value { + json!({"schema":"lnsat.action_request_record.v1","status":"complete","request_id":R,"evaluation_state":"evaluation_unknown","request":root(),"evaluation":null,"observations":[],"evidence":null,"security_activity_touched":false}) +} +fn degraded() -> Value { + json!({"schema":"lnsat.action_request_record.v1","status":"degraded","request_id":R,"evaluation_state":"evaluation_unknown","request":null,"evaluation":null,"observations":[],"evidence":null,"security_activity_touched":true}) +} +fn ctx(b: RequestRecordBody) -> RequestRecordInput { + RequestRecordInput { + installation_id: "test".into(), + environment: "test".into(), + selected_request_id: R.into(), + expected_project_ref: P.into(), + expected_resource_ref: X.into(), + body: b, + read_at: Some(at(58)), + } +} +fn host(v: Value) -> RequestInspectionHost { + let mut h = RequestInspectionHost::new(); + let w = h + .begin(ctx(RequestRecordBody::Body200( + serde_json::to_vec(&v).unwrap(), + ))) + .unwrap(); + assert_eq!(h.complete(w.decode()), CompletionDisposition::Published); + h +} +fn view(h: &mut RequestInspectionHost) -> Value { + let l = h.presentation().unwrap(); + serde_json::from_slice(&l.json_bytes().unwrap()).unwrap() +} +fn assert_summary(p: &Value, a: &str, e: &str, pol: &str, security: Value, counts: Value) { + assert_eq!( + p, + &json!({"schemaVersion":"rangoon.inspection.lnsat-request-summary-view.v1","epoch":1,"state":"summary_ready","error":null,"summary":{"schemaVersion":"rangoon.integrations.lnsat-request-summary.v1","recordAvailability":a,"reportedEvaluation":e,"reportedPolicy":pol,"readFailure":null,"securityActivityTouched":security,"familyCounts":counts,"truth":{"authenticity":"unverified","authority":"none","execution":"unavailable","authoritativeOutcome":"unknown","independentEffect":"not_observed","currentness":"unverified"},"omissions":[{"path":"request.requester_ref","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"},{"path":"evidence.approval_decisions[*].reason","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"}]}}) + ); + let text = serde_json::to_string(p).unwrap(); + for canary in [ + SECRET, + R, + P, + X, + "packet:synthetic", + "2026-10-26T", + "sha256:", + ] { + assert!(!text.contains(canary), "leaked {canary}"); + } +} +#[test] +fn i01_allow_full_projection() { + let mut h = host(complete("allow")); + assert_summary( + &view(&mut h), + "complete", + "policy_recorded", + "allow", + json!(false), + json!({"approvals":0,"approval_decisions":0,"authorization_attempts":0,"authorizations":0,"operations":0,"consumptions":0,"operation_attempts":0,"receipts":0,"reconciliations":0,"states":0}), + ) +} +#[test] +fn i02_context_mismatch_rejects() { + for n in 0..3 { + let mut c = ctx(RequestRecordBody::Body200( + serde_json::to_vec(&complete("allow")).unwrap(), + )); + if n == 0 { + c.selected_request_id = id("arq_", 9) + } + if n == 1 { + c.expected_project_ref = "project:other".into() + } + if n == 2 { + c.expected_resource_ref = "resource:other".into() + } + let mut h = RequestInspectionHost::new(); + let w = h.begin(c).unwrap(); + h.complete(w.decode()); + assert_eq!(view(&mut h)["state"], "rejected") + } +} +#[test] +fn i04_allow_no_authority() { + let mut h = host(complete("allow")); + assert_eq!(view(&mut h)["summary"]["truth"]["authority"], "none") +} +#[test] +fn i05_deny_report() { + let mut h = host(complete("deny")); + assert_eq!(view(&mut h)["summary"]["reportedPolicy"], "deny") +} +#[test] +fn i06_approval_report() { + let mut h = host(complete("approval_required")); + assert_eq!( + view(&mut h)["summary"]["reportedPolicy"], + "approval_required" + ) +} +#[test] +fn i07_failed_unknown() { + for (v, e) in [ + (failed(), "evaluation_failed"), + (unknown(), "evaluation_unknown"), + ] { + let mut h = host(v); + assert_summary( + &view(&mut h), + "complete", + e, + "not_observed", + json!(false), + Value::Null, + ) + } +} +#[test] +fn i08_degraded() { + let mut h = host(degraded()); + assert_summary( + &view(&mut h), + "degraded", + "evaluation_unknown", + "not_observed", + json!(true), + Value::Null, + ) +} +#[test] +fn i09_unavailable() { + for (kind, failure) in [ + (ReadUnavailable::NotConfigured, "read_not_configured"), + ( + ReadUnavailable::TransportUnavailable, + "read_transport_unavailable", + ), + (ReadUnavailable::Cancelled, "read_cancelled"), + (ReadUnavailable::Timeout, "read_timeout"), + (ReadUnavailable::Unauthenticated, "read_unauthenticated"), + ( + ReadUnavailable::UnsupportedTransport, + "read_unsupported_transport", + ), + ] { + let mut h = RequestInspectionHost::new(); + let w = h + .begin(ctx(RequestRecordBody::ReadUnavailable(kind))) + .unwrap(); + h.complete(w.decode()); + let mut p = view(&mut h); + assert_eq!(p["summary"]["readFailure"], failure); + p["summary"]["readFailure"] = Value::Null; + assert_summary( + &p, + "read_unavailable", + "not_observed", + "not_observed", + Value::Null, + Value::Null, + ); + } +} + +#[test] +fn i10_refused_403() { + let mut h = RequestInspectionHost::new(); + let w=h.begin(ctx(RequestRecordBody::Refused403(br#"{"schema":"lnsat.action_request_record.v1","ok":false,"error":{"code":"gateway.action_request_record.denied"}}"#.to_vec()))).unwrap(); + h.complete(w.decode()); + let mut p = view(&mut h); + assert_eq!( + p["summary"]["readFailure"], + "native_read_rejected_unclassified" + ); + p["summary"]["readFailure"] = Value::Null; + assert_summary( + &p, + "read_rejected_unclassified", + "not_observed", + "not_observed", + Value::Null, + Value::Null, + ); +} + +#[test] +fn i12_debug_opaque() { + let h = RequestInspectionHost::new(); + assert!(!format!("{h:?}").contains(SECRET)) +} +#[test] +fn i17_i18_busy() { + let mut h = host(complete("allow")); + assert!(matches!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))), + Err(InspectionControlError::Busy) + )); + let t = h.discard().unwrap(); + h.acknowledge_purge(t).unwrap(); + assert!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .is_ok() + ) +} +#[test] +fn i19_i20_late_dropped() { + let mut h = RequestInspectionHost::new(); + let d = h + .begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout, + ))) + .unwrap() + .decode(); + let t = h.discard().unwrap(); + assert_eq!(h.complete(d), CompletionDisposition::Dropped); + h.acknowledge_purge(t).unwrap(); + assert_eq!(h.state(), InspectionState::Discarded) +} +#[test] +fn i22_i23_cross_host_ticket() { + let mut a = host(complete("allow")); + let mut b = RequestInspectionHost::new(); + let t = a.discard().unwrap(); + assert!(matches!( + b.acknowledge_purge(t.clone()), + Err(InspectionControlError::StaleTicket) + )); + a.acknowledge_purge(t).unwrap() +} +#[test] +fn i24_i25_close_sticky() { + let mut h = host(complete("allow")); + let t = h.discard().unwrap(); + h.close(); + h.acknowledge_purge(t).unwrap(); + assert_eq!(h.state(), InspectionState::Closed); + assert_eq!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .unwrap_err(), + InspectionControlError::Closed + ); + assert!(h.close().is_none()); + assert!(h.discard().is_none()); + assert!(h.presentation().is_err()) +} +#[test] +fn i27_drop_waits_ack() { + let mut h = RequestInspectionHost::new(); + let w = h + .begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout, + ))) + .unwrap(); + let t = h.discard().unwrap(); + drop(w); + h.refresh_cleanup(); + assert_eq!(h.state(), InspectionState::DiscardPending); + h.acknowledge_purge(t).unwrap(); + assert_eq!(h.state(), InspectionState::Discarded) +} + +#[test] +fn i03_payload_cannot_choose_its_own_expected_scope() { + let mut v = complete("allow"); + v["request_id"] = json!(id("arq_", 9)); + v["request"]["request_id"] = json!(id("arq_", 9)); + let mut h = host(v); + let p = view(&mut h); + assert_eq!(p["state"], "rejected"); + assert_eq!(p["error"]["code"], "selection_mismatch"); + assert!(p["summary"].is_null()); +} +#[test] +fn i17_busy_during_active_decode_has_no_prior_payload() { + let mut h = RequestInspectionHost::new(); + let held = h + .begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout, + ))) + .unwrap(); + assert_eq!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Cancelled + ))) + .unwrap_err(), + InspectionControlError::Busy + ); + assert!(h.presentation().is_err()); + drop(held); + assert_eq!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .unwrap_err(), + InspectionControlError::Busy + ); +} +#[test] +fn i18_rejected_result_requires_completed_discard() { + let mut h = host(json!({})); + assert_eq!(view(&mut h)["state"], "rejected"); + assert_eq!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .unwrap_err(), + InspectionControlError::Busy + ); + let t = h.discard().unwrap(); + assert_eq!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .unwrap_err(), + InspectionControlError::Busy + ); + h.acknowledge_purge(t).unwrap(); + assert!( + h.begin(ctx(RequestRecordBody::ReadUnavailable( + ReadUnavailable::Timeout + ))) + .is_ok() + ); +} +#[test] +fn i12_all_opaque_objects_keep_sensitive_context_out_of_debug() { + let mut h = RequestInspectionHost::new(); + let mut i = ctx(RequestRecordBody::ReadUnavailable(ReadUnavailable::Timeout)); + i.installation_id = "PRIVATE_INSTALLATION".into(); + i.environment = "PRIVATE_ENVIRONMENT".into(); + let work = h.begin(i).unwrap(); + let w = format!("{work:?}"); + let done = work.decode(); + let d = format!("{done:?}"); + h.complete(done); + let v = format!("{:?}", h.presentation().unwrap()); + let t = h.discard().unwrap(); + let text = format!("{h:?} {t:?} {w} {d} {v}"); + for canary in [ + "PRIVATE_INSTALLATION", + "PRIVATE_ENVIRONMENT", + R, + P, + X, + SECRET, + "read_timeout", + ] { + assert!(!text.contains(canary)); + } +} diff --git a/docs/development.md b/docs/development.md index 1574376..a6a54ca 100644 --- a/docs/development.md +++ b/docs/development.md @@ -3963,3 +3963,21 @@ Publication integration found the reviewed decoder used unsigned `is_multiple_of Current publication validation: the existing Rust 1.85.0 tuple passed all 78 package tests (19 library, 11 unchanged public-base D3a, 36 new decoder and 12 OpenShell), zero failures/ignored, through locked offline Cargo. The earlier 81-test source receipt includes three unrelated dirty-worktree D3a tests and is not the public-base regression count. Strict package all-target Clippy02 passes with warnings denied. Clippy01 correctly rejected one needless explicit implementation lifetime; replacing `impl<'a> Parser<'a>` with `impl Parser<'_>` is the second compatibility-only line change. No lint exemption was added. Workspace Rustfmt01 and document/reference checks (469 authored files, eight image hashes and historical brief) pass; the final exact-source format/readback and independent integration review are recorded separately. Existing source reviews are reused for the unchanged decoder/test behavior; historical receipts and failed attempts remain preserved. Publication integration qualification: final Rust 1.85 package tests02 passed 78/78; strict all-target package Clippy02, final workspace Rustfmt02, scoped whitespace and document/reference validation passed (469 authored text files). Fresh independent native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra/xhigh`, reviewed the six-path integration and exact two-line compatibility delta: PASS with no actionable P1/P2/P3. Backend runtime model ID is unexposed. No source/test/dependency/workflow bytes changed after those checks. Hosted source CI and publication outcome remain separately pending; no merge or runtime authority follows. + +## Offline request-record inspection boundary — October 26, 2026 + +Authority: Jeff directly accepted implementation of the reviewed offline inspection contract, synthetic tests, docs and independent GPT review, preserving D3a and excluding live reads, reconciliation, installs and real runtime. Canonical private source evidence is `/private/tmp/rangoon-offline-request-record-inspection-source-20261026`; the frozen reviewed preparation remains `/private/tmp/rangoon-offline-request-record-inspection-contract-20261026`. Preparation-only labels are dated history, superseded only for this exact pure source/test slice. Publication, native/UI adoption and later operational gates remain closed. The new isolated branch starts from then-verified public main `0e78b1d7dcb45f6e01a36b5c1559d839afbfdbaf`, preserving the prior publication branch and unrelated dirty checkout. + +Experience track: one offline inspection, summary-only fixed labels/counts, explicit Discard and honest pending/closed states. No rendered view, accessibility, keyboard, responsive or native UI qualification is supplied. Technical track: the pure host lifecycle/projection module implements the 28 reviewed source/synthetic/structural obligations using the existing pinned decoder without changing D3a or O1/O2. Current-candidate validation and source review are recorded below; earlier decoder CI is not evidence for this new module. + +Security/standards impact: sensitive input, full selection, native correlation fields, decoder host output and digest remain host-owned. Only a strictly closed summary or fixed error may reach a cooperating presenter; summary is not anonymous or accepted for storage. No persistence, diagnostics/model transmission, plaintext fallback, key/vault access, dependency, build privilege, workflow or authority change is included. Logical owned release and purge acknowledgment do not establish zeroization, native callback drain, authenticated ingress, hostile-process containment or supply-chain provenance. Applicable existing ISO/OpenSSF/OSPS/SLSA readiness work is bounded input/privacy/ownership documentation, positive/negative synthetic obligations, pinned source, named validation, fresh review and explicit gaps. No badge, score, certification, maturity/level or organizational compliance is claimed. Jeff owns separately accepting later source/native/UI/operational work and release-wide evidence; the controller owns current packet integration and the independent GPT owns review judgment only. + +Current validation scope selects the existing Rust 1.85 toolchain explicitly through rustup, locked/offline package tests and strict package all-target Clippy, workspace Rustfmt and document/reference checks. No installation/download or dependency-cache copying/import is permitted. Conditional trusted controller fixtures cannot prove installed runtime, physical clocks/deadlines/custody/durability/cleanup, three-OS GUI support, actual LNSAT consequence, Phase 11 or full functional readiness. All six later acquisition/renderer/workspace/native/connected adoption groups remain NOT_RUN. + +Current source: `lnsat_request_inspection` owns move-only input/completion custody and a non-Clone host with serialized mutable commands. A private original-instance/view/owner binding and terminal generation fence prevent late or foreign work from publishing. A borrowed presentation lease excludes mutation of that host while used. Discard clears the retained projection immediately but retains exact owner accounting until input/context/result release; final state also requires the current opaque purge-ticket acknowledgment. Repeated pending Discard cannot allocate a replacement purge after observing final release, and Close cannot reopen. The first API is pure; acknowledgment is a cooperating caller's report, not authenticated IPC or physical erasure. Caller copies and native/renderer caches are outside this source proof. + +Final source-candidate checks: existing Rust 1.85.0, locked/offline `tests-02`, passed 110 distinct Rust tests (32 library = 19 inherited plus 13 new, 11 D3a, 19 new inspection integration, 36 underlying decoder and 12 OpenShell), zero failures/ignored, plus one borrow compile-fail doctest. The new inspection evidence is 32 tests plus one compile-fail check; 28 contract obligations are mapped across these and named preservation checks, not 28 physical executions. Strict all-target package Clippy02 and workspace Rustfmt-check01 passed. Test repetitions across earlier candidates are not additional unique tests. Twelve separately reviewed mocked controller-helper guards passed under optimized isolated Python; they are metadata/process-port models, not physical process-containment proof. The first full source candidate and changed-oracle unit/integration successors also passed, but final qualification uses current exact candidate04. No local or target dependency install/download or cache copying/import occurred; existing cache was used in place. Tools and linked platform inputs remain conditional controller inputs, not authenticated loaded-code or supply-chain proof. + +Independent native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra/xhigh`, passed the corrected exact source/test chain with no open actionable P1/P2/P3. It closed two P2 oracle gaps (six unavailable failure labels and nested escaped duplicates) and a P3 post-close admission gap. Strict Clippy01 had failed two private enum-name warnings; the private type rename preserves serialized variant names and behavior, adds no allowance and passed exact delta review. Primary Codex integrated and strengthened initial native GPT worker source/tests; worker configured `gpt-5.6-terra/high`. Backend runtime model IDs are unexposed. All available draft, rejected helper and review snapshots, failed Clippy01 and the explicitly retracted helper-review observation remain in the private packet. Initial weak combined test names were rejected before any execution; they are not coverage evidence. Initial setup/ref/tool-dispatch and preparatory formatting/metadata failures are recorded separately. Document/reference, scope/preservation and final independent actual-evidence records belong to the same canonical private source packet; no hosted CI or publication is claimed. + +The accepted preparation remains byte-frozen. Existing decoder, D3a and O1/O2 source/tests/profile, dependencies, lockfiles, workflow and toolchain files are protected; all other checkouts and unrelated work remain untouched. Real collection/selector entry, renderer/IPC and purge authentication, workspace lock/close mounting, native failure/allocator cleanup, connected reads and the six adoption groups remain unqualified and unrun. No source CI, synthetic marker, checksum or reported acknowledgment grants LNSAT authority, installation/runtime compatibility, zeroization, support, release or full functional readiness. This source/docs packet is uncommitted and grants no push, PR, merge or later operational authority. diff --git a/docs/lnsat-evidence-connector.md b/docs/lnsat-evidence-connector.md index b49d3fd..18237ea 100644 --- a/docs/lnsat-evidence-connector.md +++ b/docs/lnsat-evidence-connector.md @@ -102,3 +102,11 @@ One coherent caller-owned record is checked against independently selected reque Host output removes `requester_ref` and approval-decision `reason` after validation. It retains sensitive native identifiers, references, digests and times only in caller-owned host memory, with a fixed omission ledger. It is not anonymous, renderer-safe or accepted for plaintext persistence. Summary bytes contain only fixed labels and bounded counts; errors and Debug/Display are payload-free. No secret/session/header/path/URL/callback input, logger, network, database, clock sampling, storage or reconciliation interface is introduced. Offline decode claims no authentication or permission. A later native GET requires the engine's paired current session/proof and ReadEvidence plus active Owner or original-requester scope. Evidence reading never grants reconciliation-write authority. No POST, login, session cleanup, local capability, role upgrade, production observer/coordinator or actual Git consequence is opened. L01–L06 connected checks, credential custody, consent/encrypted retention/purge, transport, target OS/runtime and independent effect/reconciliation qualification remain separate and unrun. No O1/O2 wire conversion or UI is mounted; Rangoon remains usable without LNSAT and every provider. + +## Pure offline request-record inspection boundary + +The separately accepted source slice `rangoon_integrations::lnsat_request_inspection` wraps only the pinned pure request-record decoder. Its independently selected complete input context is host-owned; no renderer-supplied path, credential, host-detail accessor or caller-supplied summary route is introduced. Presentation is restricted to the exact fixed-label/count summary or an explicitly mapped closed error envelope. The existing decoder error wire is unchanged. Reported allow, receipt counts and accepted records never become current permission, independently verified completion or reconciliation authority. + +The logical lifecycle separates publication rights from owned-data release. Discard clears retained presentation and invalidates delivery, while the current purge cycle keeps the exact outstanding owner accounted for even after its publication generation is revoked. Late results must be released and cannot restore the view. Discard completes only after owner drain and an exact current instance/view/purge-ticket acknowledgment; Close latches permanent admission closure. A delivery borrow models serialization, not an authenticated native IPC channel. Fixed errors and Debug output exclude raw, selection, host and summary contents. + +No persistence, history, logging/telemetry, clipboard/export, provider/model transmission, live read, session/CSRF, native command or workspace encryption mount is added. Logical release cannot erase caller copies, previous disclosures, swap or crash dumps. Actual acquisition, sensitive selector entry, authenticated renderer delivery/purge, workspace lock/close coupling and platform cleanup require separate accepted adoption packets. The six adoption groups remain unrun. D3a, O1/O2 and the native profile/wire pins are protected; the [source receipt](development.md#offline-request-record-inspection-boundary--october-26-2026) owns exact current validation and review evidence.