1#[derive(Debug)]
8pub struct RootedRead {
9 pub content: String,
10 pub canonical_path: String,
11}
12
13#[derive(Debug)]
15pub struct AdmittedRootedRead {
16 pub content: String,
18 pub(crate) canonical_path: String,
19 pub(crate) classification: lean_ctx_protocol::context_gateway::ClassificationV1,
21 pub storable: bool,
23 pub complete: bool,
25}
26
27#[derive(Debug)]
28struct DecodedRead {
29 content: String,
30 decode_lossy: bool,
31}
32
33pub fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
37 read_file_internal(path, "ctx_read", false)
38}
39
40pub 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 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
70pub 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
81pub 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
103pub 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
129pub 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
144pub 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 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#[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
237use crate::core::context_admission::carrier::gateway_snapshot as gateway_rules_now;
240
241#[path = "rooted_read_units.rs"]
244mod units;
245pub use units::{UnitBounds, UnitRefusal};
246
247#[derive(Debug)]
249pub(crate) struct AdmittedUnit {
250 pub(crate) content: String,
252 pub(crate) storable: bool,
254}
255
256pub 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 #[doc(hidden)]
314 pub fn byte_len(&self) -> u64 {
315 self.byte_len
316 }
317
318 #[doc(hidden)]
325 pub fn gateway_rules_unchanged(&self) -> bool {
326 gateway_rules_now().digest() == self.gateway.digest()
327 }
328
329 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 pub(crate) fn admit_unit(&self, bytes: Vec<u8>) -> Result<AdmittedUnit, std::io::Error> {
362 self.admit_bytes(bytes, true)
363 }
364
365 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 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
437fn 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
471use crate::core::context_admission::cross_line::{
474 ends_inside_classification_field, pattern_is_single_line,
475};
476
477pub 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 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 match (last_header, last_end) {
528 (Some(header), Some(end)) => header >= end,
529 (Some(_), None) => true,
530 (None, _) => false,
531 }
532}
533
534pub 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 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 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 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
656fn 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 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 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
754fn 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
776fn 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 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 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 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 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 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 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 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
950pub struct LineWindow {
954 pub body: String,
956 pub total_lines: usize,
958 pub start: usize,
960 pub end: usize,
961}
962
963pub 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
976pub 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
1018fn 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 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 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 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}