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 jti so a proof can't be replayed
Addresses @jatmn P2 on #108: the verifier checked exp/level/sub but never
consumed the proof's jti, so one solved challenge was a reusable bearer proof
for that DID until expiry, covering every gated create_repo/register in the
window. Now, in enforce mode, each verified proof's jti is recorded once and
replays are rejected.

- db: migration v7 adds icaptcha_consumed_proofs(jti PK, expires_at); new
  consume_proof_jti (INSERT ON CONFLICT DO NOTHING -> bool) and
  sweep_expired_proofs. DB-backed so it holds across restarts and instances.
- icaptcha: ProofClaims carries jti; verify returns the claims; decide() stays
  pure and returns Allow | Reject | Consume{jti,exp}; check() is now async and
  spends the jti via the DB, rejecting replays (enforce only; shadow observes
  without consuming).
- handlers: create_repo/register await check(&state.db, ...).
- main: periodic sweep of expired proof rows alongside rate-limit cleanup.
- tests: 12 pass incl. decide() yields Consume with the proof's jti.

Author: Kevin Codex <kevin@gitlawb.com>
  • Loading branch information
kevincodex1 committed Jun 30, 2026
commit 1d1d265777fb8fa6ef074c06c05ee2ba52de4b96
2 changes: 1 addition & 1 deletion crates/gitlawb-node/src/api/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub async fn register(
Json(req): Json<RegisterRequest>,
) -> Result<(StatusCode, Json<RegisterResponse>)> {
// iCaptcha proof-of-intelligence gate (inert unless ICAPTCHA_MODE is set).
crate::icaptcha::check(&headers, &auth.0)?;
crate::icaptcha::check(&state.db, &headers, &auth.0).await?;

// Parse and validate the DID
let agent_did: Did = req
Expand Down
2 changes: 1 addition & 1 deletion crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ pub async fn create_repo(
Json(req): Json<CreateRepoRequest>,
) -> Result<(StatusCode, Json<RepoResponse>)> {
// iCaptcha proof-of-intelligence gate (inert unless ICAPTCHA_MODE is set).
crate::icaptcha::check(&headers, &auth.0)?;
crate::icaptcha::check(&state.db, &headers, &auth.0).await?;

// Sanitize name: alphanumeric, hyphens, underscores only
if !req
Expand Down
41 changes: 41 additions & 0 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,21 @@ const MIGRATIONS: &[Migration] = &[
"CREATE INDEX IF NOT EXISTS idx_repos_owner_key_name ON repos ((CASE WHEN owner_did LIKE 'did:key:%' AND position(':' in substr(owner_did, 9)) = 0 THEN substr(owner_did, 9) ELSE owner_did END), name)",
],
},
Migration {
version: 8,
name: "icaptcha_consumed_proofs",
stmts: &[
// Single-use ledger for iCaptcha proof ids (jti). A proof may be
// spent once per gated action; replays are rejected until the row
// is swept after the proof's own expiry. `expires_at` is the
// proof's unix-seconds exp, used for cleanup.
r#"CREATE TABLE IF NOT EXISTS icaptcha_consumed_proofs (
jti TEXT NOT NULL PRIMARY KEY,
expires_at BIGINT NOT NULL
)"#,
"CREATE INDEX IF NOT EXISTS idx_icaptcha_consumed_expires ON icaptcha_consumed_proofs(expires_at)",
],
},
];

// ── Repos ─────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -1099,6 +1114,32 @@ impl Db {
Ok(())
}

/// Atomically consume an iCaptcha proof id (`jti`). Returns `Ok(true)` if it
/// was newly recorded (the proof may be used), `Ok(false)` if it was already
/// spent (a replay). `expires_at` is the proof's unix-seconds `exp`, kept so
/// the ledger row can be swept once the proof can no longer be valid.
pub async fn consume_proof_jti(&self, jti: &str, expires_at: i64) -> Result<bool> {
let result = sqlx::query(
"INSERT INTO icaptcha_consumed_proofs (jti, expires_at)
VALUES ($1, $2)
ON CONFLICT (jti) DO NOTHING",
)
.bind(jti)
.bind(expires_at)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() > 0)
}

