Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(node): address review on #68 — 403 status, finish owner-match con…
…solidation

Per @beardthelion's review:

- Return 403 Forbidden (not 400) for authorization denials: the owner-push gate,
  the branch-protection denial, and the owner checks in protect.rs / visibility.rs.
  400 reads as a malformed request and some git/CI clients retry it.
- Finish the is_repo_owner consolidation: route the branch-protection check and
  the repos list filter through the helper. The branch-protection check now uses
  the verified AuthenticatedDid (auth.0) instead of re-parsing the headers.
- Drop the second identity source on the push path entirely: the post-push event
  recording also uses auth.0, so extract_did_from_auth (and the handler's
  HeaderMap param + import) are removed.
- Tests assert the Forbidden variant (so a future status regression fails loudly)
  and add direct coverage for is_repo_owner / caller_authorized_to_push.
- Docs: warn that enabling the flag blocks delegated and CI agents until the
  Phase 2 UCAN git/push capability is honored.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
  • Loading branch information
FrozenRaspberry and claude committed Jun 22, 2026
commit f9df6eb6542fabc9bee043f85ec8027c992eb5c6
4 changes: 2 additions & 2 deletions crates/gitlawb-node/src/api/protect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub async fn protect_branch(
// Only the repo owner can protect branches
let caller = &auth.0;
if !is_repo_owner(&record, caller) {
return Err(AppError::BadRequest(
return Err(AppError::Forbidden(
"only the repo owner can protect branches".into(),
));
}
Expand Down Expand Up @@ -59,7 +59,7 @@ pub async fn unprotect_branch(

let caller = &auth.0;
if !is_repo_owner(&record, caller) {
return Err(AppError::BadRequest(
return Err(AppError::Forbidden(
"only the repo owner can unprotect branches".into(),
));
}
Expand Down
116 changes: 55 additions & 61 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use axum::extract::{Extension, Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::http::StatusCode;
use axum::response::Response;
use axum::Json;
use bytes::Bytes;
use std::sync::Arc;

use crate::auth::{caller_authorized_to_push, AuthenticatedDid};
use crate::auth::{caller_authorized_to_push, is_repo_owner, AuthenticatedDid};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
Expand Down Expand Up @@ -162,8 +162,7 @@ pub async fn list_repos(
.iter()
.filter(|(r, _)| {
if let Some(owner) = &query.owner {
let short = r.owner_did.split(':').next_back().unwrap_or(&r.owner_did);
short == owner.as_str() || r.owner_did == owner.as_str()
is_repo_owner(r, owner.as_str())
} else {
true
}
Expand Down Expand Up @@ -480,7 +479,7 @@ fn owner_push_rejection(
}
match caller {
Some(did) if caller_authorized_to_push(record, did) => None,
_ => Some(AppError::BadRequest(
_ => Some(AppError::Forbidden(
"push rejected — only the repo owner may push to this repository \
(GITLAWB_ENFORCE_OWNER_PUSH is enabled)"
.into(),
Expand All @@ -493,7 +492,6 @@ pub async fn git_receive_pack(
State(state): State<AppState>,
Path((owner, repo)): Path<(String, String)>,
Extension(auth): Extension<AuthenticatedDid>,
headers: HeaderMap,
body: Bytes,
) -> Result<Response> {
let name = repo.trim_end_matches(".git");
Expand Down Expand Up @@ -532,8 +530,9 @@ pub async fn git_receive_pack(
}

// ── Branch protection check ──────────────────────────────────────────
let pusher_did_for_check = extract_did_from_auth(&headers);
tracing::debug!(pusher_did = ?pusher_did_for_check, "extracted pusher DID from auth headers");
// Uses the same verified identity as the owner-push gate above. (When that
// gate is enabled a non-owner never reaches here; this still applies when it
// is off, gating only the branches an owner has explicitly protected.)
for update in &ref_updates {
// Strip refs/heads/ prefix to get plain branch name
let branch = update
Expand All @@ -545,27 +544,17 @@ pub async fn git_receive_pack(
.is_branch_protected(&record.id, branch)
.await
.unwrap_or(false)
&& !is_repo_owner(&record, &auth.0)
{
let owner_short = record
.owner_did
.split(':')
.next_back()
.unwrap_or(&record.owner_did);
let is_owner = pusher_did_for_check
.as_deref()
.map(|did| did == record.owner_did || did == owner_short)
.unwrap_or(false);
if !is_owner {
tracing::warn!(
branch = %branch,
pusher = ?pusher_did_for_check,
owner_did = %record.owner_did,
"branch protection: rejecting push from non-owner"
);
return Err(AppError::BadRequest(format!(
"branch '{branch}' is protected — only the repo owner can push to it"
)));
}
tracing::warn!(
branch = %branch,
pusher = %auth.0,
owner_did = %record.owner_did,
"branch protection: rejecting push from non-owner"
);
return Err(AppError::Forbidden(format!(
"branch '{branch}' is protected — only the repo owner can push to it"
)));
}
}

Expand Down Expand Up @@ -601,9 +590,11 @@ pub async fn git_receive_pack(
crate::metrics::record_push(&record.id);
crate::metrics::observe_pack_size(body_len as f64);

// Record push event for trust score and issue a signed ref certificate
let pusher_did = extract_did_from_auth(&headers);
if let Some(ref did) = pusher_did {
// Record push event for trust score and issue a signed ref certificate.
// The route is behind `require_signature`, so the verified pusher identity is
// always present; use it directly rather than re-parsing the headers.
let did = auth.0.as_str();
{
// Use the first new commit hash we parsed, fall back to timestamp
let commit_hash = ref_updates
.first()
Expand Down Expand Up @@ -661,7 +652,7 @@ pub async fn git_receive_pack(
"created": update.old_sha == "0000000000000000000000000000000000000000",
"forced": false,
"pusher": {
"did": pusher_did.as_deref().unwrap_or("unknown"),
"did": did,
},
"repository": {
"id": record.id,
Expand Down Expand Up @@ -773,7 +764,7 @@ pub async fn git_receive_pack(
.map(|u| (u.ref_name.clone(), u.new_sha.clone()))
.collect::<Vec<_>>();
let p2p_handle = state.p2p.clone();
let pusher_did_clone = pusher_did.clone().unwrap_or_default();
let pusher_did_clone = did.to_string();
let db_for_peers = state.db.clone();
let ref_update_tx = state.ref_update_tx.clone();
let irys_url = state.config.irys_url.clone();
Expand Down Expand Up @@ -1215,30 +1206,6 @@ fn parse_ref_updates(body: &[u8]) -> Vec<RefUpdate> {
updates
}

/// Extract the DID from RFC 9421 Signature-Input header (keyid="...").
/// Falls back to draft-cavage Authorization header for old clients.
fn extract_did_from_auth(headers: &HeaderMap) -> Option<String> {
// RFC 9421: Signature-Input: sig1=(...);keyid="did:key:z6Mk...";...
if let Some(sig_input) = headers.get("signature-input").and_then(|v| v.to_str().ok()) {
if let Some(start) = sig_input.find("keyid=\"") {
let rest = &sig_input[start + 7..];
if let Some(end) = rest.find('"') {
return Some(rest[..end].to_string());
}
}
}
// Fallback: draft-cavage Authorization: Signature keyId="..."
if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
if let Some(start) = auth.find("keyId=\"") {
let rest = &auth[start + 7..];
if let Some(end) = rest.find('"') {
return Some(rest[..end].to_string());
}
}
}
None
}

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

fn to_response(record: &crate::db::RepoRecord, state: &AppState, star_count: i64) -> RepoResponse {
Expand Down Expand Up @@ -1273,6 +1240,8 @@ fn to_response(record: &crate::db::RepoRecord, state: &AppState, star_count: i64
#[cfg(test)]
mod tests {
use super::owner_push_rejection;
use crate::auth::{caller_authorized_to_push, is_repo_owner};
use crate::error::AppError;

const OWNER_DID: &str = "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH";
const OWNER_SHORT: &str = "z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH";
Expand All @@ -1295,6 +1264,15 @@ mod tests {
}
}

/// A rejection must be a 403 Forbidden (authenticated but not authorized),
/// not a 400 — some git/CI clients retry 400s.
fn assert_forbidden(rejection: Option<AppError>) {
assert!(
matches!(rejection, Some(AppError::Forbidden(_))),
"expected Some(Forbidden), got {rejection:?}"
);
}

#[test]
fn enforced_allows_owner_full_did() {
let repo = repo_owned_by(OWNER_DID);
Expand All @@ -1310,16 +1288,16 @@ mod tests {
}

#[test]
fn enforced_rejects_non_owner() {
fn enforced_rejects_non_owner_with_forbidden() {
let repo = repo_owned_by(OWNER_DID);
assert!(owner_push_rejection(true, &repo, Some(STRANGER_DID)).is_some());
assert_forbidden(owner_push_rejection(true, &repo, Some(STRANGER_DID)));
}

#[test]
fn enforced_rejects_missing_did() {
fn enforced_rejects_missing_did_with_forbidden() {
// Fail closed: an absent authenticated identity is rejected, not allowed.
let repo = repo_owned_by(OWNER_DID);
assert!(owner_push_rejection(true, &repo, None).is_some());
assert_forbidden(owner_push_rejection(true, &repo, None));
}

#[test]
Expand All @@ -1329,4 +1307,20 @@ mod tests {
assert!(owner_push_rejection(false, &repo, Some(STRANGER_DID)).is_none());
assert!(owner_push_rejection(false, &repo, None).is_none());
}

#[test]
fn is_repo_owner_matches_full_and_short_did_only() {
let repo = repo_owned_by(OWNER_DID);
assert!(is_repo_owner(&repo, OWNER_DID));
assert!(is_repo_owner(&repo, OWNER_SHORT));
assert!(!is_repo_owner(&repo, STRANGER_DID));
}

#[test]
fn caller_authorized_to_push_is_owner_only_in_phase_1() {
let repo = repo_owned_by(OWNER_DID);
assert!(caller_authorized_to_push(&repo, OWNER_DID));
assert!(caller_authorized_to_push(&repo, OWNER_SHORT));
assert!(!caller_authorized_to_push(&repo, STRANGER_DID));
}
}
2 changes: 1 addition & 1 deletion crates/gitlawb-node/src/api/visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct RemoveVisibilityRequest {

fn require_owner(record: &crate::db::RepoRecord, caller: &str) -> Result<()> {
if !is_repo_owner(record, caller) {
return Err(AppError::BadRequest(
return Err(AppError::Forbidden(
"only the repo owner can manage visibility".into(),
));
}
Expand Down
12 changes: 8 additions & 4 deletions docs/RUN-A-NODE.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,14 @@ GITLAWB_ENFORCE_OWNER_PUSH=true
- **Default `false`** — preserves current behavior so live nodes are unaffected by
an upgrade. Turn it on once you're ready for owner-only writes.
- **When `true`** — a push whose authenticated DID is not the repo owner is
rejected before any ref update is applied. The owner is matched in both the full
`did:key:z6Mk…` form and its bare `z6Mk…` suffix.
- Collaborator and UCAN-delegated push rights are a separate, planned follow-up;
today this is strictly owner-only.
rejected (HTTP 403) before any ref update is applied. The owner is matched in
both the full `did:key:z6Mk…` form and its bare `z6Mk…` suffix.
- **Caution: this blocks every non-owner pusher, including your own delegated and
CI agents.** Push authorization is owner-only today — a UCAN `git/push`
capability is verified but not yet honored for authorization, so delegated keys
cannot push while this is on. Don't enable it until every identity that pushes
to your repos is the owner, or you'll lock out your own automation. Scoped
collaborator / UCAN-delegated push rights are a planned follow-up.

---

Expand Down
Loading