diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index b6ec1806..4c9df644 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -413,6 +413,49 @@ pub(crate) async fn read_json(resp: reqwest::Response, what: &str) -> Result bool { + use gitlawb_core::http_sig::{build_signing_string, HttpSignature}; + use std::collections::HashMap; + + let header = |name: &str| -> Option { + req.header(name) + .first() + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + }; + let (Some(input), Some(sig_header), Some(digest)) = ( + header("signature-input"), + header("signature"), + header("content-digest"), + ) else { + return false; + }; + let Ok(sig) = HttpSignature::parse(&input, &sig_header) else { + return false; + }; + let Ok(vk) = sig.key_id.to_verifying_key() else { + return false; + }; + let mut values = HashMap::new(); + values.insert("@method".to_string(), "GET".to_string()); + values.insert("@path".to_string(), req.path_and_query().to_string()); + values.insert("content-digest".to_string(), digest); + let params = input.strip_prefix("sig1=").unwrap_or(&input); + let components: Vec<&str> = sig.components.iter().map(String::as_str).collect(); + let Ok(signing_string) = build_signing_string(&components, params, &values) else { + return false; + }; + let Ok(arr) = <[u8; 64]>::try_from(sig.signature_bytes.as_slice()) else { + return false; + }; + gitlawb_core::identity::verify(&vk, signing_string.as_bytes(), &arr).is_ok() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/gl/src/mcp.rs b/crates/gl/src/mcp.rs index 06340ec9..52508941 100644 --- a/crates/gl/src/mcp.rs +++ b/crates/gl/src/mcp.rs @@ -223,7 +223,7 @@ fn tool_definitions() -> Value { "required": ["name"], "properties": { "name": { "type": "string", "description": "Repository name" }, - "owner": { "type": "string", "description": "Owner DID or short DID (optional, defaults to node owner)" } + "owner": { "type": "string", "description": "Owner DID or short DID (optional, defaults to the signing identity when one is configured, otherwise the node owner)" } } } }, @@ -716,9 +716,15 @@ async fn call_tool( "repo_get" => { let name = args["name"].as_str().context("missing 'name'")?; - let owner = resolve_owner(&args, &client).await?; + let owner = resolve_signed_read_owner(&args, &keypair, &client).await?; + // Signed over the target as sent, so each caller-supplied component is + // percent-encoded: a raw `/` or `?` would retarget the owner-signed read. + let owner = urlencoding::encode(&owner); + let name = urlencoding::encode(name); let repo = crate::http::read_json( - client.get(&format!("/api/v1/repos/{owner}/{name}")).await?, + client + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}")) + .await?, "repo", ) .await?; @@ -727,10 +733,14 @@ async fn call_tool( "repo_commits" => { let name = args["name"].as_str().context("missing 'name'")?; - let owner = resolve_owner(&args, &client).await?; + let owner = resolve_signed_read_owner(&args, &keypair, &client).await?; + // Signed over the target as sent, so each caller-supplied component is + // percent-encoded: a raw `/` or `?` would retarget the owner-signed read. + let owner = urlencoding::encode(&owner); + let name = urlencoding::encode(name); let commits = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{name}/commits")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/commits")) .await?, "commits", ) @@ -900,10 +910,14 @@ async fn call_tool( "pr_list" => { let repo = args["repo"].as_str().context("missing 'repo'")?; - let owner = resolve_owner(&args, &client).await?; + let owner = resolve_signed_read_owner(&args, &keypair, &client).await?; + // Signed over the target as sent, so each caller-supplied component is + // percent-encoded: a raw `/` or `?` would retarget the owner-signed read. + let owner = urlencoding::encode(&owner); + let repo = urlencoding::encode(repo); let resp = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{repo}/pulls")) .await?, "pull requests", ) @@ -914,17 +928,21 @@ async fn call_tool( "pr_view" => { let repo = args["repo"].as_str().context("missing 'repo'")?; let number = args["number"].as_i64().context("missing 'number'")?; - let owner = resolve_owner(&args, &client).await?; + let owner = resolve_signed_read_owner(&args, &keypair, &client).await?; + // Signed over the target as sent, so each caller-supplied component is + // percent-encoded: a raw `/` or `?` would retarget the owner-signed read. + let owner = urlencoding::encode(&owner); + let repo = urlencoding::encode(repo); let pr = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}")) .await?, "pull request", ) .await?; let reviews = crate::http::read_json( client - .get(&format!( + .get_maybe_signed(&format!( "/api/v1/repos/{owner}/{repo}/pulls/{number}/reviews" )) .await?, @@ -939,10 +957,14 @@ async fn call_tool( "pr_diff" => { let repo = args["repo"].as_str().context("missing 'repo'")?; let number = args["number"].as_i64().context("missing 'number'")?; - let owner = resolve_owner(&args, &client).await?; + let owner = resolve_signed_read_owner(&args, &keypair, &client).await?; + // Signed over the target as sent, so each caller-supplied component is + // percent-encoded: a raw `/` or `?` would retarget the owner-signed read. + let owner = urlencoding::encode(&owner); + let repo = urlencoding::encode(repo); let resp = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}/diff")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}/diff")) .await?, "diff", ) @@ -1415,6 +1437,27 @@ async fn resolve_owner(args: &Value, client: &NodeClient) -> Result { Ok(did.split(':').next_back().unwrap_or(did).to_string()) } +/// Owner for the owner-gated signed reads (`repo_get`, `repo_commits`, +/// `pr_list`, `pr_view`, `pr_diff`): an explicit `owner` arg wins, then the +/// signing keypair's short DID, and only a caller with no identity falls back to +/// the node root DID. The request is signed by the keypair, so a path owner that +/// names the node instead would be aimed at a namespace the signer does not own +/// and the node would deny it. +async fn resolve_signed_read_owner( + args: &Value, + keypair: &Option, + client: &NodeClient, +) -> Result { + if let Some(o) = args.get("owner").and_then(|v| v.as_str()) { + return Ok(o.to_string()); + } + if let Some(kp) = keypair { + let did = kp.did().to_string(); + return Ok(did.split(':').next_back().unwrap_or(&did).to_string()); + } + resolve_owner(args, client).await +} + /// Resolve (owner, repo) for the webhook tools, matching the CLI's /// `resolve_owner_repo_pair` contract: an `owner/repo` string splits first, an /// explicit `owner` arg wins next, then the signing keypair's short DID. The @@ -2649,6 +2692,276 @@ mod tests { assert!(result.contains("webhooks"), "got: {result}"); } + /// Drive one owner-gated MCP read with an identity and a mock that requires + /// the signature headers (#115). `path` is the exact request path; a + /// regression of that arm to an unsigned `get` leaves the mock unmatched, so + /// the call errors on mockito's 501. + async fn assert_mcp_read_is_signed(tool: &str, args: Value, path: &str, body: &str) -> String { + let mut server = mockito::Server::new_async().await; + let dir = tempfile::TempDir::new().unwrap(); + let kp = gitlawb_core::identity::Keypair::generate(); + std::fs::write( + dir.path().join("identity.pem"), + kp.to_pem().unwrap().as_bytes(), + ) + .unwrap(); + let m = server + .mock("GET", path) + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .expect(1) + .create_async() + .await; + let out = call_tool(tool, args, &server.url(), Some(dir.path())) + .await + .unwrap_or_else(|e| panic!("{tool} must send a signed request: {e:#}")); + m.assert_async().await; + out + } + + #[tokio::test] + async fn test_repo_get_via_mcp_signs_the_request() { + let out = assert_mcp_read_is_signed( + "repo_get", + json!({"name": "myrepo", "owner": "alice"}), + "/api/v1/repos/alice/myrepo", + r#"{"name":"myrepo"}"#, + ) + .await; + assert!(out.contains("myrepo"), "got: {out}"); + } + + #[tokio::test] + async fn test_repo_commits_via_mcp_signs_the_request() { + assert_mcp_read_is_signed( + "repo_commits", + json!({"name": "myrepo", "owner": "alice"}), + "/api/v1/repos/alice/myrepo/commits", + r#"{"commits":[]}"#, + ) + .await; + } + + #[tokio::test] + async fn test_pr_list_via_mcp_signs_the_request() { + assert_mcp_read_is_signed( + "pr_list", + json!({"repo": "myrepo", "owner": "alice"}), + "/api/v1/repos/alice/myrepo/pulls", + r#"{"pulls":[]}"#, + ) + .await; + } + + #[tokio::test] + async fn test_pr_diff_via_mcp_signs_the_request() { + let out = assert_mcp_read_is_signed( + "pr_diff", + json!({"repo": "myrepo", "owner": "alice", "number": 1}), + "/api/v1/repos/alice/myrepo/pulls/1/diff", + r#"{"diff":"diff --git a/x b/x"}"#, + ) + .await; + assert!(out.contains("diff --git"), "got: {out}"); + } + + /// pr_view issues two gated GETs; each must be signed on its own. + #[tokio::test] + async fn test_pr_view_via_mcp_signs_both_requests() { + let mut server = mockito::Server::new_async().await; + let dir = tempfile::TempDir::new().unwrap(); + let kp = gitlawb_core::identity::Keypair::generate(); + std::fs::write( + dir.path().join("identity.pem"), + kp.to_pem().unwrap().as_bytes(), + ) + .unwrap(); + let pr = server + .mock("GET", "/api/v1/repos/alice/myrepo/pulls/1") + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"number":1}"#) + .expect(1) + .create_async() + .await; + let reviews = server + .mock("GET", "/api/v1/repos/alice/myrepo/pulls/1/reviews") + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"reviews":[]}"#) + .expect(1) + .create_async() + .await; + call_tool( + "pr_view", + json!({"repo": "myrepo", "owner": "alice", "number": 1}), + &server.url(), + Some(dir.path()), + ) + .await + .expect("pr_view must send signed requests"); + pr.assert_async().await; + reviews.assert_async().await; + } + + /// A `name`/`repo` argument carrying `/` or `?` must stay one encoded path + /// segment on the signed request. Raw interpolation let `myrepo/hooks` or + /// `myrepo/hooks?x=` retarget an owner-signed read at the webhook endpoint. + #[tokio::test] + async fn test_signed_mcp_reads_encode_path_segments() { + let cases: Vec<(&str, Value, Vec<&str>)> = vec![ + ( + "repo_get", + json!({"name": "myrepo/hooks?x=", "owner": "alice"}), + vec!["/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D"], + ), + ( + "repo_commits", + json!({"name": "myrepo/hooks?x=", "owner": "alice"}), + vec!["/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D/commits"], + ), + ( + "pr_list", + json!({"repo": "myrepo/hooks?x=", "owner": "alice"}), + vec!["/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D/pulls"], + ), + ( + "pr_diff", + json!({"repo": "myrepo/hooks?x=", "owner": "alice", "number": 1}), + vec!["/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D/pulls/1/diff"], + ), + ( + "pr_view", + json!({"repo": "myrepo/hooks?x=", "owner": "alice", "number": 1}), + vec![ + "/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D/pulls/1", + "/api/v1/repos/alice/myrepo%2Fhooks%3Fx%3D/pulls/1/reviews", + ], + ), + ]; + for (tool, args, paths) in cases { + let mut server = mockito::Server::new_async().await; + let dir = tempfile::TempDir::new().unwrap(); + let kp = gitlawb_core::identity::Keypair::generate(); + std::fs::write( + dir.path().join("identity.pem"), + kp.to_pem().unwrap().as_bytes(), + ) + .unwrap(); + let mut mocks = Vec::new(); + for path in &paths { + mocks.push( + server + .mock("GET", *path) + .match_request(crate::http::signature_binds_wire_target) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"diff":"d","reviews":[],"commits":[]}"#) + .expect(1) + .create_async() + .await, + ); + } + call_tool(tool, args, &server.url(), Some(dir.path())) + .await + .unwrap_or_else(|e| panic!("{tool} must sign the encoded target: {e:#}")); + for m in mocks { + m.assert_async().await; + } + } + } + + /// With `owner` omitted and an identity present, the path owner must be the + /// signing keypair's short DID, not the node root DID: a signed request whose + /// keyid differs from the path owner is denied on a private repo. Every + /// changed read tool is driven; the node-root mock returns a different DID, + /// so a fallback to it leaves the keypair-owner mock unmatched. + #[tokio::test] + async fn test_gated_mcp_reads_default_owner_is_keypair_not_node_did() { + let cases: [(&str, Value, &str); 5] = [ + ("repo_get", json!({"name": "myrepo"}), ""), + ("repo_commits", json!({"name": "myrepo"}), "/commits"), + ("pr_list", json!({"repo": "myrepo"}), "/pulls"), + ( + "pr_view", + json!({"repo": "myrepo", "number": 1}), + "/pulls/1", + ), + ( + "pr_diff", + json!({"repo": "myrepo", "number": 1}), + "/pulls/1/diff", + ), + ]; + for (tool, args, suffix) in cases { + let mut server = mockito::Server::new_async().await; + let dir = tempfile::TempDir::new().unwrap(); + let kp = gitlawb_core::identity::Keypair::generate(); + std::fs::write( + dir.path().join("identity.pem"), + kp.to_pem().unwrap().as_bytes(), + ) + .unwrap(); + let did = kp.did().to_string(); + let short = did.split(':').next_back().unwrap_or(&did).to_string(); + + let _root = server + .mock("GET", "/") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"did":"did:key:z6MkNodeRootDid"}"#) + .create_async() + .await; + let m = server + .mock( + "GET", + format!("/api/v1/repos/{short}/myrepo{suffix}").as_str(), + ) + .match_header("signature", mockito::Matcher::Any) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"diff":"d","reviews":[]}"#) + .expect(1) + .create_async() + .await; + // pr_view's second GET (reviews) lives under the same owner. + let _reviews = server + .mock( + "GET", + format!("/api/v1/repos/{short}/myrepo/pulls/1/reviews").as_str(), + ) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"reviews":[]}"#) + .create_async() + .await; + + call_tool(tool, args, &server.url(), Some(dir.path())) + .await + .unwrap_or_else(|e| panic!("{tool} must default owner to the keypair: {e:#}")); + m.assert_async().await; + } + } + + /// An explicit `owner` still wins over the keypair default. + #[tokio::test] + async fn test_gated_mcp_read_explicit_owner_beats_keypair() { + assert_mcp_read_is_signed( + "pr_list", + json!({"repo": "myrepo", "owner": "bob"}), + "/api/v1/repos/bob/myrepo/pulls", + r#"{"pulls":[]}"#, + ) + .await; + } + /// The MCP tool deliberately diverges from the CLI here: `gl webhook list` /// requires a local identity and fails client-side without one, while the MCP /// tool issues the request unsigned and lets the node answer. Pin that path, diff --git a/crates/gl/src/pr.rs b/crates/gl/src/pr.rs index b3a96330..9dce64e8 100644 --- a/crates/gl/src/pr.rs +++ b/crates/gl/src/pr.rs @@ -277,11 +277,13 @@ async fn cmd_create( async fn cmd_list(repo: String, node: String, dir: Option) -> Result<()> { let keypair = load_keypair_from_dir(dir.as_deref())?; let owner = resolve_owner(&keypair); - let client = NodeClient::new(&node, None); + let client = NodeClient::new(&node, Some(keypair)); + // The target is signed as sent: keep a `/` or `?` in `repo` one path segment. + let repo_seg = urlencoding::encode(&repo); let resp = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{repo_seg}/pulls")) .await?, "pull requests", ) @@ -322,11 +324,13 @@ async fn cmd_list(repo: String, node: String, dir: Option) -> Result<() async fn cmd_view(repo: String, number: u64, node: String, dir: Option) -> Result<()> { let keypair = load_keypair_from_dir(dir.as_deref())?; let owner = resolve_owner(&keypair); - let client = NodeClient::new(&node, None); + let client = NodeClient::new(&node, Some(keypair)); + // The target is signed as sent: keep a `/` or `?` in `repo` one path segment. + let repo_seg = urlencoding::encode(&repo); let pr = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}")) + .get_maybe_signed(&format!("/api/v1/repos/{owner}/{repo_seg}/pulls/{number}")) .await?, "pull request", ) @@ -353,8 +357,8 @@ async fn cmd_view(repo: String, number: u64, node: String, dir: Option) // skips the comments below it. Mirrors `gl status`'s unavailable-section line. let reviews = match crate::http::read_json( client - .get(&format!( - "/api/v1/repos/{owner}/{repo}/pulls/{number}/reviews" + .get_maybe_signed(&format!( + "/api/v1/repos/{owner}/{repo_seg}/pulls/{number}/reviews" )) .await?, "reviews", @@ -393,8 +397,8 @@ async fn cmd_view(repo: String, number: u64, node: String, dir: Option) // Show comments let comments = match crate::http::read_json( client - .get(&format!( - "/api/v1/repos/{owner}/{repo}/pulls/{number}/comments" + .get_maybe_signed(&format!( + "/api/v1/repos/{owner}/{repo_seg}/pulls/{number}/comments" )) .await?, "comments", @@ -431,11 +435,15 @@ async fn cmd_view(repo: String, number: u64, node: String, dir: Option) async fn cmd_diff(repo: String, number: u64, node: String, dir: Option) -> Result<()> { let keypair = load_keypair_from_dir(dir.as_deref())?; let owner = resolve_owner(&keypair); - let client = NodeClient::new(&node, None); + let client = NodeClient::new(&node, Some(keypair)); + // The target is signed as sent: keep a `/` or `?` in `repo` one path segment. + let repo_seg = urlencoding::encode(&repo); let resp = crate::http::read_json( client - .get(&format!("/api/v1/repos/{owner}/{repo}/pulls/{number}/diff")) + .get_maybe_signed(&format!( + "/api/v1/repos/{owner}/{repo_seg}/pulls/{number}/diff" + )) .await?, "diff", ) @@ -534,12 +542,14 @@ async fn cmd_comment( async fn cmd_comments(repo: String, number: u64, node: String, dir: Option) -> Result<()> { let keypair = load_keypair_from_dir(dir.as_deref())?; let owner = resolve_owner(&keypair); - let client = NodeClient::new(&node, None); + let client = NodeClient::new(&node, Some(keypair)); + // The target is signed as sent: keep a `/` or `?` in `repo` one path segment. + let repo_seg = urlencoding::encode(&repo); let resp = crate::http::read_json( client - .get(&format!( - "/api/v1/repos/{owner}/{repo}/pulls/{number}/comments" + .get_maybe_signed(&format!( + "/api/v1/repos/{owner}/{repo_seg}/pulls/{number}/comments" )) .await?, "comments", @@ -602,6 +612,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/pulls$".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"pulls":[]}"#) @@ -628,6 +641,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/pulls$".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"pulls":[{"number":1,"title":"Add feature","status":"open","source_branch":"feat","target_branch":"main","author_did":"did:key:z6MkTest"}]}"#) @@ -643,6 +659,39 @@ mod tests { .unwrap(); } + /// A repo argument carrying `/` must stay one path segment on the signed + /// request, not retarget it to a different endpoint. + #[tokio::test] + async fn test_cmd_list_encodes_the_repo_segment() { + let dir = TempDir::new().unwrap(); + write_identity(&dir); + + let mut server = mockito::Server::new_async().await; + let _m = server + .mock( + "GET", + mockito::Matcher::Regex( + r"^/api/v1/repos/[^/]+/myrepo%2Fhooks%3Fx%3D/pulls$".to_string(), + ), + ) + .match_request(crate::http::signature_binds_wire_target) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"pulls":[]}"#) + .expect(1) + .create_async() + .await; + + cmd_list( + "myrepo/hooks?x=".to_string(), + server.url(), + Some(dir.path().to_path_buf()), + ) + .await + .unwrap(); + _m.assert_async().await; + } + #[tokio::test] async fn test_cmd_create_success() { let dir = TempDir::new().unwrap(); @@ -721,6 +770,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/pulls/1$".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"number":1,"title":"Fix it","status":"open","source_branch":"fix","target_branch":"main","author_did":"did:key:z6MkTest","body":"some body"}"#) @@ -733,6 +785,9 @@ mod tests { r"^/api/v1/repos/[^/]+/myrepo/pulls/1/reviews$".to_string(), ), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"reviews":[]}"#) @@ -745,6 +800,9 @@ mod tests { r"^/api/v1/repos/[^/]+/myrepo/pulls/1/comments$".to_string(), ), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"comments":[]}"#) @@ -759,6 +817,10 @@ mod tests { ) .await .unwrap(); + // cmd_view tolerates a failed sub-fetch, so success alone proves nothing + // about whether the reviews and comments requests were signed. + _m2.assert_async().await; + _m3.assert_async().await; } #[tokio::test] @@ -836,6 +898,9 @@ mod tests { r"^/api/v1/repos/[^/]+/myrepo/pulls/1/comments$".to_string(), ), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"comments":[]}"#) @@ -863,6 +928,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/pulls/2/comments$".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"comments":[{"id":"c1","pr_id":"pr1","author_did":"did:key:z6MkTest","body":"nice work","created_at":"2026-03-23T00:00:00Z"}]}"#) @@ -905,7 +973,6 @@ mod tests { .await .unwrap(); } - // ── Gated PR reads surface node denials, not empty/stub renders (#123) ── #[tokio::test] @@ -915,6 +982,8 @@ mod tests { let mut server = mockito::Server::new_async().await; let _m = server .mock("GET", mockito::Matcher::Regex(r"/pulls$".to_string())) + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(404) .with_header("content-type", "application/json") .with_body(r#"{"message":"repository not found"}"#) @@ -943,6 +1012,8 @@ mod tests { // The PR fetch is first; a 404 there errors before the reviews/comments reads. let _m = server .mock("GET", mockito::Matcher::Regex(r"/pulls/1$".to_string())) + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(404) .with_header("content-type", "application/json") .with_body(r#"{"message":"repository not found"}"#) @@ -1023,6 +1094,37 @@ mod tests { _m.assert_async().await; } + // cmd_diff had no signing coverage, so the unsigned read (#115) was invisible + // here. An identity is supplied, so the request must be signed. + #[tokio::test] + async fn test_cmd_diff_signs_request() { + let dir = TempDir::new().unwrap(); + write_identity(&dir); + + let mut server = mockito::Server::new_async().await; + let _m = server + .mock( + "GET", + mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/pulls/1/diff$".to_string()), + ) + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"diff":"diff --git a/x b/x"}"#) + .create_async() + .await; + + cmd_diff( + "myrepo".to_string(), + 1, + server.url(), + Some(dir.path().to_path_buf()), + ) + .await + .unwrap(); + } + /// A denied sub-fetch must not abort `gl pr view` after the header has /// already printed. The header is fatal; reviews and comments degrade. #[tokio::test] diff --git a/crates/gl/src/repo.rs b/crates/gl/src/repo.rs index 4db01c78..533c4fbb 100644 --- a/crates/gl/src/repo.rs +++ b/crates/gl/src/repo.rs @@ -656,7 +656,21 @@ pub(crate) async fn cmd_commits( node: String, dir: Option, ) -> Result<()> { - let client = NodeClient::new(&node, None); + // Sign when an identity is available so a private repo's owner can read their + // own commits; `owner/name` against a public repo still works anonymously. + // An absent identity file falls back to an anonymous read; a file that is + // there but unreadable or unparseable is a local failure and propagates. + let keypair = match load_keypair_from_dir(dir.as_deref()) { + Ok(kp) => Some(kp), + Err(e) + if e.downcast_ref::() + .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound) => + { + None + } + Err(e) => return Err(e), + }; + let client = NodeClient::new(&node, keypair); let (owner, name) = if repo.contains('/') { let (o, n) = repo.split_once('/').unwrap(); @@ -666,8 +680,15 @@ pub(crate) async fn cmd_commits( (short, repo) }; - let url = format!("/api/v1/repos/{owner}/{name}/commits?branch={branch}&limit={limit}"); - let resp = crate::http::read_json(client.get(&url).await?, "commits").await?; + // Signed as sent, so encode here: reqwest would otherwise percent-encode a + // non-ASCII branch after signing and the node would reject the signature. + let url = format!( + "/api/v1/repos/{}/{}/commits?branch={}&limit={limit}", + urlencoding::encode(&owner), + urlencoding::encode(&name), + urlencoding::encode(&branch) + ); + let resp = crate::http::read_json(client.get_maybe_signed(&url).await?, "commits").await?; let commits = resp["commits"].as_array().cloned().unwrap_or_default(); if commits.is_empty() { @@ -1386,6 +1407,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/commits".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"commits":[]}"#) @@ -1403,6 +1427,39 @@ mod tests { .unwrap(); } + /// A valid non-ASCII branch name is percent-encoded on the wire by reqwest, so + /// the signature must be computed over the encoded target or the node 401s it. + #[tokio::test] + async fn test_cmd_commits_signs_the_encoded_branch() { + let dir = TempDir::new().unwrap(); + write_identity(&dir); + + let mut server = mockito::Server::new_async().await; + let m = server + .mock( + "GET", + "/api/v1/repos/alice/myrepo/commits?branch=caf%C3%A9&limit=20", + ) + .match_request(crate::http::signature_binds_wire_target) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"commits":[]}"#) + .expect(1) + .create_async() + .await; + + cmd_commits( + "alice/myrepo".to_string(), + "café".to_string(), + 20, + server.url(), + Some(dir.path().to_path_buf()), + ) + .await + .unwrap(); + m.assert_async().await; + } + #[tokio::test] async fn test_cmd_commits_with_data() { let dir = TempDir::new().unwrap(); @@ -1414,6 +1471,9 @@ mod tests { "GET", mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/commits".to_string()), ) + // An identity is supplied, so get_maybe_signed must sign the request. + .match_header("signature", mockito::Matcher::Any) + .match_header("signature-input", mockito::Matcher::Any) .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"commits":[{"sha":"abc1234567","message":"initial commit","author_name":"alice","date":"2026-03-18T00:00:00Z"}]}"#) @@ -1431,6 +1491,71 @@ mod tests { .unwrap(); } + // An identity file that exists but will not parse is a local failure, not an + // absent identity: it must surface, not silently downgrade to an anonymous + // read whose private-repo denial hides the cause. + #[tokio::test] + async fn test_cmd_commits_corrupt_identity_is_an_error_not_anonymous() { + let dir = TempDir::new().unwrap(); + std::fs::write(dir.path().join("identity.pem"), "not a pem").unwrap(); + + let mut server = mockito::Server::new_async().await; + let m = server + .mock("GET", mockito::Matcher::Any) + .with_status(200) + .with_body(r#"{"commits":[]}"#) + .expect(0) + .create_async() + .await; + + let err = cmd_commits( + "alice/myrepo".to_string(), + "main".to_string(), + 20, + server.url(), + Some(dir.path().to_path_buf()), + ) + .await + .expect_err("a corrupt identity must fail the command"); + assert!( + format!("{err:#}").contains("keypair"), + "the PEM error must surface, got: {err:#}" + ); + m.assert_async().await; + } + + // Empty dir → no identity → get_maybe_signed must fall back to an anonymous + // GET (the public-repo path). `owner/name` needs no local identity, so this + // is the negative twin of the #115 signing fix. Assert NO signature header. + #[tokio::test] + async fn test_cmd_commits_anonymous_when_no_identity() { + let dir = TempDir::new().unwrap(); + + let mut server = mockito::Server::new_async().await; + let _m = server + .mock( + "GET", + mockito::Matcher::Regex(r"^/api/v1/repos/owner/pubrepo/commits".to_string()), + ) + .match_header("signature", mockito::Matcher::Missing) + .match_header("signature-input", mockito::Matcher::Missing) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"commits":[]}"#) + .create_async() + .await; + + cmd_commits( + "owner/pubrepo".to_string(), + "main".to_string(), + 20, + server.url(), + Some(dir.path().to_path_buf()), + ) + .await + .unwrap(); + } + #[tokio::test] async fn test_cmd_fork_success() { let dir = TempDir::new().unwrap();