Skip to content
Prev Previous commit
Next Next commit
feat(node): enforce per-route authorization on REST mutations
Closes the missing-authorization cluster on the signed REST surface, where
'authenticated' meant 'any participant' because identities are permissionless.
Adds two shared helpers in api/mod.rs: require_repo_owner (403) and did_matches,
a method-safe DID comparison that collapses the full did:key vs bare short form
without matching across methods (did:web/did:gitlawb share the base58 space).

Per-route gates:
- merge_pr is owner-only (subsumes branch protection); close_pr and close_issue
  allow the repo owner or the PR/issue author (the issue author is read from the
  git-JSON blob, with a None author falling back to owner-only).
- create_review, create_comment, create_issue_comment, and create_bounty are
  read-gated (participants need read access, not ownership; this also closes the
  private-repo bounty leak).
- the task handlers bind the acting DID to the authenticated signer.
- dispute_bounty, previously ungated, now requires the creator or claimant; the
  other bounty and replica identity checks switch from raw equality to did_matches.

A source-level guard test asserts every in-scope mutation handler still carries
its expected gate marker, so a removed gate or an unclassified new route fails
CI. DB-backed tests (via the integration harness) cover merge owner-only and the
task signer-binding; did_matches has unit coverage for the cross-method case.
  • Loading branch information
beardthelion committed Jun 22, 2026
commit 6404165fed540f401542ca0550d2f4dc331b4961
32 changes: 23 additions & 9 deletions crates/gitlawb-node/src/api/bounties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,9 @@ pub async fn create_bounty(
return Err(AppError::BadRequest("amount must be positive".into()));
}

// Verify repo exists
let _ = state
.db
.get_repo(&owner, &repo)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
// Read-gate: anyone who can read the repo may fund a bounty on it (this closes
// the private-repo bounty leak); ownership is not required.
crate::api::authorize_repo_read(&state, &owner, &repo, Some(auth.0.as_str()), "/").await?;

let now = Utc::now().to_rfc3339();
let bounty = BountyRecord {
Expand Down Expand Up @@ -213,7 +210,11 @@ pub async fn submit_bounty(
bounty.status
)));
}
if bounty.claimant_did.as_deref() != Some(&auth.0) {
let is_claimant = bounty
.claimant_did
.as_deref()
.is_some_and(|c| crate::api::did_matches(&auth.0, c));
if !is_claimant {
return Err(AppError::BadRequest("only the claimant can submit".into()));
}

Expand Down Expand Up @@ -249,7 +250,7 @@ pub async fn approve_bounty(
bounty.status
)));
}
if bounty.creator_did != auth.0 {
if !crate::api::did_matches(&auth.0, &bounty.creator_did) {
return Err(AppError::BadRequest(
"only the bounty creator can approve".into(),
));
Expand Down Expand Up @@ -296,7 +297,7 @@ pub async fn cancel_bounty(
bounty.status
)));
}
if bounty.creator_did != auth.0 {
if !crate::api::did_matches(&auth.0, &bounty.creator_did) {
return Err(AppError::BadRequest(
"only the bounty creator can cancel".into(),
));
Expand Down Expand Up @@ -332,6 +333,19 @@ pub async fn dispute_bounty(
)));
}

// Only the bounty creator or the current claimant may dispute (N19 — this
// endpoint had no identity check at all).
let is_creator = crate::api::did_matches(&auth.0, &bounty.creator_did);
let is_claimant = bounty
.claimant_did
.as_deref()
.is_some_and(|c| crate::api::did_matches(&auth.0, c));
if !is_creator && !is_claimant {
return Err(AppError::Forbidden(
"only the bounty creator or claimant can dispute this bounty".into(),
));
}

// Check if deadline exceeded
if let Some(ref claimed_at) = bounty.claimed_at {
if let Ok(claimed) = chrono::DateTime::parse_from_rfc3339(claimed_at) {
Expand Down
37 changes: 31 additions & 6 deletions crates/gitlawb-node/src/api/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,9 @@ pub async fn create_issue_comment(
));
}

