diff --git a/CHANGELOG.d/export-stored-request-cli.md b/CHANGELOG.d/export-stored-request-cli.md new file mode 100644 index 000000000..0f13ba87b --- /dev/null +++ b/CHANGELOG.d/export-stored-request-cli.md @@ -0,0 +1 @@ +- `tepp-export-request get` mints naruon stored-request GET onto spawned `tepp-loopback` TCP (ADR 0090). Metric-free. LineageWeave refused. `NaruonLiveService` stays POST-only. Does not re-open cancel lineages. Not GAP-010 Figma/export, not persistence. diff --git a/CHANGELOG.d/export-stored-request-get.md b/CHANGELOG.d/export-stored-request-get.md new file mode 100644 index 000000000..a9d818b53 --- /dev/null +++ b/CHANGELOG.d/export-stored-request-get.md @@ -0,0 +1 @@ +- `GET /v1/exports/{export_id}/request` returns the accepted naruon export-authorization request on `tepp-loopback` (ADR 0089). Metric-free. LineageWeave refused. `NaruonLiveService` stays POST-only. Does not re-open cancel lineages. Not GAP-010 Figma/export, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6fa4b9683..dc40ebde7 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -11,6 +11,8 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Architecture | [`ARCHITECTURE.md`](ARCHITECTURE.md) | | Modular/API integration contract | [`docs/API_CONTRACT.md`](docs/API_CONTRACT.md) | | naruon modular consumer contract | [`docs/connectors/naruon-artifact-consumer.md`](docs/connectors/naruon-artifact-consumer.md) | +| Export stored-request GET doctoring | [`docs/research/export-stored-request-get.md`](docs/research/export-stored-request-get.md) | +| Export stored-request CLI doctoring | [`docs/research/export-stored-request-cli.md`](docs/research/export-stored-request-cli.md) | | contextual-orchestrator interpretation port | [`docs/connectors/contextual-orchestrator-interpretation-port.md`](docs/connectors/contextual-orchestrator-interpretation-port.md) | | Orchestrator live HTTP doctoring | [`docs/research/orchestrator-live-http.md`](docs/research/orchestrator-live-http.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | @@ -109,6 +111,8 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Architecture | [`ARCHITECTURE.md`](ARCHITECTURE.md) | | Modular/API integration contract | [`docs/API_CONTRACT.md`](docs/API_CONTRACT.md) | | naruon modular consumer contract | [`docs/connectors/naruon-artifact-consumer.md`](docs/connectors/naruon-artifact-consumer.md) | +| Export stored-request GET doctoring | [`docs/research/export-stored-request-get.md`](docs/research/export-stored-request-get.md) | +| Export stored-request CLI doctoring | [`docs/research/export-stored-request-cli.md`](docs/research/export-stored-request-cli.md) | | contextual-orchestrator interpretation port | [`docs/connectors/contextual-orchestrator-interpretation-port.md`](docs/connectors/contextual-orchestrator-interpretation-port.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | diff --git a/crates/tepp_api/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c433..0dc52e700 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-request" +path = "src/bin/tepp_export_request.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/analysis_run_live.rs b/crates/tepp_api/src/analysis_run_live.rs index a5f1f9f93..17e5972cc 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -3,7 +3,8 @@ //! This module keeps the Naruon compatibility listener intact while providing //! the shared `/v1/analysis-runs` and cutoff-safe `/v1/temporal-context` //! boundaries needed by Naruon and `LineageWeave`. Naruon may also POST and -//! GET `/v1/exports/{export_id}` for metric-free purpose-bound retrieval. +//! GET `/v1/exports/{export_id}` for metric-free purpose-bound retrieval, and +//! GET `/v1/exports/{export_id}/request` for the stored authorization request. //! It accepts transport acknowledgements, temporal evidence context, and //! export identities only; completed psychometric results remain outside this //! crate. @@ -13,8 +14,11 @@ use std::io::Write; use std::net::{SocketAddr, TcpListener}; use crate::export_http::{export_retrieval_path_id, refuse_metrics_on_export_retrieval_payload}; +use crate::export_stored_request_http::{ + export_stored_request_path_id, refuse_metrics_on_export_stored_request_payload, +}; use crate::lineageweave_http::{ - LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, consumer_is_supported, + consumer_is_supported, LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, }; use crate::live_http::{ header_value, map_io_error, parse_headers, parse_request_line, read_http_request_with_limit, @@ -22,12 +26,12 @@ use crate::live_http::{ }; use crate::naruon_http::{NARUON_ANALYSIS_RUN_PATH, NARUON_EXPORT_PATH}; use crate::{ - AnalysisRunAccepted, AnalysisRunRequest, AnalyticalPurpose, ApiError, - DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, ErrorEnvelope, ExportAuthorizationRequest, ExportRetrieval, - NARUON_LIVE_IO_TIMEOUT, NaruonLiveResponse, PROJECT_HISTORY_PATH, ProjectHistoryProjection, - ProjectHistoryRequest, TEMPORAL_CONTEXT_PATH, TemporalContextRequest, authorize_export, - build_temporal_context, project_history_projection, requests_are_idempotent_matches, - require_export_allowed, + authorize_export, build_temporal_context, project_history_projection, + requests_are_idempotent_matches, require_export_allowed, AnalysisRunAccepted, + AnalysisRunRequest, AnalyticalPurpose, ApiError, ErrorEnvelope, ExportAuthorizationRequest, + ExportRetrieval, NaruonLiveResponse, ProjectHistoryProjection, ProjectHistoryRequest, + TemporalContextRequest, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, NARUON_LIVE_IO_TIMEOUT, + PROJECT_HISTORY_PATH, TEMPORAL_CONTEXT_PATH, }; const MAX_LIVE_REQUEST_BODY_BYTES: usize = DEFAULT_PROJECT_HISTORY_BYTE_LIMIT; @@ -162,6 +166,12 @@ impl AnalysisRunLiveService { let (method, path) = parse_request_line(lines.next().unwrap_or(""))?; let headers = parse_headers(&mut lines)?; if method == "GET" { + if matches!( + export_stored_request_path_id(path), + Ok(_) | Err(ApiError::LimitExceeded) + ) { + return self.get_export_stored_request(path, &headers, body); + } if matches!( export_retrieval_path_id(path), Ok(_) | Err(ApiError::LimitExceeded) @@ -342,6 +352,35 @@ impl AnalysisRunLiveService { Ok(json_response(200, "OK", response_body)) } + fn get_export_stored_request( + &self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + if !body.trim().is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_export_stored_request_payload(body)?; + let consumer = require_headers(headers, self.bound_addr, false)?; + if consumer != NARUON_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + let export_id = export_stored_request_path_id(path)?; + let replay_key = self + .exports_by_id + .get(&export_id) + .cloned() + .ok_or(ApiError::InvalidWirePayload)?; + let stored = self + .authorized_exports + .get(&replay_key) + .ok_or(ApiError::InvalidWirePayload)?; + let response_body = crate::wire::to_json(&stored.request)?; + refuse_metrics_on_export_stored_request_payload(&response_body)?; + Ok(json_response(200, "OK", response_body)) + } + fn response_from_error(&mut self, error: ApiError) -> NaruonLiveResponse { let request_id = format!("analysis-run-live-{}", self.next_request_serial); self.next_request_serial += 1; @@ -417,17 +456,16 @@ mod tests { use std::time::Duration; use super::{ - AnalysisRunLiveService, consumer_tenant_idempotency_key, declared_content_length, - error_envelope_json, host_implies_table_access, map_io_error, parse_headers, - require_headers, split_header_line, status_for, + consumer_tenant_idempotency_key, declared_content_length, error_envelope_json, + host_implies_table_access, map_io_error, parse_headers, require_headers, split_header_line, + status_for, AnalysisRunLiveService, }; use crate::live_http::{host_is_loopback, read_http_request, split_request}; use crate::{ - ANALYSIS_RUN_CONTRACT_VERSION, AnalysisRunRequest, ApiError, - DEFAULT_ANALYSIS_RUN_BYTE_LIMIT, ErrorEnvelope, LINEAGEWEAVE_CONSUMER_CODE, - NARUON_ANALYSIS_RUN_PATH, NARUON_CONSUMER_CODE, NARUON_EXPORT_PATH, - NARUON_LIVE_HEADER_BYTE_LIMIT, NARUON_LIVE_HEADER_COUNT_LIMIT, NARUON_LIVE_IO_TIMEOUT, - TEMPORAL_CONTEXT_PATH, + AnalysisRunRequest, ApiError, ErrorEnvelope, ANALYSIS_RUN_CONTRACT_VERSION, + DEFAULT_ANALYSIS_RUN_BYTE_LIMIT, LINEAGEWEAVE_CONSUMER_CODE, NARUON_ANALYSIS_RUN_PATH, + NARUON_CONSUMER_CODE, NARUON_EXPORT_PATH, NARUON_LIVE_HEADER_BYTE_LIMIT, + NARUON_LIVE_HEADER_COUNT_LIMIT, NARUON_LIVE_IO_TIMEOUT, TEMPORAL_CONTEXT_PATH, }; fn sample_run() -> AnalysisRunRequest { @@ -1220,6 +1258,73 @@ mod tests { ); } + #[test] + fn handler_returns_stored_export_authorization_request_and_fails_closed() { + use crate::ExportAuthorizationRequest; + + let request = ExportAuthorizationRequest { + tenant_workspace_id: "export-live-tenant".into(), + principal_id: "principal-analyst-1".into(), + purpose: crate::AnalyticalPurpose::ModularServiceConsumer, + artifact_id: "artifact-live-1".into(), + includes_source_text: false, + }; + let body = crate::wire::to_json(&request).expect("export json"); + let mut service = AnalysisRunLiveService::new(); + let posted = service.handle_http_request(&export_post_http( + &body, + NARUON_CONSUMER_CODE, + "export-idem-1", + )); + assert_eq!(posted.status_code, 200); + let retrieval = crate::ExportRetrieval::from_json(&posted.body).expect("posted retrieval"); + let got = service.handle_http_request(&format!( + "GET {NARUON_EXPORT_PATH}/{}/request 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\ncontent-length: 0\r\n\r\n", + retrieval.export_id + )); + assert_eq!(got.status_code, 200, "{}", got.body); + let stored: ExportAuthorizationRequest = crate::wire::from_json(&got.body).expect("stored"); + assert_eq!(stored, request); + assert!(!got.body.contains("rmse")); + assert!(!got.body.contains("tepp.scientific_acceptance.v1")); + assert!(!got.body.contains("scientific_acceptance")); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_EXPORT_PATH}/{}/request HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {LINEAGEWEAVE_CONSUMER_CODE}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n", + retrieval.export_id + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_EXPORT_PATH}/{}/cancel 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\ncontent-length: 0\r\n\r\n", + retrieval.export_id + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_EXPORT_PATH}/missing/request 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\ncontent-length: 0\r\n\r\n" + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_EXPORT_PATH}/{}/request 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\ncontent-length: 2\r\n\r\n{{}}", + retrieval.export_id + )) + .status_code, + 400 + ); + } + fn export_post_http(body: &str, consumer: &str, idempotency_key: &str) -> String { format!( "POST {NARUON_EXPORT_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {consumer}\r\ntepp-contract-version: 1\r\nidempotency-key: {idempotency_key}\r\ncontent-length: {}\r\n\r\n{body}", diff --git a/crates/tepp_api/src/bin/tepp_export_request.rs b/crates/tepp_api/src/bin/tepp_export_request.rs new file mode 100644 index 000000000..825d2f87c --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_export_request.rs @@ -0,0 +1,33 @@ +//! Operator CLI for loopback naruon export stored-request GET. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + ApiError, ExportStoredRequestCliInvocation, execute_export_stored_request_cli, + read_export_stored_request_cli_stdin, render_export_stored_request_cli_stdout, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("tepp-export-request: {error}"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result<(), ApiError> { + let args: Vec = std::env::args().skip(1).collect(); + let body = read_export_stored_request_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = ExportStoredRequestCliInvocation::from_args(&args, body)?; + let response = execute_export_stored_request_cli(&invocation)?; + let stdout = render_export_stored_request_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_stored_request_cli.rs b/crates/tepp_api/src/export_stored_request_cli.rs new file mode 100644 index 000000000..e577dc97f --- /dev/null +++ b/crates/tepp_api/src/export_stored_request_cli.rs @@ -0,0 +1,673 @@ +//! Operator loopback CLI for naruon export stored-request GET. +//! +//! GAP-003A unique slice: operators run `tepp-export-request get` to mint +//! `naruon_export_stored_request_exchange` onto spawned `tepp-loopback` TCP. +//! Stdout is the stored `ExportAuthorizationRequest`. +//! `tepp.scientific_acceptance.v1` never appears. The CLI does not infer +//! causality. `LineageWeave` is refused on this naruon-owned adapter. +//! `NaruonLiveService` stays POST-only. This module does not duplicate +//! stored-request GET (#457), GET-by-id HTTP (#411), retrieval CLI (#417), +//! collection GET/CLI (#443/#444), export-authorize CLI (#410), +//! project-history stored-request CLI (#456), interpretation-run +//! stored-request CLI (#454), cancel lineages (closed), Leiden, or GAP-010 +//! Figma/export. Persistence remains GAP-003B. + +use std::collections::HashSet; +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::{ + AnalysisRunLiveService, ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, ErrorEnvelope, + ExportAuthorizationRequest, NARUON_CONSUMER_CODE, NARUON_LIVE_HEADER_BYTE_LIMIT, + NARUON_LIVE_HEADER_COUNT_LIMIT, NARUON_LIVE_IO_TIMEOUT, NaruonHttpExchange, NaruonLiveResponse, + export_stored_request_path_id, naruon_export_stored_request_exchange, + refuse_metrics_on_export_stored_request_payload, +}; + +const MAXIMUM_HTTP_RESPONSE_BYTES: usize = + NARUON_LIVE_HEADER_BYTE_LIMIT + 4 + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT; + +/// Supported operator verbs for the loopback export stored-request CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ExportStoredRequestCliVerb { + /// `GET /v1/exports/{export_id}/request`. + Get, +} + +impl ExportStoredRequestCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "get" => Ok(Self::Get), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Get => "get", + } + } +} + +/// One operator CLI invocation against a loopback export stored-request listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ExportStoredRequestCliInvocation { + /// CLI verb to execute. + pub verb: ExportStoredRequestCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published HTTPS origin used to mint the typed stored-request exchange. + pub origin: String, + /// Published modular consumer. Stored-request GET admits `naruon` only. + pub consumer: String, + /// Opaque export identity minted by naruon export authorization. + pub export_id: String, + /// JSON body. Stored-request GET requires empty. + pub body: String, +} + +impl ExportStoredRequestCliInvocation { + /// Parse argv plus stdin body into a validated loopback stored-request invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, a non-`https` origin, an unpublished or `LineageWeave` + /// 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 = ExportStoredRequestCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile GET body. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`] for + /// empty, unpublished, `LineageWeave`, nonempty-body, or oversized 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() > crate::EXPORT_RETRIEVAL_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + if !self.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_export_stored_request_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: ExportStoredRequestCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = ExportStoredRequestCliInvocation { + 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 stored-request GET exchange as HTTP/1.1 for a loopback listener. +/// +/// The exchange keeps its HTTPS origin contract. Only the HTTP/1.1 `Host` is +/// the loopback bind address. Public bind hosts fail closed. GET-by-id, +/// collection, cancel extra-segments, and pagination headers fail closed. +/// +/// # Errors +/// +/// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host or a +/// credential-bearing header, and [`ApiError::InvalidWirePayload`] when the +/// exchange is not a GET `/v1/exports/{export_id}/request` with an empty body. +pub fn loopback_http1_from_export_stored_request_exchange( + exchange: &NaruonHttpExchange, + loopback_host: &str, +) -> Result { + let _addr = require_loopback_host(loopback_host)?; + let host = loopback_host.trim(); + if exchange.method != "GET" { + 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)?; + let _export_id = export_stored_request_path_id(path)?; + let mut seen = HashSet::with_capacity(exchange.headers.len()); + let mut has_content_type = false; + let mut has_consumer = false; + let mut has_contract = false; + for (name, value) in &exchange.headers { + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + if !valid_http_field_name(name) + || value.chars().any(char::is_control) + || !seen.insert(name.to_ascii_lowercase()) + { + return Err(ApiError::InvalidWirePayload); + } + let valid = match name.to_ascii_lowercase().as_str() { + "content-type" => { + has_content_type = true; + value == "application/json" + } + "tepp-consumer" => { + has_consumer = true; + value == NARUON_CONSUMER_CODE + } + "tepp-contract-version" => { + has_contract = true; + value == "1" + } + _ => false, + }; + if !valid { + return Err(ApiError::InvalidWirePayload); + } + } + if !has_content_type || !has_consumer || !has_contract { + 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 { + 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 stored-request GET from the typed naruon exchange. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`ExportStoredRequestCliInvocation::validate`]. +pub fn compose_export_stored_request_cli_http( + invocation: &ExportStoredRequestCliInvocation, +) -> Result { + invocation.validate()?; + let exchange = + naruon_export_stored_request_exchange(&invocation.origin, &invocation.export_id)?; + loopback_http1_from_export_stored_request_exchange(&exchange, &invocation.host) +} + +/// Dispatch one stored-request CLI invocation against an in-process listener. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_export_stored_request_cli( + service: &mut AnalysisRunLiveService, + invocation: &ExportStoredRequestCliInvocation, +) -> Result { + let request = compose_export_stored_request_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one stored-request CLI invocation over loopback TCP against `tepp-loopback`. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_export_stored_request_cli( + invocation: &ExportStoredRequestCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_export_stored_request_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 bytes = read_bounded(&mut stream, MAXIMUM_HTTP_RESPONSE_BYTES)?; + parse_http_response(&bytes) +} + +/// Filter CLI stdout so stored-request GET never prints scientific acceptance. +/// +/// Tenant, principal, and `includes_source_text` belong to the stored +/// authorization request and are admitted. RMSE, bias, coverage, SE-gate, and +/// causal-score keys fail closed. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a body carries metric keys, +/// `tepp.scientific_acceptance.v1`, or a success body that is not a stored +/// `ExportAuthorizationRequest`. +pub fn render_export_stored_request_cli_stdout( + invocation: &ExportStoredRequestCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_export_stored_request_payload(&response.body)?; + if !(200..300).contains(&response.status_code) { + let expected_code = match response.status_code { + 400 => "invalid_wire_payload", + 403 => "authorization_denied", + 413 => "limit_exceeded", + 422 => "unsupported_contract_version", + _ => return Err(ApiError::InvalidWirePayload), + }; + let envelope: ErrorEnvelope = + serde_json::from_str(&response.body).map_err(|_| ApiError::InvalidWirePayload)?; + if envelope.error_code() != expected_code { + return Err(ApiError::InvalidWirePayload); + } + return envelope.to_json(); + } + if response.status_code != 200 { + return Err(ApiError::InvalidWirePayload); + } + let stored: ExportAuthorizationRequest = crate::wire::from_json(&response.body)?; + crate::wire::to_json(&stored) +} + +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)?; + if header_block.len() > NARUON_LIVE_HEADER_BYTE_LIMIT { + return Err(ApiError::LimitExceeded); + } + let mut lines = header_block.split("\r\n"); + let status_line = lines.next().ok_or(ApiError::InvalidWirePayload)?; + let (version, status) = status_line + .split_once(' ') + .ok_or(ApiError::InvalidWirePayload)?; + if version != "HTTP/1.1" { + return Err(ApiError::InvalidWirePayload); + } + let (code, reason) = status.split_once(' ').ok_or(ApiError::InvalidWirePayload)?; + let code = code + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?; + let reason_phrase = static_reason(code)?; + if reason != reason_phrase { + return Err(ApiError::InvalidWirePayload); + } + let mut content_length = None; + let mut seen = HashSet::new(); + for (index, line) in lines.enumerate() { + if index >= NARUON_LIVE_HEADER_COUNT_LIMIT { + return Err(ApiError::LimitExceeded); + } + let (name, value) = line.split_once(':').ok_or(ApiError::InvalidWirePayload)?; + if !valid_http_field_name(name) + || value + .chars() + .any(|character| character.is_control() && character != '\t') + || !seen.insert(name.to_ascii_lowercase()) + || name.eq_ignore_ascii_case("transfer-encoding") + { + return Err(ApiError::InvalidWirePayload); + } + if name.eq_ignore_ascii_case("content-length") { + content_length = Some( + value + .trim() + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?, + ); + } + } + let declared = content_length.ok_or(ApiError::InvalidWirePayload)?; + if declared > DEFAULT_PROJECT_HISTORY_BYTE_LIMIT { + return Err(ApiError::LimitExceeded); + } + if declared != body.len() { + return Err(ApiError::InvalidWirePayload); + } + Ok(NaruonLiveResponse { + status_code: code, + reason_phrase, + body: body.to_owned(), + }) +} + +fn static_reason(code: u16) -> Result<&'static str, ApiError> { + match code { + 200 => Ok("OK"), + 202 => Ok("Accepted"), + 400 => Ok("Bad Request"), + 403 => Ok("Forbidden"), + 413 => Ok("Payload Too Large"), + 422 => Ok("Unprocessable Entity"), + _ => Err(ApiError::InvalidWirePayload), + } +} + +/// Read stdin leftover bytes on a non-terminal; stored-request GET admits empty. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read and +/// [`ApiError::LimitExceeded`] when leftover stdin exceeds the live wire +/// limit. +pub fn read_export_stored_request_cli_stdin( + stdin_is_terminal: bool, + mut stdin: impl Read, +) -> Result { + if stdin_is_terminal { + Ok(String::new()) + } else { + let bytes = read_bounded(&mut stdin, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT)?; + String::from_utf8(bytes).map_err(|_| ApiError::InvalidWirePayload) + } +} + +fn read_bounded(reader: &mut impl Read, maximum_bytes: usize) -> Result, ApiError> { + let mut bytes = Vec::new(); + reader + .take((maximum_bytes + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|error| map_io_error(&error))?; + if bytes.len() > maximum_bytes { + return Err(ApiError::LimitExceeded); + } + Ok(bytes) +} + +fn valid_http_field_name(name: &str) -> bool { + !name.is_empty() + && name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) + }) +} + +#[cfg(test)] +mod branch_coverage_tests { + use std::io::{self, Cursor, Read}; + + use super::{ + ExportStoredRequestCliInvocation, ExportStoredRequestCliVerb, + loopback_http1_from_export_stored_request_exchange, parse_http_response, + read_export_stored_request_cli_stdin, valid_http_field_name, + }; + use crate::{ + ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, NARUON_CONSUMER_CODE, + naruon_export_stored_request_exchange, + }; + + fn invocation() -> ExportStoredRequestCliInvocation { + ExportStoredRequestCliInvocation { + verb: ExportStoredRequestCliVerb::Get, + host: "127.0.0.1:18081".into(), + origin: "https://tepp.example.test".into(), + consumer: NARUON_CONSUMER_CODE.into(), + export_id: "export-1".into(), + body: String::new(), + } + } + + #[test] + fn invocation_and_flag_error_arms_are_covered() { + let mut value = invocation(); + value.origin = "http://tepp.example.test".into(); + assert_eq!(value.validate(), Err(ApiError::InvalidWirePayload)); + value = invocation(); + value.consumer = "lineageweave".into(); + assert_eq!(value.validate(), Err(ApiError::InvalidWirePayload)); + value = invocation(); + value.body = "{}".into(); + assert_eq!(value.validate(), Err(ApiError::InvalidWirePayload)); + value = invocation(); + value.export_id = "export\nother".into(); + assert_eq!(value.validate(), Err(ApiError::InvalidWirePayload)); + value = invocation(); + value.origin = "https://bad/path".into(); + assert!(super::compose_export_stored_request_cli_http(&value).is_err()); + + for args in [ + vec!["get", "host"], + vec!["get", "--host"], + vec!["get", "--host", "a", "--host", "b"], + vec!["get", "--host", ""], + ] { + assert!(ExportStoredRequestCliInvocation::from_args(args, "").is_err()); + } + } + + #[test] + fn exchange_header_and_target_error_arms_are_covered() { + let origin = "https://tepp.example.test"; + let base = naruon_export_stored_request_exchange(origin, "export-1").expect("exchange"); + let mut cases = Vec::new(); + let mut value = base.clone(); + value.body = "{}".into(); + cases.push(value); + let mut value = base.clone(); + value.target_url = "http://tepp.example.test/v1/exports/export-1".into(); + cases.push(value); + let mut value = base.clone(); + value.target_url = "https://tepp.example.test".into(); + cases.push(value); + for (name, header_value) in [("bad name", "x"), ("x-good", "bad\nvalue")] { + let mut value = base.clone(); + value.headers.push((name.into(), header_value.into())); + cases.push(value); + } + let mut value = base.clone(); + value + .headers + .push(("content-type".into(), "application/json".into())); + cases.push(value); + for index in 0..base.headers.len() { + let mut value = base.clone(); + value.headers.remove(index); + cases.push(value); + } + for value in cases { + assert!( + loopback_http1_from_export_stored_request_exchange(&value, "127.0.0.1:18081") + .is_err() + ); + } + } + + #[test] + fn response_parser_and_reader_error_arms_are_covered() { + use std::fmt::Write as _; + + let oversized_header = "x".repeat(crate::NARUON_LIVE_HEADER_BYTE_LIMIT + 1); + let mut many_headers = String::new(); + for index in 0..=crate::NARUON_LIVE_HEADER_COUNT_LIMIT { + write!(many_headers, "x-{index}: b\r\n").expect("string write"); + } + let cases = [ + vec![0xff], + b"HTTP/1.1 200 OK".to_vec(), + format!("{oversized_header}\r\n\r\n").into_bytes(), + b"HTTP/1.0 200 OK\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 nope\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 999 Unknown\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 200 Bad\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\nbad\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\nbad name: x\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\nx-good: bad\x01value\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\nx-good: a\r\nx-good: b\r\ncontent-length: 0\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\ncontent-length: x\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\n\r\n".to_vec(), + b"HTTP/1.1 200 OK\r\ncontent-length: 1\r\n\r\n".to_vec(), + format!( + "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n", + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT + 1 + ) + .into_bytes(), + format!("HTTP/1.1 200 OK\r\n{many_headers}content-length: 0\r\n\r\n").into_bytes(), + ]; + for bytes in cases { + assert!(parse_http_response(&bytes).is_err()); + } + for (code, reason) in [ + (202, "Accepted"), + (400, "Bad Request"), + (403, "Forbidden"), + (413, "Payload Too Large"), + (422, "Unprocessable Entity"), + ] { + let response = format!("HTTP/1.1 {code} {reason}\r\ncontent-length: 0\r\n\r\n"); + assert_eq!( + parse_http_response(response.as_bytes()) + .expect("response") + .status_code, + code + ); + } + assert!(read_export_stored_request_cli_stdin(false, Cursor::new([0xff])).is_err()); + assert!( + read_export_stored_request_cli_stdin( + false, + Cursor::new(vec![b'a'; DEFAULT_PROJECT_HISTORY_BYTE_LIMIT + 1]), + ) + .is_err() + ); + assert!(read_export_stored_request_cli_stdin(false, FailingReader).is_err()); + assert!(!valid_http_field_name("")); + assert!(!valid_http_field_name("bad name")); + } + + struct FailingReader; + + impl Read for FailingReader { + fn read(&mut self, _buffer: &mut [u8]) -> io::Result { + Err(io::Error::other("redacted")) + } + } +} diff --git a/crates/tepp_api/src/export_stored_request_http.rs b/crates/tepp_api/src/export_stored_request_http.rs new file mode 100644 index 000000000..c9a42989a --- /dev/null +++ b/crates/tepp_api/src/export_stored_request_http.rs @@ -0,0 +1,262 @@ +//! Provider-owned export stored-request GET contracts. +//! +//! GAP-003A unique slice: `GET /v1/exports/{export_id}/request` returns the +//! accepted naruon export-authorization request on `AnalysisRunLiveService` +//! / `tepp-loopback` so operators who hold a retrieval identity do not replay +//! POST. `NaruonLiveService` stays POST-only. `LineageWeave` is refused on this +//! naruon-owned adapter. `tepp.scientific_acceptance.v1` never appears. This +//! module does not duplicate GET-by-id (#411), retrieval CLI (#417), +//! collection GET/CLI (#443/#444), export-authorize CLI (#410), analysis-run +//! stored-request GET (#377), project-history stored-request GET (#455), +//! interpretation-run stored-request GET (#453), or cancel lineages (closed). +//! Persistence remains GAP-003B. GAP-010 Figma/export remains later work. + +use crate::export_http::EXPORT_RETRIEVAL_ID_MAX_LEN; +use crate::naruon_http::{compose_https_target, NaruonHttpExchange}; +use crate::wire::require_nonempty; +use crate::{ApiError, NARUON_EXPORT_PATH}; + +const FORBIDDEN_STORED_REQUEST_KEYS: [&str; 13] = [ + "rmse", + "rmse_standard_error", + "mean_bias", + "bias_standard_error", + "interval_coverage", + "coverage_wilson_lower", + "coverage_wilson_upper", + "temporal_order_accuracy", + "se_gate_accepted", + "se_gate_k", + "scientific_acceptance", + "report", + "terminal_result", +]; + +/// Extract the opaque export identity from +/// `GET /v1/exports/{export_id}/request`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for collection, GET-by-id, extra +/// segments, a hostile encoding, or an empty identity, and +/// [`ApiError::LimitExceeded`] when oversized. +pub fn export_stored_request_path_id(path: &str) -> Result { + let remainder = path + .strip_prefix(NARUON_EXPORT_PATH) + .ok_or(ApiError::InvalidWirePayload)?; + let encoded = remainder + .strip_prefix('/') + .ok_or(ApiError::InvalidWirePayload)?; + let (encoded_id, rest) = encoded + .split_once('/') + .ok_or(ApiError::InvalidWirePayload)?; + if rest != "request" || encoded_id.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + let export_id = decode_path_segment(encoded_id)?; + require_nonempty(&export_id)?; + if export_id.contains('/') || export_id.contains('\0') { + return Err(ApiError::InvalidWirePayload); + } + if export_id.len() > EXPORT_RETRIEVAL_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(export_id) +} + +/// Whether `path` is the stored-request extra-segment resource. +#[must_use] +pub fn is_export_stored_request_path(path: &str) -> bool { + export_stored_request_path_id(path).is_ok() +} + +/// Refuse stored-request JSON that already carries scientific-metric keys. +/// +/// Empty payloads are admitted for the GET request body. The original +/// authorization request may carry `tenant_workspace_id`, `principal_id`, and +/// `includes_source_text`; those keys are not scientific metrics. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a forbidden metric key is +/// present. +pub fn refuse_metrics_on_export_stored_request_payload(payload: &str) -> Result<(), ApiError> { + if payload.trim().is_empty() { + return Ok(()); + } + let value: serde_json::Value = + serde_json::from_str(payload).map_err(|_| ApiError::InvalidWirePayload)?; + if !value.is_object() { + return Err(ApiError::InvalidWirePayload); + } + refuse_metrics_on_json(&value) +} + +fn refuse_metrics_on_json(value: &serde_json::Value) -> Result<(), ApiError> { + match value { + serde_json::Value::Object(object) => { + if object + .get("schema_version") + .and_then(serde_json::Value::as_str) + == Some("tepp.scientific_acceptance.v1") + { + return Err(ApiError::InvalidWirePayload); + } + if FORBIDDEN_STORED_REQUEST_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + for nested in object.values() { + refuse_metrics_on_json(nested)?; + } + Ok(()) + } + serde_json::Value::Array(items) => { + for nested in items { + refuse_metrics_on_json(nested)?; + } + Ok(()) + } + _ => Ok(()), + } +} + +/// Build a credential-free naruon stored-request GET exchange. +/// +/// # Errors +/// +/// Returns a fail-closed origin or identity error. +pub fn naruon_export_stored_request_exchange( + origin: &str, + export_id: &str, +) -> Result { + require_nonempty(export_id)?; + if export_id.contains('/') || export_id.contains('\0') { + return Err(ApiError::InvalidWirePayload); + } + if export_id.len() > EXPORT_RETRIEVAL_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + let encoded_id = encode_path_segment(export_id); + let target_path = format!("{NARUON_EXPORT_PATH}/{encoded_id}/request"); + let target_url = compose_https_target(origin, &target_path)?; + Ok(NaruonHttpExchange { + method: "GET", + target_url, + headers: vec![ + ("content-type".into(), "application/json".into()), + ("tepp-consumer".into(), "naruon".into()), + ("tepp-contract-version".into(), "1".into()), + ], + body: String::new(), + }) +} + +fn encode_path_segment(value: &str) -> String { + let mut out = String::with_capacity(value.len() + value.len() / 2); + let hex = b"0123456789ABCDEF"; + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(byte as char); + } + _ => { + out.push('%'); + out.push(hex[usize::from(byte >> 4)] as char); + out.push(hex[usize::from(byte & 0x0F)] as char); + } + } + } + out +} + +fn decode_path_segment(value: &str) -> Result { + let mut out = Vec::with_capacity(value.len()); + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' => { + if index + 2 >= bytes.len() { + return Err(ApiError::InvalidWirePayload); + } + let hi = from_hex(bytes[index + 1])?; + let lo = from_hex(bytes[index + 2])?; + out.push((hi << 4) | lo); + index += 3; + } + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(bytes[index]); + index += 1; + } + _ => return Err(ApiError::InvalidWirePayload), + } + } + let decoded = String::from_utf8(out).map_err(|_| ApiError::InvalidWirePayload)?; + if decoded.chars().any(char::is_control) { + return Err(ApiError::InvalidWirePayload); + } + Ok(decoded) +} + +fn from_hex(byte: u8) -> Result { + match byte { + b'0'..=b'9' => Ok(byte - b'0'), + b'A'..=b'F' => Ok(byte - b'A' + 10), + b'a'..=b'f' => Ok(byte - b'a' + 10), + _ => Err(ApiError::InvalidWirePayload), + } +} + +#[cfg(test)] +mod tests { + use super::{ + export_stored_request_path_id, is_export_stored_request_path, + naruon_export_stored_request_exchange, refuse_metrics_on_export_stored_request_payload, + }; + use crate::ApiError; + + #[test] + fn stored_request_exchange_is_naruon_get_without_credentials() { + let exchange = + naruon_export_stored_request_exchange("https://tepp.example.test", "export-1") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert!(exchange + .target_url + .ends_with("/v1/exports/export-1/request")); + assert!(exchange.body.is_empty()); + assert!(!exchange + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("authorization") + || name.eq_ignore_ascii_case("idempotency-key"))); + assert!(is_export_stored_request_path( + "/v1/exports/export-1/request" + )); + assert!(!is_export_stored_request_path("/v1/exports/export-1")); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1/request").expect("id"), + "export-1" + ); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_export_stored_request_exchange("http://tepp.example.test", "export-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!(refuse_metrics_on_export_stored_request_payload(""), Ok(())); + assert_eq!( + refuse_metrics_on_export_stored_request_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index bd8a933e0..8206d45ae 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -21,6 +21,8 @@ mod envelope; mod error; mod export; mod export_http; +mod export_stored_request_cli; +mod export_stored_request_http; mod lineage_criterion_anchor; mod lineage_pair_criterion; mod lineageweave_http; @@ -106,6 +108,30 @@ pub use export_http::ExportRetrieval; pub use export_http::naruon_export_retrieval_exchange; /// Refuse scientific-metric keys on export-retrieval JSON. pub use export_http::refuse_metrics_on_export_retrieval_payload; +/// Loopback CLI invocation for naruon export stored-request GET. +pub use export_stored_request_cli::ExportStoredRequestCliInvocation; +/// Loopback CLI verb for export stored-request GET. +pub use export_stored_request_cli::ExportStoredRequestCliVerb; +/// Compose HTTP/1.1 from a stored-request CLI invocation. +pub use export_stored_request_cli::compose_export_stored_request_cli_http; +/// Dispatch a stored-request CLI invocation against an in-process listener. +pub use export_stored_request_cli::dispatch_export_stored_request_cli; +/// Execute a stored-request CLI invocation over loopback TCP. +pub use export_stored_request_cli::execute_export_stored_request_cli; +/// Render `tepp-loopback` HTTP/1.1 from a stored-request exchange. +pub use export_stored_request_cli::loopback_http1_from_export_stored_request_exchange; +/// Read leftover stdin for stored-request GET; empty is admitted. +pub use export_stored_request_cli::read_export_stored_request_cli_stdin; +/// Filter stored-request CLI stdout so scientific-acceptance never prints. +pub use export_stored_request_cli::render_export_stored_request_cli_stdout; +/// Extract the opaque export identity from a stored-request path. +pub use export_stored_request_http::export_stored_request_path_id; +/// Whether a path is the export stored-request extra-segment resource. +pub use export_stored_request_http::is_export_stored_request_path; +/// Build a naruon export stored-request GET exchange. +pub use export_stored_request_http::naruon_export_stored_request_exchange; +/// Refuse scientific-metric keys on export stored-request JSON. +pub use export_stored_request_http::refuse_metrics_on_export_stored_request_payload; /// Analytical export purpose. pub use authorization::AnalyticalPurpose; diff --git a/crates/tepp_api/tests/export_stored_request_cli_contract.rs b/crates/tepp_api/tests/export_stored_request_cli_contract.rs new file mode 100644 index 000000000..3eac1231b --- /dev/null +++ b/crates/tepp_api/tests/export_stored_request_cli_contract.rs @@ -0,0 +1,401 @@ +//! Contract tests for the naruon export stored-request loopback CLI. + +use tepp_api::{ + AnalysisRunLiveService, AnalyticalPurpose, ApiError, EXPORT_RETRIEVAL_ID_MAX_LEN, + ExportAuthorizationRequest, ExportRetrieval, ExportStoredRequestCliInvocation, + ExportStoredRequestCliVerb, LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, + NARUON_EXPORT_PATH, NaruonHttpExchange, NaruonLiveResponse, NaruonLiveService, + compose_export_stored_request_cli_http, dispatch_export_stored_request_cli, + execute_export_stored_request_cli, loopback_http1_from_export_stored_request_exchange, + naruon_export_stored_request_exchange, read_export_stored_request_cli_stdin, + render_export_stored_request_cli_stdout, +}; + +const ORIGIN: &str = "https://tepp.example.test"; +const SCHEMA: &str = "tepp.scientific_acceptance.v1"; + +fn sample_request() -> ExportAuthorizationRequest { + ExportAuthorizationRequest { + tenant_workspace_id: "export-cli-tenant".into(), + principal_id: "principal-analyst-1".into(), + purpose: AnalyticalPurpose::ModularServiceConsumer, + artifact_id: "artifact-cli-1".into(), + includes_source_text: false, + } +} + +fn export_post(request: &ExportAuthorizationRequest, idempotency_key: &str) -> String { + let body = tepp_api_wire_json(request); + 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: {idempotency_key}\r\ncontent-length: {}\r\n\r\n{body}", + body.len() + ) +} + +fn tepp_api_wire_json(request: &ExportAuthorizationRequest) -> String { + serde_json::to_string(request).expect("request json") +} + +fn get_args<'a>(host: &'a str, export_id: &'a str, consumer: &'a str) -> [&'a str; 9] { + [ + "get", + "--host", + host, + "--origin", + ORIGIN, + "--consumer", + consumer, + "--export-id", + export_id, + ] +} + +#[test] +fn verbs_and_from_args_fail_closed() { + assert_eq!( + ExportStoredRequestCliVerb::parse("get").expect("get"), + ExportStoredRequestCliVerb::Get + ); + assert_eq!(ExportStoredRequestCliVerb::Get.as_str(), "get"); + assert_eq!( + ExportStoredRequestCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args("8.8.8.8:80", "export-1", NARUON_CONSUMER_CODE), + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + [ + "get", + "--host", + "localhost:18081", + "--origin", + ORIGIN, + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + "http://tepp.example.test", + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--authorization", + "secret", + "--export-id", + "export-1" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); +} + +#[test] +fn from_args_refuses_lineageweave_slash_body_size_and_pagination() { + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export-1", LINEAGEWEAVE_CONSUMER_CODE), + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export-1", "unpublished"), + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export-1", NARUON_CONSUMER_CODE), + "{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export/slash", NARUON_CONSUMER_CODE), + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + get_args( + "127.0.0.1:18081", + &"a".repeat(EXPORT_RETRIEVAL_ID_MAX_LEN + 1), + NARUON_CONSUMER_CODE + ), + "" + ) + .unwrap_err(), + ApiError::LimitExceeded + ); + assert_eq!( + ExportStoredRequestCliInvocation::from_args( + [ + "get", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--export-id", + "export-1", + "--page-limit", + "1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); +} + +#[test] +fn compose_is_typed_https_get_without_credentials() { + let invocation = ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export-1", NARUON_CONSUMER_CODE), + "", + ) + .expect("invocation"); + let http = compose_export_stored_request_cli_http(&invocation).expect("http"); + assert!(http.starts_with("GET /v1/exports/export-1/request HTTP/1.1")); + assert!(http.contains("tepp-consumer: naruon")); + assert!(!http.to_ascii_lowercase().contains("authorization")); + assert!(!http.contains("rmse")); + assert!(!http.contains(SCHEMA)); +} + +#[test] +fn naruon_cli_retrieves_stored_request_and_naruon_live_stays_post_only() { + let mut service = AnalysisRunLiveService::new(); + let request = sample_request(); + let posted = service.handle_http_request(&export_post(&request, "export-idem-1")); + assert_eq!(posted.status_code, 200, "{}", posted.body); + let retrieval = ExportRetrieval::from_json(&posted.body).expect("posted retrieval"); + let invocation = ExportStoredRequestCliInvocation::from_args( + get_args( + "127.0.0.1:18081", + &retrieval.export_id, + NARUON_CONSUMER_CODE, + ), + "", + ) + .expect("invocation"); + let got = dispatch_export_stored_request_cli(&mut service, &invocation).expect("get"); + assert_eq!(got.status_code, 200, "{}", got.body); + let stdout = render_export_stored_request_cli_stdout(&invocation, &got).expect("out"); + let stored: ExportAuthorizationRequest = serde_json::from_str(&stdout).expect("stored"); + assert_eq!(stored, request); + assert!(stdout.contains("tenant_workspace_id")); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains(SCHEMA)); + let missing = ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "missing-export", NARUON_CONSUMER_CODE), + "", + ) + .expect("missing"); + let denied = dispatch_export_stored_request_cli(&mut service, &missing).expect("denied"); + assert_eq!(denied.status_code, 400); + assert!( + render_export_stored_request_cli_stdout(&missing, &denied) + .expect("err") + .contains("invalid_wire_payload") + ); + let mut naruon = NaruonLiveService::new(); + assert_eq!( + naruon + .handle_http_request( + &compose_export_stored_request_cli_http(&invocation).expect("composed") + ) + .status_code, + 400 + ); +} + +#[test] +fn render_refuses_metrics_schema_and_empty_success() { + let invocation = ExportStoredRequestCliInvocation::from_args( + get_args("127.0.0.1:18081", "export-1", NARUON_CONSUMER_CODE), + "", + ) + .expect("invocation"); + assert_eq!( + render_export_stored_request_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new() + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_export_stored_request_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"tenant_workspace_id":"t","rmse":1.0}"#.into() + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_export_stored_request_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: format!(r#"{{"schema_version":"{SCHEMA}"}}"#) + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); +} + +#[test] +fn loopback_http1_refuses_non_get_collection_get_by_id_cancel_and_credentials() { + let host = "127.0.0.1:18081"; + let exchange = naruon_export_stored_request_exchange(ORIGIN, "export-1").expect("ex"); + let ok = loopback_http1_from_export_stored_request_exchange(&exchange, host).expect("ok"); + assert!(ok.starts_with("GET /v1/exports/export-1/request HTTP/1.1")); + let mut posted = exchange.clone(); + posted.method = "POST"; + assert_eq!( + loopback_http1_from_export_stored_request_exchange(&posted, host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut by_id = exchange.clone(); + by_id.target_url = format!("{ORIGIN}{NARUON_EXPORT_PATH}/export-1"); + assert_eq!( + loopback_http1_from_export_stored_request_exchange(&by_id, host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut cancel = exchange.clone(); + cancel.target_url = format!("{ORIGIN}{NARUON_EXPORT_PATH}/export-1/cancel"); + assert_eq!( + loopback_http1_from_export_stored_request_exchange(&cancel, host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let credentialed = NaruonHttpExchange { + method: "GET", + target_url: format!("{ORIGIN}{NARUON_EXPORT_PATH}/export-1/request"), + headers: vec![("authorization".into(), "secret".into())], + body: String::new(), + }; + assert_eq!( + loopback_http1_from_export_stored_request_exchange(&credentialed, host).unwrap_err(), + ApiError::AuthorizationDenied + ); +} + +#[test] +fn execute_over_tcp_and_stdin_reader() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let addr = service.local_addr().expect("addr").to_string(); + let request = sample_request(); + let posted = service.handle_http_request(&export_post(&request, "export-idem-tcp")); + assert_eq!(posted.status_code, 200, "{}", posted.body); + let retrieval = ExportRetrieval::from_json(&posted.body).expect("posted retrieval"); + let export_id = retrieval.export_id.clone(); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let invocation = ExportStoredRequestCliInvocation::from_args( + get_args(addr.as_str(), &export_id, NARUON_CONSUMER_CODE), + "", + ) + .expect("tcp"); + let response = execute_export_stored_request_cli(&invocation).expect("execute"); + assert_eq!(response.status_code, 200, "{}", response.body); + let stored: ExportAuthorizationRequest = serde_json::from_str( + &render_export_stored_request_cli_stdout(&invocation, &response).expect("stdout"), + ) + .expect("parsed"); + assert_eq!(stored.artifact_id, "artifact-cli-1"); + handle.join().expect("join"); + assert!( + read_export_stored_request_cli_stdin(true, std::io::empty()) + .expect("tty") + .is_empty() + ); + assert!( + read_export_stored_request_cli_stdin(false, std::io::Cursor::new(b"")) + .expect("pipe") + .is_empty() + ); +} + +#[test] +fn binary_reports_redacted_success_and_failure_statuses() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let addr = service.local_addr().expect("addr").to_string(); + let request = sample_request(); + let posted = service.handle_http_request(&export_post(&request, "export-idem-bin")); + assert_eq!(posted.status_code, 200, "{}", posted.body); + let retrieval = ExportRetrieval::from_json(&posted.body).expect("posted retrieval"); + let export_id = retrieval.export_id.clone(); + let handle = std::thread::spawn(move || { + service.serve_one().expect("success request"); + service.serve_one().expect("missing request"); + }); + let binary = env!("CARGO_BIN_EXE_tepp-export-request"); + let run = |export_id: &str| { + std::process::Command::new(binary) + .args(get_args(&addr, export_id, NARUON_CONSUMER_CODE)) + .output() + .expect("binary") + }; + let success = run(&export_id); + assert!( + success.status.success(), + "{}", + String::from_utf8_lossy(&success.stderr) + ); + assert!(String::from_utf8_lossy(&success.stdout).contains("artifact-cli-1")); + let failure = run("missing-export"); + assert!(!failure.status.success()); + assert!(String::from_utf8_lossy(&failure.stderr).contains("invalid API wire payload")); + handle.join().expect("server"); +} diff --git a/crates/tepp_api/tests/export_stored_request_http_contract.rs b/crates/tepp_api/tests/export_stored_request_http_contract.rs new file mode 100644 index 000000000..fb06fd15f --- /dev/null +++ b/crates/tepp_api/tests/export_stored_request_http_contract.rs @@ -0,0 +1,43 @@ +//! Contract tests for naruon export stored-request GET. + +use tepp_api::{ + export_stored_request_path_id, naruon_export_stored_request_exchange, + refuse_metrics_on_export_stored_request_payload, ApiError, NARUON_CONSUMER_CODE, +}; + +#[test] +fn stored_request_exchange_is_metric_free_get_without_credentials() { + let exchange = naruon_export_stored_request_exchange("https://tepp.example.test", "export-1") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert!(exchange + .target_url + .ends_with("/v1/exports/export-1/request")); + assert!(exchange.body.is_empty()); + assert!(exchange + .headers + .iter() + .any(|(name, value)| name == "tepp-consumer" && value == NARUON_CONSUMER_CODE)); + assert!(!exchange + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("authorization") + || name.eq_ignore_ascii_case("idempotency-key"))); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1/request").expect("id"), + "export-1" + ); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + export_stored_request_path_id("/v1/exports/export-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_export_stored_request_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!(refuse_metrics_on_export_stored_request_payload(""), Ok(())); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 1142e99fe..e1c3d42cb 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); `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); loopback `GET /v1/exports/{export_id}/request` returns the stored authorization request (ADR 0089); `tepp-export-request get` mints that stored-request GET onto spawned `tepp-loopback` TCP (ADR 0090); `NaruonLiveService` stays POST-only. ## 2. Contract families @@ -69,6 +69,7 @@ GET /v1/analysis-runs/{run_id} POST /v1/analysis-runs/{run_id}/cancel GET /v1/model-artifacts/{artifact_id} GET /v1/exports/{export_id} +GET /v1/exports/{export_id}/request ``` Long-running analysis is durable asynchronous work. `POST /v1/analysis-runs` accepts an idempotency key, immutable input snapshot identity, knowledge cutoff, versioned model contract/configuration, and requested output profile. A retry with the same principal/idempotency key and semantically identical request returns the same run identity; a conflicting body fails closed. diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 20d4b7f01..cc80a54f5 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 | `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 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/0089/0090 | `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, `GET /v1/exports/{export_id}/request` returns the stored authorization request, and `tepp-export-request` mints that GET onto `tepp-loopback` 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/0089-export-stored-request-get.md b/docs/adr/0089-export-stored-request-get.md new file mode 100644 index 000000000..9a2b4e0dd --- /dev/null +++ b/docs/adr/0089-export-stored-request-get.md @@ -0,0 +1,62 @@ +# ADR 0089 — Loopback export stored-request GET + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-09-01 +**Supersedes:** None; complements ADR 0054. Does not re-open cancel lineages. +Does not supersede ADR 0014. Unique versus protected main; 0026–0088 occupied. + +## Context + +ADR 0054 retrieves one authorized export identity. Operators still had no +extra-segment GET for the stored naruon authorization request. +Project-history stored-request GET (#455) is LineageWeave-owned. +Interpretation-run stored-request GET (#453) is orchestrator-owned. +Duplicating GET-by-id (#411), retrieval CLI (#417), collection GET/CLI +(#443/#444), export-authorize CLI (#410), Leiden, or GAP-010 would collide +with live PRs. Cancel lineages stay closed. LineageWeave is refused on this +naruon-owned adapter. `NaruonLiveService` stays POST-only. + +## Decision + +Publish `GET /v1/exports/{export_id}/request` on `AnalysisRunLiveService`. +Extra-segment parse before GET-by-id. Slash/NUL fail closed. Empty body. +Naruon-only. Response is the stored authorization request. Scientific-metric +keys and `tepp.scientific_acceptance.v1` never appear. Cancel extra-segment +stays refused. `NaruonLiveService` stays POST-only. + +## Alternatives considered + +1. Re-open cancel HTTP — rejected. +2. Return GET-by-id retrieval identity — rejected (ADR 0054). +3. Loopback stored-request GET — accepted. + +## Consequences + +HTTP 200 is not measurement evidence and is not an ADR 0014 claim. Sequence +remains association, not causation. + +## Failure and recovery + +LineageWeave, nonempty bodies, extra segments, slash/NUL, missing keys, http +origins, unpublished consumers, credential flags, and metric keys fail closed. + +## Verification + +- `GET /v1/exports/{export_id}/request` of an authorized export returns the + stored authorization request without RMSE/`tepp.scientific_acceptance.v1`; +- LineageWeave, GET-by-id path, extra segments, slash/NUL, nonempty body, and + missing keys fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain + required. + +## Rollback and supersession + +Rollback removes the extra-segment GET; POST and GET-by-id remain valid. A +superseding ADR is required to persist the registry, bind a public address, +re-open cancel, emit scientific-acceptance, open LineageWeave on this adapter, +add GET to `NaruonLiveService`, or treat retrieval success as an ADR 0014 claim. + +## Related authority + +ADR 0054, ADR 0009, ADR 0011, ADR 0014, RFC 9110 (Fielding, Nottingham, & Reschke, 2022). diff --git a/docs/adr/0090-export-stored-request-cli.md b/docs/adr/0090-export-stored-request-cli.md new file mode 100644 index 000000000..5fb1bc0a0 --- /dev/null +++ b/docs/adr/0090-export-stored-request-cli.md @@ -0,0 +1,64 @@ +# ADR 0090 — Loopback export stored-request CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-09-01 +**Supersedes:** None; complements ADR 0089. Does not re-open cancel lineages. +Does not supersede ADR 0014. Unique versus protected main; 0026–0089 occupied. + +## Context + +ADR 0089 publishes `GET /v1/exports/{export_id}/request`. Operators still had +no published binary that mints that GET onto spawned `tepp-loopback` TCP. +Duplicating stored-request GET (#457), GET-by-id (#411), retrieval CLI (#417), +collection GET/CLI (#443/#444), export-authorize CLI (#410), project-history +stored-request CLI (#456), interpretation-run stored-request CLI (#454), +Leiden, or GAP-010 would collide with live PRs. Cancel lineages stay closed. +LineageWeave is refused on this naruon-owned adapter. `NaruonLiveService` +stays POST-only. + +## Decision + +Publish `tepp-export-request get` which mints +`naruon_export_stored_request_exchange` onto spawned `tepp-loopback` TCP. +Empty stdin is admitted. Nonempty leftover stdin, public bind, `localhost`, +`http` origin, unpublished consumer, LineageWeave, and credential flags fail +closed. Dedicated binary so it does not collide with `tepp-export-list` +(#444), `tepp-export-get` (#417), or export-authorize (#410). Response is the +stored authorization request. `tepp.scientific_acceptance.v1` never appears. + +## Alternatives considered + +1. Re-open cancel CLI — rejected. +2. Reuse `tepp-export-get` — rejected; that is ADR 0055. +3. Dedicated stored-request binary — accepted. + +## Consequences + +CLI success is not measurement evidence and is not an ADR 0014 claim. +Sequence remains association, not causation. + +## Failure and recovery + +LineageWeave, nonempty leftover stdin, extra segments, slash/NUL, missing +keys, public bind, `localhost`, and metric keys fail closed. + +## Verification + +- `tepp-export-request get` of an authorized export prints the stored + authorization request without RMSE/`tepp.scientific_acceptance.v1`; +- LineageWeave, public bind, `localhost`, `http` origin, leftover stdin, + slash/NUL, and missing keys fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain + required. + +## Rollback and supersession + +Rollback removes the published binary; stored-request GET remains valid. A +superseding ADR is required to persist the registry, bind a public address, +re-open cancel, emit scientific-acceptance, open LineageWeave on this adapter, +add GET to `NaruonLiveService`, or treat CLI success as an ADR 0014 claim. + +## Related authority + +ADR 0089, ADR 0054, ADR 0009, ADR 0011, ADR 0014, RFC 9110 (Fielding, Nottingham, & Reschke, 2022). diff --git a/docs/adr/README.md b/docs/adr/README.md index 5e43e54fb..9c5854aa3 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -31,6 +31,8 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0024](0024-lineage-pair-criterion-and-project-journey-posterior.md) | Independent Event Lineage pair criterion and posterior Project Journey | Proposed | active-PR | Strict artifacts preserve criterion/event-time draws, branches, ties, and CPU/GPU receipts without claiming the scientific estimator is complete. | | [0025](0025-macos-native-rust-mlx-metal-boundary.md) | macOS-native Rust-owned MLX Metal execution | Accepted | accepted-target | Compose authenticates to a native host service; Linux never claims Metal, and actual backend/parity receipts fail closed. | | [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. | +| [0089](0089-export-stored-request-get.md) | Loopback export stored-request GET | Accepted | active-PR | `AnalysisRunLiveService` serves `GET /v1/exports/{export_id}/request` for the stored naruon authorization request; `NaruonLiveService` stays POST-only. | +| [0090](0090-export-stored-request-cli.md) | Loopback export stored-request CLI | Accepted | active-PR | Complements ADR 0089; `tepp-export-request get` mints stored-request GET onto `tepp-loopback`. Unique versus protected main (0026–0089 occupied). Does not re-open cancel lineages. | | [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. | @@ -142,6 +144,8 @@ Use the narrowest owning ADR when decisions overlap: - **independent lineage criterion and posterior Project Journey:** ADR 0023. - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. - **loopback export retrieval identity:** ADR 0054. +- **loopback export stored-request GET:** ADR 0089. +- **loopback export stored-request CLI:** ADR 0090. ## Change and supersession rule diff --git a/docs/research/export-stored-request-cli.md b/docs/research/export-stored-request-cli.md new file mode 100644 index 000000000..9baa46430 --- /dev/null +++ b/docs/research/export-stored-request-cli.md @@ -0,0 +1,14 @@ +# Export stored-request CLI (doctoring) + +`tepp-export-request get` mints `naruon_export_stored_request_exchange` onto +spawned `tepp-loopback` TCP. HTTP semantics follow RFC 9110 (Fielding, +Nottingham, & Reschke, 2022). Fail-closed LineageWeave, public bind, +`localhost`, leftover stdin, slash/NUL, credential flags, and +scientific-authority promotion are repository contract (ADR 0090; ADR 0014). + +Stdout is the stored naruon authorization request. +`tepp.scientific_acceptance.v1` never appears. Process exit 0 is not a +scientific claim. `NaruonLiveService` stays POST-only. + +Does not re-open cancel lineages, GAP-010 Figma/export, persistence, Leiden, +or an ADR 0014 claim-promotion package. diff --git a/docs/research/export-stored-request-get.md b/docs/research/export-stored-request-get.md new file mode 100644 index 000000000..04ecd0ab8 --- /dev/null +++ b/docs/research/export-stored-request-get.md @@ -0,0 +1,13 @@ +# Export stored-request GET (doctoring) + +`GET /v1/exports/{export_id}/request` returns one accepted naruon +export-authorization request on `tepp-loopback`. HTTP semantics follow RFC 9110 +(Fielding, Nottingham, & Reschke, 2022). Fail-closed LineageWeave, extra +segments, slash/NUL, leftover bodies, credential flags, and scientific-authority +promotion are repository contract (ADR 0089; ADR 0014). + +`tepp.scientific_acceptance.v1` never appears. HTTP 200 is not a scientific +claim. `NaruonLiveService` stays POST-only. + +Does not re-open cancel lineages, GAP-010 Figma/export, persistence, Leiden, +or an ADR 0014 claim-promotion package.