diff --git a/CHANGELOG.d/project-history-cli.md b/CHANGELOG.d/project-history-cli.md new file mode 100644 index 000000000..64f4db72b --- /dev/null +++ b/CHANGELOG.d/project-history-cli.md @@ -0,0 +1,2 @@ +- `tepp_api` loopback `tepp-project-history query` mints a typed LineageWeave `POST /v1/project-histories` onto spawned `tepp-loopback` TCP (ADR 0061). Metric-free `temporal_association_only` JSON only. `tepp.scientific_acceptance.v1` never appears. Does not infer causality. Naruon is refused. Not temporal-context CLI, not export CLI, not persistence. +- Fail closed on HTTP field injection, duplicate or transfer-encoded framing, non-2xx stdout, and stdin/response payloads above the existing project-history wire limits. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6fa4b9683..94821a7ed 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -11,9 +11,11 @@ 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) | +| Project-history CLI doctoring | [`docs/research/project-history-cli.md`](docs/research/project-history-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) | + | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | | Security policy | [`SECURITY.md`](SECURITY.md) | | Threat model | [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) | diff --git a/crates/tepp_api/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c433..4815e09a4 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-project-history" +path = "src/bin/tepp_project_history.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/bin/tepp_project_history.rs b/crates/tepp_api/src/bin/tepp_project_history.rs new file mode 100644 index 000000000..8a0b16bcb --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_project_history.rs @@ -0,0 +1,36 @@ +//! Operator CLI for loopback `LineageWeave` project-history POST. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + ApiError, ProjectHistoryCliInvocation, execute_project_history_cli, + read_project_history_cli_stdin, render_project_history_cli_stdout, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error}"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result<(), ApiError> { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("query") => run_query(&args), + _ => Err(ApiError::InvalidWirePayload), + } +} + +fn run_query(args: &[String]) -> Result<(), ApiError> { + let body = read_project_history_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = ProjectHistoryCliInvocation::from_args(args, body)?; + let response = execute_project_history_cli(&invocation)?; + let stdout = render_project_history_cli_stdout(&invocation, &response)?; + println!("{stdout}"); + Ok(()) +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 876703ebc..1318b21fa 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -9,7 +9,9 @@ //! may also request a cutoff-safe project-history projection from explicit //! source evidence. Naruon owns the current purpose-bound export adapter. //! Loopback listeners prove the HTTP boundary without claiming production TLS, -//! causality, or completed psychometric model results. +//! causality, or completed psychometric model results. The published +//! `tepp-project-history` CLI mints typed `LineageWeave` project-history POST +//! exchanges onto spawned `tepp-loopback` TCP. mod analysis_result; mod analysis_run; @@ -28,6 +30,7 @@ mod naruon_http; mod naruon_live; mod orchestration; mod project_history; +mod project_history_cli; mod project_journey; mod provider_payload; mod temporal_context; @@ -230,6 +233,24 @@ pub use project_history::ProjectHistoryProjection; pub use project_history::ProjectHistoryRequest; /// Build a cutoff-safe project-history projection. pub use project_history::project_history_projection; +/// Loopback project-history CLI invocation. +pub use project_history_cli::ProjectHistoryCliInvocation; +/// Loopback project-history CLI verb. +pub use project_history_cli::ProjectHistoryCliVerb; +/// Compose HTTP/1.1 project-history POST from a CLI invocation. +pub use project_history_cli::compose_project_history_cli_http; +/// Dispatch a project-history CLI invocation against an in-process listener. +pub use project_history_cli::dispatch_project_history_cli; +/// Execute a project-history CLI invocation over loopback TCP. +pub use project_history_cli::execute_project_history_cli; +/// Render a typed project-history exchange onto a loopback HTTP/1.1 request. +pub use project_history_cli::loopback_http1_from_project_history_exchange; +/// Read leftover stdin for the project-history CLI. +pub use project_history_cli::read_project_history_cli_stdin; +/// Refuse scientific-metric keys on project-history CLI JSON. +pub use project_history_cli::refuse_metrics_on_project_history_cli_payload; +/// Filter project-history CLI stdout so the projection stays metric-free. +pub use project_history_cli::render_project_history_cli_stdout; /// Maximum posterior Project Journey artifact size. pub use project_journey::DEFAULT_PROJECT_JOURNEY_BYTE_LIMIT; /// Exact posterior Project Journey schema identity. diff --git a/crates/tepp_api/src/project_history.rs b/crates/tepp_api/src/project_history.rs index 433fab458..07cacae52 100644 --- a/crates/tepp_api/src/project_history.rs +++ b/crates/tepp_api/src/project_history.rs @@ -162,7 +162,7 @@ impl ProjectHistoryRequest { fn validate(&self) -> Result<(), ApiError> { require_contract_version(self.contract_version, PROJECT_HISTORY_CONTRACT_VERSION)?; - validate_bounded_text(&self.idempotency_key, 256)?; + validate_http_field_value(&self.idempotency_key, 256)?; validate_bounded_text(&self.tenant_workspace_id, 256)?; validate_bounded_text(&self.project_key, 256)?; validate_bounded_text(&self.project_name, 512)?; @@ -391,6 +391,13 @@ fn validate_bounded_text(value: &str, maximum_bytes: usize) -> Result<(), ApiErr Ok(()) } +fn validate_http_field_value(value: &str, maximum_bytes: usize) -> Result<(), ApiError> { + validate_bounded_text(value, maximum_bytes)?; + (value.trim() == value && !value.chars().any(char::is_control)) + .then_some(()) + .ok_or(ApiError::InvalidWirePayload) +} + fn validate_code(value: &str) -> Result<(), ApiError> { validate_bounded_text(value, 64)?; if !value @@ -597,7 +604,7 @@ mod tests { use super::{ PROJECT_HISTORY_CONTRACT_VERSION, ProjectHistoryEvent, ProjectHistoryProjection, ProjectHistoryRequest, build_project_history_exchange, compose_https_target, - project_history_projection, validate_code, + project_history_projection, validate_code, validate_http_field_value, }; use crate::ApiError; @@ -707,6 +714,18 @@ mod tests { project_history_projection(&excess), Err(ApiError::LimitExceeded) ); + + let mut injected = request_with_single_event(); + injected.idempotency_key = "safe\r\nx-api-key: secret".into(); + assert_eq!(injected.to_json(), Err(ApiError::InvalidWirePayload)); + assert_eq!( + validate_http_field_value("safe\0value", 256), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + validate_http_field_value(" padded", 256), + Err(ApiError::InvalidWirePayload) + ); } #[test] diff --git a/crates/tepp_api/src/project_history_cli.rs b/crates/tepp_api/src/project_history_cli.rs new file mode 100644 index 000000000..4b3dd9950 --- /dev/null +++ b/crates/tepp_api/src/project_history_cli.rs @@ -0,0 +1,1098 @@ +//! Operator loopback CLI for `LineageWeave` project-history POST. +//! +//! Operator-visible client of `POST /v1/project-histories` on +//! `AnalysisRunLiveService` / `tepp-loopback` (ADR 0021 / ADR 0011). Operators +//! run `tepp-project-history query` to mint +//! `lineageweave_project_history_exchange` onto spawned `tepp-loopback` TCP. +//! Stdout is a metric-free `temporal_association_only` projection. +//! `tepp.scientific_acceptance.v1` never appears. The CLI does not infer +//! causality. Naruon is refused on this LineageWeave-owned adapter. +//! `NaruonLiveService` stays POST-only for analysis-run and export. This +//! module does not duplicate temporal-context CLI, export CLIs, analysis-run +//! CLIs, GET-by-id, 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, + LINEAGEWEAVE_CONSUMER_CODE, NARUON_LIVE_HEADER_BYTE_LIMIT, NARUON_LIVE_HEADER_COUNT_LIMIT, + NARUON_LIVE_IO_TIMEOUT, NaruonLiveResponse, PROJECT_HISTORY_CONTRACT_VERSION, + PROJECT_HISTORY_PATH, ProjectHistoryHttpExchange, ProjectHistoryProjection, + ProjectHistoryRequest, lineageweave_project_history_exchange, project_history_projection, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; +const MAXIMUM_HTTP_RESPONSE_BYTES: usize = + NARUON_LIVE_HEADER_BYTE_LIMIT + 4 + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT; + +/// Supported operator verbs for the loopback project-history CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProjectHistoryCliVerb { + /// `POST /v1/project-histories`. + Query, +} + +impl ProjectHistoryCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "query" => Ok(Self::Query), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Query => "query", + } + } +} + +/// One operator CLI invocation against a loopback project-history listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProjectHistoryCliInvocation { + /// CLI verb to execute. + pub verb: ProjectHistoryCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published HTTPS origin used to mint the typed project-history exchange. + pub origin: String, + /// Published modular consumer. Project-history admits `lineageweave` only. + pub consumer: String, + /// Validated cutoff-safe project-history request. + pub request: ProjectHistoryRequest, +} + +impl ProjectHistoryCliInvocation { + /// Parse argv plus stdin JSON into a validated loopback query invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing flags, a + /// non-loopback host, a non-`https` origin, an unpublished or naruon + /// consumer, credential-shaped flags, metric keys, or an invalid 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 = ProjectHistoryCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + let body = body.into(); + refuse_scientific_acceptance(&body)?; + refuse_metrics_on_project_history_cli_payload(&body)?; + let request = ProjectHistoryRequest::from_json(&body)?; + let invocation = Self { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + origin: flags.origin.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| LINEAGEWEAVE_CONSUMER_CODE.to_owned()), + request, + }; + invocation.validate()?; + Ok(invocation) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile origin. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] when the origin is not `https` or the + /// consumer is not `lineageweave`. + 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 != LINEAGEWEAVE_CONSUMER_CODE { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + origin: Option, + consumer: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + origin: None, + consumer: 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, + _ => 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 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 project-history 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. +/// +/// # 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/project-histories`. +pub fn loopback_http1_from_project_history_exchange( + exchange: &ProjectHistoryHttpExchange, + loopback_host: &str, +) -> Result { + let _addr = require_loopback_host(loopback_host)?; + let host = loopback_host.trim(); + if exchange.method != "POST" { + 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)?; + if path != PROJECT_HISTORY_PATH { + return Err(ApiError::InvalidWirePayload); + } + let body = ProjectHistoryRequest::from_json(&exchange.body)?; + let mut seen = HashSet::with_capacity(exchange.headers.len()); + 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" => value == "application/json", + "tepp-consumer" => value == LINEAGEWEAVE_CONSUMER_CODE, + "tepp-contract-version" => value == &PROJECT_HISTORY_CONTRACT_VERSION.to_string(), + "idempotency-key" => value == &body.idempotency_key, + _ => false, + }; + if !valid { + return Err(ApiError::InvalidWirePayload); + } + } + if seen.len() != 4 { + 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: {}\r\n\r\n{}", + exchange.body.len(), + exchange.body + ) + .map_err(|_| ApiError::InvalidWirePayload)?; + Ok(request) +} + +/// Compose one HTTP/1.1 project-history POST from the typed consumer exchange. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`ProjectHistoryCliInvocation::validate`]. +pub fn compose_project_history_cli_http( + invocation: &ProjectHistoryCliInvocation, +) -> Result { + invocation.validate()?; + let exchange = lineageweave_project_history_exchange(&invocation.origin, &invocation.request)?; + loopback_http1_from_project_history_exchange(&exchange, &invocation.host) +} + +/// Dispatch one project-history CLI invocation against an in-process listener. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_project_history_cli( + service: &mut AnalysisRunLiveService, + invocation: &ProjectHistoryCliInvocation, +) -> Result { + let request = compose_project_history_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one project-history CLI invocation over loopback TCP. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_project_history_cli( + invocation: &ProjectHistoryCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_project_history_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 project-history never prints scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when the body is empty, carries +/// metric or causal-score keys, or a success body is not a +/// `temporal_association_only` projection for the requested project. +pub fn render_project_history_cli_stdout( + invocation: &ProjectHistoryCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance(&response.body)?; + refuse_metrics_on_project_history_cli_payload(&response.body)?; + if !(200..300).contains(&response.status_code) { + return Err(ApiError::InvalidWirePayload); + } + if response.status_code != 200 { + return Err(ApiError::InvalidWirePayload); + } + let projection = ProjectHistoryProjection::from_json(&response.body)?; + if projection != project_history_projection(&invocation.request)? { + return Err(ApiError::InvalidWirePayload); + } + projection.to_json() +} + +fn refuse_scientific_acceptance(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +/// Refuse project-history JSON that already carries scientific-metric keys. +/// +/// Empty payloads are admitted so missing stdin can fail later as invalid +/// wire. Non-object JSON fails closed. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a forbidden metric or causal +/// key is present or the payload is a non-empty non-object. +pub fn refuse_metrics_on_project_history_cli_payload(payload: &str) -> Result<(), ApiError> { + const FORBIDDEN: [&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", + "scientific_acceptance", + "causal_score", + "causality", + "terminal_result", + ]; + 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); + } + if contains_forbidden(&value, &FORBIDDEN) { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) +} + +fn contains_forbidden(value: &serde_json::Value, forbidden: &[&str]) -> bool { + match value { + serde_json::Value::Object(object) => object.iter().any(|(key, nested)| { + forbidden.contains(&key.as_str()) || contains_forbidden(nested, forbidden) + }), + serde_json::Value::Array(values) => values + .iter() + .any(|nested| contains_forbidden(nested, forbidden)), + _ => false, + } +} + +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; query requires JSON. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_project_history_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)] +#[allow(clippy::too_many_lines)] +mod tests { + use std::fmt::Write as _; + + use super::{ + ProjectHistoryCliInvocation, ProjectHistoryCliVerb, SCIENTIFIC_ACCEPTANCE_SCHEMA, + compose_project_history_cli_http, dispatch_project_history_cli, + execute_project_history_cli, loopback_http1_from_project_history_exchange, + parse_http_response, read_project_history_cli_stdin, render_project_history_cli_stdout, + static_reason, + }; + use crate::{ + AnalysisRunLiveService, ApiError, DEFAULT_PROJECT_HISTORY_BYTE_LIMIT, + LINEAGEWEAVE_CONSUMER_CODE, NARUON_CONSUMER_CODE, NARUON_LIVE_HEADER_BYTE_LIMIT, + NARUON_LIVE_HEADER_COUNT_LIMIT, NaruonLiveResponse, NaruonLiveService, + PROJECT_HISTORY_CONTRACT_VERSION, ProjectHistoryEvent, ProjectHistoryHttpExchange, + ProjectHistoryProjection, ProjectHistoryRequest, lineageweave_project_history_exchange, + }; + + const ORIGIN: &str = "https://tepp.example.test"; + + fn sample_event() -> ProjectHistoryEvent { + ProjectHistoryEvent { + event_id: "event-voc".into(), + event_type_code: "voc_received".into(), + event_title: "VOC received".into(), + occurred_at: "2026-07-30T09:00:00Z".into(), + available_at: "2026-07-30T09:00:00Z".into(), + source_post_id: "post-voc".into(), + evidence_text: "evidence for VOC received".into(), + actor_ids: vec!["person-3".into()], + } + } + + fn query_body() -> String { + ProjectHistoryRequest { + contract_version: PROJECT_HISTORY_CONTRACT_VERSION, + idempotency_key: "lineageweave-project-cli-1".into(), + tenant_workspace_id: "tenant-demo".into(), + project_key: "project-acme".into(), + project_name: "Acme renewal".into(), + knowledge_cutoff: "2026-08-19T23:59:59Z".into(), + focus_event_id: "event-voc".into(), + events: vec![ + ProjectHistoryEvent { + event_id: "event-award".into(), + event_type_code: "contract_awarded".into(), + event_title: "Contract award".into(), + occurred_at: "2022-03-11T09:00:00Z".into(), + available_at: "2022-03-11T09:00:00Z".into(), + source_post_id: "post-award".into(), + evidence_text: "evidence for Contract award".into(), + actor_ids: vec!["person-1".into()], + }, + sample_event(), + ], + } + .to_json() + .expect("json") + } + + fn query_args() -> [&'static str; 7] { + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + ] + } + + #[test] + fn verbs_and_from_args_fail_closed() { + assert_eq!( + ProjectHistoryCliVerb::parse("query").expect("verb"), + ProjectHistoryCliVerb::Query + ); + assert_eq!(ProjectHistoryCliVerb::Query.as_str(), "query"); + assert_eq!( + ProjectHistoryCliVerb::parse("QUERY"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + ProjectHistoryCliVerb::parse("authorize"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args(Vec::::new(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "8.8.8.8:80", + "--origin", + ORIGIN, + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE + ], + query_body() + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + for args in [ + vec!["query", "host", "value"], + vec!["query", "--unknown", "value"], + vec!["query", "--host"], + vec!["query", "--host", "127.0.0.1:1", "--host", "127.0.0.1:2"], + ] { + assert_eq!( + ProjectHistoryCliInvocation::from_args(args, query_body()).unwrap_err(), + ApiError::InvalidWirePayload + ); + } + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + "http://tepp.example.test", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE + ], + query_body() + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "localhost:18081", + "--origin", + ORIGIN, + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE + ], + query_body() + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--authorization", + "secret" + ], + query_body() + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + } + + #[test] + fn from_args_refuses_naruon_metrics_and_empty_body() { + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + NARUON_CONSUMER_CODE + ], + query_body() + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + ORIGIN, + "--consumer", + "unpublished" + ], + query_body() + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args(query_args(), r#"{"rmse":1.0}"#).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args(query_args(), "").unwrap_err(), + ApiError::InvalidWirePayload + ); + let injected = + query_body().replace("lineageweave-project-cli-1", r"safe\r\nx-api-key: secret"); + assert_eq!( + ProjectHistoryCliInvocation::from_args(query_args(), injected).unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn compose_is_typed_https_post_without_credentials() { + let invocation = + ProjectHistoryCliInvocation::from_args(query_args(), query_body()).expect("inv"); + let http = compose_project_history_cli_http(&invocation).expect("http"); + assert!(http.starts_with("POST /v1/project-histories HTTP/1.1")); + assert!(http.contains("tepp-consumer: lineageweave")); + assert!(http.contains("idempotency-key: lineageweave-project-cli-1")); + assert!(!http.to_ascii_lowercase().contains("authorization")); + assert!(!http.contains("/analysis-runs")); + assert!(!http.contains("/v1/exports")); + assert!(!http.contains("/v1/temporal-context")); + assert!(!http.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!http.contains("rmse")); + } + + #[test] + fn dispatch_returns_association_only_and_naruon_live_stays_post_only() { + let mut service = AnalysisRunLiveService::new(); + let invocation = + ProjectHistoryCliInvocation::from_args(query_args(), query_body()).expect("inv"); + let got = dispatch_project_history_cli(&mut service, &invocation).expect("dispatch"); + assert_eq!(got.status_code, 200, "{}", got.body); + let stdout = render_project_history_cli_stdout(&invocation, &got).expect("stdout"); + let projection = ProjectHistoryProjection::from_json(&stdout).expect("projection"); + assert_eq!(projection.project_key, "project-acme"); + assert_eq!(projection.focus_event_id, "event-voc"); + assert_eq!(projection.inference_status, "temporal_association_only"); + assert!(!stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("causal_score")); + + let http = compose_project_history_cli_http(&invocation).expect("http"); + let mut naruon = NaruonLiveService::new(); + assert_eq!(naruon.handle_http_request(&http).status_code, 400); + } + + #[test] + fn loopback_http1_refuses_non_post_and_wrong_path() { + let invocation = + ProjectHistoryCliInvocation::from_args(query_args(), query_body()).expect("inv"); + let mut exchange = + lineageweave_project_history_exchange(&invocation.origin, &invocation.request) + .expect("exchange"); + exchange.method = "GET"; + assert_eq!( + loopback_http1_from_project_history_exchange(&exchange, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let collection = ProjectHistoryHttpExchange { + method: "POST", + target_url: "https://tepp.example.test/v1/temporal-context".into(), + headers: exchange.headers.clone(), + body: exchange.body.clone(), + }; + assert_eq!( + loopback_http1_from_project_history_exchange(&collection, &invocation.host) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + + let fresh = lineageweave_project_history_exchange(&invocation.origin, &invocation.request) + .expect("exchange"); + let mut injected = fresh.clone(); + injected.headers[3].1 = "safe\r\nx-api-key: secret".into(); + assert_eq!( + loopback_http1_from_project_history_exchange(&injected, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut extra = fresh; + extra.headers.push(("x-extra".into(), "value".into())); + assert_eq!( + loopback_http1_from_project_history_exchange(&extra, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut duplicate = + lineageweave_project_history_exchange(&invocation.origin, &invocation.request) + .expect("exchange"); + duplicate + .headers + .push(("Content-Type".into(), "application/json".into())); + assert_eq!( + loopback_http1_from_project_history_exchange(&duplicate, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut missing = + lineageweave_project_history_exchange(&invocation.origin, &invocation.request) + .expect("exchange"); + missing.headers.pop(); + assert_eq!( + loopback_http1_from_project_history_exchange(&missing, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut credential = missing.clone(); + credential + .headers + .push(("authorization".into(), "secret".into())); + assert_eq!( + loopback_http1_from_project_history_exchange(&credential, &invocation.host) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + let mut malformed = missing; + malformed.headers.push(("bad name".into(), "value".into())); + assert_eq!( + loopback_http1_from_project_history_exchange(&malformed, &invocation.host).unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn render_refuses_metrics_schema_and_identity_mismatch() { + let invocation = + ProjectHistoryCliInvocation::from_args(query_args(), query_body()).expect("inv"); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut later_cutoff = + crate::project_history_projection(&invocation.request).expect("projection"); + later_cutoff.knowledge_cutoff = "2026-08-20T23:59:59Z".into(); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: later_cutoff.to_json().expect("projection json"), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let mut mismatched = + crate::project_history_projection(&invocation.request).expect("projection"); + mismatched.project_key = "other-project".into(); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: mismatched.to_json().expect("projection json"), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let valid = crate::project_history_projection(&invocation.request) + .expect("projection") + .to_json() + .expect("projection json"); + let mut wrong_focus = invocation.clone(); + wrong_focus.request.focus_event_id = "event-award".into(); + assert_eq!( + render_project_history_cli_stdout( + &wrong_focus, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: valid, + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 202, + reason_phrase: "Accepted", + body: r#"{"error":"pending"}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + super::refuse_metrics_on_project_history_cli_payload("[]").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: r#"{"error":"invalid"}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"inference_status":"temporal_association_only","rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_project_history_cli_stdout( + &invocation, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: format!(r#"{{"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"#), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn execute_over_tcp_and_stdin_reader() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let addr = service.local_addr().expect("addr"); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let mut invocation = + ProjectHistoryCliInvocation::from_args(query_args(), query_body()).expect("inv"); + invocation.host = addr.to_string(); + let response = execute_project_history_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 200, "{}", response.body); + handle.join().expect("join"); + + invocation.host = "127.0.0.1:1".into(); + assert_eq!( + execute_project_history_cli(&invocation).unwrap_err(), + ApiError::InvalidWirePayload + ); + + let parsed = + parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").expect("parse"); + assert_eq!(parsed.status_code, 200); + assert_eq!( + parse_http_response(b"not-http").unwrap_err(), + ApiError::InvalidWirePayload + ); + for response in [ + "HTTP/1.0 200 OK\r\ncontent-length: 2\r\n\r\n{}".to_owned(), + "HTTP/1.1 200 Wrong\r\ncontent-length: 2\r\n\r\n{}".to_owned(), + "HTTP/1.1 200 OK\r\ncontent-length: 1\r\n\r\n{}".to_owned(), + ] { + assert_eq!( + parse_http_response(response.as_bytes()).unwrap_err(), + ApiError::InvalidWirePayload + ); + } + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\ncontent-length: 2\r\n\r\n{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + for response in [ + b"HTTP/1.1 200 OK\r\n: value\r\ncontent-length: 2\r\n\r\n{}".as_slice(), + b"HTTP/1.1 200 OK\r\nx-value: bad\0value\r\ncontent-length: 2\r\n\r\n{}".as_slice(), + b"HTTP/1.1 200 OK\r\nx-value: one\r\nX-Value: two\r\ncontent-length: 2\r\n\r\n{}" + .as_slice(), + ] { + assert_eq!( + parse_http_response(response).unwrap_err(), + ApiError::InvalidWirePayload + ); + } + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\nx-value:\tvalue\r\ncontent-length: 2\r\n\r\n{}" + ) + .expect("tab header") + .status_code, + 200 + ); + let oversized = format!( + "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n", + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT + 1 + ); + assert_eq!( + parse_http_response(oversized.as_bytes()).unwrap_err(), + ApiError::LimitExceeded + ); + let long_header = format!( + "HTTP/1.1 200 OK\r\nx-long: {}\r\ncontent-length: 2\r\n\r\n{{}}", + "x".repeat(NARUON_LIVE_HEADER_BYTE_LIMIT) + ); + assert_eq!( + parse_http_response(long_header.as_bytes()).unwrap_err(), + ApiError::LimitExceeded + ); + let mut many_headers = String::new(); + for index in 0..NARUON_LIVE_HEADER_COUNT_LIMIT { + write!(many_headers, "x-{index}: value\r\n").expect("header"); + } + let crowded = format!("HTTP/1.1 200 OK\r\n{many_headers}content-length: 2\r\n\r\n{{}}"); + assert_eq!( + parse_http_response(crowded.as_bytes()).unwrap_err(), + ApiError::LimitExceeded + ); + assert_eq!(static_reason(200).expect("200"), "OK"); + for (code, reason) in [ + (202, "Accepted"), + (400, "Bad Request"), + (403, "Forbidden"), + (413, "Payload Too Large"), + (422, "Unprocessable Entity"), + ] { + assert_eq!(static_reason(code).expect("known status"), reason); + } + assert_eq!( + static_reason(500).unwrap_err(), + ApiError::InvalidWirePayload + ); + let empty = read_project_history_cli_stdin(true, std::io::empty()).expect("tty"); + assert!(empty.is_empty()); + let piped = + read_project_history_cli_stdin(false, std::io::Cursor::new(b"{}")).expect("piped"); + assert_eq!(piped, "{}"); + let exact = vec![b'x'; DEFAULT_PROJECT_HISTORY_BYTE_LIMIT]; + assert_eq!( + read_project_history_cli_stdin(false, std::io::Cursor::new(exact)) + .expect("bounded stdin") + .len(), + DEFAULT_PROJECT_HISTORY_BYTE_LIMIT + ); + let excess = vec![b'x'; DEFAULT_PROJECT_HISTORY_BYTE_LIMIT + 1]; + assert_eq!( + read_project_history_cli_stdin(false, std::io::Cursor::new(excess)).unwrap_err(), + ApiError::LimitExceeded + ); + } +} diff --git a/crates/tepp_api/tests/project_history_cli_contract.rs b/crates/tepp_api/tests/project_history_cli_contract.rs new file mode 100644 index 000000000..6740078cc --- /dev/null +++ b/crates/tepp_api/tests/project_history_cli_contract.rs @@ -0,0 +1,140 @@ +//! Contract tests for the `LineageWeave` project-history loopback CLI. + +use std::io::Write; +use std::process::{Command, Stdio}; + +use tepp_api::{ + AnalysisRunLiveService, ApiError, LINEAGEWEAVE_CONSUMER_CODE, PROJECT_HISTORY_CONTRACT_VERSION, + ProjectHistoryCliInvocation, ProjectHistoryCliVerb, ProjectHistoryEvent, ProjectHistoryRequest, + compose_project_history_cli_http, +}; + +fn query_body() -> String { + ProjectHistoryRequest { + contract_version: PROJECT_HISTORY_CONTRACT_VERSION, + idempotency_key: "lineageweave-project-cli-contract-1".into(), + tenant_workspace_id: "tenant-demo".into(), + project_key: "project-acme".into(), + project_name: "Acme renewal".into(), + knowledge_cutoff: "2026-08-19T23:59:59Z".into(), + focus_event_id: "event-voc".into(), + events: vec![ProjectHistoryEvent { + event_id: "event-voc".into(), + event_type_code: "voc_received".into(), + event_title: "VOC received".into(), + occurred_at: "2026-07-30T09:00:00Z".into(), + available_at: "2026-07-30T09:00:00Z".into(), + source_post_id: "post-voc".into(), + evidence_text: "evidence for VOC received".into(), + actor_ids: vec!["person-3".into()], + }], + } + .to_json() + .expect("json") +} + +#[test] +fn project_history_cli_is_metric_free_post_without_credentials() { + assert_eq!( + ProjectHistoryCliVerb::parse("query").expect("verb"), + ProjectHistoryCliVerb::Query + ); + let invocation = ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + "https://tepp.example.test", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + ], + query_body(), + ) + .expect("invocation"); + let http = compose_project_history_cli_http(&invocation).expect("http"); + assert!(http.starts_with("POST /v1/project-histories HTTP/1.1")); + assert!(http.contains("tepp-consumer: lineageweave")); + assert!(!http.contains("authorization")); + assert!(!http.contains("tepp.scientific_acceptance.v1")); + assert!(!http.contains("/analysis-runs")); + assert!(!http.contains("/v1/exports")); +} + +#[test] +fn project_history_cli_refuses_non_loopback_unknown_verbs_and_metrics() { + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "8.8.8.8:80", + "--origin", + "https://tepp.example.test" + ], + query_body() + ), + Err(ApiError::AuthorizationDenied) + ); + assert_eq!( + ProjectHistoryCliVerb::parse("cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + ProjectHistoryCliInvocation::from_args( + [ + "query", + "--host", + "127.0.0.1:18081", + "--origin", + "https://tepp.example.test" + ], + r#"{"rmse":1.0}"# + ), + Err(ApiError::InvalidWirePayload) + ); +} + +#[test] +fn project_history_binary_queries_loopback_and_rejects_unknown_verbs() { + let binary = env!("CARGO_BIN_EXE_tepp-project-history"); + let rejected = Command::new(binary).arg("unknown").output().expect("run"); + assert!(!rejected.status.success()); + assert!(!rejected.stderr.is_empty()); + + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let host = service.local_addr().expect("address").to_string(); + let server = std::thread::spawn(move || service.serve_one().expect("serve")); + let mut child = Command::new(binary) + .args([ + "query", + "--host", + &host, + "--origin", + "https://tepp.example.test", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("spawn"); + child + .stdin + .take() + .expect("stdin") + .write_all(query_body().as_bytes()) + .expect("write"); + let output = child.wait_with_output().expect("wait"); + server.join().expect("join"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8(output.stdout) + .expect("utf8") + .contains("temporal_association_only") + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index b76b688e1..0536ad501 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; export retrieval stays a target shape until an executable export route ships. +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; export retrieval stays a target shape until an executable export route ships. Loopback `tepp-project-history query` is the operator-visible client for `POST /v1/project-histories` (ADR 0061); stdout stays metric-free with `inference_status` `temporal_association_only`. ## 2. Contract families diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 2b783c2ab..4c8f5e089 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -57,6 +57,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | 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 | | 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); LineageWeave loopback contracts and request-bound terminal result are composed on the active product branch; production TLS remaining | partial | +| loopback LineageWeave project-history CLI | ADR 0061; ADR 0021/0011; API contract; RFC 9110 | `tepp_api` `tepp-project-history query` CLI against `tepp-loopback` (`POST /v1/project-histories`); metric-free `temporal_association_only` JSON; `tepp.scientific_acceptance.v1` never appears; does not infer causality; naruon refused | active-PR | | executable cutoff-safe analysis runs | ADR 0012/0022; temporal research; API terminal-result contract | `analysis_engine` availability cutoff, snapshot binding, multiple-membership aggregation, digest-bound readiness artifact, and `tepp.trsl_topic_lineage.v1` execution through `topic_measurement`; synthetic recovery plus tamper/non-convergence tests and exact coverage on the active product branch | active-PR | | immutable split/run/reproducibility manifests | ADR 0013; ERD | `tepp_api` reproducibility manifest contract on protected main; `persistence_postgres` append-only SQL insert/lookup for `reproducibility_manifest`, `corpus_split_manifest`, `model_run`, and `model_artifact` (migration `0003`); full physical ERD constraints remaining | partial | | multilingual shared latent semantic space | PRD; ADR 0004; ADR 0020 | `semantic_core` span-grounded units (active-PR); concept dictionary and shared latent estimator remaining | active-PR | diff --git a/docs/adr/0061-project-history-cli.md b/docs/adr/0061-project-history-cli.md new file mode 100644 index 000000000..d25001009 --- /dev/null +++ b/docs/adr/0061-project-history-cli.md @@ -0,0 +1,116 @@ +# ADR 0061 — LineageWeave project-history loopback CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0021 and ADR 0011 for the operator-visible project-history client. Does not supersede ADR 0014 claim-promotion authority. This ADR number is unique on protected main; live vs-main PRs already occupy 0026–0060. + +## Context + +Protected main already serves `POST /v1/project-histories` on +`AnalysisRunLiveService` / `tepp-loopback`, but LineageWeave operators still +had to write raw HTTP/1.1. Duplicating temporal-context CLI (#414), export +CLIs (#410/#417), analysis-run CLIs, GET-by-id, Leiden, Driver p.16, or +GAP-010 Figma/export would collide with live PRs. Naruon is refused on this +adapter; `NaruonLiveService` stays POST-only for analysis-run and export. + +## Decision + +`tepp_api` publishes a loopback-only `tepp-project-history query` verb: + +- `query` mints `lineageweave_project_history_exchange` and renders through + `loopback_http1_from_project_history_exchange` onto spawned `tepp-loopback` + TCP. `--origin` stays the published HTTPS origin; only `--host` is the + loopback bind address. +- Stdin is `ProjectHistoryRequest` JSON. Consumer is `lineageweave` only. +- The idempotency key travels in the typed exchange header from the request + body. HTTP control characters fail closed, and the raw serializer revalidates + the exact four-header set against the typed body. Operators do not pass a + separate credential flag. +- Stdout is the cutoff-safe `ProjectHistoryProjection`. + `inference_status` remains `temporal_association_only`. + `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, and + `causal_score` keys never appear. +- The CLI does not infer causality, mutate TEPP state, or return a completed + psychometric result. +- Non-loopback hosts, `localhost`, credential-shaped flags, unknown verbs, + empty stdin, unpublished consumers, naruon, non-`https` origins, and metric + keys fail closed. +- Stdin and response bodies are bounded by the existing 256 KiB project-history + wire limit. Response headers use the existing loopback header limits; + duplicate framing, transfer encoding, and non-2xx bodies never reach stdout. +- This slice does not implement temporal-context CLI, export CLI, or + analysis-run HTTP. + +## Alternatives considered + +1. **Keep raw HTTP as the only project-history path** — rejected because + operators still guess framing after ADR 0021. +2. **Add `query` onto `tepp-temporal-context`** — rejected because + project-history is a distinct LineageWeave projection, not a temporal-context + verb, and #414 is a live PR. +3. **Open naruon on this adapter** — rejected; `AnalysisRunLiveService` + project-history is LineageWeave-only (ADR 0021). +4. **Return scientific-acceptance on ordered events** — rejected because + project-history bodies must stay metric-free. +5. **Loopback project-history CLI against `tepp-loopback`** — accepted. + +## Consequences + +- Operators can request a cutoff-safe project-history projection without + writing HTTP. +- Project-history stdout cannot be mistaken for a succeeded + scientific-acceptance result or a causal score. +- CLI success is not release evidence and is not an ADR 0014 claim. + +## Failure and recovery + +Non-loopback hosts return authorization denied. Unknown verbs, empty stdin, +credential flags, padded or control-bearing idempotency keys, naruon consumer +codes, and events unavailable at cutoff fail closed. Failures emit the stable, +redacted API error on stderr and never echo an upstream body to stdout. The +in-memory listener is not durable. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Header injection, duplicate headers, unbounded reads, and ambiguous HTTP/1.1 + response framing fail closed before operator output. +- The CLI remains loopback-only. Event identities stay opaque; free-text PII + is not introduced by this client. +- Process exit 0 on query is not measurement evidence and is not a causal + claim. + +## Compatibility and migration + +`POST /v1/analysis-runs`, `POST /v1/exports`, `POST /v1/temporal-context`, and +`tepp-loopback` paths are unchanged. Temporal-context CLI remains #414. + +## Verification + +Falsifiable evidence: + +- CLI query of a cutoff-safe LineageWeave body returns + `temporal_association_only` with no RMSE/bias/coverage/SE-gate/ + `tepp.scientific_acceptance.v1`/`causal_score` keys; +- non-loopback host, `localhost`, credential flags, empty stdin, naruon, + unknown verbs, and metric keys fail closed; +- `NaruonLiveService` still refuses `POST /v1/project-histories`; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review + remain required. + +## Rollback and supersession + +Rollback removes `tepp-project-history`; `POST /v1/project-histories` remains +valid. A superseding ADR is required to persist the registry, bind a public +address, emit scientific-acceptance on project-history, infer causality, open +naruon on this adapter, or treat CLI success as an ADR 0014 claim. + +## Related authority + +- ADR 0021 owns the LineageWeave project-history service boundary. +- ADR 0019 owns symmetric project-history wire-size enforcement. +- ADR 0011 owns standalone/modular HTTP boundaries. +- 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 1254c8079..beaa28193 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -30,6 +30,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0022](0022-deterministic-analysis-run-execution.md) | Deterministic cutoff-safe analysis-run execution | Accepted | active-PR | Closes the first executable product path from accepted run to digest-bound terminal result without claiming estimator authority. | | [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. | +| [0061](0061-project-history-cli.md) | Loopback `tepp-project-history query` is LineageWeave POST /v1/project-histories client | Accepted | active-PR | Complements ADR 0021/0011; does not supersede ADR 0014. Unique on protected main. Does not infer causality. | | [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. | @@ -140,6 +141,7 @@ Use the narrowest owning ADR when decisions overlap: - **accepted-run execution and terminal artifact production:** ADR 0022. - **independent lineage criterion and posterior Project Journey:** ADR 0023. - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. +- **LineageWeave project-history CLI:** ADR 0061. ## Change and supersession rule diff --git a/docs/research/project-history-cli.md b/docs/research/project-history-cli.md new file mode 100644 index 000000000..5b106ef26 --- /dev/null +++ b/docs/research/project-history-cli.md @@ -0,0 +1,57 @@ +# Project-history CLI (doctoring) + +## Scope + +`tepp-project-history query` is the operator-visible client of loopback +`POST /v1/project-histories` on `AnalysisRunLiveService` / `tepp-loopback`. +The CLI mints `lineageweave_project_history_exchange` and renders onto spawned +`tepp-loopback` TCP. HTTP method, path, and header semantics follow current +HTTP semantics (Fielding, Nottingham, & Reschke, 2022). Fail-closed refusal of +non-loopback hosts, unpublished consumers, naruon on this adapter, +review/Copilot/GitHub credential flags, and scientific-authority promotion is +repository contract authority (ADR 0061; ADR 0021; ADR 0011; ADR 0014), not an +RFC inference rule. + +CLI stdout is the cutoff-safe `ProjectHistoryProjection`. +`inference_status` remains `temporal_association_only`. +`tepp.scientific_acceptance.v1` never appears. Process exit 0 is not a +completed temporal model, 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 the enclosed +representation. TEPP maps that processing onto a bounded, cutoff-safe +project-history projection. The RFC does not define psychometric acceptance, +RMSE, causality, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0061-project-history-cli.md` — this client +- `docs/adr/0021-lineageweave-project-history-boundary.md` — HTTP boundary +- `docs/adr/0011-standalone-modular-msa-boundary.md` — modular HTTP boundary +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — CLI + success is not a scientific claim +- `crates/tepp_api/tests/project_history_cli_contract.rs` — fail-closed + project-history CLI proofs + +## Verification + +- `tepp-project-history query` of a cutoff-safe LineageWeave body returns + `temporal_association_only` without RMSE/bias/coverage/SE-gate keys, + `causal_score`, or `tepp.scientific_acceptance.v1`; +- non-loopback hosts, `localhost`, credential flags, empty stdin, naruon, and + unknown verbs fail closed; +- `NaruonLiveService` still refuses `POST /v1/project-histories`. + +## Non-claims + +This slice does not implement temporal-context CLI, export CLI, analysis-run +CLIs, GET-by-id, wait CLI, lookup CLI, persistence, production TLS, Leiden +consensus, GAP-010 Figma/export, causal inference, or an ADR 0014 scientific +claim-promotion package.