Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
8b91534
fix(node): gate agent-task reads behind the same visibility rules as …
Aug 12, 2026
e1d5149
fix(node): query the task limit-clamp test as the delegator
Aug 12, 2026
d3f0880
fix(node): scope task visibility lookups to the page's repos
Aug 12, 2026
c765498
Preserve authorized task reads across shipped clients.
Aug 13, 2026
b26db4b
Bound denied task history scans.
Aug 13, 2026
e3b1372
Signal incomplete task scans with recoverable cursors and map read er…
Aug 14, 2026
d43829b
Stop disclosing denied task rows in the scan-wall cursor and add Grap…
Aug 15, 2026
81a1776
Normalize task cursors and gate mutation endpoints behind visibility.
Aug 15, 2026
b1ddf9d
Update complete_task test in test_support to exercise both 404 on unr…
Aug 15, 2026
15d5748
Bind task to repo id in complete_task test in test_support.
Aug 15, 2026
70b2509
Preserve timestamp fractional width and anchor continuation tests on …
Aug 15, 2026
1029cdb
Match on Value::Object to extract task ID in GraphQL continuation test.
Aug 15, 2026
1ed73ae
Remove unused mut binding on visible_newer in GraphQL query test.
Aug 15, 2026
0ec4c71
Hide unauthorized claim and keep assigned tasks from being stolen
Aug 16, 2026
1b9820b
Keep task-list incomplete for the scan ceiling only.
Aug 16, 2026
ecf478e
fix(node): pin claim guards and map mutation errors through AppError
Aug 18, 2026
ecfbfe8
fix(node): match bare and did:key assignee forms in claim and list
Aug 18, 2026
5ac011f
fix(node): check task creation status and add assignee expression index
Aug 31, 2026
cb41fc3
fix(node)!: Replace task cursors with opaque continuation tokens
Aug 21, 2026
193a965
fix(node): End the candidate stream only after the batch is examined
Aug 21, 2026
a65d7c7
fix(gl): Reject a non-positive task-list limit and fault the write un…
Aug 21, 2026
62893e6
fix(node): Bind task cursors to the caller and brake the task read ro…
Aug 21, 2026
d0a34f1
fix(node): Brake anonymous GraphQL task reads on the same per-IP bucket
Aug 22, 2026
94605f8
fix(gl,node): parse typed task pages, track cursor cycles, and normal…
Aug 22, 2026
e6cf84e
fix(node): Cap aliased GraphQL task reads per request and derive has_…
Aug 23, 2026
e3f4031
fix(node): Check database continuation when scan budget ends on exact…
Aug 23, 2026
7d641a3
fix(node): Document and pin the bound on the task scan-ceiling probe
Aug 24, 2026
7da135c
Index task keyset pages so the scan ceiling bounds database work.
Aug 31, 2026
664fad4
Reject oversized task pages so list never returns more than the reque…
Aug 31, 2026
eccaf90
Enforce task page limits on legacy responses and drop redundant singl…
Sep 2, 2026
b079c11
Address review feedback on task-read authorization gating and client …
Sep 2, 2026
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): Brake anonymous GraphQL task reads on the same per-IP bucket
The per-IP brake added for the task read routes covered only
/api/v1/tasks*, so an anonymous caller reached the same
collect_visible_tasks and get_visible_task gate over /graphql with no
bucket at all. The fence had an open lane beside it.

Carry the brake as GraphQL request data and debit it in the tasks and
task resolvers rather than layering rate_limit_by_ip onto the GraphQL
router: /graphql is one endpoint for every operation, so a router layer
would charge unrelated queries and every mutation against the task-read
bucket. Debiting per resolved field also prices an aliased query
honestly, since ten aliased tasks fields run the gate ten times.

Extract RATE_LIMIT_MESSAGE so the GraphQL surface, which cannot return a
429 status inside a 200 envelope, refuses with the same text the REST
routes use.

/graphql/ws serves the query root as well and stays unbraked; closing it
needs a WebSocketUpgrade handler and is left for a follow-up.

Refs #268
Refs #327
  • Loading branch information
euxaristia
euxaristia committed Aug 31, 2026
commit d0a34f19e648b7a096fee71cb8ca0168636b4bad
101 changes: 101 additions & 0 deletions crates/gitlawb-node/src/api/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,107 @@ mod visible_tasks_tests {
);
}

