Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
2a8d64d
feat(core)!: verify_chain returns the proof chain's root issuer
Vasanthdev2004 Aug 14, 2026
13a2424
fix(node): gate two Unix-only tests so the crate compiles on Windows
Vasanthdev2004 Aug 14, 2026
1b1c972
feat(node): carry the verified UCAN and its root into the request
Vasanthdev2004 Aug 14, 2026
f8b9cf1
feat(node): add ucan_grants_push, anchored at the repo owner
Vasanthdev2004 Aug 14, 2026
d27f0be
feat(node): honour a delegated git/push capability on the push path
Vasanthdev2004 Aug 14, 2026
d141e59
feat(gl): gl ucan import stores a delegation for the push helper
Vasanthdev2004 Aug 14, 2026
3d81f57
feat(git-remote): send a delegated push capability as X-Ucan
Vasanthdev2004 Aug 14, 2026
8843c4f
test(git-remote): cover pack-POST URL splitting
Vasanthdev2004 Aug 14, 2026
a9e9c48
build: sync Cargo.lock for the git-remote-gitlawb dependencies
Vasanthdev2004 Aug 14, 2026
f455726
fix(core,gl,git-remote): close two review findings on delegated push
Vasanthdev2004 Aug 14, 2026
a2502fc
fix(core,node,gl,git-remote): close the second review round on delega…
Vasanthdev2004 Aug 14, 2026
d503655
fix(gl): restrict the delegations directory, and state the contract
Vasanthdev2004 Aug 14, 2026
5071524
fix(gl,git-remote): make a delegation issued the documented way actua…
Vasanthdev2004 Aug 15, 2026
5dfd8c5
fix(gl): refuse a relative or non-UTF-8 GITLAWB_KEY when deriving the…
Vasanthdev2004 Aug 15, 2026
e15fa73
fix(identity): one resolver for GITLAWB_KEY across gl and the helper
Vasanthdev2004 Aug 16, 2026
05fc52d
test(git-remote): cover delegation_header end to end
Vasanthdev2004 Aug 16, 2026
75aa1a0
fix(gl): finish the identity-path sweep on the write side
Vasanthdev2004 Aug 16, 2026
fad75a6
fix(gl,core): close round five — lazy home, envelope reads, honest re…
Vasanthdev2004 Aug 18, 2026
82f2484
fix(node,gl,git-remote): enforce repo narrowing at the node, honour t…
Vasanthdev2004 Aug 22, 2026
a47ea93
fix(gl): align the MCP ucan_show tool with gl ucan show
Vasanthdev2004 Aug 22, 2026
ec4399c
fix(gl): drop a needless borrow in quickstart's unix key write
Vasanthdev2004 Aug 22, 2026
1ab55e5
fix(node,gl,git-remote): fix a delegation's scope at issuance
Vasanthdev2004 Aug 22, 2026
89fa647
Merge origin/main into feat/ucan-push-authorization
Vasanthdev2004 Aug 27, 2026
9cf48f5
fix(gl): drop an unused import in the unix-only refresh tests
Vasanthdev2004 Aug 27, 2026
04e7941
fix(node): pass the UCAN extension at the last two receive-pack call …
Vasanthdev2004 Aug 27, 2026
f79309b
fix(core,node,gl,git-remote): one definition of a usable push capability
Vasanthdev2004 Sep 8, 2026
4dc62b2
fix(node): drop repo_capability_matches, orphaned by the shared push …
Vasanthdev2004 Sep 8, 2026
1da4251
fix(core,gl): bound every proof-chain walk and make verify report the…
Vasanthdev2004 Sep 8, 2026
fb831b1
docs: state the two gates a delegated push crosses, and finish the sweep
Vasanthdev2004 Sep 8, 2026
8b91f28
fix(gl): store one repository per imported delegation; pin the two-ga…
Vasanthdev2004 Sep 8, 2026
e3314c6
fix(gl,core): sanitize token-derived output, prove the publish step, …
Vasanthdev2004 Sep 8, 2026
1b5cb7d
test(gl): count the MCP tool list at 41 with ucan_import
Vasanthdev2004 Sep 8, 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
Prev Previous commit
Next Next commit
fix(identity): one resolver for GITLAWB_KEY across gl and the helper
`gl` and `git-remote-gitlawb` each carried their own answer to "where is my
identity?", and so did five call sites inside `gl` itself. The round-three fix
hardened one of them — `gitlawb_dir` — and left the rest, which is why the same
misconfiguration kept surfacing in a new place each round.

