Skip to content

Commit 3e11dc9

Browse files
tlongwell-blocknpub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyfDawn (sprout agent)
authored
fix(git): carry NIP-OA delegation in auth event (#2120)
Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Signed-off-by: tlongwell-block <[email protected]> Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
1 parent e055af0 commit 3e11dc9

4 files changed

Lines changed: 176 additions & 7 deletions

File tree

‎crates/buzz-relay/src/api/git/transport.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,19 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
185185
// The ±60s timestamp window + URL scoping + HTTPS transport provide sufficient
186186
// replay protection for v1. Per-request signing requires protocol changes.
187187

188-
// Relay membership gate (NIP-43).
189-
let auth_tag = parts
188+
let event: nostr::Event = serde_json::from_str(&event_json)
189+
.map_err(|_| (StatusCode::UNAUTHORIZED, "invalid auth event").into_response())?;
190+
191+
// Relay membership gate (NIP-43). Git cannot carry a standalone
192+
// x-auth-tag header through the credential-helper protocol, so agents
193+
// attach their NIP-OA attestation to the signed NIP-98 event, matching
194+
// the WebSocket NIP-42 flow.
195+
let event_auth_tag = crate::handlers::auth::extract_auth_tag_json(&event);
196+
let header_auth_tag = parts
190197
.headers
191198
.get("x-auth-tag")
192-
.and_then(|v| v.to_str().ok());
199+
.and_then(|value| value.to_str().ok());
200+
let auth_tag = event_auth_tag.as_deref().or(header_auth_tag);
193201
if crate::api::relay_members::enforce_relay_membership(
194202
state,
195203
tenant.community(),

‎crates/buzz-relay/src/handlers/auth.rs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,3 +374,58 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc<ConnectionState>, state:
374374
}
375375
}
376376
}
377+
378+
#[cfg(test)]
379+
mod tests {
380+
use super::extract_auth_tag_json;
381+
use nostr::{EventBuilder, Keys, Kind, Tag};
382+
383+
/// Build a signed NIP-98 (kind 27235) event carrying the given tags. The
384+
/// `auth` tag lives inside the signed event exactly as the git and
385+
/// WebSocket auth paths receive it.
386+
fn signed_event_with_tags(tags: Vec<Tag>) -> nostr::Event {
387+
EventBuilder::new(Kind::HttpAuth, "")
388+
.tags(tags)
389+
.sign_with_keys(&Keys::generate())
390+
.expect("sign auth event")
391+
}
392+
393+
/// A single `auth` tag is extracted verbatim as its JSON-array string —
394+
/// this is the exact value fed to `verify_auth_tag` on the git path.
395+
#[test]
396+
fn single_auth_tag_extracted_verbatim() {
397+
let owner = Keys::generate().public_key().to_hex();
398+
let sig = "00".repeat(64);
399+
let event = signed_event_with_tags(vec![
400+
Tag::parse(["u", "https://relay/git/x/y"]).unwrap(),
401+
Tag::parse(["auth", owner.as_str(), "", sig.as_str()]).unwrap(),
402+
]);
403+
404+
let extracted = extract_auth_tag_json(&event).expect("auth tag present");
405+
let expected = serde_json::to_string(&["auth", owner.as_str(), "", sig.as_str()]).unwrap();
406+
assert_eq!(extracted, expected);
407+
}
408+
409+
/// No `auth` tag → `None` (the direct-member path, tag absent).
410+
#[test]
411+
fn no_auth_tag_returns_none() {
412+
let event =
413+
signed_event_with_tags(vec![Tag::parse(["u", "https://relay/git/x/y"]).unwrap()]);
414+
assert_eq!(extract_auth_tag_json(&event), None);
415+
}
416+
417+
/// More than one `auth` tag → `None`. Per NIP-OA, an ambiguous set of
418+
/// attestations is treated as no valid attestation (fail-closed), so a
419+
/// second forged tag cannot smuggle an alternate delegation past the gate.
420+
#[test]
421+
fn duplicate_auth_tags_return_none() {
422+
let a = Keys::generate().public_key().to_hex();
423+
let b = Keys::generate().public_key().to_hex();
424+
let sig = "00".repeat(64);
425+
let event = signed_event_with_tags(vec![
426+
Tag::parse(["auth", a.as_str(), "", sig.as_str()]).unwrap(),
427+
Tag::parse(["auth", b.as_str(), "", sig.as_str()]).unwrap(),
428+
]);
429+
assert_eq!(extract_auth_tag_json(&event), None);
430+
}
431+
}

