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(gl): finish the identity-path sweep on the write side
The previous commit unified where `gl` READS the identity from and stopped
there. Four resolvers were left holding their own `~/.gitlawb`, and one of them
is a write:

  register.rs   ucan_path        the bootstrap UCAN from POST /api/register
  quickstart.rs the wizard dir   identity generation AND the UCAN it stores
  name.rs       identity_dir     reads identity.pem
  node_stake.rs load_did         reads identity.pem

`register.rs` is the one that actually breaks a working setup. With
`GITLAWB_KEY=/data/keys/identity.pem` — the shape `.env.example` documents —
`gl register` loaded the key from `/data/keys/identity.pem` and then wrote
`ucan.json` to `~/.gitlawb/`. Registration reported success; `gl doctor`,
`gl ucan show`, `gl init`, and `gl mcp ucan_show` all read `ucan.json` from the
key's directory, found nothing, and reported an unregistered identity. Split
storage, no error anywhere.

`quickstart` had the same shape end to end: it generates the identity and stores
the bootstrap token, so an operator who ran the wizard under `GITLAWB_KEY` got
both in a directory nothing else consults.

`name.rs` and `node_stake.rs` only read, but both fell back to `PathBuf::from(".")`
when the home directory could not be determined, which makes the identity path
depend on the working directory — the same defect the helper's `resolve_key_path`
carried before it moved to the shared resolver.

All four now go through `crate::identity::gitlawb_dir`. Afterwards the only
`dirs::home_dir()` calls left in `gl` are the one inside `gitlawb_dir` itself,
one test expectation, and `doctor`'s shell-rc scan, which is unrelated to the
identity directory.

`gl register` also no longer prints a path it did not use: the success line was
hardcoded to `~/.gitlawb/ucan.json`, so an operator with `GITLAWB_KEY` set was
told to look somewhere the file was not. It now prints the real destination, and
says so plainly when the node returned no token at all.

The `GITLAWB_KEY` test guard moves to `identity::test_env` so the resolver's own
cases and the new register case share one lock. Two suites each holding their
own mutex over the same process-global variable would not serialise against each
other.

Verified by reverting `ucan_path` to the hardcoded form and watching
`register_saves_the_bootstrap_ucan_beside_the_key` fail on exactly that
assertion.
  • Loading branch information
Vasanthdev2004 committed Aug 16, 2026
commit 75aa1a0a4ebe8c778cdedfceef9ea692f3567a4e
62 changes: 45 additions & 17 deletions crates/gl/src/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,32 +523,60 @@ mod tests {
}
}

