Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
e07503d
fix(gitio): refuse unsafe tree names and never emit symlink modes on …
tonibergholm-codento Nov 20, 2026
aa89b11
fix(repo): write serve-tokens.toml owner-only
tonibergholm-codento Nov 20, 2026
370fa56
fix: escape terminal controls in remote and commit text before printing
tonibergholm-codento Nov 20, 2026
c4106b7
fix(crypto): redact DEKs from Debug of IndexEntry and BranchIndex
tonibergholm-codento Nov 20, 2026
28a98f5
feat(cli): warn when an identity file is readable by group or others
tonibergholm-codento Nov 20, 2026
def9346
docs(threat-model): record hygiene fixes and the sealed-blob placemen…
tonibergholm-codento Nov 20, 2026
e4b0d3d
fix(cli): escape newlines and bidi controls in one-line output
tonibergholm-codento Nov 20, 2026
4c0af82
fix(gitio): use gix's path validation, keep symlink modes, check only…
tonibergholm-codento Nov 20, 2026
23be4a4
fix(cli): check names in every commit a network push uploads, includi…
tonibergholm-codento Nov 20, 2026
eab75ef
fix(repo): escape ref-name diagnostics, send error text raw on the wi…
tonibergholm-codento Nov 20, 2026
05a0044
refactor(gitio): check names where export builds a Git tree; escape R…
tonibergholm-codento Nov 20, 2026
93d9bc7
test(gitio): assert the ref stays put when export refuses
tonibergholm-codento Nov 20, 2026
10b26bd
fix(gitio): remove a target repo a refused export created; docs wording
tonibergholm-codento Nov 20, 2026
e6f46b3
fix(gitio): claim a new export target exclusively before owning it
tonibergholm-codento Nov 20, 2026
2abb108
fix(gitio): never remove an export target; a ref-less target takes th…
tonibergholm-codento Nov 20, 2026
1f4e762
fix(gitio): adopt only a bare, ref-less target with a symbolic HEAD
tonibergholm-codento Nov 20, 2026
b5b9c2e
Merge branch 'main' into fix/sc-hygiene
tonibergholm-codento Nov 20, 2026
4d412a0
Merge branch 'main' into fix/sc-hygiene
tonibergholm-codento Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 89 additions & 16 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2700,19 +2700,7 @@ fn run_log(json: bool, identity: Option<PathBuf>) -> Result<()> {
return Ok(());
}
for ((id, snap), status) in entries.iter().zip(&statuses) {
let merge = if snap.parents.len() > 1 {
" (merge)"
} else {
""
};
print_line(&format!(
"{} {} {} — {}{}",
id.short(),
fmt_utc(snap.timestamp),
snap.author,
snap.message,
merge
));
print_line(&render_log_line(id, snap));
if let Some(line) = render_sig_status_line(status) {
print_line(&line);
}
Expand All @@ -2732,6 +2720,23 @@ fn run_log(json: bool, identity: Option<PathBuf>) -> Result<()> {
/// themselves, but that needs `libc`; catching `BrokenPipe` at the point of
/// writing gets the same externally-visible result (clean exit, no panic)
/// without a new dependency.
fn render_log_line(id: &scl_core::ObjectId, snap: &scl_core::Snapshot) -> String {
let merge = if snap.parents.len() > 1 {
" (merge)"
} else {
""
};
// Author and message are authored by whoever made the commit, not by this user: no raw escapes.
format!(
"{} {} {} — {}{}",
id.short(),
fmt_utc(snap.timestamp),
scl_core::sanitize_display_line(&snap.author),
scl_core::sanitize_display_line(&snap.message),
merge
)
}

fn print_line(line: &str) {
use std::io::Write;
if let Err(e) = writeln!(std::io::stdout(), "{line}") {
Expand Down Expand Up @@ -3145,9 +3150,16 @@ fn run_transcript(op: TranscriptOp) -> Result<()> {
return Ok(());
}
for (tid, t) in &transcripts {
println!("--- {} (agent: {}) ---", tid.short(), t.agent);
println!(
"--- {} (agent: {}) ---",
tid.short(),
scl_core::sanitize_display_line(&t.agent)
);
let body = repo.open_transcript(tid, &sk)?;
print!("{}", String::from_utf8_lossy(&body));
print!(
"{}",
scl_core::sanitize_display(&String::from_utf8_lossy(&body))
);
println!();
}
Ok(())
Expand Down Expand Up @@ -3194,7 +3206,7 @@ fn run_transcript(op: TranscriptOp) -> Result<()> {
"{} {} agent={} {}",
snap.short(),
tid.short(),
agent,
scl_core::sanitize_display_line(agent),
transcript_sig_label(status)
));
}
Expand Down Expand Up @@ -3729,8 +3741,38 @@ fn run_ws(op: WsOp) -> Result<()> {
/// is this function with `.enc` projected out — same file format handling,
/// same errors, just a narrower return type so none of those call sites had
/// to change shape.
/// Whether a unix file mode lets group or others read or write the file (ssh's test for a private key).
#[cfg(unix)]
fn mode_open_to_group_or_others(mode: u32) -> bool {
mode & 0o077 != 0
}

/// Warn once on stderr when the identity file is accessible to group or others, as ssh does for keys.
/// A warning only: an existing setup keeps working.
#[cfg(unix)]
fn warn_if_identity_too_open(path: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let Ok(meta) = std::fs::metadata(path) else {
return;
};
let mode = meta.permissions().mode() & 0o777;
if mode_open_to_group_or_others(mode)
&& !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
{
eprintln!(
"warning: identity file {} is accessible to other users (mode {mode:04o}); \
run `chmod 600 {}`",
path.display(),
path.display()
);
}
}

fn load_identity_full(flag: Option<PathBuf>) -> Result<scl_crypto::Identity> {
let path = resolve_identity_path(flag);
#[cfg(unix)]
warn_if_identity_too_open(&path);
let contents = scl_crypto::Zeroizing::new(
std::fs::read_to_string(&path)
.with_context(|| format!("reading identity {}", path.display()))?,
Expand Down Expand Up @@ -4879,6 +4921,37 @@ mod tests {
use super::*;
use std::time::Duration;

#[cfg(unix)]
#[test]
fn identity_mode_predicate_flags_group_and_other_access() {
for open in [0o644, 0o640, 0o604, 0o660, 0o666, 0o700 | 0o001, 0o620] {
assert!(mode_open_to_group_or_others(open), "{open:o}");
}
for private in [0o600, 0o400, 0o700, 0o500] {
assert!(!mode_open_to_group_or_others(private), "{private:o}");
}
}

#[test]
fn log_line_escapes_terminal_controls_from_author_and_message() {
let snap = scl_core::Snapshot {
root: scl_core::ObjectId::of(b"r"),
parents: vec![],
author: "evil\x1b]0;x\x07".into(),
timestamp: 0,
message: "a\x1b[2J\u{9b}b\nsecond line".into(),
secrets: Default::default(),
protection: Default::default(),
};
let line = render_log_line(&scl_core::ObjectId::of(b"s"), &snap);
assert!(
line.contains("evil\\x1b]0;x\\x07") && line.contains("a\\x1b[2J\\u{9b}b\\x0asecond"),
"{line}"
);
// One line: a message cannot start a line that looks like a signature status.
assert!(!line.chars().any(|c| c.is_control()));
}

#[test]
fn default_budget_warning_logic() {
assert!(runs_default_budget(false, None));
Expand Down
53 changes: 53 additions & 0 deletions crates/cli/tests/git_remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,56 @@ fn push_refuses_when_remote_has_unseen_commit() {

std::fs::remove_dir_all(&root).unwrap();
}

// A hostile `.gitmodules` is refused in what a push uploads, but not in history the server already
// has: git itself accepted that commit, and a fix that removes the file must still push. Goes
// through the network bridge (file://). Names are checked where export builds a tree, so a commit
// reused through a mark is never judged and a refusal leaves the remote tip where it was.
#[test]
fn network_push_checks_names_only_in_commits_the_server_lacks() {
let root = tmp("netnames");
let hub = root.join("hub.git");
git(
&root,
&["init", "-q", "--bare", "-b", "main", hub.to_str().unwrap()],
);
let up = root.join("up");
std::fs::create_dir_all(&up).unwrap();
git(&up, &["init", "-q", "-b", "main"]);
std::fs::write(up.join(".gitmodules"), b"# none\n").unwrap();
std::fs::write(up.join("a.txt"), b"a").unwrap();
git(&up, &["add", "."]);
git(&up, &["commit", "-q", "-m", "old"]);
git(&up, &["push", "-q", hub.to_str().unwrap(), "main"]);

let screpo = root.join("work");
std::fs::create_dir_all(&screpo).unwrap();
assert!(sc(&screpo, &["init"]).status.success());
let url = format!("file://{}", hub.display());
assert!(sc(&screpo, &["remote", "add", "hub", &url, "--git"])
.status
.success());
assert!(sc(&screpo, &["fetch", "hub"]).status.success());
assert!(sc(&screpo, &["merge", "hub/main"]).status.success());

// The fix removes the file: allowed although the server's history has it.
std::fs::remove_file(screpo.join(".gitmodules")).unwrap();
assert!(sc(&screpo, &["commit", "-m", "drop"]).status.success());
let p = sc(&screpo, &["push", "hub"]);
assert!(p.status.success(), "{}", String::from_utf8_lossy(&p.stderr));
let tip = git(&hub, &["rev-parse", "main"]).stdout;

// A new commit that adds it again is refused, and the server is untouched.
std::fs::write(screpo.join(".gitmodules"), b"# again\n").unwrap();
assert!(sc(&screpo, &["commit", "-m", "again"]).status.success());
let p = sc(&screpo, &["push", "hub"]);
assert!(!p.status.success());
assert!(
String::from_utf8_lossy(&p.stderr).contains("not a safe Git path"),
"{}",
String::from_utf8_lossy(&p.stderr)
);
assert_eq!(git(&hub, &["rev-parse", "main"]).stdout, tip);

std::fs::remove_dir_all(&root).unwrap();
}
75 changes: 75 additions & 0 deletions crates/core/src/display.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! Making untrusted text safe to print to a terminal.

use std::borrow::Cow;

/// Replace control characters in text that came from a peer or from stored objects (a server's error
/// string, a commit author or message) with a visible escape, so it cannot drive the terminal with
/// ANSI/OSC sequences or reorder what is shown with bidi controls. `\n` and `\t` pass through. C0
/// controls and DEL print as `\x1b`, C1, bidi and other invisible format characters as `\u{202e}`.
/// Format-time only: stored data is never changed.
pub fn sanitize_display(s: &str) -> Cow<'_, str> {
escape(s, false)
}

/// [`sanitize_display`] for text printed inside one line (a `sc log` row, a list row): `\n`, `\r`
/// and `\t` are escaped too, so a commit message cannot start a line that looks like `sc`'s own
/// output, such as a forged signature status.
pub fn sanitize_display_line(s: &str) -> Cow<'_, str> {
escape(s, true)
}

/// Invisible characters that change how the surrounding text is laid out or read: bidi controls,
/// zero-width characters and the byte-order mark.
fn invisible_format(c: char) -> bool {
matches!(c, '\u{061c}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}')
}

fn escape(s: &str, one_line: bool) -> Cow<'_, str> {
let bad =
|c: char| (c.is_control() && (one_line || (c != '\n' && c != '\t'))) || invisible_format(c);
if !s.chars().any(bad) {
return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len() + 8);
for c in s.chars() {
if !bad(c) {
out.push(c);
} else if (c as u32) < 0x80 {
out.push_str(&format!("\\x{:02x}", c as u32));
} else {
out.push_str(&format!("\\u{{{:x}}}", c as u32));
}
}
Cow::Owned(out)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn escapes_ansi_osc_c1_and_del_but_keeps_newline_and_tab() {
let s = "a\x1b[2Jb\x1b]0;pwn\x07c\u{9b}31m\x7fd\re\nf\tg";
let out = sanitize_display(s);
assert_eq!(
out,
"a\\x1b[2Jb\\x1b]0;pwn\\x07c\\u{9b}31m\\x7fd\\x0de\nf\tg"
);
assert!(!out
.chars()
.any(|c| c.is_control() && c != '\n' && c != '\t'));
}

#[test]
fn one_line_form_escapes_newlines_and_bidi_controls() {
let s = "msg\n signature: good\r\tx\u{202e}y";
let out = sanitize_display_line(s);
assert_eq!(out, "msg\\x0a signature: good\\x0d\\x09x\\u{202e}y");
assert_eq!(sanitize_display("a\u{2066}b"), "a\\u{2066}b");
}

#[test]
fn clean_text_is_untouched_and_unallocated() {
assert!(matches!(sanitize_display("héllo — ok\n"), Cow::Borrowed(_)));
}
}
38 changes: 37 additions & 1 deletion crates/core/src/fsutil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// directory so the rename itself is durable. The parent directory must
/// exist.
pub fn atomic_write_durable(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
write_durable(path, bytes, false)
}

/// Like [`atomic_write_durable`], but the staging file (and so the final file, even when it replaces
/// a wider one) is readable by its owner only from the first byte. For files holding credential
/// material, such as `.sc/serve-tokens.toml`.
pub fn atomic_write_durable_owner_only(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
write_durable(path, bytes, true)
}

fn write_durable(path: &Path, bytes: &[u8], owner_only: bool) -> std::io::Result<()> {
let parent = path.parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
Expand All @@ -38,7 +49,11 @@ pub fn atomic_write_durable(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let tmp = path.with_extension(format!("{}.{n}.tmp", std::process::id()));
{
let mut f = std::fs::File::create(&tmp)?;
let mut f = if owner_only {
crate::owner_only::create_new_owner_only_or_warn(&tmp)?
} else {
std::fs::File::create(&tmp)?
};
f.write_all(bytes)?;
f.sync_all()?;
}
Expand Down Expand Up @@ -96,6 +111,27 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}

#[cfg(unix)]
#[test]
fn owner_only_write_is_0600_on_create_and_on_rewrite_of_a_wider_file() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("scl-fsutil-oo-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("tokens");
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;

atomic_write_durable_owner_only(&path, b"one").unwrap();
assert_eq!(mode(&path), 0o600);
// A pre-existing world-readable file (written by an older build) is replaced by a 0600 one.
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
atomic_write_durable_owner_only(&path, b"two").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"two");
assert_eq!(mode(&path), 0o600);

std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn missing_parent_directory_is_an_error_not_a_panic() {
let dir = std::env::temp_dir().join(format!("scl-fsutil-miss-{}", std::process::id()));
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! BLAKE3-addressed objects (blobs, trees, snapshots, secrets) and a [`Store`]
//! that bounds resident blob memory with LRU eviction and optional spill.

pub mod display;
pub mod error;
pub mod fsutil;
pub mod id;
Expand Down Expand Up @@ -171,6 +172,7 @@ pub fn read_exact_vec(r: &mut impl std::io::Read, len: usize) -> std::io::Result
Ok(buf)
}

pub use display::{sanitize_display, sanitize_display_line};
pub use error::{Error, Result};
pub use id::ObjectId;
pub use object::{
Expand Down
Loading
Loading