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
Preserve authorized task reads across shipped clients.
Refs #268
  • Loading branch information
euxaristia
euxaristia committed Aug 31, 2026
commit c7654983f0833e860e489798170b53bc77440b83
159 changes: 114 additions & 45 deletions crates/gitlawb-node/src/api/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,15 @@ pub(crate) fn task_visible(
return true;
}
}
let Some(record) = task.repo_id.as_deref().and_then(|id| repos_by_id.get(id)) else {
let Some(repo_id) = task.repo_id.as_deref() else {
return false;
};
// Slash-form ids are mirror rows. Mirrors are public placeholders and do
// not replicate visibility rules, so they cannot establish read access.
if repo_id.contains('/') {
return false;
}
let Some(record) = repos_by_id.get(repo_id) else {
return false;
};
let rules = rules_by_repo
Expand All @@ -165,13 +173,6 @@ pub(crate) fn task_visible(
/// pattern in `api/events.rs`. `limit` is clamped here so a caller-supplied
/// value never reaches SQL unclamped.
///
/// Unlike the ref-updates feed, this does not page past invisible rows: it
/// fetches one bounded page and filters it, so a request whose newest
/// `MAX_VISIBLE_TASKS` rows are mostly invisible to the caller can return
/// fewer rows than are truly visible further back. Accepted here because,
/// unlike the cross-tenant ref-updates feed, task queries are already scoped
/// by `status`/`assignee_did` up front, which keeps the visible/invisible mix
/// per query far narrower in practice.
pub(crate) async fn collect_visible_tasks(
db: &crate::db::Db,
status: Option<&str>,
Expand All @@ -183,44 +184,53 @@ pub(crate) async fn collect_visible_tasks(
if bounded_limit == 0 {
return Ok(Vec::new());
}
let tasks = db.list_tasks(status, assignee_did, bounded_limit).await?;
if tasks.is_empty() {
return Ok(tasks);
}
// Narrow to the repos this page's tasks actually name, so the rule lookup
// below is bounded by the page (≤ MAX_VISIBLE_TASKS) instead of by how many
// repos the node hosts — otherwise an anonymous request pulls every
// visibility rule on the node. The deduped snapshot stays the source of
// truth for *which* repo a `repo_id` resolves to: it collapses
// mirror/canonical pairs and omits quarantined repos, and an id that is
// absent from it must keep failing closed in `task_visible` (a raw
// repos-by-id lookup would resurrect exactly those rows).
let referenced: HashSet<&str> = tasks.iter().filter_map(|t| t.repo_id.as_deref()).collect();
if referenced.is_empty() {
let empty_repos = HashMap::new();
let empty_rules = HashMap::new();
return Ok(tasks
let mut visible = Vec::with_capacity(bounded_limit as usize);
let mut cursor: Option<(String, String)> = None;
loop {
let tasks = db
.list_tasks_keyset(
status,
assignee_did,
MAX_VISIBLE_TASKS,
cursor
.as_ref()
.map(|(created_at, id)| (created_at.as_str(), id.as_str())),
)
.await?;
if tasks.is_empty() {
break;
}
let next_cursor = tasks
.last()
.map(|task| (task.created_at.clone(), task.id.clone()));
let referenced: Vec<String> = tasks
.iter()
.filter_map(|task| task.repo_id.clone())
.collect::<HashSet<_>>()
.into_iter()
.filter(|t| task_visible(t, caller, &empty_repos, &empty_rules))
.collect());
.collect();
let repos_by_id: HashMap<String, RepoRecord> = db
.list_repos_deduped_by_ids(&referenced)
.await?
.into_iter()
.map(|repo| (repo.id.clone(), repo))
.collect();
let repo_ids: Vec<String> = repos_by_id.keys().cloned().collect();
let rules_by_repo = db.list_visibility_rules_for_repos(&repo_ids).await?;

visible.extend(
tasks
.iter()
.filter(|task| task_visible(task, caller, &repos_by_id, &rules_by_repo))
.take((bounded_limit as usize).saturating_sub(visible.len()))
.cloned(),
);
if visible.len() == bounded_limit as usize || tasks.len() < MAX_VISIBLE_TASKS as usize {
break;
}
cursor = next_cursor;
}
let repos_by_id: HashMap<String, RepoRecord> = db
.list_all_repos_deduped()
.await?
.into_iter()
.filter(|r| referenced.contains(r.id.as_str()))
.map(|r| (r.id.clone(), r))
.collect();
let ids: Vec<String> = repos_by_id.keys().cloned().collect();
let rules_by_repo = if ids.is_empty() {
HashMap::new()
} else {
db.list_visibility_rules_for_repos(&ids).await?
};
Ok(tasks
.into_iter()
.filter(|t| task_visible(t, caller, &repos_by_id, &rules_by_repo))
.collect())
Ok(visible)
}

/// Fetch a single task gated the same way `collect_visible_tasks` gates a
Expand All @@ -238,7 +248,8 @@ pub(crate) async fn get_visible_task(
};
let (repos_by_id, rules_by_repo) = match task.repo_id.as_deref() {
Some(repo_id) => {
let repos = db.list_all_repos_deduped().await?;
let ids = [repo_id.to_string()];
let repos = db.list_repos_deduped_by_ids(&ids).await?;
match repos.into_iter().find(|r| r.id == repo_id) {
Some(record) => {
let rules = db.list_visibility_rules(&record.id).await?;
Expand Down Expand Up @@ -742,6 +753,35 @@ mod visible_tasks_tests {
);
}

#[sqlx::test]
async fn mirror_only_repo_task_is_hidden_from_anonymous_reads(pool: PgPool) {
let state = test_state(pool).await;
state
.db
.upsert_mirror_repo(DELEGATOR, "mirror", "/tmp/mirror", None, false)
.await
.unwrap();
let mirror_id = format!("{DELEGATOR}/mirror");
state
.db
.create_task(&task("t1", Some(&mirror_id), DELEGATOR))
.await
.unwrap();

let resp = list_router(state.clone())
.oneshot(anon_get("/api/v1/tasks"))
.await
.unwrap();
let body = body_json(resp).await;
assert_eq!(body["count"], 0);

let resp = list_router(state)
.oneshot(anon_get("/api/v1/tasks/t1"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

/// A negative limit must clamp to zero through `collect_visible_tasks`,
/// not fall through to the visible set.
#[sqlx::test]
Expand All @@ -765,4 +805,33 @@ mod visible_tasks_tests {
let body = body_json(resp).await;
assert_eq!(body["count"], 0, "negative limit must clamp to 0");
}

#[sqlx::test]
async fn older_visible_task_is_not_hidden_by_newer_denied_window(pool: PgPool) {
let state = test_state(pool).await;
state
.db
.create_repo(&repo("public-repo", DELEGATOR, "public", true))
.await
.unwrap();
let mut visible = task("visible", Some("public-repo"), DELEGATOR);
visible.created_at = "2026-01-01T00:00:00Z".into();
visible.updated_at = visible.created_at.clone();
state.db.create_task(&visible).await.unwrap();

for i in 0..MAX_VISIBLE_TASKS {
let mut hidden = task(&format!("hidden-{i:03}"), None, DELEGATOR);
hidden.created_at = "2026-01-02T00:00:00Z".into();
hidden.updated_at = hidden.created_at.clone();
state.db.create_task(&hidden).await.unwrap();
}

let resp = list_router(state)
.oneshot(anon_get("/api/v1/tasks?limit=1"))
.await
.unwrap();
let body = body_json(resp).await;
assert_eq!(body["count"], 1);
assert_eq!(body["tasks"][0]["id"], "visible");
}
}
134 changes: 93 additions & 41 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1426,11 +1426,13 @@ impl Db {

/// Shared dedup CTE: collapses the mirror row and the canonical row of one
/// logical repo into a single survivor. `$1` is an optional owner filter
/// (NULL = all rows). Grouping collapses on a did:key-aware owner key: strip a
/// `did:key:` prefix (8 chars, so `substr(owner_did, 9)`) only when the
/// remainder is a bare id with no `:`, otherwise keep the full DID. That is the
/// exact normalization in `crate::api::did_matches`, so `did:key:X` and a bare
/// `X` collapse while distinct DID methods (`did:gitlawb:X`) never merge. The
/// (NULL = all rows). `$2` optionally scopes the work to the logical groups
/// containing the supplied repo ids. Grouping collapses on a did:key-aware
/// owner key: strip a `did:key:` prefix (8 chars, so
/// `substr(owner_did, 9)`) only when the remainder is a bare id with no `:`,
/// otherwise keep the full DID. That is the exact normalization in
/// `crate::api::did_matches`, so `did:key:X` and a bare `X` collapse while
/// distinct DID methods (`did:gitlawb:X`) never merge. The
/// CASE is repeated verbatim in `count_repos_deduped` and the v7 index and must
/// stay byte-identical or Postgres stops using the index.
/// The canonical row wins (mirror rows carry a slash-form `id` written only by
Expand All @@ -1440,7 +1442,12 @@ impl Db {
/// `crate::api::repos::dedupe_canonical_repos` must stay in sync.
fn dedup_cte() -> String {
format!(
"WITH deduped AS (
"WITH requested_groups AS (
SELECT DISTINCT {key} AS owner_key, name
FROM repos
WHERE $2::text[] IS NOT NULL AND id = ANY($2)
),
deduped AS (
SELECT DISTINCT ON ({key}, name)
id, name, owner_did, description, is_public, default_branch,
created_at,
Expand All @@ -1459,6 +1466,11 @@ impl Db {
-- Quarantined mirrors (admitted but unvalidated by the iCaptcha
-- propagation gate) are withheld from every listing surface.
WHERE quarantined = FALSE AND ($1::text IS NULL OR ({key}) = $1)
AND ($2::text[] IS NULL OR EXISTS (
SELECT 1 FROM requested_groups requested
WHERE requested.owner_key = ({key})
AND requested.name = repos.name
))
ORDER BY {key}, name,
-- mirror rows carry a slash-form id (\"{{owner_short}}/{{name}}\"),
-- written only by upsert_mirror_repo; canonical ids are UUIDs.
Expand Down Expand Up @@ -1506,6 +1518,7 @@ impl Db {
);
let rows = sqlx::query(&sql)
.bind(owner_key)
.bind(None::<&[String]>)
.fetch_all(&self.pool)
.await?;

Expand Down Expand Up @@ -1534,6 +1547,32 @@ impl Db {
);
let rows = sqlx::query(&sql)
.bind(None::<&str>)
.bind(None::<&[String]>)
.fetch_all(&self.pool)
.await?;

Ok(rows.into_iter().map(row_to_repo).collect())
}

/// Resolve only the requested repository ids through the same canonical
/// survivor and quarantine rules as `list_all_repos_deduped`.
pub async fn list_repos_deduped_by_ids(&self, repo_ids: &[String]) -> Result<Vec<RepoRecord>> {
if repo_ids.is_empty() {
return Ok(Vec::new());
}
let sql = format!(
"{}
SELECT d.id, d.name, d.owner_did, d.description, d.is_public,
d.default_branch, d.created_at, d.updated_at, d.disk_path,
d.forked_from, d.machine_id
FROM deduped d
WHERE d.id = ANY($2)
ORDER BY d.updated_at DESC",
Self::dedup_cte()
);
let rows = sqlx::query(&sql)
.bind(None::<&str>)
.bind(repo_ids)
.fetch_all(&self.pool)
.await?;

Expand Down Expand Up @@ -3697,46 +3736,29 @@ impl Db {
Ok(row.map(row_to_task))
}

pub async fn list_tasks(
pub async fn list_tasks_keyset(
&self,
status: Option<&str>,
assignee_did: Option<&str>,
limit: i64,
after: Option<(&str, &str)>,
) -> Result<Vec<AgentTask>> {
let rows = match (status, assignee_did) {
(Some(s), Some(a)) => sqlx::query(
"SELECT id, repo_id, kind, status, delegator_did, assignee_did, capability, ucan_token, payload, result, created_at, updated_at, deadline
FROM agent_tasks WHERE status=$1 AND assignee_did=$2 ORDER BY created_at DESC LIMIT $3",
)
.bind(s)
.bind(a)
.bind(limit)
.fetch_all(&self.pool)
.await?,
(Some(s), None) => sqlx::query(
"SELECT id, repo_id, kind, status, delegator_did, assignee_did, capability, ucan_token, payload, result, created_at, updated_at, deadline
FROM agent_tasks WHERE status=$1 ORDER BY created_at DESC LIMIT $2",
)
.bind(s)
.bind(limit)
.fetch_all(&self.pool)
.await?,
(None, Some(a)) => sqlx::query(
"SELECT id, repo_id, kind, status, delegator_did, assignee_did, capability, ucan_token, payload, result, created_at, updated_at, deadline
FROM agent_tasks WHERE assignee_did=$1 ORDER BY created_at DESC LIMIT $2",
)
.bind(a)
.bind(limit)
.fetch_all(&self.pool)
.await?,
(None, None) => sqlx::query(
"SELECT id, repo_id, kind, status, delegator_did, assignee_did, capability, ucan_token, payload, result, created_at, updated_at, deadline
FROM agent_tasks ORDER BY created_at DESC LIMIT $1",
)
.bind(limit)
.fetch_all(&self.pool)
.await?,
};
let rows = sqlx::query(
"SELECT id, repo_id, kind, status, delegator_did, assignee_did, capability, ucan_token, payload, result, created_at, updated_at, deadline
FROM agent_tasks
WHERE ($1::text IS NULL OR status = $1)
AND ($2::text IS NULL OR assignee_did = $2)
AND ($3::text IS NULL OR (created_at, id) < ($3, $4))
ORDER BY created_at DESC, id DESC
LIMIT $5",
)
.bind(status)
.bind(assignee_did)
.bind(after.map(|cursor| cursor.0))
.bind(after.map(|cursor| cursor.1))
.bind(limit)
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(row_to_task).collect())
}
Comment thread
euxarist marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -5261,6 +5283,36 @@ mod dedup_db_tests {
);
}

#[sqlx::test]
async fn deduped_id_lookup_returns_only_requested_repo(pool: PgPool) {
let db = db(pool).await;
let requested = rec(
"requested",
"did:key:z6MkRequested",
"requested",
"requested",
"2026-01-01T00:00:00Z",
"2026-01-01T00:00:00Z",
);
let unrelated = rec(
"unrelated",
"did:key:z6MkUnrelated",
"unrelated",
"unrelated",
"2026-01-02T00:00:00Z",
"2026-01-02T00:00:00Z",
);
db.create_repo(&requested).await.unwrap();
db.create_repo(&unrelated).await.unwrap();

let out = db
.list_repos_deduped_by_ids(&[requested.id.clone()])
.await
.unwrap();
assert_eq!(out.len(), 1);
assert_eq!(out[0].id, requested.id);
}

/// A PRIVATE canonical repo and a PUBLIC mirror row for the same
/// (owner, name) collapse to a single survivor whose `is_public` is the
/// canonical `false`, not the mirror's `true`. `upsert_mirror_repo` always
Expand Down
Loading