Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 10 additions & 5 deletions .claude/skills/sc-cli-reference/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,12 +272,17 @@ cargo run --bin sc -- serve --http <addr> <path> [--read-only] [--allow-public]
# cap, both --http and --stdio, default 16 GiB,
# 0=unlimited, floor 256 MiB (MAX_OBJECT_SIZE);
# counted mid-stream abort -> EC_TOO_LARGE (P31)
cargo run --bin sc -- serve token add --label <name> --scope ro|rw # mint an
# sct-<hex> bearer token in .sc/serve-tokens.toml;
# raw value prints once on stdout (P29)
cargo run --bin sc -- serve token add --label <name> --scope ro|rw [--expires <30m|12h|7d|2w|YYYY-MM-DD>]
# mint an sct-<hex> bearer token in
# .sc/serve-tokens.toml; raw value prints once on
# stdout; --expires: duration or 00:00 UTC date;
# value must be in the future; default never (P29, #209)
cargo run --bin sc -- serve token rotate <label> # new secret, same label/scope and the same
# ABSOLUTE expires_at (no renewed duration); old one
# dies at once; refused if expired (#209)
cargo run --bin sc -- serve token remove <label> # drop a token by label (P29)
cargo run --bin sc -- serve token list [--json] # list token labels + scopes, never the
# raw value (P29)
cargo run --bin sc -- serve token list [--json] # list labels, scopes, expiry (EXPIRED
# flagged), never the raw value (P29)
# client: SC_HTTP_TOKEN=<raw> sc clone/fetch/push
# sc+http://... presents the bearer on every
# connection once any token is configured (P29)
Expand Down
8 changes: 6 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -816,9 +816,13 @@ scale-&-reach horizon):
- **Per-path/per-ref ACLs (P29).** `sc serve --http` access control is
all-or-nothing per connection (`ro`/`rw`); scoping a token to specific
path prefixes or refs is beyond the MVP. Deferred.
- **Token expiry/rotation metadata (P29).** `sct-` tokens have no expiry
- ~~**Token expiry/rotation metadata (P29).** `sct-` tokens have no expiry
field; rotation today is add-new + remove-old with no automation or
reminder. Deferred.
reminder.~~ **Done.** (#209) `sc serve token add --expires <30d|2030-01-31>`
stores an optional `expires_at` (Unix seconds); `verify` treats an expired
token like an unknown one (`401`); `list` shows and flags expiry; `sc serve
token rotate <label>` swaps the secret in one step. Expired entries stay in
the file. (ADR-0040.)
- ~~**`sc+https://` / TLS (P29).** `sc serve --http` is plaintext-only; a
bearer token crosses the wire in cleartext, so a public deployment must
front with a TLS reverse proxy today. A first-party TLS dependency is
Expand Down
47 changes: 43 additions & 4 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,10 +776,18 @@ enum ServeTokenOp {
/// Access scope: `ro` (read-only) or `rw` (read-write).
#[arg(long)]
scope: String,
/// Expire the token after a duration (`30m`, `12h`, `7d`, `2w`) or at
/// 00:00 UTC on a date (`2030-01-31`). Default: never expires.
#[arg(long)]
expires: Option<String>,
},
/// Remove a token by label.
Remove { label: String },
/// List token labels + scopes (never the token value itself).
/// Replace a token's secret in one step, keeping its label, scope and
/// expiry date; prints the new value ONCE. The old secret stops working
/// immediately. An expired token must be removed and re-added instead.
Rotate { label: String },
/// List token labels, scopes and expiry (never the token value itself).
List {
#[arg(long)]
json: bool,
Expand Down Expand Up @@ -3824,13 +3832,20 @@ fn run_serve_token(op: ServeTokenOp) -> Result<()> {
let repo = open_repo()?;
let layout = repo.layout();
match op {
ServeTokenOp::Add { label, scope } => {
ServeTokenOp::Add {
label,
scope,
expires,
} => {
let scope = match scope.as_str() {
"ro" => scl_repo::serve_tokens::Scope::Ro,
"rw" => scl_repo::serve_tokens::Scope::Rw,
other => anyhow::bail!("scope must be 'ro' or 'rw', got {other}"),
};
let raw = scl_repo::serve_tokens::add(layout, &label, scope)?;
let expires_at = expires
.map(|e| scl_repo::serve_tokens::parse_expiry(&e, scl_repo::serve_tokens::now()))
.transpose()?;
let raw = scl_repo::serve_tokens::add_expiring(layout, &label, scope, expires_at)?;
println!("{raw}");
eprintln!(
"token '{label}' ({scope:?}) added — store this value now; it is not recoverable"
Expand All @@ -3842,22 +3857,46 @@ fn run_serve_token(op: ServeTokenOp) -> Result<()> {
eprintln!("removed serve token '{label}'");
Ok(())
}
ServeTokenOp::Rotate { label } => {
let raw =
scl_repo::serve_tokens::rotate(layout, &label, scl_repo::serve_tokens::now())?;
println!("{raw}");
eprintln!(
"token '{label}' rotated — store this value now; the old one no longer works"
);
Ok(())
}
ServeTokenOp::List { json } => {
let tokens = scl_repo::serve_tokens::load(layout)?;
let now = scl_repo::serve_tokens::now();
if json {
let v: Vec<_> = tokens
.iter()
.map(|t| {
serde_json::json!({
"label": t.label,
"scope": format!("{:?}", t.scope).to_lowercase(),
"expires_at": t.expires_at,
"expired": t.is_expired(now),
})
})
.collect();
println!("{}", serde_json::to_string_pretty(&v)?);
} else {
for t in tokens {
println!("{} {}", t.label, format!("{:?}", t.scope).to_lowercase());
let expiry = match t.expires_at {
None => String::new(),
Some(e) => format!(
" expires {}{}",
scl_repo::serve_tokens::format_time(e),
if t.is_expired(now) { " EXPIRED" } else { "" }
),
};
println!(
"{} {}{expiry}",
t.label,
format!("{:?}", t.scope).to_lowercase()
);
}
}
Ok(())
Expand Down
85 changes: 85 additions & 0 deletions crates/cli/tests/http_remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,91 @@ fn serve_token_add_list_remove_round_trips() {
);
}

/// `--expires` shows in `list`, `rotate` prints a new value and keeps the
/// label and expiry, and a bad `--expires` is rejected.
#[test]
fn serve_token_expires_and_rotate() {
let root = tmp("token-expiry");
assert!(sc(&root, &["init"]).status.success());
let add = sc(
&root,
&[
"serve",
"token",
"add",
"--label",
"t",
"--scope",
"rw",
"--expires",
"7d",
],
);
assert!(add.status.success(), "{:?}", add);
let old = String::from_utf8_lossy(&add.stdout).trim().to_string();

let rot = sc(&root, &["serve", "token", "rotate", "t"]);
assert!(rot.status.success(), "{:?}", rot);
let new = String::from_utf8_lossy(&rot.stdout).trim().to_string();
assert!(new.starts_with("sct-") && new != old);

let list = sc(&root, &["serve", "token", "list"]);
let out = String::from_utf8_lossy(&list.stdout);
assert!(out.contains("t rw expires "), "{out}");
assert!(!out.contains("EXPIRED"), "{out}");

for bad in ["bogus", "2001-01-01"] {
let out = sc(
&root,
&[
"serve",
"token",
"add",
"--label",
"u",
"--scope",
"ro",
"--expires",
bad,
],
);
assert!(!out.status.success(), "{bad} should be rejected");
}
assert!(!sc(&root, &["serve", "token", "rotate", "missing"])
.status
.success());

// A past expires_at (written directly: `add` refuses one) is flagged.
let path = root.join(".sc").join("serve-tokens.toml");
let text = std::fs::read_to_string(&path).unwrap();
let past: Vec<String> = text
.lines()
.map(|l| {
if l.starts_with("expires_at") {
"expires_at = 1".to_string()
} else {
l.to_string()
}
})
.collect();
std::fs::write(&path, past.join("\n")).unwrap();
let list = sc(&root, &["serve", "token", "list"]);
let out = String::from_utf8_lossy(&list.stdout);
assert!(
out.contains("EXPIRED") && out.contains("1970-01-01"),
"{out}"
);
assert!(
!sc(&root, &["serve", "token", "rotate", "t"])
.status
.success(),
"rotating an expired token is refused"
);

std::fs::remove_dir_all(&root).unwrap();
assert!(!root.exists(), "test must leave no residue");
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// An invalid `--scope` is rejected with a clear message rather than
/// silently defaulting.
#[test]
Expand Down
28 changes: 27 additions & 1 deletion crates/repo/src/http_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1275,7 +1275,7 @@ fn handle_http_connection(
match opening
.bearer
.as_deref()
.and_then(|t| crate::serve_tokens::verify(&tokens, t))
.and_then(|t| crate::serve_tokens::verify(&tokens, t, crate::serve_tokens::now()))
{
Some(crate::serve_tokens::Scope::Ro) => true,
Some(crate::serve_tokens::Scope::Rw) => false,
Expand Down Expand Up @@ -2055,6 +2055,32 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}

/// An expired token is the same 401 as an unknown one, on a token-justified
/// public bind and on the loopback default alike (the entry still counts as
/// a configured token, so auth stays on).
#[test]
fn expired_token_is_401_on_both_policies() {
let root = tmp_repo("expired-token");
let layout = crate::layout::Layout::at(&root);
let raw = crate::serve_tokens::add_expiring(
&layout,
"dead",
crate::serve_tokens::Scope::Rw,
Some(1),
)
.unwrap();
for mandatory in [true, false] {
let port = spawn_real_http_server_policy_auth(root.clone(), false, mandatory);
assert_eq!(
connect_raw_status(port, Some(&raw)),
401,
"mandatory={mandatory}"
);
assert_eq!(connect_raw_status(port, None), 401, "mandatory={mandatory}");
}
let _ = std::fs::remove_dir_all(&root);
}

/// A mandatory-auth listener (tokens are the sole justification for its
/// public bind) answers 401 to everyone when its root holds no repo, not
/// 404: an unauthenticated probe must not learn whether a repo is served.
Expand Down
Loading
Loading