/// Scoped `GITLAWB_KEY` for tests, shared crate-wide.
///
/// The process environment is global and more than one suite in this crate
/// depends on it — the resolver's own cases here, and `gl register`'s check that
/// the bootstrap token lands beside the key. They take one lock rather than each
/// declaring its own, which would not serialise them against each other.
#[cfg(test)]
mod gitlawb_dir_tests {
use super::{gitlawb_dir, load_keypair_from_dir};
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::Mutex;
pub(crate) mod test_env {
use std::ffi::{OsStr, OsString};
use std::sync::{Mutex, MutexGuard};

/// The process environment is global. Every case that touches `GITLAWB_KEY`
/// takes this lock so they cannot race each other.
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// Run `f` with `GITLAWB_KEY` set to `value` (or removed for `None`), restoring
/// whatever was there before.
fn with_key_env<T>(value: Option<OsString>, f: impl FnOnce() -> T) -> T {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
/// Restores the previous value and releases the lock on drop.
pub(crate) struct KeyEnv {
_guard: MutexGuard<'static, ()>,
restore: Option<OsString>,
}

impl Drop for KeyEnv {
fn drop(&mut self) {
match self.restore.take() {
Some(v) => std::env::set_var("GITLAWB_KEY", v),
None => std::env::remove_var("GITLAWB_KEY"),
}
}
}

/// Set `GITLAWB_KEY` (or remove it, for `None`) until the guard drops.
pub(crate) fn set_key<V: AsRef<OsStr>>(value: Option<V>) -> KeyEnv {
let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let restore = std::env::var_os("GITLAWB_KEY");
match &value {
match value {
Some(v) => std::env::set_var("GITLAWB_KEY", v),
None => std::env::remove_var("GITLAWB_KEY"),
}
let out = f();
match restore {
Some(v) => std::env::set_var("GITLAWB_KEY", v),
None => std::env::remove_var("GITLAWB_KEY"),
KeyEnv {
_guard: guard,
restore,
}
out
}
}

#[cfg(test)]
mod gitlawb_dir_tests {
use super::{gitlawb_dir, load_keypair_from_dir};
use std::ffi::OsString;
use std::path::PathBuf;

/// Run `f` with `GITLAWB_KEY` set to `value` (or removed for `None`), restoring
/// whatever was there before.
fn with_key_env<T>(value: Option<OsString>, f: impl FnOnce() -> T) -> T {
let _env = crate::identity::test_env::set_key(value);
f()
}

/// An explicit --dir always wins and is never validated against GITLAWB_KEY.
Expand Down
15 changes: 7 additions & 8 deletions crates/gl/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,16 +168,15 @@ pub async fn run(args: NameArgs) -> Result<()> {

// ── Helpers ───────────────────────────────────────────────────────────────────

fn identity_dir(dir: Option<PathBuf>) -> PathBuf {
dir.unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".gitlawb")
})
fn identity_dir(dir: Option<PathBuf>) -> Result<PathBuf> {
// The shared resolver, not a local `~/.gitlawb`: `gl identity new` writes the
// key wherever `GITLAWB_KEY` points, and the old fallback to `.` on a missing
// home made the answer depend on the working directory.
crate::identity::gitlawb_dir(dir)
}

fn load_did(dir: Option<PathBuf>) -> Result<String> {
let path = identity_dir(dir).join("identity.pem");
let path = identity_dir(dir)?.join("identity.pem");
let pem = std::fs::read_to_string(&path).with_context(|| {
format!(
"No identity at {} — run `gl identity new` first",
Expand All @@ -190,7 +189,7 @@ fn load_did(dir: Option<PathBuf>) -> Result<String> {
}

fn load_did_and_document(dir: Option<PathBuf>) -> Result<(String, String)> {
let path = identity_dir(dir).join("identity.pem");
let path = identity_dir(dir)?.join("identity.pem");
let pem = std::fs::read_to_string(&path).with_context(|| {
format!(
"No identity at {} — run `gl identity new` first",
Expand Down
9 changes: 4 additions & 5 deletions crates/gl/src/node_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,11 +328,10 @@ pub async fn cmd_unstake(
// ── Helpers ─────────────────────────────────────────────────────────────────

fn load_did(dir: Option<PathBuf>) -> Result<String> {
let base = dir.unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".gitlawb")
});
// The shared resolver, not a local `~/.gitlawb`: `gl identity new` writes the
// key wherever `GITLAWB_KEY` points, and the old fallback to `.` on a missing
// home made the answer depend on the working directory.
let base = crate::identity::gitlawb_dir(dir)?;
let path = base.join("identity.pem");
let pem = std::fs::read_to_string(&path).with_context(|| {
format!(
Expand Down
9 changes: 4 additions & 5 deletions crates/gl/src/quickstart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@ pub async fn run(args: QuickstartArgs) -> Result<()> {
println!("and create your first repository.");
println!();

let dir = args.dir.clone().unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".gitlawb")
});
// The wizard generates the identity AND stores the bootstrap UCAN, so it has to
// land where every later command reads from — the parent of `GITLAWB_KEY`, not
// an unconditional `~/.gitlawb`.
let dir = crate::identity::gitlawb_dir(args.dir.clone())?;

// ── Step 1: Identity ──────────────────────────────────────────────────
println!("── Step 1: Identity ─────────────────────────────────────────────────");
Expand Down
83 changes: 68 additions & 15 deletions crates/gl/src/register.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! `gl register` — register this agent identity with a gitlawb node.
//!
//! Sends a signed POST /api/register request and saves the returned bootstrap
//! UCAN token to `~/.gitlawb/ucan.json` for use by other commands.
//! UCAN token as `ucan.json` beside the identity key, where the other commands
//! look for it.

use anyhow::{Context, Result};
use clap::Args;
Expand Down Expand Up @@ -69,17 +70,20 @@ pub async fn run(args: RegisterArgs) -> Result<()> {
// Save bootstrap UCAN
let ucan = payload.get("ucan").and_then(|v| v.as_str()).unwrap_or("");

if !ucan.is_empty() {
let ucan_path = ucan_path(args.dir.as_deref())?;
let saved_to = if ucan.is_empty() {
None
} else {
let path = ucan_path(args.dir.as_deref())?;
let record = json!({
"ucan": ucan,
"node": args.node,
"did": did.to_string(),
"saved_at": chrono::Utc::now().to_rfc3339(),
});
std::fs::write(&ucan_path, serde_json::to_string_pretty(&record)?)?;
tracing::debug!("saved UCAN to {}", ucan_path.display());
}
std::fs::write(&path, serde_json::to_string_pretty(&record)?)?;
tracing::debug!("saved UCAN to {}", path.display());
Some(path)
};

let trust = payload
.get("trust_score")
Expand All @@ -99,21 +103,28 @@ pub async fn run(args: RegisterArgs) -> Result<()> {
println!(" Trust score: {trust:.2}");
println!(" UCAN expires: {expires}");
println!();
println!(" Bootstrap UCAN saved to ~/.gitlawb/ucan.json");
// The real path, not the default one: `GITLAWB_KEY` moves it, and an operator
// told to look in `~/.gitlawb` would find nothing there.
match &saved_to {
Some(path) => println!(" Bootstrap UCAN saved to {}", path.display()),
None => println!(" The node returned no bootstrap UCAN."),
}
println!(" You are now a verified agent on the gitlawb network.");

Ok(())
}

/// Where the bootstrap UCAN is stored: beside the identity key, always.
///
/// Routed through `gitlawb_dir` rather than resolving `~/.gitlawb` locally. The
/// key is READ from the parent of `GITLAWB_KEY`, so writing the token anywhere
/// else splits the two: registration succeeds, and `gl doctor`, `gl ucan show`,
/// `gl init`, and `gl mcp ucan_show` all read `ucan.json` from the key's
/// directory and report an unregistered identity.
fn ucan_path(dir: Option<&std::path::Path>) -> Result<PathBuf> {
let base = if let Some(d) = dir {
d.to_path_buf()
} else {
dirs::home_dir()
.context("could not determine home directory")?
.join(".gitlawb")
};
std::fs::create_dir_all(&base)?;
let base = crate::identity::gitlawb_dir(dir.map(std::path::Path::to_path_buf))?;
std::fs::create_dir_all(&base)
.with_context(|| format!("failed to create {}", base.display()))?;
Ok(base.join("ucan.json"))
}

Expand Down Expand Up @@ -160,6 +171,48 @@ mod tests {
assert_eq!(content["node"].as_str().unwrap(), server.url());
}

/// `gl register` READS the identity from the parent of `GITLAWB_KEY`, so it has
/// to WRITE the bootstrap token there too. Sending it to `~/.gitlawb` instead is
/// silent split-brain: registration prints success, and every command that later
/// reads `ucan.json` — `gl doctor`, `gl ucan show`, `gl init`, `gl mcp` — looks
/// beside the key, finds nothing, and reports an unregistered identity.
#[tokio::test]
async fn register_saves_the_bootstrap_ucan_beside_the_key() {
let dir = TempDir::new().unwrap();
write_identity(&dir);
// No --dir: the destination has to come from GITLAWB_KEY alone.
let _env = crate::identity::test_env::set_key(Some(dir.path().join("identity.pem")));

let mut server = mockito::Server::new_async().await;
let _m = server
.mock("POST", "/api/register")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"message":"Welcome","ucan":"eyJhbGci.test.token","trust_score":0.5,"expires":"2026-12-31"}"#,
)
.create_async()
.await;

run(RegisterArgs {
node: server.url(),
capabilities: vec!["git:push".to_string()],
model: None,
dir: None,
})
.await
.unwrap();

let beside_the_key = dir.path().join("ucan.json");
assert!(
beside_the_key.exists(),
"the bootstrap UCAN must land beside GITLAWB_KEY, not in ~/.gitlawb"
);
let content: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(beside_the_key).unwrap()).unwrap();
assert_eq!(content["ucan"].as_str().unwrap(), "eyJhbGci.test.token");
}

#[tokio::test]
async fn test_register_server_error() {
let dir = TempDir::new().unwrap();
Expand Down
Loading