/// Delete consumed-proof rows whose proof has expired. Returns rows removed.
pub async fn sweep_expired_proofs(&self, now: i64) -> Result<u64> {
let result = sqlx::query("DELETE FROM icaptcha_consumed_proofs WHERE expires_at < $1")
.bind(now)
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}

pub async fn get_trust_score(&self, agent_did: &str) -> Result<f64> {
let row = sqlx::query("SELECT trust_score FROM agents WHERE did = $1")
.bind(agent_did)
Expand Down
109 changes: 84 additions & 25 deletions crates/gitlawb-node/src/icaptcha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,13 @@ struct Verifier {

static VERIFIER: OnceLock<Verifier> = OnceLock::new();

#[derive(Deserialize)]
#[derive(Deserialize, Debug)]
struct ProofClaims {
sub: String,
level: u32,
exp: i64,
/// Unique proof id, consumed once so a proof cannot be replayed.
jti: String,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -167,49 +169,86 @@ pub async fn init() {
});
}

/// Outcome of the synchronous, IO-free decision step.
#[derive(Debug)]
enum Decision {
/// Allow the request (off, shadow, inert/no-key, or verified non-enforcing).
Allow,
/// Enforce mode and verification failed; reject with this reason.
Reject(String),
/// Enforce mode and the proof verified; the caller must consume this `jti`
/// (and reject replays) before allowing.
Consume { jti: String, exp: i64 },
}

/// Gate an authenticated request. `did` is the authenticated agent DID the proof
/// must belong to. Returns `Ok(())` to allow, `Err(Unauthorized)` to reject.
/// Honors the configured mode (Off/Shadow never reject).
pub fn check(headers: &HeaderMap, did: &str) -> Result<(), AppError> {
/// 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> {
let v = match VERIFIER.get() {
Some(v) => v,
None => return Ok(()), // not initialized -> inert
};
decide(v, headers, did, now_secs())
match decide(v, headers, did, now_secs()) {
Decision::Allow => Ok(()),
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)"))
}
}
}
}

fn reject_error(v: &Verifier, reason: &str) -> AppError {
AppError::Unauthorized(format!(
"iCaptcha proof required ({reason}). Solve a challenge at {} for level >= {} and resend with the {} header.",
v.url, v.required_level, PROOF_HEADER
))
}