‎crates/git-credential-nostr/src/lib.rs‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::io::{self, BufRead, Write};
1010
use base64::Engine as _;
1111
use nostr::nips::nip98::{HttpData, HttpMethod};
1212
use nostr::types::Url;
13-
use nostr::{EventBuilder, Keys};
13+
use nostr::{EventBuilder, Keys, Tag};
1414
use zeroize::Zeroize;
1515

1616
fn git_config(key: &str) -> Option<String> {
@@ -71,6 +71,30 @@ fn load_key() -> Result<String, String> {
7171
Ok(raw.trim().to_string())
7272
}
7373

74+
/// Load the NIP-OA owner attestation injected by Buzz Desktop/ACP.
75+
///
76+
/// The tag must be part of the signed NIP-98 event: Git's credential protocol
77+
/// can return an Authorization value, but it cannot add a separate HTTP header.
78+
fn load_auth_tag() -> Result<Option<Tag>, String> {
79+
let raw = std::env::var("BUZZ_AUTH_TAG")
80+
.ok()
81+
.filter(|value| !value.is_empty())
82+
.or_else(|| git_config("nostr.authtag"));
83+
84+
raw.map(|value| {
85+
let parts: Vec<String> =
86+
serde_json::from_str(&value).map_err(|e| format!("invalid NIP-OA auth tag: {e}"))?;
87+
if parts.len() != 4 || parts.first().map(String::as_str) != Some("auth") {
88+
return Err(
89+
"invalid NIP-OA auth tag: expected [auth, owner, conditions, signature]"
90+
.to_string(),
91+
);
92+
}
93+
Tag::parse(parts).map_err(|e| format!("invalid NIP-OA auth tag: {e}"))
94+
})
95+
.transpose()
96+
}
97+
7498
#[derive(Default)]
7599
struct CredRequest {
76100
has_authtype_capability: bool,
@@ -201,7 +225,19 @@ pub fn run() -> i32 {
201225

202226
let parsed_url = Url::parse(&url).unwrap_or_else(|e| panic!("invalid URL {url:?}: {e}"));
203227
let http_data = HttpData::new(parsed_url, method);
204-
let event = match EventBuilder::http_auth(http_data).sign_with_keys(&keys) {
228+
let auth_tag = match load_auth_tag() {
229+
Ok(tag) => tag,
230+
Err(e) => {
231+
eprintln!("error: {e}");
232+
return 1;
233+
}
234+
};
235+
let builder = EventBuilder::http_auth(http_data);
236+
let builder = match auth_tag {
237+
Some(tag) => builder.tag(tag),
238+
None => builder,
239+
};
240+
let event = match builder.sign_with_keys(&keys) {
205241
Ok(e) => e,
206242
Err(e) => {
207243
eprintln!("error: failed to sign NIP-98 event: {e}");

‎crates/git-credential-nostr/tests/integration.rs‎

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,12 @@ fn run_helper(input: &str, env_vars: &[(&str, &str)]) -> std::process::Output {
1818
cmd.stdin(Stdio::piped())
1919
.stdout(Stdio::piped())
2020
.stderr(Stdio::piped())
21+
.current_dir(std::env::temp_dir())
2122
.env_remove("NOSTR_PRIVATE_KEY")
22-
// Prevent git config on the test machine from supplying a keyfile.
23+
.env_remove("BUZZ_AUTH_TAG")
24+
.env_remove("GIT_CONFIG_COUNT")
25+
// Prevent git config on the test machine from supplying credentials.
26+
.env("GIT_CONFIG_GLOBAL", "/dev/null")
2327
.env("GIT_CONFIG_NOSYSTEM", "1")
2428
.env("HOME", std::env::temp_dir());
2529
for (k, v) in env_vars {
@@ -116,6 +120,69 @@ fn happy_path() {
116120
assert!(event["tags"].is_array(), "event missing 'tags'");
117121
}
118122

123+
/// A Buzz-managed agent must carry its NIP-OA owner attestation inside the
124+
/// signed NIP-98 event so the relay can admit it through the owner's membership.
125+
#[test]
126+
fn includes_nip_oa_auth_tag_in_signed_event() {
127+
let agent_keys = Keys::generate();
128+
let owner_keys = Keys::generate();
129+
let nsec = agent_keys.secret_key().to_bech32().unwrap();
130+
let auth_tag = serde_json::to_string(&[
131+
"auth",
132+
owner_keys.public_key().to_hex().as_str(),
133+
"",
134+
&"00".repeat(64),
135+
])
136+
.expect("serialize auth tag");
137+
138+
let out = run_helper(
139+
&valid_input(),
140+
&[("NOSTR_PRIVATE_KEY", &nsec), ("BUZZ_AUTH_TAG", &auth_tag)],
141+
);
142+
assert!(
143+
out.status.success(),
144+
"helper failed: {}",
145+
String::from_utf8_lossy(&out.stderr)
146+
);
147+
148+
let stdout = String::from_utf8_lossy(&out.stdout);
149+
let credential = stdout
150+
.lines()
151+
.find_map(|line| line.strip_prefix("credential="))
152+
.expect("credential output");
153+
let event_json = base64::engine::general_purpose::STANDARD
154+
.decode(credential)
155+
.expect("base64 credential");
156+
let event: nostr::Event = serde_json::from_slice(&event_json).expect("NIP-98 event");
157+
158+
assert!(
159+
event.verify().is_ok(),
160+
"auth tag must be covered by the event signature"
161+
);
162+
assert!(event.tags.iter().any(|tag| tag.as_slice()
163+
== [
164+
"auth",
165+
owner_keys.public_key().to_hex().as_str(),
166+
"",
167+
serde_json::from_str::<Vec<String>>(&auth_tag).unwrap()[3].as_str(),
168+
]));
169+
}
170+
171+
/// A configured but malformed owner attestation must fail closed rather than
172+
/// silently authenticating the agent without delegation.
173+
#[test]
174+
fn malformed_nip_oa_auth_tag_fails_closed() {
175+
let nsec = fresh_nsec();
176+
let out = run_helper(
177+
&valid_input(),
178+
&[("NOSTR_PRIVATE_KEY", &nsec), ("BUZZ_AUTH_TAG", "not-json")],
179+
);
180+
181+
assert_eq!(out.status.code(), Some(1));
182+
assert!(String::from_utf8_lossy(&out.stderr).contains("invalid NIP-OA auth tag"));
183+
assert!(!String::from_utf8_lossy(&out.stdout).contains("credential="));
184+
}
185+
119186
/// Old git (no `capability[]=authtype` in input) → empty line on stdout, exit 0.
120187
#[test]
121188
fn old_git_no_authtype_capability() {
@@ -264,7 +331,10 @@ fn bad_keyfile_permissions() {
264331

265332
let out = run_helper(
266333
&valid_input(),
267-
&[("HOME", git_config_dir.to_str().unwrap())],
334+
&[
335+
("HOME", git_config_dir.to_str().unwrap()),
336+
("GIT_CONFIG_GLOBAL", git_config_file.to_str().unwrap()),
337+
],
268338
);
269339

270340
// Clean up regardless of outcome.

0 commit comments

Comments
 (0)