Skip to content
Closed
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)!: bound repo names so emitted cursors always parse
The reposPage cursor embeds base64(JSON(owner_did, name)) while
parse_repo_cursor rejects cursors over 4096 bytes, but repo names were
unbounded on every write path. A single long-named visible repo made the
server emit an endCursor it then rejected as "invalid repository cursor",
dead-ending pagination for every caller past that row.

Bound names to MAX_REPO_NAME_LEN (100 bytes) at the create_repo and
fork_repo handlers via a shared validate_repo_name helper (bad charset is
still a 400), and reject overlong peer-supplied names in
Db::upsert_mirror_repo (the sync caller already drops the error and skips
the mirror).

Also in this round:
- docs/graphql-pagination.md states the 200 page-size maximum and corrects
  the over-budget remedy: a smaller limit does not reduce the reposPage or
  repos price, which is charged at the full MAX_VISIBLE_REPO_PAGE_SIZE
  scan regardless of limit.
- Tests pin refUpdates(limit: -1) clamping to zero rows, the
  parse_repo_cursor wrong-shape-JSON arm with its exact "invalid
  repository cursor" message, the longest-admissible-name cursor
  round-trip, and the mirror write-path rejection.

BREAKING CHANGE: the GraphQL `repos` field now returns an error instead of
the full list when more than MAX_VISIBLE_REPO_PAGE_SIZE (200) repositories
are visible; larger lists must use `reposPage` with `limit`/`after`.
Repository names are additionally limited to 100 bytes at creation, fork,
and mirror-registration time.
  • Loading branch information
cairn-intern committed Nov 7, 2026
commit 1c5838b56179cfdac1a2afb99d8208ab7bdaca7f
62 changes: 43 additions & 19 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,30 @@ pub struct InfoRefsQuery {

// ── Handlers ──────────────────────────────────────────────────────────────

/// Validate a repository name at the create/fork write paths. The charset is
/// restricted, and the length is bounded so every cursor the server emits
/// parses back: `repo_cursor` embeds the name in a base64(JSON) cursor that
/// `parse_repo_cursor` rejects over 4096 bytes (#465 4th round).
fn validate_repo_name(name: &str) -> Result<()> {
// Sanitize name: alphanumeric, hyphens, underscores only
if !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(AppError::BadRequest(
"repo name must contain only alphanumeric characters, hyphens, and underscores".into(),
));
}
// Byte length, not char count: the cursor budget is measured in bytes.
if name.len() > crate::db::MAX_REPO_NAME_LEN {
return Err(AppError::BadRequest(format!(
"repo name must be at most {} bytes",
crate::db::MAX_REPO_NAME_LEN
)));
}
Ok(())
}

/// POST /api/v1/repos
/// Create a new repository. Requires HTTP Signature auth.
pub async fn create_repo(
Expand All @@ -247,16 +271,7 @@ pub async fn create_repo(
// 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
.name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(AppError::BadRequest(
"repo name must contain only alphanumeric characters, hyphens, and underscores".into(),
));
}
validate_repo_name(&req.name)?;

// default_branch is caller-supplied and becomes a PR's target_branch when the
// PR omits one, which is interpolated into a git revision argument. Validate
Expand Down Expand Up @@ -3544,15 +3559,7 @@ pub async fn fork_repo(
let fork_name = req.name.unwrap_or_else(|| source.name.clone());
let forker_did = auth.0;

// Validate fork name
if !fork_name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(AppError::BadRequest(
"repo name must contain only alphanumeric characters, hyphens, and underscores".into(),
));
}
validate_repo_name(&fork_name)?;

// Same barrier every other repo-creation route goes through. The character
// allowlist above is vacuously true on an empty name, and `repo_disk_path`
Expand Down Expand Up @@ -4299,6 +4306,23 @@ mod tests {
);
}