/// Mode-aware decision, separated from the global state for testability.
fn decide(v: &Verifier, headers: &HeaderMap, did: &str, now: i64) -> Result<(), AppError> {
/// Mode-aware decision. Pure and IO-free (no DB; clock injected via `now`) so it
/// is fully unit-testable. The caller performs jti consumption for `Consume`.
fn decide(v: &Verifier, headers: &HeaderMap, did: &str, now: i64) -> Decision {
if v.mode == Mode::Off {
return Ok(());
return Decision::Allow;
}

// Fail safe: if no public key could be loaded (e.g. iCaptcha was unreachable
// at startup), stay inert rather than rejecting every request. The operator
// already saw a startup warning. An iCaptcha hiccup must never break repo
// creation or registration.
if v.key.is_none() {
return Ok(());
return Decision::Allow;
}

match verify(v, headers, did, now) {
Ok(()) => Ok(()),
Ok(claims) => match v.mode {
Mode::Enforce => Decision::Consume {
jti: claims.jti,
exp: claims.exp,
},
// Shadow/Off: never reject, and do not consume (observational only).
_ => Decision::Allow,
},
Err(reason) => match v.mode {
Mode::Shadow => {
tracing::warn!(did = %did, reason, "iCaptcha (shadow) would reject");
Ok(())
Decision::Allow
}
Mode::Enforce => Err(AppError::Unauthorized(format!(
"iCaptcha proof required ({reason}). Solve a challenge at {} for level >= {} and resend with the {} header.",
v.url, v.required_level, PROOF_HEADER
))),
Mode::Off => Ok(()),
Mode::Enforce => Decision::Reject(reason),
Mode::Off => Decision::Allow,
},
}
}

/// Core verification, separated for testability. `now` is unix seconds.
fn verify(v: &Verifier, headers: &HeaderMap, did: &str, now: i64) -> Result<(), String> {
/// Core verification, separated for testability. Returns the validated claims.
/// `now` is unix seconds.
fn verify(v: &Verifier, headers: &HeaderMap, did: &str, now: i64) -> Result<ProofClaims, String> {
let key = v.key.as_ref().ok_or("verifier has no public key")?;
let proof = headers
.get(PROOF_HEADER)
Expand Down Expand Up @@ -241,7 +280,7 @@ fn verify(v: &Verifier, headers: &HeaderMap, did: &str, now: i64) -> Result<(),
if !crate::api::did_matches(did, &claims.sub) {
return Err("proof subject does not match authenticated DID".to_string());
}
Ok(())
Ok(claims)
}

#[cfg(test)]
Expand Down Expand Up @@ -329,7 +368,10 @@ mod tests {
fn off_mode_allows_everything() {
let mut v = verifier(3);
v.mode = Mode::Off;
assert!(decide(&v, &HeaderMap::new(), SUB, IAT).is_ok());
assert!(matches!(
decide(&v, &HeaderMap::new(), SUB, IAT),
Decision::Allow
));
}

#[test]
Expand All @@ -341,25 +383,42 @@ mod tests {
required_level: 3,
key: None,
};
assert!(decide(&v, &HeaderMap::new(), SUB, IAT).is_ok());
assert!(matches!(
decide(&v, &HeaderMap::new(), SUB, IAT),
Decision::Allow
));
}

#[test]
fn enforce_with_key_rejects_missing_proof() {
let v = verifier(3);
assert!(decide(&v, &HeaderMap::new(), SUB, IAT).is_err());
assert!(matches!(
decide(&v, &HeaderMap::new(), SUB, IAT),
Decision::Reject(_)
));
}

#[test]
fn shadow_allows_despite_bad_proof() {
let mut v = verifier(3);
v.mode = Mode::Shadow;
assert!(decide(&v, &HeaderMap::new(), SUB, IAT).is_ok());
assert!(matches!(
decide(&v, &HeaderMap::new(), SUB, IAT),
Decision::Allow
));
}

#[test]
fn enforce_accepts_valid_proof_via_decide() {
fn enforce_valid_proof_requires_consuming_its_jti() {
// A verified proof under enforce must yield Consume carrying the jti, so
// the caller can spend it once and reject replays.
let v = verifier(3);
assert!(decide(&v, &headers_with(PROOF), SUB, IAT).is_ok());
match decide(&v, &headers_with(PROOF), SUB, IAT) {
Decision::Consume { jti, exp } => {
assert_eq!(jti, "4b5228a5bed7122dee9f47ff");
assert_eq!(exp, 1782573151);
}
other => panic!("expected Consume, got {other:?}"),
}
}
}
10 changes: 9 additions & 1 deletion crates/gitlawb-node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,15 +265,23 @@ async fn main() -> Result<()> {
});
}

// Periodic cleanup of expired rate limit entries
// Periodic cleanup of expired rate limit entries + consumed-proof ledger
{
let rl = state.rate_limiter.clone();
let db = state.db.clone();
let mut shutdown_rx = state.subscribe_shutdown();
tokio::spawn(async move {
loop {
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(300)) => {
rl.cleanup().await;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
if let Err(e) = db.sweep_expired_proofs(now).await {
tracing::warn!(err = %e, "failed to sweep expired iCaptcha proofs");
}
}
_ = shutdown_rx.changed() => {
if *shutdown_rx.borrow() {
Expand Down