From 004a3900540c8bdcee005f5cbcc7cb599b1b5a08 Mon Sep 17 00:00:00 2001 From: felix Date: Sun, 22 Nov 2026 16:24:43 +0000 Subject: [PATCH] atlas(classification): enforce disclosure-context filters at output boundaries (#12404) Implements the #9096 design section 4 disclosure contexts in Atlas search: the destination surface's context ceiling (fleet-internal=local-only, hosted-per-user=personal, public-surface=shareable, local-owner=secret-bearing) intersects the caller's grant ceiling at the final output boundary in atlas-core's run_search_impl, so neither can widen the other and excluded_personal_life content is ineligible in every context. One filter point covers every rendered shape: flat results, grouped sessions (chunks and hit_count), raw branch rows, neighbor expansion (filtered per neighbor classification), --with-message and hydration payloads (withheld outright on public-surface), and get-chunk (context-gated; a withheld chunk reads as not found). Missing/unknown sensitivity labels fail closed to secret-bearing; an absent context fails closed to public-surface (library default), with front-ends stating their surface's context: CLI search defaults fleet-internal, CLI get-chunk defaults local-owner, the service resolves a stated context fail-closed and defaults fleet-internal for its authenticated callers, and the service dedupe/result CacheKey now includes the resolved context so cached payloads cannot cross contexts. SearchRequest gains an additive optional context field. Leak evidence: at base, a stub-backend demonstration served secret-bearing and excluded content at a maximal caller ceiling, leaked a secret-bearing neighbor through --expand, and served an excluded chunk by id. The new crates/atlas-core/tests/disclosure.rs (13 tests) plus disclosure.rs unit/proptests and a server cache-separation test pin the intersection per boundary class; all atlas-core, atlas-proto, and atlas-search suites green (357 tests). Deferred boundaries, filed and enqueued from this slice: Worker (TS) stated context + cache keying -> #12622 (task 21057); legacy Python atlas_search.py parity -> #12623 (task 21058); span-level filtering of full-content payloads -> #12624 (task 21059). The query-trace context field belongs to #9099 per design section 10 and is not built here. --- .../crates/atlas-core/examples/live_smoke.rs | 8 +- .../crates/atlas-core/src/classification.rs | 12 + .../crates/atlas-core/src/disclosure.rs | 292 ++++++++++++++ .../atlas-search/crates/atlas-core/src/lib.rs | 5 +- .../crates/atlas-core/src/search.rs | 237 +++++++++-- .../crates/atlas-core/tests/disclosure.rs | 380 ++++++++++++++++++ .../crates/atlas-core/tests/flags.rs | 12 +- .../crates/atlas-core/tests/parity.rs | 11 +- .../crates/atlas-proto/src/lib.rs | 11 + .../crates/atlas-search/src/main.rs | 52 ++- .../crates/atlas-search/src/server.rs | 114 +++++- .../crates/atlas-search/tests/cli_parity.rs | 12 +- 12 files changed, 1087 insertions(+), 59 deletions(-) create mode 100644 pkgs/atlas-search/crates/atlas-core/src/disclosure.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs diff --git a/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs b/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs index fa96cf395b..5ec6d6276f 100644 --- a/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs +++ b/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs @@ -34,7 +34,8 @@ use std::process::Command; use atlas_core::{ - AtlasEmbedder, DEFAULT_VEC_TABLE, Filters, SearchOptions, TursoBackend, run_search, + AtlasEmbedder, DEFAULT_VEC_TABLE, DisclosureContext, Filters, SearchOptions, TursoBackend, + run_search, }; use serde_json::Value as Json; @@ -106,7 +107,10 @@ fn main() { let mut failures = 0; for q in &questions { - let opts = SearchOptions::new(q.clone()); + let mut opts = SearchOptions::new(q.clone()); + // Live smoke runs as the local operator against the + // Python CLI's surface (#12404). + opts.context = DisclosureContext::LocalOwner; let rust_env = match run_search(&backend, &embedder, &filters, &opts) { Ok(env) => env, Err(e) => { diff --git a/pkgs/atlas-search/crates/atlas-core/src/classification.rs b/pkgs/atlas-search/crates/atlas-core/src/classification.rs index 96e7e6c823..8274bdcbb9 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/classification.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/classification.rs @@ -170,6 +170,18 @@ pub struct EffectiveClassification { } impl EffectiveClassification { + /// Build directly from a resolved sensitivity and exclusion + /// flag, for surfaces whose store carries the legacy label + /// string rather than full classification records (the search + /// detail rows). Composition from records ([`Self::compose`]) + /// remains the rule wherever records exist. + pub fn from_parts(sensitivity: Sensitivity, excluded: bool) -> Self { + Self { + sensitivity, + excluded, + } + } + pub fn compose<'a>(records: impl IntoIterator) -> Self { let mut result = Self { sensitivity: Sensitivity::Shareable, diff --git a/pkgs/atlas-search/crates/atlas-core/src/disclosure.rs b/pkgs/atlas-search/crates/atlas-core/src/disclosure.rs new file mode 100644 index 0000000000..41d9ab1e73 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/disclosure.rs @@ -0,0 +1,292 @@ +//! Disclosure contexts (#12404): the destination-side half of the +//! #9096 classification model (design +//! `doc/2026-11-21T21-32-00Z_design_atlas_classification_model_v1.md` +//! section 4). +//! +//! A caller's ceiling (the [`Filters`](crate::Filters) grant) says +//! what the *searcher* may see. A disclosure context says what the +//! *destination surface* may receive. The two intersect: neither +//! can widen the other. Enforcement lives at the final output +//! boundary in [`crate::search`], applied to every result payload +//! regardless of caller clearance — snippets, metadata, citations, +//! cached payloads, and generated-output references all derive +//! from the one filtered candidate set. +//! +//! The context table (design section 4): +//! +//! | Context | Ceiling | +//! |-------------------|-----------------| +//! | `fleet-internal` | `local-only` | +//! | `hosted-per-user` | `personal` | +//! | `public-surface` | `shareable` | +//! | `local-owner` | `secret-bearing`| +//! +//! `excluded_personal_life` content is ineligible in *every* +//! context, including `local-owner`. `secret-bearing` content +//! under `fleet-internal` requires the dedicated secret path and +//! purpose-bound authorization, neither of which an ordinary +//! search carries — so the fleet-internal ceiling is `local-only`, +//! not `secret-bearing`. +//! +//! Fail-closed rules (design sections 2 and 4): a missing or +//! unrecognized sensitivity value resolves to `secret-bearing`; +//! an absent or unknown disclosure context on an outbound sink +//! resolves to `public-surface`. + +use crate::classification::EffectiveClassification; +use crate::filters::Sensitivity; + +/// The `excluded_personal_life` disposition as it appears in the +/// legacy label strings carried on search detail rows (the +/// disposition is not a sensitivity level; see the design's +/// section 2 table). +pub const EXCLUDED_PERSONAL_LIFE_LABEL: &str = "excluded_personal_life"; + +/// One destination surface's disclosure context. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DisclosureContext { + /// Authenticated fleet task agents, within their grant. + FleetInternal, + /// Hosted per-user surfaces: tenant/owner boundary + grant. + HostedPerUser, + /// Anything posted or transmitted to a public surface. + PublicSurface, + /// The owner's own local surface, via the local secret path. + LocalOwner, +} + +impl DisclosureContext { + /// The design's spelling of this context. + pub fn name(self) -> &'static str { + match self { + Self::FleetInternal => "fleet-internal", + Self::HostedPerUser => "hosted-per-user", + Self::PublicSurface => "public-surface", + Self::LocalOwner => "local-owner", + } + } + + /// Parse the design's spelling; anything else is `None`. + pub fn from_name(name: &str) -> Option { + match name { + "fleet-internal" => Some(Self::FleetInternal), + "hosted-per-user" => Some(Self::HostedPerUser), + "public-surface" => Some(Self::PublicSurface), + "local-owner" => Some(Self::LocalOwner), + _ => None, + } + } + + /// Every context, in the design table's order (for help text + /// and exhaustive tests). + pub fn all() -> [Self; 4] { + [ + Self::FleetInternal, + Self::HostedPerUser, + Self::PublicSurface, + Self::LocalOwner, + ] + } + + /// The maximum sensitivity this context may ever receive + /// (design section 4's table). + pub fn ceiling(self) -> Sensitivity { + match self { + Self::FleetInternal => Sensitivity::LocalOnly, + Self::HostedPerUser => Sensitivity::Personal, + Self::PublicSurface => Sensitivity::Shareable, + Self::LocalOwner => Sensitivity::SecretBearing, + } + } + + /// Resolve the context for an outbound sink: an absent or + /// unknown context fails closed to `public-surface` (design + /// section 4). Interactive local surfaces state their context + /// explicitly instead of relying on this default. + pub fn for_outbound(name: Option<&str>) -> Self { + name.and_then(Self::from_name) + .unwrap_or(Self::PublicSurface) + } + + /// The ceiling a result must satisfy under both the caller's + /// grant and this context: the intersection is the *lower* of + /// the two, so neither side can widen the other. + pub fn effective_ceiling(self, grant: Sensitivity) -> Sensitivity { + grant.min(self.ceiling()) + } + + /// Whether content with this effective classification may be + /// disclosed to this context at all (before the grant is even + /// consulted): excluded content is ineligible in every + /// context, and nothing above the context ceiling may cross. + pub fn permits(self, class: EffectiveClassification) -> bool { + !class.is_excluded() && class.sensitivity <= self.ceiling() + } + + /// Whether content with this effective classification may be + /// served to a caller whose grant ceiling is `grant`, under + /// this context: the full intersection of grant, context + /// ceiling, and exclusion disposition. + pub fn permits_with_grant(self, class: EffectiveClassification, grant: Sensitivity) -> bool { + !class.is_excluded() && class.sensitivity <= self.effective_ceiling(grant) + } +} + +/// The effective classification of one search detail row, from +/// the legacy label string the row carries (`ChunkDetail`'s +/// chunk-or-label sensitivity). Fail-closed, per design +/// sections 2–3: a missing, empty, or unrecognized value is +/// `secret-bearing` (the locked default for unclassified +/// content), and the `excluded_personal_life` label is the +/// exclusion disposition, which is sticky and outranks every +/// sensitivity value. Where full classification records exist, +/// compose them with +/// [`EffectiveClassification::compose`] instead. +pub fn chunk_classification(eff_sensitivity: Option<&str>) -> EffectiveClassification { + match eff_sensitivity { + Some(EXCLUDED_PERSONAL_LIFE_LABEL) => { + EffectiveClassification::from_parts(Sensitivity::SecretBearing, true) + } + Some(name) => EffectiveClassification::from_parts( + Sensitivity::from_name(name).unwrap_or(Sensitivity::SecretBearing), + false, + ), + None => EffectiveClassification::from_parts(Sensitivity::SecretBearing, false), + } +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::{DisclosureContext, chunk_classification}; + use crate::classification::EffectiveClassification; + use crate::filters::Sensitivity; + + const LADDER: [Sensitivity; 4] = [ + Sensitivity::Shareable, + Sensitivity::Personal, + Sensitivity::LocalOnly, + Sensitivity::SecretBearing, + ]; + + #[test] + fn context_table_matches_the_design() { + // Oracle: design section 4's disclosure-context table. + assert_eq!( + DisclosureContext::FleetInternal.ceiling(), + Sensitivity::LocalOnly + ); + assert_eq!( + DisclosureContext::HostedPerUser.ceiling(), + Sensitivity::Personal + ); + assert_eq!( + DisclosureContext::PublicSurface.ceiling(), + Sensitivity::Shareable + ); + assert_eq!( + DisclosureContext::LocalOwner.ceiling(), + Sensitivity::SecretBearing + ); + for ctx in DisclosureContext::all() { + assert_eq!(DisclosureContext::from_name(ctx.name()), Some(ctx)); + } + } + + #[test] + fn absent_or_unknown_context_fails_closed_to_public_surface() { + assert_eq!( + DisclosureContext::for_outbound(None), + DisclosureContext::PublicSurface + ); + assert_eq!( + DisclosureContext::for_outbound(Some("everywhere")), + DisclosureContext::PublicSurface + ); + assert_eq!( + DisclosureContext::for_outbound(Some("")), + DisclosureContext::PublicSurface + ); + assert_eq!( + DisclosureContext::for_outbound(Some("fleet-internal")), + DisclosureContext::FleetInternal + ); + } + + #[test] + fn chunk_classification_is_fail_closed() { + // Oracle: design decisions 2-3 — missing/invalid + // sensitivity takes the most-locked-down value, never + // shareable. + for bad in [None, Some(""), Some("internal"), Some("Shareable")] { + let class = chunk_classification(bad); + assert_eq!(class.sensitivity, Sensitivity::SecretBearing, "{bad:?}"); + assert!(!class.is_excluded(), "{bad:?}"); + } + let excluded = chunk_classification(Some("excluded_personal_life")); + assert!(excluded.is_excluded()); + assert_eq!( + chunk_classification(Some("personal")).sensitivity, + Sensitivity::Personal + ); + } + + #[test] + fn excluded_content_is_ineligible_in_every_context() { + // Oracle: design section 4 — excluded_personal_life is + // ineligible in every context, including local-owner. + let excluded = chunk_classification(Some("excluded_personal_life")); + for ctx in DisclosureContext::all() { + assert!(!ctx.permits(excluded), "{}", ctx.name()); + for grant in LADDER { + assert!(!ctx.permits_with_grant(excluded, grant), "{}", ctx.name()); + } + } + } + + fn context_strategy() -> impl Strategy { + prop_oneof![ + Just(DisclosureContext::FleetInternal), + Just(DisclosureContext::HostedPerUser), + Just(DisclosureContext::PublicSurface), + Just(DisclosureContext::LocalOwner), + ] + } + + fn sensitivity_strategy() -> impl Strategy { + prop_oneof![ + Just(Sensitivity::Shareable), + Just(Sensitivity::Personal), + Just(Sensitivity::LocalOnly), + Just(Sensitivity::SecretBearing), + ] + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn intersection_never_exceeds_either_side( + ctx in context_strategy(), + grant in sensitivity_strategy(), + ) { + let effective = ctx.effective_ceiling(grant); + prop_assert!(effective <= grant); + prop_assert!(effective <= ctx.ceiling()); + prop_assert_eq!(effective, grant.min(ctx.ceiling())); + } + + #[test] + fn permits_with_grant_is_exactly_the_intersection( + ctx in context_strategy(), + grant in sensitivity_strategy(), + sensitivity in sensitivity_strategy(), + excluded in any::(), + ) { + let class = EffectiveClassification::from_parts(sensitivity, excluded); + let expected = !excluded && sensitivity <= grant.min(ctx.ceiling()); + prop_assert_eq!(ctx.permits_with_grant(class, grant), expected); + } + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index ba728901bd..6d5a61d554 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -31,6 +31,7 @@ pub mod aggregate; pub mod backend; pub mod classification; pub mod detect; +pub mod disclosure; pub mod embed; pub mod embed_cache; pub mod error; @@ -67,6 +68,7 @@ pub use detect::{ PathVerdict, PlainTreeOptions, SourceLedger, Verdict, VerdictCounts, default_ledger_path, git_tree_detection, plain_tree_detection, resolve_commit, }; +pub use disclosure::{DisclosureContext, chunk_classification}; pub use embed::{ AtlasEmbedder, DocEmbedder, FixedDocEmbedder, FixedEmbedder, QUERY_PROMPT, QueryEmbedder, }; @@ -105,7 +107,8 @@ pub use owner_inventory::{ }; pub use search::{ BackendBranchExecutor, BranchPoolExecutor, SearchMode, SearchOptions, TraceJob, run_get_chunk, - run_search, run_search_traced, run_search_with_executor, run_search_with_executor_traced, + run_get_chunk_with_context, run_search, run_search_traced, run_search_with_executor, + run_search_with_executor_traced, }; pub use stage::{ REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL, STAGE_V1_TABLES, StagingUnit, diff --git a/pkgs/atlas-search/crates/atlas-core/src/search.rs b/pkgs/atlas-search/crates/atlas-core/src/search.rs index 7037872ea7..6ce0f270c5 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/search.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/search.rs @@ -12,9 +12,10 @@ use atlas_proto::{RawMode, SearchParametersV1}; use serde_json::{Map, Value as Json, json}; use crate::backend::SearchBackend; +use crate::disclosure::{DisclosureContext, chunk_classification}; use crate::embed::QueryEmbedder; use crate::error::{Error, Result}; -use crate::filters::Filters; +use crate::filters::{Filters, Sensitivity}; use crate::fusion::{FusedEntry, fts_match_expr, fuse_with_parameters}; use crate::trace::{TraceContext, TraceSink, build_trace_record, new_query_id}; use crate::types::{BranchPools, BranchQuery, ChunkDetail, DEFAULT_MODEL, VectorBackend, round6}; @@ -81,6 +82,14 @@ pub struct SearchOptions { pub vector_backend: VectorBackend, /// Versioned query-time controls shared with the wire protocol. pub parameters: SearchParametersV1, + /// The disclosure context of the destination surface + /// (#12404, #9096 design section 4). The context ceiling + /// intersects the filters' caller ceiling at the output + /// boundary; neither can widen the other. The default is + /// `public-surface` — fail-closed: a caller that does not + /// state its surface's context gets the strictest outbound + /// treatment. Front-ends state their context explicitly. + pub context: DisclosureContext, } impl Default for SearchOptions { @@ -98,6 +107,7 @@ impl Default for SearchOptions { trunc: 0, vector_backend: VectorBackend::Scan, parameters: SearchParametersV1::default(), + context: DisclosureContext::PublicSurface, } } } @@ -352,13 +362,77 @@ fn run_search_impl( notes.push(n); } + // Disclosure-context enforcement (#12404, #9096 design + // section 4): the caller's ceiling was applied inside the + // branch queries (filter-before-rank); here, at the final + // output boundary, the destination context's ceiling + // intersects it — neither can widen the other, and + // excluded content is ineligible in every context. Every + // rendered shape below (flat, grouped, raw branch rows) + // draws only from `permitted`, and the trace's served set + // is collected from the rendered envelope, so cached and + // paged payloads inherit the same filter. Details are + // resolved for every ranked candidate (the traced path + // already pays this) because a candidate's classification + // is a property of its detail row. + let all_ids: Vec = ranked.iter().map(|e| e.chunk_id).collect(); + let all_details = details_map(backend, &all_ids)?; + let mut permitted: std::collections::HashSet = std::collections::HashSet::new(); + let mut withheld = 0usize; + for e in &ranked { + match all_details.get(&e.chunk_id) { + Some(d) => { + let class = chunk_classification(d.eff_sensitivity.as_deref()); + if opts + .context + .permits_with_grant(class, filters.max_sensitivity) + { + permitted.insert(e.chunk_id); + } else { + withheld += 1; + } + } + // No detail row: the candidate renders nowhere + // (the flat/grouped paths already skip it), and it + // is not a disclosure decision, so it is not + // counted as withheld. + None => {} + } + } + if withheld > 0 { + notes.push(format!( + "disclosure: context {} withheld {} candidate(s) (context ceiling {}, caller ceiling {})", + opts.context.name(), + withheld, + opts.context.ceiling().name(), + filters.max_sensitivity.name(), + )); + } + // Full-content payloads (the parent message, hydration) + // carry text beyond the classified chunk itself; a public + // surface cannot safely filter them at chunk granularity, + // so they are withheld there outright (design section 4: + // "if an output cannot be safely filtered, withhold it"). + let withhold_full_content = opts.context == DisclosureContext::PublicSurface + && (opts.with_message || opts.parameters.hydrate > 0); + if withhold_full_content { + notes.push( + "disclosure: context public-surface withholds full-content message/hydration payloads" + .to_string(), + ); + } + let mut out = if opts.parameters.raw_mode == RawMode::Branches { // Pre-fusion branch rows, exactly as the branches // produced them (design s3.3 --raw=branches): no fusion, - // no grouping, no detail fetch. + // no grouping, no detail fetch beyond the disclosure + // pass above. let mut rows = Vec::new(); for (branch, hits) in [("fts", &pools.fts), ("vector", &pools.vector)] { for (i, hit) in hits.iter().enumerate() { + if !permitted.contains(&hit.chunk_id) { + continue; + } let mut row = Map::new(); row.insert("chunk_id".into(), json!(hit.chunk_id)); row.insert("branch".into(), json!(branch)); @@ -375,20 +449,31 @@ fn run_search_impl( .insert("raw".into(), json!("branches")); env } else if opts.group_by_session && opts.parameters.raw_mode == RawMode::Off { - grouped_output(backend, opts, filters, &ranked, &vec_dist, ¬es)? + grouped_output( + backend, opts, filters, &ranked, &vec_dist, &permitted, ¬es, + )? } else { - let keep = &ranked[..opts.k.min(ranked.len())]; - let ids: Vec = keep.iter().map(|e| e.chunk_id).collect(); - let details = details_map(backend, &ids)?; + // Take the top-k *permitted* candidates: a withheld + // candidate must not shrink the page (the same + // filter-before-serve rule the branch queries apply + // to the caller ceiling). let mut results = Vec::new(); - for e in keep { - let Some(d) = details.get(&e.chunk_id) else { + for e in &ranked { + if results.len() >= opts.k { + break; + } + if !permitted.contains(&e.chunk_id) { + continue; + } + let Some(d) = all_details.get(&e.chunk_id) else { continue; }; - let mut entry = result_entry(backend, opts, e, d, &vec_dist)?; + let mut entry = result_entry(backend, opts, filters.max_sensitivity, e, d, &vec_dist)?; // Hydration: the first `hydrate` RENDERED results - // (details present) gain full content. - if results.len() < opts.parameters.hydrate { + // (details present) gain full content — except on a + // public surface, where full-content payloads are + // withheld outright (see the disclosure pass above). + if !withhold_full_content && results.len() < opts.parameters.hydrate { let hydrated = hydrate_entry(backend, d)?; entry .as_object_mut() @@ -435,9 +520,11 @@ fn run_search_impl( // Trace capture (issue #9973): resolve details for EVERY // pool entrant (not only the served top-k), build the // record, and persist it before the response is released. - // Fail-closed: any failure here fails the search. - let all_ids: Vec = ranked.iter().map(|e| e.chunk_id).collect(); - let details = details_map(backend, &all_ids)?; + // Fail-closed: any failure here fails the search. The + // disclosure pass above already resolved every ranked + // candidate's details; withheld candidates appear in + // the record as considered-but-not-served. + let details = &all_details; let mut served: Vec = Vec::new(); collect_served(out.get("results"), &mut served); let record = build_trace_record( @@ -451,7 +538,7 @@ fn run_search_impl( &pools, &ranked, &vec_dist, - &details, + details, &served, ); job.sink.write_trace(&record)?; @@ -511,13 +598,35 @@ fn hydrate_entry(backend: &dyn SearchBackend, d: &ChunkDetail) -> Result { })) } -/// The Python's `run_get_chunk`: a by-id lookup with NO +/// The Python's `run_get_chunk`: a by-id lookup with NO caller /// sensitivity ceiling (an explicit-id tool, like the Python). +/// The local-owner disclosure context still applies (#12404): +/// its ceiling is `secret-bearing`, so the only content this +/// entry point withholds that the Python served is +/// `excluded_personal_life` content, ineligible in every +/// context (design section 4). pub fn run_get_chunk(backend: &dyn SearchBackend, chunk_id: i64, neighbors: usize) -> Result { + run_get_chunk_with_context(backend, chunk_id, neighbors, DisclosureContext::LocalOwner) +} + +/// `run_get_chunk` under an explicit disclosure context: the +/// chunk itself must be permitted by the context (a withheld +/// chunk reads exactly like a missing one — the lookup must not +/// confirm that classified content exists), and neighbor +/// expansion is filtered by each neighbor's own classification. +pub fn run_get_chunk_with_context( + backend: &dyn SearchBackend, + chunk_id: i64, + neighbors: usize, + context: DisclosureContext, +) -> Result { let details = backend.chunk_details(&[chunk_id])?; let Some(d) = details.iter().find(|d| d.chunk_id == chunk_id) else { return Err(Error::fatal(format!("chunk {chunk_id} not found"))); }; + if !context.permits(chunk_classification(d.eff_sensitivity.as_deref())) { + return Err(Error::fatal(format!("chunk {chunk_id} not found"))); + } let mut msg = Map::new(); msg.insert("id".into(), Json::String(d.message_id.clone())); msg.insert( @@ -535,7 +644,10 @@ pub fn run_get_chunk(backend: &dyn SearchBackend, chunk_id: i64, neighbors: usiz out.insert("session".into(), session_obj(d)); out.insert("session_id".into(), Json::String(d.session_id.clone())); if neighbors > 0 { - out.insert("context".into(), neighbor_map(backend, d, neighbors)?); + out.insert( + "context".into(), + neighbor_map(backend, d, neighbors, context, context.ceiling())?, + ); } let notes = backend.notes(); if !notes.is_empty() { @@ -614,6 +726,7 @@ fn session_obj(d: &ChunkDetail) -> Json { fn result_entry( backend: &dyn SearchBackend, opts: &SearchOptions, + grant: Sensitivity, e: &FusedEntry, d: &ChunkDetail, vec_dist: &HashMap>, @@ -625,7 +738,7 @@ fn result_entry( entry.insert("rank_sources".into(), e.rank_sources_json()); entry.insert("text".into(), Json::String(d.text.clone())); entry.insert("session".into(), session_obj(d)); - entry_chunk_extras(backend, opts, e, d, vec_dist, &mut entry)?; + entry_chunk_extras(backend, opts, grant, e, d, vec_dist, &mut entry)?; Ok(Json::Object(entry)) } @@ -634,6 +747,7 @@ fn result_entry( fn entry_chunk_extras( backend: &dyn SearchBackend, opts: &SearchOptions, + grant: Sensitivity, e: &FusedEntry, d: &ChunkDetail, vec_dist: &HashMap>, @@ -643,22 +757,48 @@ fn entry_chunk_extras( entry.insert("vector_distance".into(), json!(round6(*dist))); } if opts.expand > 0 { - entry.insert("context".into(), neighbor_map(backend, d, opts.expand)?); + entry.insert( + "context".into(), + neighbor_map(backend, d, opts.expand, opts.context, grant)?, + ); } - if opts.with_message { + // The parent message is a full-content payload: it carries + // text beyond the classified chunk, so on a public surface + // it is withheld outright (design section 4). Other + // contexts gate it on the served chunk's own classification + // via the disclosure pass that admitted the chunk. + if opts.with_message && opts.context != DisclosureContext::PublicSurface { entry.insert("message".into(), message_obj(backend, d)?); } Ok(()) } -/// The Python's `neighbor_map`. -fn neighbor_map(backend: &dyn SearchBackend, d: &ChunkDetail, n: usize) -> Result { +/// The Python's `neighbor_map`, with disclosure filtering +/// (#12404): neighbor rows come from a raw adjacency query that +/// carries no classification, so each neighbor's own detail row +/// decides whether its text may cross this boundary. A neighbor +/// with no detail row is withheld (fail-closed). +fn neighbor_map( + backend: &dyn SearchBackend, + d: &ChunkDetail, + n: usize, + context: DisclosureContext, + grant: Sensitivity, +) -> Result { let n = i64::try_from(n) .map_err(|_| Error::fatal("neighbor count does not fit in the backend's signed range"))?; let rows = backend.neighbors(&d.message_id, d.chunk_idx, n)?; + let ids: Vec = rows.iter().map(|r| r.chunk_id).collect(); + let details = details_map(backend, &ids)?; let mut before = Vec::new(); let mut after = Vec::new(); for r in &rows { + let permitted = details.get(&r.chunk_id).is_some_and(|nd| { + context.permits_with_grant(chunk_classification(nd.eff_sensitivity.as_deref()), grant) + }); + if !permitted { + continue; + } let item = json!({"chunk_id": r.chunk_id, "text": r.text}); if r.chunk_idx < d.chunk_idx { before.push(item); @@ -702,6 +842,7 @@ fn grouped_output( filters: &Filters, ranked: &[FusedEntry], vec_dist: &HashMap>, + permitted: &std::collections::HashSet, notes: &[String], ) -> Result { // The consideration window is k * 10, but k is unbounded at @@ -719,6 +860,11 @@ fn grouped_output( let mut order: Vec = Vec::new(); let mut groups: HashMap = HashMap::new(); for e in consideration { + // Disclosure pass (#12404): a withheld candidate + // contributes neither a chunk nor a hit_count. + if !permitted.contains(&e.chunk_id) { + continue; + } let Some(d) = details.get(&e.chunk_id) else { continue; }; @@ -763,7 +909,15 @@ fn grouped_output( ce.insert("score".into(), json!(round6(e.score))); ce.insert("rank_sources".into(), e.rank_sources_json()); ce.insert("text".into(), Json::String(d.text.clone())); - entry_chunk_extras(backend, opts, e, d, vec_dist, &mut ce)?; + entry_chunk_extras( + backend, + opts, + filters.max_sensitivity, + e, + d, + vec_dist, + &mut ce, + )?; chunks.push(Json::Object(ce)); } let mut entry = Map::new(); @@ -877,10 +1031,22 @@ mod trace_tests { } } + /// The local operator's maximal grant: the stub chunks' + /// non-ladder labels fail closed to secret-bearing under + /// the disclosure pass, so the harness's ceiling must be + /// secret-bearing for the chunks to be servable at all. + fn local_filters() -> Filters { + Filters::new(vec![], vec![], vec![], vec![], "secret-bearing", None, None).expect("filters") + } + fn fts_opts(k: usize) -> SearchOptions { SearchOptions { mode: SearchMode::Fts, k, + // The harness models the local operator surface; + // its stub labels are non-ladder values, which the + // disclosure pass fail-closes to secret-bearing. + context: DisclosureContext::LocalOwner, ..SearchOptions::new("backup database") } } @@ -892,7 +1058,7 @@ mod trace_tests { let out = run_search_traced( &StubBackend, &StubEmbedder, - &Filters::default(), + &local_filters(), &fts_opts(1), &sink, ctx, @@ -929,13 +1095,8 @@ mod trace_tests { assert_eq!(unserved["stages"]["merge"]["rank_after_fusion"], 3); // Ranking behaviour unchanged: the untraced envelope is the // traced envelope minus query_id. - let plain = run_search( - &StubBackend, - &StubEmbedder, - &Filters::default(), - &fts_opts(1), - ) - .unwrap(); + let plain = + run_search(&StubBackend, &StubEmbedder, &local_filters(), &fts_opts(1)).unwrap(); let mut stripped = out.clone(); stripped.as_object_mut().unwrap().remove("query_id"); assert_eq!(stripped, plain); @@ -949,7 +1110,7 @@ mod trace_tests { let err = run_search_traced( &StubBackend, &StubEmbedder, - &Filters::default(), + &local_filters(), &fts_opts(2), &FailSink, TraceContext::new("cli", "user", "test"), @@ -1060,10 +1221,18 @@ mod jaccard_tests { } } + /// As in trace_tests: maximal local grant, because the + /// stub labels fail closed to secret-bearing. + fn local_filters() -> Filters { + Filters::new(vec![], vec![], vec![], vec![], "secret-bearing", None, None).expect("filters") + } + fn opts(depth: usize) -> SearchOptions { let mut o = SearchOptions { mode: SearchMode::Fts, k: 3, + // Local operator surface, as in trace_tests above. + context: DisclosureContext::LocalOwner, ..SearchOptions::new(PASSAGE) }; o.parameters.jaccard_depth = depth; @@ -1083,12 +1252,12 @@ mod jaccard_tests { fn rescore_promotes_the_pasted_passage_end_to_end() { // Off (the production default): fused order stands, the // topical chunk leads. - let off = run_search(&JaccardStub, &StubEmbedder, &Filters::default(), &opts(0)).unwrap(); + let off = run_search(&JaccardStub, &StubEmbedder, &local_filters(), &opts(0)).unwrap(); assert_eq!(result_ids(&off)[0], 1); // On: the near-exact tier promotes the quoted passage itself // to rank 1, and the envelope notes the rescore. - let on = run_search(&JaccardStub, &StubEmbedder, &Filters::default(), &opts(100)).unwrap(); + let on = run_search(&JaccardStub, &StubEmbedder, &local_filters(), &opts(100)).unwrap(); assert_eq!(result_ids(&on)[0], 2); let notes = on["notes"].to_string(); assert!(notes.contains("jaccard rescore"), "{notes}"); diff --git a/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs new file mode 100644 index 0000000000..a7c665c765 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs @@ -0,0 +1,380 @@ +//! Disclosure-context leak tests (#12404, #9096 design +//! section 4). Every test runs the real runner over a fake +//! backend whose branch pool deliberately contains content of +//! every classification — the stub does not pre-filter, so +//! anything withheld was withheld by the output-boundary +//! disclosure pass, and anything served crossed it. The oracle +//! is the design's context table: +//! +//! fleet-internal -> local-only ceiling +//! hosted-per-user -> personal ceiling +//! public-surface -> shareable ceiling +//! local-owner -> secret-bearing ceiling +//! +//! intersected with the caller's grant ceiling, with +//! `excluded_personal_life` ineligible in every context and +//! missing/unknown sensitivity labels fail-closed to +//! secret-bearing. + +use atlas_core::backend::SearchBackend; +use atlas_core::embed::QueryEmbedder; +use atlas_core::error::Result; +use atlas_core::filters::Filters; +use atlas_core::types::{ + BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, +}; +use atlas_core::{ + DisclosureContext, SearchMode, SearchOptions, run_get_chunk_with_context, run_search, +}; +use atlas_proto::RawMode; +use serde_json::Value as Json; + +/// (chunk_id, label, text, session) +const CORPUS: [(i64, Option<&str>, &str, &str); 7] = [ + (1, Some("shareable"), "shareable deployment notes", "s1"), + (2, Some("personal"), "personal project journal", "s1"), + (3, Some("local-only"), "local-only homelab runbook", "s2"), + (4, Some("secret-bearing"), "SECRET production API key", "s1"), + ( + 5, + Some("excluded_personal_life"), + "personal-life diary entry", + "s2", + ), + (6, None, "unlabeled scratch note", "s2"), + (7, Some("internal"), "mislabeled ops note", "s2"), +]; + +struct LeakBackend; + +fn detail(id: i64) -> ChunkDetail { + let (_, label, text, session) = CORPUS + .iter() + .find(|(cid, _, _, _)| *cid == id) + .unwrap_or_else(|| panic!("unknown chunk {id}")); + ChunkDetail { + chunk_id: id, + text: text.to_string(), + // Chunk 1 sits in message m1 at index 1; its message + // also holds chunks 2 (index 2) and 4 (index 4), which + // the neighbors stub below serves as its context. + chunk_idx: id, + message_id: if id == 1 || id == 2 || id == 4 { + "m1".to_string() + } else { + format!("m{id}") + }, + m_role: Some("user".to_string()), + session_id: session.to_string(), + s_title: Some("session".to_string()), + s_client: None, + s_created_at: None, + l_kind: None, + l_topics: None, + l_projects: None, + eff_sensitivity: label.map(str::to_string), + } +} + +impl SearchBackend for LeakBackend { + fn name(&self) -> &'static str { + "fake" + } + fn vec_table(&self) -> &str { + "vec_chunks" + } + fn notes(&self) -> Vec { + Vec::new() + } + fn branch_pools(&self, _q: &BranchQuery, _f: &Filters) -> Result { + // No filter-before-rank here on purpose: the pool is + // the whole corpus, so the boundary pass is the only + // thing that can withhold a candidate. + Ok(BranchPools { + fts: CORPUS + .iter() + .map(|(chunk_id, _, _, _)| BranchHit { + chunk_id: *chunk_id, + dist: None, + }) + .collect(), + vector: Vec::new(), + candidate_models: Default::default(), + }) + } + fn chunk_details(&self, ids: &[i64]) -> Result> { + Ok(ids.iter().map(|&id| detail(id)).collect()) + } + fn neighbors(&self, message_id: &str, _idx: i64, _n: i64) -> Result> { + if message_id != "m1" { + return Ok(Vec::new()); + } + Ok([2, 4] + .iter() + .map(|&id| NeighborRow { + chunk_id: id, + chunk_idx: id, + text: detail(id).text, + }) + .collect()) + } + fn message(&self, message_id: &str) -> Result> { + Ok(Some(MessageRow { + id: message_id.to_string(), + role: Some("user".to_string()), + text: format!("FULL MESSAGE TEXT of {message_id}, beyond any single chunk"), + })) + } +} + +struct FakeEmbedder; + +impl QueryEmbedder for FakeEmbedder { + fn embed_query(&self, _text: &str, _trunc: usize) -> Result> { + Ok(vec![0.0; 4]) + } +} + +fn filters(ceiling: &str) -> Filters { + Filters::new(vec![], vec![], vec![], vec![], ceiling, None, None).expect("filters") +} + +fn search(context: DisclosureContext, ceiling: &str, tweak: impl Fn(&mut SearchOptions)) -> Json { + let mut o = SearchOptions::new("deployment"); + o.mode = SearchMode::Fts; + o.k = 10; + o.context = context; + tweak(&mut o); + run_search(&LeakBackend, &FakeEmbedder, &filters(ceiling), &o).expect("search") +} + +fn served_ids(out: &Json) -> Vec { + out["results"] + .as_array() + .expect("results array") + .iter() + .map(|r| r["chunk_id"].as_i64().expect("chunk id")) + .collect() +} + +#[test] +fn public_surface_filters_even_a_fully_cleared_caller() { + // The packet's headline case: caller clearance is maximal, + // the destination is public — only shareable content may + // cross, in ANY field of the envelope. + let out = search(DisclosureContext::PublicSurface, "secret-bearing", |_| {}); + assert_eq!(served_ids(&out), vec![1]); + let whole = out.to_string(); + for leaked in [ + "personal project journal", + "local-only homelab runbook", + "SECRET production API key", + "personal-life diary entry", + "unlabeled scratch note", + "mislabeled ops note", + ] { + assert!( + !whole.contains(leaked), + "envelope leaked {leaked:?}: {whole}" + ); + } + // The withholding is on the record, not silent. + assert!( + out["notes"] + .as_array() + .expect("notes") + .iter() + .any(|n| n.as_str().unwrap_or("").contains("public-surface")), + "notes record the disclosure decision: {out}" + ); +} + +#[test] +fn fleet_internal_withholds_secret_bearing_from_a_cleared_caller() { + // fleet-internal's ceiling is local-only: secret-bearing + // content needs the dedicated secret path, which an + // ordinary search is not. + let out = search(DisclosureContext::FleetInternal, "secret-bearing", |_| {}); + assert_eq!(served_ids(&out), vec![1, 2, 3]); +} + +#[test] +fn hosted_context_narrows_a_wider_grant() { + let out = search(DisclosureContext::HostedPerUser, "secret-bearing", |_| {}); + assert_eq!(served_ids(&out), vec![1, 2]); +} + +#[test] +fn context_never_widens_a_narrower_grant() { + // The intersection is symmetric: the widest context with a + // personal grant still serves only personal-and-below. + let out = search(DisclosureContext::LocalOwner, "personal", |_| {}); + assert_eq!(served_ids(&out), vec![1, 2]); +} + +#[test] +fn excluded_content_is_ineligible_in_every_context() { + for context in DisclosureContext::all() { + let out = search(context, "secret-bearing", |_| {}); + assert!( + !served_ids(&out).contains(&5), + "{} served the excluded chunk", + context.name() + ); + assert!( + !out.to_string().contains("personal-life diary entry"), + "{} leaked the excluded chunk's text", + context.name() + ); + } +} + +#[test] +fn missing_and_unknown_labels_fail_closed_to_secret_bearing() { + // Chunks 6 (no label) and 7 (non-ladder label) classify as + // secret-bearing: servable only where secret-bearing is. + let owner = search(DisclosureContext::LocalOwner, "secret-bearing", |_| {}); + assert!(served_ids(&owner).contains(&6)); + assert!(served_ids(&owner).contains(&7)); + let public = search(DisclosureContext::PublicSurface, "secret-bearing", |_| {}); + assert!(!served_ids(&public).contains(&6)); + assert!(!served_ids(&public).contains(&7)); + let fleet = search(DisclosureContext::FleetInternal, "secret-bearing", |_| {}); + assert!(!served_ids(&fleet).contains(&6)); + assert!(!served_ids(&fleet).contains(&7)); +} + +#[test] +fn unstated_context_defaults_to_public_surface() { + // The library default is fail-closed: a caller that never + // states a context gets the strictest outbound treatment. + let mut o = SearchOptions::new("deployment"); + o.mode = SearchMode::Fts; + o.k = 10; + let out = + run_search(&LeakBackend, &FakeEmbedder, &filters("secret-bearing"), &o).expect("search"); + assert_eq!(served_ids(&out), vec![1]); +} + +#[test] +fn grouped_output_counts_only_permitted_hits() { + let out = search(DisclosureContext::FleetInternal, "secret-bearing", |o| { + o.group_by_session = true + }); + let groups = out["results"].as_array().expect("groups"); + let s1 = groups + .iter() + .find(|g| g["session_id"] == "s1") + .expect("s1 group"); + // s1 holds chunks 1, 2, 4; chunk 4 (secret-bearing) is + // withheld, so neither the chunks nor the hit_count may + // reflect it — a count is metadata, and metadata is covered. + assert_eq!(s1["hit_count"], 2); + let chunk_ids: Vec = s1["chunks"] + .as_array() + .expect("chunks") + .iter() + .map(|c| c["chunk_id"].as_i64().unwrap()) + .collect(); + assert_eq!(chunk_ids, vec![1, 2]); + assert!(!out.to_string().contains("SECRET production API key")); +} + +#[test] +fn raw_branch_rows_are_filtered() { + let out = search(DisclosureContext::PublicSurface, "secret-bearing", |o| { + o.parameters.raw_mode = RawMode::Branches + }); + assert_eq!(served_ids(&out), vec![1]); + assert!(!out.to_string().contains("SECRET production API key")); + assert!(!out.to_string().contains("personal-life diary entry")); +} + +#[test] +fn expand_drops_neighbors_above_the_intersection() { + // Chunk 1's message-mates are chunk 2 (personal) and chunk + // 4 (secret-bearing). Expansion is a boundary too. + let after_texts = |context: DisclosureContext| -> Vec { + let out = search(context, "secret-bearing", |o| { + o.k = 1; + o.expand = 2; + }); + out["results"][0]["context"]["after"] + .as_array() + .expect("after neighbors") + .iter() + .map(|n| n["text"].as_str().unwrap_or("").to_string()) + .collect() + }; + let fleet = after_texts(DisclosureContext::FleetInternal); + assert!(fleet.iter().any(|t| t.contains("personal project journal"))); + assert!(!fleet.iter().any(|t| t.contains("SECRET"))); + let public = after_texts(DisclosureContext::PublicSurface); + assert!( + public.is_empty(), + "public expand served neighbors: {public:?}" + ); + let owner = after_texts(DisclosureContext::LocalOwner); + assert!( + owner + .iter() + .any(|t| t.contains("SECRET production API key")) + ); +} + +#[test] +fn get_chunk_gates_on_context_and_never_serves_excluded() { + // Excluded: not found even for the owner — and the error is + // the same shape as a missing chunk, so the lookup cannot + // confirm the content exists. + let err = run_get_chunk_with_context(&LeakBackend, 5, 0, DisclosureContext::LocalOwner) + .expect_err("excluded chunk must not be served"); + assert_eq!(err.to_string(), "chunk 5 not found"); + // Secret-bearing: served to the owner, withheld publicly. + let owner = run_get_chunk_with_context(&LeakBackend, 4, 0, DisclosureContext::LocalOwner) + .expect("owner get-chunk"); + assert_eq!(owner["text"], "SECRET production API key"); + let err = run_get_chunk_with_context(&LeakBackend, 4, 0, DisclosureContext::PublicSurface) + .expect_err("secret chunk must not cross to a public surface"); + assert_eq!(err.to_string(), "chunk 4 not found"); + // Shareable crosses everywhere. + let public = run_get_chunk_with_context(&LeakBackend, 1, 0, DisclosureContext::PublicSurface) + .expect("public get-chunk"); + assert_eq!(public["text"], "shareable deployment notes"); +} + +#[test] +fn get_chunk_neighbors_are_filtered() { + let out = run_get_chunk_with_context(&LeakBackend, 1, 2, DisclosureContext::FleetInternal) + .expect("get-chunk"); + let after = out["context"]["after"].as_array().expect("after"); + assert_eq!(after.len(), 1); + assert_eq!(after[0]["chunk_id"], 2); +} + +#[test] +fn public_surface_withholds_full_content_payloads() { + // --with-message and hydration attach text beyond the + // classified chunk; a public surface cannot filter them at + // chunk granularity, so they are withheld outright while + // the chunk's own (shareable) text still serves. + let out = search(DisclosureContext::PublicSurface, "secret-bearing", |o| { + o.with_message = true; + o.parameters.hydrate = 1; + }); + let entry = &out["results"][0]; + assert_eq!(entry["text"], "shareable deployment notes"); + assert!(entry.get("message").is_none(), "message leaked: {entry}"); + assert!(entry.get("hydrated").is_none(), "hydration leaked: {entry}"); + assert!(!out.to_string().contains("FULL MESSAGE TEXT")); + // The same request on a fleet-internal surface keeps the + // payloads: the withholding is the context's, not the + // feature's. + let fleet = search(DisclosureContext::FleetInternal, "secret-bearing", |o| { + o.with_message = true; + o.parameters.hydrate = 1; + }); + let entry = &fleet["results"][0]; + assert!(entry.get("message").is_some()); + assert!(entry.get("hydrated").is_some()); +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/flags.rs b/pkgs/atlas-search/crates/atlas-core/tests/flags.rs index 2dd17cac92..d1f0c11838 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/flags.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/flags.rs @@ -11,7 +11,7 @@ use atlas_core::filters::Filters; use atlas_core::types::{ BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, }; -use atlas_core::{SearchMode, SearchOptions, run_search}; +use atlas_core::{DisclosureContext, SearchMode, SearchOptions, run_search}; use atlas_proto::RawMode; use serde_json::Value as Json; @@ -56,7 +56,11 @@ impl SearchBackend for FakeBackend { l_kind: None, l_topics: None, l_projects: None, - eff_sensitivity: None, + // Labeled personal: an unlabeled row now + // fail-closes to secret-bearing at the + // disclosure boundary (#12404), which would + // leave these flag tests rendering nothing. + eff_sensitivity: Some("personal".to_string()), }) .collect()) } @@ -83,6 +87,10 @@ impl QueryEmbedder for FakeEmbedder { fn opts() -> SearchOptions { let mut o = SearchOptions::new("atlas"); o.mode = SearchMode::Fts; + // The harness models the local operator surface (the + // Python-CLI shape these flag tests pin), so it states the + // local-owner disclosure context explicitly (#12404). + o.context = DisclosureContext::LocalOwner; o } diff --git a/pkgs/atlas-search/crates/atlas-core/tests/parity.rs b/pkgs/atlas-search/crates/atlas-core/tests/parity.rs index cd4ea49efc..9cf7942bd0 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/parity.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/parity.rs @@ -30,8 +30,8 @@ use atlas_core::filters::{Filters, TURSO_SHAPE, branch_queries}; use atlas_core::turso::{PipelineTransport, TursoBackend}; use atlas_core::types::{Row, Stmt, Value}; use atlas_core::{ - DEFAULT_VEC_TABLE, FixedEmbedder, LocalBackend, SearchMode, SearchOptions, VectorBackend, - run_get_chunk, run_search, + DEFAULT_VEC_TABLE, DisclosureContext, FixedEmbedder, LocalBackend, SearchMode, SearchOptions, + VectorBackend, run_get_chunk, run_search, }; use serde_json::Value as Json; @@ -125,6 +125,9 @@ fn dns_config_source_is_retrievable_by_vector_search_fixture() { let mut options = SearchOptions::new(query); options.mode = SearchMode::Vector; options.k = 1; + // Parity harnesses model the local Python CLI surface: + // state its local-owner disclosure context (#12404). + options.context = DisclosureContext::LocalOwner; let got = run_search( &be, &FixedEmbedder { raw: query_vector }, @@ -173,6 +176,9 @@ fn default_filters() -> Filters { fn case_request(name: &str) -> (SearchOptions, Filters) { let mut o = SearchOptions::new("how do we back up the database"); + // The recorded Python envelopes come from the local CLI: + // state the local-owner disclosure context (#12404). + o.context = DisclosureContext::LocalOwner; let f = match name { "hybrid_default" => default_filters(), "hybrid_secret_ceiling" => filters(&[], &[], &[], &[], "secret-bearing", None, None), @@ -275,6 +281,7 @@ fn grouped_wrap_range_k_considers_all_candidates() { let embedder = FixedEmbedder { raw: qvec_raw }; let run = |k: usize| { let mut o = SearchOptions::new("how do we back up the database"); + o.context = DisclosureContext::LocalOwner; o.group_by_session = true; o.pool = 2; o.k = k; diff --git a/pkgs/atlas-search/crates/atlas-proto/src/lib.rs b/pkgs/atlas-search/crates/atlas-proto/src/lib.rs index 98bcc3f863..7061b97f7f 100644 --- a/pkgs/atlas-search/crates/atlas-proto/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-proto/src/lib.rs @@ -527,6 +527,16 @@ pub struct SearchRequest { /// page size on each results request. #[serde(default, skip_serializing_if = "Option::is_none")] pub page_limit: Option, + /// The disclosure context of the destination surface the + /// results are bound for (#12404, #9096 design section 4): + /// one of `fleet-internal`, `hosted-per-user`, + /// `public-surface`, `local-owner`. The context ceiling + /// intersects the (clamped) caller ceiling at the output + /// boundary. Additive and optional: an absent or unknown + /// value fails closed per the receiving surface's rule — + /// atlas-core's default is `public-surface`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, } impl Default for SearchRequest { @@ -547,6 +557,7 @@ impl Default for SearchRequest { trunc: 0, vector_backend: VectorBackend::default(), page_limit: None, + context: None, } } } diff --git a/pkgs/atlas-search/crates/atlas-search/src/main.rs b/pkgs/atlas-search/crates/atlas-search/src/main.rs index a3b0990b5f..d81c26edcd 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/main.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/main.rs @@ -31,13 +31,14 @@ use atlas_core::filters::{Filters, split_csv}; use atlas_core::shards::{ShardedBackend, TierCeiling, open_from_spec}; use atlas_core::turso::{TURSO_HOST, resolve_turso_token}; use atlas_core::{ - AtlasEmbedder, CachingEmbedder, Error as CoreError, FeedbackInput, FixedEmbedder, - JsonlFeedbackSink, JsonlTraceSink, LocalBackend, QueryEmbedder, QueryEmbeddingCache, - SearchBackend, SearchMode, SearchOptions, TraceContext, TraceDocument, TursoBackend, - VectorBackend, Vote, aggregate_traces, feedback_for, ingest_traces, load_feedback_dir, - load_feedback_refs, load_feedback_votes, load_query_feedback_votes, load_query_requesters, - normalise_records, record_feedback, run_get_chunk, run_retention, run_search_traced, - search_traces, valid_civil_date, weekly_report, write_normalised, write_report, + AtlasEmbedder, CachingEmbedder, DisclosureContext, Error as CoreError, FeedbackInput, + FixedEmbedder, JsonlFeedbackSink, JsonlTraceSink, LocalBackend, QueryEmbedder, + QueryEmbeddingCache, SearchBackend, SearchMode, SearchOptions, TraceContext, TraceDocument, + TursoBackend, VectorBackend, Vote, aggregate_traces, feedback_for, ingest_traces, + load_feedback_dir, load_feedback_refs, load_feedback_votes, load_query_feedback_votes, + load_query_requesters, normalise_records, record_feedback, run_get_chunk_with_context, + run_retention, run_search_traced, search_traces, valid_civil_date, weekly_report, + write_normalised, write_report, }; use atlas_proto::{ FilterSpec, QueryVariant, SearchMode as ProtoSearchMode, SearchParametersV1, SearchRequest, @@ -365,6 +366,9 @@ struct SearchArgs { /// ceiling in shareable CliError { } } +/// Resolve a `--context` value (#12404). An unknown context is +/// a usage error (exit 2), never a silent default: the caller +/// stated a destination, and guessing at it could widen +/// disclosure. (The wire protocol's absent/unknown rule — +/// fail closed to public-surface — applies to requests that +/// arrive without a stated context, not to a CLI flag the user +/// typed.) +fn parse_context(value: &str) -> Result { + DisclosureContext::from_name(value).ok_or_else(|| { + ( + 2, + format!( + "invalid --context {value:?}: expected one of {}", + DisclosureContext::all() + .iter() + .map(|c| c.name()) + .collect::>() + .join(", ") + ), + ) + }) +} + /// get-chunk's not-found is the Python's one `die(..., code=1)`. fn map_get_chunk_err(e: CoreError, chunk_id: i64) -> CliError { if let CoreError::Fatal(m) = &e @@ -746,6 +776,7 @@ fn proto_search_request(args: &SearchArgs) -> SearchRequest { VectorBackendChoice::IndexFixed => ProtoVectorBackend::IndexFixed, }, page_limit: None, + context: Some(args.context.clone()), } } @@ -899,6 +930,9 @@ fn cmd_search(args: SearchArgs) -> Result<(), CliError> { parameters_from_args(&args) .validate(expand) .map_err(|m| (2, m))?; + // The disclosure context validates up front too (#12404), + // so a bad value fails identically on every path. + let context = parse_context(&args.context)?; let mut note: Option = None; // The shard fan-out is standalone-only: the service does not // honor it yet, so a via-service answer would silently come @@ -960,6 +994,7 @@ fn cmd_search(args: SearchArgs) -> Result<(), CliError> { VectorBackendChoice::IndexFixed => VectorBackend::IndexFixed, }, parameters: parameters_from_args(&args), + context, }; // Trace capture (issue #9973): every executed search persists // an atlas-query-trace/v1 record and returns its query_id in @@ -985,11 +1020,12 @@ fn cmd_search(args: SearchArgs) -> Result<(), CliError> { fn cmd_get_chunk(args: GetChunkArgs) -> Result<(), CliError> { let neighbors = count("--neighbors", args.neighbors, 0, Some(100))?; + let context = parse_context(&args.context)?; let note = via_service_note_get_chunk(&args.backend); // The Python's get-chunk takes no vector args: pick_backend // sees the defaults (getattr fallbacks in its main()). let backend = pick_backend(&args.backend, atlas_core::DEFAULT_VEC_TABLE, 0)?; - let mut out = run_get_chunk(backend.as_ref(), args.chunk_id, neighbors) + let mut out = run_get_chunk_with_context(backend.as_ref(), args.chunk_id, neighbors, context) .map_err(|e| map_get_chunk_err(e, args.chunk_id))?; if let Some(note) = note { push_note(&mut out, note); diff --git a/pkgs/atlas-search/crates/atlas-search/src/server.rs b/pkgs/atlas-search/crates/atlas-search/src/server.rs index a017258fd8..d84fb70a55 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/server.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/server.rs @@ -29,10 +29,11 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use atlas_core::types::BranchPools; use atlas_core::{ - BranchPoolExecutor, BranchQuery, Error as CoreError, Filters, JsonlFeedbackSink, - JsonlTraceSink, QueryEmbedder, SearchBackend, SearchMode as CoreSearchMode, SearchOptions, - Sensitivity as CoreSensitivity, TraceContext, VectorBackend as CoreVectorBackend, feedback_for, - load_feedback_dir, record_feedback, run_get_chunk, run_search_with_executor_traced, + BranchPoolExecutor, BranchQuery, DisclosureContext, Error as CoreError, Filters, + JsonlFeedbackSink, JsonlTraceSink, QueryEmbedder, SearchBackend, SearchMode as CoreSearchMode, + SearchOptions, Sensitivity as CoreSensitivity, TraceContext, + VectorBackend as CoreVectorBackend, chunk_classification, feedback_for, load_feedback_dir, + record_feedback, run_get_chunk, run_search_with_executor_traced, }; use atlas_proto::{ BranchState, BranchStates, EmbedRequest, EmbedResponse, ErrorResponse, HealthResponse, @@ -43,6 +44,22 @@ use atlas_proto::{ use serde::Deserialize; use serde_json::{Value as Json, json}; +/// The disclosure context a service request runs under +/// (#12404, #9096 design section 4): a stated context resolves +/// fail-closed — an unknown value means `public-surface` — and +/// an unstated one takes this surface's stated default. The +/// service's callers are authenticated fleet surfaces (the job +/// API requires a client credential), so the default is +/// `fleet-internal`; a caller preparing output for any other +/// destination states that destination's context, and sinks +/// beyond this service apply their own. +fn request_context(req: &SearchRequest) -> DisclosureContext { + match req.context.as_deref() { + Some(name) => DisclosureContext::for_outbound(Some(name)), + None => DisclosureContext::FleetInternal, + } +} + // -------------------------------------------------------------- time ---- fn now_ms() -> u64 { @@ -697,6 +714,7 @@ where trunc: request.trunc, vector_backend: core_vector_backend(request.vector_backend), parameters: request.parameters.clone(), + context: request_context(request), }; let executor = ConcurrentBranchExecutor { backend: self.backend.as_ref(), @@ -745,7 +763,13 @@ where .and_then(CoreSensitivity::from_name) .map(|s| s <= core_sensitivity(ceiling)) .unwrap_or(false); - if !allowed { + // Excluded content (#12404): `excluded_personal_life` + // is ineligible in every disclosure context. The label + // is not a ladder value, so the check above already + // refuses it; this states the rule explicitly so it + // survives any change to the label mapping. + let excluded = chunk_classification(detail.eff_sensitivity.as_deref()).is_excluded(); + if !allowed || excluded { return Err(not_found()); } run_get_chunk(self.backend.as_ref(), chunk_id, neighbors) @@ -951,11 +975,13 @@ where // (query, mode, k, pool, group_by_session, expand, with_message, // model, embedder, trunc, vector_backend, // kind[], topic[], project[], client[], since, until, -// effective_ceiling) +// effective_ceiling, disclosure_context) // // Exact-key sharing only: the effective ceiling is IN the key, so // a lower-ceiling request can never be served from a -// higher-ceiling entry; filters are in the key, so a filtered +// higher-ceiling entry; the disclosure context is in the key for +// the same reason (#12404) — a payload filtered for one +// destination surface is never served to another; filters are in the key, so a filtered // request is never answered by subsetting an unfiltered ranking // (or vice versa). An identical submit while a matching // computation is queued/running COALESCES onto it (no second @@ -997,6 +1023,11 @@ struct CacheKey { since: Option, until: Option, effective_ceiling: ProtoSensitivity, + /// The resolved disclosure context (#12404): cached and + /// coalesced payloads are context-filtered, so the context + /// is part of the effective request exactly like the + /// ceiling. + context: DisclosureContext, } impl CacheKey { @@ -1042,6 +1073,7 @@ impl CacheKey { since: req.filters.since.clone(), until: req.filters.until.clone(), effective_ceiling, + context: request_context(req), } } } @@ -3668,10 +3700,16 @@ mod tests { let (handle, calls) = start(RuntimeLimits::default(), None); let addr = handle.addr; + // Both jobs state the local-owner disclosure context + // (#12404): the canary is secret-bearing, and under the + // service's fleet-internal default context it is now + // withheld from every caller — only the owner's local + // surface may receive it. The variable under test here + // stays the effective ceiling. let low = submit( addr, PERSONAL_TOKEN, - json!({"query": "secret canary", "ceiling": "secret-bearing"}), + json!({"query": "secret canary", "ceiling": "secret-bearing", "context": "local-owner"}), ); let low_id = low.body["job_id"].as_str().unwrap().to_string(); let low_tok = low.body["job_token"].as_str().unwrap().to_string(); @@ -3683,7 +3721,7 @@ mod tests { let high = submit( addr, SECRET_TOKEN, - json!({"query": "secret canary", "ceiling": "secret-bearing"}), + json!({"query": "secret canary", "ceiling": "secret-bearing", "context": "local-owner"}), ); assert_eq!(high.body["effective_ceiling"], "secret-bearing"); let high_id = high.body["job_id"].as_str().unwrap().to_string(); @@ -3718,6 +3756,64 @@ mod tests { ); } + #[test] + fn dedupe_never_crosses_disclosure_contexts() { + // #12404: the caller's ceiling is identical and maximal + // for both jobs; only the destination context differs. + // The context is part of the cache key, so the public + // job executes separately and its stored payload is the + // context-filtered one — the owner's unfiltered-by- + // context ranking must never be served into it. + let (handle, calls) = start(RuntimeLimits::default(), None); + let addr = handle.addr; + + let owner = submit( + addr, + SECRET_TOKEN, + json!({"query": "secret canary", "ceiling": "secret-bearing", "context": "local-owner"}), + ); + let owner_id = owner.body["job_id"].as_str().unwrap().to_string(); + let owner_tok = owner.body["job_token"].as_str().unwrap().to_string(); + wait_done(addr, &owner_id, &owner_tok); + let calls_after_owner = calls.lock().unwrap().len(); + + let public = submit( + addr, + SECRET_TOKEN, + json!({"query": "secret canary", "ceiling": "secret-bearing", "context": "public-surface"}), + ); + let public_id = public.body["job_id"].as_str().unwrap().to_string(); + let public_tok = public.body["job_token"].as_str().unwrap().to_string(); + wait_done(addr, &public_id, &public_tok); + assert!( + calls.lock().unwrap().len() > calls_after_owner, + "different disclosure context must execute separately" + ); + + let public_page = http( + addr, + "GET", + &format!("/v1/search/jobs/{public_id}/results"), + Some(&public_tok), + None, + ); + assert!( + !result_ids(&public_page.body).contains(&3), + "canary must not cross to the public context" + ); + let owner_page = http( + addr, + "GET", + &format!("/v1/search/jobs/{owner_id}/results"), + Some(&owner_tok), + None, + ); + assert!( + result_ids(&owner_page.body).contains(&3), + "owner-context job sees its own canary" + ); + } + #[test] fn dedupe_distinguishes_filters() { let (handle, calls) = start(RuntimeLimits::default(), None); diff --git a/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs b/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs index 62d3b73668..c766b45ace 100644 --- a/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs +++ b/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs @@ -115,7 +115,17 @@ fn run_bin(db: &Path, args: &[&str]) -> std::process::Output { fn search_tail(name: &str) -> Vec<&'static str> { match name { "hybrid_default" => vec![], - "hybrid_secret_ceiling" => vec!["--max-sensitivity", "secret-bearing"], + // The recorded envelope comes from the local Python + // CLI at a spelled-out secret ceiling; the matching + // disclosure context is the owner's local surface + // (#12404) — the CLI's fleet-internal default would + // (correctly) withhold the secret-bearing rows. + "hybrid_secret_ceiling" => vec![ + "--max-sensitivity", + "secret-bearing", + "--context", + "local-owner", + ], "hybrid_shareable_ceiling" => vec!["--max-sensitivity", "shareable"], "fts_default" => vec!["--mode", "fts"], "vector_default" => vec!["--mode", "vector"],