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): Cap aliased GraphQL task reads per request and derive has_…
…more from visible rows

- Cap aliased GraphQL task read fields per request using an atomic counter
  on TaskReadBrake (MAX_GRAPHQL_TASK_READS_PER_REQUEST = 5).
- Derive has_more in collect_visible_tasks by scanning for bounded_limit + 1
  visible rows, eliminating the un-gated keyset probe that could leak the
  presence of trailing denied tasks.
- Add regression tests covering aliased GraphQL capping and trailing denied
  task has_more privacy.

Refs #327
  • Loading branch information
euxaristia
euxaristia committed Aug 31, 2026
commit e6cf84ef02206be2055fc698f2d197284f2a679e
150 changes: 129 additions & 21 deletions crates/gitlawb-node/src/api/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,15 @@ pub(crate) async fn collect_visible_tasks(
next_position: None,
});
}
let mut visible = Vec::with_capacity(bounded_limit);
// Probe for bounded_limit + 1 visible tasks to prove has_more from visible rows only (#327 review).
let target_visible = bounded_limit + 1;
let mut visible = Vec::with_capacity(target_visible);
let mut examined: Option<TaskPosition> = resume.cloned();
let mut resume_position_for_page: Option<TaskPosition> = None;
let mut scanned: i64 = 0;
let mut stream_ended = false;

while scanned < MAX_TASK_SCAN_CANDIDATES && visible.len() < bounded_limit {
while scanned < MAX_TASK_SCAN_CANDIDATES && visible.len() < target_visible {
let batch_limit = MAX_VISIBLE_TASKS.min(MAX_TASK_SCAN_CANDIDATES - scanned);
let batch = db
.list_tasks_keyset(
Expand Down Expand Up @@ -286,40 +289,36 @@ pub(crate) async fn collect_visible_tasks(
// request neither repeats nor skips its successors.
scanned += 1;
consumed += 1;
examined = Some(TaskPosition::new(task.created_at.clone(), task.id.clone()));
let current_pos = TaskPosition::new(task.created_at.clone(), task.id.clone());
examined = Some(current_pos.clone());
if task_visible(task, caller, &repos_by_id, &rules_by_repo) {
visible.push(task.clone());
if visible.len() == bounded_limit {
resume_position_for_page = Some(current_pos);
} else if visible.len() == target_visible {
break;
}
}
}

// A short batch only ends the stream once every row in it has been
// examined. Filling the page mid-batch leaves rows behind that the
// next request must still see, so the position advances and `has_more`
// is settled by the probe below rather than assumed false.
// examined.
if consumed == batch.len() && batch_len < batch_limit {
stream_ended = true;
break;
}
}

// A full final batch is ambiguous: more rows may exist, or the stream may
// have ended on an exact multiple of the batch size. One probe row past
// the last examined candidate settles it, so `has_more` never advertises a
// page that turns out to be empty.
let has_more = if stream_ended {
false
// Derive has_more from visible rows or scan-budget exhaustion, never from
// an un-gated candidate probe that would leak the existence of trailing
// denied rows (#327 review).
let (has_more, next_position) = if visible.len() > bounded_limit {
visible.truncate(bounded_limit);
(true, resume_position_for_page)
} else if stream_ended {
(false, None)
} else {
!db.list_tasks_keyset(
status,
assignee_did,
1,
examined.as_ref().map(TaskPosition::as_pair),
)
.await?
.is_empty()
(true, examined)
};

let incomplete = has_more && visible.len() < bounded_limit;
Expand All @@ -328,7 +327,7 @@ pub(crate) async fn collect_visible_tasks(
tasks: visible,
has_more,
incomplete,
next_position: if has_more { examined } else { None },
next_position,
})
}

Expand Down Expand Up @@ -1370,6 +1369,115 @@ mod visible_tasks_tests {
);
}