/// The GraphQL task resolvers reach the SAME `collect_visible_tasks` /
/// `get_visible_task` gate as the REST read routes, so they must carry the
/// same per-IP brake — otherwise `task_read_routes` is a fence with an open
/// gate beside it and a prober just asks over /graphql instead (#327
/// review). The brake rides as request data rather than a router layer
/// because /graphql is one endpoint for every operation; see
/// `rate_limit::TaskReadBrake`.
/// MUTATION (RED): drop the `TaskReadBrake` data from `graphql_handler`, or
/// the `task_read_brake` call from either resolver, and the exhausted-bucket
/// probes below answer normally instead of with the brake message.
#[sqlx::test]
async fn graphql_task_queries_share_the_task_read_ip_brake(pool: PgPool) {
use std::net::SocketAddr;

let mut state = test_state(pool).await;
// Two slots, so the third task field from this IP is braked.
state.task_read_rate_limiter =
crate::rate_limit::RateLimiter::new(2, std::time::Duration::from_secs(3600));
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
state
.db
.create_task(&task("t1", None, DELEGATOR))
.await
.unwrap();

let router = crate::server::build_router(state);
let peer: SocketAddr = "198.51.100.7:5000".parse().unwrap();
let query = |peer: SocketAddr, q: &str| {
let mut req = Request::builder()
.method(Method::POST)
.uri("/graphql")
.header("content-type", "application/json")
.body(Body::from(serde_json::json!({ "query": q }).to_string()))
.unwrap();
req.extensions_mut()
.insert(axum::extract::ConnectInfo(peer));
req
};
let run = |router: Router, peer: SocketAddr, q: &'static str| async move {
let resp = router.oneshot(query(peer, q)).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "GraphQL answers 200: {q}");
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
serde_json::from_slice::<serde_json::Value>(&bytes).unwrap()
};
let braked = |body: &serde_json::Value| {
body["errors"].as_array().is_some_and(|errs| {
errs.iter()
.any(|e| e["message"].as_str() == Some(crate::rate_limit::RATE_LIMIT_MESSAGE))
})
};

// Anonymous list, then anonymous single-id lookup: both run the gate,
// both spend a slot.
for q in ["{ tasks { items { id } } }", "{ task(id: \"t1\") { id } }"] {
let body = run(router.clone(), peer, q).await;
// Asserting the whole `errors` key is absent, not merely that the
// brake message is missing: a query that failed for some other
// reason would still spend its slot and leave this test vacuous.
assert!(
body.get("errors").is_none(),
"{q}: the first probes must pass the brake and resolve, got {body}"
);
}

let body = run(router.clone(), peer, "{ tasks { items { id } } }").await;
assert!(
braked(&body),
"an exhausted per-IP bucket must brake the GraphQL task query too, \
got {body}"
);
assert!(
body["data"]["tasks"].is_null(),
"a braked field must resolve to null, not answer with rows: {body}"
);

// The bucket is the one `task_read_routes` debits, not a second budget:
// the REST route is already exhausted by the GraphQL traffic above.
let mut rest = Request::builder()
.method(Method::GET)
.uri("/api/v1/tasks")
.body(Body::empty())
.unwrap();
rest.extensions_mut()
.insert(axum::extract::ConnectInfo(peer));
let resp = router.clone().oneshot(rest).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"GraphQL and REST task reads must share one per-IP bucket"
);

let other: SocketAddr = "198.51.100.8:5000".parse().unwrap();
let body = run(router, other, "{ tasks { items { id } } }").await;
assert!(
!braked(&body),
"a different IP must not be braked by another IP's exhausted bucket"
);
}

/// #327 review: a cursor records how far a scan got under *one* caller's
/// visibility, so presenting it as a different caller must fail rather
/// than resume. Here an anonymous page stops at a public task, having
Expand Down
19 changes: 19 additions & 0 deletions crates/gitlawb-node/src/graphql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ use super::types::{AgentTaskReadType, RefUpdateType, RepoType, TaskPageType};

pub struct QueryRoot;

/// Debit the per-IP task-read brake for one task field, mirroring the
/// `rate_limit_by_ip` layer on `task_read_routes`. Both surfaces run the same
/// #268 visibility gate and pay the same queries before answering, so an
/// anonymous prober must not get an unbraked lane by asking over GraphQL
/// (#327 review).
///
/// A schema built without the brake (unit tests, subscriptions) is not braked,
/// exactly as `rate_limit_by_ip` is a no-op without its extension.
async fn task_read_brake(ctx: &Context<'_>, field: &str) -> Result<()> {
match ctx.data::<crate::rate_limit::TaskReadBrake>() {
Ok(brake) if !brake.check(field).await => Err(async_graphql::Error::new(
crate::rate_limit::RATE_LIMIT_MESSAGE,
)),
_ => Ok(()),
}
}

