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): consume iCaptcha proof only after request passes validation
Addresses CodeRabbit (Major) on #108: check() spent the jti as soon as the proof
verified, but create_repo/register ran it before name/DID/existence checks, so a
rejected request (bad name, already-exists, wrong DID) permanently burned a
valid proof without the action succeeding.

Split verification from consumption:
- icaptcha: replace check() with verify_request() -> ProofGuard (verifies and
  rejects invalid/missing proofs early; off/shadow/inert yield a no-op guard)
  plus ProofGuard::consume(db) which spends the jti right before the write and
  rejects replays. Guard is #[must_use].
- create_repo/register: verify_request() up front, then consume() immediately
  before the first write, after cheap validation passes.

Replay protection unchanged (consume-before-write). 12 tests pass; clippy clean.

Author: Kevin Codex <kevin@gitlawb.com>
  • Loading branch information
kevincodex1 committed Jun 30, 2026
commit e3dea0b7cef9f9134c6fcdf76412c74599a9120f
9 changes: 7 additions & 2 deletions crates/gitlawb-node/src/api/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ pub async fn register(
headers: axum::http::HeaderMap,
Json(req): Json<RegisterRequest>,
) -> Result<(StatusCode, Json<RegisterResponse>)> {
// iCaptcha proof-of-intelligence gate (inert unless ICAPTCHA_MODE is set).
crate::icaptcha::check(&state.db, &headers, &auth.0).await?;
// iCaptcha gate (inert unless ICAPTCHA_MODE is set). Verify up front; spend
// the proof only once the request is admissible, just before the write, so a
// rejected request never burns a valid proof.
let proof = crate::icaptcha::verify_request(&headers, &auth.0)?;

// Parse and validate the DID
let agent_did: Did = req
Expand All @@ -56,6 +58,9 @@ pub async fn register(
));
}

// Request is admissible — spend the proof now, immediately before the write.
proof.consume(&state.db).await?;

// Store the agent in the local index
state
.db
Expand Down
10 changes: 8 additions & 2 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,11 @@ pub async fn create_repo(
headers: axum::http::HeaderMap,
Json(req): Json<CreateRepoRequest>,
) -> Result<(StatusCode, Json<RepoResponse>)> {
// iCaptcha proof-of-intelligence gate (inert unless ICAPTCHA_MODE is set).
crate::icaptcha::check(&state.db, &headers, &auth.0).await?;
// iCaptcha gate (inert unless ICAPTCHA_MODE is set). Verify the proof up
// front so an invalid/missing proof is rejected early; the proof is only
// spent once the request is admissible, just before the first write — so a
// rejected request (bad name, already exists) never burns a valid proof.
let proof = crate::icaptcha::verify_request(&headers, &auth.0)?;

// Sanitize name: alphanumeric, hyphens, underscores only
if !req
Expand All @@ -201,6 +204,9 @@ pub async fn create_repo(
return Err(AppError::RepoExists(req.name));
}

// Request is admissible — spend the proof now, immediately before the write.
proof.consume(&state.db).await?;

let disk_path = state
.repo_store
.init(&owner_did, &req.name)
Expand Down
51 changes: 36 additions & 15 deletions crates/gitlawb-node/src/icaptcha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,26 +181,47 @@ enum Decision {
Consume { jti: String, exp: i64 },
}

/// Gate an authenticated request. `did` is the authenticated agent DID the proof
/// must belong to. In enforce mode a valid proof is consumed once (its `jti` is
/// recorded in the DB) so it cannot be replayed across gated actions. Returns
/// `Ok(())` to allow, `Err(Unauthorized)` to reject. Off/Shadow never reject.
pub async fn check(db: &crate::db::Db, headers: &HeaderMap, did: &str) -> Result<(), AppError> {
/// A verified proof awaiting consumption. Verification (which rejects invalid or
/// missing proofs) is separated from consumption (which spends the single-use
/// `jti`) so a request rejected by later validation never burns a valid proof.
/// The caller must `consume()` this guard immediately before the gated write.
/// For off/shadow/inert there is nothing to consume.
#[must_use = "a verified iCaptcha proof must be consumed before the gated action"]
pub struct ProofGuard(Option<ConsumeJob>);

struct ConsumeJob {
jti: String,
exp: i64,
}

impl ProofGuard {
/// Spend the proof's `jti` (single-use). A replay is rejected. No-op when
/// there is nothing to consume (off/shadow/inert).
pub async fn consume(self, db: &crate::db::Db) -> Result<(), AppError> {
if let Some(job) = self.0 {
if !db.consume_proof_jti(&job.jti, job.exp).await? {
return Err(AppError::Unauthorized(
"iCaptcha proof already used (replay); solve a fresh challenge".to_string(),
));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
Ok(())
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// Verify the proof in `headers` belongs to `did`. Rejects missing/invalid
/// proofs early (enforce mode); off/shadow never reject. Returns a [`ProofGuard`]
/// the caller must `consume()` right before the gated write. Off/shadow/inert
/// yield a no-op guard that consumes nothing.
pub fn verify_request(headers: &HeaderMap, did: &str) -> Result<ProofGuard, AppError> {
let v = match VERIFIER.get() {
Some(v) => v,
None => return Ok(()), // not initialized -> inert
None => return Ok(ProofGuard(None)), // not initialized -> inert
};
match decide(v, headers, did, now_secs()) {
Decision::Allow => Ok(()),
Decision::Allow => Ok(ProofGuard(None)),
Decision::Reject(reason) => Err(reject_error(v, &reason)),
Decision::Consume { jti, exp } => {
// First use records the jti; a replay finds it already present.
if db.consume_proof_jti(&jti, exp).await? {
Ok(())
} else {
Err(reject_error(v, "proof already used (replay)"))
}
}
Decision::Consume { jti, exp } => Ok(ProofGuard(Some(ConsumeJob { jti, exp }))),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

Expand Down