#[test]
fn repo_name_validation_rejects_bad_charset_and_overlong_names() {
assert!(validate_repo_name("ok-name_123").is_ok());
assert!(validate_repo_name(&"a".repeat(crate::db::MAX_REPO_NAME_LEN)).is_ok());
// The bound is in bytes: the cursor budget is measured in bytes.
let overlong = "a".repeat(crate::db::MAX_REPO_NAME_LEN + 1);
let err = validate_repo_name(&overlong).unwrap_err();
assert!(
matches!(err, AppError::BadRequest(_)),
"overlong name must be a 400, got: {err:?}"
);
assert!(validate_repo_name("bad name!").is_err());
// Empty names were already admissible before the length bound; the
// bound does not change that.
assert!(validate_repo_name("").is_ok());
}

#[test]
fn upload_pack_request_finalizes_only_with_done_pktline() {
let want = "0032want 1111111111111111111111111111111111111111\n";
Expand Down
17 changes: 17 additions & 0 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ use uuid::Uuid;
/// Maximum visible repositories per page, plus one internal look-ahead row.
pub(crate) const MAX_VISIBLE_REPO_PAGE_SIZE: usize = 200;

/// Maximum repository name length in bytes. `repo_cursor` embeds the name in
/// a base64(JSON) cursor that `parse_repo_cursor` rejects over 4096 bytes, so
/// every write path must bound the name: a cursor the server emits must
/// always parse back (#465 4th round). 100 bytes keeps the longest possible
/// cursor an order of magnitude under the parse limit.
pub(crate) const MAX_REPO_NAME_LEN: usize = 100;

/// Maximum agent tasks returned per query. Shared by the GraphQL `tasks`
/// complexity meter and the resolver clamp so they can't drift.
pub(crate) const MAX_VISIBLE_TASK_PAGE_SIZE: i64 = 200;
Expand Down Expand Up @@ -1578,6 +1585,16 @@ impl Db {
machine_id: Option<&str>,
quarantined: bool,
) -> Result<()> {
// Peer-supplied names are bound like the local write paths: an
// unbounded name would make reposPage emit a cursor longer than the
// 4096-byte parse limit, dead-ending pagination for every caller past
// that row (#465 4th round). The sync caller drops the error and skips
// the mirror.
if name.len() > MAX_REPO_NAME_LEN {
anyhow::bail!(
"mirror repo name exceeds {MAX_REPO_NAME_LEN} bytes: refusing to register"
);
}
let now = Utc::now().to_rfc3339();
let id = format!("{owner_short}/{name}");
// `quarantined` is set only on first insert (the admission decision).
Expand Down
95 changes: 95 additions & 0 deletions crates/gitlawb-node/src/graphql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,101 @@ mod tests {
assert!(super::parse_repo_cursor(&oversized).is_err());
}

#[tokio::test]
async fn parse_repo_cursor_rejects_wrong_shape_json() {
// Valid base64 and valid JSON, but not a (String, String) pair: the
// wrong-shape arm must report "invalid repository cursor", exactly,
// before any database access.
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://localhost/unused")
.unwrap();
let schema = schema(Arc::new(Db::for_testing(pool)));
for payload in [
serde_json::json!(["only-one"]),
serde_json::json!(["a", "b", "c"]),
serde_json::json!({"owner": "x", "name": "y"}),
serde_json::json!(42),
serde_json::json!(["a", 1]),
] {
let cursor = super::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
let err = super::parse_repo_cursor(&cursor).unwrap_err();
assert_eq!(err.message, "invalid repository cursor");
let query = format!("{{ reposPage(after: \"{cursor}\") {{ hasNextPage }} }}");
let response =
tokio::time::timeout(std::time::Duration::from_secs(1), anon(&schema, &query))
.await
.expect("wrong-shape cursors must be rejected without accessing the database");
assert_eq!(response.errors.len(), 1);
assert_eq!(response.errors[0].message, "invalid repository cursor");
assert_eq!(response.data, async_graphql::Value::Null);
}
}

#[tokio::test]
async fn longest_repo_name_cursor_round_trips() {
// #465 4th round: a cursor the server emits must always parse back.
// Repo names are bounded at the create/fork/mirror write paths, so the
// longest admissible name must produce a cursor under the 4096-byte
// parse limit.
let name = "a".repeat(crate::db::MAX_REPO_NAME_LEN);
let record = repo("long", OWNER, &name, true);
let cursor = super::repo_cursor(&record);
assert!(
cursor.len() <= 4096,
"emitted cursor must stay under the parse limit: {}",
cursor.len()
);
assert_eq!(
super::parse_repo_cursor(&cursor).unwrap(),
(OWNER.to_owned(), name)
);
}

/// A negative refUpdates(limit) must be accepted and clamped to zero rows,
/// like tasks(limit: -1): the complexity formula's `limit.clamp(0, ...)`
/// prices it at the floor and the shared collector returns before any
/// database access. Mirrors tasks_negative_limit_clamped.
#[tokio::test]
async fn ref_updates_negative_limit_clamped() {
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://localhost/unused")
.unwrap();
let schema = schema(Arc::new(Db::for_testing(pool)));
let resp = tokio::time::timeout(
std::time::Duration::from_secs(1),
anon(&schema, "{ refUpdates(limit: -1) { repo } }"),
)
.await
.expect("negative limit must clamp without accessing the database");
assert!(
resp.errors.is_empty(),
"negative limit must clamp, not fail: {:?}",
resp.errors
);
assert_eq!(count(&resp), 0);
}

/// The mirror write path binds peer-supplied names verbatim, so it must
/// enforce the same bound as the local write paths: an overlong peer name
/// would otherwise make reposPage emit an unparseable cursor. The
/// rejection happens before any database access.
#[tokio::test]
async fn mirror_repo_rejects_overlong_name() {
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://localhost/unused")
.unwrap();
let db = Db::for_testing(pool);
let name = "b".repeat(crate::db::MAX_REPO_NAME_LEN + 1);
let err = db
.upsert_mirror_repo("z6MkLong", &name, "/tmp/long", None, false)
.await
.unwrap_err();
assert!(
err.to_string().contains("exceeds"),
"unexpected error: {err}"
);
}

async fn db(pool: PgPool) -> Arc<Db> {
let db = Db::for_testing(pool);
db.run_migrations().await.unwrap();
Expand Down
14 changes: 8 additions & 6 deletions docs/graphql-pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ query Repositories($after: String) {

Start with `after: null`. When `hasNextPage` is true, pass the returned
`endCursor` as `after` on the next request. Stop when `hasNextPage` is false.
An empty page has a null `endCursor`. The default limit is 50; limits below
1 or above the maximum page size are rejected (see Query budgets below).
Malformed cursors, including decoded owner or name strings containing NUL,
return `invalid repository cursor` before database access.
An empty page has a null `endCursor`. The default limit is 50 and the maximum
page size is 200; limits below 1 or above 200 are rejected (see Query budgets
below). Malformed cursors, including decoded owner or name strings containing
NUL, return `invalid repository cursor` before database access.

Pages are ordered by normalized owner DID and repository name. Visibility and
mirror deduplication are applied in the database before limiting the page;
Expand Down Expand Up @@ -67,8 +67,10 @@ smaller. The constants live in `crates/gitlawb-node/src/graphql/mod.rs`.
- `task`, mutations, subscriptions: 50 + child fields.

A document whose total exceeds 400 is rejected with
`Query is too complex.` before any resolver runs, so requesting many
fields or aliases may require a smaller page or fewer aliases.
`Query is too complex.` before any resolver runs, so an over-budget
document needs fewer aliases or fewer child fields. A smaller `limit` does
not help `reposPage` or `repos`: both are priced at the full
`MAX_VISIBLE_REPO_PAGE_SIZE` scan regardless of `limit`.

- **Depth cap: 14 per document** (`GRAPHQL_MAX_DEPTH`). Documents nested
deeper than 14 selections are rejected with `Query is nested too deep.`