#[Object]
impl QueryRoot {
async fn repos(&self, ctx: &Context<'_>) -> Result<Vec<RepoType>> {
Expand Down Expand Up @@ -122,6 +139,7 @@ impl QueryRoot {
) -> Result<TaskPageType> {
use crate::api::task_cursor::{self, TaskCursorKey, TaskFilter};

task_read_brake(ctx, "tasks").await?;
let db = ctx.data_unchecked::<Arc<Db>>();
// #268: gate rows via the same collector the REST list route uses (like
// `ref_updates` shares `collect_visible_ref_updates` with its REST feed),
Expand Down Expand Up @@ -167,6 +185,7 @@ impl QueryRoot {
}

async fn task(&self, ctx: &Context<'_>, id: String) -> Result<Option<AgentTaskReadType>> {
task_read_brake(ctx, "task").await?;
let db = ctx.data_unchecked::<Arc<Db>>();
// #268: same gate as the REST get route, via the shared helper.
let caller = ctx
Expand Down
41 changes: 39 additions & 2 deletions crates/gitlawb-node/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ pub async fn rate_limit_by_did(request: Request, next: Next) -> Response {
return (
StatusCode::TOO_MANY_REQUESTS,
[("retry-after", "60")],
"rate limit exceeded — try again later",
RATE_LIMIT_MESSAGE,
)
.into_response();
}
Expand Down Expand Up @@ -384,18 +384,55 @@ impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PeerAddr {
}
}

/// The message every per-IP brake answers with, shared so the GraphQL surface
/// (which cannot return a 429 status inside a 200 GraphQL envelope) says the
/// same thing as the REST routes.
pub const RATE_LIMIT_MESSAGE: &str = "rate limit exceeded — try again later";

/// The shared 429 response for the per-IP flood brakes. Route-agnostic: this
/// middleware now serves the push path AND the peer-sync routes, so the message
/// stays generic (the offending path is recorded in the warn log below).
pub fn too_many_requests() -> Response {
(
StatusCode::TOO_MANY_REQUESTS,
[("retry-after", "60")],
"rate limit exceeded — try again later",
RATE_LIMIT_MESSAGE,
)
.into_response()
}

/// The per-IP task-read brake carried as GraphQL request data: the limiter plus
/// the client key the transport already resolved.
///
/// `/graphql` is a single POST endpoint, so this brake cannot sit in middleware
/// the way `task_read_routes` mounts `rate_limit_by_ip`: that would charge every
/// unrelated query and every mutation against the task-read bucket. The two task
/// resolvers debit it instead, which also prices an aliased query honestly — ten
/// aliased `tasks` fields run the visibility gate ten times and pay ten slots,
/// where one request-scoped debit would pay one (#327 review).
#[derive(Clone)]
pub struct TaskReadBrake {
pub limiter: RateLimiter,
/// `None` when no key could be resolved at all (no trusted header and no
/// `ConnectInfo`, e.g. a synthetic test request). Never braked, matching
/// [`rate_limit_by_ip`].
pub key: Option<String>,
}

impl TaskReadBrake {
/// Debit one slot for one task-read field. `true` = proceed.
pub async fn check(&self, field: &str) -> bool {
let Some(key) = self.key.as_deref() else {
return true;
};
if self.limiter.check(key).await {
return true;
}
tracing::warn!(key = %key, field = %field, "per-IP rate limit exceeded");
false
}
}

/// Throttle the git push path by resolved client IP. The socket peer address is
/// read from `ConnectInfo` (see `into_make_service_with_connect_info` in
/// `main`). Only skips the limiter when no key can be resolved at all.
Expand Down
13 changes: 13 additions & 0 deletions crates/gitlawb-node/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ use crate::state::AppState;
async fn graphql_handler(
State(state): State<AppState>,
auth: Option<axum::Extension<crate::auth::AuthenticatedDid>>,
headers: axum::http::HeaderMap,
rate_limit::PeerAddr(peer): rate_limit::PeerAddr,
req: GraphQLRequest,
) -> GraphQLResponse {
// `optional_signature` attaches the verified DID when a signature is present.
Expand All @@ -32,6 +34,17 @@ async fn graphql_handler(
if let Some(axum::Extension(did)) = auth {
inner = inner.data(did);
}
// The anonymous `tasks`/`task` resolvers run the same #268 visibility gate
// as the REST read routes and cost the node the same queries, so they carry
// the same per-IP brake. It rides as request data rather than a router layer
// because /graphql is one endpoint for every operation — see `TaskReadBrake`
// (#327 review). It debits before the gate runs, but unlike the REST layer
// it sits inside `optional_signature`, so it brakes the gate's query cost
// and not signature verification.
inner = inner.data(rate_limit::TaskReadBrake {
limiter: state.task_read_rate_limiter.clone(),
key: rate_limit::client_key(&headers, peer, state.push_limiter_trust),
});
state.graphql_schema.execute(inner).await.into()
}

Expand Down