From 86a2202852595f372013d1f8ee4c604ceadbd616 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Tue, 1 Sep 2026 10:33:52 +0000 Subject: [PATCH] feat(api): cancel authorized exports via loopback CLI Publish tepp-export-cancel cancel so operators mint naruon POST /v1/exports/{export_id}/cancel onto spawned tepp-loopback TCP. Receipts stay metric-free cancelled=true. LineageWeave is refused. NaruonLiveService stays POST-only. ADR 0078. --- CHANGELOG.d/export-cancel-cli.md | 1 + DOCUMENTATION.md | 1 + crates/tepp_api/Cargo.toml | 6 + crates/tepp_api/src/bin/tepp_export_cancel.rs | 30 + crates/tepp_api/src/export_cancel_cli.rs | 602 ++++++++++++++++++ crates/tepp_api/src/lib.rs | 17 + .../tests/export_cancel_cli_contract.rs | 120 ++++ docs/API_CONTRACT.md | 2 +- docs/TRACEABILITY.md | 2 +- docs/adr/0078-export-cancel-cli.md | 103 +++ docs/adr/README.md | 1 + docs/connectors/naruon-artifact-consumer.md | 1 + docs/research/export-cancel-cli.md | 55 ++ 13 files changed, 939 insertions(+), 2 deletions(-) create mode 100644 CHANGELOG.d/export-cancel-cli.md create mode 100644 crates/tepp_api/src/bin/tepp_export_cancel.rs create mode 100644 crates/tepp_api/src/export_cancel_cli.rs create mode 100644 crates/tepp_api/tests/export_cancel_cli_contract.rs create mode 100644 docs/adr/0078-export-cancel-cli.md create mode 100644 docs/research/export-cancel-cli.md diff --git a/CHANGELOG.d/export-cancel-cli.md b/CHANGELOG.d/export-cancel-cli.md new file mode 100644 index 000000000..48198627d --- /dev/null +++ b/CHANGELOG.d/export-cancel-cli.md @@ -0,0 +1 @@ +- `tepp-export-cancel cancel` mints naruon `POST /v1/exports/{export_id}/cancel` onto spawned `tepp-loopback` TCP (ADR 0078). Metric-free `cancelled=true` receipts only. `tepp.scientific_acceptance.v1` never appears. Does not infer causality. LineageWeave refused. `NaruonLiveService` stays POST-only. Not export collection CLI, not interpretation-run cancel CLI, not GAP-010 Figma/export, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 0f1e1e03c..337cacf06 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -15,6 +15,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Orchestrator live HTTP doctoring | [`docs/research/orchestrator-live-http.md`](docs/research/orchestrator-live-http.md) | | Export collection GET doctoring | [`docs/research/export-collection-http.md`](docs/research/export-collection-http.md) | | Export cancel HTTP doctoring | [`docs/research/export-cancel-http.md`](docs/research/export-cancel-http.md) | +| Export cancel CLI doctoring | [`docs/research/export-cancel-cli.md`](docs/research/export-cancel-cli.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | | Security policy | [`SECURITY.md`](SECURITY.md) | diff --git a/crates/tepp_api/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c433..784ac358b 100644 --- a/crates/tepp_api/Cargo.toml +++ b/crates/tepp_api/Cargo.toml @@ -29,5 +29,11 @@ path = "src/bin/tepp_loopback.rs" test = false bench = false +[[bin]] +name = "tepp-export-cancel" +path = "src/bin/tepp_export_cancel.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/bin/tepp_export_cancel.rs b/crates/tepp_api/src/bin/tepp_export_cancel.rs new file mode 100644 index 000000000..e921ac0c0 --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_export_cancel.rs @@ -0,0 +1,30 @@ +//! Operator CLI for loopback naruon export cancel POST. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + execute_export_cancel_cli, read_export_cancel_cli_stdin, render_export_cancel_cli_stdout, + ApiError, ExportCancelCliInvocation, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(_) => ExitCode::FAILURE, + } +} + +fn run() -> Result<(), ApiError> { + let args: Vec = std::env::args().skip(1).collect(); + let body = read_export_cancel_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = ExportCancelCliInvocation::from_args(&args, body)?; + let response = execute_export_cancel_cli(&invocation)?; + let stdout = render_export_cancel_cli_stdout(&invocation, &response)?; + println!("{stdout}"); + if (200..300).contains(&response.status_code) { + Ok(()) + } else { + Err(ApiError::InvalidWirePayload) + } +} diff --git a/crates/tepp_api/src/export_cancel_cli.rs b/crates/tepp_api/src/export_cancel_cli.rs new file mode 100644 index 000000000..9142562a8 --- /dev/null +++ b/crates/tepp_api/src/export_cancel_cli.rs @@ -0,0 +1,602 @@ +//! Operator loopback CLI for naruon export cancel POST. +//! +//! GAP-003A unique slice: operators run `tepp-export-cancel cancel` to mint +//! `naruon_export_cancel_exchange` onto spawned `tepp-loopback` TCP. Stdout is +//! one metric-free cancelled identity with `cancelled=true`. +//! `tepp.scientific_acceptance.v1` never appears. `LineageWeave` is refused. +//! `NaruonLiveService` stays POST-only. Dedicated binary so it does not +//! collide with `tepp-export-list` (#444) or `tepp-export-get` (#417). This +//! module does not duplicate export cancel HTTP (#445), export collection CLI +//! (#444), export collection GET (#443), interpretation-run cancel CLI (#442), +//! interpretation-run cancel HTTP (#440), analysis-run cancel (#361), Leiden, +//! or GAP-010 Figma/export. Persistence remains GAP-003B. + +use std::fmt::Write as _; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; + +use crate::live_http::map_io_error; +use crate::naruon_http::header_is_credential; +use crate::wire::require_nonempty; +use crate::{ + export_cancel_path_id, naruon_export_cancel_exchange, refuse_metrics_on_export_retrieval_payload, + AnalysisRunLiveService, ApiError, ExportCancelled, EXPORT_CANCEL_ID_MAX_LEN, + NARUON_CONSUMER_CODE, NARUON_LIVE_IO_TIMEOUT, NaruonHttpExchange, NaruonLiveResponse, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; + +/// Supported operator verbs for the loopback export-cancel CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ExportCancelCliVerb { + /// `POST /v1/exports/{export_id}/cancel`. + Cancel, +} + +impl ExportCancelCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "cancel" => Ok(Self::Cancel), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Cancel => "cancel", + } + } +} + +/// One operator CLI invocation against a loopback export-cancel POST listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ExportCancelCliInvocation { + /// CLI verb to execute. + pub verb: ExportCancelCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published HTTPS origin used to mint the typed cancel exchange. + pub origin: String, + /// Published modular consumer. Cancel POST is naruon-only. + pub consumer: String, + /// Opaque export identity to cancel. + pub export_id: String, + /// JSON body. Cancel POST requires empty. + pub body: String, +} + +impl ExportCancelCliInvocation { + /// Parse argv plus stdin body into a validated loopback cancel invocation. + /// + /// Empty stdin is admitted. Nonempty leftover stdin fails closed. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, a non-`https` origin, a non-naruon consumer, + /// credential-shaped flags, a hostile identity, or a nonempty body. + pub fn from_args(args: I, body: impl Into) -> Result + where + I: IntoIterator, + S: AsRef, + { + let tokens: Vec = args + .into_iter() + .map(|token| token.as_ref().to_owned()) + .collect(); + let (verb_token, rest) = tokens.split_first().ok_or(ApiError::InvalidWirePayload)?; + let verb = ExportCancelCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile POST body. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`] for + /// empty, unpublished, nonempty-body, or hostile identity fields. + pub fn validate(&self) -> Result<(), ApiError> { + require_loopback_host(&self.host)?; + require_nonempty(&self.origin)?; + if !self.origin.starts_with("https://") { + return Err(ApiError::InvalidWirePayload); + } + require_nonempty(&self.consumer)?; + if self.consumer != NARUON_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + require_nonempty(&self.export_id)?; + if self.export_id.contains('/') || self.export_id.contains('\0') { + return Err(ApiError::InvalidWirePayload); + } + if self.export_id.len() > EXPORT_CANCEL_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + if !self.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance_schema(&self.body)?; + refuse_metrics_on_export_retrieval_payload(&self.body)?; + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + origin: Option, + consumer: Option, + export_id: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + origin: None, + consumer: None, + export_id: None, + }; + let mut index = 0; + while index < rest.len() { + let flag = rest[index].as_str(); + if !flag.starts_with("--") { + return Err(ApiError::InvalidWirePayload); + } + let name = &flag[2..]; + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + let slot = match name { + "host" => &mut flags.host, + "origin" => &mut flags.origin, + "consumer" => &mut flags.consumer, + "export-id" => &mut flags.export_id, + _ => return Err(ApiError::InvalidWirePayload), + }; + if slot.is_some() || index + 1 >= rest.len() { + return Err(ApiError::InvalidWirePayload); + } + let value = rest[index + 1].as_str(); + require_nonempty(value)?; + *slot = Some(value.to_owned()); + index += 2; + } + Ok(flags) +} + +fn assemble_invocation( + verb: ExportCancelCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = ExportCancelCliInvocation { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + origin: flags.origin.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| NARUON_CONSUMER_CODE.to_owned()), + export_id: flags.export_id.ok_or(ApiError::InvalidWirePayload)?, + body, + }; + invocation.validate()?; + Ok(invocation) +} + +fn require_loopback_host(host: &str) -> Result { + let addr: SocketAddr = host.parse().map_err(|_| ApiError::InvalidWirePayload)?; + if addr.ip().is_loopback() { + Ok(addr) + } else { + Err(ApiError::AuthorizationDenied) + } +} + +/// Render a typed export-cancel exchange as HTTP/1.1 for a loopback listener. +/// +/// # Errors +/// +/// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host or a +/// credential-bearing header, and [`ApiError::InvalidWirePayload`] when the +/// exchange is not a POST `/v1/exports/{export_id}/cancel` with an empty body. +pub fn loopback_http1_from_export_cancel_exchange( + exchange: &NaruonHttpExchange, + loopback_host: &str, +) -> Result { + let _addr = require_loopback_host(loopback_host)?; + let host = loopback_host.trim(); + if exchange.method != "POST" { + return Err(ApiError::InvalidWirePayload); + } + if !exchange.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + let rest = exchange + .target_url + .strip_prefix("https://") + .ok_or(ApiError::InvalidWirePayload)?; + let path = rest + .find('/') + .map(|index| &rest[index..]) + .ok_or(ApiError::InvalidWirePayload)?; + export_cancel_path_id(path)?; + for (name, _) in &exchange.headers { + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + if name.eq_ignore_ascii_case("idempotency-key") { + return Err(ApiError::InvalidWirePayload); + } + } + let mut request = String::new(); + write!( + request, + "{} {path} HTTP/1.1\r\nHost: {host}\r\n", + exchange.method + ) + .map_err(|_| ApiError::InvalidWirePayload)?; + for (name, value) in &exchange.headers { + if name.eq_ignore_ascii_case("host") || name.eq_ignore_ascii_case("content-length") { + continue; + } + write!(request, "{name}: {value}\r\n").map_err(|_| ApiError::InvalidWirePayload)?; + } + write!(request, "content-length: 0\r\n\r\n").map_err(|_| ApiError::InvalidWirePayload)?; + Ok(request) +} + +/// Compose one HTTP/1.1 cancel POST from the typed naruon exchange. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`ExportCancelCliInvocation::validate`]. +pub fn compose_export_cancel_cli_http( + invocation: &ExportCancelCliInvocation, +) -> Result { + invocation.validate()?; + let exchange = naruon_export_cancel_exchange(&invocation.origin, &invocation.export_id)?; + loopback_http1_from_export_cancel_exchange(&exchange, &invocation.host) +} + +/// Dispatch one cancel CLI invocation against an in-process listener. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_export_cancel_cli( + service: &mut AnalysisRunLiveService, + invocation: &ExportCancelCliInvocation, +) -> Result { + let request = compose_export_cancel_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one cancel CLI invocation over loopback TCP. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_export_cancel_cli( + invocation: &ExportCancelCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_export_cancel_cli_http(invocation)?; + let mut stream = TcpStream::connect(addr).map_err(|error| map_io_error(&error))?; + stream + .set_read_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .set_write_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .write_all(request.as_bytes()) + .map_err(|error| map_io_error(&error))?; + stream.flush().map_err(|error| map_io_error(&error))?; + let mut bytes = Vec::new(); + stream + .read_to_end(&mut bytes) + .map_err(|error| map_io_error(&error))?; + parse_http_response(&bytes) +} + +/// Filter CLI stdout so cancel never prints scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a receipt carries metric keys, +/// `tepp.scientific_acceptance.v1`, or a success body that is not a metric-free +/// cancelled identity. +pub fn render_export_cancel_cli_stdout( + invocation: &ExportCancelCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance_schema(&response.body)?; + refuse_metrics_on_export_retrieval_payload(&response.body)?; + if response.status_code != 200 { + return Err(ApiError::InvalidWirePayload); + } + let parsed = ExportCancelled::from_json(&response.body)?; + if !parsed.cancelled { + return Err(ApiError::InvalidWirePayload); + } + parsed.to_json() +} + +fn refuse_scientific_acceptance_schema(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +fn parse_http_response(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes).map_err(|_| ApiError::InvalidWirePayload)?; + let (header_block, body) = text + .split_once("\r\n\r\n") + .ok_or(ApiError::InvalidWirePayload)?; + let mut lines = header_block.split("\r\n"); + let status_line = lines.next().ok_or(ApiError::InvalidWirePayload)?; + let mut parts = status_line.split(' '); + if parts.next() != Some("HTTP/1.1") { + return Err(ApiError::InvalidWirePayload); + } + let code = parts + .next() + .ok_or(ApiError::InvalidWirePayload)? + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?; + let reason_phrase = match code { + 200 => "OK", + 202 => "Accepted", + 400 => "Bad Request", + 403 => "Forbidden", + 413 => "Payload Too Large", + 422 => "Unprocessable Entity", + _ => return Err(ApiError::InvalidWirePayload), + }; + let mut content_length = None; + for line in lines { + let (name, value) = line.split_once(':').ok_or(ApiError::InvalidWirePayload)?; + if name.eq_ignore_ascii_case("content-length") { + if content_length.is_some() { + return Err(ApiError::InvalidWirePayload); + } + content_length = Some( + value + .trim() + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?, + ); + } + } + let declared = content_length.ok_or(ApiError::InvalidWirePayload)?; + if declared != body.len() { + return Err(ApiError::InvalidWirePayload); + } + Ok(NaruonLiveResponse { + status_code: code, + reason_phrase, + body: body.to_owned(), + }) +} + +/// Read stdin leftover bytes on a non-terminal; cancel POST admits empty. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_export_cancel_cli_stdin( + stdin_is_terminal: bool, + mut stdin: impl Read, +) -> Result { + if stdin_is_terminal { + Ok(String::new()) + } else { + let mut body = String::new(); + stdin + .read_to_string(&mut body) + .map_err(|_| ApiError::InvalidWirePayload)?; + Ok(body) + } +} + +#[cfg(test)] +mod tests { + use super::{ + compose_export_cancel_cli_http, loopback_http1_from_export_cancel_exchange, + read_export_cancel_cli_stdin, ExportCancelCliInvocation, ExportCancelCliVerb, + }; + use crate::{naruon_export_cancel_exchange, ApiError, NARUON_CONSUMER_CODE, NaruonHttpExchange}; + + const ORIGIN: &str = "https://tepp.example.test"; + + fn cancel_args() -> [&'static str; 9] { + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + NARUON_CONSUMER_CODE, + "--export-id", + "export-1", + ] + } + + #[test] + fn from_args_mints_cancel_and_refuses_fail_closed_inputs() { + assert_eq!( + ExportCancelCliVerb::parse("cancel").expect("cancel"), + ExportCancelCliVerb::Cancel + ); + assert_eq!(ExportCancelCliVerb::Cancel.as_str(), "cancel"); + assert_eq!( + ExportCancelCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + let cancel = ExportCancelCliInvocation::from_args(cancel_args(), "").expect("cancel"); + assert_eq!(cancel.verb, ExportCancelCliVerb::Cancel); + let http = compose_export_cancel_cli_http(&cancel).expect("http"); + assert!(http.starts_with("POST /v1/exports/export-1/cancel HTTP/1.1")); + assert!(http.contains("tepp-consumer: naruon")); + assert!(http.contains("content-length: 0")); + assert!(!http.contains("idempotency-key:")); + assert!(!http.contains("authorization")); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "8.8.8.8:80", + "--origin", + ORIGIN, + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "localhost:18081", + "--origin", + ORIGIN, + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + "http://tepp.example.test", + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--export-id", + "export-1", + "--authorization", + "secret" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + } + + #[test] + fn from_args_refuses_unpublished_body_slash_and_non_post() { + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + "lineageweave", + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportCancelCliInvocation::from_args(cancel_args(), "{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--export-id", + "a/b" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--idempotency-key", + "k" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let leftover = read_export_cancel_cli_stdin(false, std::io::Cursor::new(b"leftover")) + .expect("leftover"); + assert_eq!(leftover, "leftover"); + assert!(read_export_cancel_cli_stdin(true, std::io::empty()) + .expect("tty") + .is_empty()); + let exchange = naruon_export_cancel_exchange(ORIGIN, "export-1").expect("exchange"); + let gotten = NaruonHttpExchange { + method: "GET", + target_url: exchange.target_url, + headers: exchange.headers, + body: exchange.body, + }; + assert_eq!( + loopback_http1_from_export_cancel_exchange(&gotten, "127.0.0.1:18081").unwrap_err(), + ApiError::InvalidWirePayload + ); + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index b3459f3fa..6e159f4a4 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -20,6 +20,7 @@ mod corpus_split_manifest; mod envelope; mod error; mod export; +mod export_cancel_cli; mod export_cancel_http; mod export_collection_http; mod export_http; @@ -132,6 +133,22 @@ pub use export_cancel_http::EXPORT_CANCEL_ID_MAX_LEN; pub use export_cancel_http::export_cancel_path_id; /// Build a credential-free naruon cancel POST exchange. pub use export_cancel_http::naruon_export_cancel_exchange; +/// Supported operator verbs for the loopback export-cancel CLI. +pub use export_cancel_cli::ExportCancelCliVerb; +/// One operator CLI invocation against a loopback export-cancel POST listener. +pub use export_cancel_cli::ExportCancelCliInvocation; +/// Compose one HTTP/1.1 cancel POST from the typed naruon exchange. +pub use export_cancel_cli::compose_export_cancel_cli_http; +/// Dispatch one cancel CLI invocation against an in-process listener. +pub use export_cancel_cli::dispatch_export_cancel_cli; +/// Execute one cancel CLI invocation over loopback TCP. +pub use export_cancel_cli::execute_export_cancel_cli; +/// Render a typed export-cancel exchange as HTTP/1.1 for a loopback listener. +pub use export_cancel_cli::loopback_http1_from_export_cancel_exchange; +/// Read stdin leftover bytes on a non-terminal; cancel POST admits empty. +pub use export_cancel_cli::read_export_cancel_cli_stdin; +/// Filter CLI stdout so cancel never prints scientific acceptance. +pub use export_cancel_cli::render_export_cancel_cli_stdout; /// Refuse scientific-metric keys on export-retrieval JSON. pub use export_http::refuse_metrics_on_export_retrieval_payload; diff --git a/crates/tepp_api/tests/export_cancel_cli_contract.rs b/crates/tepp_api/tests/export_cancel_cli_contract.rs new file mode 100644 index 000000000..316b905e1 --- /dev/null +++ b/crates/tepp_api/tests/export_cancel_cli_contract.rs @@ -0,0 +1,120 @@ +//! Contract tests for `tepp-export-cancel cancel`. + +use tepp_api::{ + compose_export_cancel_cli_http, dispatch_export_cancel_cli, execute_export_cancel_cli, + render_export_cancel_cli_stdout, AnalysisRunLiveService, AnalyticalPurpose, ApiError, + ExportAuthorizationRequest, ExportCancelCliInvocation, ExportCancelled, NARUON_CONSUMER_CODE, + NARUON_EXPORT_PATH, NaruonLiveResponse, +}; + +const ORIGIN: &str = "https://tepp.example.test"; + +fn authorize_body() -> String { + let request = ExportAuthorizationRequest { + tenant_workspace_id: "export-cancel-cli-tenant".into(), + principal_id: "principal-analyst-1".into(), + purpose: AnalyticalPurpose::ModularServiceConsumer, + artifact_id: "artifact-cancel-cli-1".into(), + includes_source_text: false, + }; + serde_json::to_string(&request).expect("json") +} + +fn authorize_http(idem: &str) -> String { + let body = authorize_body(); + format!( + "POST {NARUON_EXPORT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {NARUON_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\nidempotency-key: {idem}\r\ncontent-length: {}\r\n\r\n{body}", + body.len() + ) +} + +fn cancel_invocation(export_id: &str) -> ExportCancelCliInvocation { + ExportCancelCliInvocation::from_args( + [ + "cancel", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + NARUON_CONSUMER_CODE, + "--export-id", + export_id, + ], + "", + ) + .expect("cancel") +} + +#[test] +fn dispatch_cancels_one_metric_free_identity() { + let mut service = AnalysisRunLiveService::new(); + let posted = service.handle_http_request(&authorize_http("export-cancel-cli-1")); + assert_eq!(posted.status_code, 200, "{}", posted.body); + let retrieval: serde_json::Value = serde_json::from_str(&posted.body).expect("posted"); + let export_id = retrieval["export_id"].as_str().expect("id"); + let cancelled = + dispatch_export_cancel_cli(&mut service, &cancel_invocation(export_id)).expect("cancel"); + assert_eq!(cancelled.status_code, 200, "{}", cancelled.body); + let stdout = + render_export_cancel_cli_stdout(&cancel_invocation(export_id), &cancelled).expect("out"); + assert!(!stdout.contains("tepp.scientific_acceptance.v1")); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("tenant_workspace_id")); + assert!(!stdout.contains("principal_id")); + let parsed = ExportCancelled::from_json(&stdout).expect("parsed"); + assert!(parsed.cancelled); + assert_eq!(parsed.export_id, export_id); +} + +#[test] +fn render_refuses_metrics_schema_and_empty_bodies() { + let cancel = cancel_invocation("export-1"); + assert_eq!( + render_export_cancel_cli_stdout( + &cancel, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_export_cancel_cli_stdout( + &cancel, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"export_id":"e","artifact_id":"a","decision_code":"purpose_bound_export_allowed","purpose":"modular_service_consumer","idempotency_key":"k","cancelled":true,"rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let http = compose_export_cancel_cli_http(&cancel).expect("http"); + assert!(http.starts_with("POST /v1/exports/export-1/cancel HTTP/1.1")); +} + +#[test] +fn execute_over_tcp_cancels_authorized_export() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let posted = service.handle_http_request(&authorize_http("export-cancel-tcp-1")); + assert_eq!(posted.status_code, 200, "{}", posted.body); + let retrieval: serde_json::Value = serde_json::from_str(&posted.body).expect("posted"); + let export_id = retrieval["export_id"].as_str().expect("id").to_owned(); + let addr = service.local_addr().expect("addr"); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let mut invocation = cancel_invocation(&export_id); + invocation.host = addr.to_string(); + let response = execute_export_cancel_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 200, "{}", response.body); + let stdout = render_export_cancel_cli_stdout(&invocation, &response).expect("out"); + let parsed = ExportCancelled::from_json(&stdout).expect("parsed"); + assert!(parsed.cancelled); + handle.join().expect("join"); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index a61c96986..607488529 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -8,7 +8,7 @@ TEPP must work both as a standalone product and as a modular CWL component. Integrations with `naruon`, `contextual-orchestrator`, `.github`, or other repositories use explicit versioned API/artifact contracts. Cross-service direct table access is prohibited. -Current protected main exposes Rust library/domain contracts. The active stack adds a loopback HTTP/1.1 listener for naruon analysis-run, LineageWeave temporal-context, and export POSTs, including `POST /v1/project-histories` on the `AnalysisRunLiveService` contract boundary. `tepp-loopback` runs the shared consumer listener on `127.0.0.1:18081` by default; a caller may pass another loopback socket address and an optional maximum request count as its two arguments. The container is intended for a trusted same-host or shared-network-namespace sidecar, checks readiness through a synthetic bounded temporal-context request, and deliberately cannot bind a public or bridge address. It is not a production TLS/`$PORT` service. Endpoint examples below that are not covered by `NaruonLiveService` or `AnalysisRunLiveService` remain target interface shapes. Loopback `GET /v1/exports/{export_id}` on `AnalysisRunLiveService` is the executable export-retrieval route (ADR 0054); `GET /v1/exports` enumerates those identities (ADR 0075); `POST /v1/exports/{export_id}/cancel` removes one identity (ADR 0077); `NaruonLiveService` stays POST-only. +Current protected main exposes Rust library/domain contracts. The active stack adds a loopback HTTP/1.1 listener for naruon analysis-run, LineageWeave temporal-context, and export POSTs, including `POST /v1/project-histories` on the `AnalysisRunLiveService` contract boundary. `tepp-loopback` runs the shared consumer listener on `127.0.0.1:18081` by default; a caller may pass another loopback socket address and an optional maximum request count as its two arguments. The container is intended for a trusted same-host or shared-network-namespace sidecar, checks readiness through a synthetic bounded temporal-context request, and deliberately cannot bind a public or bridge address. It is not a production TLS/`$PORT` service. Endpoint examples below that are not covered by `NaruonLiveService` or `AnalysisRunLiveService` remain target interface shapes. Loopback `GET /v1/exports/{export_id}` on `AnalysisRunLiveService` is the executable export-retrieval route (ADR 0054); `GET /v1/exports` enumerates those identities (ADR 0075); `POST /v1/exports/{export_id}/cancel` removes one identity (ADR 0077); published `tepp-export-cancel cancel` mints that cancel POST onto spawned `tepp-loopback` TCP (ADR 0078); `NaruonLiveService` stays POST-only. ## 2. Contract families diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index fc8c06c6c..c31d689e4 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -52,7 +52,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | recovery metrics (RMSE, bias, coverage, graph, temporal order, Monte Carlo SE gates) | PRD; Test Strategy; ADR 0007/0014 | `validation_core` on protected main (PR #19); SE-aware Monte Carlo gates included | implemented-main | | PostgreSQL bitemporal/lineage persistence | ADR 0013; Architecture/ERD | `persistence_postgres` migration contracts, in-memory adapters, live SQL session/document SQL port, tenant RLS (`0002` + session GUC/role helpers), `DATABASE_URL` SQLx gate, optional session-affine `live-sqlx` `PgPool` driver, exact-head live PostgreSQL CI with isolation proof, append-only immutability triggers (`0004`), temporal interval ordering CHECKs (`0005`), typed membership assignment (`0006` implemented-main), event-relation/mention/instance SQL (#37–#39 implemented-main), source-artifact SQL (#40 implemented-main), audit-event SQL (#41 implemented-main), concurrent document-write stress (#43 implemented-main), backup/restore integrity revalidation (#44 implemented-main), `revision_order` later-revision system-time ordering implemented-main, entity/project target SQL on PR #131; remaining physical ERD constraints | partial | | known-truth temporal/event simulation manifests | PRD; TRD; Test Strategy | `tepp_simulation` on protected main; recovery metrics in `validation_core` | implemented-main | -| versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013/0054/0075/0077 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); loopback `GET /v1/exports/{export_id}` is the executable retrieval route; loopback `GET /v1/exports` enumerates authorized identities; `POST /v1/exports/{export_id}/cancel` removes one identity on this PR; request-bound terminal result active in PR #157; production TLS remaining | partial | +| versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013/0054/0075/0077/0078 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); loopback `GET /v1/exports/{export_id}` is the executable retrieval route; loopback `GET /v1/exports` enumerates authorized identities; `POST /v1/exports/{export_id}/cancel` removes one identity; `tepp-export-cancel cancel` mints that cancel POST onto spawned `tepp-loopback` TCP on this PR; request-bound terminal result active in PR #157; production TLS remaining | partial | | executable cutoff-safe analysis-run readiness | ADR 0021; temporal research; API terminal-result contract | stacked `analysis_engine` PR on #157: availability cutoff, snapshot binding, multiple-membership aggregation, digest-bound artifact, realistic end-to-end tests | active-PR | | delayed-reporting cutoff eligibility in truth corpora | ADR 0002; research | `tepp_simulation` eligible-at-cutoff filter on the active PR | active-PR | | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); HTTP service remaining accepted-target | partial | diff --git a/docs/adr/0078-export-cancel-cli.md b/docs/adr/0078-export-cancel-cli.md new file mode 100644 index 000000000..2639c9975 --- /dev/null +++ b/docs/adr/0078-export-cancel-cli.md @@ -0,0 +1,103 @@ +# ADR 0078 — Loopback export cancel CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-09-01 +**Supersedes:** None; complements ADR 0077 for operator-visible cancel POST. +Does not supersede ADR 0014 claim-promotion authority. This ADR number is +unique versus protected main; live vs-main and sibling GAP-003A PRs already +occupy 0026–0077. + +## Context + +ADR 0077 removes an authorized export identity on +`AnalysisRunLiveService`. Operators still had no published binary that mints +that POST onto spawned `tepp-loopback` TCP. Duplicating export cancel HTTP +(#445), export collection CLI (#444), export collection GET (#443), +export-retrieval CLI (#417), export retrieval GET (#411), export-authorize +CLI (#410), interpretation-run cancel CLI (#442), interpretation-run cancel +HTTP (#440), analysis-run cancel (#361), Leiden, Driver p.16, or GAP-010 +Figma/export would collide with live PRs. LineageWeave is refused on this +naruon-owned adapter; `NaruonLiveService` stays POST-only. + +## Decision + +Publish `tepp-export-cancel cancel`: + +- Pattern: `from_args` + typed `naruon_export_cancel_exchange` + + `loopback_http1_from_export_cancel_exchange` + + `dispatch`/`execute`/`render` + published `[[bin]]`. +- Empty stdin is admitted. Nonempty leftover stdin fails closed. +- Public bind, `localhost` host, `http` origin, unpublished consumer, and + credential flags fail closed. +- Stdout is one metric-free cancelled identity with `cancelled=true`. + Tenant, principal, source text, RMSE, bias, coverage, SE-gate, and + `tepp.scientific_acceptance.v1` never appear. +- Dedicated binary so it does not collide with `tepp-export-list` (#444) or + `tepp-export-get` (#417). + +## Alternatives considered + +1. **Reuse `tepp-export-list list`** — rejected; that CLI is collection GET. +2. **Reuse `tepp-export-get get`** — rejected; that CLI is GET-by-id (#417). +3. **Add GET to `NaruonLiveService`** — rejected; POST-only. +4. **Published `tepp-export-cancel cancel`** — accepted. + +## Consequences + +- Operators can retract an authorized export identity without a second + cancel HTTP PR. +- Cancel JSON cannot be mistaken for a succeeded scientific-acceptance + result or a causal score. +- Cancel success is not release evidence and is not an ADR 0014 claim. + +## Failure and recovery + +Non-`naruon` consumers, nonempty leftover stdin, present `idempotency-key`, +slash/NUL identities, credential flags, public bind, and metric keys fail +closed. TCP execute does not fall back to an empty in-process listener. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Tenant, principal, and source text stay off the cancel receipt. +- HTTP 200 on cancel is not measurement evidence and is not a causal claim. + +## Compatibility and migration + +Cancel HTTP, collection GET, GET-by-id, POST `/v1/exports`, and +`NaruonLiveService` POST-only remain unchanged. Persistence remains +GAP-003B. + +## Verification + +Falsifiable evidence: + +- `tepp-export-cancel cancel` of an authorized export returns metric-free + `cancelled=true` without RMSE/bias/coverage/SE-gate/tenant/principal/ + source-text/`tepp.scientific_acceptance.v1` keys; +- LineageWeave, nonempty leftover stdin, present `idempotency-key`, slash/NUL + identities, public bind, `localhost`, `http` origin, and unknown keys fail + closed; +- `NaruonLiveService` still refuses GET; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review + remain required. + +## Rollback and supersession + +Rollback removes the published binary; cancel HTTP remains valid. A +superseding ADR is required to persist cancel, bind a public address, emit +scientific-acceptance on cancel, open LineageWeave, add GET to +`NaruonLiveService`, or treat cancel success as an ADR 0014 claim. + +## Related authority + +- ADR 0077 owns loopback export cancel HTTP. +- ADR 0076 owns the export collection CLI (live #444). +- ADR 0075 owns loopback export collection GET. +- ADR 0054 owns loopback export retrieval GET. +- ADR 0029 owns analysis-run cancel HTTP (live #361). +- ADR 0074 owns interpretation-run cancel CLI (live #442). +- ADR 0014 owns scientific claim promotion. +- RFC 9110 owns POST semantics (Fielding, Nottingham, & Reschke, 2022). It + does not authorize scientific claims. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2e6a6dbf8..5184e861d 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -33,6 +33,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0054](0054-export-retrieval-get.md) | Loopback export retrieval GET | Accepted | active-PR | `AnalysisRunLiveService` mints a metric-free `export_id` on naruon `POST /v1/exports` and serves `GET /v1/exports/{export_id}`; `NaruonLiveService` stays POST-only. | | [0075](0075-export-collection-get.md) | Loopback export collection GET | Accepted | active-PR | Complements ADR 0054; `GET /v1/exports` enumerates metric-free authorized identities. Unique versus protected main (0026–0074 occupied). `NaruonLiveService` stays POST-only. | | [0077](0077-export-cancel-http.md) | Loopback export cancel HTTP | Accepted | active-PR | Complements ADR 0075/0054; `POST /v1/exports/{export_id}/cancel` removes one metric-free identity. Unique versus protected main (0026–0076 occupied). `NaruonLiveService` stays POST-only. | +| [0078](0078-export-cancel-cli.md) | Loopback export cancel CLI | Accepted | active-PR | Complements ADR 0077; published `tepp-export-cancel cancel` mints naruon `POST /v1/exports/{export_id}/cancel` onto spawned `tepp-loopback` TCP. Unique versus protected main (0026–0077 occupied). | | [0023](0023-lineage-criterion-anchor-contract.md) | TEPP-owned Event Lineage criterion anchor | Accepted | active-PR | PR #237 publishes the strict accepted/rejected artifact and identities; estimator execution remains fail-closed future work. | | [0024](0024-independent-topic-importance-anchor.md) | Posterior topic-context producer contract | Accepted | contract-only active-PR | Strict DTO/schema only; the current estimator does not emit it. fast-mlsirm owns case-deletion influence. | | [0001](0001-rust-first-modular-msa.md) | Rust-first numerical core and CPU `f64` reference | Accepted | partial | ADR 0011 owns cross-service/MSA authority; 0001 retains numerical/backend authority. | diff --git a/docs/connectors/naruon-artifact-consumer.md b/docs/connectors/naruon-artifact-consumer.md index 5665eb86f..67ad1de80 100644 --- a/docs/connectors/naruon-artifact-consumer.md +++ b/docs/connectors/naruon-artifact-consumer.md @@ -31,6 +31,7 @@ TEPP remains the scientific authority for estimation, recovery metrics, temporal | Live loopback export retrieval | `tepp_api` `AnalysisRunLiveService` → `POST /v1/exports` then `GET /v1/exports/{export_id}` | naruon → TEPP | | Live loopback export collection | `tepp_api` `AnalysisRunLiveService` → `GET /v1/exports` | naruon → TEPP | | Live loopback export cancel | `tepp_api` `AnalysisRunLiveService` → `POST /v1/exports/{export_id}/cancel` | naruon → TEPP | +| Live loopback export cancel CLI | `tepp-export-cancel cancel` → spawned `tepp-loopback` TCP `POST /v1/exports/{export_id}/cancel` | naruon → TEPP | Committed examples live under `examples/`. Schemas for analysis-run requests and corpus-split manifests live under `schemas/`. diff --git a/docs/research/export-cancel-cli.md b/docs/research/export-cancel-cli.md new file mode 100644 index 000000000..4a2a7f9b1 --- /dev/null +++ b/docs/research/export-cancel-cli.md @@ -0,0 +1,55 @@ +# Export cancel CLI (doctoring) + +## Scope + +`tepp-export-cancel cancel` is the operator-visible loopback CLI that mints a +typed naruon `POST /v1/exports/{export_id}/cancel` onto spawned +`tepp-loopback` TCP. HTTP method, path, and header semantics follow current +HTTP semantics (Fielding, Nottingham, & Reschke, 2022). Fail-closed refusal +of unpublished consumers, nonempty leftover stdin, present +`idempotency-key`, slash/NUL identities, review/Copilot/GitHub credential +flags, public bind, `localhost`, `http` origin, and scientific-authority +promotion is repository contract authority (ADR 0078; ADR 0077; ADR 0014), +not an RFC inference rule. + +Stdout is metric-free with `cancelled=true`. Tenant, principal, source text, +and `tepp.scientific_acceptance.v1` never appear. HTTP 200 is not a +completed psychometric result, calibrated score, theta estimate, uncertainty +statement, causal inference, or scientific claim. + +## Authority + +### External standards (HTTP only) + +Fielding, R., Nottingham, M., & Reschke, J. (Eds.). (2022). *HTTP semantics* +(RFC 9110). IETF. https://doi.org/10.17487/RFC9110 + +RFC 9110 §9.3.3 describes POST as a method for processing according to the +resource's own semantics. TEPP maps that processing onto in-memory removal of +one metric-free export identity. The RFC does not define psychometric +acceptance, RMSE, causality, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0078-export-cancel-cli.md` — this CLI +- `docs/adr/0077-export-cancel-http.md` — cancel HTTP +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — HTTP + 200 is not a scientific claim +- `crates/tepp_api/tests/export_cancel_cli_contract.rs` — fail-closed CLI + proofs + +## Verification + +- `tepp-export-cancel cancel` of an authorized naruon export returns + metric-free `cancelled=true` without RMSE/bias/coverage/SE-gate keys, + tenant, principal, source text, or `tepp.scientific_acceptance.v1`; +- LineageWeave, nonempty leftover stdin, present `idempotency-key`, slash/NUL + identities, public bind, `localhost`, and `http` origin fail closed; +- `NaruonLiveService` still refuses GET. + +## Non-claims + +This slice does not implement GAP-010 Figma/export, analysis-run cancel CLI, +interpretation-run cancel CLI, persistence, production TLS, Leiden +consensus, provider execution, causal inference, or an ADR 0014 scientific +claim-promotion package.