use std::path::{Component, Path};
use crate::domain::{FileDisposition, MetadataOnlyReason};
use crate::live_index::LiveIndex;
use crate::protocol::format;
#[derive(Debug, PartialEq, Eq)]
pub enum GenerationResolution<'a> {
Published(&'a [u8]),
NotInGeneration,
}
pub fn resolve_generation_bytes<'a>(
live: &'a LiveIndex,
relative_path: &str,
) -> GenerationResolution<'a> {
match live.get_file(relative_path) {
Some(file) => GenerationResolution::Published(&file.content),
None => GenerationResolution::NotInGeneration,
}
}
pub fn observe_disk_beneath(
live: &LiveIndex,
workspace_root: &Path,
relative_path: &str,
) -> Result<Vec<u8>, String> {
observe_beneath(live, workspace_root, relative_path, true)
}
pub(crate) fn observe_disk_beneath_without_lines(
live: &LiveIndex,
workspace_root: &Path,
relative_path: &str,
) -> Result<Vec<u8>, String> {
observe_beneath(live, workspace_root, relative_path, false)
}
fn observe_beneath(
live: &LiveIndex,
workspace_root: &Path,
relative_path: &str,
name_lines: bool,
) -> Result<Vec<u8>, String> {
let candidate = Path::new(relative_path);
let escapes = candidate.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
});
if escapes || candidate.is_absolute() {
return Err(format!(
"{relative_path} [error: path escapes the workspace root; a disk \
observation is confined beneath it]"
));
}
refuse_disk_spelling(workspace_root, relative_path)?;
let full_path = workspace_root.join(candidate);
disk_read(live, relative_path, &full_path, name_lines)
}
pub(crate) use crate::index_lifecycle::guidance::read_gate::hard_scope_refusal;
use crate::index_lifecycle::guidance::read_gate::refuse_disk_spelling;
#[cfg(test)]
use crate::index_lifecycle::guidance::read_gate::file_type_is_disk;
#[cfg(all(test, windows))]
use crate::index_lifecycle::guidance::read_gate::open_for_gate_read;
#[cfg(test)]
use crate::index_lifecycle::guidance::read_gate::read_regular_file;
use crate::index_lifecycle::guidance::read_gate::read_regular_file_limited;
pub(crate) fn admit_worktree_text(
live: &LiveIndex,
repo: &crate::git::GitRepo,
relative_path: &str,
) -> Result<Option<String>, String> {
worktree_text(live, repo, relative_path, true)
}
pub(crate) fn admit_worktree_text_without_lines(
live: &LiveIndex,
repo: &crate::git::GitRepo,
relative_path: &str,
) -> Result<Option<String>, String> {
worktree_text(live, repo, relative_path, false)
}
fn worktree_text(
live: &LiveIndex,
repo: &crate::git::GitRepo,
relative_path: &str,
name_lines: bool,
) -> Result<Option<String>, String> {
crate::index_lifecycle::guidance::read_gate::worktree_text_with(
repo,
relative_path,
&mut |full_path| disk_read(live, relative_path, full_path, name_lines),
)
}
pub(crate) fn disk_read_would_refuse(
live: &LiveIndex,
relative_path: &str,
size: Option<u64>,
) -> bool {
if crate::knowledge::sensitive_path_rule(relative_path).is_some() {
return true;
}
if let Some(FileDisposition::MetadataOnly {
reason:
MetadataOnlyReason::SensitivePath { .. } | MetadataOnlyReason::SensitiveContent { .. },
}) = live.capture_file_disposition(relative_path)
{
return true;
}
size.is_some_and(|size| crate::knowledge::exceeds_scan_limit(size as usize))
}
pub(crate) fn refuse_by_policy(live: &LiveIndex, relative_path: &str) -> Option<String> {
crate::index_lifecycle::guidance::read_gate::refuse_by_policy_with(
live,
relative_path,
&mut crate::protocol::withheld::record_pending_withheld,
)
}
pub(crate) use crate::index_lifecycle::guidance::read_gate::normalize_requested_path;
pub(crate) use crate::index_lifecycle::guidance::read_gate::unverified_notice;
fn recorded_refusal_naming_lines(live: &LiveIndex, relative_path: &str) -> Option<String> {
if crate::knowledge::sensitive_path_rule(relative_path).is_some() {
return None;
}
let Some(FileDisposition::MetadataOnly {
reason:
MetadataOnlyReason::SensitiveContent {
rule_ids,
finding_count,
},
}) = live.capture_file_disposition(relative_path)
else {
return None;
};
if rule_ids
.iter()
.any(|id| id == crate::knowledge::INDETERMINATE_RULE_ID)
{
return None;
}
let (line_ranges, findings) = recorded_finding_evidence(live, relative_path, rule_ids);
if !findings.is_empty() {
crate::protocol::withheld::record_pending_withheld(
crate::protocol::withheld::WithheldMeta::from_content_findings(
relative_path,
&findings,
),
);
}
(!line_ranges.is_empty()).then(|| {
format::content_withheld_by_admission(relative_path, rule_ids, *finding_count, &line_ranges)
})
}
fn recorded_finding_evidence(
live: &LiveIndex,
relative_path: &str,
recorded: &[String],
) -> (
Vec<(u32, u32)>,
Vec<crate::knowledge::SecretFindingDescriptor>,
) {
let Some(root) = live.indexed_root.as_deref() else {
return (Vec::new(), Vec::new());
};
let Ok(Some(full_path)) = crate::discovery::resolve_repo_path(root, relative_path) else {
return (Vec::new(), Vec::new());
};
let budget = crate::knowledge::SECRET_SCAN_MAX_BYTES as u64 + 1;
let Ok(bytes) = read_regular_file_limited(&full_path, Some(budget)) else {
return (Vec::new(), Vec::new());
};
crate::index_lifecycle::guidance::read_gate::recorded_finding_evidence_from_bytes(
relative_path,
&bytes,
recorded,
)
}
pub(crate) fn admit_git_text(
live: &LiveIndex,
repo: &crate::git::GitRepo,
git_ref: &str,
relative_path: &str,
) -> Result<Option<String>, String> {
crate::index_lifecycle::guidance::read_gate::admit_git_text_with(
live,
repo,
git_ref,
relative_path,
&mut crate::protocol::withheld::record_pending_withheld,
)
}
pub(crate) fn admit_disk_read(
live: &LiveIndex,
relative_path: &str,
canon_path: &Path,
) -> Result<Vec<u8>, String> {
disk_read(live, relative_path, canon_path, true)
}
fn disk_read(
live: &LiveIndex,
relative_path: &str,
canon_path: &Path,
name_lines: bool,
) -> Result<Vec<u8>, String> {
crate::index_lifecycle::guidance::read_gate::disk_read_with(
live,
relative_path,
canon_path,
&mut || {
if name_lines {
recorded_refusal_naming_lines(live, relative_path)
} else {
None
}
},
&mut crate::protocol::withheld::record_pending_withheld,
)
}
pub struct ReadGate;
impl ReadGate {
pub fn admit_disk_read(
live: &LiveIndex,
relative_path: &str,
canon_path: &Path,
) -> Result<Vec<u8>, String> {
admit_disk_read(live, relative_path, canon_path)
}
}
#[cfg(test)]
mod tests {
#[test]
fn recorded_line_reread_is_called_only_from_the_disk_read_lane() {
let needle = concat!("recorded_refusal_", "naming_lines(");
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let src = manifest.join("src");
let mut callers: Vec<(String, String)> = Vec::new();
let mut stack = vec![src.clone()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).expect("read source dir") {
let path = entry.expect("dir entry").path();
if path.is_dir() {
stack.push(path);
continue;
}
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
continue;
}
let relative = path
.strip_prefix(&src)
.expect("under src")
.to_string_lossy()
.replace('\\', "/");
let contents = std::fs::read_to_string(&path).expect("read source file");
let mut enclosing = String::new();
for line in contents.lines() {
let trimmed = line.trim_start();
if trimmed.starts_with("//") {
continue;
}
for prefix in ["fn ", "pub fn ", "pub(crate) fn "] {
if let Some(rest) = trimmed.strip_prefix(prefix) {
enclosing = rest.split(['(', '<']).next().unwrap_or("").to_string();
}
}
if line.contains(needle) && !trimmed.contains(&format!("fn {needle}")) {
callers.push((relative.clone(), enclosing.clone()));
}
}
}
}
assert_eq!(
callers,
vec![("protocol/read_gate.rs".to_string(), "disk_read".to_string())],
"the line re-read must be reached only through the disk-read lane"
);
}
#[test]
fn file_type_is_disk_accepts_remote_disk_and_rejects_pipes() {
assert!(super::file_type_is_disk(1));
assert!(super::file_type_is_disk(1 | 0x8000));
assert!(!super::file_type_is_disk(2));
assert!(!super::file_type_is_disk(3));
assert!(!super::file_type_is_disk(3 | 0x8000));
assert!(!super::file_type_is_disk(0));
}
#[test]
fn read_regular_file_reads_bytes_of_a_regular_file() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("note.txt");
std::fs::write(&path, b"hello").expect("write");
let bytes = super::read_regular_file(&path).expect("regular file");
assert_eq!(bytes, b"hello");
}
#[cfg(windows)]
#[test]
fn open_for_gate_read_does_not_block_on_a_named_pipe() {
let pipe = IdleOutboundPipe::listen("open");
let path = pipe.path.clone();
let result = finish_within(
std::time::Duration::from_secs(5),
"open_for_gate_read",
move || super::open_for_gate_read(&path),
);
let err = result.expect_err("a named pipe is not a regular file");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{err}");
assert!(err.to_string().contains("not a regular file"), "{err}");
}
#[cfg(windows)]
#[test]
fn read_regular_file_does_not_block_on_a_named_pipe() {
let pipe = IdleOutboundPipe::listen("read");
let path = pipe.path.clone();
let result = finish_within(
std::time::Duration::from_secs(5),
"read_regular_file",
move || super::read_regular_file(&path),
);
let err = result.expect_err("a named pipe is not admissible content");
assert!(
err.to_string().contains("not a regular file") || err.raw_os_error().is_some(),
"unexpected refusal: {err:?}"
);
}
#[cfg(windows)]
fn finish_within<T: Send + 'static>(
budget: std::time::Duration,
label: &str,
work: impl FnOnce() -> T + Send + 'static,
) -> T {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(work());
});
match rx.recv_timeout(budget) {
Ok(value) => value,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
panic!("{label} blocked for {budget:?}")
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
panic!("{label} ended without a result")
}
}
}
#[cfg(windows)]
struct IdleOutboundPipe {
handle: windows::Win32::Foundation::HANDLE,
path: std::path::PathBuf,
}
#[cfg(windows)]
impl IdleOutboundPipe {
#[allow(unsafe_code)]
fn listen(label: &str) -> Self {
use std::os::windows::ffi::OsStrExt;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Storage::FileSystem::{
FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_OUTBOUND,
};
use windows::Win32::System::Pipes::{CreateNamedPipeW, PIPE_REJECT_REMOTE_CLIENTS};
let path = std::path::PathBuf::from(format!(
r"\\.\pipe\symforge-read-gate-{}-{label}",
std::process::id()
));
let wide: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let handle: HANDLE = unsafe {
CreateNamedPipeW(
windows::core::PCWSTR(wide.as_ptr()),
PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_REJECT_REMOTE_CLIENTS,
1,
4096,
4096,
0,
None,
)
};
assert!(
!handle.is_invalid(),
"CreateNamedPipeW({}): {}",
path.display(),
std::io::Error::last_os_error()
);
Self { handle, path }
}
}
#[cfg(windows)]
impl Drop for IdleOutboundPipe {
#[allow(unsafe_code)]
fn drop(&mut self) {
use windows::Win32::Foundation::CloseHandle;
unsafe { CloseHandle(self.handle) }.ok();
}
}
}