let record = state
.db
.get_repo(&owner, &repo)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
// Read-gate: a commenter must be able to read the repo, but need not own it.
let (record, _rules) =
crate::api::authorize_repo_read(&state, &owner, &repo, Some(auth.0.as_str()), "/").await?;

let disk_path = state
.repo_store
Expand Down Expand Up @@ -207,7 +205,7 @@ pub async fn list_issue_comments(
/// POST /api/v1/repos/{owner}/{repo}/issues/{id}/close
pub async fn close_issue(
State(state): State<AppState>,
Extension(_auth): Extension<AuthenticatedDid>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, repo, issue_id)): Path<(String, String, String)>,
) -> Result<Json<serde_json::Value>> {
let record = state
Expand All @@ -223,6 +221,33 @@ pub async fn close_issue(
.map_err(|e| AppError::Git(e.to_string()))?;
let disk_path = guard.path().to_path_buf();

// Owner OR issue author may close. The author lives in the issue's git-JSON
// blob (not a DB column); a None author (legacy issues) falls back to
// owner-only. Read it under the write guard, before mutating.
let author_did: Option<String> = match git_issues::get_issue(&disk_path, &issue_id) {
Ok(Some(raw)) => serde_json::from_str::<IssueRecord>(&raw)
.ok()
.and_then(|i| i.author),
Ok(None) => {
guard.release(false).await;
return Err(AppError::NotFound(format!("issue {issue_id} not found")));
}
Err(e) => {
guard.release(false).await;
return Err(AppError::Git(e.to_string()));
}
};
let is_owner = crate::api::require_repo_owner(&record, &auth.0).is_ok();
let is_author = author_did
.as_deref()
.is_some_and(|a| crate::api::did_matches(&auth.0, a));
if !is_owner && !is_author {
guard.release(false).await;
return Err(AppError::Forbidden(
"only the repo owner or the issue author can close this issue".into(),
));
}

let close_result = git_issues::close_issue(&disk_path, &issue_id);

// Always release the advisory lock — even on error; upload to Tigris only on success.
Expand Down
6 changes: 4 additions & 2 deletions crates/gitlawb-node/src/api/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct LabelRequest {
/// POST /api/v1/repos/:owner/:repo/labels
pub async fn add_label(
State(state): State<AppState>,
Extension(_auth): Extension<AuthenticatedDid>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, name)): Path<(String, String)>,
Json(req): Json<LabelRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>)> {
Expand All @@ -39,6 +39,7 @@ pub async fn add_label(
.get_repo(&owner, &name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
crate::api::require_repo_owner(&record, &auth.0)?;

let added = state.db.add_label(&record.id, &label).await?;
let status = if added {
Expand All @@ -55,14 +56,15 @@ pub async fn add_label(
/// DELETE /api/v1/repos/:owner/:repo/labels/:label
pub async fn remove_label(
State(state): State<AppState>,
Extension(_auth): Extension<AuthenticatedDid>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, name, label)): Path<(String, String, String)>,
) -> Result<Json<serde_json::Value>> {
let record = state
.db
.get_repo(&owner, &name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
crate::api::require_repo_owner(&record, &auth.0)?;

state.db.remove_label(&record.id, &label).await?;
Ok(Json(serde_json::json!({ "label": label, "removed": true })))
Expand Down
136 changes: 136 additions & 0 deletions crates/gitlawb-node/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,139 @@ pub(crate) async fn authorize_repo_read(
}
Ok((record, rules))
}

/// Match a presented DID against a stored DID that may be the full `did:key:<id>`
/// form or the bare `<id>` short form (mirror rows store the bare key). Collapse
/// representation only within `did:key`; never let a bare id match across methods —
/// `did:web` / `did:gitlawb` share the base58 space with `did:key`, so a
/// trailing-segment compare would treat `did:key:X` and `did:gitlawb:X` as equal.
pub(crate) fn did_matches(a: &str, b: &str) -> bool {
if a == b {
return true;
}
fn key_id(d: &str) -> &str {
d.strip_prefix("did:key:").unwrap_or(d)
}
let (ka, kb) = (key_id(a), key_id(b));
// After stripping `did:key:`, a value still containing ':' is a non-key full
// DID — do not let it match a bare `did:key` id.
!ka.contains(':') && !kb.contains(':') && ka == kb
}

/// 403 unless `caller` is the repo owner. Uses [`did_matches`] so the owner check
/// and the author check (close policy) share one normalization.
pub(crate) fn require_repo_owner(record: &RepoRecord, caller: &str) -> Result<()> {
if did_matches(caller, &record.owner_did) {
Ok(())
} else {
Err(AppError::Forbidden(
"only the repo owner can perform this action".into(),
))
}
}

#[cfg(test)]
mod did_tests {
use super::did_matches;

#[test]
fn full_matches_bare_same_key() {
assert!(did_matches("did:key:zABC", "zABC"));
assert!(did_matches("zABC", "did:key:zABC"));
}

#[test]
fn rejects_cross_method_collision() {
assert!(!did_matches("did:key:zABC", "did:gitlawb:zABC"));
assert!(!did_matches("did:key:zABC", "did:web:zABC"));
}

#[test]
fn exact_match_and_distinct_keys() {
assert!(did_matches("did:key:zABC", "did:key:zABC"));
assert!(!did_matches("did:key:zABC", "did:key:zXYZ"));
assert!(!did_matches("zABC", "zXYZ"));
}
}

/// Drift guard (plan 002 §Gate-type table, Step 5). Every in-scope mutation
/// handler must contain its expected gate marker in its own body; removing a
/// gate fails this test. Source-level (no DB), so it runs everywhere. When a new
/// route is added to an in-scope group, add its row here with a deliberate gate
/// type — that forced decision is the point.
#[cfg(test)]
mod authz_guard {
fn fn_body<'a>(src: &'a str, func: &'a str) -> &'a str {
let needle = format!("fn {func}(");
let start = src
.find(&needle)
.unwrap_or_else(|| panic!("handler `{func}` not found (renamed or removed?)"));
let rest = &src[start..];
// End at the next top-level handler so a marker in a later fn can't leak in.
let end = rest[1..]
.find("\npub async fn ")
.map(|i| i + 1)
.unwrap_or(rest.len());
&rest[..end]
}

#[test]
fn every_in_scope_mutation_has_its_gate() {
let pulls = include_str!("pulls.rs");
let webhooks = include_str!("webhooks.rs");
let labels = include_str!("labels.rs");
let issues = include_str!("issues.rs");
let bounties = include_str!("bounties.rs");
let replicas = include_str!("replicas.rs");
let tasks = include_str!("tasks.rs");
let stars = include_str!("stars.rs");
let protect = include_str!("protect.rs");
let visibility = include_str!("visibility.rs");

// (source, handler, expected gate marker)
let rows: &[(&str, &str, &str)] = &[
// Bucket A — owner-gate
(pulls, "merge_pr", "require_repo_owner"),
(webhooks, "create_webhook", "require_repo_owner"),
(webhooks, "delete_webhook", "require_repo_owner"),
(labels, "add_label", "require_repo_owner"),
(labels, "remove_label", "require_repo_owner"),
// Bucket A' — owner OR author
(pulls, "close_pr", "did_matches"),
(issues, "close_issue", "did_matches"),
// Bucket B — read-gate
(pulls, "create_review", "authorize_repo_read"),
(pulls, "create_comment", "authorize_repo_read"),
(issues, "create_issue_comment", "authorize_repo_read"),
(bounties, "create_bounty", "authorize_repo_read"),
// Bucket C — signer-self (acting DID bound to auth.0)
(tasks, "create_task", "auth.0"),
(tasks, "claim_task", "auth.0"),
(tasks, "complete_task", "auth.0"),
(tasks, "fail_task", "auth.0"),
// Bucket D — non-owner-by-design, positive per-route marker
(bounties, "submit_bounty", "did_matches"),
(bounties, "approve_bounty", "did_matches"),
(bounties, "cancel_bounty", "did_matches"),
(bounties, "dispute_bounty", "did_matches"),
(replicas, "register_replica", "did_matches"),
(replicas, "unregister_replica", "auth.0"),
(stars, "star_repo", "auth.0"),
(stars, "unstar_repo", "auth.0"),
// PRE-GATED — already owner-gated, in-scope group; guarded against regression
(protect, "protect_branch", "owner_did"),
(protect, "unprotect_branch", "owner_did"),
(visibility, "set_visibility", "require_owner"),
(visibility, "remove_visibility", "require_owner"),
(visibility, "list_visibility", "require_owner"),
];

for (src, func, marker) in rows {
let body = fn_body(src, func);
assert!(
body.contains(marker),
"handler `{func}` is missing its gate marker `{marker}` — gate removed or route reclassified"
);
}
}
}
31 changes: 21 additions & 10 deletions crates/gitlawb-node/src/api/pulls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ pub async fn merge_pr(
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;

// Owner-only merge (N7). Merging writes the served tree, so this is the same
// trust boundary as owner-only push; it subsumes branch protection (a
// non-owner cannot merge to any branch, protected or not).
crate::api::require_repo_owner(&record, &auth.0)?;

let pr = state
.db
.get_pr(&record.id, number)
Expand Down Expand Up @@ -252,6 +257,7 @@ pub async fn merge_pr(
/// POST /api/v1/repos/:owner/:repo/pulls/:number/close
pub async fn close_pr(
State(state): State<AppState>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, name, number)): Path<(String, String, i64)>,
) -> Result<Json<serde_json::Value>> {
let record = state
Expand All @@ -266,6 +272,15 @@ pub async fn close_pr(
.await?
.ok_or_else(|| AppError::NotFound(format!("PR #{number} not found")))?;

// Owner OR author may close (forge norm).
let is_owner = crate::api::require_repo_owner(&record, &auth.0).is_ok();
let is_author = crate::api::did_matches(&auth.0, &pr.author_did);
if !is_owner && !is_author {
return Err(AppError::Forbidden(
"only the repo owner or the PR author can close this PR".into(),
));
}

state.db.close_pr(&pr.id).await?;

webhooks::fire_event(
Expand All @@ -290,11 +305,9 @@ pub async fn create_review(
Path((owner, name, number)): Path<(String, String, i64)>,
Json(req): Json<CreateReviewRequest>,
) -> Result<(StatusCode, Json<PrReview>)> {
let record = state
.db
.get_repo(&owner, &name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
// Read-gate: a reviewer must be able to read the repo, but need not own it.
let (record, _rules) =
crate::api::authorize_repo_read(&state, &owner, &name, Some(auth.0.as_str()), "/").await?;

let pr = state
.db
Expand Down Expand Up @@ -369,11 +382,9 @@ pub async fn create_comment(
));
}

let record = state
.db
.get_repo(&owner, &name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
// Read-gate: a commenter must be able to read the repo, but need not own it.
let (record, _rules) =
crate::api::authorize_repo_read(&state, &owner, &name, Some(auth.0.as_str()), "/").await?;

let pr = state
.db
Expand Down
5 changes: 3 additions & 2 deletions crates/gitlawb-node/src/api/replicas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ pub async fn register_replica(

let replica_did = &auth.0;

// Don't let an owner register themselves as a replica of their own repo.
if replica_did == &record.owner_did {
// Don't let an owner register themselves as a replica of their own repo
// (did_matches handles the full vs bare did:key owner form).
if crate::api::did_matches(replica_did, &record.owner_did) {
return Err(AppError::BadRequest(
"the repo owner is not a replica of their own repo".into(),
));
Expand Down
Loading