mirror of
https://github.com/Twigpine/node.git
synced 2026-11-08 17:55:53 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1424447257 | ||
|
|
99ef7b6035 | ||
|
|
c805e35f40 |
No files matched your search
@@ -326,19 +326,6 @@ GITLAWB_IPFS_RESOLVE_BUDGET_SECS=10
|
||||
# from the concurrency caps above). 0 disables. Default 600.
|
||||
GITLAWB_IPFS_RATE_LIMIT=600
|
||||
|
||||
# Per-client-IP rate limit for the anonymous task read routes
|
||||
# (GET /api/v1/tasks, GET /api/v1/tasks/{id}), in requests per hour.
|
||||
# Both are publicly reachable (optional_signature). GET /api/v1/tasks runs
|
||||
# collect_visible_tasks and returns a visibility-filtered page;
|
||||
# GET /api/v1/tasks/{id} runs get_visible_task and returns an opaque 404 when
|
||||
# the task is hidden or missing. These reads can require task, repository,
|
||||
# and visibility-rule queries even when no task is returned, so the brake
|
||||
# bounds the cost of anonymous probes. Keyed on the resolved client IP via
|
||||
# GITLAWB_TRUSTED_PROXY. 0 disables. Default: 1200 (a list page
|
||||
# followed by per-task reads is a normal client pattern, so this sits above
|
||||
# the /ipfs budget). The GraphQL/WS task-read brake shares this budget.
|
||||
GITLAWB_TASK_READ_RATE_LIMIT=1200
|
||||
|
||||
# ── Creation rate limiting (repo/agent/issue/PR flood brake) ──────────────
|
||||
# Max creation requests (POST /api/v1/repos, /api/register, fork, issues,
|
||||
# pulls) per client IP per hour, in addition to the per-DID limit. The per-DID
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.7.1"
|
||||
".": "0.8.0"
|
||||
}
|
||||
+167
@@ -1,5 +1,172 @@
|
||||
# Changelog
|
||||
|
||||
## [0.8.0](https://github.com/Twigpine/node/compare/v0.7.1...v0.8.0) (2026-11-08)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **node:** 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.
|
||||
* **node:** gl cert show <id> --verify now requires --expect-node <did>; the node's self-reported DID is no longer trusted as a cert anchor.
|
||||
* **node:** `git-receive-pack` now rejects a push whose authenticated DID is not the repo owner, returning 403 before any ref update is applied. Delegated and CI keys count as non-owners: a UCAN `git/push` capability is verified but not yet honored for authorization, so an agent pushing under its own DID cannot push while this is on. Set `GITLAWB_ENFORCE_OWNER_PUSH=false` during a rolling upgrade, or have automation push as the repo owner, until scoped collaborator / UCAN-delegated push rights land.
|
||||
|
||||
### Features
|
||||
|
||||
* **core:** carry the resumed candidate's identity in the scan token ([2656718](https://github.com/Twigpine/node/commit/2656718916ab9c68dd7fccb8f6fba8bba6b43e82))
|
||||
* **node,git:** cap concurrent served git ops with a 503 load-shed ([#62](https://github.com/Twigpine/node/issues/62)) ([5981257](https://github.com/Twigpine/node/commit/5981257be582fe1d39980bb2b1b3ff5c98448e84))
|
||||
* **node:** persist upstream mirror configuration and transition state ([#538](https://github.com/Twigpine/node/issues/538)) ([0e5a160](https://github.com/Twigpine/node/commit/0e5a1608e21f4859b2919307287747263f9fa8d0))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **api,sync:** Delimit positional arguments in git clone mirror invocations ([#539](https://github.com/Twigpine/node/issues/539)) ([0cdb4bc](https://github.com/Twigpine/node/commit/0cdb4bcc7c4f7b0eb997fc5ea26981b1e0e26e3c))
|
||||
* **attest:** bound did:key method-id length before base58 decode ([#360](https://github.com/Twigpine/node/issues/360)) ([#535](https://github.com/Twigpine/node/issues/535)) ([9b915b0](https://github.com/Twigpine/node/commit/9b915b09a7c727af15c5c520107403b9dc93d35a))
|
||||
* **attest:** make verify_all lenient under RequireAll ([#359](https://github.com/Twigpine/node/issues/359)) ([#532](https://github.com/Twigpine/node/issues/532)) ([db98b39](https://github.com/Twigpine/node/commit/db98b3957a15eff9e9f286f8a2d084d8e731fcdb))
|
||||
* **attest:** use strict Ed25519 verification with regression test ([1fcbbbd](https://github.com/Twigpine/node/commit/1fcbbbd89c027ae7d1d903f705631d94f8dfbadc))
|
||||
* **ci:** add tested release tag resolver ([1b65f70](https://github.com/Twigpine/node/commit/1b65f70403ab47ced8c2828745c1c79c89a185e4))
|
||||
* **ci:** recognize namespaced test attributes in pr-triage's needs-tests check ([1989fcc](https://github.com/Twigpine/node/commit/1989fcca112d0efb56978efe09d9a836afa7cb59))
|
||||
* **ci:** reject unsafe release dispatch tags ([7b365b0](https://github.com/Twigpine/node/commit/7b365b0dc3ef3b5e3d14fd62bccc434e57200612))
|
||||
* **ci:** reject unsafe release dispatch tags ([0b990d6](https://github.com/Twigpine/node/commit/0b990d687f0eb379b62eb600ede2a6233017e419))
|
||||
* **core:** cap the blinded recipient scan in open_blob ([#419](https://github.com/Twigpine/node/issues/419)) ([#440](https://github.com/Twigpine/node/issues/440)) ([2450bbd](https://github.com/Twigpine/node/commit/2450bbd9e962f47b374b07932a1ff3fc969b9427))
|
||||
* **core:** compute created-skew in checked arithmetic ([#358](https://github.com/Twigpine/node/issues/358)) ([#545](https://github.com/Twigpine/node/issues/545)) ([61d8a4f](https://github.com/Twigpine/node/commit/61d8a4f8f1503ca0b088a039802a8999d305642d))
|
||||
* **core:** count distinct signer DIDs in certificate threshold check ([3993fd1](https://github.com/Twigpine/node/commit/3993fd1f5daacbebb8f8e2c62af8856c493ec87a))
|
||||
* **core:** Count distinct signer DIDs in certificate threshold check ([50d3cbb](https://github.com/Twigpine/node/commit/50d3cbbe97f77b3cab9fab220add9f3a0d0dbc2f))
|
||||
* **core:** enforce strict RFC 8032 Ed25519 signature verification ([425ebf4](https://github.com/Twigpine/node/commit/425ebf40e7737f44c5fe4e9dc8995c8aeb074ce1))
|
||||
* **core:** put the redirect predicate behind a feature so core stays lean ([c82a70a](https://github.com/Twigpine/node/commit/c82a70ab21a21192b2579693b7d7c13aeb8a4d20))
|
||||
* **core:** refuse a redirect that rewrites the signed request-target ([5c0d6f3](https://github.com/Twigpine/node/commit/5c0d6f32522adea8f167f8e445a26377b6fe3963))
|
||||
* **core:** reject small-order Ed25519 keys at DID resolution and before X25519 ([#314](https://github.com/Twigpine/node/issues/314)) ([86c544a](https://github.com/Twigpine/node/commit/86c544a577f28efb2341a53d4faa6b54d1c8b919))
|
||||
* **core:** reject zero threshold, canonicalize did:key, document replay ([#509](https://github.com/Twigpine/node/issues/509)) ([#540](https://github.com/Twigpine/node/issues/540)) ([b4a3122](https://github.com/Twigpine/node/commit/b4a3122500e87d0b84aa3b116171de070188a6bd))
|
||||
* **core:** share the origin-scoped redirect rule with the git helper ([ba44a01](https://github.com/Twigpine/node/commit/ba44a018ec8945b447977d89fc6a10d98fc1bb7b))
|
||||
* **core:** use strict Ed25519 signature verification ([a6c13be](https://github.com/Twigpine/node/commit/a6c13be15b1421f3791e49a8219ea739f1e3ec6e))
|
||||
* **deps:** bump aws-smithy-json to 0.62.7 (GHSA-8ffr-xgwf-xj56) ([#516](https://github.com/Twigpine/node/issues/516)) ([151d688](https://github.com/Twigpine/node/commit/151d68838743a96198879b3154cfbaedca04c3cd))
|
||||
* **deps:** bump follow-redirects and override ws in scripts/ ([#525](https://github.com/Twigpine/node/issues/525)) ([a23c81d](https://github.com/Twigpine/node/commit/a23c81d75ae0a7567905ca9ad093bc9ad7c5adcf))
|
||||
* **deps:** bump libp2p to pick up hickory 0.26 and serde_with 3.22 ([#518](https://github.com/Twigpine/node/issues/518)) ([623b600](https://github.com/Twigpine/node/commit/623b600835d717fcfdab36af116dd4b9a92a92cd)), closes [#76](https://github.com/Twigpine/node/issues/76)
|
||||
* **deps:** resolve cargo audit failures on main ([#514](https://github.com/Twigpine/node/issues/514)) ([4d024e0](https://github.com/Twigpine/node/commit/4d024e01bcf25c93a3b878ac50e6435575dcc5f4))
|
||||
* **git-remote:** abort fetch on EOF without POSTing; harden the real-git test harness ([#192](https://github.com/Twigpine/node/issues/192)) ([1cb930c](https://github.com/Twigpine/node/commit/1cb930cbd57ea5d232edddc8e50dc94fab4362a5))
|
||||
* **git-remote:** drive multi-round fetch as a v0 stateless-RPC client loop ([#117](https://github.com/Twigpine/node/issues/117)) ([5fdf155](https://github.com/Twigpine/node/commit/5fdf155c7fd7398f61c200c256cb7327729f378a))
|
||||
* **git-remote:** drive multi-round fetch as a v0 stateless-RPC client loop ([#117](https://github.com/Twigpine/node/issues/117)) ([a64b141](https://github.com/Twigpine/node/commit/a64b14150dfb7e369c16e5fab98375ba0ce38404))
|
||||
* **git-remote:** normalize the shim's accepted socket to blocking ([10e0840](https://github.com/Twigpine/node/commit/10e0840dd95204d2b8faa1c594808e2ad57bc9c4))
|
||||
* **git-remote:** normalize the shim's accepted socket to blocking ([#192](https://github.com/Twigpine/node/issues/192)) ([8d7f95f](https://github.com/Twigpine/node/commit/8d7f95fd63769ef30540f216190e1bb52ccd4f69))
|
||||
* **git-remote:** reject malformed pkt-line length headers instead of flushing ([8c04043](https://github.com/Twigpine/node/commit/8c04043fb56b5030a0aa6b328c91f20173352aa6))
|
||||
* **git-remote:** skip content-free flush rounds in the fetch loop ([#117](https://github.com/Twigpine/node/issues/117)) ([68ba492](https://github.com/Twigpine/node/commit/68ba49267c8d65169ab9adf0552761f87baba4c1))
|
||||
* **git-remote:** stop waiting on EOF for a delete-only push ([#442](https://github.com/Twigpine/node/issues/442)) ([c2e175d](https://github.com/Twigpine/node/commit/c2e175d2222975eccb4776447268e8678fd48ba4))
|
||||
* **gl:** accept the resume token the incomplete-scan message tells you to pass ([181f617](https://github.com/Twigpine/node/commit/181f6178a0e0f5b9506093fa7579ad6ef8dd2ff5))
|
||||
* **gl:** assert 404 verdict and harden transport error handling in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([a329174](https://github.com/Twigpine/node/commit/a3291741757038307e61d3952e6c20aa4901c8a3))
|
||||
* **gl:** assert whoami 404 verdict and preserve transport error cause ([#220](https://github.com/Twigpine/node/issues/220)) ([b4007a5](https://github.com/Twigpine/node/commit/b4007a5e005c63aa0c083b969cd8b5f65b918adb))
|
||||
* **gl:** close two completeness-gate escapes; surface the node's error key ([6b2c53b](https://github.com/Twigpine/node/commit/6b2c53bbb86bcb35a54ef2edd2078e8f208263a6))
|
||||
* **gl:** derive View: URL from node instead of hardcoding gitlawb.com ([#370](https://github.com/Twigpine/node/issues/370)) ([#549](https://github.com/Twigpine/node/issues/549)) ([d84c445](https://github.com/Twigpine/node/commit/d84c445f94c05e43994c8199bb8e4cd432554fbc))
|
||||
* **gl:** follow scan continuations in gl ipfs get, bounded three ways ([9a8d190](https://github.com/Twigpine/node/commit/9a8d190492315cf767807dd1a98470debff4bd25))
|
||||
* **gl:** make doctor exit non-zero on Fail-class checks ([#357](https://github.com/Twigpine/node/issues/357)) ([#547](https://github.com/Twigpine/node/issues/547)) ([42cc893](https://github.com/Twigpine/node/commit/42cc893fb3af17468767cd8c6722894cd4ef7e44))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([21c74c6](https://github.com/Twigpine/node/commit/21c74c65d985200221489fa342d7419e8626362f))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([fd78cfa](https://github.com/Twigpine/node/commit/fd78cfa3ad0e7997b284371a55b7fb52753236d1))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([3cc15cf](https://github.com/Twigpine/node/commit/3cc15cf7247396ab1efcd279d3dd51dd8deaf014))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([16cc3b3](https://github.com/Twigpine/node/commit/16cc3b37e8268d048f3145ab16978dae297df5d4))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([3f41df5](https://github.com/Twigpine/node/commit/3f41df5868838544876473c2560c3d6be20e679c))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([b0e5cc0](https://github.com/Twigpine/node/commit/b0e5cc0ee0e91ebe35689bb1e073fa7e48ab37ee))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([12bc759](https://github.com/Twigpine/node/commit/12bc759ea6b20ab97c9dfeb4e00d7c6a6ca4fcfe))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([10e3492](https://github.com/Twigpine/node/commit/10e34928254205fafa8e96513a3df7899bfb10b1))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([c10f2ca](https://github.com/Twigpine/node/commit/c10f2ca255d63331f6acf3a29629e2a1c11ff355))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([3add535](https://github.com/Twigpine/node/commit/3add5356e36f0c2f89a0617fcb8018209bf722ff))
|
||||
* **gl:** only report registered: false on 404 in whoami ([#220](https://github.com/Twigpine/node/issues/220)) ([fdd1103](https://github.com/Twigpine/node/commit/fdd11030dc55a68142441ecf05f0bf33a8d38695))
|
||||
* **gl:** pass the mirror temp path to git as an OS string ([#434](https://github.com/Twigpine/node/issues/434)) ([df87b15](https://github.com/Twigpine/node/commit/df87b150fdb00e4b70e359996a41b2eebf7bb426))
|
||||
* **gl:** read whoami error bodies through CappedBody.text ([bfc44f9](https://github.com/Twigpine/node/commit/bfc44f926d08c0bf774e2c05dd76b245871294f1))
|
||||
* **gl:** read whoami error bodies through CappedBody.text ([4725146](https://github.com/Twigpine/node/commit/4725146db2c13cd3b8f998260d9df3a4b5f70c9e))
|
||||
* **gl:** report why the node-DID comparison was skipped in cert show ([6b2c53b](https://github.com/Twigpine/node/commit/6b2c53bbb86bcb35a54ef2edd2078e8f208263a6))
|
||||
* **gl:** require non-empty error message and use ephemeral port in whoami tests ([#220](https://github.com/Twigpine/node/issues/220)) ([a27a267](https://github.com/Twigpine/node/commit/a27a2678712cc512b316f143d8c053dbdf981a4b))
|
||||
* **gl:** sanitize full transport error chain in whoami, remove raw error attachment ([#220](https://github.com/Twigpine/node/issues/220)) ([39ce655](https://github.com/Twigpine/node/commit/39ce655904f516094cbbef6f2ee585906ef77e05))
|
||||
* **gl:** status-check the client read/write surfaces so a node denial surfaces as an error, not a fake result ([#123](https://github.com/Twigpine/node/issues/123)) ([#186](https://github.com/Twigpine/node/issues/186)) ([6b2c53b](https://github.com/Twigpine/node/commit/6b2c53bbb86bcb35a54ef2edd2078e8f208263a6))
|
||||
* **gl:** stop carrying request signatures to a host the node redirected us to ([de3f230](https://github.com/Twigpine/node/commit/de3f230940f21d88da48a972bddeb877420d2165))
|
||||
* **icaptcha-client:** parse GITLAWB_ICAPTCHA_INSECURE as truthy only ([#227](https://github.com/Twigpine/node/issues/227)) ([#533](https://github.com/Twigpine/node/issues/533)) ([77ac103](https://github.com/Twigpine/node/commit/77ac1037cbf893bf0e2e861753cc4bc78cc9053a))
|
||||
* **icaptcha:** return unsolved instead of blocking or overflowing ([#444](https://github.com/Twigpine/node/issues/444)) ([5479fd5](https://github.com/Twigpine/node/commit/5479fd59b848f13e7c0f0f1054b0d41cf50cbb73))
|
||||
* **infra:** serialize the upgrade and write compose through a unique temp path ([888fab6](https://github.com/Twigpine/node/commit/888fab602828dc8b514cfa5fbb4d027a3a2db019))
|
||||
* **ipfs:** page the legacy CID scan instead of materializing every repo ([4985e38](https://github.com/Twigpine/node/commit/4985e38af2bd629fa81ec70aec63937ed9894b73))
|
||||
* **node,infra,macos:** make the owner-push opt-out reach every launch path ([1f0d9ff](https://github.com/Twigpine/node/commit/1f0d9ff368c0169048aeec219de4114c2630dff6))
|
||||
* **node:** ANS-104 codec and recovery policy types ([#26](https://github.com/Twigpine/node/issues/26) split 2/4) ([#524](https://github.com/Twigpine/node/issues/524)) ([2c341f7](https://github.com/Twigpine/node/commit/2c341f71ac66c0011a09ff5864e8734fd0348c09))
|
||||
* **node:** authenticate gossip ref-update events before writing them ([#325](https://github.com/Twigpine/node/issues/325)) ([9bda2e1](https://github.com/Twigpine/node/commit/9bda2e103c9ae25a5a798343164b4fa02219735b))
|
||||
* **node:** bind a peer row to its DID so only its keyholder can repoint it ([#273](https://github.com/Twigpine/node/issues/273)) ([8d38043](https://github.com/Twigpine/node/commit/8d38043a4ca7d0df3c9a4c4bdbb171d7adcdec4f))
|
||||
* **node:** bound federated repository aggregation ([#546](https://github.com/Twigpine/node/issues/546)) ([0189990](https://github.com/Twigpine/node/commit/0189990ac9e72bed3c42bc589347eacec04be740))
|
||||
* **node:** bound GraphQL query cost ([#552](https://github.com/Twigpine/node/issues/552)) ([c805e35](https://github.com/Twigpine/node/commit/c805e35f40873a120c81bf00d9ddb50da956fd97))
|
||||
* **node:** bound Identify-derived Kademlia addresses ([#544](https://github.com/Twigpine/node/issues/544)) ([b33562f](https://github.com/Twigpine/node/commit/b33562f1a913cbc1b294f00577f4ab1f7ad67984))
|
||||
* **node:** bound legacy readiness fallback ([5af14c2](https://github.com/Twigpine/node/commit/5af14c203d07fdd2d0b5689fcb12e189237dbbb2))
|
||||
* **node:** bound peer failure tracking ([74f7554](https://github.com/Twigpine/node/commit/74f75548941712573d344aa058d162f40189b4df))
|
||||
* **node:** bound replay of authenticated gossip ref-update events ([#334](https://github.com/Twigpine/node/issues/334)) ([206e082](https://github.com/Twigpine/node/commit/206e0827ad6beb051cbb0fb5ef459a63a102c454))
|
||||
* **node:** bound the fruitless reads one sweep run will spend ([e4aaae8](https://github.com/Twigpine/node/commit/e4aaae8c5229355010ca710abf22c181210201c3))
|
||||
* **node:** bound the legacy CID scan and let the caller carry its position ([22f4db9](https://github.com/Twigpine/node/commit/22f4db94b2fb3b3c7c43c5bd34608ea77ce5d197))
|
||||
* **node:** bound the legacy scan's query by the remaining row budget ([21e6873](https://github.com/Twigpine/node/commit/21e687368336fd219d82308ee20b3d6bb018a3dc))
|
||||
* **node:** bound the legacy-repair read by the pin batch deadline ([ea2219b](https://github.com/Twigpine/node/commit/ea2219b2cb635da61f120f65434db4c427494f6c))
|
||||
* **node:** bound the pin loops' DB work by the batch deadline, both lanes ([9984e08](https://github.com/Twigpine/node/commit/9984e082121f3e8d25750dd54c0d60c85cef0ac7))
|
||||
* **node:** bound the pre-walk CID resolve on its own short budget ([0d7711c](https://github.com/Twigpine/node/commit/0d7711c08917a70f982391249439485ddce382b0))
|
||||
* **node:** bound the request body the signature middleware buffers before it verifies ([#262](https://github.com/Twigpine/node/issues/262)) ([288ad92](https://github.com/Twigpine/node/commit/288ad92fe83526a717fa1a6ac37b1f3cf1f97961))
|
||||
* **node:** bring the Pinata pin path back into lockstep with the Kubo one ([4681f54](https://github.com/Twigpine/node/commit/4681f54327b58b6ebdd569a1cec17a3c2643ad13))
|
||||
* **node:** budget provenance and fallback walks separately ([ae96ffa](https://github.com/Twigpine/node/commit/ae96ffa46706a6d088a412aa02dbf2f715ceaa37))
|
||||
* **node:** canonicalize and 404-on-no-match in remove_label ([#344](https://github.com/Twigpine/node/issues/344)) ([#530](https://github.com/Twigpine/node/issues/530)) ([8c9e4ad](https://github.com/Twigpine/node/commit/8c9e4adc2d5ae3560c1bd3ba76c1d0ddb4de2af6))
|
||||
* **node:** carry discovery onto the per-(oid, repo) incompleteness marker ([bd0bef1](https://github.com/Twigpine/node/commit/bd0bef1476f90e99d9a697e2520c32b954f3ba6f))
|
||||
* **node:** charge discovery's probes against the per-run read budget ([bc20236](https://github.com/Twigpine/node/commit/bc202368e13202504fe77534273b508f7559a84a))
|
||||
* **node:** clamp every admission-held DB await in the CID resolver ([bad82b3](https://github.com/Twigpine/node/commit/bad82b3cd9fa970ebf67817395bfbd98591879b1))
|
||||
* **node:** close review findings on the owner-push default ([2f0174c](https://github.com/Twigpine/node/commit/2f0174cc041fb6e9eb3c904172b37b5b9a6c094b))
|
||||
* **node:** close three host-class gaps in the public-URL gate ([#346](https://github.com/Twigpine/node/issues/346)) ([76ca04f](https://github.com/Twigpine/node/commit/76ca04f3552aa8c17305fca73fa1c3469a29903c))
|
||||
* **node:** count a completed fetch once per fetch, not per stateless-RPC POST ([1c690c1](https://github.com/Twigpine/node/commit/1c690c125c16ad2ed38a5885d0e16b96789b715e))
|
||||
* **node:** count fetch completion from the response outcome, not the request ([5a5d4e1](https://github.com/Twigpine/node/commit/5a5d4e1b43a5b37fcc57731ec504b221a58931f1))
|
||||
* **node:** drop withheld-subtree trees from the replication pin set ([#382](https://github.com/Twigpine/node/issues/382)) ([19a7ce2](https://github.com/Twigpine/node/commit/19a7ce2bbdad9dd96bdc35ed6230d14f772a5969))
|
||||
* **node:** enforce owner-only push by default ([cdbda19](https://github.com/Twigpine/node/commit/cdbda19c29db576d2ea37ae74578c899b4eb3bb9))
|
||||
* **node:** Escape LIKE metacharacters in certificate prefix search ([eeafa1f](https://github.com/Twigpine/node/commit/eeafa1fa5350fb2d15ba30ac6cd6ad8247b4b7ec))
|
||||
* **node:** Escape LIKE wildcards in certificate prefix search ([96d8123](https://github.com/Twigpine/node/commit/96d8123e0f84e85a7b0234ad84f5e603a5a303aa))
|
||||
* **node:** fail pin_git_object when the add response carries no Hash ([#528](https://github.com/Twigpine/node/issues/528)) ([47c6e6c](https://github.com/Twigpine/node/commit/47c6e6ce2200dd196cb531bc6a6ed946cf587409))
|
||||
* **node:** fence a repo publish on the write attempt that owns it ([#285](https://github.com/Twigpine/node/issues/285)) ([ed76adf](https://github.com/Twigpine/node/commit/ed76adfe29d793229fbc63eeb86d24cac5d23d13))
|
||||
* **node:** gate /ipfs/pins and /arweave/anchors behind authentication ([#121](https://github.com/Twigpine/node/issues/121)) ([#543](https://github.com/Twigpine/node/issues/543)) ([d3845ce](https://github.com/Twigpine/node/commit/d3845ced69597b3e73e3c8cb5f452f6367897e5b))
|
||||
* **node:** gate bounty mutations on repo read before status checks ([#529](https://github.com/Twigpine/node/issues/529)) ([8eedb93](https://github.com/Twigpine/node/commit/8eedb935c3525a91ac311e273c3f22d3b4eb4615))
|
||||
* **node:** gate GET /ipfs/{cid} tree objects so a withheld subtree's structure can't leak ([#135](https://github.com/Twigpine/node/issues/135)) ([21f8cb6](https://github.com/Twigpine/node/commit/21f8cb61350b2355edd2b2ed527d9fb9c4305bd9))
|
||||
* **node:** gate replica register/unregister on repo read visibility ([#445](https://github.com/Twigpine/node/issues/445)) ([0303222](https://github.com/Twigpine/node/commit/0303222eae486c6d519be1441d4b3b11115a05ab))
|
||||
* **node:** gate two Unix-only tests so the crate compiles on Windows ([5a7a77b](https://github.com/Twigpine/node/commit/5a7a77b8dc1723cde44b0439327e517e23a048ab)), closes [#228](https://github.com/Twigpine/node/issues/228)
|
||||
* **node:** give each discovery row its own slice of the pass budget ([22560b0](https://github.com/Twigpine/node/commit/22560b0872bd16dd66100681b1050faa677fc568))
|
||||
* **node:** harden peer readiness state ([6bd8f41](https://github.com/Twigpine/node/commit/6bd8f4121235ec6c4b7062aadcf3a631f174510c))
|
||||
* **node:** hold fork to the same repo-name rules as every other creation route ([#412](https://github.com/Twigpine/node/issues/412)) ([fc87586](https://github.com/Twigpine/node/commit/fc8758641147ca5f38561fc71b13b1e41a78a5ed))
|
||||
* **node:** honor pre-assigned task assignee on claim ([#550](https://github.com/Twigpine/node/issues/550)) ([a4026e8](https://github.com/Twigpine/node/commit/a4026e84ffe82f48b41817c8ba687fbc1aac8f9b))
|
||||
* **node:** make metrics::init race-safe with Once ([c45ec96](https://github.com/Twigpine/node/commit/c45ec9605d55171f7b8f1b0b542478097ddf43a3))
|
||||
* **node:** make the pin-source incompleteness marker per (object, repo) ([5575da4](https://github.com/Twigpine/node/commit/5575da4b65ff19da78a6b218da07f854706a811c))
|
||||
* **node:** map ipfs/arweave DB outages to 503 via bare ? ([#251](https://github.com/Twigpine/node/issues/251)) ([0e2328b](https://github.com/Twigpine/node/commit/0e2328bd8044ce6e8923cc6bd42219068d3f6b9d))
|
||||
* **node:** map ipfs/arweave DB outages to 503 via bare ? ([#251](https://github.com/Twigpine/node/issues/251)) ([c29a91a](https://github.com/Twigpine/node/commit/c29a91af6b7eb444e202f4724e3f677d2ef25466))
|
||||
* **node:** mint a continuation when a ceiling stops the /ipfs scan mid-page ([69cfbd4](https://github.com/Twigpine/node/commit/69cfbd4b3ccde243ff669392820f0fce86381663))
|
||||
* **node:** never hand back a continuation that made no progress ([76f6300](https://github.com/Twigpine/node/commit/76f630008f0088c952755b643126affdf962d12b))
|
||||
* **node:** opaque AppError::Internal and AppError::Db HTTP bodies ([#226](https://github.com/Twigpine/node/issues/226)) ([241b366](https://github.com/Twigpine/node/commit/241b36633bca7e0ead33bf670b7c1531c3bd9ab5))
|
||||
* **node:** opaque AppError::Internal and AppError::Db HTTP bodies ([#226](https://github.com/Twigpine/node/issues/226)) ([d192028](https://github.com/Twigpine/node/commit/d192028ee1487a3638c545d6a39e58a4575df1f1))
|
||||
* **node:** opaque GraphQL DB error messages ([#250](https://github.com/Twigpine/node/issues/250)) ([c10ccf1](https://github.com/Twigpine/node/commit/c10ccf1f059eae18fcb0b7058a35bb134838b790))
|
||||
* **node:** order the CID candidate list so it cannot depend on heap order ([366b599](https://github.com/Twigpine/node/commit/366b59933112b345113501a65f0f30e76518ff61))
|
||||
* **node:** owner-gate create_task repo_id against hosted repos ([#541](https://github.com/Twigpine/node/issues/541)) ([bac49f1](https://github.com/Twigpine/node/commit/bac49f150a2b99d7b14fc9d53e231b7e743a753c))
|
||||
* **node:** persist the libp2p identity instead of deriving it from the node DID ([#324](https://github.com/Twigpine/node/issues/324)) ([c301a68](https://github.com/Twigpine/node/commit/c301a681619e890a081c385d7cbab5b8a8d4efbb))
|
||||
* **node:** port discovery's candidate load onto the paged repo query ([4c665fb](https://github.com/Twigpine/node/commit/4c665fbca8641f7dfe6770d1ee5384a0af3d215c))
|
||||
* **node:** preserve legacy peer compatibility ([547f9ae](https://github.com/Twigpine/node/commit/547f9aed10706bc617d0e1e2e5346cf52d19a901))
|
||||
* **node:** reconcile public-read messaging with per-repo enforcement ([#439](https://github.com/Twigpine/node/issues/439)) ([0366f18](https://github.com/Twigpine/node/commit/0366f18458dd996ea18057ce60abf88673e16ed4))
|
||||
* **node:** record a discovered source and its marker in one commit ([9babb5e](https://github.com/Twigpine/node/commit/9babb5ece053608c522f49b4528de23d5b61b749))
|
||||
* **node:** reject revision syntax in issue ids and drop service passthrough ([#521](https://github.com/Twigpine/node/issues/521)) ([421f03a](https://github.com/Twigpine/node/commit/421f03ac46592c57bc0df5a8fa79061c74d32fe6))
|
||||
* **node:** repair source-less legacy pins by bounded additive discovery ([d88c0c7](https://github.com/Twigpine/node/commit/d88c0c726c8630e104e0161366d1815d69e96428))
|
||||
* **node:** require Content-Digest on a signed request ([#306](https://github.com/Twigpine/node/issues/306)) ([189aad9](https://github.com/Twigpine/node/commit/189aad96e5c831f94cef654048d2d9797a5f574d))
|
||||
* **node:** resolve issue ids from git refnames, not request input ([#526](https://github.com/Twigpine/node/issues/526)) ([3063719](https://github.com/Twigpine/node/commit/30637193a626da800984363b6192fc50131b9741))
|
||||
* **node:** resume the /ipfs scan per candidate so a starved one is not skipped ([d0635d9](https://github.com/Twigpine/node/commit/d0635d95b7d601490474419c6bdb99b0ce402e71))
|
||||
* **node:** rewind the pin repair sweep cursor on every completed walk ([1b44b12](https://github.com/Twigpine/node/commit/1b44b12b468c265f946390a57cd815d67d205166))
|
||||
* **node:** rotate discovery candidates across traversals ([4fdfa1c](https://github.com/Twigpine/node/commit/4fdfa1cedb3dcb6d7d6cc4004e7277a9fa95de94))
|
||||
* **node:** scope bounty aggregates to anonymously-listable repos ([#477](https://github.com/Twigpine/node/issues/477)) ([#527](https://github.com/Twigpine/node/issues/527)) ([317a155](https://github.com/Twigpine/node/commit/317a1550c2810932118429b9987ea437a1465cf5))
|
||||
* **node:** scope the refs listing by the canonical repo slug ([#388](https://github.com/Twigpine/node/issues/388)) ([131bb95](https://github.com/Twigpine/node/commit/131bb95c686698d0f6a90dabd3976509df86b595))
|
||||
* **node:** size the ipfs work floor for provenance walks plus one full search ([dc5daa1](https://github.com/Twigpine/node/commit/dc5daa14b4d0816d8a14fabdf057259c1d177a46))
|
||||
* **node:** stop reporting a Kubo pin whose DB record never landed ([f839fb9](https://github.com/Twigpine/node/commit/f839fb924653f1b012c2b34d51260ea3faba7f62))
|
||||
* **node:** stop the /ipfs size probe reporting a fault as a missing object ([ed6355e](https://github.com/Twigpine/node/commit/ed6355ed2c42bed09dec35d46904805e97de806c))
|
||||
* **node:** use readiness for peer liveness ([225644a](https://github.com/Twigpine/node/commit/225644a3ea0302ae91959016928df1040ddd9cb5))
|
||||
* **node:** use readiness for peer liveness ([1a841a9](https://github.com/Twigpine/node/commit/1a841a99e2d40129a33f1898d3ce28d05eb04632))
|
||||
* **node:** validate git branch refs to close option injection ([#379](https://github.com/Twigpine/node/issues/379)) ([6233bd9](https://github.com/Twigpine/node/commit/6233bd9d850b60fdd2fb05afaa3d996d9f37f59d))
|
||||
* **node:** validate ref-update SHAs are hex, not just length 40 ([#433](https://github.com/Twigpine/node/issues/433)) ([911be4d](https://github.com/Twigpine/node/commit/911be4d9fef309e56117440d21e5dad7718be666))
|
||||
* **node:** version ref_certificates for forward compat ([#26](https://github.com/Twigpine/node/issues/26) split 3/4) ([#548](https://github.com/Twigpine/node/issues/548)) ([38bab41](https://github.com/Twigpine/node/commit/38bab4191baa5e8778f3412dc1f013d1f654bb15))
|
||||
* **release:** bump icaptcha-client with the rest of the workspace ([6668525](https://github.com/Twigpine/node/commit/6668525f41936ed2e1f8a1334b0dd17eaea866f0))
|
||||
* **repo_store:** use SHA-256 for stable advisory-lock key ([#210](https://github.com/Twigpine/node/issues/210)) ([c380f9c](https://github.com/Twigpine/node/commit/c380f9cee5139a2cab6fc52000d43844b86bb143))
|
||||
* **repo_store:** use SHA-256 for stable advisory-lock key ([#210](https://github.com/Twigpine/node/issues/210)) ([89e10d0](https://github.com/Twigpine/node/commit/89e10d0ff12dcccae3bd4490548d906f77d76636))
|
||||
* **review:** assert the read-timeout postcondition and drop the socket clone ([4d9bd5a](https://github.com/Twigpine/node/commit/4d9bd5a18a0692baa67f94aac8e8663d8e69bdac))
|
||||
* **review:** bound the probe's channel waits and stop overstating the handshake ([d4e5ecf](https://github.com/Twigpine/node/commit/d4e5ecf299afaabf05eee22db462b9314b5a6998))
|
||||
* **review:** bound token key, rule bytes, and the discovery load ([e6cfb58](https://github.com/Twigpine/node/commit/e6cfb588c2a1600d59f2af88471d248a99532f03))
|
||||
* **review:** keep the resume token on every terminal that still holds one ([8c39cfd](https://github.com/Twigpine/node/commit/8c39cfdcb347ca824cbec7d6b56720df9517a472))
|
||||
* **review:** make the coupled sites findable and pin two more properties ([a7e8e35](https://github.com/Twigpine/node/commit/a7e8e35030cae4e1126cda6c161bc516e3b8ffff))
|
||||
* **review:** make the LIKE escape independent of the SQL parser mode ([1d3987b](https://github.com/Twigpine/node/commit/1d3987bba6619a64a2cef15023224cbaa6cc8d1b)), closes [#319](https://github.com/Twigpine/node/issues/319)
|
||||
* **review:** mint a continuation at every ceiling and widen the token ([342dd48](https://github.com/Twigpine/node/commit/342dd48d2426a8870423cd537781b52d03e8f175))
|
||||
* **test:** match SHA-256 advisory-lock key in receive-pack deadline test ([c68e1b0](https://github.com/Twigpine/node/commit/c68e1b07f8db752cff786bdc9c226b49889a40b1))
|
||||
* **whoami:** update registered status handling on 404 response ([75b0df8](https://github.com/Twigpine/node/commit/75b0df8f1c7bda6a02444ce17e11088b839a51b6))
|
||||
|
||||
## [0.7.1](https://github.com/Gitlawb/node/compare/v0.7.0...v0.7.1) (2026-08-03)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ time once updated.
|
||||
|
||||
**Requirements:**
|
||||
- Rust stable (≥ 1.91) — install via [rustup](https://rustup.rs)
|
||||
- PostgreSQL — required for the node. Use the bundled `docker-compose.yml` for local dev.
|
||||
- PostgreSQL 16+ — required for the node (it uses `pg_input_is_valid`, which exists only on PostgreSQL 16 and later). Use the bundled `docker-compose.yml` for local dev.
|
||||
- Docker (optional, for full-stack local testing)
|
||||
|
||||
**Environment variables:**
|
||||
|
||||
Generated
+6
-6
@@ -3470,7 +3470,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "git-remote-gitlawb"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
@@ -3485,7 +3485,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-attest"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"ed25519-dalek 2.2.0",
|
||||
@@ -3502,7 +3502,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-core"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
@@ -3530,7 +3530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-node"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
@@ -3589,7 +3589,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gl"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
@@ -4056,7 +4056,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "icaptcha-client"
|
||||
version = "0.4.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
|
||||
@@ -53,6 +53,7 @@ Good today:
|
||||
|
||||
- Local or Docker node startup.
|
||||
- Postgres-backed repo metadata.
|
||||
- Bounded GraphQL queries with [repository pagination](docs/graphql-pagination.md).
|
||||
- Bare git repository storage.
|
||||
- Git smart-HTTP clone/fetch/push.
|
||||
- RFC 9421-signed writes.
|
||||
@@ -69,7 +70,7 @@ Known limitations:
|
||||
- Repository write authorization is secure by default: `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `true`, so a valid HTTP Signature identifies a pusher and the node additionally requires that pusher to be the repository owner. Set `GITLAWB_ENFORCE_OWNER_PUSH=false` only for the duration of a rolling upgrade whose pushers are not yet the repo owner. Authentication is not authorization on its own (anyone can mint a `did:key` and sign), so owner enforcement is the only thing that prevents every signed caller from pushing to every repository, private ones included.
|
||||
- UCAN proof chains are validated when supplied, but UCAN capabilities are not consulted by write authorization and the root issuer is not independently trust-anchored. UCANs therefore do not yet grant scoped collaborator access.
|
||||
- Agent lifecycle revocation is not enforced by HTTP Signature authorization; do not rely on removing or revoking an agent record to block a compromised signer.
|
||||
- Task list/get reads (REST and GraphQL) are repository/task-gated and omit `ucan_token`. Read visibility is not a blanket data-classification boundary: IPFS-pin and Arweave-anchor listings are not repository-gated; withheld path names can be visible to a root reader; and later visibility changes cannot retract content already announced or externally anchored.
|
||||
- Read visibility is not a blanket data-classification boundary: task, IPFS-pin, and Arweave-anchor listings are not repository-gated; withheld path names can be visible to a root reader; and later visibility changes cannot retract content already announced or externally anchored.
|
||||
- Peer writes are signed by upgraded nodes, but strict signed-peer enforcement is opt-in during rolling upgrades.
|
||||
- GraphQL mutations require a signed identity (a verified signer bound to the acting DID), are limited to the agent-task queue, and are covered by a CI completeness fence that requires signer acquisition and actor binding on every registered mutation; repo writes are not exposed over GraphQL and remain REST-only.
|
||||
- Pull-request review comments do not yet have threaded line-level anchors, and merges do not enforce approval requirements.
|
||||
@@ -420,7 +421,6 @@ Important node settings:
|
||||
| `GITLAWB_IPFS_REQUEST_BUDGET_SECS` | Absolute wall-clock budget for one admitted `/ipfs/{cid}` request's acquire+walk lifetime. Per-stage clamps bound the acquire and walk stages to the remaining budget, and no stage starts once it is exhausted; the scan then stops with a retryable 503. The object-type probe and content-read `cat-file` subprocesses are budget-checked before starting and each also run under their own deadline (the lesser of `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), reaped via process-group teardown, so a hung `cat-file` cannot hold the request's walk slot past it. One hang path is still unbounded: the probe's object-store readability check is a plain filesystem sweep with nothing to reap, so a wedged filesystem can hold the slot past the deadline. Default 600. Accepted range is 1 to 3153600000 (100 years), since the node derives a deadline from this value and a larger one cannot be represented. |
|
||||
| `GITLAWB_IPFS_RESOLVE_BUDGET_SECS` | Shorter budget for the pre-walk CID resolve inside an admitted `/ipfs/{cid}` request: the lookup that maps the requested CID to its git oid(s), which runs while the scarce walk admission is already held. A well-formed CID with no pin row does no probe and no walk work, so without this it could hold a walk slot for the whole request budget while nothing walked, and enough such requests shed every real retrieval at admission. The effective deadline is the lesser of this and the remaining request budget, so a value above `GITLAWB_IPFS_REQUEST_BUDGET_SECS` degrades to the request budget. Only the resolve is on this clock; walk and probe work stay on the request budget, so a slow but progressing scan is never shed by it. Default 10. Accepted range is 1 to 3153600000 (100 years). |
|
||||
| `GITLAWB_IPFS_RATE_LIMIT` | Max `/ipfs/{cid}` requests per client IP per hour (route flood brake). 0 disables. Default 600. |
|
||||
| `GITLAWB_TASK_READ_RATE_LIMIT` | Max anonymous task-read requests (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`) per client IP per hour, sharing the budget with the GraphQL/WS task-read brake. Uses `GITLAWB_TRUSTED_PROXY` to resolve the client IP. 0 disables. Default 1200 (above the `/ipfs` budget to allow list pages followed by per-task reads). |
|
||||
| `GITLAWB_TIGRIS_BUCKET` | Optional S3/Tigris shared repo storage bucket. |
|
||||
| `GITLAWB_PINATA_JWT` | Optional Pinata/IPFS warm-storage pinning. |
|
||||
| `GITLAWB_IRYS_URL` | Optional Irys/Arweave permanent anchoring. |
|
||||
|
||||
+9
-9
@@ -26,7 +26,7 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 14 d
|
||||
|
||||
**Content addressing**
|
||||
- Every git object is content-addressed via CIDv1 (SHA-256)
|
||||
- Tamper-evident by construction: a modified object changes its CID
|
||||
- Tamper-evident by construction — a modified object changes its CID
|
||||
|
||||
**UCAN token validation**
|
||||
- Bootstrap UCAN tokens are issued at registration.
|
||||
@@ -35,8 +35,8 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 14 d
|
||||
- Capability grants are not yet consulted by repository write authorization; see the limitations below.
|
||||
|
||||
**Smart contracts (Base Sepolia testnet)**
|
||||
- `GitlawbDIDRegistry`: on-chain DID → document registry
|
||||
- `GitlawbNameRegistry`: human name → DID registry
|
||||
- `GitlawbDIDRegistry` — on-chain DID → document registry
|
||||
- `GitlawbNameRegistry` — human name → DID registry
|
||||
- Both auditable on-chain, no admin keys
|
||||
|
||||
---
|
||||
@@ -55,7 +55,7 @@ These are documented limitations of the current live release. They should be pri
|
||||
|
||||
### Repository write authorization defaults
|
||||
- `git-receive-pack` verifies HTTP Signatures and, with the default configuration, also requires the pusher DID to be the repository owner: `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `true`.
|
||||
- **Impact:** With the default setting, a valid signature authenticates the pusher, and the pusher must be the repository owner. Authentication is not authorization on its own, since anyone can mint a `did:key` and sign, so owner enforcement is the only thing that prevents every signed caller from pushing to every repository, including private ones.
|
||||
- **Impact:** With the default setting, a valid signature authenticates the pusher *and* the pusher must be the repository owner. Authentication is not authorization on its own — anyone can mint a `did:key` and sign — so owner enforcement is the only thing that prevents every signed caller from pushing to every repository, including private ones.
|
||||
- **Mitigation:** `GITLAWB_ENFORCE_OWNER_PUSH=false` is the explicit rolling-upgrade compatibility override. Disable it only for the duration of an upgrade whose pushers are not yet the repo owner, then turn it back on. Delegated and CI keys count as non-owners: a UCAN `git/push` capability is verified but not yet honored for authorization, so they cannot push while this is on.
|
||||
|
||||
### UCAN delegation and revocation
|
||||
@@ -73,7 +73,7 @@ These are documented limitations of the current live release. They should be pri
|
||||
### Private repository reads
|
||||
- Repository and path-scoped visibility checks are enforced for repository API and Git content reads. A denied whole-repository or root read returns the same 404 shape as a missing repository, so the denial does not reveal private-repository existence.
|
||||
- Sparse-clone support exposes withheld path globs to callers who may read the repository root. Do not put sensitive information in withheld path names.
|
||||
- Task list/get reads (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`, and GraphQL `tasks` / `task` over HTTP and WebSocket) are repository/task-gated through shared visibility collectors and omit `ucan_token`. All of those transports share the same per-IP `GITLAWB_TASK_READ_RATE_LIMIT` budget. `/api/v1/ipfs/pins` and `/api/v1/arweave/anchors` are not repository-gated; pin and anchor listings expose object and ref metadata.
|
||||
- `GET /api/v1/tasks`, `/api/v1/ipfs/pins`, and `/api/v1/arweave/anchors` are not repository-gated. Task records include a UCAN token; pin and anchor listings expose object and ref metadata.
|
||||
- Changing a repository's visibility controls future serving, but cannot retract ref metadata or configured external pins and anchors already announced while the repository was public. Do not push secrets to an announceable repository.
|
||||
- **Impact:** Visibility policies protect the repository and Git content routes they gate, not every metadata endpoint or previously published content.
|
||||
- **Remaining boundary:** This read control does not address the independent write-authorization and UCAN-delegation limitations described above.
|
||||
@@ -119,10 +119,10 @@ These are documented limitations of the current live release. They should be pri
|
||||
## Threat Model
|
||||
|
||||
Twigpine is designed to be secure against:
|
||||
- **Unauthenticated writes:** HTTP Signature auth on protected write endpoints; see Known Limitations for owner and capability authorization gaps
|
||||
- **Tampered git objects:** CIDv1 content addressing detects modification
|
||||
- **Identity spoofing:** DIDs derived from public keys, unforgeable without the private key
|
||||
- **Centralized takedown:** no single point of control; data on IPFS + Arweave
|
||||
- **Unauthenticated writes** — HTTP Signature auth on protected write endpoints; see Known Limitations for owner and capability authorization gaps
|
||||
- **Tampered git objects** — CIDv1 content addressing detects modification
|
||||
- **Identity spoofing** — DIDs derived from public keys, unforgeable without the private key
|
||||
- **Centralized takedown** — no single point of control; data on IPFS + Arweave
|
||||
|
||||
Twigpine is **not yet** designed to defend against:
|
||||
- A compromised node operator (node operators are trusted for their own node)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "git-remote-gitlawb"
|
||||
description = "Git remote helper — enables 'git clone gitlawb://did:gitlawb:...'"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-attest"
|
||||
description = "External Attestation v1: pluggable provenance attachments for Twigpine ref-update certs"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-core"
|
||||
description = "Core cryptographic primitives for the Twigpine network: DIDs, CIDs, UCAN, HTTP Signatures, ref-update certificates"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-node"
|
||||
description = "The Twigpine node daemon — git hosting over HTTP with DID auth"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -11,7 +11,8 @@ use crate::state::AppState;
|
||||
|
||||
/// Hard ceiling on rows any ref-update feed returns in one request. Shared by the
|
||||
/// shared collector's clamp and the per-handler request caps so they can't drift.
|
||||
const MAX_VISIBLE_REF_UPDATES: i64 = 200;
|
||||
/// `pub(crate)` so the GraphQL complexity meter can price against the same bound.
|
||||
pub(crate) const MAX_VISIBLE_REF_UPDATES: i64 = 200;
|
||||
|
||||
/// Collect up to `limit` ref-update rows visible to `caller`, newest first,
|
||||
/// paging past rows the feed gate drops. Filtering after a plain SQL `LIMIT`
|
||||
|
||||
@@ -8367,6 +8367,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn get_by_cid_per_source_cap_sheds_same_source_admits_other() {
|
||||
let mut state = crate::test_support::test_state_lazy();
|
||||
state.db.pool().close().await;
|
||||
// Global pool has room; the per-source cap is 1.
|
||||
state.git_ipfs_walk_semaphore = Arc::new(Semaphore::new(8));
|
||||
state.git_ipfs_walk_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 100);
|
||||
@@ -8393,16 +8394,23 @@ mod tests {
|
||||
"a source at its per-source /ipfs walk cap must shed 503 with global capacity free"
|
||||
);
|
||||
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(body["error"], "overloaded");
|
||||
|
||||
// A DIFFERENT source is NOT shed by the per-source cap: it clears admission and
|
||||
// proceeds (then errors on the lazy DB, which is not a 503).
|
||||
// proceeds to the closed DB, which has a distinct db_unavailable error code.
|
||||
let resp = ipfs_router(state)
|
||||
.oneshot(get_cid(&cid, Some(other)))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(
|
||||
resp.status(),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"a different source must not be shed by the per-source cap"
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
body["error"],
|
||||
crate::error::DB_UNAVAILABLE_CODE,
|
||||
"a different source must clear admission and reach the closed database"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ pub mod replicas;
|
||||
pub mod repos;
|
||||
pub mod resolve;
|
||||
pub mod stars;
|
||||
pub mod task_cursor;
|
||||
pub mod tasks;
|
||||
pub mod visibility;
|
||||
pub mod webhooks;
|
||||
|
||||
@@ -247,6 +247,40 @@ 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).
|
||||
///
|
||||
/// This is the API-side validator, and it deliberately differs from the
|
||||
/// stricter disk-side `validate_repo_name` in `git/repo_store.rs`: this one
|
||||
/// admits names the store rejects (empty, leading `-`, non-ASCII
|
||||
/// alphanumeric) and rejects `.`, which the store allows. The divergence
|
||||
/// predates this bound (#412 owns the fork half), so a store-rejected name
|
||||
/// still fails later at `repo_store.init` after the proof is spent. Do not
|
||||
/// "fix" the divergence here; the length bound below is the one that keeps
|
||||
/// emitted cursors parseable, and it is shared via `MAX_REPO_NAME_LEN` so the
|
||||
/// two validators cannot drift apart on length.
|
||||
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(
|
||||
@@ -261,16 +295,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
|
||||
@@ -3774,15 +3799,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`
|
||||
@@ -5049,6 +5066,50 @@ mod tests {
|
||||
peer_mock.assert_async().await;
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_repo_rejects_overlong_name_through_handler() {
|
||||
// Pins the wiring: `create_repo` must call `validate_repo_name`
|
||||
// before any database access. The lazy state never connects, so
|
||||
// deleting the call site would let the handler proceed to `get_repo`
|
||||
// and fail with a connection error instead of BadRequest.
|
||||
let state = crate::test_support::test_state_lazy();
|
||||
let overlong = "a".repeat(crate::db::MAX_REPO_NAME_LEN + 1);
|
||||
let err = create_repo(
|
||||
State(state),
|
||||
Extension(AuthenticatedDid(OWNER_DID.to_owned())),
|
||||
axum::http::HeaderMap::new(),
|
||||
Json(CreateRepoRequest {
|
||||
name: overlong,
|
||||
description: None,
|
||||
is_public: true,
|
||||
default_branch: "main".into(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, AppError::BadRequest(ref msg) if msg.contains("at most")),
|
||||
"overlong name through create_repo must be a 400, got: {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upload_pack_request_finalizes_only_with_done_pktline() {
|
||||
let want = "0032want 1111111111111111111111111111111111111111\n";
|
||||
@@ -9179,6 +9240,7 @@ mod tests {
|
||||
/// A pkt-line receive-pack body carrying one branch-create ref update, so the
|
||||
/// handler's post-receive tail resolves a non-empty new-tip set (the delta
|
||||
/// scan's git stages run).
|
||||
#[cfg(unix)]
|
||||
fn ref_update_body(new_sha: &str) -> axum::body::Bytes {
|
||||
let line = format!("{ZERO_SHA} {new_sha} refs/heads/main");
|
||||
axum::body::Bytes::from(format!("{:04x}{}0000", line.len() + 4, line))
|
||||
@@ -11636,6 +11698,7 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn f2a_log(log: &std::path::Path) -> String {
|
||||
std::fs::read_to_string(log).unwrap_or_default()
|
||||
}
|
||||
@@ -11643,6 +11706,7 @@ mod tests {
|
||||
/// Withheld-walk children run so far. `ls-tree` is the walk's signature child
|
||||
/// (`blob_paths` lists every reachable commit's tree); the delta scan and the
|
||||
/// full-scan fallback use `rev-list` / `cat-file` instead.
|
||||
#[cfg(unix)]
|
||||
fn f2a_walks(log: &std::path::Path) -> usize {
|
||||
f2a_log(log)
|
||||
.lines()
|
||||
@@ -11654,6 +11718,7 @@ mod tests {
|
||||
/// the withheld walk actually runs rather than taking the no-rule shortcut).
|
||||
/// The repo's on-disk path is passed to the tail directly, so no repo_store or
|
||||
/// receive-pack plumbing is involved.
|
||||
#[cfg(unix)]
|
||||
async fn f2a_state(
|
||||
pool: sqlx::PgPool,
|
||||
git_bin: &str,
|
||||
@@ -11685,6 +11750,7 @@ mod tests {
|
||||
(state, rec)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn f2a_update(ref_name: &str, new_sha: &str) -> Vec<RefUpdate> {
|
||||
vec![RefUpdate {
|
||||
old_sha: ZERO_SHA.to_string(),
|
||||
@@ -11693,6 +11759,7 @@ mod tests {
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const F2A_PUSHER: &str = "did:key:z6MkF2aPusherAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
|
||||
/// When publish durability is fenced, the tail must not run walks or take
|
||||
@@ -11805,6 +11872,7 @@ mod tests {
|
||||
}
|
||||
/// Poll `cond` until it holds, with a bound so a regression fails the test
|
||||
/// rather than hanging the suite.
|
||||
#[cfg(unix)]
|
||||
async fn f2a_wait_for(mut cond: impl FnMut() -> bool, what: &str) {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
while !cond() {
|
||||
@@ -11819,6 +11887,7 @@ mod tests {
|
||||
/// A `rev-list --objects` line names the tips a DELTA scan was asked to resolve,
|
||||
/// so it attributes that scan to one push's tips. The withheld walk's own
|
||||
/// `rev-list --all` / `ls-tree` lines never carry a tip as an argument this way.
|
||||
#[cfg(unix)]
|
||||
fn f2a_delta_scanned(log: &std::path::Path, tip: &str) -> bool {
|
||||
f2a_log(log)
|
||||
.lines()
|
||||
@@ -11967,6 +12036,7 @@ mod tests {
|
||||
|
||||
/// Mount a Pinata upload endpoint that assigns every object the same CID, and
|
||||
/// point the state at it. Returns the server (kept alive by the caller) and CID.
|
||||
#[cfg(unix)]
|
||||
async fn f2a_pinata(state: &mut AppState) -> (mockito::ServerGuard, String) {
|
||||
let cid = "bafyf2acoalescedmapping".to_string();
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
@@ -11986,6 +12056,7 @@ mod tests {
|
||||
|
||||
/// Poll the branch to CID table until the push's mapping lands (the Pinata
|
||||
/// worker is detached), bounded so a regression fails rather than hangs.
|
||||
#[cfg(unix)]
|
||||
async fn f2a_wait_for_branch_cid(
|
||||
db: &crate::db::Db,
|
||||
slug: &str,
|
||||
@@ -12005,6 +12076,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn f2a_slug(rec: &crate::db::RepoRecord) -> String {
|
||||
format!(
|
||||
"{}/{}",
|
||||
@@ -12139,6 +12211,7 @@ mod tests {
|
||||
// and `z6p2fail`), and owner-only push is on by default, so the identity has to
|
||||
// follow the repo each push targets rather than being fixed for both.
|
||||
|
||||
#[cfg(unix)]
|
||||
fn p2_push(
|
||||
state: &AppState,
|
||||
owner: &str,
|
||||
@@ -12157,6 +12230,7 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn p2_logged(log: &std::path::Path, prefix: &str) -> bool {
|
||||
f2a_log(log).lines().any(|l| l.starts_with(prefix))
|
||||
}
|
||||
@@ -13152,6 +13226,7 @@ exit 0
|
||||
/// runs exactly one `rev-list --all`, so this counts the walks that were attempted
|
||||
/// (the `ls-tree` counter above cannot: a walk whose enumeration fails never gets
|
||||
/// to `ls-tree`).
|
||||
#[cfg(unix)]
|
||||
fn f2b_walk_attempts(log: &std::path::Path) -> usize {
|
||||
f2a_log(log)
|
||||
.lines()
|
||||
|
||||
@@ -1,782 +0,0 @@
|
||||
//! Opaque, integrity-protected continuation tokens for the task read surfaces.
|
||||
//!
|
||||
//! The task list pages by keyset over `(created_at, id)`, but the rows a
|
||||
//! caller may *see* are a filtered subset of the rows the query has to
|
||||
//! *examine*. Handing the caller a raw `(created_at, id)` cursor therefore
|
||||
//! forced a choice between two broken options (#327 review): anchor the cursor
|
||||
//! on the last visible row, and a window of denied tasks longer than the scan
|
||||
//! budget stalls paging forever; or anchor it on the last examined row, and a
|
||||
//! denied read leaks the id and timestamp of a task `GET /tasks/{id}` other-
|
||||
//! wise 404s.
|
||||
//!
|
||||
//! A server-issued token removes the choice. The position it carries is the
|
||||
//! last *examined* candidate, so paging always advances, and the payload is
|
||||
//! opaque and MAC'd, so the caller learns nothing from it and cannot forge one
|
||||
//! naming a row of their choosing.
|
||||
//!
|
||||
//! The position must be *confidential*, not merely unforgeable: a token that
|
||||
//! merely signed a base64 payload would still let its holder read the id and
|
||||
//! timestamp of the denied row it names, which is the disclosure the token
|
||||
//! exists to prevent. The payload is therefore encrypted under a
|
||||
//! synthetic-IV construction (SIV): the tag is an HMAC over the filter and the
|
||||
//! plaintext, and it doubles as the IV seeding the keystream the plaintext is
|
||||
//! XORed with. That needs no randomness source and no dependency beyond the
|
||||
//! `hmac`/`sha2` pair already used for webhook signatures and blob recipient
|
||||
//! tags, and it is decrypt-last: nothing is parsed until the tag verifies.
|
||||
//!
|
||||
//! Making the token the *only* accepted cursor also fixes the ordering-domain
|
||||
//! bug the same review found. `agent_tasks.created_at` is TEXT and compared as
|
||||
//! TEXT, so `...Z` and `...+00:00` denote one instant but sort differently. A
|
||||
//! caller-typed timestamp could silently skip or repeat same-time rows. The
|
||||
//! token instead carries the stored string verbatim, so the value compared is
|
||||
//! always a value the server wrote.
|
||||
//!
|
||||
//! A token is bound to the *caller* as well as the filter. The position it
|
||||
//! names is the last examined candidate, not the last visible one, so it
|
||||
//! encodes how far a scan got under one caller's visibility. Resuming it as a
|
||||
//! different caller would start the scan past rows that caller is entitled to
|
||||
//! read, silently dropping them from the answer (#327 review). The presenting
|
||||
//! caller's normalized DID (empty and flagged absent when anonymous) is
|
||||
//! therefore part of the MAC input, so a token presented by anyone else fails
|
||||
//! to verify rather than under-reporting.
|
||||
//!
|
||||
//! Wire form: `v1.<iv>.<body>`, both parts base64url unpadded: the 16-byte
|
||||
//! synthetic IV (the truncated MAC, which also seeds the keystream) and the
|
||||
//! padded, encrypted JSON payload.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
const CURSOR_PREFIX: &str = "v1";
|
||||
const KEY_DERIVATION_LABEL: &[u8] = b"gitlawb/tasks-cursor-key/v1";
|
||||
const TAG_DOMAIN: &[u8] = b"gitlawb/tasks-cursor-tag/v1";
|
||||
const STREAM_DOMAIN: &[u8] = b"gitlawb/tasks-cursor-stream/v1";
|
||||
/// Truncated MAC length, and the synthetic IV width. 128 bits is far beyond
|
||||
/// forgery reach for a token that carries no authority of its own (every page
|
||||
/// re-runs the visibility gate against the presenting caller), and keeps the
|
||||
/// token short enough to sit in a query string.
|
||||
const TAG_LEN: usize = 16;
|
||||
|
||||
/// Padding bucket for the serialized cursor payload, in bytes. The keystream
|
||||
/// XORs the plaintext byte for byte, so token length would otherwise track
|
||||
/// payload length and leak the named row's field widths to a holder who
|
||||
/// cannot decrypt anything. 128 comfortably covers the widest realistic
|
||||
/// payload: a 35-char RFC3339 timestamp (`to_rfc3339()` renders 29 chars at
|
||||
/// millisecond precision and 32 at microsecond, 35 only with all nine
|
||||
/// fractional digits), a 36-char server-minted UUID, and the fixed JSON
|
||||
/// envelope plus a 10-digit expiry, which together total 101 bytes. Should a future payload ever exceed the bucket, the length
|
||||
/// rounds up to the next multiple instead of failing, so `encode` never
|
||||
/// breaks — it just mints a longer token.
|
||||
const PAYLOAD_BUCKET: usize = 128;
|
||||
|
||||
/// How long an issued cursor stays acceptable. Keyset positions never go stale
|
||||
/// on their own — `created_at`/`id` are immutable — so this is not a
|
||||
/// correctness bound. It bounds how long a token stays valid across a node
|
||||
/// restart-and-rotate and keeps an abandoned page from being resumed
|
||||
/// indefinitely.
|
||||
const CURSOR_TTL_SECS: i64 = 24 * 60 * 60;
|
||||
|
||||
/// Node-keyed MAC key for continuation tokens, derived from the node keypair
|
||||
/// seed so it needs no configuration and survives restarts of the same node.
|
||||
/// Derived rather than used directly so a token forgery oracle could not
|
||||
/// bear on the signing key itself.
|
||||
#[derive(Clone)]
|
||||
pub struct TaskCursorKey([u8; 32]);
|
||||
|
||||
impl std::fmt::Debug for TaskCursorKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("TaskCursorKey(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskCursorKey {
|
||||
pub fn derive(node_seed: &[u8; 32]) -> Self {
|
||||
let mut mac = HmacSha256::new_from_slice(node_seed).expect("HMAC accepts any key length");
|
||||
mac.update(KEY_DERIVATION_LABEL);
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&mac.finalize().into_bytes());
|
||||
Self(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyset position a token carries: the last candidate row the previous
|
||||
/// request examined, whether or not the caller was allowed to see it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TaskPosition {
|
||||
pub created_at: String,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
impl TaskPosition {
|
||||
pub fn new(created_at: impl Into<String>, id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
created_at: created_at.into(),
|
||||
id: id.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_pair(&self) -> (&str, &str) {
|
||||
(self.created_at.as_str(), self.id.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CursorPayload<'a> {
|
||||
/// `created_at` of the last examined candidate, verbatim as stored.
|
||||
t: &'a str,
|
||||
/// `id` of the last examined candidate.
|
||||
i: &'a str,
|
||||
/// Unix expiry.
|
||||
e: i64,
|
||||
}
|
||||
|
||||
/// The filter a page was issued under. A cursor is only meaningful against the
|
||||
/// same `status`/`assignee_did` filter that produced it: resuming a filtered
|
||||
/// scan from an unfiltered position (or the reverse) silently skips rows.
|
||||
/// Bound into the MAC rather than stored in the payload, so it costs no token
|
||||
/// length and cannot be edited without invalidating the tag.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TaskFilter<'a> {
|
||||
pub status: Option<&'a str>,
|
||||
pub assignee_did: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// The visibility identity a token was issued to. Normalized through
|
||||
/// `normalize_owner_key` so the two spellings of one `did:key` identity
|
||||
/// (`did:key:X` and bare `X`) bind identically, matching `did_matches` on the
|
||||
/// read path: a caller who authenticates with the other spelling of their own
|
||||
/// DID must be able to resume their own page.
|
||||
fn caller_binding(caller: Option<&str>) -> &str {
|
||||
caller.map(crate::db::normalize_owner_key).unwrap_or("")
|
||||
}
|
||||
|
||||
/// The assignee filter a token was issued under. Normalized through
|
||||
/// `normalize_owner_key` so the two spellings of one `did:key` identity
|
||||
/// (`did:key:X` and bare `X`) bind identically, matching `list_tasks_keyset`
|
||||
/// in SQL: minting under `did:key:X` and resuming with bare `X` (or the reverse)
|
||||
/// hits the same rows and must verify under the MAC.
|
||||
fn assignee_binding(assignee: Option<&str>) -> &str {
|
||||
assignee.map(crate::db::normalize_owner_key).unwrap_or("")
|
||||
}
|
||||
|
||||
fn cursor_mac(
|
||||
key: &TaskCursorKey,
|
||||
filter: TaskFilter<'_>,
|
||||
caller: Option<&str>,
|
||||
plaintext: &[u8],
|
||||
) -> HmacSha256 {
|
||||
let mut mac = HmacSha256::new_from_slice(&key.0).expect("HMAC accepts any key length");
|
||||
mac.update(TAG_DOMAIN);
|
||||
// Length-prefix every field so no two distinct filter/caller/plaintext
|
||||
// tuples can produce the same MAC input.
|
||||
for field in [
|
||||
filter.status.unwrap_or("").as_bytes(),
|
||||
assignee_binding(filter.assignee_did).as_bytes(),
|
||||
caller_binding(caller).as_bytes(),
|
||||
plaintext,
|
||||
] {
|
||||
mac.update(&(field.len() as u64).to_be_bytes());
|
||||
mac.update(field);
|
||||
}
|
||||
// Presence is distinct from emptiness for all three optional fields, so an
|
||||
// anonymous token cannot collide with one issued to a caller whose
|
||||
// normalized DID is the empty string.
|
||||
mac.update(&[
|
||||
u8::from(filter.status.is_some()),
|
||||
u8::from(filter.assignee_did.is_some()),
|
||||
u8::from(caller.is_some()),
|
||||
]);
|
||||
mac
|
||||
}
|
||||
|
||||
/// Synthetic IV: the authentication tag over the filter and plaintext, which
|
||||
/// also seeds the keystream. Deterministic by construction, so no randomness
|
||||
/// source is needed and two tokens for the same page are byte-identical.
|
||||
fn siv(
|
||||
key: &TaskCursorKey,
|
||||
filter: TaskFilter<'_>,
|
||||
caller: Option<&str>,
|
||||
plaintext: &[u8],
|
||||
) -> [u8; TAG_LEN] {
|
||||
let mut out = [0u8; TAG_LEN];
|
||||
out.copy_from_slice(
|
||||
&cursor_mac(key, filter, caller, plaintext)
|
||||
.finalize()
|
||||
.into_bytes()[..TAG_LEN],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// XOR `buf` with the keystream for `iv`. Its own inverse, so encrypt and
|
||||
/// decrypt are the same call.
|
||||
fn apply_keystream(key: &TaskCursorKey, iv: &[u8; TAG_LEN], buf: &mut [u8]) {
|
||||
for (block_index, chunk) in buf.chunks_mut(32).enumerate() {
|
||||
let mut mac = HmacSha256::new_from_slice(&key.0).expect("HMAC accepts any key length");
|
||||
mac.update(STREAM_DOMAIN);
|
||||
mac.update(iv);
|
||||
mac.update(&(block_index as u64).to_be_bytes());
|
||||
let block = mac.finalize().into_bytes();
|
||||
for (byte, k) in chunk.iter_mut().zip(block.iter()) {
|
||||
*byte ^= k;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint a token resuming at `position` for `filter`, usable only by `caller`.
|
||||
///
|
||||
/// The serialized payload is padded with trailing whitespace to a fixed
|
||||
/// bucket before the SIV tag is computed: the keystream preserves plaintext
|
||||
/// length, so an unpadded payload would let the token's length leak the
|
||||
/// named row's field widths (a 25-char `to_rfc3339()` rendering mints a
|
||||
/// shorter token than a 35-char one). `decode` tolerates the padding because
|
||||
/// `serde_json` ignores trailing whitespace, and the tag covers the padded
|
||||
/// bytes, so a token minted before padding landed still verifies.
|
||||
pub fn encode(
|
||||
key: &TaskCursorKey,
|
||||
filter: TaskFilter<'_>,
|
||||
caller: Option<&str>,
|
||||
position: &TaskPosition,
|
||||
) -> String {
|
||||
let mut payload = serde_json::to_vec(&CursorPayload {
|
||||
t: &position.created_at,
|
||||
i: &position.id,
|
||||
e: chrono::Utc::now().timestamp() + CURSOR_TTL_SECS,
|
||||
})
|
||||
.expect("cursor payload is plain strings and an integer");
|
||||
let padded_len = payload.len().next_multiple_of(PAYLOAD_BUCKET);
|
||||
payload.resize(padded_len, b' ');
|
||||
let iv = siv(key, filter, caller, &payload);
|
||||
apply_keystream(key, &iv, &mut payload);
|
||||
format!(
|
||||
"{CURSOR_PREFIX}.{}.{}",
|
||||
URL_SAFE_NO_PAD.encode(iv),
|
||||
URL_SAFE_NO_PAD.encode(&payload)
|
||||
)
|
||||
}
|
||||
|
||||
/// One rejection message for every way a token can fail to verify. A caller
|
||||
/// who mangled a token, replayed an expired one, or tried to move one to a
|
||||
/// different filter or a different presenting identity learns only that the
|
||||
/// cursor is not usable — never which of those it was, and never anything
|
||||
/// about the row it named.
|
||||
const INVALID_CURSOR: &str = "invalid or expired cursor";
|
||||
|
||||
fn reject() -> AppError {
|
||||
AppError::BadRequest(INVALID_CURSOR.into())
|
||||
}
|
||||
|
||||
/// Verify a token against `filter` and the presenting `caller`, and return the
|
||||
/// position it carries.
|
||||
pub fn decode(
|
||||
key: &TaskCursorKey,
|
||||
filter: TaskFilter<'_>,
|
||||
caller: Option<&str>,
|
||||
token: &str,
|
||||
) -> crate::error::Result<TaskPosition> {
|
||||
let mut parts = token.split('.');
|
||||
let (Some(version), Some(iv_b64), Some(body_b64), None) =
|
||||
(parts.next(), parts.next(), parts.next(), parts.next())
|
||||
else {
|
||||
return Err(reject());
|
||||
};
|
||||
if version != CURSOR_PREFIX {
|
||||
return Err(reject());
|
||||
}
|
||||
let iv_bytes = URL_SAFE_NO_PAD.decode(iv_b64).map_err(|_| reject())?;
|
||||
let mut plaintext = URL_SAFE_NO_PAD.decode(body_b64).map_err(|_| reject())?;
|
||||
let iv: [u8; TAG_LEN] = iv_bytes.try_into().map_err(|_| reject())?;
|
||||
|
||||
apply_keystream(key, &iv, &mut plaintext);
|
||||
// Authenticate before parsing: until the tag matches, `plaintext` is just
|
||||
// attacker-chosen bytes run through a keystream. `verify_truncated_left`
|
||||
// is the constant-time compare, so a forgery attempt cannot be steered by
|
||||
// timing the first differing byte.
|
||||
cursor_mac(key, filter, caller, &plaintext)
|
||||
.verify_truncated_left(&iv)
|
||||
.map_err(|_| reject())?;
|
||||
|
||||
let decoded: CursorPayload<'_> = serde_json::from_slice(&plaintext).map_err(|_| reject())?;
|
||||
if decoded.e < chrono::Utc::now().timestamp() {
|
||||
return Err(reject());
|
||||
}
|
||||
Ok(TaskPosition::new(decoded.t, decoded.i))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key() -> TaskCursorKey {
|
||||
TaskCursorKey::derive(&[7u8; 32])
|
||||
}
|
||||
|
||||
fn unfiltered() -> TaskFilter<'static> {
|
||||
TaskFilter {
|
||||
status: None,
|
||||
assignee_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_position_verbatim() {
|
||||
let k = key();
|
||||
// A stored timestamp the server wrote, fractional digits and all.
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00.123456789+00:00", "task-a");
|
||||
let token = encode(&k, unfiltered(), None, &pos);
|
||||
assert_eq!(decode(&k, unfiltered(), None, &token).unwrap(), pos);
|
||||
// A sub-bucket payload pads to exactly one bucket: the padding
|
||||
// claim is an exact width, and every other width assertion here is
|
||||
// bucket-relative, so only an absolute check catches a pad that
|
||||
// skips "next multiple" or a drifted bucket constant.
|
||||
let body = token.split('.').nth(2).expect("token has a body part");
|
||||
let raw = URL_SAFE_NO_PAD.decode(body).unwrap();
|
||||
assert_eq!(
|
||||
raw.len(),
|
||||
PAYLOAD_BUCKET,
|
||||
"normal token must pad to exactly one bucket"
|
||||
);
|
||||
}
|
||||
|
||||
/// The whole point of the token is that the caller may hold it without
|
||||
/// learning the denied row it names. A signed-but-plaintext payload would
|
||||
/// pass every other test here and still fail this one.
|
||||
#[test]
|
||||
fn token_does_not_expose_the_row_it_names() {
|
||||
let k = key();
|
||||
let token = encode(
|
||||
&k,
|
||||
unfiltered(),
|
||||
None,
|
||||
&TaskPosition::new("2026-01-03T00:00:00+00:00", "denied-task-id"),
|
||||
);
|
||||
let body = token.split('.').nth(2).expect("token has a body part");
|
||||
let raw = URL_SAFE_NO_PAD.decode(body).unwrap();
|
||||
let as_text = String::from_utf8_lossy(&raw);
|
||||
for secret in ["denied-task-id", "2026-01-03", "\"t\"", "\"i\""] {
|
||||
assert!(
|
||||
!as_text.contains(secret),
|
||||
"token body must not carry {secret:?} in the clear: {as_text:?}"
|
||||
);
|
||||
}
|
||||
// Also assert it is not merely reordered or whitespace-mangled JSON.
|
||||
assert!(
|
||||
serde_json::from_slice::<serde_json::Value>(&raw).is_err(),
|
||||
"token body must not be parseable as JSON"
|
||||
);
|
||||
}
|
||||
|
||||
/// The keystream preserves plaintext length, so without the fixed-width
|
||||
/// padding a token naming a 35-char timestamp would be measurably longer
|
||||
/// than one naming a 32-char one: the holder would learn the withheld
|
||||
/// row's field widths without decrypting anything. Mint the same shape
|
||||
/// both ways and require identical token length.
|
||||
#[test]
|
||||
fn token_length_does_not_vary_with_position_width() {
|
||||
let k = key();
|
||||
// Ids are server-minted fixed-length UUIDs; the timestamp is the
|
||||
// width that varies in production (`to_rfc3339()` renders 35 chars
|
||||
// with nanoseconds, 25 without fractional seconds).
|
||||
let id = "b3f7a1c2-4d5e-4f6a-8b9c-0d1e2f3a4b5c";
|
||||
let narrow = encode(
|
||||
&k,
|
||||
unfiltered(),
|
||||
None,
|
||||
&TaskPosition::new("2026-01-03T00:00:00+00:00", id),
|
||||
);
|
||||
let wide = encode(
|
||||
&k,
|
||||
unfiltered(),
|
||||
None,
|
||||
&TaskPosition::new("2026-01-03T00:00:00.123456789+00:00", id),
|
||||
);
|
||||
assert_eq!(
|
||||
narrow.len(),
|
||||
wide.len(),
|
||||
"tokens must not leak the named row's field widths: {narrow} vs {wide}"
|
||||
);
|
||||
// The padded token still decodes to the exact stored string.
|
||||
assert_eq!(
|
||||
decode(&k, unfiltered(), None, &wide).unwrap(),
|
||||
TaskPosition::new("2026-01-03T00:00:00.123456789+00:00", id)
|
||||
);
|
||||
}
|
||||
|
||||
/// A token minted before the fixed-width padding landed (unpadded payload,
|
||||
/// tag over the raw bytes) must still verify: `decode` MACs whatever
|
||||
/// plaintext the keystream recovers and `serde_json` tolerates the
|
||||
/// missing trailing whitespace. This pins the back-compat claim in the
|
||||
/// `encode` docstring with a frozen v1 artifact, so a change to the v1
|
||||
/// recipe pins (domains, MAC input, keystream, segment layout, field
|
||||
/// names) breaks this test instead of silently re-deriving under the
|
||||
/// new internals. It does not pin the padding: `decode` never consults
|
||||
/// `PAYLOAD_BUCKET` and the fixture is unpadded, so the padding-width
|
||||
/// claim belongs to `oversized_payload_rounds_up_to_next_bucket`.
|
||||
///
|
||||
/// Fixture expiry is fixed at 2100-01-01 (`4102444800`): it must stay in
|
||||
/// the future whenever the test runs.
|
||||
#[test]
|
||||
fn unpadded_legacy_token_still_verifies() {
|
||||
let k = key();
|
||||
let filter = unfiltered();
|
||||
let position = TaskPosition::new("2026-01-03T00:00:00+00:00", "legacy-task");
|
||||
// Pre-padding recipe minted once and frozen: serialize with no
|
||||
// padding, tag, and encrypt. Deterministic by construction (SIV needs
|
||||
// no randomness), so this literal is stable across runs.
|
||||
let token = "v1.ILJyy7JZScm_h-HM1-CggA.l4kJUoHTbqSGTVKL0DP4hORnbOS1_gHYV2fwJYXd2QtM-6TBMCKh-wvluIiaEYC9rUSUPVSteAKkp7jBCmK_bR2D";
|
||||
assert_eq!(
|
||||
decode(&k, filter, None, token).unwrap(),
|
||||
position,
|
||||
"pre-padding token must verify under the current decode"
|
||||
);
|
||||
// The fixture is a genuine pre-padding artifact, so its decoded
|
||||
// body must stay below one bucket: a literal re-minted under the
|
||||
// padded recipe would retire this back-compat pin silently.
|
||||
let body = token.split('.').nth(2).expect("token has a body part");
|
||||
let raw = URL_SAFE_NO_PAD.decode(body).unwrap();
|
||||
assert!(
|
||||
raw.len() < PAYLOAD_BUCKET,
|
||||
"legacy fixture must be the unpadded shape: {} bytes",
|
||||
raw.len()
|
||||
);
|
||||
}
|
||||
|
||||
/// The `PAYLOAD_BUCKET` docstring promises an oversized payload rounds up
|
||||
/// to the next multiple instead of failing. Mint a position whose id
|
||||
/// pushes the serialized payload past one bucket and require the token
|
||||
/// to round-trip (at two buckets).
|
||||
#[test]
|
||||
fn oversized_payload_rounds_up_to_next_bucket() {
|
||||
let k = key();
|
||||
// ~140-char id: payload crosses the 128-byte bucket.
|
||||
let long_id = "a".repeat(140);
|
||||
let position = TaskPosition::new("2026-01-03T00:00:00+00:00", long_id.clone());
|
||||
let probe = serde_json::to_vec(&CursorPayload {
|
||||
t: &position.created_at,
|
||||
i: &position.id,
|
||||
e: 1_700_000_000,
|
||||
})
|
||||
.expect("cursor payload is plain strings and an integer");
|
||||
assert!(
|
||||
probe.len() > PAYLOAD_BUCKET,
|
||||
"fixture payload must exceed one bucket: {} bytes",
|
||||
probe.len()
|
||||
);
|
||||
assert!(
|
||||
probe.len() <= 2 * PAYLOAD_BUCKET,
|
||||
"fixture payload must fit in two buckets: {} bytes",
|
||||
probe.len()
|
||||
);
|
||||
let token = encode(&k, unfiltered(), None, &position);
|
||||
assert_eq!(
|
||||
decode(&k, unfiltered(), None, &token).unwrap(),
|
||||
position,
|
||||
"oversized payload must round-trip at two buckets"
|
||||
);
|
||||
// The padded body must be exactly two buckets, not merely longer
|
||||
// than one: the padding claim is an exact width, not a direction.
|
||||
let body = token.split('.').nth(2).expect("token has a body part");
|
||||
let raw = URL_SAFE_NO_PAD.decode(body).unwrap();
|
||||
assert_eq!(
|
||||
raw.len(),
|
||||
2 * PAYLOAD_BUCKET,
|
||||
"oversized payload must pad to exactly two buckets"
|
||||
);
|
||||
}
|
||||
|
||||
/// Callers paste the token straight into a query string, so it must carry
|
||||
/// no character that needs percent-encoding.
|
||||
#[test]
|
||||
fn token_is_url_safe_verbatim() {
|
||||
let token = encode(
|
||||
&key(),
|
||||
TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: Some("did:key:z6MkAssignee"),
|
||||
},
|
||||
None,
|
||||
&TaskPosition::new("2026-01-03T00:00:00.123456789+00:00", "task-a"),
|
||||
);
|
||||
assert!(
|
||||
token
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')),
|
||||
"token must be query-safe without encoding: {token}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Flipping any byte of a token must fail the tag, not decode to a
|
||||
/// different position: the keystream is malleable on its own, the tag is
|
||||
/// what stops a chosen-position forgery.
|
||||
#[test]
|
||||
fn rejects_any_tampered_byte() {
|
||||
let k = key();
|
||||
let token = encode(
|
||||
&k,
|
||||
unfiltered(),
|
||||
None,
|
||||
&TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a"),
|
||||
);
|
||||
let parts: Vec<&str> = token.split('.').collect();
|
||||
for part in [1usize, 2] {
|
||||
for position in [0usize, 3] {
|
||||
let mut bytes = parts[part].as_bytes().to_vec();
|
||||
bytes[position] = if bytes[position] == b'A' { b'B' } else { b'A' };
|
||||
let mut mangled: Vec<String> = parts.iter().map(|p| p.to_string()).collect();
|
||||
mangled[part] = String::from_utf8(bytes).unwrap();
|
||||
assert!(
|
||||
decode(&k, unfiltered(), None, &mangled.join(".")).is_err(),
|
||||
"byte {position} of part {part} must not be malleable"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Sanity: the untouched token still decodes, so the loop above is not
|
||||
// passing because every token is rejected.
|
||||
assert!(decode(&k, unfiltered(), None, &token).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_token_from_another_node() {
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(&TaskCursorKey::derive(&[1u8; 32]), unfiltered(), None, &pos);
|
||||
assert!(decode(
|
||||
&TaskCursorKey::derive(&[2u8; 32]),
|
||||
unfiltered(),
|
||||
None,
|
||||
&token
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_cursor_moved_to_a_different_filter() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: None,
|
||||
},
|
||||
None,
|
||||
&pos,
|
||||
);
|
||||
assert!(decode(&k, unfiltered(), None, &token).is_err());
|
||||
assert!(decode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some("claimed"),
|
||||
assignee_did: None
|
||||
},
|
||||
None,
|
||||
&token
|
||||
)
|
||||
.is_err());
|
||||
assert!(decode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: None
|
||||
},
|
||||
None,
|
||||
&token
|
||||
)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
/// A filter of `Some("")` must not verify a token minted with `None`.
|
||||
#[test]
|
||||
fn distinguishes_absent_filter_from_empty_filter() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(&k, unfiltered(), None, &pos);
|
||||
assert!(decode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some(""),
|
||||
assignee_did: None
|
||||
},
|
||||
None,
|
||||
&token
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
/// A cursor names how far a scan got under one caller's visibility. Moved
|
||||
/// to a different presenting identity it would start that caller's scan
|
||||
/// past rows they are entitled to read, so it must fail to verify rather
|
||||
/// than silently under-report (#327 review).
|
||||
#[test]
|
||||
fn rejects_cursor_moved_to_a_different_caller() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let alice = Some("did:key:z6MkAlice");
|
||||
let bob = Some("did:key:z6MkBob");
|
||||
|
||||
let anon_token = encode(&k, unfiltered(), None, &pos);
|
||||
assert!(
|
||||
decode(&k, unfiltered(), alice, &anon_token).is_err(),
|
||||
"an anonymously minted cursor must not resume an authenticated scan"
|
||||
);
|
||||
assert!(decode(&k, unfiltered(), None, &anon_token).is_ok());
|
||||
|
||||
let alice_token = encode(&k, unfiltered(), alice, &pos);
|
||||
assert!(
|
||||
decode(&k, unfiltered(), bob, &alice_token).is_err(),
|
||||
"one caller's cursor must not resume another caller's scan"
|
||||
);
|
||||
assert!(
|
||||
decode(&k, unfiltered(), None, &alice_token).is_err(),
|
||||
"an authenticated cursor must not resume an anonymous scan"
|
||||
);
|
||||
assert!(decode(&k, unfiltered(), alice, &alice_token).is_ok());
|
||||
}
|
||||
|
||||
/// The binding is on identity, not spelling: `did:key:X` and bare `X` are
|
||||
/// one caller everywhere else on the read path (`did_matches`), so a caller
|
||||
/// who presents the other form of their own DID must keep their own page.
|
||||
#[test]
|
||||
fn caller_binding_is_normalized_across_did_key_spellings() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(&k, unfiltered(), Some("did:key:z6MkAlice"), &pos);
|
||||
assert_eq!(
|
||||
decode(&k, unfiltered(), Some("z6MkAlice"), &token).unwrap(),
|
||||
pos
|
||||
);
|
||||
// A different method sharing the base58 tail is a different principal.
|
||||
assert!(decode(&k, unfiltered(), Some("did:web:z6MkAlice"), &token).is_err());
|
||||
}
|
||||
|
||||
/// The filter binding is on identity, not spelling: `assignee_did` matches
|
||||
/// normalized keys in SQL (`normalize_owner_key`), so minting under
|
||||
/// `did:key:X` and resuming under bare `X` (or vice versa) must succeed,
|
||||
/// while `did:web:X` remains distinct.
|
||||
#[test]
|
||||
fn assignee_filter_binding_is_normalized_across_did_key_spellings() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let filter_did_key = TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: Some("did:key:z6MkAssignee"),
|
||||
};
|
||||
let filter_bare = TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: Some("z6MkAssignee"),
|
||||
};
|
||||
let filter_web = TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: Some("did:web:z6MkAssignee"),
|
||||
};
|
||||
|
||||
let token_from_did_key = encode(&k, filter_did_key, None, &pos);
|
||||
assert_eq!(
|
||||
decode(&k, filter_bare, None, &token_from_did_key).unwrap(),
|
||||
pos
|
||||
);
|
||||
assert!(decode(&k, filter_web, None, &token_from_did_key).is_err());
|
||||
|
||||
let token_from_bare = encode(&k, filter_bare, None, &pos);
|
||||
assert_eq!(
|
||||
decode(&k, filter_did_key, None, &token_from_bare).unwrap(),
|
||||
pos
|
||||
);
|
||||
assert!(decode(&k, filter_web, None, &token_from_bare).is_err());
|
||||
}
|
||||
|
||||
/// Anonymous is a distinct binding from a caller whose normalized DID is
|
||||
/// the empty string, the same way `Some("")` is distinct from `None` for
|
||||
/// the filter fields.
|
||||
#[test]
|
||||
fn distinguishes_anonymous_from_empty_caller() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(&k, unfiltered(), None, &pos);
|
||||
assert!(decode(&k, unfiltered(), Some(""), &token).is_err());
|
||||
}
|
||||
|
||||
/// Length-prefixing must stop a status/assignee pair from being re-split.
|
||||
#[test]
|
||||
fn rejects_field_boundary_shift() {
|
||||
let k = key();
|
||||
let pos = TaskPosition::new("2026-01-03T00:00:00+00:00", "task-a");
|
||||
let token = encode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some("pend"),
|
||||
assignee_did: Some("ing"),
|
||||
},
|
||||
None,
|
||||
&pos,
|
||||
);
|
||||
assert!(decode(
|
||||
&k,
|
||||
TaskFilter {
|
||||
status: Some("pending"),
|
||||
assignee_did: Some("")
|
||||
},
|
||||
None,
|
||||
&token
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_expired_token() {
|
||||
let k = key();
|
||||
// Minted the same way `encode` does, but already past its expiry.
|
||||
let mut payload = serde_json::to_vec(&CursorPayload {
|
||||
t: "2026-01-03T00:00:00+00:00",
|
||||
i: "task-a",
|
||||
e: chrono::Utc::now().timestamp() - 1,
|
||||
})
|
||||
.unwrap();
|
||||
let iv = siv(&k, unfiltered(), None, &payload);
|
||||
apply_keystream(&k, &iv, &mut payload);
|
||||
let expired = format!(
|
||||
"v1.{}.{}",
|
||||
URL_SAFE_NO_PAD.encode(iv),
|
||||
URL_SAFE_NO_PAD.encode(&payload)
|
||||
);
|
||||
let err = decode(&k, unfiltered(), None, &expired).unwrap_err();
|
||||
assert!(err.to_string().contains(INVALID_CURSOR));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_shapes() {
|
||||
let k = key();
|
||||
for bad in [
|
||||
"",
|
||||
"v1",
|
||||
"v1.",
|
||||
"v1.abc",
|
||||
"v2.abc.def",
|
||||
"v1.abc.def.ghi",
|
||||
"v1.!!!.def",
|
||||
] {
|
||||
assert!(
|
||||
decode(&k, unfiltered(), None, bad).is_err(),
|
||||
"must reject {bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rejection path renders the same text, so a caller cannot tell a
|
||||
/// forged token from an expired one from a filter mismatch.
|
||||
#[test]
|
||||
fn every_rejection_is_indistinguishable() {
|
||||
let k = key();
|
||||
for bad in ["v1.abc.def", "not-a-cursor", "v1..", "v9.a.b"] {
|
||||
assert_eq!(
|
||||
decode(&k, unfiltered(), None, bad).unwrap_err().to_string(),
|
||||
format!("invalid request: {INVALID_CURSOR}")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
-2714
File diff suppressed because it is too large.
Load diff
@@ -634,12 +634,10 @@ mod tests {
|
||||
.connect_lazy("postgres://localhost/gitlawb_test_placeholder")
|
||||
.expect("lazy pool creation should not fail");
|
||||
let db = Arc::new(crate::db::Db::for_testing(pool.clone()));
|
||||
let task_cursor_key = crate::api::task_cursor::TaskCursorKey::derive(&keypair.to_seed());
|
||||
let schema = Arc::new(graphql::build_schema(
|
||||
db.clone(),
|
||||
ref_tx.clone(),
|
||||
task_tx.clone(),
|
||||
task_cursor_key.clone(),
|
||||
));
|
||||
crate::state::AppState {
|
||||
config: Arc::new(Config::parse_from(["gitlawb-node"])),
|
||||
@@ -651,7 +649,6 @@ mod tests {
|
||||
ref_update_tx: ref_tx,
|
||||
task_event_tx: task_tx,
|
||||
graphql_schema: schema,
|
||||
task_cursor_key,
|
||||
machine_id: None,
|
||||
repo_store: crate::git::repo_store::RepoStore::for_testing(PathBuf::from("/tmp"), pool),
|
||||
rate_limiter: RateLimiter::new(100, Duration::from_secs(60)),
|
||||
@@ -687,7 +684,6 @@ mod tests {
|
||||
git_ipfs_walk_semaphore: Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
git_ipfs_walk_per_caller:
|
||||
crate::rate_limit::PerCallerConcurrency::with_default_max_keys(16),
|
||||
task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)),
|
||||
git_bin: "git".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,21 +762,6 @@ pub struct Config {
|
||||
value_parser = clap::builder::RangedU64ValueParser::<u64>::new().range(0..=86_400)
|
||||
)]
|
||||
pub pin_repair_sweep_delay_secs: u64,
|
||||
|
||||
/// Per-client-IP rate limit for the anonymous task read routes
|
||||
/// (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`), in requests per hour.
|
||||
/// Both are publicly reachable (`optional_signature`). `GET /api/v1/tasks`
|
||||
/// runs `collect_visible_tasks` and returns a visibility-filtered page;
|
||||
/// `GET /api/v1/tasks/{id}` runs `get_visible_task` and returns an opaque 404
|
||||
/// when the task is hidden or missing. These reads can require task,
|
||||
/// repository, and visibility-rule queries even when no task is returned,
|
||||
/// so the brake bounds the cost of anonymous probes. Keyed on the resolved
|
||||
/// client IP via `GITLAWB_TRUSTED_PROXY`. `0` disables. Default: 1200 (a list page
|
||||
/// followed by per-task reads is a normal client pattern, so this sits above
|
||||
/// the `/ipfs` budget). GraphQL `tasks` / `task` queries, including WebSocket
|
||||
/// operations, share this per-IP budget with REST task reads.
|
||||
#[arg(long, env = "GITLAWB_TASK_READ_RATE_LIMIT", default_value_t = 1200)]
|
||||
pub task_read_rate_limit: usize,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
|
||||
+136
-796
File diff suppressed because it is too large.
Load diff
@@ -12,9 +12,6 @@ pub enum AppError {
|
||||
#[error("repo already exists: {0}")]
|
||||
RepoExists(String),
|
||||
|
||||
#[error("conflict: {0}")]
|
||||
Conflict(String),
|
||||
|
||||
#[error("not found: {0}")]
|
||||
NotFound(String),
|
||||
|
||||
@@ -192,7 +189,6 @@ impl IntoResponse for AppError {
|
||||
"repo_exists",
|
||||
format!("repository '{r}' already exists"),
|
||||
),
|
||||
AppError::Conflict(msg) => (StatusCode::CONFLICT, "conflict", msg.clone()),
|
||||
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, "not_found", msg.clone()),
|
||||
AppError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, "not_an_agent", msg.clone()),
|
||||
AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, "forbidden", msg.clone()),
|
||||
@@ -325,16 +321,6 @@ pub type Result<T> = std::result::Result<T, AppError>;
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn conflict_maps_to_409() {
|
||||
assert_eq!(
|
||||
AppError::Conflict("task not claimable".into())
|
||||
.into_response()
|
||||
.status(),
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_maps_to_504_distinct_from_git_500() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -118,7 +118,7 @@ impl RepoStore {
|
||||
/// Test-only: every guard from this store parks in `release` right before the
|
||||
/// `pg_advisory_unlock` await, until `gate` is notified. Dropping the future
|
||||
/// while it is parked reproduces a client disconnect inside `release`.
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, unix))]
|
||||
pub fn with_pre_unlock_gate(mut self, gate: Arc<tokio::sync::Notify>) -> Self {
|
||||
self.pre_unlock_gate = Some(gate);
|
||||
self
|
||||
@@ -126,7 +126,7 @@ impl RepoStore {
|
||||
|
||||
/// Test-only: how many write guards from this store have reached the Tigris upload
|
||||
/// site. See [`RepoWriteGuard::release`].
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, unix))]
|
||||
pub fn tigris_upload_site_reached(&self) -> usize {
|
||||
self.upload_site_reached
|
||||
.load(std::sync::atomic::Ordering::SeqCst)
|
||||
@@ -1717,8 +1717,11 @@ fn validate_repo_name(repo_name: &str) -> Result<()> {
|
||||
if repo_name.is_empty() {
|
||||
anyhow::bail!("repo_name is empty");
|
||||
}
|
||||
if repo_name.len() > 100 {
|
||||
anyhow::bail!("repo_name exceeds 100 chars");
|
||||
// Byte bound shared with the API-side validator via `MAX_REPO_NAME_LEN`:
|
||||
// the two validators differ on charset by design, but must not drift on
|
||||
// length, or an API-admitted name fails here after the proof is spent.
|
||||
if repo_name.len() > crate::db::MAX_REPO_NAME_LEN {
|
||||
anyhow::bail!("repo_name exceeds {} chars", crate::db::MAX_REPO_NAME_LEN);
|
||||
}
|
||||
// Repo names are `[A-Za-z0-9._-]+` minus path-traversal traps.
|
||||
if repo_name.contains("..") {
|
||||
|
||||
@@ -3,7 +3,7 @@ pub mod query;
|
||||
pub mod subscription;
|
||||
pub mod types;
|
||||
|
||||
use async_graphql::Schema;
|
||||
use async_graphql::{Schema, SchemaBuilder};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::db::Db;
|
||||
@@ -14,6 +14,22 @@ use subscription::SubscriptionRoot;
|
||||
|
||||
pub type GitlawbSchema = Schema<QueryRoot, MutationRoot, SubscriptionRoot>;
|
||||
|
||||
// Keep ordinary schema discovery and application queries usable while
|
||||
// bounding validation work and the number of resolver selections per request.
|
||||
const GRAPHQL_MAX_COMPLEXITY: usize = 400;
|
||||
// The current public schema is shallow; this leaves headroom for composed
|
||||
// clients and the canonical getIntrospectionQuery without allowing
|
||||
// recursively nested documents to grow unchecked.
|
||||
const GRAPHQL_MAX_DEPTH: usize = 14;
|
||||
|
||||
fn apply_query_limits<Query, Mutation, Subscription>(
|
||||
builder: SchemaBuilder<Query, Mutation, Subscription>,
|
||||
) -> SchemaBuilder<Query, Mutation, Subscription> {
|
||||
builder
|
||||
.limit_complexity(GRAPHQL_MAX_COMPLEXITY)
|
||||
.limit_depth(GRAPHQL_MAX_DEPTH)
|
||||
}
|
||||
|
||||
/// Client-facing message for GraphQL resolver failures that wrap a real
|
||||
/// `sqlx::Error`. The real error is logged server-side; never put sqlx/Postgres
|
||||
/// detail in the GraphQL `errors` array (#250).
|
||||
@@ -60,7 +76,6 @@ pub(crate) fn graphql_app_err(e: crate::error::AppError) -> async_graphql::Error
|
||||
// Curated client-safe variants — `Display` is intentional API text.
|
||||
safe @ (crate::error::AppError::RepoNotFound(_)
|
||||
| crate::error::AppError::RepoExists(_)
|
||||
| crate::error::AppError::Conflict(_)
|
||||
| crate::error::AppError::NotFound(_)
|
||||
| crate::error::AppError::Unauthorized(_)
|
||||
| crate::error::AppError::Forbidden(_)
|
||||
@@ -77,87 +92,25 @@ pub(crate) fn graphql_app_err(e: crate::error::AppError) -> async_graphql::Error
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a failed `claim_task` for GraphQL exactly as REST's claim handler
|
||||
/// classifies it: a lost race is a client-safe conflict, a real sqlx fault
|
||||
/// stays opaque. Lives here rather than at the three call sites so the
|
||||
/// classification cannot drift between transports (#327 review), and so
|
||||
/// `every_graphql_map_err_uses_opaque_helpers` can keep whitelisting by name.
|
||||
pub(crate) fn graphql_claim_conflict(e: anyhow::Error) -> async_graphql::Error {
|
||||
graphql_app_err(crate::api::tasks::task_write_conflict(
|
||||
e,
|
||||
"task not claimable: not found or already claimed",
|
||||
))
|
||||
}
|
||||
|
||||
/// The `finish_task` half of [`graphql_claim_conflict`], covering both
|
||||
/// `completeTask` and `failTask`.
|
||||
pub(crate) fn graphql_finish_conflict(e: anyhow::Error) -> async_graphql::Error {
|
||||
graphql_app_err(crate::api::tasks::task_write_conflict(
|
||||
e,
|
||||
"task not found or not in claimed state",
|
||||
))
|
||||
}
|
||||
|
||||
pub struct TaskReadBrakeExtension;
|
||||
|
||||
impl async_graphql::extensions::ExtensionFactory for TaskReadBrakeExtension {
|
||||
fn create(&self) -> Arc<dyn async_graphql::extensions::Extension> {
|
||||
Arc::new(TaskReadBrakeExtensionImpl)
|
||||
}
|
||||
}
|
||||
|
||||
use async_graphql::async_trait::async_trait;
|
||||
|
||||
struct TaskReadBrakeExtensionImpl;
|
||||
|
||||
#[async_trait]
|
||||
impl async_graphql::extensions::Extension for TaskReadBrakeExtensionImpl {
|
||||
async fn prepare_request(
|
||||
&self,
|
||||
ctx: &async_graphql::extensions::ExtensionContext<'_>,
|
||||
mut request: async_graphql::Request,
|
||||
next: async_graphql::extensions::NextPrepareRequest<'_>,
|
||||
) -> async_graphql::ServerResult<async_graphql::Request> {
|
||||
if let Some(session_brake) = ctx
|
||||
.session_data
|
||||
.get(&std::any::TypeId::of::<crate::rate_limit::TaskReadBrake>())
|
||||
.and_then(|d| d.downcast_ref::<crate::rate_limit::TaskReadBrake>())
|
||||
{
|
||||
request = request.data(crate::rate_limit::TaskReadBrake {
|
||||
limiter: session_brake.limiter.clone(),
|
||||
key: session_brake.key.clone(),
|
||||
request_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
|
||||
});
|
||||
}
|
||||
if let Some(did) = ctx
|
||||
.session_data
|
||||
.get(&std::any::TypeId::of::<crate::auth::AuthenticatedDid>())
|
||||
.and_then(|d| d.downcast_ref::<crate::auth::AuthenticatedDid>())
|
||||
{
|
||||
request = request.data(did.clone());
|
||||
}
|
||||
next.run(ctx, request).await
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_schema(
|
||||
db: Arc<Db>,
|
||||
ref_update_tx: tokio::sync::broadcast::Sender<RefUpdateBroadcast>,
|
||||
task_event_tx: tokio::sync::broadcast::Sender<TaskEventBroadcast>,
|
||||
task_cursor_key: crate::api::task_cursor::TaskCursorKey,
|
||||
) -> GitlawbSchema {
|
||||
Schema::build(QueryRoot, MutationRoot, SubscriptionRoot)
|
||||
apply_query_limits(Schema::build(QueryRoot, MutationRoot, SubscriptionRoot))
|
||||
.data(db)
|
||||
.data(ref_update_tx)
|
||||
.data(task_event_tx)
|
||||
.data(task_cursor_key)
|
||||
.extension(TaskReadBrakeExtension)
|
||||
.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::api::events::MAX_VISIBLE_REF_UPDATES;
|
||||
use crate::db::{MAX_VISIBLE_REPO_PAGE_SIZE, MAX_VISIBLE_TASK_PAGE_SIZE};
|
||||
use async_graphql::{EmptyMutation, EmptySubscription, Object, Value};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn graphql_db_err_opaques_sqlx_chain() {
|
||||
@@ -227,11 +180,671 @@ mod tests {
|
||||
assert!(!err.message.contains("failed to open"));
|
||||
}
|
||||
|
||||
fn production_test_schema() -> GitlawbSchema {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy("postgres://localhost/unused")
|
||||
.unwrap();
|
||||
production_test_schema_with_db(Arc::new(Db::for_testing(pool)))
|
||||
}
|
||||
|
||||
fn production_test_schema_with_db(db: Arc<Db>) -> GitlawbSchema {
|
||||
build_schema(
|
||||
db,
|
||||
tokio::sync::broadcast::channel(1).0,
|
||||
tokio::sync::broadcast::channel(1).0,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ref_update_subscription_alias_budget() {
|
||||
assert_subscription_alias_budget("refUpdates { repo }").await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn task_event_subscription_alias_budget() {
|
||||
assert_subscription_alias_budget("taskEvents { taskId }").await;
|
||||
}
|
||||
|
||||
async fn assert_subscription_alias_budget(field: &str) {
|
||||
use futures::StreamExt;
|
||||
use std::time::Duration;
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy("postgres://localhost/unused")
|
||||
.unwrap();
|
||||
let (ref_tx, _) = tokio::sync::broadcast::channel(16);
|
||||
let (task_tx, _) = tokio::sync::broadcast::channel(16);
|
||||
let schema = build_schema(
|
||||
Arc::new(Db::for_testing(pool)),
|
||||
ref_tx.clone(),
|
||||
task_tx.clone(),
|
||||
);
|
||||
for count in [7, 8] {
|
||||
let fields = (0..count)
|
||||
.map(|n| format!("r{n}: {field}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let query = format!("subscription {{ {fields} }}");
|
||||
let mut responses = Box::pin(schema.execute_stream(query));
|
||||
if count == 8 {
|
||||
let response = tokio::time::timeout(Duration::from_secs(1), responses.next())
|
||||
.await
|
||||
.expect("over-budget subscriptions must reject before waiting for events")
|
||||
.expect("the validation error must be returned");
|
||||
assert_eq!(response.errors.len(), 1);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
assert_eq!(ref_tx.receiver_count() + task_tx.receiver_count(), 0);
|
||||
continue;
|
||||
}
|
||||
// Poll the accepted operation far enough to register its receivers.
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(30), responses.next())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(ref_tx.receiver_count() + task_tx.receiver_count(), 7);
|
||||
let _ = ref_tx.send(RefUpdateBroadcast {
|
||||
repo: "owner/repo".into(),
|
||||
ref_name: "refs/heads/main".into(),
|
||||
old_sha: "0".repeat(40),
|
||||
new_sha: "1".repeat(40),
|
||||
pusher_did: "did:key:test".into(),
|
||||
node_did: "did:key:node".into(),
|
||||
timestamp: "2026-01-01T00:00:00Z".into(),
|
||||
owner_did: "did:key:test".into(),
|
||||
});
|
||||
let _ = task_tx.send(TaskEventBroadcast {
|
||||
task_id: "task".into(),
|
||||
old_status: "pending".into(),
|
||||
new_status: "claimed".into(),
|
||||
by_did: "did:key:test".into(),
|
||||
at: "2026-01-01T00:00:00Z".into(),
|
||||
});
|
||||
let response = tokio::time::timeout(Duration::from_secs(1), responses.next())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(response.errors.is_empty(), "{:?}", response.errors);
|
||||
assert_ne!(response.data, Value::Null);
|
||||
drop(responses);
|
||||
assert_eq!(ref_tx.receiver_count() + task_tx.receiver_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn production_mutation_budget_accepts_seven_and_rejects_eight(pool: sqlx::PgPool) {
|
||||
let db = Arc::new(Db::for_testing(pool));
|
||||
db.run_migrations().await.unwrap();
|
||||
let caller = "did:key:reviewer";
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
for index in 0..8 {
|
||||
db.create_task(&crate::db::AgentTask {
|
||||
id: format!("task-{index}"),
|
||||
repo_id: None,
|
||||
kind: "test".into(),
|
||||
status: "pending".into(),
|
||||
delegator_did: caller.into(),
|
||||
assignee_did: None,
|
||||
capability: "test".into(),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now.clone(),
|
||||
deadline: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let schema = production_test_schema_with_db(db.clone());
|
||||
for count in [8, 7] {
|
||||
let fields = (0..count)
|
||||
.map(|n| {
|
||||
format!("r{n}: claimTask(id: \"task-{n}\", assigneeDid: \"{caller}\") {{ id }}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema
|
||||
.execute(
|
||||
async_graphql::Request::new(format!("mutation {{ {fields} }}"))
|
||||
.data(crate::auth::AuthenticatedDid(caller.into())),
|
||||
)
|
||||
.await;
|
||||
if count == 8 {
|
||||
assert_eq!(response.errors.len(), 1);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
assert_eq!(
|
||||
db.list_tasks(Some("pending"), None, 8).await.unwrap().len(),
|
||||
8
|
||||
);
|
||||
continue;
|
||||
}
|
||||
assert!(response.errors.is_empty(), "{:?}", response.errors);
|
||||
assert_eq!(
|
||||
response
|
||||
.data
|
||||
.into_json()
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.len(),
|
||||
7
|
||||
);
|
||||
assert_eq!(
|
||||
db.list_tasks(Some("claimed"), Some(caller), 8)
|
||||
.await
|
||||
.unwrap()
|
||||
.len(),
|
||||
7
|
||||
);
|
||||
assert_eq!(
|
||||
db.get_task("task-7").await.unwrap().unwrap().status,
|
||||
"pending"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn production_list_cost_scales_with_the_same_alias_count(pool: sqlx::PgPool) {
|
||||
let db = Arc::new(Db::for_testing(pool));
|
||||
db.run_migrations().await.unwrap();
|
||||
let schema = production_test_schema_with_db(db);
|
||||
// Bounds are per-root named constants so the cases move with the
|
||||
// documented maximums instead of going stale as literals.
|
||||
for (field, selection, max) in [
|
||||
("refUpdates", "repo", MAX_VISIBLE_REF_UPDATES),
|
||||
("tasks", "id", MAX_VISIBLE_TASK_PAGE_SIZE),
|
||||
(
|
||||
"reposPage",
|
||||
"nodes { name }",
|
||||
MAX_VISIBLE_REPO_PAGE_SIZE as i64,
|
||||
),
|
||||
] {
|
||||
// Two aliases at the maximum always exceed the budget.
|
||||
let fields = (0..2)
|
||||
.map(|n| format!("r{n}: {field}(limit: {max}) {{ {selection} }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
assert_eq!(response.errors.len(), 1);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
|
||||
// At limit 1 two aliases fit for the row-priced roots; reposPage
|
||||
// prices the full corpus scan, so a single alias is the most that
|
||||
// fits under the budget.
|
||||
let aliases = if field == "reposPage" { 1 } else { 2 };
|
||||
let fields = (0..aliases)
|
||||
.map(|n| format!("r{n}: {field}(limit: 1) {{ {selection} }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
assert!(response.errors.is_empty(), "{field}: {:?}", response.errors);
|
||||
assert_eq!(
|
||||
response
|
||||
.data
|
||||
.into_json()
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.len(),
|
||||
aliases
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_limits_reject_mutation_aliases_and_large_lists() {
|
||||
let schema = production_test_schema();
|
||||
// Limits are derived from the MAX_* constants so the boundaries move
|
||||
// with the documented maximums instead of going stale as literals.
|
||||
for (prefix, count, field) in [
|
||||
("mutation", 8, "claimTask(id: \"missing\", assigneeDid: \"did:key:test\") { id }".to_owned()),
|
||||
("mutation", 8, "createTask(delegatorDid: \"did:key:test\", input: { kind: \"test\", capability: \"test\" }) { id }".to_owned()),
|
||||
("mutation", 8, "completeTask(id: \"missing\", byDid: \"did:key:test\", input: {}) { id }".to_owned()),
|
||||
("mutation", 8, "failTask(id: \"missing\", byDid: \"did:key:test\", input: {}) { id }".to_owned()),
|
||||
("query", 8, "task(id: \"missing\") { id }".to_owned()),
|
||||
("query", 2, format!("refUpdates(limit: {MAX_VISIBLE_REF_UPDATES}) {{ repo }}")),
|
||||
("query", 2, format!("tasks(limit: {MAX_VISIBLE_TASK_PAGE_SIZE}) {{ id }}")),
|
||||
("query", 2, format!("reposPage(limit: {MAX_VISIBLE_REPO_PAGE_SIZE}) {{ nodes {{ name }} }}")),
|
||||
("query", 8, "reposPage(limit: 1) { nodes { name } }".to_owned()),
|
||||
] {
|
||||
let fields = (0..count)
|
||||
.map(|n| format!("r{n}: {field}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{prefix} {{ {fields} }}")).await;
|
||||
assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn production_repos_page_serves_the_documented_maximum(pool: sqlx::PgPool) {
|
||||
let db = Arc::new(Db::for_testing(pool));
|
||||
db.run_migrations().await.unwrap();
|
||||
let schema = production_test_schema_with_db(db);
|
||||
for selection in [
|
||||
"nodes { name }",
|
||||
"nodes { name ownerDid } hasNextPage endCursor",
|
||||
] {
|
||||
let response = schema
|
||||
.execute(format!(
|
||||
"{{ reposPage(limit: {MAX_VISIBLE_REPO_PAGE_SIZE}) {{ {selection} }} }}"
|
||||
))
|
||||
.await;
|
||||
assert!(response.errors.is_empty(), "{:?}", response.errors);
|
||||
assert_eq!(
|
||||
response.data.into_json().unwrap()["reposPage"]["nodes"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seven_root_aliases_are_accepted() {
|
||||
struct Root(Arc<AtomicUsize>);
|
||||
#[Object]
|
||||
impl Root {
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn repos(&self) -> Vec<Nested> {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
vec![Nested]
|
||||
}
|
||||
}
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let schema = apply_query_limits(Schema::build(
|
||||
Root(calls.clone()),
|
||||
EmptyMutation,
|
||||
EmptySubscription,
|
||||
))
|
||||
.finish();
|
||||
let fields = (0..7)
|
||||
.map(|n| format!("r{n}: repos {{ value }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
assert!(response.errors.is_empty(), "{:?}", response.errors);
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 7);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expensive_root_aliases_are_rejected_before_database_access() {
|
||||
// Use the production builder with a lazy pool: rejection must precede DB access.
|
||||
let schema = production_test_schema();
|
||||
let fields = (0..8)
|
||||
.map(|n| format!("r{n}: repos {{ name }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
|
||||
assert_eq!(response.data, Value::Null);
|
||||
assert_eq!(response.errors.len(), 1);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_schema_introspection_remains_available() {
|
||||
let schema = production_test_schema();
|
||||
let canonical_introspection = r#"
|
||||
query IntrospectionQuery {
|
||||
__schema {
|
||||
queryType { name }
|
||||
mutationType { name }
|
||||
subscriptionType { name }
|
||||
types {
|
||||
...FullType
|
||||
}
|
||||
directives {
|
||||
name
|
||||
description
|
||||
locations
|
||||
args {
|
||||
...InputValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment FullType on __Type {
|
||||
kind
|
||||
name
|
||||
description
|
||||
fields(includeDeprecated: true) {
|
||||
name
|
||||
description
|
||||
args {
|
||||
...InputValue
|
||||
}
|
||||
type {
|
||||
...TypeRef
|
||||
}
|
||||
isDeprecated
|
||||
deprecationReason
|
||||
}
|
||||
inputFields {
|
||||
...InputValue
|
||||
}
|
||||
interfaces {
|
||||
...TypeRef
|
||||
}
|
||||
enumValues(includeDeprecated: true) {
|
||||
name
|
||||
description
|
||||
isDeprecated
|
||||
deprecationReason
|
||||
}
|
||||
possibleTypes {
|
||||
...TypeRef
|
||||
}
|
||||
}
|
||||
|
||||
fragment InputValue on __InputValue {
|
||||
name
|
||||
description
|
||||
type { ...TypeRef }
|
||||
defaultValue
|
||||
}
|
||||
|
||||
fragment TypeRef on __Type {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let response = schema.execute(canonical_introspection).await;
|
||||
assert!(
|
||||
response.errors.is_empty(),
|
||||
"canonical introspection query failed against production schema: {:?}",
|
||||
response.errors
|
||||
);
|
||||
assert_ne!(response.data, Value::Null);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ref_updates_and_tasks_single_alias_max_limit_complexity_contract() {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy("postgres://localhost/unused")
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
let (ref_tx, _) = tokio::sync::broadcast::channel(16);
|
||||
let (task_tx, _) = tokio::sync::broadcast::channel(16);
|
||||
let schema = build_schema(Arc::new(Db::for_testing(pool)), ref_tx, task_tx);
|
||||
|
||||
// refUpdates(limit: MAX_VISIBLE_REF_UPDATES):
|
||||
// Single-field selection has child_complexity 1 -> cost 100 + 200 + 1 = 301 <= 400.
|
||||
// It passes validation and reaches the resolver (which yields db error on lazy pool).
|
||||
let single_ref = schema
|
||||
.execute(format!(
|
||||
"{{ refUpdates(limit: {MAX_VISIBLE_REF_UPDATES}) {{ repo }} }}"
|
||||
))
|
||||
.await;
|
||||
assert!(
|
||||
!single_ref
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == "Query is too complex."),
|
||||
"single-field refUpdates at max limit must pass complexity validation: {:?}",
|
||||
single_ref.errors
|
||||
);
|
||||
assert!(
|
||||
single_ref
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"single-field refUpdates at max limit must reach the resolver: {:?}",
|
||||
single_ref.errors
|
||||
);
|
||||
|
||||
// Two-field selection has child_complexity 2 -> cost 100 + 200 + 2 = 302 <= 400.
|
||||
// The documented max-200 request stays reachable with multiple fields
|
||||
// (the old multiplicative price rejected it at 450); it passes
|
||||
// validation and reaches the resolver like the single-field case.
|
||||
let multi_ref = schema
|
||||
.execute(format!(
|
||||
"{{ refUpdates(limit: {MAX_VISIBLE_REF_UPDATES}) {{ repo refName }} }}"
|
||||
))
|
||||
.await;
|
||||
assert!(
|
||||
!multi_ref
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == "Query is too complex."),
|
||||
"two-field refUpdates at max limit must pass complexity validation: {:?}",
|
||||
multi_ref.errors
|
||||
);
|
||||
assert!(
|
||||
multi_ref
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"two-field refUpdates at max limit must reach the resolver: {:?}",
|
||||
multi_ref.errors
|
||||
);
|
||||
|
||||
// tasks(limit: MAX_VISIBLE_TASK_PAGE_SIZE):
|
||||
// Single-field selection has child_complexity 1, so the cost is
|
||||
// 50 + MAX_VISIBLE_TASK_PAGE_SIZE + 1 <= 400.
|
||||
// It passes validation and reaches the resolver.
|
||||
let single_task = schema
|
||||
.execute(format!(
|
||||
"{{ tasks(limit: {MAX_VISIBLE_TASK_PAGE_SIZE}) {{ id }} }}"
|
||||
))
|
||||
.await;
|
||||
assert!(
|
||||
!single_task
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == "Query is too complex."),
|
||||
"single-field tasks at the maximum page size must pass complexity validation: {:?}",
|
||||
single_task.errors
|
||||
);
|
||||
assert!(
|
||||
single_task
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"single-field tasks at the maximum page size must reach the resolver: {:?}",
|
||||
single_task.errors
|
||||
);
|
||||
|
||||
// Two-field selection has child_complexity 2, so the cost is
|
||||
// 50 + MAX_VISIBLE_TASK_PAGE_SIZE + 2 <= 400.
|
||||
// A request at the documented maximum stays reachable with multiple
|
||||
// fields (the old multiplicative price rejected it at 450); it passes
|
||||
// validation and reaches the resolver like the single-field case.
|
||||
let multi_task = schema
|
||||
.execute(format!(
|
||||
"{{ tasks(limit: {MAX_VISIBLE_TASK_PAGE_SIZE}) {{ id status }} }}"
|
||||
))
|
||||
.await;
|
||||
assert!(
|
||||
!multi_task
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == "Query is too complex."),
|
||||
"two-field tasks at the maximum page size must pass complexity validation: {:?}",
|
||||
multi_task.errors
|
||||
);
|
||||
assert!(
|
||||
multi_task
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message == GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"two-field tasks at the maximum page size must reach the resolver: {:?}",
|
||||
multi_task.errors
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_repos_aliases_exceed_the_budget() {
|
||||
// `repos` is priced as the full page it scans
|
||||
// (50 + MAX_VISIBLE_REPO_PAGE_SIZE + child), so two `repos { name }`
|
||||
// aliases cost 2 * 251 = 502 > 400 and the document is rejected before
|
||||
// any resolver runs. If the price reverts to `50 + child_complexity`
|
||||
// the aliases cost 2 * 51 = 102, validation passes, and the failure
|
||||
// mode changes (resolver DB errors on the lazy pool): this test goes
|
||||
// red on revert.
|
||||
let schema = production_test_schema();
|
||||
let response = schema
|
||||
.execute("{ r0: repos { name } r1: repos { name } }")
|
||||
.await;
|
||||
assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seven_repos_page_aliases_exceed_the_budget() {
|
||||
// `reposPage` is priced as the full corpus scan
|
||||
// (50 + MAX_VISIBLE_REPO_PAGE_SIZE + child_complexity), so seven
|
||||
// `reposPage(limit: 1) { nodes { name } }` aliases cost
|
||||
// 7 * (50 + 200 + 2) = 1764 > 400 and the document is rejected
|
||||
// before any resolver runs. Under the previous row-priced formula
|
||||
// the same aliases cost 7 * (50 + 1 + 2) = 371, validation passes,
|
||||
// and the failure mode changes (resolver DB errors on the lazy
|
||||
// pool): this test goes red on revert. Eight aliases are rejected
|
||||
// under both formulas, so seven is the load-bearing boundary.
|
||||
let schema = production_test_schema();
|
||||
let fields = (0..7)
|
||||
.map(|n| format!("r{n}: reposPage(limit: 1) {{ nodes {{ name }} }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ref_updates_fixed_base_is_charged() {
|
||||
// The 100 base in the refUpdates complexity formula charges for the
|
||||
// collector's fixed work (loading the deduped repo set, the
|
||||
// quarantined set, and the visibility rules, then walking up to 16
|
||||
// keyset pages) even at limit: 1. Four aliases at limit: 1 cost
|
||||
// 4 * (100 + 1 + 1) = 408 > 400 and must be rejected. If the base
|
||||
// disappears, the cost drops to 4 * (1 + 1) = 8 and this test fails.
|
||||
let schema = production_test_schema();
|
||||
let fields = (0..4)
|
||||
.map(|n| format!("r{n}: refUpdates(limit: 1) {{ repo }}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let response = schema.execute(format!("{{ {fields} }}")).await;
|
||||
assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
|
||||
assert_eq!(response.errors[0].message, "Query is too complex.");
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Nested;
|
||||
|
||||
#[Object]
|
||||
impl Nested {
|
||||
async fn child(&self) -> Nested {
|
||||
Nested
|
||||
}
|
||||
|
||||
async fn value(&self) -> i32 {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingQuery(Arc<AtomicUsize>);
|
||||
|
||||
#[Object]
|
||||
impl CountingQuery {
|
||||
async fn nested(&self) -> Nested {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
Nested
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn query_depth_limit_accepts_fourteen_and_rejects_fifteen() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let schema = apply_query_limits(Schema::build(
|
||||
CountingQuery(Arc::clone(&calls)),
|
||||
EmptyMutation,
|
||||
EmptySubscription,
|
||||
))
|
||||
.finish();
|
||||
let query_at_depth = |depth: usize| {
|
||||
let selection = (2..depth).fold("value".to_string(), |selection, _| {
|
||||
format!("child {{ {selection} }}")
|
||||
});
|
||||
format!("{{ nested {{ {selection} }} }}")
|
||||
};
|
||||
|
||||
let accepted = schema.execute(query_at_depth(GRAPHQL_MAX_DEPTH)).await;
|
||||
|
||||
assert!(
|
||||
accepted.errors.is_empty(),
|
||||
"depth {GRAPHQL_MAX_DEPTH} should be accepted: {:?}",
|
||||
accepted.errors
|
||||
);
|
||||
assert_eq!(calls.swap(0, Ordering::Relaxed), 1);
|
||||
|
||||
let rejected = schema.execute(query_at_depth(GRAPHQL_MAX_DEPTH + 1)).await;
|
||||
|
||||
assert_eq!(rejected.data, Value::Null);
|
||||
assert_eq!(rejected.errors.len(), 1);
|
||||
assert_eq!(rejected.errors[0].message, "Query is nested too deep.");
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_schema_enforces_depth_limit() {
|
||||
let schema = production_test_schema();
|
||||
// Depth 14 is accepted through the production build_schema path.
|
||||
let of_types_14 = (0..9).fold("name".to_string(), |acc, _| format!("ofType {{ {acc} }}"));
|
||||
let query_14 =
|
||||
format!("{{ __schema {{ types {{ fields {{ type {{ {of_types_14} }} }} }} }} }}");
|
||||
let accepted = schema.execute(&query_14).await;
|
||||
assert!(accepted.errors.is_empty(), "{:?}", accepted.errors);
|
||||
|
||||
// Construct an introspection query of depth 15 using __schema.
|
||||
// 1: __schema
|
||||
// 2: types
|
||||
// 3: fields
|
||||
// 4: type
|
||||
// 5..14: ofType (10 times)
|
||||
// 15: name
|
||||
// Total depth = 15 > GRAPHQL_MAX_DEPTH (14).
|
||||
let of_types = (0..10).fold("name".to_string(), |acc, _| format!("ofType {{ {acc} }}"));
|
||||
let query = format!("{{ __schema {{ types {{ fields {{ type {{ {of_types} }} }} }} }} }}");
|
||||
|
||||
let rejected = schema.execute(&query).await;
|
||||
assert_eq!(rejected.data, async_graphql::Value::Null);
|
||||
assert_eq!(rejected.errors.len(), 1);
|
||||
assert_eq!(rejected.errors[0].message, "Query is nested too deep.");
|
||||
}
|
||||
|
||||
/// Every `.map_err(` in the GraphQL query/mutation resolvers must route
|
||||
/// through one of the curated helpers in this module, or discard the error
|
||||
/// (`|_|`). Same source-scrape pattern as `api::authz_guard` (#255
|
||||
/// review). The list is deliberately a whitelist of names rather than a
|
||||
/// prefix match, so adding a new mapper is a decision a reviewer sees.
|
||||
/// through the opaque helpers, or discard the error (`|_|`). Same source-
|
||||
/// scrape pattern as `api::authz_guard` (#255 review).
|
||||
#[test]
|
||||
fn every_graphql_map_err_uses_opaque_helpers() {
|
||||
for (file, src) in [
|
||||
@@ -246,8 +859,6 @@ mod tests {
|
||||
let after = code[idx + ".map_err(".len()..].trim_start();
|
||||
let ok = after.starts_with("crate::graphql::graphql_db_err")
|
||||
|| after.starts_with("crate::graphql::graphql_app_err")
|
||||
|| after.starts_with("crate::graphql::graphql_claim_conflict")
|
||||
|| after.starts_with("crate::graphql::graphql_finish_conflict")
|
||||
|| after.starts_with("|_|")
|
||||
|| after.starts_with("|_ ");
|
||||
assert!(
|
||||
|
||||
@@ -22,6 +22,7 @@ pub struct MutationRoot;
|
||||
|
||||
#[Object]
|
||||
impl MutationRoot {
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn create_task(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
@@ -89,6 +90,7 @@ impl MutationRoot {
|
||||
Ok(AgentTaskType::from(stored))
|
||||
}
|
||||
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn claim_task(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
@@ -104,39 +106,29 @@ impl MutationRoot {
|
||||
let assignee_did = caller.to_string();
|
||||
let db = ctx.data_unchecked::<Arc<Db>>();
|
||||
let tx = ctx.data_unchecked::<tokio::sync::broadcast::Sender<TaskEventBroadcast>>();
|
||||
crate::api::tasks::get_claimable_task(db, &id, caller)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_app_err)?
|
||||
.ok_or_else(|| async_graphql::Error::new("task not found"))?;
|
||||
// Same classification REST's claim handler applies: a claim race is a
|
||||
// client-safe conflict, a genuine sqlx failure stays opaque. Routing
|
||||
// both transports through `task_write_conflict` is what stops a normal
|
||||
// race from reaching a GraphQL caller as a generic database error
|
||||
// (#327 review).
|
||||
let task = db
|
||||
.claim_task(&id, &assignee_did)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_claim_conflict)?;
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
// Report the stored assignee form like REST, so subscribers see the
|
||||
// same identity whichever API surface ran the transition.
|
||||
let by_did = task
|
||||
.assignee_did
|
||||
.as_deref()
|
||||
.map(crate::db::trim_assignee_did)
|
||||
.unwrap_or(assignee_did.as_str())
|
||||
.to_string();
|
||||
crate::api::tasks::announce_task_event(
|
||||
db,
|
||||
tx,
|
||||
TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "pending".to_string(),
|
||||
new_status: "claimed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "pending".to_string(),
|
||||
new_status: "claimed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
});
|
||||
Ok(AgentTaskType::from(task))
|
||||
}
|
||||
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn complete_task(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
@@ -153,12 +145,12 @@ impl MutationRoot {
|
||||
let by_did = caller.to_string();
|
||||
let db = ctx.data_unchecked::<Arc<Db>>();
|
||||
let tx = ctx.data_unchecked::<tokio::sync::broadcast::Sender<TaskEventBroadcast>>();
|
||||
// Authorize the actor: the task must be visible to the caller (returning
|
||||
// not found for invisible tasks so existence is not leaked), and only
|
||||
// the task's assignee may finish it.
|
||||
let existing = crate::api::tasks::get_visible_task(db, &id, Some(caller))
|
||||
// Authorize the actor: binding by_did to the signer is necessary but not
|
||||
// sufficient — only the task's assignee may finish it.
|
||||
let existing = db
|
||||
.get_task(&id)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_app_err)?
|
||||
.map_err(crate::graphql::graphql_db_err)?
|
||||
.ok_or_else(|| async_graphql::Error::new("task not found"))?;
|
||||
if !crate::api::did_matches(
|
||||
caller,
|
||||
@@ -171,28 +163,24 @@ impl MutationRoot {
|
||||
let task = db
|
||||
.finish_task(&id, "completed", input.result.as_deref(), caller)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_finish_conflict)?;
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
let by_did = task
|
||||
.assignee_did
|
||||
.as_deref()
|
||||
.map(crate::db::trim_assignee_did)
|
||||
.unwrap_or(by_did.as_str())
|
||||
.to_string();
|
||||
crate::api::tasks::announce_task_event(
|
||||
db,
|
||||
tx,
|
||||
TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
new_status: "completed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
new_status: "completed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
});
|
||||
Ok(AgentTaskType::from(task))
|
||||
}
|
||||
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn fail_task(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
@@ -209,12 +197,11 @@ impl MutationRoot {
|
||||
let by_did = caller.to_string();
|
||||
let db = ctx.data_unchecked::<Arc<Db>>();
|
||||
let tx = ctx.data_unchecked::<tokio::sync::broadcast::Sender<TaskEventBroadcast>>();
|
||||
// Authorize the actor: the task must be visible to the caller (returning
|
||||
// not found for invisible tasks so existence is not leaked), and only
|
||||
// the task's assignee may fail it.
|
||||
let existing = crate::api::tasks::get_visible_task(db, &id, Some(caller))
|
||||
// Authorize the actor: only the task's assignee may fail it.
|
||||
let existing = db
|
||||
.get_task(&id)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_app_err)?
|
||||
.map_err(crate::graphql::graphql_db_err)?
|
||||
.ok_or_else(|| async_graphql::Error::new("task not found"))?;
|
||||
if !crate::api::did_matches(
|
||||
caller,
|
||||
@@ -228,25 +215,20 @@ impl MutationRoot {
|
||||
let task = db
|
||||
.finish_task(&id, "failed", Some(&reason), caller)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_finish_conflict)?;
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
let by_did = task
|
||||
.assignee_did
|
||||
.as_deref()
|
||||
.map(crate::db::trim_assignee_did)
|
||||
.unwrap_or(by_did.as_str())
|
||||
.to_string();
|
||||
crate::api::tasks::announce_task_event(
|
||||
db,
|
||||
tx,
|
||||
TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
new_status: "failed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
new_status: "failed".to_string(),
|
||||
by_did,
|
||||
at: Utc::now().to_rfc3339(),
|
||||
});
|
||||
Ok(AgentTaskType::from(task))
|
||||
}
|
||||
}
|
||||
@@ -344,7 +326,7 @@ mod tests {
|
||||
);
|
||||
if *name == "claimTask" {
|
||||
assert!(
|
||||
errs.contains("task not found"),
|
||||
errs.contains("task not claimable"),
|
||||
"claim race / missing task must keep its business message: {errs}"
|
||||
);
|
||||
assert!(
|
||||
@@ -388,210 +370,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// #327 review: `claimTask`/`completeTask`/`failTask` called
|
||||
/// `graphql_db_err` directly on db-layer business failures, so an ordinary
|
||||
/// claim race or stale finish reached GraphQL clients as a generic
|
||||
/// database error while REST clients got an actionable conflict. All three
|
||||
/// now route through the shared `task_write_conflict` classifier.
|
||||
///
|
||||
/// Deleting either `map_err` from a mutation turns this red: the message
|
||||
/// becomes the raw anyhow text instead of the fixed conflict form.
|
||||
#[sqlx::test]
|
||||
async fn task_write_races_surface_as_conflicts_not_db_errors(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool).await;
|
||||
let schema = state.graphql_schema.as_ref();
|
||||
let assignee = "did:key:zGQLRACEASSIGNEEAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
let rival = "did:key:zGQLRACERIVALBBBBBBBBBBBBBBBBBBBBBBBBBB";
|
||||
let delegator = "did:key:zGQLRACEDELEGATORCCCCCCCCCCCCCCCCCCCCC";
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
state
|
||||
.db
|
||||
.create_repo(&crate::db::RepoRecord {
|
||||
id: "race-repo".into(),
|
||||
name: "race".into(),
|
||||
owner_did: delegator.into(),
|
||||
description: None,
|
||||
is_public: true,
|
||||
default_branch: "main".into(),
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
disk_path: "/tmp/race-repo".into(),
|
||||
forked_from: None,
|
||||
machine_id: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.db
|
||||
.create_task(&crate::db::AgentTask {
|
||||
id: "race-task".into(),
|
||||
repo_id: Some("race-repo".into()),
|
||||
kind: "build".into(),
|
||||
status: "pending".into(),
|
||||
delegator_did: delegator.into(),
|
||||
assignee_did: None,
|
||||
capability: "repo:write".into(),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
deadline: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// The assignee wins the claim.
|
||||
let claim = |did: &str| {
|
||||
format!(r#"mutation {{ claimTask(id: "race-task", assigneeDid: "{did}") {{ id }} }}"#)
|
||||
};
|
||||
let resp = schema
|
||||
.execute(Request::new(claim(assignee)).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
assert!(resp.errors.is_empty(), "first claim: {}", errors(&resp));
|
||||
|
||||
// The rival loses the race: ineligible caller receives opaque not-found.
|
||||
let resp = schema
|
||||
.execute(Request::new(claim(rival)).data(AuthenticatedDid(rival.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains("task not found"),
|
||||
"ineligible caller after task is claimed must receive opaque not-found: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"ineligible claim is not a database failure: {errs}"
|
||||
);
|
||||
|
||||
// A second claim that reaches the conditional SQL write (e.g. assignee claiming
|
||||
// again on an already-claimed task) exercises the conflict mapper:
|
||||
let resp = schema
|
||||
.execute(Request::new(claim(assignee)).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains("task not claimable: not found or already claimed"),
|
||||
"a lost claim race must render the fixed conflict message: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"a claim race is not a database failure: {errs}"
|
||||
);
|
||||
|
||||
// A stale finish on an already-completed task is the same class.
|
||||
let complete = format!(
|
||||
r#"mutation {{ completeTask(id: "race-task", byDid: "{assignee}", input: {{ result: "ok" }}) {{ id }} }}"#
|
||||
);
|
||||
let resp = schema
|
||||
.execute(Request::new(&complete).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
assert!(resp.errors.is_empty(), "first complete: {}", errors(&resp));
|
||||
|
||||
let resp = schema
|
||||
.execute(Request::new(&complete).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains("task not found or not in claimed state"),
|
||||
"a stale complete must render the fixed conflict message: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"a stale complete is not a database failure: {errs}"
|
||||
);
|
||||
|
||||
let fail = format!(
|
||||
r#"mutation {{ failTask(id: "race-task", byDid: "{assignee}", input: {{ reason: "nope" }}) {{ id }} }}"#
|
||||
);
|
||||
let resp = schema
|
||||
.execute(Request::new(&fail).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains("task not found or not in claimed state"),
|
||||
"a stale fail must render the fixed conflict message: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"a stale fail is not a database failure: {errs}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The other half of the same classification: a genuine SQL fault on the
|
||||
/// write itself must stay opaque. Without this, routing conflicts through
|
||||
/// `task_write_conflict` could be "fixed" by making every db failure a
|
||||
/// client-visible conflict message.
|
||||
#[sqlx::test]
|
||||
async fn task_write_sql_faults_stay_opaque(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
let assignee = "did:key:zGQLOPAQUEASSIGNEEAAAAAAAAAAAAAAAAAAAAA";
|
||||
let delegator = "did:key:zGQLOPAQUEDELEGATORBBBBBBBBBBBBBBBBBBB";
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
state
|
||||
.db
|
||||
.create_task(&crate::db::AgentTask {
|
||||
id: "opaque-task".into(),
|
||||
repo_id: None,
|
||||
kind: "build".into(),
|
||||
status: "pending".into(),
|
||||
delegator_did: delegator.into(),
|
||||
assignee_did: Some(assignee.into()),
|
||||
capability: "repo:write".into(),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
deadline: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Fault the write itself, not the schema. Dropping a column the
|
||||
// visibility pre-check also SELECTs would fail in `get_visible_task`
|
||||
// and never reach `graphql_claim_conflict`, so this test would pass
|
||||
// against a claim mapper that leaks (#327 review). A BEFORE UPDATE
|
||||
// trigger keeps every read valid and faults only inside
|
||||
// `Db::claim_task`.
|
||||
sqlx::raw_sql(
|
||||
"CREATE FUNCTION gl_test_fault_task_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $fn$
|
||||
BEGIN RAISE EXCEPTION 'gl_test_forced_update_fault'; END;
|
||||
$fn$;
|
||||
CREATE TRIGGER gl_test_fault_task_update
|
||||
BEFORE UPDATE ON agent_tasks
|
||||
FOR EACH ROW EXECUTE FUNCTION gl_test_fault_task_update();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let resp = state
|
||||
.graphql_schema
|
||||
.execute(
|
||||
Request::new(format!(
|
||||
r#"mutation {{ claimTask(id: "opaque-task", assigneeDid: "{assignee}") {{ id }} }}"#
|
||||
))
|
||||
.data(AuthenticatedDid(assignee.into())),
|
||||
)
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"a real sqlx fault on the write must stay opaque: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains("task not claimable"),
|
||||
"a write-time sqlx fault must not be reclassified as a claim race: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains("gl_test_forced_update_fault") && !errs.contains("trigger"),
|
||||
"database text leaked through the conflict mapper: {errs}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Adversarial-review GATE-1 (GraphQL): completing a task requires being its
|
||||
/// assignee, not merely signing as the by_did you pass. A signer who is not
|
||||
/// the assignee is rejected even though the by_did binding passes; the
|
||||
@@ -614,7 +392,7 @@ mod tests {
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now.clone(),
|
||||
updated_at: now,
|
||||
deadline: None,
|
||||
};
|
||||
state.db.create_task(&task).await.expect("seed task");
|
||||
@@ -631,69 +409,14 @@ mod tests {
|
||||
)
|
||||
};
|
||||
|
||||
// Stranger signs as themselves on a repo-less task they cannot see:
|
||||
// invisible task returns "task not found" so existence is not leaked.
|
||||
// Stranger signs as themselves and passes byDid=self (so the signer
|
||||
// binding passes), but is not the assignee → rejected by authorization.
|
||||
let resp = schema
|
||||
.execute(Request::new(q(stranger)).data(AuthenticatedDid(stranger.into())))
|
||||
.await;
|
||||
assert!(
|
||||
errors(&resp).contains("task not found"),
|
||||
"an invisible task must return not found, got: {}",
|
||||
errors(&resp)
|
||||
);
|
||||
|
||||
// Seed a task on a public repo that stranger CAN see, but is not assignee of:
|
||||
let pub_repo = crate::db::RepoRecord {
|
||||
id: "pub-r".into(),
|
||||
name: "pub-r".into(),
|
||||
owner_did: "did:key:zGQLDELEGATORCCCCCCCCCCCCCCCCCCCCCCCCCC".into(),
|
||||
description: None,
|
||||
is_public: true,
|
||||
default_branch: "main".into(),
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
disk_path: "/tmp/pub-r".into(),
|
||||
forked_from: None,
|
||||
machine_id: None,
|
||||
};
|
||||
state.db.create_repo(&pub_repo).await.expect("create repo");
|
||||
let pub_task = crate::db::AgentTask {
|
||||
id: "task-pub".into(),
|
||||
repo_id: Some("pub-r".into()),
|
||||
kind: "build".into(),
|
||||
status: "pending".into(),
|
||||
delegator_did: "did:key:zGQLDELEGATORCCCCCCCCCCCCCCCCCCCCCCCCCC".into(),
|
||||
assignee_did: None,
|
||||
capability: "repo:write".into(),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
deadline: None,
|
||||
};
|
||||
state
|
||||
.db
|
||||
.create_task(&pub_task)
|
||||
.await
|
||||
.expect("seed pub task");
|
||||
state
|
||||
.db
|
||||
.claim_task("task-pub", assignee)
|
||||
.await
|
||||
.expect("claim pub task");
|
||||
|
||||
let q_pub = |actor: &str| {
|
||||
format!(
|
||||
r#"mutation {{ completeTask(id: "task-pub", byDid: "{actor}", input: {{}}) {{ id status }} }}"#
|
||||
)
|
||||
};
|
||||
let resp = schema
|
||||
.execute(Request::new(q_pub(stranger)).data(AuthenticatedDid(stranger.into())))
|
||||
.await;
|
||||
assert!(
|
||||
errors(&resp).contains("assignee"),
|
||||
"a non-assignee signer on a visible task must be rejected: {}",
|
||||
"a non-assignee signer must be rejected: {}",
|
||||
errors(&resp)
|
||||
);
|
||||
|
||||
@@ -759,7 +482,7 @@ mod tests {
|
||||
// repo id afterwards.
|
||||
let stored = state
|
||||
.db
|
||||
.list_tasks_keyset(None, None, 50, None)
|
||||
.list_tasks(None, None, 50)
|
||||
.await
|
||||
.expect("list tasks");
|
||||
assert!(
|
||||
@@ -921,11 +644,9 @@ mod tests {
|
||||
.execute(Request::new(q(thief)).data(AuthenticatedDid(thief.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
// The claim gate hides existence: an ineligible claimer gets the same
|
||||
// not-found as a missing task, not a reserved deny that would leak it.
|
||||
assert!(
|
||||
errs.contains("task not found"),
|
||||
"stranger claim must read as not-found, got: {errs}"
|
||||
errs.contains("reserved"),
|
||||
"stranger claim must surface reserved deny distinctly: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains("gql-ucan-secret"),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,15 +11,16 @@ pub struct SubscriptionRoot;
|
||||
|
||||
#[Subscription]
|
||||
impl SubscriptionRoot {
|
||||
/// Live ref-update stream. `/graphql/ws` is mounted under the
|
||||
/// `optional_signature` layer and carries optional caller identity, but this
|
||||
/// resolver does not inspect it — it relays whatever enters the broadcast
|
||||
/// Live ref-update stream. `/graphql/ws` is mounted outside the
|
||||
/// `optional_signature` layer, so this resolver has NO caller identity and
|
||||
/// cannot gate per-subscriber — it relays whatever enters the broadcast
|
||||
/// channel to any anonymous client. Its visibility safety therefore rests
|
||||
/// entirely on the WRITE side: the push handler only sends a
|
||||
/// `RefUpdateBroadcast` for repos the anonymous public may read (inside its
|
||||
/// `if announce` block, `api/repos.rs`). This is a single-point invariant —
|
||||
/// any new sender to `ref_update_tx` MUST be `announce`-gated, or private-repo
|
||||
/// ref metadata leaks here to unauthenticated subscribers (#112/#114 class).
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn ref_updates(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
@@ -46,6 +47,7 @@ impl SubscriptionRoot {
|
||||
})
|
||||
}
|
||||
|
||||
#[graphql(complexity = "50 + child_complexity")]
|
||||
async fn task_events(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
|
||||
@@ -11,6 +11,14 @@ pub struct RepoType {
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(SimpleObject)]
|
||||
pub struct RepoPageType {
|
||||
pub nodes: Vec<RepoType>,
|
||||
pub has_next_page: bool,
|
||||
/// Position after the last returned visible repository; null for an empty page.
|
||||
pub end_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(SimpleObject, Clone)]
|
||||
pub struct AgentTaskType {
|
||||
pub id: String,
|
||||
@@ -48,65 +56,6 @@ impl From<AgentTask> for AgentTaskType {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only projection of `AgentTask` for the `tasks`/`task` queries, as
|
||||
/// opposed to `AgentTaskType`, which the task mutations (`createTask`,
|
||||
/// `claimTask`, `completeTask`, `failTask` — all `require_signer`-gated)
|
||||
/// return. Identical except for the missing `ucan_token` (#268): a read
|
||||
/// surface never needs to echo it back, since the assignee already received it
|
||||
/// at delegation/claim time via the mutation response.
|
||||
#[derive(SimpleObject, Clone)]
|
||||
pub struct AgentTaskReadType {
|
||||
pub id: String,
|
||||
pub repo_id: Option<String>,
|
||||
pub kind: String,
|
||||
pub status: String,
|
||||
pub delegator_did: String,
|
||||
pub assignee_did: Option<String>,
|
||||
pub capability: String,
|
||||
pub payload: Option<String>,
|
||||
pub result: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub deadline: Option<String>,
|
||||
}
|
||||
|
||||
/// Wraps a `tasks` page with the same completion signals the REST list route
|
||||
/// exposes, so the two surfaces answer pagination identically.
|
||||
///
|
||||
/// `hasMore` and `incomplete` are separate because they are separate facts
|
||||
/// (#327 review): `hasMore` says more candidates remain, `incomplete` says
|
||||
/// this page is short *only* because the authorization scan hit its safety
|
||||
/// wall. `nextCursor` is present exactly when `hasMore` is true and is an
|
||||
/// opaque MAC'd token — it can name the last examined candidate, denied or
|
||||
/// not, without disclosing it, which is what lets a caller page past a denied
|
||||
/// window instead of stalling on it.
|
||||
#[derive(SimpleObject, Clone)]
|
||||
pub struct TaskPageType {
|
||||
pub items: Vec<AgentTaskReadType>,
|
||||
pub has_more: bool,
|
||||
pub incomplete: bool,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl From<AgentTask> for AgentTaskReadType {
|
||||
fn from(t: AgentTask) -> Self {
|
||||
Self {
|
||||
id: t.id,
|
||||
repo_id: t.repo_id,
|
||||
kind: t.kind,
|
||||
status: t.status,
|
||||
delegator_did: t.delegator_did,
|
||||
assignee_did: t.assignee_did,
|
||||
capability: t.capability,
|
||||
payload: t.payload,
|
||||
result: t.result,
|
||||
created_at: t.created_at,
|
||||
updated_at: t.updated_at,
|
||||
deadline: t.deadline,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(SimpleObject, Clone)]
|
||||
pub struct RefUpdateType {
|
||||
pub repo: String,
|
||||
|
||||
@@ -2638,6 +2638,7 @@ mod tests {
|
||||
/// type probe carries its oid on stdin rather than in argv, so an oid appears in
|
||||
/// the log only once an object has already got past its probe, and a healthy
|
||||
/// object costs two invocations to a faulting one's one.
|
||||
#[cfg(unix)]
|
||||
fn objects_attempted(log: &std::path::Path) -> usize {
|
||||
std::fs::read_to_string(log)
|
||||
.unwrap_or_default()
|
||||
|
||||
@@ -306,15 +306,10 @@ async fn main() -> Result<()> {
|
||||
let (ref_update_tx, _) = tokio::sync::broadcast::channel::<state::RefUpdateBroadcast>(256);
|
||||
let (task_event_tx, _) = tokio::sync::broadcast::channel::<state::TaskEventBroadcast>(256);
|
||||
|
||||
// Node-keyed, so continuation tokens this node mints are only accepted by
|
||||
// this node and survive its restarts without any configured secret.
|
||||
let task_cursor_key = api::task_cursor::TaskCursorKey::derive(&keypair.to_seed());
|
||||
|
||||
let graphql_schema = Arc::new(graphql::build_schema(
|
||||
Arc::clone(&db),
|
||||
ref_update_tx.clone(),
|
||||
task_event_tx.clone(),
|
||||
task_cursor_key.clone(),
|
||||
));
|
||||
|
||||
let machine_id = std::env::var("FLY_MACHINE_ID").ok();
|
||||
@@ -455,7 +450,6 @@ async fn main() -> Result<()> {
|
||||
db,
|
||||
node_did: node_did.clone(),
|
||||
node_keypair: keypair,
|
||||
task_cursor_key,
|
||||
p2p: p2p_handle,
|
||||
http_client,
|
||||
ref_update_tx,
|
||||
@@ -554,19 +548,11 @@ async fn main() -> Result<()> {
|
||||
std::time::Duration::from_secs(3600),
|
||||
200_000,
|
||||
),
|
||||
task_read_rate_limiter: rate_limit::RateLimiter::new_bounded(
|
||||
config.task_read_rate_limit,
|
||||
std::time::Duration::from_secs(3600),
|
||||
200_000,
|
||||
),
|
||||
git_bin: "git".to_string(),
|
||||
};
|
||||
if config.ipfs_rate_limit == 0 {
|
||||
tracing::warn!("GITLAWB_IPFS_RATE_LIMIT=0 — per-IP /ipfs rate limiting disabled");
|
||||
}
|
||||
if config.task_read_rate_limit == 0 {
|
||||
tracing::warn!("GITLAWB_TASK_READ_RATE_LIMIT=0 — per-IP task read rate limiting disabled");
|
||||
}
|
||||
|
||||
// Periodic peer-count poll for the metrics gauge. If p2p is disabled
|
||||
// we still set the gauge to 0 so dashboards don't show "no data".
|
||||
@@ -1201,8 +1187,6 @@ mod rate_limiter_sweep_tests {
|
||||
state.peer_write_rate_limiter = RateLimiter::new(10, window);
|
||||
state.federated_rate_limiter = RateLimiter::new(10, window);
|
||||
state.ipfs_rate_limiter = RateLimiter::new(10, window);
|
||||
state.ipfs_work_rate_limiter = RateLimiter::new(10, window);
|
||||
state.task_read_rate_limiter = RateLimiter::new(10, window);
|
||||
|
||||
let limiters = |s: &crate::state::AppState| {
|
||||
[
|
||||
@@ -1214,8 +1198,6 @@ mod rate_limiter_sweep_tests {
|
||||
s.peer_write_rate_limiter.clone(),
|
||||
s.federated_rate_limiter.clone(),
|
||||
s.ipfs_rate_limiter.clone(),
|
||||
s.ipfs_work_rate_limiter.clone(),
|
||||
s.task_read_rate_limiter.clone(),
|
||||
]
|
||||
};
|
||||
for l in limiters(&state) {
|
||||
|
||||
@@ -912,6 +912,7 @@ mod tests {
|
||||
/// probe carries its oid on stdin rather than in argv, so an oid appears in the log only
|
||||
/// once an object has already got past its probe, and a healthy object costs two
|
||||
/// invocations to a faulting one's one.
|
||||
#[cfg(unix)]
|
||||
fn objects_attempted(log: &std::path::Path) -> usize {
|
||||
std::fs::read_to_string(log)
|
||||
.unwrap_or_default()
|
||||
|
||||
@@ -296,7 +296,7 @@ pub async fn rate_limit_by_did(request: Request, next: Next) -> Response {
|
||||
return (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
[("retry-after", "60")],
|
||||
RATE_LIMIT_MESSAGE,
|
||||
"rate limit exceeded — try again later",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
@@ -401,11 +401,6 @@ 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).
|
||||
@@ -413,60 +408,11 @@ pub fn too_many_requests() -> Response {
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
[("retry-after", "60")],
|
||||
RATE_LIMIT_MESSAGE,
|
||||
"rate limit exceeded — try again later",
|
||||
)
|
||||
.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).
|
||||
/// 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 {
|
||||
/// 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;
|
||||
};
|
||||
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;
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use async_graphql::http::ALL_WEBSOCKET_PROTOCOLS;
|
||||
use async_graphql_axum::{GraphQLProtocol, GraphQLRequest, GraphQLResponse, GraphQLWebSocket};
|
||||
use axum::extract::{DefaultBodyLimit, WebSocketUpgrade};
|
||||
use async_graphql_axum::{GraphQLRequest, GraphQLResponse, GraphQLSubscription};
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::{
|
||||
extract::State,
|
||||
middleware,
|
||||
@@ -24,8 +23,6 @@ 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.
|
||||
@@ -35,49 +32,9 @@ 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),
|
||||
request_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
|
||||
});
|
||||
state.graphql_schema.execute(inner).await.into()
|
||||
}
|
||||
|
||||
async fn graphql_ws_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
rate_limit::PeerAddr(peer): rate_limit::PeerAddr,
|
||||
auth: Option<axum::Extension<auth::AuthenticatedDid>>,
|
||||
protocol: GraphQLProtocol,
|
||||
upgrade: WebSocketUpgrade,
|
||||
) -> axum::response::Response {
|
||||
let mut data = async_graphql::Data::default();
|
||||
if let Some(axum::Extension(did)) = auth {
|
||||
data.insert(did);
|
||||
}
|
||||
data.insert(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)),
|
||||
});
|
||||
let schema = state.graphql_schema.as_ref().clone();
|
||||
upgrade
|
||||
.protocols(ALL_WEBSOCKET_PROTOCOLS)
|
||||
.on_upgrade(move |stream| {
|
||||
GraphQLWebSocket::new(stream, schema, protocol)
|
||||
.with_data(data)
|
||||
.serve()
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn graphql_playground() -> impl IntoResponse {
|
||||
axum::response::Html(async_graphql::http::playground_source(
|
||||
async_graphql::http::GraphQLPlaygroundConfig::new("/graphql")
|
||||
@@ -120,14 +77,17 @@ fn add_auth_layers(
|
||||
|
||||
pub fn build_router(state: AppState) -> Router {
|
||||
// ── GraphQL routes ─────────────────────────────────────────────────────
|
||||
let schema = state.graphql_schema.as_ref().clone();
|
||||
let graphql_routes = Router::new()
|
||||
.route("/graphql", get(graphql_playground).post(graphql_handler))
|
||||
.route("/graphql/ws", get(graphql_ws_handler))
|
||||
// Attach the verified DID to /graphql and /graphql/ws when a signature is present.
|
||||
// Attach the verified DID to /graphql when a signature is present. The
|
||||
// layer covers only routes added before it, so /graphql/ws (added after,
|
||||
// read-only subscriptions) stays open.
|
||||
.layer(middleware::from_fn_with_state(
|
||||
auth::SignatureBodyLimit(SIGNED_BODY_LIMIT),
|
||||
auth::optional_signature,
|
||||
));
|
||||
))
|
||||
.route_service("/graphql/ws", GraphQLSubscription::new(schema));
|
||||
|
||||
// ── Task routes (write — require HTTP Signature) ───────────────────────
|
||||
let task_write_routes = add_auth_layers(
|
||||
@@ -140,31 +100,10 @@ pub fn build_router(state: AppState) -> Router {
|
||||
SIGNED_BODY_LIMIT,
|
||||
);
|
||||
|
||||
// ── Task routes (read — open, but scoped) ──────────────────────────────
|
||||
// `optional_signature` attaches the verified DID when a signature is present
|
||||
// so the handlers can identify the caller; the routes stay anonymous-reachable,
|
||||
// but each task/row is gated to its delegator, its assignee, or (for a
|
||||
// repo-scoped task) whoever can read that repo (#268 — these routes previously
|
||||
// carried no gate and no identity at all).
|
||||
// Both routes also carry a per-IP flood brake, mirroring `/ipfs/{cid}`: they are
|
||||
// anon-reachable and the gate above costs a task lookup plus deduped-repo and
|
||||
// visibility-rule queries *before* the opaque 404, so a prober pays nothing and
|
||||
// the node pays per request. The limiter is the outermost layer so a flood is
|
||||
// rejected before signature verification and the visibility queries run. The
|
||||
// extension MUST be attached or `rate_limit_by_ip` is a silent no-op.
|
||||
let task_read_limiter = rate_limit::IpRateLimiter {
|
||||
limiter: state.task_read_rate_limiter.clone(),
|
||||
trust: state.push_limiter_trust,
|
||||
};
|
||||
// ── Task routes (read — open) ──────────────────────────────────────────
|
||||
let task_read_routes = Router::new()
|
||||
.route("/api/v1/tasks", get(tasks::list_tasks))
|
||||
.route("/api/v1/tasks/{id}", get(tasks::get_task))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
auth::SignatureBodyLimit(SIGNED_BODY_LIMIT),
|
||||
auth::optional_signature,
|
||||
))
|
||||
.layer(middleware::from_fn(rate_limit::rate_limit_by_ip))
|
||||
.layer(axum::Extension(task_read_limiter));
|
||||
.route("/api/v1/tasks/{id}", get(tasks::get_task));
|
||||
|
||||
// ── Rate-limited creation routes — require HTTP Signature, plus a per-DID
|
||||
// throttle AND a per-IP flood brake. The per-DID limiter (inner) caps a
|
||||
@@ -776,349 +715,13 @@ async fn p2p_info(State(state): State<AppState>) -> Json<serde_json::Value> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::test_state;
|
||||
use sqlx::PgPool;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
async fn ws_send_text(stream: &mut tokio::net::TcpStream, text: &str) {
|
||||
let payload = text.as_bytes();
|
||||
let len = payload.len();
|
||||
let mut frame = Vec::new();
|
||||
frame.push(0x81);
|
||||
let mask = [0x12, 0x34, 0x56, 0x78];
|
||||
if len <= 125 {
|
||||
frame.push(0x80 | (len as u8));
|
||||
} else if len <= 65535 {
|
||||
frame.push(0x80 | 126);
|
||||
frame.extend_from_slice(&(len as u16).to_be_bytes());
|
||||
} else {
|
||||
frame.push(0x80 | 127);
|
||||
frame.extend_from_slice(&(len as u64).to_be_bytes());
|
||||
}
|
||||
frame.extend_from_slice(&mask);
|
||||
for (i, b) in payload.iter().enumerate() {
|
||||
frame.push(b ^ mask[i % 4]);
|
||||
}
|
||||
stream.write_all(&frame).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
}
|
||||
|
||||
async fn ws_recv_text(stream: &mut tokio::net::TcpStream) -> String {
|
||||
let mut header = [0u8; 2];
|
||||
stream.read_exact(&mut header).await.unwrap();
|
||||
let b1 = header[1];
|
||||
let masked = (b1 & 0x80) != 0;
|
||||
let mut len = (b1 & 0x7f) as usize;
|
||||
if len == 126 {
|
||||
let mut ext = [0u8; 2];
|
||||
stream.read_exact(&mut ext).await.unwrap();
|
||||
len = u16::from_be_bytes(ext) as usize;
|
||||
} else if len == 127 {
|
||||
let mut ext = [0u8; 8];
|
||||
stream.read_exact(&mut ext).await.unwrap();
|
||||
len = u64::from_be_bytes(ext) as usize;
|
||||
}
|
||||
let mask = if masked {
|
||||
let mut m = [0u8; 4];
|
||||
stream.read_exact(&mut m).await.unwrap();
|
||||
Some(m)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut payload = vec![0u8; len];
|
||||
stream.read_exact(&mut payload).await.unwrap();
|
||||
if let Some(m) = mask {
|
||||
for (i, b) in payload.iter_mut().enumerate() {
|
||||
*b ^= m[i % 4];
|
||||
}
|
||||
}
|
||||
String::from_utf8(payload).unwrap()
|
||||
}
|
||||
|
||||
async fn ws_recv_op_frames(stream: &mut tokio::net::TcpStream, op_id: &str) -> Vec<String> {
|
||||
let mut frames = Vec::new();
|
||||
loop {
|
||||
let text = ws_recv_text(stream).await;
|
||||
frames.push(text.clone());
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
if v.get("id").and_then(|id| id.as_str()) == Some(op_id) {
|
||||
let msg_type = v.get("type").and_then(|t| t.as_str()).unwrap_or("");
|
||||
if msg_type == "complete" || msg_type == "error" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
async fn connect_ws(addr: std::net::SocketAddr) -> tokio::net::TcpStream {
|
||||
let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
|
||||
let req = format!(
|
||||
"GET /graphql/ws HTTP/1.1\r\n\
|
||||
Host: {}\r\n\
|
||||
Upgrade: websocket\r\n\
|
||||
Connection: Upgrade\r\n\
|
||||
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
|
||||
Sec-WebSocket-Version: 13\r\n\
|
||||
Sec-WebSocket-Protocol: graphql-transport-ws\r\n\r\n",
|
||||
addr
|
||||
);
|
||||
stream.write_all(req.as_bytes()).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
|
||||
let mut buf = [0u8; 1024];
|
||||
let n = stream.read(&mut buf).await.unwrap();
|
||||
let resp = String::from_utf8_lossy(&buf[..n]);
|
||||
assert!(resp.starts_with("HTTP/1.1 101 Switching Protocols"));
|
||||
|
||||
// Init connection
|
||||
ws_send_text(&mut stream, r#"{"type":"connection_init"}"#).await;
|
||||
let ack = ws_recv_text(&mut stream).await;
|
||||
assert!(ack.contains("connection_ack"));
|
||||
|
||||
stream
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn graphql_ws_task_query_enforces_per_request_field_limit(pool: PgPool) {
|
||||
let state = test_state(pool).await;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let app = build_router(state);
|
||||
tokio::spawn(async move {
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let mut stream = connect_ws(addr).await;
|
||||
|
||||
// Query with 6 aliased task fields (exceeding MAX_GRAPHQL_TASK_READS_PER_REQUEST = 5)
|
||||
let query = r#"{"id":"1","type":"subscribe","payload":{"query":"query { f1: tasks { items { id } } f2: tasks { items { id } } f3: tasks { items { id } } f4: tasks { items { id } } f5: tasks { items { id } } f6: tasks { items { id } } }"}}"#;
|
||||
ws_send_text(&mut stream, query).await;
|
||||
let frames = ws_recv_op_frames(&mut stream, "1").await;
|
||||
let resp = frames.join("\n");
|
||||
assert!(
|
||||
resp.contains("rate limit exceeded"),
|
||||
"6th task field over WS must be braked: {resp}"
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn graphql_ws_task_query_enforces_per_ip_rate_limit(pool: PgPool) {
|
||||
let mut state = test_state(pool).await;
|
||||
// Restrict task read rate limiter to 1 request per 60s
|
||||
state.task_read_rate_limiter =
|
||||
crate::rate_limit::RateLimiter::new(1, std::time::Duration::from_secs(60));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let app = build_router(state);
|
||||
tokio::spawn(async move {
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let mut stream = connect_ws(addr).await;
|
||||
|
||||
// First task query succeeds (or returns valid data)
|
||||
let query1 = r#"{"id":"1","type":"subscribe","payload":{"query":"query { tasks { items { id } } }"}}"#;
|
||||
ws_send_text(&mut stream, query1).await;
|
||||
let frames1 = ws_recv_op_frames(&mut stream, "1").await;
|
||||
let resp1 = frames1.join("\n");
|
||||
assert!(!resp1.contains("rate limit exceeded"));
|
||||
|
||||
// Second task query on the same connection hits per-IP limiter
|
||||
let query2 = r#"{"id":"2","type":"subscribe","payload":{"query":"query { tasks { items { id } } }"}}"#;
|
||||
ws_send_text(&mut stream, query2).await;
|
||||
let frames2 = ws_recv_op_frames(&mut stream, "2").await;
|
||||
let resp2 = frames2.join("\n");
|
||||
assert!(
|
||||
resp2.contains("rate limit exceeded"),
|
||||
"exceeded per-IP limiter over WS must return rate limit message: {resp2}"
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn graphql_ws_task_query_resets_field_budget_per_operation(pool: PgPool) {
|
||||
let state = test_state(pool).await;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let app = build_router(state);
|
||||
tokio::spawn(async move {
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let mut stream = connect_ws(addr).await;
|
||||
|
||||
// Execute 6 sequential 1-field queries on the same connection.
|
||||
// Each operation must receive its own 5-field budget, so none are braked by the per-request limit.
|
||||
for i in 1..=6 {
|
||||
let id = i.to_string();
|
||||
let query = format!(
|
||||
r#"{{"id":"{id}","type":"subscribe","payload":{{"query":"query {{ tasks {{ items {{ id }} }} }}"}}}}"#
|
||||
);
|
||||
ws_send_text(&mut stream, &query).await;
|
||||
let frames = ws_recv_op_frames(&mut stream, &id).await;
|
||||
let resp = frames.join("\n");
|
||||
assert!(
|
||||
!resp.contains("rate limit exceeded"),
|
||||
"operation {id} on the same WS connection must have a fresh field budget: {resp}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_ws_signed(
|
||||
addr: std::net::SocketAddr,
|
||||
keypair: &gitlawb_core::identity::Keypair,
|
||||
) -> tokio::net::TcpStream {
|
||||
let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
|
||||
let signed = gitlawb_core::http_sig::sign_request(keypair, "GET", "/graphql/ws", b"");
|
||||
let req = format!(
|
||||
"GET /graphql/ws HTTP/1.1\r\n\
|
||||
Host: {}\r\n\
|
||||
Upgrade: websocket\r\n\
|
||||
Connection: Upgrade\r\n\
|
||||
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
|
||||
Sec-WebSocket-Version: 13\r\n\
|
||||
Sec-WebSocket-Protocol: graphql-transport-ws\r\n\
|
||||
content-digest: {}\r\n\
|
||||
signature-input: {}\r\n\
|
||||
signature: {}\r\n\r\n",
|
||||
addr, signed.content_digest, signed.signature_input, signed.signature
|
||||
);
|
||||
stream.write_all(req.as_bytes()).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
|
||||
let mut buf = [0u8; 1024];
|
||||
let n = stream.read(&mut buf).await.unwrap();
|
||||
let resp = String::from_utf8_lossy(&buf[..n]);
|
||||
assert!(resp.starts_with("HTTP/1.1 101 Switching Protocols"));
|
||||
|
||||
// Init connection
|
||||
ws_send_text(&mut stream, r#"{"type":"connection_init"}"#).await;
|
||||
let ack = ws_recv_text(&mut stream).await;
|
||||
assert!(ack.contains("connection_ack"));
|
||||
|
||||
stream
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn graphql_ws_authenticated_query_accesses_private_task(pool: PgPool) {
|
||||
let state = test_state(pool).await;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let app = build_router(state.clone());
|
||||
tokio::spawn(async move {
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let keypair = gitlawb_core::identity::Keypair::generate();
|
||||
let delegator_did = keypair.did().to_string();
|
||||
|
||||
let task = crate::db::AgentTask {
|
||||
id: "ws-auth-task-01".into(),
|
||||
repo_id: None,
|
||||
delegator_did: delegator_did.clone(),
|
||||
kind: "test".into(),
|
||||
capability: "read".into(),
|
||||
status: "pending".into(),
|
||||
assignee_did: Some(delegator_did.clone()),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: "2026-01-01T00:00:00Z".into(),
|
||||
updated_at: "2026-01-01T00:00:00Z".into(),
|
||||
deadline: None,
|
||||
};
|
||||
state.db.create_task(&task).await.unwrap();
|
||||
|
||||
// 1. Unauthenticated WS connection cannot see the private task
|
||||
let mut unauth_stream = connect_ws(addr).await;
|
||||
let query = r#"{"id":"1","type":"subscribe","payload":{"query":"query { tasks { items { id } } }"}}"#;
|
||||
ws_send_text(&mut unauth_stream, query).await;
|
||||
let unauth_frames = ws_recv_op_frames(&mut unauth_stream, "1").await;
|
||||
let unauth_resp = unauth_frames.join("\n");
|
||||
assert!(
|
||||
!unauth_resp.contains("ws-auth-task-01"),
|
||||
"unauthenticated WS must not disclose private task: {unauth_resp}"
|
||||
);
|
||||
|
||||
// 2. Forged signature claiming the delegator DID must be rejected at handshake
|
||||
let attacker_keypair = gitlawb_core::identity::Keypair::generate();
|
||||
let attacker_signed =
|
||||
gitlawb_core::http_sig::sign_request(&attacker_keypair, "GET", "/graphql/ws", b"");
|
||||
let forged_sig_input = attacker_signed
|
||||
.signature_input
|
||||
.replace(&attacker_keypair.did().to_string(), &delegator_did);
|
||||
let mut forged_stream = tokio::net::TcpStream::connect(addr).await.unwrap();
|
||||
let forged_req = format!(
|
||||
"GET /graphql/ws HTTP/1.1\r\n\
|
||||
Host: {}\r\n\
|
||||
Upgrade: websocket\r\n\
|
||||
Connection: Upgrade\r\n\
|
||||
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
|
||||
Sec-WebSocket-Version: 13\r\n\
|
||||
Sec-WebSocket-Protocol: graphql-transport-ws\r\n\
|
||||
content-digest: {}\r\n\
|
||||
signature-input: {}\r\n\
|
||||
signature: {}\r\n\r\n",
|
||||
addr, attacker_signed.content_digest, forged_sig_input, attacker_signed.signature
|
||||
);
|
||||
forged_stream
|
||||
.write_all(forged_req.as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
forged_stream.flush().await.unwrap();
|
||||
let mut forged_bytes = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
while !forged_bytes.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
let n = forged_stream.read(&mut chunk).await.unwrap();
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
forged_bytes.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
let forged_resp = String::from_utf8_lossy(&forged_bytes);
|
||||
assert!(
|
||||
forged_resp.starts_with("HTTP/1.1 401 Unauthorized"),
|
||||
"forged WS signature must be rejected with 401: {forged_resp}"
|
||||
);
|
||||
|
||||
// 3. Signed WS connection authenticates caller and retrieves the private task
|
||||
let mut auth_stream = connect_ws_signed(addr, &keypair).await;
|
||||
ws_send_text(&mut auth_stream, query).await;
|
||||
let auth_frames = ws_recv_op_frames(&mut auth_stream, "1").await;
|
||||
let auth_resp = auth_frames.join("\n");
|
||||
assert!(
|
||||
auth_resp.contains("ws-auth-task-01"),
|
||||
"signed WS must authenticate delegator and return private task: {auth_resp}"
|
||||
);
|
||||
}
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
use crate::db::RepoRecord;
|
||||
use crate::test_support::test_state;
|
||||
|
||||
/// Regression: anonymous callers must not see the pin/anchor index (#121, #134).
|
||||
#[sqlx::test]
|
||||
|
||||
@@ -59,10 +59,6 @@ pub struct AppState {
|
||||
pub task_event_tx: tokio::sync::broadcast::Sender<TaskEventBroadcast>,
|
||||
/// GraphQL schema (queries + mutations + subscriptions)
|
||||
pub graphql_schema: Arc<crate::graphql::GitlawbSchema>,
|
||||
/// MAC key for task-list continuation tokens, derived from the node
|
||||
/// keypair seed. Held here (and handed to the GraphQL schema) so REST and
|
||||
/// GraphQL mint and accept the same tokens.
|
||||
pub task_cursor_key: crate::api::task_cursor::TaskCursorKey,
|
||||
/// Fly.io machine ID — used for fly-replay routing in multi-machine deployments
|
||||
pub machine_id: Option<String>,
|
||||
/// Centralized repo storage: local disk cache + optional Tigris backend
|
||||
@@ -330,16 +326,6 @@ pub struct AppState {
|
||||
/// (`with_default_max_keys`, reject-before-insert) so a source-key farm cannot grow
|
||||
/// it (INV-15).
|
||||
pub git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency,
|
||||
/// Per-client-IP rate limiter for the task read routes. `GET /api/v1/tasks`
|
||||
/// and `GET /api/v1/tasks/{id}` are anonymously reachable and run the #268
|
||||
/// visibility gate (a task lookup plus deduped-repo and visibility-rule
|
||||
/// queries) before returning the opaque 404, so an unauthenticated prober
|
||||
/// costs the node real work per request whether or not anything is visible.
|
||||
/// Keyed on the resolved client IP via `push_limiter_trust`. Layered on
|
||||
/// `task_read_routes` via `rate_limit_by_ip`.
|
||||
/// The same per-IP hourly budget applies to GraphQL `tasks` / `task`
|
||||
/// queries and WebSocket task queries via `TaskReadBrake`.
|
||||
pub task_read_rate_limiter: RateLimiter,
|
||||
/// The `git` executable the served-git withheld-blob walk spawns. Production is
|
||||
/// `"git"` (resolved via PATH); injectable so a fake `git` can drive the walk's
|
||||
/// process-group teardown in handler tests without mutating the process-global
|
||||
@@ -368,7 +354,6 @@ impl AppState {
|
||||
self.ipfs_work_rate_limiter.cleanup().await;
|
||||
self.sync_trigger_rate_limiter.cleanup().await;
|
||||
self.peer_write_rate_limiter.cleanup().await;
|
||||
self.task_read_rate_limiter.cleanup().await;
|
||||
self.federated_rate_limiter.cleanup().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -1330,6 +1330,18 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Use a rooted path without a Windows drive prefix in the remote fixture.
|
||||
/// The destination still resolves on the temp directory's current drive,
|
||||
/// while the remote's relative path contains no illegal colon component.
|
||||
fn absolute_slug_path(path: &Path) -> String {
|
||||
assert!(path.is_absolute());
|
||||
path.components()
|
||||
.filter(|part| !matches!(part, std::path::Component::Prefix(_)))
|
||||
.collect::<std::path::PathBuf>()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn process_batch_rejects_slug_escaping_repos_dir(pool: PgPool) {
|
||||
// The verified escape from #272: `PathBuf::join` discards everything
|
||||
@@ -1345,12 +1357,13 @@ mod tests {
|
||||
// fails on but leaves the parent it created, so assert on both.
|
||||
let outside = TempDir::new().unwrap();
|
||||
let escape_dir = outside.path().join("nest");
|
||||
let slug = format!("a/{}/escape", escape_dir.display());
|
||||
let escape_path = absolute_slug_path(&escape_dir);
|
||||
let slug = format!("a/{escape_path}/escape");
|
||||
let escape_target = escape_dir.join("escape.git");
|
||||
|
||||
// Serve the composed URL for real, so a run without the guard genuinely
|
||||
// clones outside the root rather than merely failing at git.
|
||||
let rel = format!("a{}/escape", escape_dir.display());
|
||||
let rel = format!("a{escape_path}/escape");
|
||||
let (_remote, peer_url) = rooted_remote(&[&rel]);
|
||||
|
||||
let did = "did:key:z6MkAttacker";
|
||||
@@ -1470,6 +1483,7 @@ mod tests {
|
||||
// ── canonical containment before the git call (issue #272) ───────────────
|
||||
|
||||
/// Every ref in `repo`, as one string, for a before/after comparison.
|
||||
#[cfg(unix)]
|
||||
fn refs_of(repo: &Path) -> String {
|
||||
let out = Command::new("git")
|
||||
.args(["-C", repo.to_str().unwrap(), "for-each-ref"])
|
||||
@@ -1802,6 +1816,7 @@ mod tests {
|
||||
/// starvation tests is fixed rather than dependent on how fast the loop
|
||||
/// runs. Two rows enqueued in the same microsecond would otherwise order
|
||||
/// arbitrarily.
|
||||
#[cfg(unix)]
|
||||
async fn enqueue_at(db: &Db, pool: &PgPool, repo: &str, did: &str, enqueued_at: &str) {
|
||||
enqueue(db, repo, did).await;
|
||||
sqlx::query("UPDATE sync_queue SET enqueued_at = $1 WHERE repo = $2")
|
||||
@@ -1995,7 +2010,8 @@ mod tests {
|
||||
|
||||
let outside = TempDir::new().unwrap();
|
||||
let escape_dir = outside.path().join("nest");
|
||||
let slug = format!("a/{}/gitlawb-probe", escape_dir.display());
|
||||
let escape_path = absolute_slug_path(&escape_dir);
|
||||
let slug = format!("a/{escape_path}/gitlawb-probe");
|
||||
let escape_target = escape_dir.join("gitlawb-probe.git");
|
||||
|
||||
// Two things this fixture must get right or the test is green for the
|
||||
@@ -2006,7 +2022,7 @@ mod tests {
|
||||
// run without the guard genuinely clones outside the root instead of
|
||||
// just failing at git. Db::upsert_peer cannot seed this row: it gates on
|
||||
// is_public_http_url, which rejects file://.
|
||||
let rel = format!("a{}/gitlawb-probe", escape_dir.display());
|
||||
let rel = format!("a{escape_path}/gitlawb-probe");
|
||||
let (_remote, peer_url) = rooted_remote(&[&rel]);
|
||||
let did = "did:key:z6MkAttacker";
|
||||
seed_local_peer(&pool, did, &peer_url).await;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Native Git fixtures shared by timing tests on Unix and Windows.
|
||||
|
||||
use std::ops::Deref;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The fixture delays or hangs in its own process, so the production watchdog
|
||||
/// can terminate it without depending on a shell or descendant process support.
|
||||
pub(super) enum Behavior<'a> {
|
||||
Delay(u64),
|
||||
Hang,
|
||||
HangOid(&'a str),
|
||||
HangRepo(&'a str),
|
||||
LogTypes(&'a Path),
|
||||
}
|
||||
|
||||
pub(super) struct GitShim {
|
||||
_directory: tempfile::TempDir,
|
||||
executable: PathBuf,
|
||||
}
|
||||
|
||||
impl Deref for GitShim {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Path {
|
||||
&self.executable
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create(name: &str, behavior: Behavior<'_>) -> GitShim {
|
||||
static COMPILED: OnceLock<tempfile::TempDir> = OnceLock::new();
|
||||
let compiled = COMPILED.get_or_init(|| {
|
||||
let directory = tempfile::tempdir().expect("native Git fixture directory");
|
||||
let source = directory.path().join("git_shim.rs");
|
||||
std::fs::write(&source, include_str!("../tests/fixtures/git_shim.rs"))
|
||||
.expect("write native Git fixture source");
|
||||
let executable = directory
|
||||
.path()
|
||||
.join(format!("git-shim{}", std::env::consts::EXE_SUFFIX));
|
||||
let output =
|
||||
std::process::Command::new(std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()))
|
||||
.arg("--edition=2021")
|
||||
.arg("-Dwarnings")
|
||||
.arg(&source)
|
||||
.arg("-o")
|
||||
.arg(executable)
|
||||
.output()
|
||||
.expect("compile native Git fixture with the installed Rust toolchain");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
directory
|
||||
});
|
||||
let directory = tempfile::Builder::new()
|
||||
.prefix(name)
|
||||
.tempdir()
|
||||
.expect("Git fixture instance");
|
||||
let file_name = format!("git-shim{}", std::env::consts::EXE_SUFFIX);
|
||||
let executable = directory.path().join(&file_name);
|
||||
std::fs::copy(compiled.path().join(file_name), &executable).expect("copy native Git fixture");
|
||||
let config = match behavior {
|
||||
Behavior::Delay(milliseconds) => format!("delay\n{milliseconds}"),
|
||||
Behavior::Hang => "hang\n".to_owned(),
|
||||
Behavior::HangOid(oid) => format!("hang-oid\n{oid}"),
|
||||
Behavior::HangRepo(repo) => format!("hang-repo\n{repo}"),
|
||||
Behavior::LogTypes(path) => format!("log-types\n{}", path.display()),
|
||||
};
|
||||
std::fs::write(directory.path().join("config"), config).expect("configure native Git fixture");
|
||||
GitShim {
|
||||
_directory: directory,
|
||||
executable,
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ use gitlawb_core::identity::Keypair;
|
||||
use crate::auth::AuthenticatedDid;
|
||||
use crate::state::AppState;
|
||||
|
||||
#[path = "test_git_shim.rs"]
|
||||
mod git_shim;
|
||||
|
||||
/// Build an [`AppState`] over a real, migrated Postgres pool (from `#[sqlx::test]`).
|
||||
/// Runs the schema migrations first, because the per-test database starts empty.
|
||||
///
|
||||
@@ -83,12 +86,10 @@ fn build_state(db: Arc<crate::db::Db>, pool: PgPool) -> AppState {
|
||||
let node_did = keypair.did();
|
||||
let (ref_tx, _) = tokio::sync::broadcast::channel(1);
|
||||
let (task_tx, _) = tokio::sync::broadcast::channel(1);
|
||||
let task_cursor_key = crate::api::task_cursor::TaskCursorKey::derive(&keypair.to_seed());
|
||||
let schema = Arc::new(graphql::build_schema(
|
||||
db.clone(),
|
||||
ref_tx.clone(),
|
||||
task_tx.clone(),
|
||||
task_cursor_key.clone(),
|
||||
));
|
||||
AppState {
|
||||
config: Arc::new(Config::parse_from(["gitlawb-node"])),
|
||||
@@ -100,7 +101,6 @@ fn build_state(db: Arc<crate::db::Db>, pool: PgPool) -> AppState {
|
||||
ref_update_tx: ref_tx,
|
||||
task_event_tx: task_tx,
|
||||
graphql_schema: schema,
|
||||
task_cursor_key,
|
||||
machine_id: None,
|
||||
repo_store: crate::git::repo_store::RepoStore::for_testing(PathBuf::from("/tmp"), pool),
|
||||
rate_limiter: RateLimiter::new(100, Duration::from_secs(60)),
|
||||
@@ -139,7 +139,6 @@ fn build_state(db: Arc<crate::db::Db>, pool: PgPool) -> AppState {
|
||||
git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys(
|
||||
16,
|
||||
),
|
||||
task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)),
|
||||
git_bin: "git".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -563,11 +562,12 @@ mod tests {
|
||||
/// #174 (SC1, load-bearing): a saturated READ pool must NOT shed an
|
||||
/// authenticated push — the write pool is a separate budget. Read pool at zero,
|
||||
/// write pool with capacity: the push proceeds PAST admission (it then errors on
|
||||
/// the placeholder DB, but crucially it is not a 503). Route git-receive-pack
|
||||
/// the closed DB, with db_unavailable rather than overloaded). Route git-receive-pack
|
||||
/// back to the read pool and this goes red — that is the isolation proof.
|
||||
#[tokio::test]
|
||||
async fn git_receive_pack_not_shed_by_exhausted_read_pool() {
|
||||
let mut state = test_state_lazy();
|
||||
state.db.pool().close().await;
|
||||
// Read pool exhausted as if a flood of anonymous clones held every slot.
|
||||
state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0));
|
||||
// Write pool keeps its default capacity from test_state_lazy.
|
||||
@@ -589,10 +589,13 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(
|
||||
resp.status(),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"an exhausted READ pool must not shed a push — the write pool is a separate budget (#174)"
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
body["error"],
|
||||
crate::error::DB_UNAVAILABLE_CODE,
|
||||
"the push must clear admission and reach the deliberately closed database"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1112,7 +1115,7 @@ mod tests {
|
||||
// repo id afterwards — a 403 that still writes is the injection.
|
||||
let stored = state
|
||||
.db
|
||||
.list_tasks_keyset(None, None, 50, None)
|
||||
.list_tasks(None, None, 50)
|
||||
.await
|
||||
.expect("list tasks");
|
||||
assert!(
|
||||
@@ -1471,11 +1474,11 @@ mod tests {
|
||||
let assignee = "did:key:zTASKASSIGNEEBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
|
||||
let stranger = "did:key:zTASKSTRANGERCCCCCCCCCCCCCCCCCCCCCCCCCCC";
|
||||
let state = test_state(pool).await;
|
||||
let repo = seed_repo(delegator, "task-pub-repo");
|
||||
state.db.create_repo(&repo).await.expect("seed repo");
|
||||
let mut t1 = seed_task("task-1", delegator);
|
||||
t1.repo_id = Some(repo.id);
|
||||
state.db.create_task(&t1).await.expect("seed task");
|
||||
state
|
||||
.db
|
||||
.create_task(&seed_task("task-1", delegator))
|
||||
.await
|
||||
.expect("seed task");
|
||||
// Assignee claims it: pending -> claimed, assignee_did = assignee.
|
||||
state
|
||||
.db
|
||||
@@ -1494,25 +1497,8 @@ mod tests {
|
||||
let uri = "/api/v1/tasks/task-1/complete";
|
||||
let body = || Body::from("{}");
|
||||
|
||||
// Stranger on an invisible (repo-less) task receives opaque 404 (no existence leak).
|
||||
let inv_task = seed_task("task-inv", delegator);
|
||||
state.db.create_task(&inv_task).await.unwrap();
|
||||
let inv_resp = router()
|
||||
.oneshot(signed_request_as(
|
||||
stranger,
|
||||
Method::POST,
|
||||
"/api/v1/tasks/task-inv/complete",
|
||||
body(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
inv_resp.status(),
|
||||
StatusCode::NOT_FOUND,
|
||||
"an invisible task must 404 so existence is not leaked"
|
||||
);
|
||||
|
||||
// Stranger on a visible task is rejected by the authorization gate with exact 403.
|
||||
// Stranger (not the assignee) is rejected by the authorization gate, even
|
||||
// with the empty body that previously bypassed the binding. Exact 403.
|
||||
let resp = router()
|
||||
.oneshot(signed_request_as(stranger, Method::POST, uri, body()))
|
||||
.await
|
||||
@@ -1581,11 +1567,9 @@ mod tests {
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
// The claim gate hides existence: an ineligible claimer gets the same
|
||||
// 404 as a missing task, not a 403 that would reveal the reservation.
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
StatusCode::NOT_FOUND,
|
||||
StatusCode::FORBIDDEN,
|
||||
"stranger must not steal a pre-assigned task, got {}",
|
||||
resp.status()
|
||||
);
|
||||
@@ -1751,7 +1735,7 @@ mod tests {
|
||||
);
|
||||
let listed_bare = state
|
||||
.db
|
||||
.list_tasks_keyset(Some("claimed"), Some(bare), 10, None)
|
||||
.list_tasks(Some("claimed"), Some(bare), 10)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
@@ -1760,14 +1744,12 @@ mod tests {
|
||||
);
|
||||
let listed_full = state
|
||||
.db
|
||||
.list_tasks_keyset(Some("claimed"), Some(&full), 10, None)
|
||||
.list_tasks(Some("claimed"), Some(&full), 10)
|
||||
.await
|
||||
.unwrap();
|
||||
// The keyset filter normalizes to the did:key short form, so the
|
||||
// claimer's full DID now matches the bare stored form too.
|
||||
assert!(
|
||||
listed_full.iter().any(|t| t.id == "task-form"),
|
||||
"normalized list by claimer's full DID must match the bare stored form"
|
||||
!listed_full.iter().any(|t| t.id == "task-form"),
|
||||
"exact list by claimer's full DID must miss the bare stored form"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1804,7 +1786,7 @@ mod tests {
|
||||
);
|
||||
let listed = state
|
||||
.db
|
||||
.list_tasks_keyset(Some("claimed"), Some(&padded), 10, None)
|
||||
.list_tasks(Some("claimed"), Some(&padded), 10)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
@@ -11220,14 +11202,10 @@ mod tests {
|
||||
seed_legacy_pin(&pool, &bare, &fx.public_oid, Some(&repo.id)).await;
|
||||
|
||||
// A git that takes 300ms per invocation (the read makes two: type, then content).
|
||||
let slow_git = std::env::temp_dir().join(format!("gl-slow-git-{short}"));
|
||||
std::fs::write(&slow_git, "#!/bin/sh\nsleep 0.3\nexec git \"$@\"\n").expect("write shim");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&slow_git, std::fs::Permissions::from_mode(0o755))
|
||||
.expect("chmod shim");
|
||||
}
|
||||
let slow_git = git_shim::create(
|
||||
&format!("gl-slow-git-{short}"),
|
||||
git_shim::Behavior::Delay(300),
|
||||
);
|
||||
|
||||
let ticks = std::sync::Arc::new(AtomicUsize::new(0));
|
||||
let ticker = {
|
||||
@@ -12174,19 +12152,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Write an executable `git` stand-in and return its path.
|
||||
fn write_git_shim(name: &str, script: &str) -> std::path::PathBuf {
|
||||
let path = std::env::temp_dir().join(name);
|
||||
std::fs::write(&path, script).expect("write the git shim");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
|
||||
.expect("chmod the git shim");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// F6 scenario 1 (#173 round 13): one hung candidate must not starve the rows behind
|
||||
/// it in the same pass. `DiscoveryCtx` is loaded once per pass, so before the per-row
|
||||
/// slice every source-less row in a pass shared ONE deadline: the first row's wedged
|
||||
@@ -12226,23 +12191,9 @@ mod tests {
|
||||
|
||||
// The type stage feeds the oid on STDIN (`cat-file --batch-check`) and the
|
||||
// content stage puts it in argv, so the stand-in has to look in both places.
|
||||
let git_bin = write_git_shim(
|
||||
let git_bin = git_shim::create(
|
||||
&format!("gl-hung-git-{short}"),
|
||||
&format!(
|
||||
"#!/bin/sh\n\
|
||||
if [ \"$2\" = \"--batch-check\" ]; then\n\
|
||||
\x20 oid=$(cat)\n\
|
||||
\x20 case \"$oid\" in\n\
|
||||
\x20 {hung_oid}) sleep 30; exit 1 ;;\n\
|
||||
\x20 esac\n\
|
||||
\x20 printf '%s\\n' \"$oid\" | git \"$@\"\n\
|
||||
\x20 exit $?\n\
|
||||
fi\n\
|
||||
case \"$*\" in\n\
|
||||
\x20 *{hung_oid}*) sleep 30; exit 1 ;;\n\
|
||||
esac\n\
|
||||
exec git \"$@\"\n"
|
||||
),
|
||||
git_shim::Behavior::HangOid(&hung_oid),
|
||||
);
|
||||
|
||||
let stats = tokio::time::timeout(
|
||||
@@ -12327,10 +12278,7 @@ mod tests {
|
||||
|
||||
// Wedges on every invocation, so no row can ever be repaired and the only
|
||||
// question left is what each one COSTS.
|
||||
let git_bin = write_git_shim(
|
||||
&format!("gl-spent-git-{short}"),
|
||||
"#!/bin/sh\nsleep 30\nexit 1\n",
|
||||
);
|
||||
let git_bin = git_shim::create(&format!("gl-spent-git-{short}"), git_shim::Behavior::Hang);
|
||||
|
||||
let stats = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(60),
|
||||
@@ -12934,10 +12882,7 @@ mod tests {
|
||||
seed_legacy_pin(&pool, &src, oid, None).await;
|
||||
}
|
||||
|
||||
let git_bin = write_git_shim(
|
||||
&format!("gl-starve-git-{short}"),
|
||||
"#!/bin/sh\nsleep 30\nexit 1\n",
|
||||
);
|
||||
let git_bin = git_shim::create(&format!("gl-starve-git-{short}"), git_shim::Behavior::Hang);
|
||||
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(120),
|
||||
@@ -13005,9 +12950,9 @@ mod tests {
|
||||
let (raw_cid, provider_cid) = seed_legacy_pin(&pool, &src, &fx.public_oid, None).await;
|
||||
|
||||
// Wedges only inside the position-nine repo, which the sweep enters by cwd.
|
||||
let git_bin = write_git_shim(
|
||||
let git_bin = git_shim::create(
|
||||
&format!("gl-mid-git-{short}"),
|
||||
"#!/bin/sh\ncase \"$(pwd)\" in\n */midcand9.git) sleep 30; exit 1 ;;\nesac\nexec git \"$@\"\n",
|
||||
git_shim::Behavior::HangRepo("midcand9.git"),
|
||||
);
|
||||
|
||||
let first = tokio::time::timeout(
|
||||
@@ -13169,19 +13114,9 @@ mod tests {
|
||||
|
||||
let log = std::env::temp_dir().join(format!("gl-ali-log-{short}"));
|
||||
let _ = std::fs::remove_file(&log);
|
||||
let git_bin = write_git_shim(
|
||||
let git_bin = git_shim::create(
|
||||
&format!("gl-ali-git-{short}"),
|
||||
&format!(
|
||||
"#!/bin/sh\n\
|
||||
if [ \"$2\" = \"--batch-check\" ]; then\n\
|
||||
\x20 oid=$(cat)\n\
|
||||
\x20 printf '%s %s\\n' \"$oid\" \"$(basename $(pwd))\" >> {log}\n\
|
||||
\x20 printf '%s\\n' \"$oid\" | git \"$@\"\n\
|
||||
\x20 exit $?\n\
|
||||
fi\n\
|
||||
exec git \"$@\"\n",
|
||||
log = log.display()
|
||||
),
|
||||
git_shim::Behavior::LogTypes(&log),
|
||||
);
|
||||
|
||||
let mut traversal = crate::ipfs_pin::DiscoveryTraversalState::default();
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let executable = std::env::current_exe()?;
|
||||
let config = std::fs::read_to_string(executable.parent().unwrap().join("config"))?;
|
||||
let (mode, parameter) = config.split_once('\n').unwrap_or((&config, ""));
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if mode == "delay" {
|
||||
std::thread::sleep(Duration::from_millis(parameter.parse().unwrap()));
|
||||
}
|
||||
let batch = args.get(1).is_some_and(|arg| arg == "--batch-check");
|
||||
let input = if batch {
|
||||
let mut bytes = Vec::new();
|
||||
std::io::stdin().read_to_end(&mut bytes)?;
|
||||
Some(bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let cwd = std::env::current_dir()?;
|
||||
let hang = mode == "hang"
|
||||
|| (mode == "hang-repo" && cwd.file_name().is_some_and(|name| name == parameter))
|
||||
|| (mode == "hang-oid"
|
||||
&& (args.iter().any(|arg| arg == parameter)
|
||||
|| input
|
||||
.as_ref()
|
||||
.is_some_and(|bytes| String::from_utf8_lossy(bytes).trim() == parameter)));
|
||||
if hang {
|
||||
std::thread::sleep(Duration::from_secs(30));
|
||||
std::process::exit(1);
|
||||
}
|
||||
if mode == "log-types" && batch {
|
||||
let mut log = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(parameter)?;
|
||||
writeln!(
|
||||
log,
|
||||
"{} {}",
|
||||
String::from_utf8_lossy(input.as_ref().unwrap()).trim(),
|
||||
cwd.file_name().unwrap().to_string_lossy()
|
||||
)?;
|
||||
}
|
||||
let mut child = Command::new("git")
|
||||
.args(&args)
|
||||
.stdin(if input.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
})
|
||||
.stdout(Stdio::inherit())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()?;
|
||||
if let Some(bytes) = input {
|
||||
child.stdin.take().unwrap().write_all(&bytes)?;
|
||||
}
|
||||
std::process::exit(child.wait()?.code().unwrap_or(1));
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gl"
|
||||
description = "The Twigpine CLI — identity management, node control, MCP server"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -99,27 +99,6 @@ pub fn load_keypair_from_dir(dir: Option<&std::path::Path>) -> Result<Keypair> {
|
||||
Keypair::from_pem(&pem).context("failed to load keypair from PEM")
|
||||
}
|
||||
|
||||
/// Load keypair from an optional directory override, distinguishing missing default
|
||||
/// identity (clean anonymous) from an explicit directory error or corrupt PEM.
|
||||
pub fn load_optional_keypair(dir: Option<&std::path::Path>) -> Result<Option<Keypair>> {
|
||||
if let Some(d) = dir {
|
||||
return load_keypair_from_dir(Some(d)).map(Some);
|
||||
}
|
||||
let base = match dirs::home_dir() {
|
||||
Some(h) => h.join(".gitlawb"),
|
||||
None => return Ok(None),
|
||||
};
|
||||
let path = key_path(&base);
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(pem) => Keypair::from_pem(&pem)
|
||||
.context("failed to load keypair from PEM")
|
||||
.map(Some),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(anyhow::Error::from(e)
|
||||
.context(format!("failed to read identity from {}", path.display()))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn cmd_new(dir: Option<PathBuf>, force: bool) -> Result<()> {
|
||||
cmd_new_with_reader(dir, force, &mut std::io::stdin().lock()).await
|
||||
}
|
||||
|
||||
+13
-384
@@ -43,6 +43,7 @@ use std::io::{BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::http::NodeClient;
|
||||
use crate::identity::load_keypair_from_dir;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct McpArgs {
|
||||
@@ -515,8 +516,7 @@ fn tool_definitions() -> Value {
|
||||
"properties": {
|
||||
"status": { "type": "string", "description": "Filter by status: pending, claimed, completed, failed" },
|
||||
"assignee_did": { "type": "string", "description": "Filter by assignee DID" },
|
||||
"limit": { "type": "integer", "minimum": 1, "description": "Total results to return (default: 50). Must be positive; a non-positive limit is rejected rather than answered with an empty list. Values above the node's 200-row page cap are gathered by following continuation tokens.", "default": 50 },
|
||||
"cursor": { "type": "string", "description": "Resume from a previous call's next_cursor. Must be paired with the same status/assignee_did filter that produced it." }
|
||||
"limit": { "type": "integer", "description": "Max results (default: 50)", "default": 50 }
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -640,14 +640,7 @@ async fn call_tool(
|
||||
node: &str,
|
||||
dir: Option<&std::path::Path>,
|
||||
) -> Result<String> {
|
||||
// An explicit dir with no identity file is a clean anonymous caller
|
||||
// (main's unsigned `webhook_list` path lets the node answer the denial);
|
||||
// a present but unloadable identity is an error, never a silent
|
||||
// downgrade to anonymous (this PR's `load_optional_keypair` contract).
|
||||
let keypair = match dir {
|
||||
Some(d) if !d.join("identity.pem").exists() => None,
|
||||
_ => crate::identity::load_optional_keypair(dir)?,
|
||||
};
|
||||
let keypair = load_keypair_from_dir(dir).ok();
|
||||
let client = NodeClient::new(node, keypair.clone());
|
||||
|
||||
match name {
|
||||
@@ -1121,31 +1114,16 @@ async fn call_tool(
|
||||
|
||||
// ── Task tools ────────────────────────────────────────────────────
|
||||
"task_list" => {
|
||||
// Follows the node's opaque `next_cursor` so a limit above the
|
||||
// 200-row server page cap returns what was asked for instead of a
|
||||
// silently truncated page, and reports an explicit incomplete
|
||||
// result when a guard or the node's scan ceiling stops it (#327).
|
||||
let limit = match args.get("limit") {
|
||||
None | Some(Value::Null) => 50,
|
||||
Some(val) => val.as_i64().context("invalid limit: expected an integer")?,
|
||||
};
|
||||
let cursor = match args.get("cursor") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(val) => Some(val.as_str().context("invalid cursor: expected a string")?),
|
||||
};
|
||||
let result = crate::task::fetch_tasks(
|
||||
&client,
|
||||
args.get("status").and_then(|v| v.as_str()),
|
||||
args.get("assignee_did").and_then(|v| v.as_str()),
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
.await?;
|
||||
let mut out = result.to_json();
|
||||
if let Some(warning) = result.truncation_warning() {
|
||||
out["warning"] = Value::String(warning);
|
||||
let limit = args["limit"].as_i64().unwrap_or(50);
|
||||
let mut path = format!("/api/v1/tasks?limit={limit}");
|
||||
if let Some(s) = args.get("status").and_then(|v| v.as_str()) {
|
||||
path.push_str(&format!("&status={}", urlencoding::encode(s)));
|
||||
}
|
||||
Ok(serde_json::to_string_pretty(&out)?)
|
||||
if let Some(a) = args.get("assignee_did").and_then(|v| v.as_str()) {
|
||||
path.push_str(&format!("&assignee_did={}", urlencoding::encode(a)));
|
||||
}
|
||||
let resp = crate::http::read_json(client.get(&path).await?, "list tasks").await?;
|
||||
Ok(serde_json::to_string_pretty(&resp)?)
|
||||
}
|
||||
|
||||
"task_create" => {
|
||||
@@ -1748,7 +1726,7 @@ mod tests {
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[{"id":"t1","kind":"test","status":"pending"}],"has_more":false,"incomplete":false,"next_cursor":null}"#)
|
||||
.with_body(r#"{"tasks":[{"id":"t1","kind":"test","status":"pending"}]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1762,275 +1740,6 @@ mod tests {
|
||||
.unwrap();
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["tasks"][0]["id"], "t1");
|
||||
assert_eq!(parsed["complete"], json!(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_uses_loaded_identity() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
std::fs::write(
|
||||
dir.path().join("identity.pem"),
|
||||
kp.to_pem().unwrap().as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/tasks\?".to_string()),
|
||||
)
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.match_header("signature-input", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(
|
||||
r#"{"tasks":[{"id":"t1"}],"has_more":false,"incomplete":false,"next_cursor":null}"#,
|
||||
)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool("task_list", json!({}), &server.url(), Some(dir.path()))
|
||||
.await
|
||||
.unwrap();
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["tasks"][0]["id"], "t1");
|
||||
assert_eq!(parsed["complete"], json!(true));
|
||||
}
|
||||
|
||||
/// #327 review: MCP `task_list` issued one request and exposed no
|
||||
/// continuation, so a limit above the node's 200-row page cap returned a
|
||||
/// silently truncated result the model had no way to detect. It now
|
||||
/// follows cursors and, when a guard stops it, says so in the payload.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_follows_cursors() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let first = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/tasks\?limit=200$".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(
|
||||
r#"{"tasks":[{"id":"t1"}],"has_more":true,"incomplete":false,"next_cursor":"c1"}"#,
|
||||
)
|
||||
.create_async()
|
||||
.await;
|
||||
let second = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"cursor=c1".to_string()))
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[{"id":"t2"}],"has_more":false,"next_cursor":null}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool("task_list", json!({"limit": 500}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
first.assert_async().await;
|
||||
second.assert_async().await;
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["count"], 2);
|
||||
assert_eq!(parsed["tasks"][1]["id"], "t2");
|
||||
assert_eq!(parsed["complete"], json!(true));
|
||||
assert!(parsed.get("warning").is_none());
|
||||
}
|
||||
|
||||
/// A truncated MCP result must carry an explicit warning and a resume
|
||||
/// cursor, so the model cannot read it as the whole answer.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_flags_incomplete_results() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(
|
||||
r#"{"tasks":[{"id":"t1"}],"has_more":true,"incomplete":true,"next_cursor":"resume-me"}"#,
|
||||
)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool("task_list", json!({"limit": 1}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["complete"], json!(false));
|
||||
assert_eq!(parsed["incomplete"], json!(true));
|
||||
assert_eq!(parsed["next_cursor"], "resume-me");
|
||||
assert!(
|
||||
parsed["warning"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("result incomplete"),
|
||||
"{parsed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A legacy response without pagination metadata is reported as incomplete via MCP.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_legacy_response_is_incomplete() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[{"id":"t1"}],"count":1}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool("task_list", json!({"limit": 50}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["complete"], json!(false));
|
||||
assert_eq!(parsed["incomplete"], json!(true));
|
||||
assert!(parsed["next_cursor"].is_null());
|
||||
assert!(
|
||||
parsed["warning"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("node does not support pagination metadata"),
|
||||
"{parsed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A legacy response with limit > 200 stops after 1 page and does not claim completeness via MCP.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_legacy_limit_above_page_cap() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let ids: Vec<String> = (0..200).map(|i| format!("t{i}")).collect();
|
||||
let tasks_json: Vec<Value> = ids.iter().map(|id| json!({ "id": id })).collect();
|
||||
let body = json!({ "tasks": tasks_json, "count": 200 }).to_string();
|
||||
|
||||
let m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/tasks\?limit=200$".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(body)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool("task_list", json!({"limit": 500}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
m.assert_async().await;
|
||||
let parsed: Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(parsed["count"], 200);
|
||||
assert_eq!(parsed["complete"], json!(false));
|
||||
assert_eq!(parsed["incomplete"], json!(true));
|
||||
assert!(parsed["next_cursor"].is_null());
|
||||
assert!(
|
||||
parsed["warning"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("node does not support pagination metadata"),
|
||||
"{parsed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A cursor the model passes back must reach the node.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_forwards_cursor_argument() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"cursor=given-cursor".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[],"has_more":false,"incomplete":false,"next_cursor":null}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
call_tool(
|
||||
"task_list",
|
||||
json!({"cursor": "given-cursor"}),
|
||||
&server.url(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_returns_http_errors() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/tasks\?".to_string()),
|
||||
)
|
||||
.with_status(500)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"error":"failed"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = call_tool("task_list", json!({}), &server.url(), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("500"));
|
||||
}
|
||||
|
||||
/// Malformed server responses fail visibly in MCP.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_malformed_response_errors() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/tasks\?".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":"not-an-array"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = call_tool("task_list", json!({}), &server.url(), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("malformed") || err.to_string().contains("invalid JSON"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// #327 review: a model that sends `limit: 0` used to get an empty list
|
||||
/// marked complete, which reads as "this node has no tasks". The shared
|
||||
/// helper rejects it, so the model sees an invalid argument instead.
|
||||
#[tokio::test]
|
||||
async fn test_task_list_via_mcp_rejects_non_positive_limit() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/tasks\?".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[],"has_more":false,"incomplete":false,"next_cursor":null}"#)
|
||||
.expect(0)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = call_tool("task_list", json!({"limit": 0}), &server.url(), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("limit must be a positive"),
|
||||
"{err}"
|
||||
);
|
||||
m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2499,86 +2208,6 @@ mod tests {
|
||||
assert!(err.to_string().contains("no identity found"), "got: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_task_list_invalid_limit_rejected() {
|
||||
let server = mockito::Server::new_async().await;
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
std::fs::write(
|
||||
dir.path().join("identity.pem"),
|
||||
kp.to_pem().unwrap().as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = call_tool(
|
||||
"task_list",
|
||||
json!({"limit": "50"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.expect_err("string limit must be rejected");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("invalid limit: expected an integer"),
|
||||
"got: {err}"
|
||||
);
|
||||
|
||||
let err_float = call_tool(
|
||||
"task_list",
|
||||
json!({"limit": 50.5}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.expect_err("float limit must be rejected");
|
||||
assert!(
|
||||
err_float
|
||||
.to_string()
|
||||
.contains("invalid limit: expected an integer"),
|
||||
"got: {err_float}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_task_list_invalid_cursor_rejected() {
|
||||
let server = mockito::Server::new_async().await;
|
||||
for invalid in [json!(123), json!({}), json!([]), json!(true)] {
|
||||
let err = call_tool("task_list", json!({"cursor": invalid}), &server.url(), None)
|
||||
.await
|
||||
.expect_err("non-string cursor must be rejected");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("invalid cursor: expected a string"),
|
||||
"for {invalid}: got {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_task_list_null_or_absent_cursor_accepted() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/tasks\?".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tasks":[],"has_more":false,"incomplete":false,"next_cursor":null}"#)
|
||||
.expect(2)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
call_tool("task_list", json!({}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
call_tool("task_list", json!({"cursor": null}), &server.url(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tool_count_is_42() {
|
||||
let tools = tool_definitions();
|
||||
|
||||
+34
-1364
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "icaptcha-client"
|
||||
version = "0.4.0" # x-release-please-version
|
||||
version = "0.8.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -8,6 +8,7 @@ Step-by-step guide to staking $GITLAWB, registering your node on-chain, and earn
|
||||
|
||||
- A wallet with at least **10,000 $GITLAWB** (minimum stake) plus a small amount of ETH on Base for gas
|
||||
- Docker or Rust 1.91+ (for running the node process)
|
||||
- PostgreSQL 16+ — the node uses `pg_input_is_valid`, which exists only on PostgreSQL 16 and later. The bundled `docker-compose.yml` pins `postgres:16-alpine`; if you supply your own `DATABASE_URL`, the server must be 16+.
|
||||
- A public HTTP URL (your-host.com) — can be a VPS, Fly.io app, or anything reachable. A Fly.io config is provided at `infra/fly/fly.toml` (deploy from the repo root with `fly deploy -c infra/fly/fly.toml`)
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# GraphQL repository pagination
|
||||
|
||||
`repos` returns the complete visible repository list when it contains at most
|
||||
200 entries. Larger lists return a GraphQL error directing the caller to
|
||||
`reposPage`; they are never silently truncated.
|
||||
|
||||
Use `reposPage` for larger lists:
|
||||
|
||||
```graphql
|
||||
query Repositories($after: String) {
|
||||
reposPage(limit: 50, after: $after) {
|
||||
nodes {
|
||||
name
|
||||
ownerDid
|
||||
}
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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 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;
|
||||
hidden and quarantined repositories do not occupy page slots or create a
|
||||
continuation signal. Cursors contain a position from the last returned visible
|
||||
repository, not a permission grant. Each request checks the current caller's
|
||||
visibility independently. Keep the same caller while traversing a list.
|
||||
Malformed reader lists in a repository's root visibility rule deny access to
|
||||
non-owners for that repository while other visible repositories remain listable.
|
||||
|
||||
Pagination is not a snapshot: concurrent renames, ownership changes, or visibility
|
||||
changes can alter subsequent pages. Treat cursors as opaque and restart from the
|
||||
first page when a fresh complete traversal is needed. Small legacy `repos`
|
||||
queries retain their activity ordering.
|
||||
|
||||
## Query budgets
|
||||
|
||||
Every GraphQL document is validated against two budgets before any resolver
|
||||
runs. Both apply per document (per request), not per client: `/graphql` has
|
||||
no per-caller rate limiting, so a rejected document can always be retried
|
||||
smaller. The constants live in `crates/gitlawb-node/src/graphql/mod.rs`.
|
||||
|
||||
- **Complexity budget: 400 per document** (`GRAPHQL_MAX_COMPLEXITY`). Each
|
||||
root field carries a base cost plus the clamped page size plus the selected
|
||||
child fields:
|
||||
- `repos`: 50 + `MAX_VISIBLE_REPO_PAGE_SIZE` + child fields. `repos`
|
||||
always scans the full visible corpus, so it is priced as the full page
|
||||
it is.
|
||||
- `reposPage`: 50 + `MAX_VISIBLE_REPO_PAGE_SIZE` + child fields. Every
|
||||
page request sorts the full deduplicated corpus, so the price does not
|
||||
depend on `limit`: seven `reposPage(limit: 1)` aliases cost the same as
|
||||
seven max-size pages.
|
||||
- `refUpdates`: 100 + clamped `limit` (`MAX_VISIBLE_REF_UPDATES`) + child
|
||||
fields. The 100 base covers the collector's fixed scan (the deduplicated
|
||||
repo set, the quarantined set, the visibility rules, and the bounded
|
||||
up-to-2048-row walk past withheld rows); the limit term prices only the
|
||||
rows returned.
|
||||
- `tasks`: 50 + clamped `limit` (`MAX_VISIBLE_TASK_PAGE_SIZE`) + child
|
||||
fields.
|
||||
- `task`, mutations, subscriptions: 50 + child fields.
|
||||
|
||||
A document whose total exceeds 400 is rejected with
|
||||
`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.`
|
||||
Reference in new issue
Block a user