/// #327 review: aliased GraphQL task queries execute within a single request,
/// so a request-scoped cap prevents an anonymous prober from exhausting the
/// rate limit or running excessive visibility scans in one POST.
#[sqlx::test]
async fn graphql_aliased_task_queries_are_capped_per_request(pool: PgPool) {
use std::net::SocketAddr;

let mut state = test_state(pool).await;
// Large per-IP budget so per-request cap is what triggers first.
state.task_read_rate_limiter =
crate::rate_limit::RateLimiter::new(100, 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.9: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 aliased_query = "{ \
a1: tasks { items { id } } \
a2: tasks { items { id } } \
a3: tasks { items { id } } \
a4: tasks { items { id } } \
a5: tasks { items { id } } \
a6: tasks { items { id } } \
}";
let resp = router.oneshot(query(peer, aliased_query)).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let body = serde_json::from_slice::<serde_json::Value>(&bytes).unwrap();
assert!(
body["errors"].as_array().is_some_and(|errs| {
errs.iter()
.any(|e| e["message"].as_str() == Some(crate::rate_limit::RATE_LIMIT_MESSAGE))
}),
"excess aliased fields beyond per-request limit must be rejected, got {body}"
);
}

/// #327 review: trailing denied tasks must not advertise `has_more = true`
/// or leak the existence of private rows through pagination metadata.
#[sqlx::test]
async fn trailing_denied_tasks_do_not_set_has_more_or_leak_existence(pool: PgPool) {
let state = test_state(pool).await;
state
.db
.create_repo(&repo("public-repo", DELEGATOR, "public", true))
.await
.unwrap();
state
.db
.create_repo(&repo("private-repo", DELEGATOR, "private", false))
.await
.unwrap();

// 2 public tasks, followed by 3 private tasks
for (id, repo_id, ts) in [
("pub-2", "public-repo", "2026-01-05T00:00:00Z"),
("pub-1", "public-repo", "2026-01-04T00:00:00Z"),
("priv-3", "private-repo", "2026-01-03T00:00:00Z"),
("priv-2", "private-repo", "2026-01-02T00:00:00Z"),
("priv-1", "private-repo", "2026-01-01T00:00:00Z"),
] {
let mut t = task(id, Some(repo_id), DELEGATOR);
t.created_at = ts.to_string();
t.updated_at = ts.to_string();
state.db.create_task(&t).await.unwrap();
}

let resp = list_router(state)
.oneshot(anon_get("/api/v1/tasks?limit=2"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = body_json(resp).await;
let tasks = body["tasks"].as_array().unwrap();
assert_eq!(tasks.len(), 2);
assert_eq!(tasks[0]["id"], "pub-2");
assert_eq!(tasks[1]["id"], "pub-1");
assert_eq!(
body["has_more"], false,
"has_more must be false when only denied tasks trail the page, got {body}"
);
assert_eq!(
body["incomplete"], false,
"incomplete must be false when all visible tasks have been delivered, got {body}"
);
assert!(
body["next_cursor"].is_null(),
"next_cursor must be null when no more visible tasks exist, got {body}"
);
}

/// #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
17 changes: 17 additions & 0 deletions crates/gitlawb-node/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,13 +410,18 @@ pub fn too_many_requests() -> Response {
/// 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).
/// Default cap on the number of task read fields (across all aliases) permitted
/// in a single GraphQL request before rejecting further field executions (#327 review).
pub const MAX_GRAPHQL_TASK_READS_PER_REQUEST: usize = 5;

#[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>,
pub request_count: Arc<std::sync::atomic::AtomicUsize>,
}

impl TaskReadBrake {
Expand All @@ -425,6 +430,18 @@ impl TaskReadBrake {
let Some(key) = self.key.as_deref() else {
return true;
};
let count = self
.request_count
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if count >= MAX_GRAPHQL_TASK_READS_PER_REQUEST {
tracing::warn!(
key = %key,
field = %field,
count = count + 1,
"per-request GraphQL task field limit exceeded"
);
return false;
}
if self.limiter.check(key).await {
return true;
}
Expand Down
1 change: 1 addition & 0 deletions crates/gitlawb-node/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ async fn graphql_handler(
inner = inner.data(rate_limit::TaskReadBrake {
limiter: state.task_read_rate_limiter.clone(),
key: rate_limit::client_key(&headers, peer, state.push_limiter_trust),
request_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
});
state.graphql_schema.execute(inner).await.into()
}
Expand Down