The rules now live in `gitlawb-core::identity_path`, the crate both binaries
already depend on:

  identity_key_path()  $GITLAWB_KEY, else ~/.gitlawb/identity.pem
  identity_dir()       its parent — the delegation store

read through `var_os` (so a non-UTF-8 path is refused rather than folded into
"unset" by `var`), with `~/` expanded on the first path component, a relative
value refused, and a bare `~`, `~/`, or `/` refused rather than resolved to a
directory whose parent is not where anything lives.

Both take the home directory as an argument rather than looking it up: core is
held to an explicit dependency allowlist and both callers already carry `dirs`,
so the rules can be shared without widening core's tree. It also lets every
case be tested against a fixed home instead of the machine's.

Call sites moved onto it:

  gl   identity::gitlawb_dir            delegates to identity_dir
  gl   identity::load_keypair_from_dir  was ~/.gitlawb even after `gl identity
                                        new` wrote elsewhere, so `gl ucan
                                        delegate` signed with a stale DID — or
                                        found nothing — for exactly the
                                        operators who moved their key. Every
                                        `load_keypair_from_dir(None)` caller
                                        (register, repo, pr, clone, mcp) is
                                        fixed with it.
  gl   doctor::run                      the one command whose job is to explain
                                        a broken setup was reporting on a
                                        directory the setup does not use
  gl   init (ucan.json, generate_identity)
  gl   mcp ucan_show
  gl   ucan_cmd::cmd_show
  helper resolve_key_path / the delegation store behind delegation_header

The helper's version was the loosest of the set: `env::var`, a literal `"~/"`
prefix, `HOME` falling back to `"."` (never set on Windows), and no absolute
check at all.

Also in this commit:

- `gl ucan import` creates the store and the token at their final mode.
  `create_dir_all` then chmod leaves 0755 under the usual umask, and
  `fs::write` then chmod leaves 0644, both readable by any local user until the
  second call lands. `DirBuilder::mode` and `OpenOptions::mode` close the
  window; the trailing `set_permissions` now only matters for a store an older
  `gl` left behind.

- `gl ucan import` refuses a delegation the push path cannot use. It filtered on
  resource shape only, so a `pr/open` token printed "Stored delegation for
  owner/repo" and was then dropped by `build_invocation` behind a
  `tracing::warn`, surfacing as a 403 with nothing connecting it to the earlier
  success. Import now applies the same push-class filter the helper does.

- README's write-authorization limitation is narrowed to what is actually
  missing (revocation, `nb` interpretation, non-push capabilities) rather than
  claiming delegated push is not implemented.

Every new guard was verified by disabling it and watching the matching test go
red: the absolute-path check, the bare-`~` refusal, the `load_keypair_from_dir`
routing, and the import action filter each own a failing test.
  • Loading branch information
Vasanthdev2004 committed Aug 16, 2026
commit e15fa73466f64a4eb624bbcfd8589e9391941f39
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
# All variables are optional unless marked REQUIRED.

# ── Node identity ─────────────────────────────────────────────────────────
# Path to the node's Ed25519 keypair PEM file.
# Path to the node's Ed25519 keypair PEM file. Must be absolute: its parent is
# also the delegation store that `gl ucan import` writes and `git-remote-gitlawb`
# reads, and the two do not share a working directory, so a relative path sends
# them to different places. `~/...` is expanded; a bare `~` is not accepted.
# Generate with: gl identity new
GITLAWB_KEY=/data/keys/identity.pem

Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ Good today:
Known limitations:

- Repository write authorization is not secure by default: `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `false` for compatibility, so a valid HTTP Signature identifies a pusher but does not enforce owner-only pushes.
- UCAN proof chains are validated when supplied, but UCAN capabilities are not consulted by write authorization and the root issuer is not independently trust-anchored. UCANs therefore do not yet grant scoped collaborator access.
- UCAN capabilities are consulted on the push path only. There, the chain's root issuer is anchored to the repository owner, so an owner-rooted, time-bounded delegation of `git/push` (or `*`/`repo/admin`) clears the owner-push gate and does grant scoped collaborator access for pushing. The rest is unchanged: there is no revocation path, `nb` constraints are refused rather than interpreted, and no other route — reads, pull requests, issues, agents — consults capabilities at all.
- Agent lifecycle revocation is not enforced by HTTP Signature authorization; do not rely on removing or revoking an agent record to block a compromised signer.
- Read visibility is not a blanket data-classification boundary: task, IPFS-pin, and Arweave-anchor listings are not repository-gated; withheld path names can be visible to a root reader; and later visibility changes cannot retract content already announced or externally anchored.
- Peer writes are signed by upgraded nodes, but strict signed-peer enforcement is opt-in during rolling upgrades.
Expand Down
3 changes: 3 additions & 0 deletions crates/git-remote-gitlawb/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ serde_json = { workspace = true }
chrono = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
# Home-directory lookup for the shared GITLAWB_KEY resolver in gitlawb-core,
# which takes `home` as an argument so core's dependency allowlist stays lean.
dirs = "5"

[dev-dependencies]
mockito = "1"
Expand Down
50 changes: 38 additions & 12 deletions crates/git-remote-gitlawb/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ fn help_text() -> String {
\n\
ENVIRONMENT:\n\
\x20 GITLAWB_NODE Node base URL (default: http://127.0.0.1:7545)\n\
\x20 GITLAWB_KEY Identity PEM path for signed fetch/push (default: ~/.gitlawb/identity.pem)\n\
\x20 GITLAWB_KEY Identity PEM path for signed fetch/push, absolute\n\
\x20 (default: ~/.gitlawb/identity.pem). Its parent also\n\
\x20 holds the delegations `gl ucan import` writes.\n\
\x20 GITLAWB_LOG Log filter (default: warn)\n\
\n\
FLAGS:\n\
Expand Down Expand Up @@ -536,7 +538,7 @@ fn delegation_header(
return None;
}

let dir = resolve_key_path().parent()?.to_path_buf();
let dir = resolve_identity_dir()?;
let path = delegation_path(&dir, &owner, &repo);
let raw = std::fs::read_to_string(&path).ok()?;

Expand Down Expand Up @@ -969,7 +971,7 @@ fn safe_error_body_excerpt(body: &str) -> String {
// ── Keypair loading ───────────────────────────────────────────────────────────

fn load_keypair() -> Option<Keypair> {
let key_path = resolve_key_path();
let key_path = resolve_key_path()?;
if !key_path.exists() {
tracing::debug!("no keypair found at {key_path:?}");
return None;
Expand All @@ -992,16 +994,40 @@ fn load_keypair() -> Option<Keypair> {
}
}

fn resolve_key_path() -> std::path::PathBuf {
let path_str =
std::env::var("GITLAWB_KEY").unwrap_or_else(|_| "~/.gitlawb/identity.pem".to_string());
/// The identity PEM, resolved by the same rules `gl` uses.
///
/// Shared through `gitlawb-core` rather than reimplemented here: this helper and
/// `gl ucan import` have to derive the same delegation store from `GITLAWB_KEY`,
/// and the two had drifted — the local version read `env::var` (so a non-UTF-8
/// value silently became the default key), expanded only a literal `"~/"`, fell
/// back to `"."` when `HOME` was unset, and never required an absolute path.
///
/// `None` means the value is unusable, not that the key is missing. Git runs this
/// helper mid-push, so a misconfiguration is logged and the push continues
/// unsigned rather than aborting the transfer.
fn resolve_key_path() -> Option<std::path::PathBuf> {
let home = home_dir()?;
gitlawb_core::identity_path::identity_key_path(&home)
.inspect_err(|e| tracing::warn!("cannot resolve the identity key path: {e}"))
.ok()
}

if let Some(stripped) = path_str.strip_prefix("~/") {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
std::path::PathBuf::from(home).join(stripped)
} else {
std::path::PathBuf::from(path_str)
}
/// The directory holding `identity.pem` and `delegations/`.
fn resolve_identity_dir() -> Option<std::path::PathBuf> {
let home = home_dir()?;
gitlawb_core::identity_path::identity_dir(&home)
.inspect_err(|e| tracing::warn!("cannot resolve the identity directory: {e}"))
.ok()
}

/// `dirs`, not `$HOME`: the old code fell back to `"."` when `HOME` was unset,
/// which on Windows is always, so the default key resolved against whatever
/// directory git happened to invoke the helper from.
fn home_dir() -> Option<std::path::PathBuf> {
dirs::home_dir().or_else(|| {
tracing::warn!("could not determine the home directory; pushing without a delegation");
None
})
}

// ── Tests ─────────────────────────────────────────────────────────────────────
Expand Down
240 changes: 240 additions & 0 deletions crates/gitlawb-core/src/identity_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
//! Where the identity key and the delegation store live.
//!
//! `gl` and `git-remote-gitlawb` have to agree on this. `gl ucan import` writes a
//! delegation to `<dir>/delegations/`, and the helper reads it back from the same
//! place when it builds the `X-Ucan` header on push. If the two resolve
//! `GITLAWB_KEY` differently the push goes out with no header and the node refuses
//! the delegate, with nothing on either side to say why — so the rules live here
//! once, in the crate both binaries already depend on, rather than being written
//! twice and drifting.
//!
//! The home directory is a parameter rather than something this module looks up.
//! `gitlawb-core` is embedded by every consumer and is held to an explicit
//! dependency allowlist (`ci/gitlawb-core-allowed-deps.txt`); the callers already
//! carry `dirs`, so taking `home` keeps the rules shared without widening core's
//! tree. It also makes every case below testable against a fixed home.

use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};

use crate::{Error, Result};

/// Environment variable naming the identity PEM.
pub const KEY_ENV: &str = "GITLAWB_KEY";

/// Name of the PEM file inside the identity directory.
pub const KEY_FILE_NAME: &str = "identity.pem";

/// Directory under the home directory used when `GITLAWB_KEY` is unset.
pub const DEFAULT_DIR_NAME: &str = ".gitlawb";

/// Absolute path of the identity PEM: `$GITLAWB_KEY`, else
/// `<home>/.gitlawb/identity.pem`.
///
/// An empty `GITLAWB_KEY` counts as unset. That is what a shell leaves behind for
/// `FOO=` and for an unset variable expanded into a wrapper script, and reading it
/// as a path would resolve against the process working directory instead.
pub fn identity_key_path(home: &Path) -> Result<PathBuf> {
// `var_os`, not `var`: `var` folds a non-UTF-8 value into the same `Err` as
// unset, so an operator whose key path is not valid UTF-8 would silently get
// the default directory rather than theirs — or an error naming the real
// problem.
match std::env::var_os(KEY_ENV) {
Some(raw) if !raw.is_empty() => resolve_key_value(Path::new(&raw), home),
_ => Ok(home.join(DEFAULT_DIR_NAME).join(KEY_FILE_NAME)),
}
}

/// The directory holding `identity.pem` and `delegations/` — the parent of
/// [`identity_key_path`].
pub fn identity_dir(home: &Path) -> Result<PathBuf> {
let key = identity_key_path(home)?;
key.parent().map(Path::to_path_buf).ok_or_else(|| {
Error::Key(format!(
"{KEY_ENV} has no parent directory: {}",
key.display()
))
})
}

/// Apply the `GITLAWB_KEY` rules to a raw value.
///
/// Split out from [`identity_key_path`] so the rules can be tested without setting
/// a process-global environment variable, which would make the tests race.
fn resolve_key_value(raw: &Path, home: &Path) -> Result<PathBuf> {
let path = expand_tilde(raw, home)?;

if !path.is_absolute() {
return Err(Error::Key(format!(
"{KEY_ENV} must be an absolute path (got {}). It also determines where \
delegations are stored, and `gl` and `git-remote-gitlawb` do not share a \
working directory, so a relative path sends them to different stores.",
raw.display()
)));
}
if path.parent().is_none() {
return Err(Error::Key(format!(
"{KEY_ENV} must name the key file, not the filesystem root (got {}). \
Point it at the PEM, e.g. ~/{DEFAULT_DIR_NAME}/{KEY_FILE_NAME}.",
raw.display()
)));
}
Ok(path)
}

/// Expand a leading `~/`, and only that.
///
/// `~user` is shell syntax this does not implement; leaving its `~` in place makes
/// it fail the absolute-path check with a message that names the real problem,
/// which beats resolving it somewhere the operator did not ask for. A bare `~` or
/// `~/` is refused outright: it names a directory where a file is required, and
/// expanding it to the home directory would put the delegation store beside the
/// home directory rather than inside it, since the store is the key's *parent*.
///
/// Matched on the first path component rather than on a string prefix. That is
/// what lets the value stay an `OsStr` end to end: the helper's old
/// `str::strip_prefix("~/")` needed a `String` first, which is why it reached for
/// `env::var` and folded every non-UTF-8 path into "unset".
fn expand_tilde(path: &Path, home: &Path) -> Result<PathBuf> {
let mut components = path.components();
match components.next() {
Some(Component::Normal(first)) if first == OsStr::new("~") => {
let rest = components.as_path();
if rest.as_os_str().is_empty() {
return Err(Error::Key(format!(
"{KEY_ENV} must name the key file, not a directory (got {}). \
Point it at the PEM, e.g. ~/{DEFAULT_DIR_NAME}/{KEY_FILE_NAME}.",
path.display()
)));
}
Ok(home.join(rest))
}
_ => Ok(path.to_path_buf()),
}
}

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

/// A home that is absolute on the host running the tests. `/home/op` is not
/// absolute on Windows — it has a root but no prefix — so a shared literal
/// would make the absolute-path assertions test the wrong thing there.
fn home() -> PathBuf {
if cfg!(windows) {
PathBuf::from(r"C:\Users\op")
} else {
PathBuf::from("/home/op")
}
}

#[test]
fn absolute_value_is_taken_verbatim() {
let raw = home().join("data").join("keys").join(KEY_FILE_NAME);
assert_eq!(resolve_key_value(&raw, &home()).unwrap(), raw);
}

#[test]
fn tilde_slash_expands_to_the_home_directory() {
let resolved = resolve_key_value(Path::new("~/keys/identity.pem"), &home()).unwrap();
assert_eq!(resolved, home().join("keys").join(KEY_FILE_NAME));
}

/// The shell-style spelling of the default resolves to the default. Worth
/// pinning: this is the form an operator gets by copying a path out of their
/// shell, and the two binaries used to reach it by different routes.
#[test]
fn the_tilde_spelling_of_the_default_resolves_to_the_default() {
let resolved = resolve_key_value(Path::new("~/.gitlawb/identity.pem"), &home()).unwrap();
assert_eq!(resolved, home().join(DEFAULT_DIR_NAME).join(KEY_FILE_NAME));
}

/// A relative value resolves against the working directory, and `gl` and
/// `git-remote-gitlawb` do not share one: the import would land where the helper
/// never looks.
#[test]
fn relative_values_are_refused() {
for raw in ["identity.pem", "keys/identity.pem", "./keys/identity.pem"] {
assert!(
resolve_key_value(Path::new(raw), &home()).is_err(),
"{raw} is relative and must be refused"
);
}
}

/// `~user` is shell syntax, not a path, and a bare `~` names a directory where
/// a file is required. Refused rather than guessed at.
#[test]
fn unsupported_tilde_forms_are_refused() {
for raw in ["~", "~/", "~someone/keys/identity.pem"] {
assert!(
resolve_key_value(Path::new(raw), &home()).is_err(),
"{raw} must be refused rather than resolved"
);
}
}

/// The root has no parent, so the delegation store would have nowhere to go.
#[test]
fn the_filesystem_root_is_refused() {
assert!(resolve_key_value(Path::new("/"), &home()).is_err());
}

/// The whole point of `var_os`: a non-UTF-8 value must reach the rules rather
/// than being folded into "unset" by `var`. Byte 0xFF is not valid UTF-8 in any
/// position, so this value is unreachable through `env::var`.
#[cfg(unix)]
#[test]
fn non_utf8_values_reach_the_rules() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;

let relative = OsString::from_vec(b"keys/\xFF/identity.pem".to_vec());
assert!(
resolve_key_value(Path::new(&relative), &home()).is_err(),
"a non-UTF-8 relative path must be refused, not silently defaulted"
);

let mut absolute = OsString::from("/data/");
absolute.push(OsString::from_vec(vec![0xFF]));
absolute.push("/identity.pem");
let resolved = resolve_key_value(Path::new(&absolute), &home()).unwrap();
assert_eq!(resolved.as_os_str(), absolute.as_os_str());
}

/// Unset and empty both mean "use the default", and the two accessors must stay
/// consistent: the directory is the parent of the key, never a sibling of it.
/// The process environment is global, so the two cases share one test and one
/// lock rather than racing each other.
#[test]
fn unset_and_empty_both_select_the_default_directory() {
use std::sync::Mutex;
static LOCK: Mutex<()> = Mutex::new(());
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());

let restore = std::env::var_os(KEY_ENV);

std::env::remove_var(KEY_ENV);
let unset = (identity_key_path(&home()), identity_dir(&home()));
std::env::set_var(KEY_ENV, "");
let empty = (identity_key_path(&home()), identity_dir(&home()));

match restore {
Some(v) => std::env::set_var(KEY_ENV, v),
None => std::env::remove_var(KEY_ENV),
}

for (label, (key, dir)) in [("unset", unset), ("empty", empty)] {
assert_eq!(
key.unwrap(),
home().join(DEFAULT_DIR_NAME).join(KEY_FILE_NAME),
"{label} key path"
);
assert_eq!(
dir.unwrap(),
home().join(DEFAULT_DIR_NAME),
"{label} directory"
);
}
}
}
1 change: 1 addition & 0 deletions crates/gitlawb-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod encrypt;
pub mod error;
pub mod http_sig;
pub mod identity;
pub mod identity_path;
pub mod sanitize;
pub mod ucan;

Expand Down
10 changes: 5 additions & 5 deletions crates/gl/src/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,11 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
println!("gl doctor — checking your gitlawb setup");
println!();

let dir = args.dir.unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".gitlawb")
});
// The same resolver every other command uses. `doctor` reporting on
// `~/.gitlawb` while `gl register` writes to the parent of `GITLAWB_KEY` would
// make the one command whose job is to explain a broken setup the one that
// misreports it.
let dir = crate::identity::gitlawb_dir(args.dir)?;

let mut checks = Vec::new();
let mut all_ok = true;
Expand Down
Loading