Skip to main content

lean_ctx/core/
rooted_read.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Rooted, admitted file readers shared by the engine and the MCP tools: every
3//! source is opened inside its root (no symlink escape), decoded, and admitted
4//! through the context gateway before its content is returned. Re-exported
5//! from `tools::ctx_read` for the tool layer.
6
7#[derive(Debug)]
8pub struct RootedRead {
9    pub content: String,
10    pub canonical_path: String,
11}
12
13/// A rooted read with the outcome of admitting its ORIGINAL bytes.
14#[derive(Debug)]
15pub struct AdmittedRootedRead {
16    /// The delivered text (project and gateway transformations applied).
17    pub content: String,
18    pub(crate) canonical_path: String,
19    /// Classification of the original source, before any redaction.
20    pub(crate) classification: lean_ctx_protocol::context_gateway::ClassificationV1,
21    /// Whether the original may enter a derived store (complete, not restricted).
22    pub storable: bool,
23    /// `false` when the bytes needed lossy decoding.
24    pub complete: bool,
25}
26
27#[derive(Debug)]
28struct DecodedRead {
29    content: String,
30    decode_lossy: bool,
31}
32
33/// Reads a file as UTF-8 with lossy fallback, enforcing binary detection and max read size limit.
34/// Defense-in-depth: verifies that the canonical path stays within the process's project root
35/// (if determinable) even though callers SHOULD have already jail-checked the path.
36pub fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
37    read_file_internal(path, "ctx_read", false)
38}
39
40/// Read and admit the original source for the CLI adapter. Unlike the generic
41/// unscoped reader, this explicit agent-facing path always applies the Gateway
42/// and carries the decoder's completeness into the admission decision.
43pub fn read_file_lossy_admitted_for_cli(
44    path: &str,
45) -> Result<crate::core::context_admission::SourceAdmission, std::io::Error> {
46    let decoded = read_file_decoded(path)?;
47    // The shared Gateway admission composes active project-policy transforms,
48    // but it does not emit the existing content-policy audit. Keep that
49    // privacy-safe audit on the original bytes; do not feed its transformed
50    // text to Gateway classification.
51    if let Some(policy) = crate::core::policy::runtime::active() {
52        let outcome = crate::core::policy::content::evaluate_text(&decoded.content, &policy);
53        crate::core::policy::audit_filter::audit_filter(
54            "ctx_read",
55            &outcome.audit,
56            outcome.blocked,
57        );
58    }
59    crate::core::context_admission::admit_project_file_with_storage(
60        &decoded.content,
61        path,
62        false,
63        crate::core::context_admission::OutputCompleteness {
64            decode_lossy: decoded.decode_lossy,
65            ..Default::default()
66        },
67    )
68}
69
70/// Acquire an original source under its project authority through a rooted descriptor.
71/// Parsing and derived metadata must use the returned, admitted content.
72pub fn read_file_for_tool_rooted(
73    path: &str,
74    root: &str,
75    tool: &str,
76) -> Result<String, std::io::Error> {
77    let mut remaining = crate::core::limits::max_read_bytes();
78    read_file_for_tool_rooted_budgeted(path, root, tool, &mut remaining)
79}
80
81/// Charge original bytes, including rejected sources, before filtering can shrink them.
82pub fn read_file_for_tool_rooted_budgeted(
83    path: &str,
84    root: &str,
85    tool: &str,
86    remaining_bytes: &mut usize,
87) -> Result<String, std::io::Error> {
88    read_file_for_tool_rooted_with_path(path, root, tool, remaining_bytes).map(|read| read.content)
89}
90
91pub fn read_file_for_tool_rooted_with_path(
92    path: &str,
93    root: &str,
94    tool: &str,
95    remaining_bytes: &mut usize,
96) -> Result<RootedRead, std::io::Error> {
97    read_file_for_tool_rooted_admitted(path, root, tool, remaining_bytes).map(|read| RootedRead {
98        content: read.content,
99        canonical_path: read.canonical_path,
100    })
101}
102
103/// Put the source a tool was asked for into the running call's lineage when
104/// the answer may not have read it (served from a cache or as a stub).
105///
106/// Under protection and inside a source capture, the file is read once
107/// through the admitted rooted reader — which publishes it, bound to what is
108/// on disk now. A source that can no longer be read that way (gone, outside
109/// the root, withheld, binary) makes the call's source set unknown. Without a
110/// capture or without protection this does nothing and reads nothing.
111///
112/// The read is not part of the call's delivery: it is kept out of the
113/// Decision Receipt so a cached answer is not counted as two admissions.
114pub fn publish_requested_source(path: &str, root: &str, tool: &str) {
115    if crate::core::archive::authority::current_capture().is_none()
116        || !crate::core::context_admission::stored::source_authority_required()
117    {
118        return;
119    }
120    let published = crate::core::context_admission::capture::ADMISSIONS.sync_scope(None, || {
121        let mut remaining = crate::core::limits::max_read_bytes();
122        read_file_for_tool_rooted_admitted(path, root, tool, &mut remaining).is_ok()
123    });
124    if !published {
125        crate::core::archive::authority::mark_unbound();
126    }
127}
128
129/// The common rooted read: descriptor-based path jail, budget charged on the
130/// original bytes, and one admission decided on the ORIGINAL decoded source.
131/// Returns the delivered text together with the outcome of that original
132/// admission, so a derived or stored item inherits the source's
133/// classification, storability and completeness instead of re-inferring them
134/// from text a project rule or the gateway has already rewritten.
135pub fn read_file_for_tool_rooted_admitted(
136    path: &str,
137    root: &str,
138    tool: &str,
139    remaining_bytes: &mut usize,
140) -> Result<AdmittedRootedRead, std::io::Error> {
141    read_file_for_tool_rooted_admitted_with(path, root, tool, remaining_bytes, None)
142}
143
144/// [`read_file_for_tool_rooted_admitted`] — the same read in every respect —
145/// with the gateway rules of a snapshot the caller captured (`Some`) instead
146/// of the configuration as it is at this moment (`None`): a caller that
147/// judges several things under one snapshot has its sources judged under
148/// that snapshot too.
149pub fn read_file_for_tool_rooted_admitted_with(
150    path: &str,
151    root: &str,
152    tool: &str,
153    remaining_bytes: &mut usize,
154    gateway: Option<&crate::core::context_admission::stores::StoreAdmission>,
155) -> Result<AdmittedRootedRead, std::io::Error> {
156    if crate::core::binary_detect::has_binary_extension(path) {
157        return Err(std::io::Error::other(
158            "source format is not inspectable as text",
159        ));
160    }
161    let authority = crate::core::policy::runtime::REQUEST_PROJECT
162        .try_with(|slot| slot.borrow().clone())
163        .ok()
164        .flatten()
165        .unwrap_or_else(|| std::path::PathBuf::from(root));
166    crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
167        std::cell::RefCell::new(Some(authority)),
168        || {
169            crate::core::io_boundary::jail_and_check_path(
170                tool,
171                std::path::Path::new(path),
172                std::path::Path::new(root),
173            )
174            .map_err(|_| {
175                std::io::Error::new(
176                    std::io::ErrorKind::PermissionDenied,
177                    "source path withheld by policy",
178                )
179            })?;
180            let (file, canonical_path) =
181                open_rooted_nofollow(std::path::Path::new(path), std::path::Path::new(root))?;
182            let decoded = read_open_file_lossy_bounded_decoded(
183                file,
184                path,
185                *remaining_bytes,
186                Some(remaining_bytes),
187            )?;
188            let complete = !decoded.decode_lossy;
189            let admission = admit_read_with(decoded, path, false, tool, gateway)?;
190            let canonical_path = canonical_path.to_string_lossy().into_owned();
191            // Source publication (G04): the call that is running learns that
192            // this source contributed. A no-op without a capture or without
193            // protection; see `archive::authority::publish_read`.
194            crate::core::archive::authority::publish_read(
195                std::path::Path::new(root),
196                &canonical_path,
197                tool,
198                &admission.text,
199            );
200            Ok(AdmittedRootedRead {
201                content: admission.text,
202                canonical_path,
203                classification: admission.classification,
204                storable: admission.storable && complete,
205                complete,
206            })
207        },
208    )
209}
210
211/// A rooted source opened ONCE for a read in admitted units: the bounded
212/// import read of a history transcript above the read cap (`core::import`).
213///
214/// The path decision and the open are those of the rooted admitted reader:
215/// path jail and secret-path rule first, then one descriptor-relative
216/// no-follow open under the root. Everything after that — the size, every
217/// byte, every admission — is taken from THIS descriptor; the path is never
218/// opened a second time. The raw bytes stay with the caller only until
219/// `Self::admit_unit` has decided on them.
220///
221/// ONE rule set judges every unit and seam of the source and is the one the
222/// unit-safety inspection reads: the pack through the source view the caller
223/// must hold open (`policy::runtime::with_project_source_view` — inside it
224/// `policy::runtime::active()` is the pinned snapshot, and the view fails if
225/// pack or role changed by its end), the gateway rules through `gateway`,
226/// captured once here and passed into every admission.
227#[derive(Debug)]
228pub struct RootedUnitSource {
229    file: std::fs::File,
230    path: String,
231    tool: String,
232    authority: std::path::PathBuf,
233    byte_len: u64,
234    gateway: crate::core::context_admission::stores::StoreAdmission,
235}
236
237// The gateway rules of this moment as one snapshot — the function the
238// database importers use too.
239use crate::core::context_admission::carrier::gateway_snapshot as gateway_rules_now;
240
241// The unit read itself (records, seams, admission of each): the only way
242// out of a `RootedUnitSource` for a caller outside this crate.
243#[path = "rooted_read_units.rs"]
244mod units;
245pub use units::{UnitBounds, UnitRefusal};
246
247/// One unit of a [`RootedUnitSource`] after the admission of its ORIGINAL bytes.
248#[derive(Debug)]
249pub(crate) struct AdmittedUnit {
250    /// The delivered text (project and gateway transformations applied).
251    pub(crate) content: String,
252    /// Whether the original may enter a derived store.
253    pub(crate) storable: bool,
254}
255
256/// Open `path` under `root` for `tool` for a read in admitted units. Same
257/// refusals as [`read_file_for_tool_rooted_admitted`] before its first byte:
258/// `PermissionDenied` for a path rule, any other error for a source that is
259/// not a readable regular file inside the root — or when the caller holds no
260/// source view: without a pinned pack nothing is admitted in units. `gateway`
261/// is the caller's ONE snapshot of the gateway rules for this source.
262pub fn open_rooted_unit_source(
263    path: &str,
264    root: &str,
265    tool: &str,
266    gateway: crate::core::context_admission::stores::StoreAdmission,
267) -> Result<RootedUnitSource, std::io::Error> {
268    if crate::core::binary_detect::has_binary_extension(path) {
269        return Err(std::io::Error::other(
270            "source format is not inspectable as text",
271        ));
272    }
273    if crate::core::policy::runtime::inherited_source_view().is_none() {
274        return Err(std::io::Error::other(
275            "unit admission requires a pinned policy view",
276        ));
277    }
278    let authority = crate::core::policy::runtime::REQUEST_PROJECT
279        .try_with(|slot| slot.borrow().clone())
280        .ok()
281        .flatten()
282        .unwrap_or_else(|| std::path::PathBuf::from(root));
283    let scope = std::cell::RefCell::new(Some(authority.clone()));
284    crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(scope, || {
285        crate::core::io_boundary::jail_and_check_path(
286            tool,
287            std::path::Path::new(path),
288            std::path::Path::new(root),
289        )
290        .map_err(|_| {
291            std::io::Error::new(
292                std::io::ErrorKind::PermissionDenied,
293                "source path withheld by policy",
294            )
295        })?;
296        let (file, _) =
297            open_rooted_nofollow(std::path::Path::new(path), std::path::Path::new(root))?;
298        let byte_len = file.metadata()?.len();
299        Ok(RootedUnitSource {
300            file,
301            path: path.to_owned(),
302            tool: tool.to_owned(),
303            authority,
304            byte_len,
305            gateway,
306        })
307    })
308}
309
310impl RootedUnitSource {
311    /// Size of the opened file, read from its descriptor.
312    // pub only for lean-ctx-engine-ext; not public API
313    #[doc(hidden)]
314    pub fn byte_len(&self) -> u64 {
315        self.byte_len
316    }
317
318    /// Whether the gateway rules configured NOW are still the ones every
319    /// unit of this source was admitted under (the digest of the admission
320    /// fingerprint, `StoreAdmission::digest`). Asked immediately before what
321    /// was read is taken over; the pack side is verified by the caller's
322    /// source view when it ends.
323    // pub only for lean-ctx-engine-ext; not public API
324    #[doc(hidden)]
325    pub fn gateway_rules_unchanged(&self) -> bool {
326        gateway_rules_now().digest() == self.gateway.digest()
327    }
328
329    /// The next raw bytes of the descriptor; `0` at its end. RAW: nothing read
330    /// here may be parsed, stored or delivered before [`Self::admit_unit`] has
331    /// admitted the unit it belongs to.
332    pub(crate) fn read_raw(&mut self, buffer: &mut [u8]) -> Result<usize, std::io::Error> {
333        use std::io::Read;
334        loop {
335            match self.file.read(buffer) {
336                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
337                read => return read,
338            }
339        }
340    }
341
342    /// Admit one unit of this source: the admission the rooted admitted reader
343    /// gives a whole file ([`admit_read`]: project policy and gateway on the
344    /// ORIGINAL text), for these bytes. The caller cuts units at line ends, so
345    /// a unit is complete lines and never divides a character.
346    ///
347    /// A unit is at most the read cap and must be complete UTF-8: a source
348    /// in another encoding cannot be decoded piece by piece and is refused,
349    /// not guessed. `PermissionDenied` when the unit is withheld.
350    ///
351    /// Lineage (G04): a source read in units has no single admitted text to
352    /// bind, so under protection the running call's source set becomes
353    /// unknown instead of silently smaller.
354    ///
355    /// Not weaker than the whole-file admission: `ErrorKind::Unsupported`
356    /// when a rule that is active now could match across lines without a
357    /// bound ([`active_rules_are_unit_safe`]), or when this unit ends inside
358    /// a built-in rule whose match would continue in the next unit
359    /// ([`unit_ends_inside_a_rule`]). The source is then not admitted in
360    /// units at all.
361    pub(crate) fn admit_unit(&self, bytes: Vec<u8>) -> Result<AdmittedUnit, std::io::Error> {
362        self.admit_bytes(bytes, true)
363    }
364
365    /// Admit a SEAM: the end of one unit followed by the start of the next,
366    /// as one text, so that a bounded match across the unit boundary is seen
367    /// by an admission. Checked only — the caller discards the result's text
368    /// and never imports it; a refused seam refuses the source like a
369    /// refused unit. A seam ends where the caller cut it, so the
370    /// "ends inside a rule" check of a unit does not apply to it.
371    pub(crate) fn admit_seam(&self, bytes: Vec<u8>) -> Result<AdmittedUnit, std::io::Error> {
372        self.admit_bytes(bytes, false)
373    }
374
375    fn admit_bytes(
376        &self,
377        bytes: Vec<u8>,
378        whole_unit: bool,
379    ) -> Result<AdmittedUnit, std::io::Error> {
380        use crate::core::text_decode::Encoding;
381        if bytes.len() > crate::core::limits::max_read_bytes() {
382            return Err(std::io::Error::other(
383                "source unit exceeded the bounded read limit",
384            ));
385        }
386        if crate::core::text_decode::looks_binary(&bytes) {
387            return Err(std::io::Error::other(
388                "source format is not inspectable as text",
389            ));
390        }
391        let decoded = crate::core::text_decode::decode_checked(bytes);
392        if !decoded.complete() || !matches!(decoded.encoding, Encoding::Utf8 | Encoding::Utf8Bom) {
393            return Err(std::io::Error::other(
394                "source is not UTF-8 text and cannot be read in units",
395            ));
396        }
397        if whole_unit && unit_ends_inside_a_rule(&decoded.text) {
398            return Err(unit_admission_unsupported());
399        }
400        let scope = std::cell::RefCell::new(Some(self.authority.clone()));
401        let admission = crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(scope, || {
402            // The inspection and the admission read the SAME two objects:
403            // the pack pinned by the caller's source view and `self.gateway`.
404            if !active_rules_are_unit_safe(&self.gateway) {
405                return Err(unit_admission_unsupported());
406            }
407            admit_read_with(
408                DecodedRead {
409                    content: decoded.text,
410                    decode_lossy: false,
411                },
412                &self.path,
413                false,
414                &self.tool,
415                Some(&self.gateway),
416            )
417        })?;
418        if crate::core::archive::authority::current_capture().is_some()
419            && crate::core::context_admission::stored::source_authority_required()
420        {
421            crate::core::archive::authority::mark_unbound();
422        }
423        Ok(AdmittedUnit {
424            content: admission.text,
425            storable: admission.storable,
426        })
427    }
428}
429
430fn unit_admission_unsupported() -> std::io::Error {
431    std::io::Error::new(
432        std::io::ErrorKind::Unsupported,
433        "source cannot be admitted in units under the active rules",
434    )
435}
436
437/// Whether every rule that is active NOW and that lean-ctx does not ship
438/// itself is proven unable to match across a line end — the condition under
439/// which admitting complete lines unit by unit finds what admitting the whole
440/// text finds.
441///
442/// - Policy pack `[redaction]` entries and `[filters.blocked_patterns]`, and
443///   the configured `secret_detection.custom_patterns`: free regular
444///   expressions. The pack parser bounds their number and their LENGTH
445///   (`MAX_RULE_PATTERN_BYTES`), not what they match: any flag is allowed and
446///   no match length is bounded. Each must pass [`pattern_is_single_line`].
447/// - A semantic detector stage judges a document, not lines: when one is
448///   configured, nothing is admitted in units.
449///
450/// The built-in rules are not covered here: they are line-local, or bounded
451/// and covered by the seam, or caught by [`unit_ends_inside_a_rule`].
452fn active_rules_are_unit_safe(
453    gateway: &crate::core::context_admission::stores::StoreAdmission,
454) -> bool {
455    let pack = crate::core::policy::runtime::active().is_none_or(|active| {
456        active
457            .redaction
458            .iter()
459            .chain(&active.blocked_patterns)
460            .all(|(_, pattern)| pattern_is_single_line(pattern.as_str()))
461    });
462    let rules = gateway.admission_policy();
463    pack && rules.semantic.is_none()
464        && rules
465            .secret_patterns
466            .custom_patterns
467            .iter()
468            .all(|pattern| pattern_is_single_line(pattern))
469}
470
471// The one statement of what a rule can match across a line end, shared with
472// the gateway's chunked scan.
473use crate::core::context_admission::cross_line::{
474    ends_inside_classification_field, pattern_is_single_line,
475};
476
477/// Whether a unit ends INSIDE a built-in rule whose match the whole-file
478/// admission would continue in the following text — the built-in rules whose
479/// reach across lines no window bounds:
480///
481/// - the private-key block mask (`core::redaction`, "Private key block"):
482///   from a PEM `BEGIN … PRIVATE KEY` header line to the first END marker
483///   anywhere after it, or over the key-material lines that follow. Open when
484///   the unit ends inside a header, or holds a header with no END marker
485///   after it. Checked on the text as that rule sees it
486///   (`normalize_secret_text`).
487/// - the classification field (`input_filters::classification::field_re`):
488///   `classification` / `sensitivity` / `data class`, `:` or `=`, and the
489///   value, separated by any amount of white space including line ends. Open
490///   when the unit ends after the key, or after the separator.
491///
492/// Decided on the unit alone; never on a seam.
493pub fn unit_ends_inside_a_rule(text: &str) -> bool {
494    use std::sync::OnceLock;
495    const KINDS: &str = r"(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----";
496    static OPEN_HEADER: OnceLock<regex::Regex> = OnceLock::new();
497    static HEADER: OnceLock<regex::Regex> = OnceLock::new();
498    static END: OnceLock<regex::Regex> = OnceLock::new();
499    let built = |cell: &'static OnceLock<regex::Regex>, pattern: &str| {
500        cell.get_or_init(|| regex::Regex::new(pattern).expect("valid built-in rule guard"))
501    };
502
503    // The same statement of the open field the gateway's chunked scan uses.
504    if ends_inside_classification_field(text) {
505        return true;
506    }
507    let normalized = crate::core::redaction::normalize_secret_text(text);
508    if !normalized.contains("-----BEGIN") {
509        return false;
510    }
511    let open_header = built(
512        &OPEN_HEADER,
513        r"-----BEGIN(?:\s+(?:RSA|EC|DSA|OPENSSH))?(?:\s+PRIVATE)?\s*\z",
514    );
515    if open_header.is_match(&normalized) {
516        return true;
517    }
518    let last_header = built(&HEADER, &format!(r"-----BEGIN\s+{KINDS}"))
519        .find_iter(&normalized)
520        .last()
521        .map(|found| found.end());
522    let last_end = built(&END, &format!(r"-----END\s+{KINDS}"))
523        .find_iter(&normalized)
524        .last()
525        .map(|found| found.start());
526    // Every header needs an END marker after it, with key material between.
527    match (last_header, last_end) {
528        (Some(header), Some(end)) => header >= end,
529        (Some(_), None) => true,
530        (None, _) => false,
531    }
532}
533
534/// The rooted no-follow open on its own, for a source that is not read as
535/// text (a history database, `core::import::database`): one open, relative to
536/// the root's descriptor, no link followed in any component on Unix, a regular
537/// file. The caller has made the path decision and runs every further check
538/// on the returned descriptor.
539pub fn open_rooted_source(
540    path: &std::path::Path,
541    root: &std::path::Path,
542) -> Result<std::fs::File, std::io::Error> {
543    open_rooted_nofollow(path, root).map(|(file, _)| file)
544}
545
546fn read_file_internal(
547    path: &str,
548    tool: &str,
549    enforce_policy: bool,
550) -> Result<String, std::io::Error> {
551    let decoded = read_file_decoded(path)?;
552    apply_read_policies(decoded, path, false, tool, enforce_policy)
553}
554
555fn read_file_decoded(path: &str) -> Result<DecodedRead, std::io::Error> {
556    if crate::core::binary_detect::has_binary_extension(path) {
557        let msg = crate::core::binary_detect::binary_file_message(path);
558        return Err(std::io::Error::other(msg));
559    }
560
561    {
562        let canonical =
563            crate::core::pathutil::safe_canonicalize_bounded(std::path::Path::new(path), 2000);
564        if let Some(cwd) = crate::core::policy::diagnostics::project() {
565            let root = crate::core::pathutil::safe_canonicalize_bounded(&cwd, 2000);
566            if !canonical.starts_with(&root) {
567                let allow = crate::core::pathjail::allow_paths_from_env_and_config();
568                let data_dir_ok = crate::core::data_dir::lean_ctx_data_dir()
569                    .is_ok_and(|d| canonical.starts_with(d));
570                let tmp_ok = canonical.starts_with(std::env::temp_dir());
571                if !allow.iter().any(|a| canonical.starts_with(a)) && !data_dir_ok && !tmp_ok {
572                    // Internal file-read workers may lack the MCP request scope.
573                    // Never put an untrusted path into this fallback diagnostic.
574                    tracing::warn!("defense-in-depth: read target may escape current project root");
575                }
576            }
577        }
578    }
579
580    let file = open_with_retry(path)?;
581    read_open_file_lossy_bounded_decoded(file, path, crate::core::limits::max_read_bytes(), None)
582}
583
584pub fn read_file_lossy_rooted(path: &str, root: &str) -> Result<RootedRead, std::io::Error> {
585    if crate::core::binary_detect::has_binary_extension(path) {
586        return Err(std::io::Error::other(
587            crate::core::binary_detect::binary_file_message(path),
588        ));
589    }
590    let (file, canonical_path) =
591        open_rooted_nofollow(std::path::Path::new(path), std::path::Path::new(root))?;
592    crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
593        std::cell::RefCell::new(Some(std::path::PathBuf::from(root))),
594        || {
595            Ok(RootedRead {
596                // A signed source snapshot must retain its original digest. If
597                // protection requires rewriting it, withhold this legacy path.
598                content: read_open_file_lossy(file, path, true, "ctx_read", true)?,
599                canonical_path: canonical_path.to_string_lossy().into_owned(),
600            })
601        },
602    )
603}
604
605fn read_open_file_lossy(
606    file: std::fs::File,
607    path: &str,
608    preserve_bytes: bool,
609    tool: &str,
610    enforce_policy: bool,
611) -> Result<String, std::io::Error> {
612    read_open_file_lossy_bounded(
613        file,
614        path,
615        preserve_bytes,
616        tool,
617        enforce_policy,
618        crate::core::limits::max_read_bytes(),
619        None,
620    )
621}
622
623fn read_open_file_lossy_bounded(
624    file: std::fs::File,
625    path: &str,
626    preserve_bytes: bool,
627    tool: &str,
628    enforce_policy: bool,
629    maximum_bytes: usize,
630    remaining_bytes: Option<&mut usize>,
631) -> Result<String, std::io::Error> {
632    let decoded = read_open_file_lossy_bounded_decoded(file, path, maximum_bytes, remaining_bytes)?;
633    apply_read_policies(decoded, path, preserve_bytes, tool, enforce_policy)
634}
635
636fn read_open_file_lossy_bounded_decoded(
637    file: std::fs::File,
638    path: &str,
639    maximum_bytes: usize,
640    remaining_bytes: Option<&mut usize>,
641) -> Result<DecodedRead, std::io::Error> {
642    let bytes = read_open_file_bounded_bytes(file, path, maximum_bytes, remaining_bytes)?;
643    // Same decoding as the index readers, so every file `ctx_compose` or
644    // `ctx_search` can return is readable here too (Windows ANSI, UTF-16).
645    // The decoder says what it could not represent: corrupt UTF-8, a dangling
646    // UTF-16 byte, an unpaired surrogate. Windows-1252 and well-formed UTF-16
647    // decode faithfully, so policy scanning sees every byte of them.
648    let decoded = crate::core::text_decode::decode_checked(bytes);
649    let decode_lossy = !decoded.complete();
650    Ok(DecodedRead {
651        content: decoded.text,
652        decode_lossy,
653    })
654}
655
656/// The bytes of an opened text source, bounded by `maximum_bytes` and the
657/// read cap and charged to the call's budget. RAW: nothing of them is parsed,
658/// stored or delivered before an admission has decided on the source.
659fn read_open_file_bounded_bytes(
660    file: std::fs::File,
661    path: &str,
662    maximum_bytes: usize,
663    remaining_bytes: Option<&mut usize>,
664) -> Result<Vec<u8>, std::io::Error> {
665    let cap = maximum_bytes.min(crate::core::limits::max_read_bytes());
666    if cap == 0 {
667        return Err(std::io::Error::other("source read budget exhausted"));
668    }
669    let meta = file
670        .metadata()
671        .map_err(|e| std::io::Error::other(format!("cannot stat open file descriptor: {e}")))?;
672    if meta.len() > cap as u64 {
673        return Err(std::io::Error::other(format!(
674            "file too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
675             Increase the limit or use a line-range read: mode=\"lines:1-100\"",
676            meta.len(),
677            cap
678        )));
679    }
680
681    use std::io::{BufRead, Read};
682    let mut bytes = Vec::with_capacity(meta.len() as usize);
683    let mut reader = std::io::BufReader::with_capacity(cap.saturating_add(1).min(8192), file);
684    let prefix = reader.fill_buf()?;
685    if crate::core::text_decode::looks_binary(prefix) {
686        if let Some(remaining) = remaining_bytes {
687            *remaining = remaining.saturating_sub(prefix.len());
688        }
689        return Err(std::io::Error::other(
690            crate::core::binary_detect::binary_file_message(path),
691        ));
692    }
693    let read_result = reader.take(cap as u64 + 1).read_to_end(&mut bytes);
694    if let Some(remaining) = remaining_bytes {
695        *remaining = remaining.saturating_sub(bytes.len());
696    }
697    read_result?;
698    if bytes.len() > cap {
699        return Err(std::io::Error::other(
700            "file exceeded the bounded read limit",
701        ));
702    }
703    Ok(bytes)
704}
705
706fn apply_read_policies(
707    decoded: DecodedRead,
708    path: &str,
709    preserve_bytes: bool,
710    tool: &str,
711    enforce_policy: bool,
712) -> Result<String, std::io::Error> {
713    let s = decoded.content;
714    // Constrain agent acquisitions, not unrelated human/local filesystem reads.
715    // Detached read workers inherit this scope from TaskSpine::spawn_thread.
716    let agent_acquisition = enforce_policy
717        || crate::core::policy::runtime::REQUEST_PROJECT
718            .try_with(|slot| slot.borrow().is_some())
719            .unwrap_or(false);
720    if !agent_acquisition {
721        return Ok(s);
722    }
723    let admission = admit_read(
724        DecodedRead {
725            content: s,
726            decode_lossy: decoded.decode_lossy,
727        },
728        path,
729        preserve_bytes,
730        tool,
731    )?;
732    // Source publication for the readers that are not handed a root (the main
733    // `ctx_read` path): the request project is the authority the read ran
734    // under. Without one the source cannot be bound, which — under protection
735    // and inside a capture — makes the call's source set unknown.
736    if crate::core::archive::authority::current_capture().is_some() {
737        let project = crate::core::policy::runtime::REQUEST_PROJECT
738            .try_with(|slot| slot.borrow().clone())
739            .ok()
740            .flatten()
741            .unwrap_or_default();
742        let canonical =
743            crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(path));
744        crate::core::archive::authority::publish_read(
745            &project,
746            &canonical.to_string_lossy(),
747            tool,
748            &admission.text,
749        );
750    }
751    Ok(admission.text)
752}
753
754/// Admit one decoded source. Order, defined once for every reader:
755///
756/// 1. the project policy audits and judges the ORIGINAL text (a block, or a
757///    lossy decode under a pack, refuses);
758/// 2. the gateway admission also decides on the ORIGINAL text, with the
759///    decoder's completeness — classification, secrets, storability. A project
760///    redaction can therefore never remove a marking before the gateway has
761///    classified the source;
762/// 3. the delivered text is the composition of both transformations, the most
763///    restrictive result winning (`admit_source_with_storage` composes the
764///    project rewrite itself and withholds when the two do not commute).
765///
766/// Clean content is returned byte-identically.
767fn admit_read(
768    decoded: DecodedRead,
769    path: &str,
770    preserve_bytes: bool,
771    tool: &str,
772) -> Result<crate::core::context_admission::SourceAdmission, std::io::Error> {
773    admit_read_with(decoded, path, preserve_bytes, tool, None)
774}
775
776/// [`admit_read`] with the gateway rules of a snapshot the caller captured
777/// once, instead of the configuration as it is at this moment: a source that
778/// is admitted in several pieces is judged by ONE rule set (the pack side is
779/// pinned by the caller's source view, `policy::runtime::with_source_view`).
780fn admit_read_with(
781    decoded: DecodedRead,
782    path: &str,
783    preserve_bytes: bool,
784    tool: &str,
785    gateway: Option<&crate::core::context_admission::stores::StoreAdmission>,
786) -> Result<crate::core::context_admission::SourceAdmission, std::io::Error> {
787    let original = decoded.content;
788    if let Some(policy) = crate::core::policy::runtime::active() {
789        let outcome = crate::core::policy::content::evaluate_text(&original, &policy);
790        crate::core::policy::audit_filter::audit_filter(tool, &outcome.audit, outcome.blocked);
791        if decoded.decode_lossy || outcome.blocked || (preserve_bytes && outcome.text != original) {
792            return Err(std::io::Error::new(
793                std::io::ErrorKind::PermissionDenied,
794                "source content withheld by policy",
795            ));
796        }
797    }
798    // Context Gateway admission runs before any cache, compression or
799    // delivery sees the source, for every read mode.
800    let completeness = crate::core::context_admission::OutputCompleteness {
801        decode_lossy: decoded.decode_lossy,
802        ..Default::default()
803    };
804    match gateway {
805        Some(snapshot) => crate::core::context_admission::admit_source_with_snapshot(
806            &original,
807            path,
808            preserve_bytes,
809            completeness,
810            snapshot,
811        ),
812        None => crate::core::context_admission::admit_project_file_with_storage(
813            &original,
814            path,
815            preserve_bytes,
816            completeness,
817        ),
818    }
819}
820
821#[cfg(unix)]
822fn open_rooted_nofollow(
823    path: &std::path::Path,
824    root: &std::path::Path,
825) -> Result<(std::fs::File, std::path::PathBuf), std::io::Error> {
826    use std::ffi::CString;
827    use std::os::unix::ffi::OsStrExt;
828    use std::os::unix::io::{AsRawFd, FromRawFd};
829
830    let root = crate::core::pathutil::canonicalize_secure(root)?;
831    let target = crate::core::pathjail::jail_path(path, &root)
832        .map_err(|_| std::io::Error::other("file is outside the rooted read boundary"))?;
833    let relative = target
834        .strip_prefix(&root)
835        .map_err(|_| std::io::Error::other("file is outside the rooted read boundary"))?;
836    let components: Vec<_> = relative.components().collect();
837    if components.is_empty() {
838        return Err(std::io::Error::other(
839            "rooted read target must be a regular file",
840        ));
841    }
842    let root_name = CString::new(root.as_os_str().as_bytes())
843        .map_err(|_| std::io::Error::other("rooted read path contains a NUL byte"))?;
844    // SAFETY: root_name is NUL-terminated; File takes ownership immediately.
845    let root_fd = unsafe {
846        libc::open(
847            root_name.as_ptr(),
848            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
849        )
850    };
851    if root_fd < 0 {
852        return Err(std::io::Error::last_os_error());
853    }
854    // SAFETY: root_fd is a new successful descriptor owned by this scope.
855    let mut directory = unsafe { std::fs::File::from_raw_fd(root_fd) };
856    for (index, component) in components.iter().enumerate() {
857        let std::path::Component::Normal(name) = component else {
858            return Err(std::io::Error::other(
859                "rooted read path contains an invalid component",
860            ));
861        };
862        let name = CString::new(name.as_bytes())
863            .map_err(|_| std::io::Error::other("rooted read path contains a NUL byte"))?;
864        let last = index + 1 == components.len();
865        let flags = if last {
866            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK
867        } else {
868            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW
869        };
870        // SAFETY: directory is live and name is NUL-terminated. File owns success.
871        let fd = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
872        if fd < 0 {
873            return Err(std::io::Error::last_os_error());
874        }
875        // SAFETY: fd is a new successful descriptor owned by this scope.
876        let opened = unsafe { std::fs::File::from_raw_fd(fd) };
877        if last {
878            if !opened.metadata()?.is_file() {
879                return Err(std::io::Error::other(
880                    "rooted read target must be a regular file",
881                ));
882            }
883            return Ok((opened, target));
884        }
885        directory = opened;
886    }
887    unreachable!("non-empty rooted path must return from its final component")
888}
889
890#[cfg(windows)]
891fn open_rooted_nofollow(
892    path: &std::path::Path,
893    root: &std::path::Path,
894) -> Result<(std::fs::File, std::path::PathBuf), std::io::Error> {
895    use std::ffi::OsString;
896    use std::os::windows::ffi::OsStringExt;
897    use std::os::windows::io::AsRawHandle;
898    use windows_sys::Win32::Storage::FileSystem::{
899        FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW, VOLUME_NAME_DOS,
900    };
901
902    let root = crate::core::pathutil::canonicalize_secure(root)?;
903    // Open the path the jail checked: a relative path resolves against the
904    // root there, not against the process CWD (the daemon's is not the project).
905    let target = crate::core::pathjail::jail_path(path, &root)
906        .map_err(|_| std::io::Error::other("file is outside the rooted read boundary"))?;
907    let file = std::fs::OpenOptions::new().read(true).open(&target)?;
908    let mut buffer = vec![0u16; 32_768];
909    // SAFETY: the handle is live and buffer is writable for its full length.
910    let length = unsafe {
911        GetFinalPathNameByHandleW(
912            file.as_raw_handle().cast(),
913            buffer.as_mut_ptr(),
914            buffer.len() as u32,
915            FILE_NAME_NORMALIZED | VOLUME_NAME_DOS,
916        )
917    };
918    if length == 0 || length as usize >= buffer.len() {
919        return Err(std::io::Error::last_os_error());
920    }
921    buffer.truncate(length as usize);
922    let final_path = crate::core::pathutil::strip_verbatim(std::path::PathBuf::from(
923        OsString::from_wide(&buffer),
924    ));
925    if !final_path.starts_with(&root) || !file.metadata()?.is_file() {
926        return Err(std::io::Error::other(
927            "opened file escaped the rooted read boundary",
928        ));
929    }
930    Ok((file, final_path))
931}
932
933#[cfg(not(any(unix, windows)))]
934fn open_rooted_nofollow(
935    path: &std::path::Path,
936    root: &std::path::Path,
937) -> Result<(std::fs::File, std::path::PathBuf), std::io::Error> {
938    let root = crate::core::pathutil::canonicalize_secure(root)?;
939    let target = crate::core::pathjail::jail_path(path, &root)
940        .map_err(|_| std::io::Error::other("file is outside the rooted read boundary"))?;
941    let file = std::fs::File::open(&target)?;
942    if !file.metadata()?.is_file() {
943        return Err(std::io::Error::other(
944            "rooted read target must be a regular file",
945        ));
946    }
947    Ok((file, target))
948}
949
950/// A streamed line-window read (#811): only the requested span's raw lines,
951/// plus the file's true total line count for the header — the rest of the
952/// file is never buffered.
953pub struct LineWindow {
954    /// Raw lines within `[start, end]`, joined with `\n`.
955    pub body: String,
956    /// True total line count of the file.
957    pub total_lines: usize,
958    /// Clamped, 1-based inclusive bounds actually served.
959    pub start: usize,
960    pub end: usize,
961}
962
963/// Parses an `anchored:` window payload for the disk-streaming short-circuit
964/// below. Only the dash form (`"N-M"`) is fast-pathed — `anchored_lines_mode`
965/// (the registered handler) always emits it, using the `999999` EOF sentinel
966/// rather than a bare `"N"`. A hand-typed bare payload (meaning "N to EOF")
967/// returns `None` and falls through to the normal full-read path instead of
968/// guessing a total line count up front.
969pub fn parse_disk_anchor_range(payload: &str) -> Option<(usize, usize)> {
970    let (s, e) = payload.split_once('-')?;
971    let start = s.trim().parse::<usize>().ok()?.max(1);
972    let end = e.trim().parse::<usize>().ok()?;
973    Some((start, end))
974}
975
976/// Streams `path` line-by-line and extracts only `[start, end]` (1-based,
977/// inclusive) without ever holding the whole file in memory — the
978/// anchored-window counterpart to [`read_file_lossy`] (#811). Every line is
979/// still counted (one cheap UTF-8 pass, no per-line allocation outside the
980/// requested window) so the caller can report the true total. Returns `None`
981/// on anything that isn't a clean streamed text read (I/O error, a binary
982/// file, invalid UTF-8 anywhere in the file) so the caller can fall back to
983/// the existing, more permissive `read_file_lossy` path — behaviour never
984/// regresses, it just doesn't always get the fast path.
985pub fn read_line_window(path: &str, start: usize, end: usize) -> Option<LineWindow> {
986    if crate::core::binary_detect::has_binary_extension(path) {
987        return None;
988    }
989    use std::io::BufRead;
990    let file = open_with_retry(path).ok()?;
991    let mut reader = std::io::BufReader::new(file);
992    if reader
993        .fill_buf()
994        .ok()?
995        .iter()
996        .take(8192)
997        .any(|byte| *byte == 0)
998    {
999        return None;
1000    }
1001    let mut total = 0usize;
1002    let mut collected = Vec::new();
1003    for line in reader.lines() {
1004        let line = line.ok()?;
1005        total += 1;
1006        if total >= start && total <= end {
1007            collected.push(line);
1008        }
1009    }
1010    Some(LineWindow {
1011        body: collected.join("\n"),
1012        total_lines: total,
1013        start: start.min(total.max(1)),
1014        end: end.min(total),
1015    })
1016}
1017
1018/// Opens a file, retrying once after a brief pause on NotFound.
1019/// Works around overlay/FUSE stat-cache races in container runtimes (Docker, Codex).
1020/// Uses O_NOFOLLOW on Unix for TOCTOU symlink protection.
1021fn open_with_retry(path: &str) -> Result<std::fs::File, std::io::Error> {
1022    match open_nofollow(path) {
1023        Ok(f) => Ok(f),
1024        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1025            std::thread::sleep(std::time::Duration::from_millis(50));
1026            open_nofollow(path).map_err(|e| {
1027                if e.kind() == std::io::ErrorKind::NotFound {
1028                    let hint = crate::core::path_suggest::hint(std::path::Path::new(path));
1029                    if hint.is_empty() {
1030                        std::io::Error::other(format!(
1031                            "file not found: {path} — verify the path with ctx_tree or ctx_search"
1032                        ))
1033                    } else {
1034                        std::io::Error::other(format!("file not found: {path}{hint}"))
1035                    }
1036                } else {
1037                    e
1038                }
1039            })
1040        }
1041        Err(e) => Err(e),
1042    }
1043}
1044
1045#[cfg(unix)]
1046fn open_nofollow(path: &str) -> Result<std::fs::File, std::io::Error> {
1047    use std::os::unix::fs::OpenOptionsExt;
1048    use std::path::Path;
1049
1050    let p = Path::new(path);
1051    // Canonicalize the parent directory (resolving symlinks in the directory path)
1052    // but apply O_NOFOLLOW only to the final file component. This prevents
1053    // symlink-following attacks on the target file while allowing legitimate
1054    // directory symlinks (e.g., /tmp → /private/tmp on macOS).
1055    if let (Some(parent), Some(filename)) = (p.parent(), p.file_name())
1056        && parent.exists()
1057    {
1058        let canonical_parent = crate::core::pathutil::safe_canonicalize_bounded(parent, 2000);
1059        let canonical_path = canonical_parent.join(filename);
1060        return std::fs::OpenOptions::new()
1061            .read(true)
1062            .custom_flags(libc::O_NOFOLLOW)
1063            .open(&canonical_path);
1064    }
1065
1066    // Fallback: direct open with O_NOFOLLOW
1067    std::fs::OpenOptions::new()
1068        .read(true)
1069        .custom_flags(libc::O_NOFOLLOW)
1070        .open(path)
1071}
1072
1073#[cfg(not(unix))]
1074fn open_nofollow(path: &str) -> Result<std::fs::File, std::io::Error> {
1075    std::fs::File::open(path)
1076}
1077
1078#[cfg(test)]
1079#[path = "rooted_read_admission_tests.rs"]
1080mod admission_tests;
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::read_file_lossy_rooted;
1085
1086    #[test]
1087    fn original_read_budget_counts_masked_and_blocked_content() {
1088        let root = tempfile::tempdir().unwrap();
1089        let policy_path = root.path().join("policy.toml");
1090        std::fs::write(&policy_path,
1091            "name = 'budget'\nversion = '1.0.0'\ndescription = 'fixture'\n[redaction]\nmasked = 'X+'\n[filters]\nclassification = 'block'\n").unwrap();
1092        let pack = crate::core::policy::parse_file(&policy_path).unwrap();
1093        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(
1094            crate::core::policy::resolve(&pack).unwrap(),
1095        ));
1096        let masked = root.path().join("masked.txt");
1097        let blocked = root.path().join("blocked.txt");
1098        std::fs::write(&masked, "X".repeat(512)).unwrap();
1099        let blocked_text = format!("CONFIDENTIAL{}", " ".repeat(500));
1100        std::fs::write(&blocked, &blocked_text).unwrap();
1101        let mut remaining = 512 + blocked_text.len();
1102        let content = super::read_file_for_tool_rooted_budgeted(
1103            masked.to_str().unwrap(),
1104            root.path().to_str().unwrap(),
1105            "ctx_symbol",
1106            &mut remaining,
1107        )
1108        .unwrap();
1109        assert!(content.len() < 512);
1110        assert_eq!(remaining, blocked_text.len());
1111        assert!(
1112            super::read_file_for_tool_rooted_budgeted(
1113                blocked.to_str().unwrap(),
1114                root.path().to_str().unwrap(),
1115                "ctx_symbol",
1116                &mut remaining,
1117            )
1118            .is_err()
1119        );
1120        assert_eq!(remaining, 0);
1121        assert!(
1122            super::read_file_for_tool_rooted_budgeted(
1123                masked.to_str().unwrap(),
1124                root.path().to_str().unwrap(),
1125                "ctx_symbol",
1126                &mut remaining,
1127            )
1128            .is_err()
1129        );
1130    }
1131
1132    #[test]
1133    fn rooted_read_binds_content_to_canonical_in_root_source() {
1134        let root = tempfile::tempdir().unwrap();
1135        let path = root.path().join("source.txt");
1136        std::fs::write(&path, "rooted content").unwrap();
1137
1138        let read = read_file_lossy_rooted(&path.to_string_lossy(), &root.path().to_string_lossy())
1139            .unwrap();
1140
1141        assert_eq!(read.content, "rooted content");
1142        assert_eq!(
1143            std::path::Path::new(&read.canonical_path),
1144            crate::core::pathutil::canonicalize_secure(&path).unwrap()
1145        );
1146    }
1147
1148    #[test]
1149    fn rooted_read_resolves_a_relative_path_against_the_root_not_the_cwd() {
1150        // Config (path_jail) is read from the data dir parallel tests repoint.
1151        let _iso = crate::core::data_dir::isolated_data_dir();
1152        let root = tempfile::tempdir().unwrap();
1153        std::fs::write(root.path().join("relative.txt"), "from the root").unwrap();
1154
1155        let read = read_file_lossy_rooted("relative.txt", &root.path().to_string_lossy()).unwrap();
1156
1157        assert_eq!(read.content, "from the root");
1158    }
1159
1160    #[test]
1161    fn rooted_read_rejects_outside_source_and_binary_content() {
1162        let root = tempfile::tempdir().unwrap();
1163        let outside = tempfile::tempdir().unwrap();
1164        let outside_path = outside.path().join("outside.txt");
1165        std::fs::write(&outside_path, "outside").unwrap();
1166        assert!(
1167            read_file_lossy_rooted(
1168                &outside_path.to_string_lossy(),
1169                &root.path().to_string_lossy(),
1170            )
1171            .is_err()
1172        );
1173
1174        let binary = root.path().join("binary.txt");
1175        std::fs::write(&binary, b"text\0binary").unwrap();
1176        let error =
1177            read_file_lossy_rooted(&binary.to_string_lossy(), &root.path().to_string_lossy())
1178                .unwrap_err();
1179        assert!(error.to_string().contains("Binary file detected"));
1180    }
1181
1182    #[cfg(unix)]
1183    #[test]
1184    fn rooted_read_resolves_safe_alias_and_rejects_escape_symlink() {
1185        use std::os::unix::fs::symlink;
1186
1187        let root = tempfile::tempdir().unwrap();
1188        let inside = root.path().join("inside.txt");
1189        std::fs::write(&inside, "inside").unwrap();
1190        let safe_alias = root.path().join("safe-alias.txt");
1191        symlink(&inside, &safe_alias).unwrap();
1192        assert_eq!(
1193            read_file_lossy_rooted(
1194                &safe_alias.to_string_lossy(),
1195                &root.path().to_string_lossy(),
1196            )
1197            .unwrap()
1198            .content,
1199            "inside"
1200        );
1201
1202        let outside = tempfile::tempdir().unwrap();
1203        let outside_path = outside.path().join("outside.txt");
1204        std::fs::write(&outside_path, "outside").unwrap();
1205        let escape = root.path().join("escape.txt");
1206        symlink(outside_path, &escape).unwrap();
1207        assert!(
1208            read_file_lossy_rooted(&escape.to_string_lossy(), &root.path().to_string_lossy(),)
1209                .is_err()
1210        );
1211    }
1212}