mirror of
https://github.com/Twigpine/node.git
synced 2026-11-08 17:55:53 -10:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
370a364b0f | ||
|
|
03aee267e6 | ||
|
|
c519d54fc1 | ||
|
|
1c82060c2b | ||
|
|
73429c7a56 | ||
|
|
fccdfc1820 | ||
|
|
8e6e2ad0fe | ||
|
|
9a70d75d13 | ||
|
|
62a99270a9 | ||
|
|
fba3c6fda3 | ||
|
|
45e269b2ae | ||
|
|
b774c435a6 | ||
|
|
0a1618f7fb | ||
|
|
c2fce67bae | ||
|
|
3351e09c08 | ||
|
|
757edf560c | ||
|
|
86828046ea | ||
|
|
d26cf6dd1d | ||
|
|
94ca744269 | ||
|
|
2eea354188 | ||
|
|
c767658b7b | ||
|
|
8afc9eaf97 | ||
|
|
433c8915bf | ||
|
|
413d6cf0bc | ||
|
|
394768711e | ||
|
|
f424ccbbcd | ||
|
|
8d17038e5b | ||
|
|
72e899dae0 | ||
|
|
5749df6e67 | ||
|
|
2a54c159e6 | ||
|
|
12643573f6 | ||
|
|
be0cdd6a9e | ||
|
|
ac59bd7e01 | ||
|
|
3cc01890fb | ||
|
|
a030eefb70 | ||
|
|
cf97405bc1 | ||
|
|
4410b834df | ||
|
|
9412aa9c5b | ||
|
|
7a6bd359eb | ||
|
|
473924dcfe | ||
|
|
f19f2813a2 | ||
|
|
79b9ee5c89 | ||
|
|
454e59ba53 | ||
|
|
c35452ed41 | ||
|
|
e750c3042d | ||
|
|
87a7e40513 | ||
|
|
ab0ea240fc | ||
|
|
71389e621a | ||
|
|
e444bc0ae5 | ||
|
|
4983b854d1 | ||
|
|
362ee3462e | ||
|
|
3b1fa54b73 | ||
|
|
5069cd13ca | ||
|
|
6336657efc | ||
|
|
57c6e01c26 | ||
|
|
2c264e08e3 | ||
|
|
fc4c206c3a | ||
|
|
2434dde42f | ||
|
|
db4de844ad | ||
|
|
65ba1374af |
No files matched your search
+6
-117
@@ -25,25 +25,7 @@ DATABASE_URL=postgresql://gitlawb:changeme@localhost:5432/gitlawb
|
||||
# Maximum connections in the PostgreSQL pool. A cap, not a floor —
|
||||
# connections open lazily. Size against the DB server's max_connections,
|
||||
# remembering admin tooling opens its own pool.
|
||||
GITLAWB_DB_MAX_CONNECTIONS=48
|
||||
# Maximum connections in the DEDICATED advisory-lock pool, separate from the
|
||||
# pool above. Every in-flight repo write pins one connection here for its whole
|
||||
# duration, so this is a hard ceiling on simultaneous writes node-wide: size it
|
||||
# to expected peak concurrent writers, not small. Keeping it separate is what
|
||||
# stops a push burst from starving ordinary request handlers. Budget
|
||||
# (GITLAWB_DB_MAX_CONNECTIONS + this) per node against the server's
|
||||
# max_connections, times node count, plus admin tooling.
|
||||
GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS=40
|
||||
# Upper bound, in seconds, on any object-storage transfer that runs while a
|
||||
# per-repo write lock is HELD (the archive download inside acquire_write and the
|
||||
# upload inside release). These were free before the lock's connection was
|
||||
# pinned to the guard; now an unbounded stall holds a lock-pool slot, and enough
|
||||
# stalls deny every write on the node. The bound applies PER SPAN and there are
|
||||
# two (the acquire-side refresh, which covers the existence check and download
|
||||
# together, and the release-side upload), so worst-case slot occupancy is about
|
||||
# twice this value plus the git work between them. Read it together with the pool
|
||||
# size above and with GITLAWB_GIT_SERVICE_TIMEOUT_SECS.
|
||||
GITLAWB_LOCK_HELD_TRANSFER_TIMEOUT_SECS=300
|
||||
GITLAWB_DB_MAX_CONNECTIONS=20
|
||||
# Seconds a request waits for a pool connection before failing with 503.
|
||||
GITLAWB_DB_ACQUIRE_TIMEOUT_SECS=5
|
||||
# Upper bound on each startup connect+migrate attempt, in seconds. Keep it
|
||||
@@ -109,14 +91,9 @@ GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false
|
||||
|
||||
# Require the authenticated pusher to be the repo owner on git-receive-pack.
|
||||
# A valid did:key signature is authentication, not authorization: anyone can
|
||||
# mint a key, derive its DID and sign, so with this off every signed caller may
|
||||
# push to every repository, private ones included. On by default.
|
||||
#
|
||||
# Set to false only for a rolling upgrade whose pushers are not yet the repo
|
||||
# owner. Note that delegated and CI keys count as non-owners: UCAN git/push is
|
||||
# verified but not yet honored for authorization, so they cannot push while this
|
||||
# is on. See docs/RUN-A-NODE.md.
|
||||
GITLAWB_ENFORCE_OWNER_PUSH=true
|
||||
# sign as their own DID. When true, pushes from a non-owner DID are rejected.
|
||||
# Keep false until the repo owner is ready for owner-only writes.
|
||||
GITLAWB_ENFORCE_OWNER_PUSH=false
|
||||
|
||||
# Comma-separated libp2p multiaddrs.
|
||||
# Example: /ip4/1.2.3.4/udp/7546/quic-v1/p2p/12D3KooW...
|
||||
@@ -135,13 +112,7 @@ GITLAWB_MAX_PACK_BYTES=2147483648
|
||||
# worker and, on push, the repo write lock. Also bounds both info/refs
|
||||
# advertisements, the withheld-blob pack build, and the push-side candidate
|
||||
# discovery (rev-list / cat-file), all reaped via process-group teardown (#174).
|
||||
# On the path-scoped upload-pack path the withheld-blob classification walk and
|
||||
# the pack serve share ONE deadline, so this value bounds their COMBINED duration
|
||||
# rather than giving each stage a full budget: a walk that consumes it leaves the
|
||||
# serve nothing and the clone gets a 504. Serving large path-scoped repos may
|
||||
# need a higher value here than when each stage was budgeted separately.
|
||||
# Must be 1..=3153600000 (100 years): the node derives deadlines from this value,
|
||||
# and a larger one cannot be represented. Default 600.
|
||||
# Default 600.
|
||||
GITLAWB_GIT_SERVICE_TIMEOUT_SECS=600
|
||||
|
||||
# Max seconds the storage-ACQUISITION phase of a served git op may run before the
|
||||
@@ -170,25 +141,6 @@ GITLAWB_MAX_CONCURRENT_GIT_OPS=128
|
||||
# Retry-After. Default 32.
|
||||
GITLAWB_MAX_CONCURRENT_GIT_PUSHES=32
|
||||
|
||||
# Max pushes PARKED at once waiting for the per-repo write lease of the SAME repo.
|
||||
# A parked push holds its already-buffered pack body in memory, so this bounds that
|
||||
# memory for a hot repo. Past the cap the newest push sheds a clean 503 +
|
||||
# Retry-After ("repo is busy with another push") instead of joining the queue; a
|
||||
# push to a DIFFERENT repo is never affected. The lease holder is not counted.
|
||||
# Raising GITLAWB_MAX_CONCURRENT_GIT_PUSHES does not raise this; set it explicitly.
|
||||
# Default 8.
|
||||
GITLAWB_REPO_LEASE_MAX_WAITERS=8
|
||||
|
||||
# Max concurrent post-push pin loops (IPFS + Pinata pin_new_objects) across all
|
||||
# repos. The per-repo encrypt-task set caps the pin-task COUNT; this caps how many
|
||||
# of those loops RUN CONCURRENTLY, and so how much MB-scale object-id list memory is
|
||||
# held WHILE BEING PINNED. It does not bound retained memory in general: on the local
|
||||
# IPFS path the caller builds its list before this pool is entered, so a loop parked
|
||||
# waiting for a permit still holds its full list, and how many park is capped only
|
||||
# per repo. Do not size memory from this knob alone. A loop DEFERS (waits) when the
|
||||
# pool is full, never drops a pin. Default 8.
|
||||
GITLAWB_MAX_CONCURRENT_PIN_TASKS=8
|
||||
|
||||
# Max concurrent read ops (upload-pack + the upload-pack info/refs advertisement)
|
||||
# a single caller may hold, so one caller cannot monopolize the read pool. Keyed
|
||||
# on the resolved SOURCE IP, never the DID: a signature does not move a caller off
|
||||
@@ -199,24 +151,6 @@ GITLAWB_MAX_CONCURRENT_PIN_TASKS=8
|
||||
# Default 16.
|
||||
GITLAWB_MAX_CONCURRENT_READS_PER_CALLER=16
|
||||
|
||||
# Two further per-source concurrency caps exist on the PUSH side but have NO
|
||||
# environment variable of their own: both are DERIVED as
|
||||
# GITLAWB_MAX_CONCURRENT_GIT_PUSHES / 8, with a floor of 1. They are not settable
|
||||
# independently, so raising the push pool raises both proportionally, and the
|
||||
# default push pool of 32 gives each a cap of 4.
|
||||
# * The anon receive-pack info/refs advertisement cap: one source IP may hold at
|
||||
# most this many slots in the dedicated advert pool, so saturating that pool
|
||||
# takes ~8 distinct source IPs.
|
||||
# * The authenticated receive-pack POST cap: one source IP may hold at most this
|
||||
# many WRITE-pool slots. This one is load-bearing for push availability, since
|
||||
# it is acquired before the global write permit: without it, one host minting
|
||||
# disposable did:key identities could open enough slow pushes to monopolize the
|
||||
# write pool and 503 every other source (the push rate limiter caps arrival
|
||||
# rate, not in-flight concurrency, and owner enforcement can be turned off for
|
||||
# a rolling upgrade).
|
||||
# Keyed on the resolved source IP, never the DID, so a DID farm does not defeat
|
||||
# them; keying granularity follows GITLAWB_TRUSTED_PROXY like the read cap above.
|
||||
|
||||
# ── Push rate limiting (git-receive-pack flood brake) ─────────────────────
|
||||
# Max receive-pack requests (info/refs advertisement + push POST) per client
|
||||
# IP per hour. 0 disables. Default 600.
|
||||
@@ -237,52 +171,7 @@ GITLAWB_IPFS_WALK_PER_SOURCE=4
|
||||
# Max legacy (NULL-provenance) repos probed per single /ipfs request, bounding the
|
||||
# scan-fallback fan-out (git cat-file per candidate repo) for an anonymous caller. A
|
||||
# truncated scan sheds a retryable 503, never a false 404. Default 256.
|
||||
GITLAWB_IPFS_MAX_LEGACY_PROBES=256
|
||||
# Max repo ROWS one /ipfs request's legacy scan may read from the database. The probe
|
||||
# ceiling above only counts once a probe runs, and quarantined or private repos are
|
||||
# denied before that, so without this an all-denying inventory paged the whole repo
|
||||
# table for one anonymous request. A truncated scan sheds a retryable 503 carrying a
|
||||
# sealed `continuation` token; echo it as ?scan= to resume, so a holder buried past the
|
||||
# ceiling is reachable in ceil(repos / ceiling) + 1 requests. Raising this also raises
|
||||
# the per-caller /ipfs work allowance, since each page is charged to it. Lowering it
|
||||
# sharpens a coarse oracle: laddering to the end reveals the node's total repo count to
|
||||
# within one ceiling. Default 2048.
|
||||
GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS=2048
|
||||
# Max EXPENSIVE path-scope visibility walks per single /ipfs request (only a
|
||||
# blob in a path-scoped repo costs a full-history walk). Over-cap repos are
|
||||
# skipped without a verdict and the scan continues; if the object is then found
|
||||
# nowhere the request sheds a retryable 503 instead of a false 404. The effective
|
||||
# cap is the tighter of this value and the node's internal per-request ceiling of
|
||||
# 17, so values above 17 have no effect; lower values do tighten it. Default 64.
|
||||
GITLAWB_IPFS_MAX_REPOS_WALKED=64
|
||||
# Ceiling on repos one /ipfs request may VISIT past the visibility gate. Each
|
||||
# visit costs a repo acquire — on a Tigris cache miss a full archive download,
|
||||
# so this is also the worst-case object-store fetch count per request — plus a
|
||||
# cat-file probe. On exhaustion the scan stops and sheds a retryable 503.
|
||||
# Default 1024.
|
||||
GITLAWB_IPFS_MAX_REPO_VISITS=1024
|
||||
# Absolute wall-clock budget for one admitted /ipfs request's acquire+walk
|
||||
# lifetime (all stages of the whole scan). Per-stage clamps bound the acquire
|
||||
# and walk stages to the remaining budget, and no stage starts once it is
|
||||
# exhausted (the scan then sheds a retryable 503). The object-type probe and
|
||||
# content-read cat-file subprocesses are budget-checked before starting AND each
|
||||
# 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.
|
||||
# Must be 1..=3153600000 (100 years): the node derives an Instant deadline from
|
||||
# this value, and a larger one cannot be represented. Default 600.
|
||||
GITLAWB_IPFS_REQUEST_BUDGET_SECS=600
|
||||
# Shorter budget (seconds) for the pre-walk CID resolve: the lookup that maps a
|
||||
# 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 a stalled lookup could hold a walk slot for the whole request
|
||||
# budget while nothing walked. The effective deadline is the lesser of this and
|
||||
# the remaining request budget; walk and probe work stay on the request budget,
|
||||
# so a slow but progressing scan is never shed by it.
|
||||
# Must be 1..=3153600000 (100 years). Default 10.
|
||||
GITLAWB_IPFS_RESOLVE_BUDGET_SECS=10
|
||||
GITLAWB_IPFS_MAX_REPOS_WALKED=256
|
||||
# Max /ipfs/{cid} requests per client IP per hour (route flood brake, distinct
|
||||
# from the concurrency caps above). 0 disables. Default 600.
|
||||
GITLAWB_IPFS_RATE_LIMIT=600
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
# Tracks main's CI state as a labeled issue: opens (or updates) a ci-main-red
|
||||
# issue when a push-to-main run of PR Checks ends red, and closes it when a
|
||||
# subsequent run on main's tip goes green.
|
||||
#
|
||||
# Why: two individually-green PRs can break main in combination when the
|
||||
# second merges on checks that ran against a stale base (semantic merge
|
||||
# race — #113 + #145 broke test compilation, found only via #229). A red main
|
||||
# is otherwise silent, and release-please PRs inherit the breakage.
|
||||
#
|
||||
# The alert reflects main's CURRENT STATE, not raw CI events: runs whose
|
||||
# commit is no longer main's tip are ignored (a re-run of an old red run
|
||||
# after a fix has landed must not cry wolf), and a green run on the tip
|
||||
# closes any open alert.
|
||||
name: Main red alert
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["PR Checks"]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
contents: read # getBranch tip check
|
||||
|
||||
# Serialize runs: concurrent completions would race the label/issue lookups
|
||||
# into duplicates (or 422 on createLabel). queue: max keeps every pending
|
||||
# completion instead of letting a later (possibly green-skipped) arrival
|
||||
# displace a pending red alert under burst merges; it is only incompatible
|
||||
# with cancel-in-progress: true, which we don't use.
|
||||
concurrency:
|
||||
group: main-red-alert
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
track:
|
||||
name: Track main CI state
|
||||
# timed_out (the test job runs 45 min against Postgres) and
|
||||
# startup_failure (malformed workflow) are red too — only cancelled is
|
||||
# excluded as a deliberate human abort. success runs are needed to close
|
||||
# the alert once main recovers.
|
||||
if: >-
|
||||
github.event.workflow_run.event == 'push' &&
|
||||
contains(fromJSON('["failure", "timed_out", "startup_failure", "success"]'), github.event.workflow_run.conclusion)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Reconcile the broken-main issue with main's current state
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
const run = context.payload.workflow_run;
|
||||
const label = 'ci-main-red';
|
||||
|
||||
// Freshness gate: only the run for main's current tip may open or
|
||||
// close anything. Re-runs of superseded commits are events about
|
||||
// the past, not statements about main's state.
|
||||
const { data: branch } = await github.rest.repos.getBranch({
|
||||
...context.repo, branch: 'main',
|
||||
});
|
||||
if (branch.commit.sha !== run.head_sha) {
|
||||
core.info(`run ${run.id} is for ${run.head_sha}, main is at ${branch.commit.sha} — ignoring stale run`);
|
||||
return;
|
||||
}
|
||||
|
||||
// listForRepo returns PRs carrying the label too — those must
|
||||
// never be mistaken for the tracking issue.
|
||||
const open = (await github.rest.issues.listForRepo({
|
||||
...context.repo, state: 'open', labels: label, per_page: 100,
|
||||
})).data.filter(item => !item.pull_request);
|
||||
|
||||
if (run.conclusion === 'success') {
|
||||
const body = `Recovered: [PR Checks](${run.html_url}) is green on main at \`${run.head_sha}\`.`;
|
||||
for (const issue of open) {
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo, issue_number: issue.number, body,
|
||||
});
|
||||
await github.rest.issues.update({
|
||||
...context.repo, issue_number: issue.number, state: 'closed', state_reason: 'completed',
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const headline = run.head_commit?.message?.split('\n')[0] ?? '';
|
||||
const body = [
|
||||
`[PR Checks run](${run.html_url}) concluded \`${run.conclusion}\` on main at \`${run.head_sha}\`.`,
|
||||
'',
|
||||
`> ${headline}`,
|
||||
'',
|
||||
'Likely a semantic merge race: each merged PR was green on a stale base.',
|
||||
'Fix main before merging anything else — release-please PRs inherit this breakage.',
|
||||
'',
|
||||
"This issue closes automatically when a run on main's tip goes green.",
|
||||
].join('\n');
|
||||
|
||||
try {
|
||||
await github.rest.issues.getLabel({ ...context.repo, name: label });
|
||||
} catch (e) {
|
||||
if (e.status !== 404) throw e;
|
||||
await github.rest.issues.createLabel({
|
||||
...context.repo,
|
||||
name: label,
|
||||
color: 'b60205',
|
||||
description: 'CI is failing on main',
|
||||
});
|
||||
}
|
||||
|
||||
if (open.length > 0) {
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo, issue_number: open[0].number, body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.create({
|
||||
...context.repo,
|
||||
title: 'CI is red on main',
|
||||
body,
|
||||
labels: [label],
|
||||
});
|
||||
}
|
||||
@@ -2,17 +2,6 @@ name: PR Checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
# Run in the merge queue so a PR is re-validated against the true merged
|
||||
# result before it lands. Guards against semantic merge races where two
|
||||
# individually-green PRs break main in combination (#113 + #145 → #229).
|
||||
merge_group:
|
||||
# Release-branch heads are created and pushed by GITHUB_TOKEN (release-please
|
||||
# and the lock-sync job), and GitHub's recursion guard means those pushes
|
||||
# trigger no workflow runs. workflow_dispatch is the documented carve-out that
|
||||
# GITHUB_TOKEN CAN trigger, so the release flow dispatches this workflow at
|
||||
# the release branch to attach check runs to its head. Read-only workflow
|
||||
# (contents: read), so the dispatch surface adds no privilege.
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
@@ -53,20 +42,7 @@ jobs:
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: cargo clippy
|
||||
run: cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
|
||||
release-tag-validation:
|
||||
name: release tag validation
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Test release tag resolver
|
||||
run: scripts/test-resolve-release-tag.sh
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
test:
|
||||
name: test (${{ matrix.toolchain }})
|
||||
@@ -114,7 +90,7 @@ jobs:
|
||||
- name: cargo test
|
||||
env:
|
||||
DATABASE_URL: postgres://postgres:postgres@localhost:5432/gitlawb_test
|
||||
run: cargo test --locked --workspace
|
||||
run: cargo test --workspace
|
||||
|
||||
build-release:
|
||||
name: build --release
|
||||
@@ -137,7 +113,7 @@ jobs:
|
||||
key: release
|
||||
|
||||
- name: cargo build --release
|
||||
run: cargo build --locked --release --workspace
|
||||
run: cargo build --release --workspace
|
||||
|
||||
audit:
|
||||
name: cargo audit
|
||||
@@ -219,7 +195,7 @@ jobs:
|
||||
key: msrv
|
||||
|
||||
- name: cargo check on MSRV
|
||||
run: cargo check --locked --workspace --all-targets
|
||||
run: cargo check --workspace --all-targets
|
||||
|
||||
docker-build:
|
||||
name: Docker build smoke test
|
||||
@@ -236,95 +212,3 @@ jobs:
|
||||
|
||||
- name: Smoke test --version
|
||||
run: docker run --rm gitlawb-node:ci-test --version
|
||||
|
||||
test-windows:
|
||||
name: test (windows, non-blocking)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
# Non-blocking, mirroring the informational `beta` lane above. We ship `gl`
|
||||
# and `git-remote-gitlawb` to Windows users (release.yml) with zero Windows
|
||||
# test coverage, so run their suites here to make Windows-only regressions
|
||||
# VISIBLE on the PR without gating merge (#228). These two are the client
|
||||
# CLIs and depend on no database, so no Postgres service is needed (service
|
||||
# containers do not run on windows-latest regardless). `git` is preinstalled
|
||||
# on windows-latest, which the real_git_fetch harness relies on.
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@b3b07ba8b418998c39fb20f53e8b695cdcc8de1b # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Cache cargo
|
||||
uses: Swatinem/rust-cache@98c8021b550208e191a6a3145459bfc9fb29c4c0 # v2.8.0
|
||||
with:
|
||||
key: windows
|
||||
|
||||
- name: cargo test (shipped Windows crates)
|
||||
run: cargo test --locked -p gl -p git-remote-gitlawb
|
||||
|
||||
# gitlawb-core is embedded by every consumer (gl, git-remote-gitlawb, the node
|
||||
# daemon), so it must stay lean. This gate fails if gitlawb-core's normal
|
||||
# (non-dev, non-build) dependency tree gains any crate not on the allowlist in
|
||||
# ci/gitlawb-core-allowed-deps.txt. Exhaustive-by-construction: a new heavy
|
||||
# dependency reds CI whether or not anyone thought to ban it, which a denylist
|
||||
# cannot do. Regen instructions live in the allowlist header.
|
||||
core-deps-purity:
|
||||
name: gitlawb-core dependency purity
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@b3b07ba8b418998c39fb20f53e8b695cdcc8de1b # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Cache cargo
|
||||
uses: Swatinem/rust-cache@98c8021b550208e191a6a3145459bfc9fb29c4c0 # v2.8.0
|
||||
with:
|
||||
key: core-deps-purity
|
||||
|
||||
- name: Check gitlawb-core dependency allowlist
|
||||
run: bash scripts/check-gitlawb-core-deps.sh
|
||||
|
||||
# release-please only rewrites a crate's version when the line carries the
|
||||
# `# x-release-please-version` annotation AND the manifest is listed under
|
||||
# extra-files in release-please-config.json. Miss either half and the crate
|
||||
# is skipped silently at release time, freezing at its creation version:
|
||||
# icaptcha-client was added as a workspace member after the config was last
|
||||
# written and sat at 0.4.0 through four releases before anyone noticed.
|
||||
# Exhaustive-by-construction, like the allowlist gate above: the required set
|
||||
# is derived from `cargo metadata`, so a newly added crate reds CI whether or
|
||||
# not its author knew this gate existed.
|
||||
release-versioning:
|
||||
name: release versioning coverage
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@b3b07ba8b418998c39fb20f53e8b695cdcc8de1b # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Cache cargo
|
||||
uses: Swatinem/rust-cache@98c8021b550208e191a6a3145459bfc9fb29c4c0 # v2.8.0
|
||||
with:
|
||||
key: release-versioning
|
||||
|
||||
- name: Check every workspace crate is release-managed
|
||||
run: bash scripts/check-release-versioning.sh
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Label and guide
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
@@ -70,15 +70,9 @@ jobs:
|
||||
const changedRust = names.some(n => n.startsWith("crates/") && n.endsWith(".rs"));
|
||||
// A test can live in a tests/ dir, a *_test.rs file, or (the common Rust
|
||||
// pattern) an inline #[test] / #[cfg(test)] block added inside the source file.
|
||||
// Async tests use a namespaced attribute (#[tokio::test], #[async_std::test],
|
||||
// possibly with args like #[tokio::test(flavor = ...)]) rather than the bare
|
||||
// #[test]. Match only on added lines, with the attribute at the start of the
|
||||
// line after horizontal whitespace, covering bare, cfg(test), namespaced,
|
||||
// optional leading ::, and raw-identifier (r#test) forms. No head-file fetch
|
||||
// or lexer: needs-tests is advisory, not a merge gate.
|
||||
const addsInlineTest = files.some(f =>
|
||||
f.filename.endsWith(".rs") && f.patch &&
|
||||
/^\+[ \t]*#\[[ \t]*(?:cfg[ \t]*\([ \t]*test[ \t]*\)|(?:::[ \t]*)?(?:[\w-]+[ \t]*::[ \t]*)*(?:r#)?test\b)/m.test(f.patch));
|
||||
/^\+.*#\[(test\]|cfg\(test\))/m.test(f.patch));
|
||||
const touchedTests =
|
||||
names.some(n => n.includes("/tests/") || n.endsWith("_test.rs")) || addsInlineTest;
|
||||
if (changedRust && !touchedTests) want.add("needs-tests");
|
||||
|
||||
+53
-360
@@ -4,20 +4,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
# Manual backfill: republish an already-cut release to a channel that
|
||||
# missed it. Fill in only the channel(s) you want — an empty input leaves
|
||||
# that channel's jobs skipped. npm reuses the existing release's binary
|
||||
# assets; docker rebuilds the image from the tag and re-tags the manifest.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
npm_backfill_tag:
|
||||
description: "Existing release tag to publish to npm (e.g. v0.6.0)"
|
||||
required: false
|
||||
type: string
|
||||
docker_backfill_tag:
|
||||
description: "Existing release tag to publish to ghcr (e.g. v0.6.0)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
@@ -28,10 +14,7 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
# Skipped on manual dispatch: a backfill must never create or advance a
|
||||
# release PR as a side effect (npm-publish tolerates the skipped need via
|
||||
# !cancelled(), and every other job gates on release_created == 'true').
|
||||
if: ${{ github.repository == 'Gitlawb/node' && github.event_name != 'workflow_dispatch' }}
|
||||
if: ${{ github.repository == 'Gitlawb/node' }}
|
||||
name: Release Please
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -41,7 +24,6 @@ jobs:
|
||||
release_created: ${{ steps.release.outputs.release_created }}
|
||||
tag_name: ${{ steps.release.outputs.tag_name }}
|
||||
version: ${{ steps.release.outputs.version }}
|
||||
pr: ${{ steps.release.outputs.pr }}
|
||||
steps:
|
||||
- name: Run release-please
|
||||
id: release
|
||||
@@ -49,197 +31,24 @@ jobs:
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# The release PR bumps the workspace crate versions in the Cargo.tomls but
|
||||
# release-please cannot update Cargo.lock, so without this job every release
|
||||
# merge ships a tag whose lockfile disagrees with its manifests (a --locked
|
||||
# build from the tag fails, and pr-checks builds --locked). Sync the lock on
|
||||
# the release branch so the tagged tree is internally consistent.
|
||||
#
|
||||
# Runs on every push-triggered release run, not only when release-please
|
||||
# reports the PR: the `pr` output is set only on runs that CREATE or UPDATE
|
||||
# the release PR, so gating on it would leave an already-open release PR
|
||||
# (opened before this job existed, or untouched by a non-releasable push)
|
||||
# permanently without the sync and without check runs. The resolve step
|
||||
# discovers any open release-please PR itself and no-ops when there is none.
|
||||
sync-release-lock:
|
||||
name: Sync Cargo.lock on the release PR
|
||||
needs: release-please
|
||||
if: ${{ !cancelled() && github.repository == 'Gitlawb/node' && github.event_name != 'workflow_dispatch' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
# actions: write lets the final step dispatch pr-checks on the release
|
||||
# branch. Note this grant is repo-wide dispatch rights (GitHub cannot
|
||||
# scope it to one workflow); acceptable here because reaching this job's
|
||||
# steps already requires write to main. Needed because every push to the
|
||||
# release branch (release-please's and the lock sync below) is made with
|
||||
# GITHUB_TOKEN, which triggers no workflow runs, so without an explicit
|
||||
# dispatch the release PR's head carries no check runs and the --locked
|
||||
# gate never validates it.
|
||||
actions: write
|
||||
steps:
|
||||
# Prefer the fresh `pr` output when this run just created/updated the
|
||||
# release PR; otherwise fall back to querying for an open release-please
|
||||
# branch (prefix match: the branch carries `--components--` suffixes).
|
||||
- name: Resolve the open release PR branch
|
||||
id: resolve
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
BRANCH_FROM_OUTPUT: ${{ needs.release-please.outputs.pr && fromJSON(needs.release-please.outputs.pr).headBranchName || '' }}
|
||||
run: |
|
||||
branch="$BRANCH_FROM_OUTPUT"
|
||||
if [ -z "$branch" ]; then
|
||||
# The branch name alone is not a trust signal. `gh pr list` includes
|
||||
# fork PRs, and a fork's headRefName is bare (no owner prefix), so a
|
||||
# prefix match by itself lets any fork nominate the branch this job
|
||||
# checks out, commits to, and dispatches checks on. Require the head
|
||||
# repo to be THIS repository and the author to be the release-please
|
||||
# app, so neither a fork nor a same-repo human branch named
|
||||
# `release-please--*` can be selected. Then take the highest PR
|
||||
# number: `[0]` depended on gh's default ordering, which is not a
|
||||
# documented guarantee, and picking a stable one keeps a second
|
||||
# (component) release PR from making the choice flap between runs.
|
||||
branch=$(gh pr list --repo "$GITHUB_REPOSITORY" --state open \
|
||||
--json headRefName,headRepositoryOwner,number,author \
|
||||
--jq '[ .[]
|
||||
| select(.headRepositoryOwner.login == env.OWNER)
|
||||
| select(.author.login == "app/github-actions")
|
||||
| select(.headRefName | startswith("release-please--"))
|
||||
] | max_by(.number).headRefName // empty')
|
||||
fi
|
||||
if [ -z "$branch" ]; then
|
||||
echo "no open release PR; nothing to sync"
|
||||
fi
|
||||
echo "branch=$branch" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Checkout release branch
|
||||
if: ${{ steps.resolve.outputs.branch != '' }}
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ steps.resolve.outputs.branch }}
|
||||
|
||||
# Resolve on a declared toolchain instead of whatever Rust the runner
|
||||
# image happens to ship, so the lock this job writes comes off the same
|
||||
# stable channel the other cargo jobs use. Not a claim of identical
|
||||
# resolution: `stable` still moves between runs, and the MSRV gate
|
||||
# checks this same lock on 1.91 (pr-checks.yml). It only removes the
|
||||
# runner image as an undeclared input.
|
||||
- name: Install Rust toolchain
|
||||
if: ${{ steps.resolve.outputs.branch != '' }}
|
||||
uses: dtolnay/rust-toolchain@b3b07ba8b418998c39fb20f53e8b695cdcc8de1b # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Sync workspace crate versions into Cargo.lock
|
||||
if: ${{ steps.resolve.outputs.branch != '' }}
|
||||
run: cargo update --workspace
|
||||
|
||||
- name: Commit and push when the lock changed
|
||||
if: ${{ steps.resolve.outputs.branch != '' }}
|
||||
run: |
|
||||
if git diff --quiet Cargo.lock; then
|
||||
echo "Cargo.lock already in sync"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add Cargo.lock
|
||||
git commit -m "chore: sync Cargo.lock with the release version bump"
|
||||
git push
|
||||
|
||||
# Every push to the release branch is made with GITHUB_TOKEN (release-
|
||||
# please's own pushes and the lock sync above), and events created by
|
||||
# GITHUB_TOKEN start no workflow runs. workflow_dispatch is the documented
|
||||
# exception GITHUB_TOKEN may trigger, so dispatch pr-checks at the release
|
||||
# branch to attach check runs to its current head. Unconditional (also on
|
||||
# the already-in-sync path) because the branch's ORIGINAL head has the
|
||||
# same no-runs problem. Loud on failure by design: a silent fallback
|
||||
# would recreate the checkless-head problem, and a job rerun is safe
|
||||
# (sync no-ops, dispatch retries). Loop-safe: pr-checks is read-only and
|
||||
# dispatches nothing. Runs after the push ack, so the dispatched ref tip
|
||||
# is the sync commit. Merge-queue note: this validates the branch tip;
|
||||
# the enforced merge queue's merge_group run still re-validates the true
|
||||
# merged result before landing.
|
||||
- name: Dispatch PR checks on the release branch
|
||||
if: ${{ steps.resolve.outputs.branch != '' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
BRANCH: ${{ steps.resolve.outputs.branch }}
|
||||
run: |
|
||||
# Every dispatch failure fails the job, including the 422 a release
|
||||
# branch cut before pr-checks gained its workflow_dispatch trigger
|
||||
# returns ("does not have a workflow_dispatch trigger", reported
|
||||
# against the dispatched ref's copy of the file). An earlier revision
|
||||
# tolerated exactly that 422 on the theory that release-please would
|
||||
# rewrite the branch and heal it, but a rewrite only happens when a
|
||||
# later releasable commit lands: an open release PR nobody touches is
|
||||
# never rewritten. Tolerating it therefore left the lock-sync commit
|
||||
# this job had just pushed sitting on the release head with no
|
||||
# --locked validation, which is the precise state this workflow exists
|
||||
# to prevent. The tolerance is also no longer needed: once this lands,
|
||||
# every release branch is cut from a main that already carries the
|
||||
# trigger, so the only branch that could 422 is one open at merge time
|
||||
# (there is none), and a job rerun after a manual rebase is safe (the
|
||||
# sync no-ops, the dispatch retries).
|
||||
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/pr-checks.yml/dispatches" \
|
||||
-f "ref=$BRANCH"
|
||||
|
||||
# Each architecture builds NATIVELY (amd64 on ubuntu-latest, arm64 on
|
||||
# ubuntu-24.04-arm) and pushes by digest; docker-manifest below stitches the
|
||||
# digests into the tagged multi-arch image. No QEMU: emulating the arm64
|
||||
# Rust release build wedged the v0.6.0 run for 3+ hours and, via the
|
||||
# workflow concurrency group, blocked every queued release run behind it.
|
||||
docker:
|
||||
name: Build & Push Docker Image (${{ matrix.arch }})
|
||||
name: Build & Push Docker Image
|
||||
needs: release-please
|
||||
# Runs on a fresh release, or on manual dispatch for an existing tag
|
||||
# (release-please is skipped on dispatch, hence !cancelled()).
|
||||
if: >-
|
||||
${{ !cancelled() && (
|
||||
needs.release-please.outputs.release_created == 'true' ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.docker_backfill_tag != '')
|
||||
) }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
os: ubuntu-latest
|
||||
platform: linux/amd64
|
||||
- arch: arm64
|
||||
os: ubuntu-24.04-arm
|
||||
platform: linux/arm64
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: ${{ needs.release-please.outputs.release_created == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Check out workflow scripts
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve release tag
|
||||
id: rel
|
||||
env:
|
||||
DISPATCH_TAG: ${{ inputs.docker_backfill_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/resolve-release-tag.sh "${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
# ghcr requires a lowercase repository path, and unlike metadata-action,
|
||||
# buildx's `--output name=` does no lowercasing — a mixed-case owner
|
||||
# makes the digest push fail with "invalid reference format".
|
||||
echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Checkout release tag
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ steps.rel.outputs.tag }}
|
||||
ref: ${{ needs.release-please.outputs.tag_name }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
@@ -250,130 +59,45 @@ jobs:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}},value=${{ needs.release-please.outputs.version }}
|
||||
type=semver,pattern={{major}}.{{minor}},value=${{ needs.release-please.outputs.version }}
|
||||
type=raw,value=latest
|
||||
|
||||
- name: Build and load locally (smoke)
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v6.16.0
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
load: true
|
||||
tags: gitlawb-node:smoke
|
||||
cache-from: type=gha,scope=docker-${{ matrix.arch }}
|
||||
cache-from: type=gha
|
||||
|
||||
# Native runner on both arches, so the built image can always execute.
|
||||
# Assert the released version so a stale artifact fails here, not in prod.
|
||||
- name: Smoke test
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
out="$(docker run --rm gitlawb-node:smoke --version)"
|
||||
echo "$out"
|
||||
grep -qF "$VERSION" <<<"$out" || {
|
||||
echo "::error::image --version did not report expected version $VERSION (got: $out)"
|
||||
exit 1
|
||||
}
|
||||
run: docker run --rm gitlawb-node:smoke --version
|
||||
|
||||
# Push by digest only — tags are applied once by docker-manifest so a
|
||||
# half-finished matrix can never publish a partially-tagged image.
|
||||
# provenance:false keeps each push a plain single-arch manifest, which is
|
||||
# what imagetools create expects to merge.
|
||||
- name: Build and push by digest
|
||||
id: push
|
||||
- name: Build and push (multi-arch)
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v6.16.0
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
provenance: false
|
||||
outputs: type=image,name=${{ steps.rel.outputs.image }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha,scope=docker-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=docker-${{ matrix.arch }}
|
||||
|
||||
- name: Export digest
|
||||
env:
|
||||
DIGEST: ${{ steps.push.outputs.digest }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/digests
|
||||
touch "/tmp/digests/${DIGEST#sha256:}"
|
||||
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: docker-digest-${{ matrix.arch }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
docker-manifest:
|
||||
name: Publish Docker manifest
|
||||
needs: [release-please, docker]
|
||||
if: ${{ !cancelled() && needs.docker.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Check out workflow scripts
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve release tag
|
||||
id: rel
|
||||
env:
|
||||
DISPATCH_TAG: ${{ inputs.docker_backfill_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/resolve-release-tag.sh "${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
pattern: docker-digest-*
|
||||
path: /tmp/digests
|
||||
merge-multiple: true
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Create and push multi-arch manifest
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# ghcr requires a lowercase repository path.
|
||||
IMAGE="ghcr.io/${GITHUB_REPOSITORY,,}"
|
||||
MAJOR_MINOR="${VERSION%.*}"
|
||||
digests=""
|
||||
for f in /tmp/digests/*; do
|
||||
digests="$digests $IMAGE@sha256:$(basename "$f")"
|
||||
done
|
||||
# shellcheck disable=SC2086
|
||||
docker buildx imagetools create \
|
||||
-t "$IMAGE:$VERSION" \
|
||||
-t "$IMAGE:$MAJOR_MINOR" \
|
||||
-t "$IMAGE:latest" \
|
||||
$digests
|
||||
docker buildx imagetools inspect "$IMAGE:$VERSION"
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Release summary
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
TAG: ${{ steps.rel.outputs.tag }}
|
||||
run: |
|
||||
{
|
||||
echo "## Released $TAG"
|
||||
echo "## Released ${{ needs.release-please.outputs.tag_name }}"
|
||||
echo
|
||||
echo "- Image: \`ghcr.io/${GITHUB_REPOSITORY,,}:$VERSION\` (linux/amd64 + linux/arm64)"
|
||||
echo "- GitHub: https://github.com/$GITHUB_REPOSITORY/releases/tag/$TAG"
|
||||
echo "- Image: \`ghcr.io/${{ github.repository }}:${{ needs.release-please.outputs.version }}\`"
|
||||
echo "- GitHub: https://github.com/${{ github.repository }}/releases/tag/${{ needs.release-please.outputs.tag_name }}"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
release-binaries:
|
||||
@@ -445,7 +169,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
args=""
|
||||
for b in $BINS; do args="$args -p $b"; done
|
||||
cargo build --release --locked --target ${{ matrix.target }} $args
|
||||
cargo build --release --target ${{ matrix.target }} $args
|
||||
|
||||
# Run each packaged binary's --version so a broken release artifact fails the
|
||||
# build instead of shipping. Every target builds on a matching-arch runner,
|
||||
@@ -524,61 +248,37 @@ jobs:
|
||||
npm-publish:
|
||||
name: Publish to npm
|
||||
needs: [release-please, release-binaries]
|
||||
# Runs on a fresh release, or on manual dispatch for an existing tag
|
||||
# (release-binaries is skipped on dispatch, hence !cancelled()). Publishing
|
||||
# auth is npm Trusted Publishing (GitHub OIDC) — no NPM_TOKEN. Each
|
||||
# @gitlawb package must have this repo + workflow (release.yml) configured
|
||||
# as its trusted publisher on npmjs.com, or publish fails loudly here —
|
||||
# deliberately loud: the silent secret-guard skip is how 0.4.x–0.6.0
|
||||
# never reached npm.
|
||||
if: >-
|
||||
${{ !cancelled() && (
|
||||
(needs.release-please.outputs.release_created == 'true' && needs.release-binaries.result == 'success') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.npm_backfill_tag != '')
|
||||
) }}
|
||||
if: ${{ needs.release-please.outputs.release_created == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # npm trusted publishing (OIDC) + provenance
|
||||
id-token: write # npm provenance
|
||||
steps:
|
||||
- name: Check out workflow scripts
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve release tag
|
||||
id: rel
|
||||
- name: Guard on secret
|
||||
id: guard
|
||||
env:
|
||||
DISPATCH_TAG: ${{ inputs.npm_backfill_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/resolve-release-tag.sh "${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
if [ -z "${NPM_TOKEN:-}" ]; then
|
||||
echo "::warning::NPM_TOKEN is not set — skipping npm publish."
|
||||
echo "enabled=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "enabled=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Checkout release tag
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ steps.rel.outputs.tag }}
|
||||
ref: ${{ needs.release-please.outputs.tag_name }}
|
||||
persist-credentials: false
|
||||
|
||||
# npm >= 11.5.1 performs the OIDC token exchange automatically when the
|
||||
# package has a trusted publisher configured; older npm silently falls
|
||||
# back to (absent) token auth and fails confusingly.
|
||||
- name: Set up Node 24 + OIDC-capable npm
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: "24"
|
||||
- name: Ensure npm supports trusted publishing
|
||||
run: |
|
||||
set -euo pipefail
|
||||
npm install -g npm@^11.5.1
|
||||
npm --version
|
||||
|
||||
- name: Lay in release binaries
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
TAG: ${{ steps.rel.outputs.tag }}
|
||||
VERSION: ${{ needs.release-please.outputs.version }}
|
||||
TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# npm platform package -> Rust target triple (unix only; Windows is not
|
||||
@@ -605,8 +305,9 @@ jobs:
|
||||
done
|
||||
|
||||
- name: Set versions
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
VERSION: ${{ needs.release-please.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node -e '
|
||||
@@ -626,12 +327,13 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Publish
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
VERSION: ${{ needs.release-please.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# No token: npm exchanges this job's GitHub OIDC identity with the
|
||||
# registry (trusted publishing); provenance is attested automatically.
|
||||
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
|
||||
# Platform packages first, then the wrapper (so its optionalDependencies resolve).
|
||||
# Skip versions already on the registry so a rerun after a partial publish
|
||||
# is idempotent instead of erroring on the first existing package.
|
||||
@@ -727,15 +429,6 @@ jobs:
|
||||
bin.install "git-remote-gitlawb"
|
||||
end
|
||||
|
||||
def caveats
|
||||
<<~CAVEATS
|
||||
oh-my-zsh's git plugin aliases gl='git pull', which shadows this
|
||||
binary in interactive shells. If \`gl\` prints "fatal: not a git
|
||||
repository", run:
|
||||
echo 'unalias gl 2>/dev/null' >> ~/.zshrc && source ~/.zshrc
|
||||
CAVEATS
|
||||
end
|
||||
|
||||
test do
|
||||
assert_match version.to_s, shell_output("#{bin}/gl --version")
|
||||
end
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.7.1"
|
||||
".": "0.5.1"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
# Contributor guide for coding agents
|
||||
|
||||
This file carries the rules a patch author cannot recover from the code alone, for humans and coding agents alike. For build, test, and PR basics, read `CONTRIBUTING.md` first.
|
||||
|
||||
## Authorization invariants (the rules PRs most often break)
|
||||
|
||||
Every repo-scoped endpoint must bind the caller to an authorization decision before serving or mutating anything. The `known_ungated` allowlist in `authz_guard::every_repo_scoped_handler_is_gated` is empty on main: `list_webhooks`, `list_replicas`, and `list_protected_branches` are gated (`list_webhooks` with read-visibility then owner; the other two with `authorize_repo_read`). Do not re-open those surfaces as exceptions.
|
||||
|
||||
- Owner-only mutations (visibility, webhooks, protected branches, merges) are gated against the repo owner. Three gate forms are in use and all are recognized: webhooks and merges call `require_repo_owner` (`crates/gitlawb-node/src/api/mod.rs`), visibility uses its module-local `require_owner`, and protected branches compare inline with `did_matches`. Use the form the surrounding module already uses.
|
||||
- Not every write is owner-only, and that is by design: `star_repo`/`unstar_repo` bind to the signer (they still require repo read access), `register_replica`/`unregister_replica` bind to the replica's own DID, the bounty actions (claim, submit, approve, cancel, dispute) have their own multi-party rules, and closing a PR or issue is owner-or-author. Do not add owner gates to these.
|
||||
- Content-serving reads (blobs, trees, raw files) gate through `authorize_repo_read` with the specific path being served, so a withheld subtree is denied even on an otherwise-public repo; repo-level reads (listings) pass `"/"` by the helper's own contract. The source scans below cannot check this argument's value, so review will.
|
||||
- A route that reaches repo data through a global id, with no repo in its path, or through an extractor shape the scans do not recognize still needs the same gate; the scans cannot see those.
|
||||
- Read-surface denials must not reveal existence: a caller who may not read a repo (or a withheld subtree) gets the same 404 as a missing repo, never a 403. (Owner-gated mutations currently return 403 after the repo lookup; do not widen that shape to read paths.)
|
||||
- Two tests in module `authz_guard` (`crates/gitlawb-node/src/api/mod.rs`) scan handler sources and fail on a repo-scoped handler without a recognized gate: `every_in_scope_mutation_has_its_gate` and `every_repo_scoped_handler_is_gated`. If they fail on your handler, add the gate. The second test's `known_ungated` allowlist is empty; never add an entry to it without an open issue and review.
|
||||
|
||||
## Adding or changing routes
|
||||
|
||||
- A new gated handler needs tests proving its route-specific gate fires: exercise an unauthorized authenticated caller and an anonymous caller where applicable, assert the exact denial status each way, and assert the body leaks nothing. The non-owner tests in `crates/gitlawb-node/src/test_support.rs` show the shape for owner-gated routes.
|
||||
- A new mutation handler also gets a row in `every_in_scope_mutation_has_its_gate` naming its gate type; the per-handler row is the point of that test.
|
||||
- A table-driven deny suite covering every deny-bearing route is in review (#194, #195). If it is present in your checkout, add a probe row there for any new deny-bearing route.
|
||||
|
||||
## Verifying signatures and certificates
|
||||
|
||||
- Derive the verifying key from something outside the artifact you are checking: the node's own DID, a pinned or configured value, a peers lookup. A key read from a field of the object being verified (`Did::from_str(&cert.node_did)`) only proves the artifact is self-consistent, and identities here are permissionless, so anyone can mint a keypair, name it in the artifact, self-sign, and be told it is valid. A mismatch against that anchor has to fail the result, not log a warning.
|
||||
- A handler whose correct answer is "valid" needs a positive case driven by a trusted, independently anchored artifact, and a rejection case for a well-formed, fully populated forged artifact. Invalid-only suites miss an implementation that rejects everything; a forged artifact that still returns valid is the regression that matters.
|
||||
- The fields a signature covers are a versioned format. Adding one invalidates every artifact already signed, so give the payload a version, keep a path that verifies the older form, and add a test that verifies an artifact signed before your change.
|
||||
|
||||
## Removing a serving path
|
||||
|
||||
When a fix removes a path that used to serve content, the same PR must add a test asserting the removed path now denies. The deletion is what turns that test green; without it the path can quietly come back.
|
||||
|
||||
## Database migrations
|
||||
|
||||
Schema changes are code-defined in `MIGRATIONS` (`crates/gitlawb-node/src/db/mod.rs`). Always append a new versioned entry; never edit an entry that has merged (operators deploy from main). Test runs build the schema from scratch, so editing an applied version stays green in CI while breaking every existing deployment.
|
||||
|
||||
## Client behavior (`gl`, `git-remote-gitlawb`)
|
||||
|
||||
When a node denies a request, surface the denial to the user. Never render a denial as an empty list or a silent success; that turns an authorization boundary into invisible data loss.
|
||||
|
||||
## Toolchain and CI reality
|
||||
|
||||
- MSRV is Rust 1.91 (`rust-version` in the workspace `Cargo.toml`). The MSRV CI job runs `cargo check --workspace --all-targets` on exactly 1.91, so check that an API you rely on is stable there; the full test suite runs on stable.
|
||||
- The PR workflow runs these jobs on every PR: `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace` (against Postgres), a release build, `cargo audit`, the MSRV check, and a Docker build. The `main` branch ruleset currently requires one approving review but does not require these checks to pass before merge; a failing job should block review approval in practice, but nothing enforces that mechanically today.
|
||||
- Conventional commit titles (`feat:`, `fix:`, `docs:`, ...) are required by convention and drive releases, but no CI job checks them; a bad title fails review, not the pipeline.
|
||||
@@ -1,65 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [0.7.1](https://github.com/Gitlawb/node/compare/v0.7.0...v0.7.1) (2026-08-03)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **ci:** make the docker dependency cache work and unbreak Dockerfile.bins ([99b2b9a](https://github.com/Gitlawb/node/commit/99b2b9a16662761a3959a2941798e6823621bda5))
|
||||
* **ci:** make the docker dependency cache work and unbreak Dockerfile.bins ([a49e04d](https://github.com/Gitlawb/node/commit/a49e04ddcd23f3b666421486ae60c3c4329e2242)), closes [#265](https://github.com/Gitlawb/node/issues/265) [#266](https://github.com/Gitlawb/node/issues/266)
|
||||
* **db:** pin profile DID matching with lone non-key fixture and boundary matrix ([b4016dc](https://github.com/Gitlawb/node/commit/b4016dce9d1fe450603173f9d92bd880127620fa)), closes [#298](https://github.com/Gitlawb/node/issues/298)
|
||||
* **node:** add a shared owner/name slug validator ([#272](https://github.com/Gitlawb/node/issues/272)) ([51d82de](https://github.com/Gitlawb/node/commit/51d82ded57a776d9c7e2fe65895efdbf9e227dc8))
|
||||
* **node:** bound the slug owner by NAME_MAX, not the DID limit ([#272](https://github.com/Gitlawb/node/issues/272)) ([27b0495](https://github.com/Gitlawb/node/commit/27b0495a6f7edeecddbe62b0f075a7e3b1ef5053))
|
||||
* **node:** fail a sync row terminally when a non-directory holds the owner path ([2e664b7](https://github.com/Gitlawb/node/commit/2e664b7885036ee72ce175af95bb567b18222583))
|
||||
* **node:** make a stalled sync queue visible, and fix two test claims ([9aa4c17](https://github.com/Gitlawb/node/commit/9aa4c17aefd1885d134b1334b54551366cdd8ef0))
|
||||
* **node:** move the attempted_at migration to v17, clear of two open branches ([fbc5868](https://github.com/Gitlawb/node/commit/fbc5868bd16946ea184dad26abcdb0e89d68e99a))
|
||||
* **node:** prove the mirror path is inside repos_dir before running git ([#272](https://github.com/Gitlawb/node/issues/272)) ([3ca9473](https://github.com/Gitlawb/node/commit/3ca94739ed7b90e4c265a0947025dc3b50e7583b))
|
||||
* **node:** reject a malformed slug at the notify boundary ([#272](https://github.com/Gitlawb/node/issues/272)) ([c587a40](https://github.com/Gitlawb/node/commit/c587a40a508acea9f74c3468d42ff037397c75d0))
|
||||
* **node:** reset a peer's reachability gate when an announce changes its http_url ([#270](https://github.com/Gitlawb/node/issues/270)) ([1964f88](https://github.com/Gitlawb/node/commit/1964f88378fe6942ffca5836de3a092b5b8f67b4))
|
||||
* **node:** reset a peer's reachability gate when an announce changes its http_url ([#270](https://github.com/Gitlawb/node/issues/270)) ([e2560ee](https://github.com/Gitlawb/node/commit/e2560ee46c28e4e966d87867a86dc4bad4ca7a3a))
|
||||
* **node:** stamp every dequeued sync row so a stuck one yields the batch ([6e64d0d](https://github.com/Gitlawb/node/commit/6e64d0d0a7fdd38ef3a56820c1808dd7c9bbd658))
|
||||
* **node:** stop a peer-supplied repo slug from escaping repos_dir ([#272](https://github.com/Gitlawb/node/issues/272)) ([c70b1df](https://github.com/Gitlawb/node/commit/c70b1df42d5c3f70ec4c272886c85fcc16ed92d1))
|
||||
* **node:** validate the queued slug before the worker derives a path ([#272](https://github.com/Gitlawb/node/issues/272)) ([9f00e24](https://github.com/Gitlawb/node/commit/9f00e24aec217e4b8256dd437cff4741b1478b96))
|
||||
* **review:** correct two comment claims and guard two more wrong shapes ([#270](https://github.com/Gitlawb/node/issues/270)) ([811ad50](https://github.com/Gitlawb/node/commit/811ad504bc268c8e9cddac93822adcd00bfe9ff8))
|
||||
* **review:** stop the dequeue overclaiming, and pin the starvation premise ([457be11](https://github.com/Gitlawb/node/commit/457be11d728a2a34775cf96be2bc5af9a58cb250))
|
||||
* strict DID matching in get_profile ([acb4714](https://github.com/Gitlawb/node/commit/acb47145beec8ce7b20b7a2479f7a55ed68e2a89))
|
||||
* strict DID matching in get_profile ([13b565b](https://github.com/Gitlawb/node/commit/13b565bcac09f075a7fd555a6e9acdd27de6c7bb))
|
||||
* target stored did on profile update aliases ([9836c3a](https://github.com/Gitlawb/node/commit/9836c3a21bc96a2ce95cb1fd12bd84b22142787d))
|
||||
|
||||
## [0.7.0](https://github.com/Gitlawb/node/compare/v0.6.0...v0.7.0) (2026-07-22)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **gl:** actually verify certificate signatures in gl cert show ([b0a2ed8](https://github.com/Gitlawb/node/commit/b0a2ed830821b5a77b0dafdcf5ce4b1ad904ec25))
|
||||
* **gl:** doctor warns when a shell alias shadows the gl binary ([0765c42](https://github.com/Gitlawb/node/commit/0765c42feff47b29054b9a277881a7cd5bfd9135))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **gl:** address review findings — non-fatal DID check, exact-host loopback, detached HEAD, multi-URL remotes, command-aware unalias ([3fa38dc](https://github.com/Gitlawb/node/commit/3fa38dce4e435ef017f607d355266c2892161f8d))
|
||||
* **gl:** anchor cert --verify to a trusted issuer; pin canonical payload form ([c681af7](https://github.com/Gitlawb/node/commit/c681af70dba3a76b11795d324f2ca0fecf7e42fd))
|
||||
* **gl:** detect gitlawb remotes beyond origin in gl status ([2d88937](https://github.com/Gitlawb/node/commit/2d88937fbabf21013f28debb4d4f93270a4bb8cd))
|
||||
* **gl:** doctor treats a reachable local node as configuration, not failure ([94c61f7](https://github.com/Gitlawb/node/commit/94c61f79421fa26ecc1bdf7c255e0c48e66a2048))
|
||||
* **gl:** make gl init's push guidance match the repo's actual state ([cb42a48](https://github.com/Gitlawb/node/commit/cb42a4830d0d070165e2212f316d009ec716dbee))
|
||||
* warn about the oh-my-zsh gl alias at install time ([e3df51d](https://github.com/Gitlawb/node/commit/e3df51d76c0275fde33954ff0af0aab95fd0cb7d))
|
||||
|
||||
## [0.6.0](https://github.com/Gitlawb/node/compare/v0.5.1...v0.6.0) (2026-07-22)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **icaptcha-client:** solve the iCaptcha proof-of-work on answer ([#181](https://github.com/Gitlawb/node/issues/181)) ([c98b503](https://github.com/Gitlawb/node/commit/c98b503f90cade54ce9c588bd2373a4e3486f2fc))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **core:** honor wildcard capabilities in Ucan::can, matching is_attenuated_by ([#200](https://github.com/Gitlawb/node/issues/200)) ([b6877a6](https://github.com/Gitlawb/node/commit/b6877a65981dbf41c4a7838971eb5c826c7fcaf2))
|
||||
* **gl:** point doctor's version check at Gitlawb/node, not the frozen Gitlawb/releases repo ([#198](https://github.com/Gitlawb/node/issues/198)) ([98d728c](https://github.com/Gitlawb/node/commit/98d728c325f68f0ee4a62e473dc484b7dd627504))
|
||||
* **node:** carry full owner DID on ref-update wire event ([#144](https://github.com/Gitlawb/node/issues/144)) ([#145](https://github.com/Gitlawb/node/issues/145)) ([69a62e5](https://github.com/Gitlawb/node/commit/69a62e51c2d2f090f9cae88f4d8ce3b9017b7149))
|
||||
* **node:** gate /hooks and sibling read surfaces leaking private repo metadata ([#94](https://github.com/Gitlawb/node/issues/94)) ([#113](https://github.com/Gitlawb/node/issues/113)) ([ee8d7c0](https://github.com/Gitlawb/node/commit/ee8d7c03b26a0b678cc90b8801aa340fe81da700))
|
||||
* strip Cf bidi/format controls in terminal-bound error sanitizers ([#183](https://github.com/Gitlawb/node/issues/183)) ([#188](https://github.com/Gitlawb/node/issues/188)) ([b07d41e](https://github.com/Gitlawb/node/commit/b07d41ea97569d79d3f545ae5d43c373cd6f0f33))
|
||||
|
||||
## [0.5.1](https://github.com/Gitlawb/node/compare/v0.5.0...v0.5.1) (2026-07-10)
|
||||
|
||||
|
||||
|
||||
+2
-5
@@ -31,9 +31,7 @@ crates/
|
||||
├── gitlawb-core/ crypto primitives (DID, CID, HTTP sigs, UCAN, ref certs)
|
||||
├── gitlawb-node/ axum HTTP server, git smart HTTP, P2P, GraphQL
|
||||
├── gl/ CLI — identity, repos, MCP server, Base L2 names
|
||||
├── git-remote-gitlawb/ git remote helper for gitlawb:// URLs
|
||||
├── gitlawb-attest/ provenance attestations for ref-update certificates
|
||||
└── icaptcha-client/ client for the iCaptcha proof-of-intelligence service
|
||||
└── git-remote-gitlawb/ git remote helper for gitlawb:// URLs
|
||||
docs/ Operator guides
|
||||
scripts/ Build helpers
|
||||
```
|
||||
@@ -56,7 +54,6 @@ Smart contracts live in a separate repo: [github.com/Gitlawb/contracts](https://
|
||||
3. **No breaking changes without discussion.** Open an issue first for protocol-level changes.
|
||||
4. **Conventional commits.** Use `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`. Releases are automated by [release-please](https://github.com/googleapis/release-please) — your commit prefixes drive the next version bump.
|
||||
5. **Format and lint.** Run `cargo fmt --all` and `cargo clippy --workspace --all-targets -- -D warnings` before submitting. CI will reject anything that fails these.
|
||||
6. **Security-surface rules.** [`AGENTS.md`](AGENTS.md) carries the authorization invariants PRs most often break; it is written for coding agents and humans alike, so read it before touching endpoints, visibility, or migrations.
|
||||
|
||||
## What gets merged, what gets closed
|
||||
|
||||
@@ -108,7 +105,7 @@ cargo test -p gitlawb-node
|
||||
|
||||
- **TypeScript SDK** (`@gitlawb/sdk`) — client library for the HTTP API
|
||||
- **Python SDK** (`gitlawb`) — for ML/agent pipeline integration
|
||||
- **UCAN authorization** — add trusted issuer anchoring, capability checks, and authorization-aware revocation
|
||||
- **UCAN chain validation** — complete the auth middleware
|
||||
- **Filecoin storage tier** — wire up cold storage deals
|
||||
- **Documentation** — guides, tutorials, API examples
|
||||
- **Node operators** — run a public node and report issues
|
||||
|
||||
Generated
+12
-93
@@ -770,23 +770,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-ff"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7a806ac6c8307b929df4645776290a50ee2aac754ad09d8bdf73391309e43af"
|
||||
dependencies = [
|
||||
"ark-ff-asm 0.6.0",
|
||||
"ark-ff-macros 0.6.0",
|
||||
"ark-serialize 0.6.0",
|
||||
"ark-std 0.6.0",
|
||||
"digest 0.10.7",
|
||||
"educe",
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-ff-asm"
|
||||
version = "0.3.0"
|
||||
@@ -817,16 +800,6 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-ff-asm"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1479009684adc073dff49a1025d3a7065b317a9ead25aaaca38cdc70058ba8a2"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-ff-macros"
|
||||
version = "0.3.0"
|
||||
@@ -865,19 +838,6 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-ff-macros"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-serialize"
|
||||
version = "0.3.0"
|
||||
@@ -911,30 +871,6 @@ dependencies = [
|
||||
"num-bigint",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-serialize"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b"
|
||||
dependencies = [
|
||||
"ark-serialize-derive",
|
||||
"ark-std 0.6.0",
|
||||
"digest 0.10.7",
|
||||
"num-bigint",
|
||||
"serde_with",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-serialize-derive"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f153690697a2b91e5e1251ff98411ee5371500a111a0fd317a70e588eb300f9"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-std"
|
||||
version = "0.3.0"
|
||||
@@ -965,16 +901,6 @@ dependencies = [
|
||||
"rand 0.8.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ark-std"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"rand 0.8.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayref"
|
||||
version = "0.3.9"
|
||||
@@ -3374,22 +3300,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "git-remote-gitlawb"
|
||||
version = "0.7.1"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
"libc",
|
||||
"mockito",
|
||||
"reqwest",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-attest"
|
||||
version = "0.7.1"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"ed25519-dalek",
|
||||
@@ -3406,7 +3329,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-core"
|
||||
version = "0.7.1"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
@@ -3427,14 +3350,13 @@ dependencies = [
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"url",
|
||||
"uuid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-node"
|
||||
version = "0.7.1"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
@@ -3490,11 +3412,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gl"
|
||||
version = "0.7.1"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"clap",
|
||||
"dirs",
|
||||
@@ -3543,9 +3464,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.18"
|
||||
version = "0.4.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228"
|
||||
checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -3864,7 +3785,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.3",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -3900,7 +3821,6 @@ version = "0.4.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
"mockito",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5432,7 +5352,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.3",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -5469,7 +5389,7 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.3",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
@@ -5819,15 +5739,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruint"
|
||||
version = "1.20.0"
|
||||
version = "1.17.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e99bff0393163bb25029a6af25d3d8d202ba5b5438a74d1bd8789f5c822970"
|
||||
checksum = "c141e807189ad38a07276942c6623032d3753c8859c146104ac2e4d68865945a"
|
||||
dependencies = [
|
||||
"alloy-rlp",
|
||||
"ark-ff 0.3.0",
|
||||
"ark-ff 0.4.2",
|
||||
"ark-ff 0.5.0",
|
||||
"ark-ff 0.6.0",
|
||||
"bytes",
|
||||
"fastrlp 0.3.1",
|
||||
"fastrlp 0.4.0",
|
||||
|
||||
@@ -53,9 +53,6 @@ chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
# http client
|
||||
reqwest = { version = "0.12", features = ["blocking", "json", "multipart", "rustls-tls"], default-features = false }
|
||||
# URL parsing (what reqwest::Url re-exports, so the shared redirect predicate can
|
||||
# take a parsed URL without pulling reqwest into gitlawb-core)
|
||||
url = "2"
|
||||
# HMAC
|
||||
hmac = "0.12"
|
||||
|
||||
|
||||
+5
-18
@@ -8,33 +8,20 @@ FROM rust:1.91-bookworm AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Cache dependencies first for faster rebuilds.
|
||||
# EVERY workspace member's manifest must be copied here, not just the ones this
|
||||
# image ships: cargo loads the whole workspace before it resolves anything, so a
|
||||
# missing member's Cargo.toml (or a path dependency pointing at one) aborts the
|
||||
# layer before a single crate is fetched.
|
||||
# Cache dependencies first for faster rebuilds
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates/gitlawb-core/Cargo.toml crates/gitlawb-core/
|
||||
COPY crates/gitlawb-node/Cargo.toml crates/gitlawb-node/
|
||||
COPY crates/gl/Cargo.toml crates/gl/
|
||||
COPY crates/git-remote-gitlawb/Cargo.toml crates/git-remote-gitlawb/
|
||||
COPY crates/gitlawb-attest/Cargo.toml crates/gitlawb-attest/
|
||||
COPY crates/icaptcha-client/Cargo.toml crates/icaptcha-client/
|
||||
|
||||
# Fetch deps (this layer caches until Cargo.{toml,lock} change).
|
||||
# No `|| true`: this layer is expected to succeed, and swallowing its exit code
|
||||
# is what let it sit dead from the moment gl gained a path dependency on
|
||||
# icaptcha-client. A failure here should stop the build, not silently turn every
|
||||
# image build into a cold one.
|
||||
RUN mkdir -p crates/gitlawb-core/src crates/gitlawb-node/src crates/gl/src \
|
||||
crates/git-remote-gitlawb/src crates/gitlawb-attest/src crates/icaptcha-client/src && \
|
||||
# Fetch deps (this layer caches until Cargo.{toml,lock} change)
|
||||
RUN mkdir -p crates/gitlawb-core/src crates/gitlawb-node/src crates/gl/src crates/git-remote-gitlawb/src && \
|
||||
echo 'fn main() {}' > crates/gitlawb-node/src/main.rs && \
|
||||
echo 'fn main() {}' > crates/gl/src/main.rs && \
|
||||
echo 'fn main() {}' > crates/git-remote-gitlawb/src/main.rs && \
|
||||
echo '' > crates/gitlawb-core/src/lib.rs && \
|
||||
echo '' > crates/gitlawb-attest/src/lib.rs && \
|
||||
echo '' > crates/icaptcha-client/src/lib.rs && \
|
||||
cargo build --release --locked -p gitlawb-node -p gl -p git-remote-gitlawb
|
||||
cargo build --release -p gitlawb-node -p gl -p git-remote-gitlawb || true
|
||||
|
||||
# Now copy real sources and build for real.
|
||||
# Force-bump mtimes so cargo's fingerprint check rebuilds — without this,
|
||||
@@ -47,7 +34,7 @@ RUN find crates -name "*.rs" -exec touch {} + && \
|
||||
rm -rf target/release/.fingerprint/gitlawb-node-* \
|
||||
target/release/.fingerprint/gl-* \
|
||||
target/release/.fingerprint/git-remote-gitlawb-* && \
|
||||
cargo build --release --locked -p gitlawb-node -p gl -p git-remote-gitlawb && \
|
||||
cargo build --release -p gitlawb-node -p gl -p git-remote-gitlawb && \
|
||||
strip target/release/gitlawb-node target/release/gl target/release/git-remote-gitlawb
|
||||
|
||||
# ── Runtime stage ───────────────────────────────────────────────────────────
|
||||
|
||||
+2
-5
@@ -3,10 +3,7 @@
|
||||
# Used by scripts/build-bins.sh — not used for node deployment.
|
||||
ARG TARGET=x86_64-unknown-linux-musl
|
||||
|
||||
# Must stay at or above the workspace `rust-version` in Cargo.toml. An unmet
|
||||
# MSRV is a hard cargo error, and nothing in CI builds this file, so a stale
|
||||
# base image here fails only when someone runs scripts/build-bins.sh.
|
||||
FROM rust:1.91-bookworm AS builder
|
||||
FROM rust:1.85-bookworm AS builder
|
||||
ARG TARGET
|
||||
|
||||
WORKDIR /build
|
||||
@@ -26,7 +23,7 @@ COPY crates/ crates/
|
||||
# Configure cross-linker for aarch64
|
||||
ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc
|
||||
|
||||
RUN cargo build --release --locked --target "$TARGET" -p gl -p git-remote-gitlawb
|
||||
RUN cargo build --release --target "$TARGET" -p gl -p git-remote-gitlawb
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
ARG TARGET
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
Gitlawb Node is the open-source node software behind the Gitlawb network. It lets anyone run a self-hosted node, publish repositories under a DID, sign writes with Ed25519 HTTP signatures, replicate git activity across peers, and move toward a resilient app-delivery network where code and build assets can be served closer to users.
|
||||
|
||||
Gitlawb is not trying to be only "another git host." The long-term direction is:
|
||||
Gitlawb is not trying to be only “another git host.” The long-term direction is:
|
||||
|
||||
```txt
|
||||
Decentralized GitHub
|
||||
@@ -19,7 +19,7 @@ The mission is simple: once code is pushed to the network, it should not disappe
|
||||
|
||||
## What is in this repository?
|
||||
|
||||
This is a Rust workspace with six crates:
|
||||
This is a Rust workspace with four crates:
|
||||
|
||||
| Crate | Purpose |
|
||||
|---|---|
|
||||
@@ -27,8 +27,6 @@ This is a Rust workspace with six crates:
|
||||
| `gl` | The Gitlawb CLI for identity, repos, issues, PRs, bounties, tasks, peers, node status, MCP, and setup flows. |
|
||||
| `git-remote-gitlawb` | Git remote helper for `gitlawb://` URLs, so normal `git clone`, `git fetch`, and `git push` can talk to Gitlawb nodes. |
|
||||
| `gitlawb-core` | Shared primitives: Ed25519 identities, `did:key`, CIDs, RFC 9421 HTTP signatures, certificates, and UCAN tokens. |
|
||||
| `gitlawb-attest` | Pluggable external provenance attestations for ref-update certificates. |
|
||||
| `icaptcha-client` | Client for the iCaptcha proof-of-intelligence flow used to protect spam-prone writes. |
|
||||
|
||||
---
|
||||
|
||||
@@ -36,12 +34,12 @@ This is a Rust workspace with six crates:
|
||||
|
||||
Most git hosting today depends on a small number of centralized platforms. Gitlawb Nodes are designed for a different model:
|
||||
|
||||
- **Own your identity**: every user, agent, and node is an Ed25519 keypair represented as `did:key:z6Mk...`.
|
||||
- **Signed writes by default**: write requests use RFC 9421 HTTP Signatures instead of passwords.
|
||||
- **Git-native transport**: repositories are still real git repositories served over smart HTTP.
|
||||
- **Agent-native workflows**: the `gl` CLI and MCP server expose repo, issue, task, PR, and UCAN flows to AI agents.
|
||||
- **Peer-aware delivery**: nodes can announce, discover, gossip, and sync with each other.
|
||||
- **App CDN direction**: the network can evolve from decentralized code storage into code + asset + app delivery.
|
||||
- **Own your identity** — every user, agent, and node is an Ed25519 keypair represented as `did:key:z6Mk...`.
|
||||
- **Signed writes by default** — write requests use RFC 9421 HTTP Signatures instead of passwords.
|
||||
- **Git-native transport** — repositories are still real git repositories served over smart HTTP.
|
||||
- **Agent-native workflows** — the `gl` CLI and MCP server expose repo, issue, task, PR, and UCAN flows to AI agents.
|
||||
- **Peer-aware delivery** — nodes can announce, discover, gossip, and sync with each other.
|
||||
- **App CDN direction** — the network can evolve from decentralized code storage into code + asset + app delivery.
|
||||
|
||||
---
|
||||
|
||||
@@ -56,7 +54,6 @@ Good today:
|
||||
- Bare git repository storage.
|
||||
- Git smart-HTTP clone/fetch/push.
|
||||
- RFC 9421-signed writes.
|
||||
- Repository and path-scoped visibility enforcement for repository and Git content reads, with 404-shaped repository denials.
|
||||
- DID identities.
|
||||
- `gl` CLI workflows.
|
||||
- libp2p peer discovery/gossip foundation.
|
||||
@@ -66,13 +63,11 @@ Good today:
|
||||
|
||||
Known limitations:
|
||||
|
||||
- Repository write authorization is not secure by default: `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `false` for compatibility, so a valid HTTP Signature identifies a pusher but does not enforce owner-only pushes.
|
||||
- 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.
|
||||
- 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.
|
||||
- Private repository read enforcement is not wired yet. Treat public nodes as public infrastructure unless you restrict access at your proxy/firewall.
|
||||
- UCAN chain validation and revocation are not complete.
|
||||
- Repository write authorization is not capability-complete yet; HTTP signatures prove identity, not full authorization policy.
|
||||
- Peer writes are signed by upgraded nodes, but strict signed-peer enforcement is opt-in during rolling upgrades.
|
||||
- Current GraphQL mutations require an authenticated signer, but there is no mutation-specific guardrail that prevents a future mutation from omitting that check.
|
||||
- Pull-request review comments do not yet have threaded line-level anchors, and merges do not enforce approval requirements.
|
||||
- GraphQL mutations need mutation-aware auth before becoming a public write surface.
|
||||
|
||||
See:
|
||||
|
||||
@@ -194,14 +189,14 @@ For public-network use, make sure `GITLAWB_NODE` points to the node you want. Th
|
||||
|
||||
Public nodes (e.g. `node.gitlawb.com`) require two things on writes:
|
||||
|
||||
1. **RFC 9421 HTTP Signatures**: every write is signed by your identity key. `gl`
|
||||
1. **RFC 9421 HTTP Signatures** — every write is signed by your identity key. `gl`
|
||||
and the `git-remote-gitlawb` helper do this automatically. An old/unsigned CLI
|
||||
fails with `401 not_an_agent`; `gl` will tell you to upgrade and register.
|
||||
2. **An iCaptcha proof** on the spam-gated writes (**repo create, fork, register**).
|
||||
`gl` solves this for you: on the node's `403 icaptcha_proof_required` it reads the
|
||||
`x-icaptcha-url` / `x-icaptcha-level` hints, requests a challenge, solves it
|
||||
locally (arithmetic / algebra / sequence), and **retries the same signed request**
|
||||
with the `x-icaptcha-proof` header. No manual steps, no env vars.
|
||||
with the `x-icaptcha-proof` header — no manual steps, no env vars.
|
||||
|
||||
```bash
|
||||
gl identity new # create did:key identity
|
||||
@@ -220,61 +215,14 @@ Notes:
|
||||
- **Proofs are short-lived (~5 min TTL) and single-use.** If one expires between
|
||||
solving and use, the client transparently solves a fresh one and retries.
|
||||
- **What needs what:** create / fork / register are signed **and** iCaptcha-gated;
|
||||
`git push` is **signed-only** (owner signature is the gate, no per-push challenge);
|
||||
`git push` is **signed-only** (owner signature is the gate — no per-push challenge);
|
||||
reads (clone / fetch / `repo info`) need no proof. A non-existent repo returns a
|
||||
clear `404`, never a placeholder.
|
||||
- **API-key iCaptcha deployments:** set `GITLAWB_ICAPTCHA_URL` to your iCaptcha
|
||||
origin and `GITLAWB_ICAPTCHA_API_KEY` to its key. The client only talks to an
|
||||
`https` origin whose host is allowlisted (that URL or the public default), and
|
||||
sends the bearer token **only** to your configured origin, never to a URL a
|
||||
node advertises, so a hostile node can't capture the key or redirect the solve.
|
||||
|
||||
### Fetching an object by CID
|
||||
|
||||
```bash
|
||||
gl ipfs list # CIDs this node has pinned
|
||||
gl ipfs get bafkrei... > object.bin # object bytes on stdout
|
||||
```
|
||||
|
||||
Objects that were pinned before the node started recording which repo they came
|
||||
from are found by scanning its repo inventory, and that scan stops at the
|
||||
per-request ceilings in the [Configuration](#configuration) table. A stopped scan
|
||||
answers 503 with a resume token instead of a false "not found", and `gl ipfs get`
|
||||
follows the token automatically: up to 8 resumes after the first request, so at
|
||||
most 9 calls to the node, waiting between attempts for as long as the node's
|
||||
`Retry-After` asks and never longer than 5 seconds.
|
||||
|
||||
The whole ladder runs under a 60 second wall-clock deadline. The deadline bounds
|
||||
the search, not the download: each attempt gets the time left on it to produce
|
||||
response headers, and once an object is found its bytes stream outside that
|
||||
deadline. They are not unbounded, though. The client's own 30 second HTTP timeout
|
||||
is a total request timeout, running from the start of a request until its body
|
||||
has finished, so a transfer still going 30 seconds after its request began is cut
|
||||
off. Waits between attempts never run past the deadline either, so a single run
|
||||
spends at most around 90 seconds on the network: the deadline plus the 30 second
|
||||
timeout covering the last attempt. Writing the object out sits outside both
|
||||
bounds, so piping into a reader that stops reading can hold the command open
|
||||
longer than that.
|
||||
|
||||
Two node-side brakes end a ladder early and are reported rather than retried
|
||||
around. A 429 is terminal, because the node's rate-limit window is an hour and
|
||||
that wait cannot be honored inside one invocation; a transient overload (a 503
|
||||
carrying no incomplete-scan code) is retried on the token already held, under the
|
||||
same cap, clamp and deadline. The per-IP fanout brake can also stop a ladder well
|
||||
short of the 9 calls, so automatic resumption is not a guarantee of reaching the
|
||||
object.
|
||||
|
||||
When a bound stops the ladder with a usable token in hand, the command prints the
|
||||
token and the invocation that continues from it before exiting nonzero:
|
||||
|
||||
```txt
|
||||
resume from where this stopped: gl ipfs get bafkrei... --scan <token>
|
||||
```
|
||||
|
||||
Run that to carry on from where the scan stopped. Re-running without `--scan`
|
||||
restarts at the first row, reproduces the same truncation and spends the node's
|
||||
per-IP budget again, so the token is the only thing that makes progress. Tokens
|
||||
are valid for an hour.
|
||||
sends the bearer token **only** to your configured origin — never to a URL a
|
||||
node advertises — so a hostile node can't capture the key or redirect the solve.
|
||||
|
||||
---
|
||||
|
||||
@@ -361,7 +309,7 @@ POST /api/v1/peers/announce
|
||||
POST /api/v1/sync/notify
|
||||
```
|
||||
|
||||
When `GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false`, unsigned legacy peers are accepted on those two routes, but signed requests are verified when signature headers are present. Staged rollout relaxes who may announce, not who owns a peer row. An unsigned announce may register a previously unseen peer, and it may refresh an existing row whose `http_url` is unchanged, but changing an existing peer's `http_url` requires an RFC 9421 signature from that peer's own DID and is refused with 403 otherwise. An unsigned announce can only register a `did:key`, since that is the only method whose verifying key can be resolved and therefore the only kind of row anyone could ever correct through the signed path; any other DID is refused with 400. Once all live peers upgrade, operators can set:
|
||||
When `GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false`, unsigned legacy peers are accepted on those two routes, but signed requests are verified when signature headers are present. Once all live peers upgrade, operators can set:
|
||||
|
||||
```bash
|
||||
GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true
|
||||
@@ -392,25 +340,14 @@ Important node settings:
|
||||
| `GITLAWB_BOOTSTRAP_PEERS` | Comma-separated HTTP peer URLs. |
|
||||
| `GITLAWB_P2P_BOOTSTRAP` | Comma-separated libp2p multiaddrs. |
|
||||
| `GITLAWB_BOOTSTRAP_DISABLE_SEEDS` | Disable embedded seed peers for isolated dev/test networks. |
|
||||
| `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` | Require signed peer announce/sync writes. Defaults to `false` during the staged rollout below. |
|
||||
| `GITLAWB_ENFORCE_OWNER_PUSH` | Require the authenticated pusher to be the repo owner on `git-receive-pack`. **Defaults to `true`.** A `did:key` signature is authentication, not authorization — anyone can mint a key and sign — so with this off every signed caller may push to every repository, private ones included. 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. Set `false` only for a rolling upgrade; see [`docs/RUN-A-NODE.md`](docs/RUN-A-NODE.md). |
|
||||
| `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` | Require signed peer announce/sync writes. |
|
||||
| `GITLAWB_AUTO_SYNC` | Enable automatic sync from known peers. |
|
||||
| `GITLAWB_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. |
|
||||
| `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. |
|
||||
| `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. |
|
||||
| `GITLAWB_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. |
|
||||
| `GITLAWB_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `GITLAWB_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. |
|
||||
| `GITLAWB_MAX_CONCURRENT_GIT_PUSHES` | Max concurrent `git-receive-pack` POST operations, in a pool separate from the read pool. The anon receive-pack `info/refs` advertisement runs in a third pool of the same size, disjoint from both, so an advertisement flood cannot shed a push either. Two per-source push caps are derived from this value (`/8`, floor 1) and have no env var of their own. Over-cap sheds a 503 + Retry-After. Default 32. |
|
||||
| `GITLAWB_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as `GITLAWB_TRUSTED_PROXY`: left unset, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. |
|
||||
| `GITLAWB_MAX_CONCURRENT_PIN_TASKS` | Max post-push pin loops (IPFS + Pinata) running concurrently across all repos. This caps how many loops RUN at once, not how much object-id list memory the node retains: on the local IPFS path a loop parked waiting for a permit still holds its full list. Do not size memory from this knob alone. A loop over cap waits, never drops a pin. Default 8. |
|
||||
| `GITLAWB_REPO_LEASE_MAX_WAITERS` | Max pushes parked at once waiting for the same repo's write lease. Each waiter pins its buffered pack body, so this bounds that memory for a hot repo; past the cap the newest push sheds a 503 + Retry-After instead of queueing. Pushes to other repos are unaffected, and the lease holder is not counted. Default 8. |
|
||||
| `GITLAWB_MAX_CONCURRENT_IPFS_WALKS` | Max concurrent `GET /ipfs/{cid}` visibility walks across all callers (own pool, disjoint from the served-git pools); over-cap sheds 503. Default 32. |
|
||||
| `GITLAWB_IPFS_WALK_PER_SOURCE` | Max concurrent `/ipfs` walks a single source IP may hold. Default 4. |
|
||||
| `GITLAWB_IPFS_MAX_LEGACY_PROBES` | Max legacy (NULL-provenance) repos probed per `/ipfs/{cid}` request, bounding the scan-fallback fan-out. A truncated scan returns a retryable 503, not a false 404. Default 256. |
|
||||
| `GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS` | Max repo rows one `/ipfs/{cid}` request's legacy scan may read from the database. The probe ceiling above only starts counting once a probe runs, and quarantined or private repos are denied before that, so this is what bounds a scan over an inventory that denies the caller everywhere. A truncated scan sheds a retryable 503 carrying an opaque `continuation` token; echoing it as `?scan=` resumes the scan where it stopped. Every per-request ceiling on this path (rows, probes, visits, retained rule bytes) mints one, so each request advances the ladder by at least the rows it read and a holder buried past a ceiling is reached in a bounded number of requests, `ceil(repos / ceiling) + 1` when this row ceiling is the one that binds. No ceiling ever produces a 404. Every page is charged to the caller's `/ipfs` work allowance, so raising this raises that allowance too. Lowering it sharpens an oracle: because a truncation emits a token and a completed wrap does not, laddering to the end reveals the node's total repo count (private and quarantined included) to within one ceiling. Default 2048. |
|
||||
| `GITLAWB_IPFS_MAX_REPOS_WALKED` | Max expensive path-scope visibility walks a `/ipfs/{cid}` request may run per phase; over-cap repos are skipped and the scan continues, shedding a retryable 503 (not a false 404) if the object is then found nowhere. The effective cap is the tighter of this knob and the node's internal history-walk ceiling of 17 (`MAX_PIN_SOURCES + 1`), so a value above 17 has no effect while a value below it does tighten the cap. It is charged per phase: the provenance lookup and the legacy-scan fallback get separate equal budgets, so one request can run up to twice the cap in total. Default 64. |
|
||||
| `GITLAWB_IPFS_MAX_REPO_VISITS` | Ceiling on repos one `/ipfs/{cid}` request may visit (acquire + probe) past the visibility gate. Also the worst-case per-request Tigris fetch count. On exhaustion the scan stops with a retryable 503. Default 1024. |
|
||||
| `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_MAX_REPOS_WALKED` | Max legacy (NULL-provenance) repos probed per `/ipfs/{cid}` request, bounding the scan-fallback fan-out. A truncated scan returns a retryable 503, not a false 404. Default 256. |
|
||||
| `GITLAWB_IPFS_RATE_LIMIT` | Max `/ipfs/{cid}` requests per client IP per hour (route flood brake). 0 disables. Default 600. |
|
||||
| `GITLAWB_TIGRIS_BUCKET` | Optional S3/Tigris shared repo storage bucket. |
|
||||
| `GITLAWB_PINATA_JWT` | Optional Pinata/IPFS warm-storage pinning. |
|
||||
@@ -524,8 +461,8 @@ Short-term priorities:
|
||||
2. Add Docker and installer smoke tests.
|
||||
3. Improve operator docs and `gl doctor` checks.
|
||||
4. Harden peer writes and publish the signed-peer rollout plan.
|
||||
5. Close default-open write authorization and wire trusted UCAN delegation into repository permissions.
|
||||
6. Add threaded, line-level pull-request discussions and enforce approval requirements on merges.
|
||||
5. Implement repo write authorization: owner checks, protected branches, and UCAN capability checks.
|
||||
6. Implement private-read enforcement or remove private repo affordances until it exists.
|
||||
7. Add metrics for pushes, fetches, pack sizes, peer sync, failed auth, and webhooks.
|
||||
|
||||
Product direction:
|
||||
|
||||
+22
-32
@@ -28,11 +28,10 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 14 d
|
||||
- Every git object is content-addressed via CIDv1 (SHA-256)
|
||||
- Tamper-evident by construction — a modified object changes its CID
|
||||
|
||||
**UCAN token validation**
|
||||
- Bootstrap UCAN tokens are issued at registration.
|
||||
- A supplied token's signature, audience, expiry, and proof-chain attenuation are validated.
|
||||
- Tokens use a signed JSON wire format with expiry.
|
||||
- Capability grants are not yet consulted by repository write authorization; see the limitations below.
|
||||
**UCAN capability tokens**
|
||||
- Bootstrap UCAN tokens issued at registration
|
||||
- Capability-scoped: `git:push`, `git:fetch`, `issue:create`, `pr:open`
|
||||
- JWT-format tokens with expiry
|
||||
|
||||
**Smart contracts (Base Sepolia testnet)**
|
||||
- `GitlawbDIDRegistry` — on-chain DID → document registry
|
||||
@@ -49,20 +48,21 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 14 d
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations
|
||||
## Known Limitations (Planned for v0.2)
|
||||
|
||||
These are documented limitations of the current live release. They should be prioritized without breaking existing nodes during rolling upgrades.
|
||||
These are **documented, accepted limitations** for the current live release and should be prioritized without breaking existing nodes during rolling upgrades.
|
||||
|
||||
### Repository write authorization defaults
|
||||
- `git-receive-pack` verifies HTTP Signatures, but `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `false` for compatibility during rollout.
|
||||
- **Impact:** With the default setting, a valid signature authenticates the pusher but does not require that DID to be the repository owner.
|
||||
- **Mitigation:** Set `GITLAWB_ENFORCE_OWNER_PUSH=true` on nodes where owner-only pushes are required. Confirm that every legitimate pusher uses the owner DID before enabling it.
|
||||
### UCAN chain validation
|
||||
- The auth middleware verifies HTTP Signatures and token structure, but does not yet walk the full UCAN delegation chain.
|
||||
- **Impact:** A node cannot yet enforce fine-grained capability delegation. Currently, any registered agent with a valid HTTP Signature can push.
|
||||
- **Mitigation:** Keep write endpoints signed, treat public nodes as public infrastructure, and treat trust scores as soft rate-limiting signals rather than authorization.
|
||||
- **Fix target:** v0.2
|
||||
|
||||
### UCAN delegation and revocation
|
||||
- The middleware validates a supplied UCAN's complete proof chain, but a root token is accepted without an independently trusted issuer anchor. `Ucan::can` is not yet used by write handlers, so a UCAN does not grant scoped repository access.
|
||||
- Agent lifecycle revocation is not checked by HTTP Signature authorization. Removing or revoking an agent record does not itself block a compromised DID from authenticating.
|
||||
- **Impact:** Do not use UCANs for collaborator permissions or rely on agent-record revocation as a key-compromise response.
|
||||
- **Mitigation:** Keep sensitive deployments behind operational network controls and enable owner-only push enforcement where it fits the deployment until trusted delegation and authorization-aware revocation are implemented.
|
||||
### UCAN revocation
|
||||
- Issued UCAN tokens cannot be revoked before expiry.
|
||||
- **Impact:** If a keypair is compromised, the attacker retains access until the UCAN expires (default: 30 days).
|
||||
- **Mitigation:** Regenerate your identity (`gl identity new --force`) and re-register to issue a new UCAN. Until revocation/blocklisting is implemented, operators should remove compromised DIDs directly from their local database.
|
||||
- **Fix target:** v0.2
|
||||
|
||||
### git-receive-pack authentication
|
||||
- The `git-receive-pack` endpoint enforces HTTP Signature auth. Plain Git smart-HTTP clients do not generate those headers, so the `git-remote-gitlawb` helper is required for pushes.
|
||||
@@ -71,20 +71,10 @@ These are documented limitations of the current live release. They should be pri
|
||||
- **Fix target:** v0.2
|
||||
|
||||
### 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.
|
||||
- `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.
|
||||
|
||||
### Pull-request review enforcement
|
||||
- Pull-request review comments are not yet threaded or line-anchored, and merges do not enforce required approvals.
|
||||
- **Impact:** Teams must use their own review policy or external controls for merge approval requirements.
|
||||
|
||||
### GraphQL mutation coverage
|
||||
- Existing GraphQL mutations require an authenticated signer, but a mutation-specific source-level guardrail has not yet been added for future mutations.
|
||||
- **Impact:** A new mutation could accidentally omit its signer check without an explicit test fence.
|
||||
- Repository records have an `is_public` field and the node exposes `GITLAWB_PUBLIC_READ`, but per-repository private-read enforcement is not wired in the current live release.
|
||||
- **Impact:** Do not store private repositories or secrets on public nodes.
|
||||
- **Mitigation:** Run isolated nodes for non-public data and restrict network access at the reverse proxy or firewall layer.
|
||||
- **Fix target:** v0.2
|
||||
|
||||
### Peer route hardening rollout
|
||||
- Peer announce and sync notification routes accept signed requests and verify DID matches when a signature is present.
|
||||
@@ -111,7 +101,7 @@ These are documented limitations of the current live release. They should be pri
|
||||
| Key storage | PKCS#8 PEM, 0600 permissions |
|
||||
| Content hashing | SHA-256 via CIDv1 |
|
||||
| HTTP Signatures | RFC 9421 (Ed25519 + SHA-256 Content-Digest) |
|
||||
| UCAN tokens | Signed JSON object (Ed25519 signature) |
|
||||
| UCAN tokens | JWT (Ed25519 signatures) |
|
||||
| On-chain | ECDSA secp256k1 (Base L2 / Ethereum) |
|
||||
|
||||
---
|
||||
@@ -119,7 +109,7 @@ These are documented limitations of the current live release. They should be pri
|
||||
## Threat Model
|
||||
|
||||
gitlawb is designed to be secure against:
|
||||
- **Unauthenticated writes** — HTTP Signature auth on protected write endpoints; see Known Limitations for owner and capability authorization gaps
|
||||
- **Unauthorized writes** — HTTP Signature auth on all write endpoints
|
||||
- **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
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
# Dependency allowlist for the `gitlawb-core` crate.
|
||||
#
|
||||
# gitlawb-core is the shared-primitives crate every consumer embeds (the `gl`
|
||||
# CLI, git-remote-gitlawb, the node daemon). It must stay lean so those
|
||||
# consumers do not inherit daemon-weight dependencies. This file is the source
|
||||
# of truth for the crates gitlawb-core's NORMAL (non-dev, non-build) transitive
|
||||
# dependency closure is allowed to contain. CI (`scripts/check-gitlawb-core-deps.sh`,
|
||||
# wired into the `core-deps-purity` job in .github/workflows/pr-checks.yml)
|
||||
# fails if gitlawb-core's tree contains any crate not listed here.
|
||||
#
|
||||
# The allowlist is exhaustive-by-construction: a NEW dependency reds CI whether
|
||||
# or not anyone thought to ban it, which a denylist cannot do.
|
||||
#
|
||||
# Measured in-workspace, so feature unification across the workspace can, in
|
||||
# rare cases, surface a crate here that gitlawb-core would not pull standalone.
|
||||
# An unexpected new entry is a prompt to check what pulled it in, not noise to
|
||||
# rubber-stamp.
|
||||
#
|
||||
# Regenerate (from repo root, after an INTENTIONAL dependency change):
|
||||
# cargo tree -p gitlawb-core --edges normal --prefix none \
|
||||
# | sed -E 's/ v[0-9].*$//' \
|
||||
# | grep -v '^gitlawb-core$' \
|
||||
# | sort -u
|
||||
# then paste the result below this header block. (The checker snapshots and
|
||||
# restores Cargo.lock; a manual regen may refresh it — `git checkout Cargo.lock`
|
||||
# afterward if you did not intend that.)
|
||||
#
|
||||
# Lines starting with `#` and blank lines are ignored by the checker.
|
||||
aead
|
||||
anyhow
|
||||
base-x
|
||||
base256emoji
|
||||
base64
|
||||
base64ct
|
||||
block-buffer
|
||||
cfg-if
|
||||
chacha20
|
||||
chacha20poly1305
|
||||
chrono
|
||||
cid
|
||||
cipher
|
||||
const-oid
|
||||
const-str
|
||||
core2
|
||||
cpufeatures
|
||||
crypto-common
|
||||
crypto_box
|
||||
crypto_secretbox
|
||||
curve25519-dalek
|
||||
curve25519-dalek-derive
|
||||
data-encoding
|
||||
data-encoding-macro
|
||||
data-encoding-macro-internal
|
||||
der
|
||||
digest
|
||||
ed25519
|
||||
ed25519-dalek
|
||||
equivalent
|
||||
generic-array
|
||||
getrandom
|
||||
hashbrown
|
||||
hex
|
||||
iana-time-zone
|
||||
indexmap
|
||||
inout
|
||||
itoa
|
||||
libc
|
||||
match-lookup
|
||||
memchr
|
||||
multibase
|
||||
multihash
|
||||
multihash-codetable
|
||||
multihash-derive
|
||||
multihash-derive-impl
|
||||
num-traits
|
||||
opaque-debug
|
||||
pem-rfc7468
|
||||
pkcs8
|
||||
poly1305
|
||||
ppv-lite86
|
||||
proc-macro-crate
|
||||
proc-macro2
|
||||
quote
|
||||
rand
|
||||
rand_chacha
|
||||
rand_core
|
||||
salsa20
|
||||
serde
|
||||
serde_core
|
||||
serde_derive
|
||||
serde_json
|
||||
sha2
|
||||
signature
|
||||
spki
|
||||
subtle
|
||||
syn
|
||||
synstructure
|
||||
thiserror
|
||||
thiserror-impl
|
||||
toml_datetime
|
||||
toml_edit
|
||||
toml_parser
|
||||
typenum
|
||||
unicode-ident
|
||||
universal-hash
|
||||
unsigned-varint
|
||||
uuid
|
||||
winnow
|
||||
zerocopy
|
||||
zeroize
|
||||
zeroize_derive
|
||||
zmij
|
||||
@@ -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.5.1" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -11,7 +11,7 @@ name = "git-remote-gitlawb"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
gitlawb-core = { path = "../gitlawb-core", features = ["redirect"] }
|
||||
gitlawb-core = { path = "../gitlawb-core" }
|
||||
anyhow = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -19,20 +19,3 @@ tracing-subscriber = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
mockito = "1"
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
# Job Object bindings for the real_git_fetch harness: the Windows analog of the
|
||||
# unix process-group teardown, so the whole `git fetch` tree can be killed
|
||||
# together on both the timeout and clean-exit paths (INV-22). Win32_Security is
|
||||
# required by CreateJobObjectW, and Win32_System_Threading by
|
||||
# JOBOBJECT_EXTENDED_LIMIT_INFORMATION (it embeds IO_COUNTERS).
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
+101
-1400
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-attest"
|
||||
description = "External Attestation v1: pluggable provenance attachments for gitlawb ref-update certs"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.5.1" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! by exact match.
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64U, Engine};
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
@@ -111,7 +111,7 @@ impl Attestation {
|
||||
.try_into()
|
||||
.map_err(|_| Error::Signature("signature must be 64 bytes".to_string()))?;
|
||||
let sig = Signature::from_bytes(&sig_bytes);
|
||||
vk.verify_strict(&bytes, &sig)
|
||||
vk.verify(&bytes, &sig)
|
||||
.map_err(|e| Error::Signature(format!("ed25519: {e}")))?;
|
||||
|
||||
Ok(vk)
|
||||
@@ -554,39 +554,4 @@ mod tests {
|
||||
let err = tampered.verify_signature(cert_hash).unwrap_err();
|
||||
assert!(matches!(err, Error::Signature(_)));
|
||||
}
|
||||
|
||||
/// Regression guard for strict verification: a signature forged under a
|
||||
/// weak (small-order) public key satisfies the verification equation
|
||||
/// but must be rejected. The identity point is such a key: with R the
|
||||
/// identity and S = 0, [S]B - [k]A is the identity for any message.
|
||||
#[test]
|
||||
fn verify_rejects_weak_key_signature() {
|
||||
let mut weak_key_bytes = [0u8; 32];
|
||||
weak_key_bytes[0] = 1; // compressed identity point (y = 1, x = 0)
|
||||
let weak_vk = VerifyingKey::from_bytes(&weak_key_bytes).unwrap();
|
||||
assert!(weak_vk.is_weak(), "identity point must be a weak key");
|
||||
|
||||
let cert_hash = sample_cert_hash();
|
||||
let mut forged = [0u8; 64];
|
||||
forged[0] = 1; // R = identity point, S = 0
|
||||
let forged_sig = B64U.encode(forged);
|
||||
|
||||
// Build an attestation with the weak key as signer and the forged
|
||||
// signature. The weak-key check happens at verify time.
|
||||
let mut att = dummy_attestation(&SigningKey::generate(&mut OsRng), cert_hash);
|
||||
let mut buf = Vec::with_capacity(ED25519_MULTICODEC.len() + 32);
|
||||
buf.extend_from_slice(&ED25519_MULTICODEC);
|
||||
buf.extend_from_slice(&weak_key_bytes);
|
||||
att.signer = format!(
|
||||
"did:key:{}",
|
||||
multibase::encode(multibase::Base::Base58Btc, &buf)
|
||||
);
|
||||
att.sig = forged_sig;
|
||||
|
||||
let err = att.verify_signature(cert_hash).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::Signature(_)),
|
||||
"signature under a weak (small-order) public key must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-core"
|
||||
description = "Core cryptographic primitives for the gitlawb network: DIDs, CIDs, UCAN, HTTP Signatures, ref-update certificates"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.5.1" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -22,7 +22,6 @@ multihash-codetable = { workspace = true }
|
||||
cid = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
url = { workspace = true, optional = true }
|
||||
zeroize = { version = "1", features = ["derive"] }
|
||||
pkcs8 = { version = "0.10", features = ["pem", "std"] }
|
||||
curve25519-dalek = "4"
|
||||
@@ -31,9 +30,3 @@ chacha20poly1305 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
# Not optional here: the redirect matrix must run under a bare
|
||||
# `cargo test -p gitlawb-core`, with no feature selected.
|
||||
url = { workspace = true }
|
||||
|
||||
[features]
|
||||
redirect = ["dep:url"]
|
||||
@@ -6,8 +6,6 @@
|
||||
//! The schema is frozen at v1. All fields are mandatory for forward compatibility.
|
||||
//! Nodes that receive a certificate with an unknown version MUST reject it.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
@@ -137,14 +135,10 @@ impl RefUpdateCert {
|
||||
|
||||
/// Check if this certificate satisfies a threshold of valid signatures
|
||||
/// from the provided set of authorized maintainer DIDs.
|
||||
///
|
||||
/// Counts distinct signer DIDs, not signature entries: a repeated
|
||||
/// signature from the same maintainer counts once.
|
||||
pub fn satisfies_threshold(&self, maintainers: &[Did], threshold: usize) -> Result<bool> {
|
||||
let valid = self.verify_all()?;
|
||||
let distinct_signers: HashSet<&Did> =
|
||||
valid.iter().filter(|d| maintainers.contains(d)).collect();
|
||||
Ok(distinct_signers.len() >= threshold)
|
||||
let count = valid.iter().filter(|d| maintainers.contains(d)).count();
|
||||
Ok(count >= threshold)
|
||||
}
|
||||
|
||||
/// Validate the certificate structure (not signatures).
|
||||
@@ -350,33 +344,6 @@ mod tests {
|
||||
assert!(!cert.satisfies_threshold(&maintainers, 1).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn satisfies_threshold_rejects_duplicated_signature() {
|
||||
let kp1 = Keypair::generate();
|
||||
let kp2 = Keypair::generate();
|
||||
let kp3 = Keypair::generate();
|
||||
let repo_did = kp1.did();
|
||||
|
||||
let mut cert = RefUpdateCert::new(
|
||||
repo_did,
|
||||
"refs/heads/main".to_string(),
|
||||
dummy_hash('0'),
|
||||
dummy_hash('a'),
|
||||
1,
|
||||
&kp1,
|
||||
)
|
||||
.unwrap();
|
||||
// Copy-paste the only real signature onto the certificate a second
|
||||
// time. Same signer, same valid signature, still one real signer.
|
||||
let dup = cert.signatures[0].clone();
|
||||
cert.signatures.push(dup);
|
||||
|
||||
let maintainers = vec![kp1.did(), kp2.did(), kp3.did()];
|
||||
// Two signature entries but a single distinct signer must not
|
||||
// satisfy a 2-of-3 threshold.
|
||||
assert!(!cert.satisfies_threshold(&maintainers, 2).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threshold_zero_is_always_satisfied() {
|
||||
let kp = Keypair::generate();
|
||||
|
||||
@@ -80,19 +80,6 @@ impl Did {
|
||||
)));
|
||||
}
|
||||
|
||||
// Refuse an oversized id before decoding. base58 decoding is quadratic
|
||||
// in its input, and both callers of this function take the string from
|
||||
// an untrusted request: the unauthenticated peer-announce gate, and the
|
||||
// HTTP-signature keyid. An ed25519 did:key method-id is a fixed 48
|
||||
// characters, so this bound is slack rather than a behavior change, and
|
||||
// it has to sit ahead of the decode to be worth anything.
|
||||
const MAX_METHOD_ID_LEN: usize = 64;
|
||||
if self.method_id().len() > MAX_METHOD_ID_LEN {
|
||||
return Err(Error::InvalidDid(
|
||||
"did:key method-specific id too long".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let (_, bytes) =
|
||||
multibase::decode(self.method_id()).map_err(|e| Error::InvalidDid(e.to_string()))?;
|
||||
|
||||
@@ -321,52 +308,4 @@ mod tests {
|
||||
assert_eq!(Did::web("example.com").method_id(), "example.com");
|
||||
assert_eq!(Did::gitlawb("z6MkSomeKey").method_id(), "z6MkSomeKey");
|
||||
}
|
||||
|
||||
/// An oversized method-specific id is refused on its length, before the
|
||||
/// base58 decode runs.
|
||||
///
|
||||
/// base58 decoding is quadratic in the input, and `to_verifying_key` is
|
||||
/// reached from two places that take an attacker-supplied string: the
|
||||
/// unauthenticated peer-announce gate, and the HTTP-signature keyid. A
|
||||
/// 64k-character DID measured 8s through the router without this guard
|
||||
/// against 4.6ms with it, on a tokio worker with no spawn_blocking, so a
|
||||
/// single caller could buy CPU-seconds by the thousand.
|
||||
///
|
||||
/// Asserting the MESSAGE is what makes this load-bearing: an oversized id
|
||||
/// errors either way, so a test that only checked `is_err()` would pass
|
||||
/// with the guard removed, having merely paid the cost it exists to avoid.
|
||||
#[test]
|
||||
fn to_verifying_key_rejects_an_oversized_method_id_before_decoding() {
|
||||
let oversized = format!("did:key:z{}", "z".repeat(64_000));
|
||||
let did: Did = oversized.parse().expect("method is still `key`");
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let err = did.to_verifying_key().expect_err("must be refused");
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
assert!(
|
||||
err.to_string().contains("too long"),
|
||||
"must be refused on length, not after the decode: {err}"
|
||||
);
|
||||
assert!(
|
||||
elapsed < std::time::Duration::from_secs(1),
|
||||
"refusal must not pay the quadratic decode: took {elapsed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The bound must not reject a real key. Every `did:key` this project
|
||||
/// mints is a fixed 48 characters, so the limit is slack, not a behavior
|
||||
/// change.
|
||||
#[test]
|
||||
fn to_verifying_key_still_accepts_a_real_did_key() {
|
||||
use ed25519_dalek::SigningKey;
|
||||
let signing = SigningKey::from_bytes(&[7u8; 32]);
|
||||
let did = Did::from_verifying_key(&signing.verifying_key());
|
||||
assert_eq!(
|
||||
did.method_id().len(),
|
||||
48,
|
||||
"did:key method-id is fixed-width"
|
||||
);
|
||||
did.to_verifying_key().expect("a real did:key must resolve");
|
||||
}
|
||||
}
|
||||
@@ -78,9 +78,10 @@ impl Keypair {
|
||||
|
||||
/// Verify an Ed25519 signature.
|
||||
pub fn verify(verifying_key: &VerifyingKey, msg: &[u8], sig_bytes: &[u8; 64]) -> Result<()> {
|
||||
use ed25519_dalek::Verifier;
|
||||
let sig = Signature::from_bytes(sig_bytes);
|
||||
verifying_key
|
||||
.verify_strict(msg, &sig)
|
||||
.verify(msg, &sig)
|
||||
.map_err(|_| Error::SignatureInvalid)
|
||||
}
|
||||
|
||||
@@ -208,28 +209,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_rejects_weak_key_signature() {
|
||||
// Regression guard for strict verification: a signature forged under a
|
||||
// weak (small-order) public key satisfies the verification equation
|
||||
// but must be rejected. The identity point is such a key: with R the
|
||||
// identity and S = 0, [S]B - [k]A is the identity for any message.
|
||||
let mut weak_key_bytes = [0u8; 32];
|
||||
weak_key_bytes[0] = 1; // compressed identity point (y = 1, x = 0)
|
||||
let weak_vk = VerifyingKey::from_bytes(&weak_key_bytes).unwrap();
|
||||
assert!(weak_vk.is_weak(), "identity point must be a weak key");
|
||||
|
||||
let msg = b"forged message";
|
||||
let mut forged = [0u8; 64];
|
||||
forged[0] = 1; // R = identity point, S = 0
|
||||
|
||||
let result = verify(&weak_vk, msg, &forged);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"signature under a weak (small-order) public key must be rejected"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_payload_round_trip() {
|
||||
let kp = Keypair::generate();
|
||||
|
||||
@@ -5,16 +5,6 @@ pub mod encrypt;
|
||||
pub mod error;
|
||||
pub mod http_sig;
|
||||
pub mod identity;
|
||||
// `url` is the one dependency here that drags a tail (idna, then the icu
|
||||
// crates), and gitlawb-core is allowlisted to stay embeddable. Every client that
|
||||
// needs this predicate already parses URLs, so they opt in and nothing else
|
||||
// pays. `test` is in the cfg so `cargo test -p gitlawb-core` still compiles and
|
||||
// runs the matrix below with no feature selected; without it the tests would
|
||||
// silently not run, which is the failure this module exists to prevent.
|
||||
#[cfg(any(feature = "redirect", test))]
|
||||
pub mod redirect;
|
||||
pub mod sanitize;
|
||||
pub mod scan_token;
|
||||
pub mod ucan;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
@@ -1,241 +0,0 @@
|
||||
//! Redirect policy shared by every gitlawb HTTP client that signs its requests.
|
||||
//!
|
||||
//! Both `gl` (async) and `git-remote-gitlawb` (blocking) attach RFC 9421
|
||||
//! `Signature` and `Signature-Input` headers, and reqwest strips only
|
||||
//! `Authorization`, `Cookie`, `Proxy-Authorization` and `WWW-Authenticate` when a
|
||||
//! redirect crosses hosts. A signature would survive that hop, and it binds
|
||||
//! `@method`, `@path` and `content-digest` with no authority component, so a node
|
||||
//! answering 302 could hand a working credential to a host of its choosing and read
|
||||
//! as the caller anywhere until the clock-skew window closes. On a 307/308 the
|
||||
//! request body goes along with it, which for the remote helper is the pack.
|
||||
//!
|
||||
//! That same missing authority component is why the predicate also pins the
|
||||
//! request-target: `@path` is signed as the client sent it and verified as the node
|
||||
//! received it, so a same-origin hop that rewrites the path or the query (a
|
||||
//! trailing-slash or query normalization) makes the signature cover a target the
|
||||
//! node never saw and the read 401s. Only a hop that re-issues the identical target,
|
||||
//! an http-to-https upgrade being the one that matters in practice, is followed.
|
||||
//!
|
||||
//! The decision lives here rather than in either client because the two used to
|
||||
//! disagree: `gl` was scoped to the origin while the remote helper, the binary that
|
||||
//! actually runs `git clone gitlawb://`, still ran reqwest's default and followed
|
||||
//! anywhere. One predicate is what keeps a future third client from repeating that.
|
||||
//!
|
||||
//! The type is `url::Url`, which is what `reqwest::Url` re-exports, so both clients
|
||||
//! pass their attempt URLs straight in.
|
||||
|
||||
/// Longest redirect chain followed. `reqwest::redirect::Policy::custom` replaces
|
||||
/// reqwest's built-in limit, so the bound has to be restated by every client that
|
||||
/// installs a custom policy; the value is reqwest's own default.
|
||||
///
|
||||
/// This counts FOLLOWS, matching `Policy::limited`: reqwest pushes the redirecting
|
||||
/// URL onto `previous` before consulting the policy, and `Limit(max)` refuses once
|
||||
/// `previous.len() > max`, so a caller comparing against this constant must use `>`
|
||||
/// too or it permits one hop fewer than it says.
|
||||
pub const MAX_REDIRECTS: usize = 10;
|
||||
|
||||
/// Follow a redirect only when it stays on the origin that issued it AND re-issues
|
||||
/// the identical request-target.
|
||||
///
|
||||
/// `Policy::none()` would have been the simpler answer, but one same-origin redirect
|
||||
/// shape is legitimate here: a node fronted by a proxy that upgrades http to https,
|
||||
/// or otherwise re-issues the same path and query, so the policy is scoped rather
|
||||
/// than switched off.
|
||||
///
|
||||
/// Path and query must match exactly, and that is the request-target clause rather
|
||||
/// than an origin one. `@path` is signed as the client sent it and verified as the
|
||||
/// node received it, so a hop that rewrites either half leaves a signature covering
|
||||
/// a target nobody asked for and the node answers 401. Refusing the hop turns a
|
||||
/// confusing 401 into the 3xx that names what actually happened. One policy covers
|
||||
/// signed and unsigned callers alike, for the same reason the predicate is shared:
|
||||
/// two rules would drift.
|
||||
///
|
||||
/// The clause pins `@path`, and only `@path`. A gitlawb signature also covers
|
||||
/// `@method` and `content-digest`, and both of those are still open on a followed
|
||||
/// hop: on a 301, 302 or 303, reqwest 0.12.28 delegates to tower-http's
|
||||
/// `FollowRedirect`, which rewrites a POST to a GET and empties the body
|
||||
/// (tower-http-0.6.8 `src/follow_redirect/mod.rs:273-285`), while its
|
||||
/// `drop_payload_headers` removes only `Content-Type`, `Content-Length`,
|
||||
/// `Content-Encoding` and `Transfer-Encoding`. So `Signature`, `Signature-Input` and
|
||||
/// `Content-Digest` ride along on a request that no longer has the method or the body
|
||||
/// they were computed over. Only 307 and 308 preserve both. This predicate returning
|
||||
/// true therefore makes a GET-shaped hop safe to replay against the node's verifier
|
||||
/// and says nothing about a bodied one: a signed write must not rely on it alone.
|
||||
///
|
||||
/// `Url::query` is `None` for `/a` and `Some("")` for `/a?`, and those are two
|
||||
/// different request-targets on the node side too, so the comparison is strict and
|
||||
/// needs no special case.
|
||||
///
|
||||
/// Host and port must match exactly. Port is compared as `Url::port`, which is
|
||||
/// `None` for a scheme's default port, so http -> https on the same host compares
|
||||
/// equal while http -> http on a different port does not. A downgrade from https to
|
||||
/// http is refused as well: the target is the same host, but the signature would go
|
||||
/// out in cleartext, which is the same credential leak by a slower route.
|
||||
///
|
||||
/// Host comparison rides on `url`'s parse-time normalization (lowercasing and IDN
|
||||
/// -> punycode), so the spellings an attacker reaches for do not open a gap. That
|
||||
/// is a property of the parsed `Url`, not of this function, which is why the test
|
||||
/// matrix pins it: a move to raw string comparison would silently lose it.
|
||||
pub fn may_follow(previous: &url::Url, next: &url::Url) -> bool {
|
||||
let same_origin = next.host_str() == previous.host_str() && next.port() == previous.port();
|
||||
let same_target = next.path() == previous.path() && next.query() == previous.query();
|
||||
let downgraded = previous.scheme() == "https" && next.scheme() != "https";
|
||||
same_origin && same_target && !downgraded
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every branch of the decision, both ways, plus the spellings that would slip
|
||||
/// past a comparison less careful than `Url`'s own normalization.
|
||||
#[test]
|
||||
fn may_follow_covers_each_origin_branch() {
|
||||
let url = |s: &str| url::Url::parse(s).unwrap();
|
||||
let cases: &[(&str, &str, bool, &str)] = &[
|
||||
(
|
||||
"http://node.example/a",
|
||||
"http://node.example/b",
|
||||
false,
|
||||
"same origin but the path changed: @path is signed as sent and verified as received",
|
||||
),
|
||||
(
|
||||
"http://node.example/a",
|
||||
"https://node.example/a",
|
||||
true,
|
||||
"http to https on one host with an identical request-target: both ports are \
|
||||
the scheme default, so the proxy upgrade is still followed",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://node.example/a/",
|
||||
false,
|
||||
"trailing-slash normalization changes the request-target, so it is refused",
|
||||
),
|
||||
(
|
||||
"https://node.example:8443/a",
|
||||
"https://node.example:8443/a",
|
||||
true,
|
||||
"same explicit port",
|
||||
),
|
||||
(
|
||||
"http://node.example/a",
|
||||
"http://attacker.example/a",
|
||||
false,
|
||||
"different host",
|
||||
),
|
||||
(
|
||||
"http://node.example/a",
|
||||
"http://node.example:8080/a",
|
||||
false,
|
||||
"same host, different port",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"http://node.example/a",
|
||||
false,
|
||||
"https downgraded to cleartext on the same host",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"http://node.example:443/a",
|
||||
false,
|
||||
"a downgrade dressed up as the https port",
|
||||
),
|
||||
// The rows below pass today because `Url::parse` normalizes the host, not
|
||||
// because anything here compares case-insensitively or decodes IDN. They
|
||||
// are the variants an attacker reaches for, so they are pinned: swapping
|
||||
// this predicate for a raw string comparison must break the suite.
|
||||
// Each of these pairs an IDENTICAL path on both sides, deliberately. The
|
||||
// request-target clause below would make every one of them false on the
|
||||
// path alone, and a row that is false for two reasons has stopped pinning
|
||||
// either. With the paths equal, the host or port comparison is the only
|
||||
// thing left that can decide them.
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://NODE.EXAMPLE/a",
|
||||
true,
|
||||
"same host in a different case: parse lowercases it",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://node.example./a",
|
||||
false,
|
||||
"a trailing dot is a different host to url, so the redirect is refused",
|
||||
),
|
||||
(
|
||||
"https://exämple.test/a",
|
||||
"https://xn--exmple-cua.test/a",
|
||||
true,
|
||||
"unicode host and its punycode spelling are one host after parse",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://user:[email protected]/a",
|
||||
true,
|
||||
"userinfo is not part of the origin: same host, still followed",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://[email protected]/a",
|
||||
false,
|
||||
"the node's name smuggled into userinfo: the host is the attacker's",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://attacker.example/a#node.example",
|
||||
false,
|
||||
"the node's name pushed into the fragment: the host is the attacker's",
|
||||
),
|
||||
// The request-target clause, both directions. `@path` is the only thing a
|
||||
// gitlawb signature binds the request to, so a hop that rewrites it hands
|
||||
// the node a signature over a target it never received.
|
||||
(
|
||||
"https://node.example/a?x=1",
|
||||
"https://node.example/a?x=1",
|
||||
true,
|
||||
"identical request-target: the same-origin hop that is still followed",
|
||||
),
|
||||
(
|
||||
"https://node.example/a?x=1",
|
||||
"https://node.example/a?x=2",
|
||||
false,
|
||||
"same path but a different query: the request-target covers the query too",
|
||||
),
|
||||
(
|
||||
"https://node.example/a",
|
||||
"https://node.example/a?x=1",
|
||||
false,
|
||||
"a query added where there was none",
|
||||
),
|
||||
(
|
||||
"http://node.example/a",
|
||||
"http://node.example/a?",
|
||||
false,
|
||||
"an empty query added where there was none: a missing query and an empty \
|
||||
one are different request-targets",
|
||||
),
|
||||
(
|
||||
"https://node.example/a?x=1",
|
||||
"https://node.example/a",
|
||||
false,
|
||||
"the query dropped where there was one: the comparison is symmetric, and \
|
||||
nothing else in the matrix pins that direction",
|
||||
),
|
||||
(
|
||||
"https://node.example/a#x",
|
||||
"https://node.example/a#y",
|
||||
true,
|
||||
"a fragment-only difference is still followed: a fragment never reaches \
|
||||
the wire, so it is no part of the request-target the node verifies",
|
||||
),
|
||||
];
|
||||
for (previous, next, expected, why) in cases {
|
||||
assert_eq!(
|
||||
may_follow(&url(previous), &url(next)),
|
||||
*expected,
|
||||
"{previous} -> {next} ({why})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
//! Text sanitization predicates shared across the workspace.
|
||||
//!
|
||||
//! Untrusted peer/remote bytes that reach an operator's terminal (node error
|
||||
//! bodies, node-advertised strings) must be stripped of BOTH `Cc` control bytes
|
||||
//! (`char::is_control()`) AND `Cf` bidi/format controls before display: a
|
||||
//! right-to-left override or directional isolate can visually reorder the line
|
||||
//! and spoof the text (Trojan Source, CWE-451). This is INV-6.
|
||||
//!
|
||||
//! `is_bidi_format` is the single workspace definition of the second half of
|
||||
//! that obligation. It was split out of `gl`'s local copy so the two terminal
|
||||
//! sanitizers that shipped with only the `Cc` half (#183) — and any future
|
||||
//! sanitizer — reuse one audited predicate instead of re-deriving the set.
|
||||
|
||||
/// True for the Unicode bidirectional/directional-isolate format characters
|
||||
/// (the reordering subset of category `Cf`) that can visually reorder a terminal
|
||||
/// line. These are NOT matched by [`char::is_control()`], which covers `Cc` only.
|
||||
///
|
||||
/// This is deliberately the reordering subset, not the whole `Cf` category:
|
||||
/// legitimate `Cf` characters such as ZWJ (`U+200D`, emoji sequences) and the
|
||||
/// soft hyphen (`U+00AD`) are NOT matched, so honest international text passes
|
||||
/// through unchanged. Widening this set is a behavior change for every consumer.
|
||||
///
|
||||
/// Pair it with `!c.is_control()` in a terminal-bound sanitizer (INV-6); see the
|
||||
/// wrappers in `gl`, `git-remote-gitlawb`, and `icaptcha-client`.
|
||||
pub fn is_bidi_format(c: char) -> bool {
|
||||
matches!(c,
|
||||
'\u{200E}' | '\u{200F}' | '\u{061C}' // LRM, RLM, ALM
|
||||
| '\u{202A}'..='\u{202E}' // LRE, RLE, PDF, LRO, RLO
|
||||
| '\u{2066}'..='\u{2069}' // LRI, RLI, FSI, PDI
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn strips_every_reordering_code_point() {
|
||||
// Asserted individually so a partial predicate (e.g. one that covers the
|
||||
// marks but not the isolates) fails loudly rather than passing.
|
||||
for c in [
|
||||
'\u{200E}', '\u{200F}', '\u{061C}', // LRM, RLM, ALM
|
||||
'\u{202A}', '\u{202B}', '\u{202C}', '\u{202D}',
|
||||
'\u{202E}', // LRE, RLE, PDF, LRO, RLO
|
||||
'\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', // LRI, RLI, FSI, PDI
|
||||
] {
|
||||
assert!(
|
||||
is_bidi_format(c),
|
||||
"U+{:04X} must be a bidi-format char",
|
||||
c as u32
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_legitimate_and_control_chars() {
|
||||
// Must NOT over-strip: plain text, a genuine RTL SCRIPT letter (Lo, not a
|
||||
// format char), ZWJ (legitimate Cf), and soft hyphen (legitimate Cf) are
|
||||
// not bidi-format. ESC is a Cc control char — owned by is_control(), not
|
||||
// this predicate, which is bidi-only.
|
||||
for c in ['a', '\u{0627}', '\u{200D}', '\u{00AD}', '\u{1b}'] {
|
||||
assert!(
|
||||
!is_bidi_format(c),
|
||||
"U+{:04X} must NOT be a bidi-format char",
|
||||
c as u32
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,499 +0,0 @@
|
||||
//! Sealed continuation token for the node's bounded legacy CID scan (INV-13).
|
||||
//!
|
||||
//! The `/ipfs/{cid}` resolver's legacy scan stops at a row ceiling and sheds a
|
||||
//! retryable 503. To let a holder buried past that ceiling still be reached, the
|
||||
//! shed carries the scan position so the caller can echo it back and resume. The
|
||||
//! whole point of the design is that the node keeps NO server-side scan state: the
|
||||
//! position rides in the caller's token.
|
||||
//!
|
||||
//! That makes the token an EMITTED continuation derived from a FETCHED row, and on
|
||||
//! a scan that served nothing every fetched row is by construction a private or
|
||||
//! quarantined repo the caller may not read. The row's `created_at` leaks its
|
||||
//! creation time and its `id` carries the owner's DID, so both halves are withheld
|
||||
//! fields and the token must be CONFIDENTIAL, not merely tamper-evident:
|
||||
//!
|
||||
//! * AEAD-sealed (XChaCha20-Poly1305), never base64-of-plaintext and never
|
||||
//! signed plaintext. Integrity is not confidentiality.
|
||||
//! * A fresh `OsRng` nonce on EVERY seal. Under a stream cipher a repeated nonce
|
||||
//! means repeated keystream, and an attacker who can force the node to seal a
|
||||
//! position whose plaintext they know XORs two tokens and recovers a withheld
|
||||
//! row's fields in full, strictly worse than emitting plaintext.
|
||||
//! * FIXED-WIDTH plaintext. AEAD ciphertext is plaintext-length plus the tag, and
|
||||
//! every field of a scan position varies in length, so a variable encoding would
|
||||
//! make token LENGTH a side channel for the sealed row (a short name under a
|
||||
//! short owner vs a long one) and for the candidate oid's width (40 hex on a
|
||||
//! sha1 repo, 64 on a sha256 one). Every token this module mints is byte-identical
|
||||
//! in length. Each field is padded to its own separate width, which is a per-field
|
||||
//! constant and so still leaks nothing about a given row or candidate.
|
||||
//! * The canonical CID as associated data, so a token minted while scanning for
|
||||
//! one CID does not authenticate when replayed against another.
|
||||
//!
|
||||
//! Every failure to open (wrong key, tampered bytes, wrong CID, expired, malformed)
|
||||
//! returns the same `None`. The caller treats that as "no token" and starts at the
|
||||
//! front, so no failure class is distinguishable and the token is no oracle.
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine};
|
||||
use chacha20poly1305::{
|
||||
aead::{Aead, KeyInit, OsRng, Payload},
|
||||
XChaCha20Poly1305, XNonce,
|
||||
};
|
||||
use rand::RngCore;
|
||||
|
||||
/// Keyset position of the last row a truncated scan fetched.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ScanPosition {
|
||||
/// The row's raw stored `created_at` text, the first half of the keyset cursor.
|
||||
pub created_at_key: String,
|
||||
/// The row's `id`, the tiebreaking half of the keyset cursor.
|
||||
pub id: String,
|
||||
/// The oid hex of the CANDIDATE this position resumes. One CID can map to several
|
||||
/// git oids, so a bare row cursor names a row without naming whose walk it belongs
|
||||
/// to. The candidate is named by IDENTITY rather than by position in the candidate
|
||||
/// list: that list is ordered by hex and mutates between rungs, so an index would
|
||||
/// name a different candidate the moment anything is pinned or unpinned.
|
||||
pub sha256_hex: String,
|
||||
}
|
||||
|
||||
/// Plaintext version byte, so a future layout change is a clean open-failure
|
||||
/// (treated as absent) rather than a misparse.
|
||||
///
|
||||
/// Bumped to 2 when the two halves stopped sharing one width (see [`ID_WIDTH`]), and
|
||||
/// to 3 when the position gained the candidate oid it resumes (see [`OID_WIDTH`]).
|
||||
/// A token minted under an earlier layout is a different length and a different
|
||||
/// framing, so it opens to `None` and the caller restarts at the front, which is the
|
||||
/// safe direction: a misparse would resume at a fabricated row and skip coverage.
|
||||
const VERSION: u8 = 3;
|
||||
|
||||
/// Byte width the `created_at` half is padded to. Every value stored here is a
|
||||
/// serialized timestamp, about 30 bytes, so 64 is roomy for the field's whole domain.
|
||||
/// It is deliberately NOT widened to match [`ID_WIDTH`]: padding both halves to the id
|
||||
/// width would nearly double every token for a field that can never use the space.
|
||||
const CREATED_WIDTH: usize = 64;
|
||||
|
||||
/// Byte width the `id` half is padded to.
|
||||
///
|
||||
/// The bound is set by the WRITERS, not by what a typical id happens to look like.
|
||||
/// `upsert_mirror_repo` builds `repos.id` as `{owner}/{name}`, and the slug validators
|
||||
/// in the node's `repo_store` admit an owner of up to 255 bytes and a name of up to
|
||||
/// 100, so 356 bytes is reachable through the ordinary write path and repo names are
|
||||
/// peer-controllable. 384 clears that with margin.
|
||||
///
|
||||
/// Under-sizing this is not a cosmetic bug. A row at a truncation boundary whose id
|
||||
/// exceeds the width fails the seal, the handler sheds a 503 with no continuation, and
|
||||
/// a tokenless shed is byte-identical to the wrapped-scan response whose contract is
|
||||
/// "the absence of a token means the ladder is over". The boundary row is deterministic
|
||||
/// for a stable inventory, so every retry reproduces it and every row past it becomes
|
||||
/// permanently unreachable. Anything past the width still fails loudly rather than
|
||||
/// silently truncating a cursor into one that resumes at the wrong row.
|
||||
const ID_WIDTH: usize = 384;
|
||||
|
||||
/// Byte width the candidate oid half is padded to.
|
||||
///
|
||||
/// Git mints exactly two oid widths and this field carries BOTH. A production repo is
|
||||
/// created by `store::init_bare` with `git init --bare --object-format=sha1`, so its
|
||||
/// oids are 40 hex; only the sha256 test fixtures mint 64. The field is therefore
|
||||
/// length-prefixed like the two row halves rather than a bare fixed 64: a 64-only
|
||||
/// field would fail every seal on a real deployment, and a failed seal sheds a
|
||||
/// tokenless 503 that is byte-identical to "your ladder is over".
|
||||
///
|
||||
/// The padding to 64 is what keeps the WIDTH off the wire. Without it a 40-hex token
|
||||
/// is 24 bytes shorter than a 64-hex one, and token length would say which object
|
||||
/// format the holder's repo uses.
|
||||
const OID_WIDTH: usize = 64;
|
||||
|
||||
/// `version | created_len:u16 | created[CREATED_WIDTH] | id_len:u16 | id[ID_WIDTH] | oid_len:u16 | oid[OID_WIDTH] | expires:i64`
|
||||
const PLAINTEXT_LEN: usize = 1 + 2 + CREATED_WIDTH + 2 + ID_WIDTH + 2 + OID_WIDTH + 8;
|
||||
|
||||
/// Nonce width for XChaCha20-Poly1305.
|
||||
const NONCE_LEN: usize = 24;
|
||||
|
||||
/// A fresh random 32-byte sealing key from the OS CSPRNG.
|
||||
pub fn new_key() -> [u8; 32] {
|
||||
let mut key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
key
|
||||
}
|
||||
|
||||
// The two halves below are deliberately separate and adjacent. The framing pair owns
|
||||
// "every token is the same length"; the AEAD pair owns "the contents are confidential
|
||||
// and CID-bound". Keeping them apart is what lets each property be exercised (and
|
||||
// broken) without disturbing the other.
|
||||
|
||||
/// Encode a position into the FIXED-WIDTH plaintext:
|
||||
/// `version | created_len:u16 | created[CREATED_WIDTH] | id_len:u16 | id[ID_WIDTH] | oid_len:u16 | oid[OID_WIDTH] | expires:i64`
|
||||
///
|
||||
/// The padding is the point. AEAD ciphertext is plaintext-length plus the tag, and every
|
||||
/// field of a scan position varies in length, so a length-prefixed encoding with no
|
||||
/// padding would make token LENGTH a side channel for the sealed row and for the
|
||||
/// candidate's object format. Each field is padded to its OWN fixed width, which keeps
|
||||
/// every minted token the same length while letting the id half carry the range the
|
||||
/// write path actually admits.
|
||||
fn encode_position(pos: &ScanPosition, expires_at_unix: i64) -> anyhow::Result<Vec<u8>> {
|
||||
let mut out = vec![0u8; PLAINTEXT_LEN];
|
||||
out[0] = VERSION;
|
||||
let mut at = 1;
|
||||
for (field, width) in [
|
||||
(pos.created_at_key.as_bytes(), CREATED_WIDTH),
|
||||
(pos.id.as_bytes(), ID_WIDTH),
|
||||
(pos.sha256_hex.as_bytes(), OID_WIDTH),
|
||||
] {
|
||||
if field.len() > width {
|
||||
// Loud rather than truncating: a clipped cursor resumes at the wrong row and
|
||||
// silently skips coverage, which is the availability half of the bug this
|
||||
// token exists to fix.
|
||||
anyhow::bail!(
|
||||
"scan token field is {} bytes, over the {width}-byte fixed width",
|
||||
field.len()
|
||||
);
|
||||
}
|
||||
out[at..at + 2].copy_from_slice(&(field.len() as u16).to_le_bytes());
|
||||
at += 2;
|
||||
out[at..at + field.len()].copy_from_slice(field);
|
||||
at += width;
|
||||
}
|
||||
out[at..at + 8].copy_from_slice(&expires_at_unix.to_le_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decode what [`encode_position`] wrote. `None` on any structural mismatch.
|
||||
fn decode_position(bytes: &[u8]) -> Option<(ScanPosition, i64)> {
|
||||
if bytes.len() != PLAINTEXT_LEN || bytes[0] != VERSION {
|
||||
return None;
|
||||
}
|
||||
let mut at = 1;
|
||||
let mut fields = [const { String::new() }; 3];
|
||||
for (slot, width) in fields.iter_mut().zip([CREATED_WIDTH, ID_WIDTH, OID_WIDTH]) {
|
||||
let len = u16::from_le_bytes([bytes[at], bytes[at + 1]]) as usize;
|
||||
at += 2;
|
||||
if len > width {
|
||||
return None;
|
||||
}
|
||||
*slot = String::from_utf8(bytes[at..at + len].to_vec()).ok()?;
|
||||
at += width;
|
||||
}
|
||||
let expires_at = i64::from_le_bytes(bytes[at..at + 8].try_into().ok()?);
|
||||
let [created_at_key, id, sha256_hex] = fields;
|
||||
// A zero-length candidate is a third state the encoder never mints. The front-of-table
|
||||
// sentinel is empty ROW halves with a real oid, so an empty oid would hand the resume
|
||||
// path a candidate that names nothing; refuse it like every other malformed frame.
|
||||
if sha256_hex.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
ScanPosition {
|
||||
created_at_key,
|
||||
id,
|
||||
sha256_hex,
|
||||
},
|
||||
expires_at,
|
||||
))
|
||||
}
|
||||
|
||||
/// AEAD-seal `plaintext` under `key`, bound to `cid`, framed as `nonce || ciphertext`.
|
||||
fn seal_bytes(key: &[u8; 32], cid: &str, plaintext: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
let cipher = XChaCha20Poly1305::new_from_slice(key)
|
||||
.map_err(|e| anyhow::anyhow!("scan token key: {e}"))?;
|
||||
// A FRESH nonce per seal, from the OS CSPRNG. Under a stream cipher a repeated nonce
|
||||
// repeats the keystream, and two tokens sealed under one nonce XOR to the difference
|
||||
// of their plaintexts, which recovers a withheld row in full when the attacker can
|
||||
// force one of the two positions. This draw is the property the whole confidentiality
|
||||
// claim rests on.
|
||||
let mut nonce = [0u8; NONCE_LEN];
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let sealed = cipher
|
||||
.encrypt(
|
||||
XNonce::from_slice(&nonce),
|
||||
Payload {
|
||||
msg: plaintext,
|
||||
// The canonical CID as associated data: a token minted while scanning for
|
||||
// one CID does not authenticate against another, so it cannot be replayed
|
||||
// to seed a different scan.
|
||||
aad: cid.as_bytes(),
|
||||
},
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("scan token seal: {e}"))?;
|
||||
let mut out = Vec::with_capacity(NONCE_LEN + sealed.len());
|
||||
out.extend_from_slice(&nonce);
|
||||
out.extend_from_slice(&sealed);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Open what [`seal_bytes`] framed. `None` on any failure, including a wrong `cid`.
|
||||
fn open_bytes(key: &[u8; 32], cid: &str, raw: &[u8]) -> Option<Vec<u8>> {
|
||||
if raw.len() <= NONCE_LEN + 16 {
|
||||
return None;
|
||||
}
|
||||
let (nonce, sealed) = raw.split_at(NONCE_LEN);
|
||||
let cipher = XChaCha20Poly1305::new_from_slice(key).ok()?;
|
||||
cipher
|
||||
.decrypt(
|
||||
XNonce::from_slice(nonce),
|
||||
Payload {
|
||||
msg: sealed,
|
||||
aad: cid.as_bytes(),
|
||||
},
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Seal `pos` under `key`, bound to `cid`, expiring at `expires_at_unix`.
|
||||
///
|
||||
/// Returns the base64url (no pad) token. Errors only when a field exceeds
|
||||
/// its own fixed width ([`CREATED_WIDTH`], [`ID_WIDTH`], [`OID_WIDTH`]) or the AEAD
|
||||
/// itself fails, never silently truncates.
|
||||
pub fn seal_scan_token(
|
||||
key: &[u8; 32],
|
||||
cid: &str,
|
||||
pos: &ScanPosition,
|
||||
expires_at_unix: i64,
|
||||
) -> anyhow::Result<String> {
|
||||
let plaintext = encode_position(pos, expires_at_unix)?;
|
||||
Ok(B64URL.encode(seal_bytes(key, cid, &plaintext)?))
|
||||
}
|
||||
|
||||
/// Open a token minted by [`seal_scan_token`] under the same key and CID.
|
||||
///
|
||||
/// `None` for every failure class alike (wrong key, tampered, foreign CID, expired,
|
||||
/// malformed, wrong version), so the caller can treat all of them as "absent" without
|
||||
/// leaking which one occurred.
|
||||
pub fn open_scan_token(
|
||||
key: &[u8; 32],
|
||||
cid: &str,
|
||||
token: &str,
|
||||
now_unix: i64,
|
||||
) -> Option<ScanPosition> {
|
||||
let raw = B64URL.decode(token).ok()?;
|
||||
let plaintext = open_bytes(key, cid, &raw)?;
|
||||
let (pos, expires_at) = decode_position(&plaintext)?;
|
||||
if now_unix >= expires_at {
|
||||
return None;
|
||||
}
|
||||
Some(pos)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A production-shaped candidate: `git init --bare --object-format=sha1`, so 40 hex.
|
||||
const OID_40: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
|
||||
/// A test-fixture-shaped candidate: the sha256 repos the suite creates mint 64 hex.
|
||||
const OID_64: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn pos(created: &str, id: &str) -> ScanPosition {
|
||||
pos_for(created, id, OID_40)
|
||||
}
|
||||
|
||||
fn pos_for(created: &str, id: &str, sha256_hex: &str) -> ScanPosition {
|
||||
ScanPosition {
|
||||
created_at_key: created.to_string(),
|
||||
id: id.to_string(),
|
||||
sha256_hex: sha256_hex.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seal a hand-built plaintext through the AEAD half, so a test can frame bytes the
|
||||
/// encoder would never mint (an old version byte, a zero-length oid) and still exercise
|
||||
/// the real open path.
|
||||
fn seal_raw(key: &[u8; 32], cid: &str, plaintext: &[u8]) -> String {
|
||||
B64URL.encode(seal_bytes(key, cid, plaintext).unwrap())
|
||||
}
|
||||
|
||||
/// Byte offset of the oid length prefix inside the plaintext, derived from the widths
|
||||
/// rather than hardcoded so a width change moves it with the layout.
|
||||
const OID_LEN_AT: usize = 1 + 2 + CREATED_WIDTH + 2 + ID_WIDTH;
|
||||
|
||||
/// Scenario 1: both of git's oid widths round trip. The 40-hex case is the PRODUCTION
|
||||
/// shape (`git init --bare --object-format=sha1`), and an all-64 fixture suite would
|
||||
/// never exercise it, which is exactly how a fixed-64 field would ship broken.
|
||||
#[test]
|
||||
fn round_trips_at_both_oid_widths() {
|
||||
let key = new_key();
|
||||
for hex in [OID_40, OID_64] {
|
||||
let p = pos_for("2020-01-01T00:00:03+00:00", "z6MkOwner/private-repo", hex);
|
||||
let t =
|
||||
seal_scan_token(&key, "bafkcid", &p, 1 << 40).expect("both oid widths must seal");
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &t, 0),
|
||||
Some(p),
|
||||
"a {}-hex candidate must open to the identical position",
|
||||
hex.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Scenario 2: a token framed under the OLD version opens to `None`, never a misparse.
|
||||
/// Both legs matter: the version-2 plaintext was a different LENGTH, and a future
|
||||
/// same-length layout would only be caught by the version byte itself.
|
||||
#[test]
|
||||
fn a_prior_layout_version_opens_to_none() {
|
||||
let key = new_key();
|
||||
|
||||
// The version-2 layout verbatim: no oid field, so 461 bytes.
|
||||
let mut old = vec![0u8; 1 + 2 + CREATED_WIDTH + 2 + ID_WIDTH + 8];
|
||||
old[0] = 2;
|
||||
assert_eq!(old.len(), 461, "the version-2 plaintext was 461 bytes");
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &seal_raw(&key, "bafkcid", &old), 0),
|
||||
None,
|
||||
"a version-2 token must open to None so the caller restarts at the front"
|
||||
);
|
||||
|
||||
// Same length, stale version byte: only the version check can refuse this one.
|
||||
let mut stamped = encode_position(
|
||||
&pos("2020-01-01T00:00:03+00:00", "z6MkOwner/private-repo"),
|
||||
1 << 40,
|
||||
)
|
||||
.unwrap();
|
||||
stamped[0] = VERSION - 1;
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &seal_raw(&key, "bafkcid", &stamped), 0),
|
||||
None,
|
||||
"a stale version byte must open to None even at the current width"
|
||||
);
|
||||
}
|
||||
|
||||
/// Scenario 3: token length is invariant across candidate VALUE and candidate WIDTH.
|
||||
/// The padding is what keeps the oid width off the wire: without it a 40-hex token is
|
||||
/// 24 bytes shorter than a 64-hex one and the length says which repo format the
|
||||
/// holder uses.
|
||||
#[test]
|
||||
fn token_length_is_invariant_across_oid_widths() {
|
||||
let key = new_key();
|
||||
let created = "2020-01-01T00:00:00+00:00";
|
||||
let id = "z6MkOwner/private-repo";
|
||||
let short =
|
||||
seal_scan_token(&key, "bafkcid", &pos_for(created, id, OID_40), 1 << 40).unwrap();
|
||||
let long =
|
||||
seal_scan_token(&key, "bafkcid", &pos_for(created, id, OID_64), 1 << 40).unwrap();
|
||||
assert_eq!(
|
||||
short.len(),
|
||||
long.len(),
|
||||
"a 40-hex and a 64-hex candidate must mint tokens of identical length, or the \
|
||||
oid width is a side channel"
|
||||
);
|
||||
|
||||
// The absolute width, pinned by execution rather than by arithmetic on paper. The
|
||||
// gl client's mock fixtures hardcode this number (`TOKEN_LEN` in
|
||||
// crates/gl/src/ipfs_cmd.rs), and nothing in that crate seals a real token, so this
|
||||
// assertion is the only executable check that the two agree.
|
||||
assert_eq!(
|
||||
short.len(),
|
||||
756,
|
||||
"24 nonce + {PLAINTEXT_LEN} plaintext + 16 tag, base64url no pad"
|
||||
);
|
||||
}
|
||||
|
||||
/// Scenario 4: the front-of-table sentinel. Empty row halves with a REAL candidate
|
||||
/// round trip, which is what lets a seal say "this candidate, no row cursor yet".
|
||||
#[test]
|
||||
fn empty_row_fields_round_trip_with_a_real_candidate() {
|
||||
let key = new_key();
|
||||
let p = pos_for("", "", OID_40);
|
||||
let t =
|
||||
seal_scan_token(&key, "bafkcid", &p, 1 << 40).expect("the front sentinel must seal");
|
||||
assert_eq!(open_scan_token(&key, "bafkcid", &t, 0), Some(p));
|
||||
}
|
||||
|
||||
/// Scenario 6, third leg: a zero-length oid is a distinguishable third state that the
|
||||
/// encoder never mints, and accepting it would hand the sentinel machinery a candidate
|
||||
/// naming nothing. The decode path refuses it.
|
||||
#[test]
|
||||
fn a_zero_length_candidate_opens_to_none() {
|
||||
let key = new_key();
|
||||
let mut plaintext = encode_position(
|
||||
&pos("2020-01-01T00:00:03+00:00", "z6MkOwner/private-repo"),
|
||||
1 << 40,
|
||||
)
|
||||
.unwrap();
|
||||
plaintext[OID_LEN_AT..OID_LEN_AT + 2].copy_from_slice(&0u16.to_le_bytes());
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &seal_raw(&key, "bafkcid", &plaintext), 0),
|
||||
None,
|
||||
"a zero-length candidate must open to None, not to a position naming nothing"
|
||||
);
|
||||
}
|
||||
|
||||
/// Scenario 6, second leg: an oid past the 64-byte width fails the seal loudly rather
|
||||
/// than being clipped into a hex that names a different candidate.
|
||||
#[test]
|
||||
fn an_oid_over_the_fixed_width_fails_loudly() {
|
||||
let key = new_key();
|
||||
let p = pos_for(
|
||||
"2020-01-01T00:00:03+00:00",
|
||||
"z6MkOwner/private-repo",
|
||||
&"a".repeat(OID_WIDTH + 1),
|
||||
);
|
||||
assert!(
|
||||
seal_scan_token(&key, "bafkcid", &p, 1 << 40).is_err(),
|
||||
"an over-wide candidate must fail the seal, never be truncated into a hex that \
|
||||
resumes the wrong candidate"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_under_the_same_key_and_cid() {
|
||||
let key = new_key();
|
||||
let p = pos("2020-01-01T00:00:03+00:00", "z6MkOwner/private-repo");
|
||||
let t = seal_scan_token(&key, "bafkcid", &p, 1 << 40).unwrap();
|
||||
assert_eq!(open_scan_token(&key, "bafkcid", &t, 0), Some(p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_failure_class_opens_to_none() {
|
||||
let key = new_key();
|
||||
let other = new_key();
|
||||
let p = pos("2020-01-01T00:00:03+00:00", "z6MkOwner/private-repo");
|
||||
let t = seal_scan_token(&key, "bafkcid", &p, 1 << 40).unwrap();
|
||||
|
||||
assert_eq!(open_scan_token(&other, "bafkcid", &t, 0), None, "wrong key");
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkOTHER", &t, 0),
|
||||
None,
|
||||
"foreign CID"
|
||||
);
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &t, 1 << 41),
|
||||
None,
|
||||
"expired"
|
||||
);
|
||||
assert_eq!(open_scan_token(&key, "bafkcid", "!!not b64", 0), None);
|
||||
assert_eq!(open_scan_token(&key, "bafkcid", "", 0), None);
|
||||
let mut flipped: Vec<u8> = t.bytes().collect();
|
||||
let last = flipped.len() - 1;
|
||||
flipped[last] = if flipped[last] == b'A' { b'B' } else { b'A' };
|
||||
assert_eq!(
|
||||
open_scan_token(&key, "bafkcid", &String::from_utf8(flipped).unwrap(), 0),
|
||||
None,
|
||||
"tampered"
|
||||
);
|
||||
}
|
||||
|
||||
/// The id half must clear the LARGEST repo id the node's own write path admits,
|
||||
/// not merely a typical one. `upsert_mirror_repo` builds `repos.id` as
|
||||
/// `{owner}/{name}`, and the slug validators in `repo_store` admit 255 bytes of
|
||||
/// owner and 100 of name, so 356 is reachable. A width under that turns the
|
||||
/// boundary row into a seal failure, which sheds a tokenless 503 that is
|
||||
/// byte-identical to "your ladder is over" and strands every row past it forever.
|
||||
#[test]
|
||||
fn round_trips_a_repo_id_at_the_write_paths_maximum() {
|
||||
let key = new_key();
|
||||
let id = format!("{}/{}", "o".repeat(255), "n".repeat(100));
|
||||
assert_eq!(id.len(), 356, "255 owner + '/' + 100 name");
|
||||
let p = pos("2020-01-01T00:00:03+00:00", &id);
|
||||
let t = seal_scan_token(&key, "bafkcid", &p, 1 << 40)
|
||||
.expect("a repo id the write path admits must seal, never fail the width");
|
||||
assert_eq!(open_scan_token(&key, "bafkcid", &t, 0), Some(p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_over_the_fixed_width_fails_loudly() {
|
||||
let key = new_key();
|
||||
let p = pos("2020-01-01T00:00:03+00:00", &"x".repeat(ID_WIDTH + 1));
|
||||
assert!(
|
||||
seal_scan_token(&key, "bafkcid", &p, 1 << 40).is_err(),
|
||||
"an over-wide field must fail the seal, never be truncated into a cursor \
|
||||
that resumes at the wrong row"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -187,17 +187,11 @@ impl Ucan {
|
||||
}
|
||||
|
||||
/// Check if this UCAN grants a specific capability on a resource.
|
||||
///
|
||||
/// Mirrors `Capability::is_attenuated_by`'s wildcard semantics: a stored
|
||||
/// capability of `with: "*"` or `can: "*"` / `"repo/admin"` covers any
|
||||
/// requested resource/action, since a valid delegation chain can produce
|
||||
/// exactly that capability (see `is_attenuated_by`).
|
||||
pub fn can(&self, resource: &str, action: &str) -> bool {
|
||||
self.payload.att.iter().any(|cap| {
|
||||
let resource_ok = cap.with == resource || cap.with == "*";
|
||||
let action_ok = cap.can == action || cap.can == "*" || cap.can == caps::REPO_ADMIN;
|
||||
resource_ok && action_ok
|
||||
})
|
||||
self.payload
|
||||
.att
|
||||
.iter()
|
||||
.any(|cap| cap.with == resource && cap.can == action)
|
||||
}
|
||||
|
||||
/// Encode to a compact JSON string (the wire format).
|
||||
@@ -318,63 +312,6 @@ mod tests {
|
||||
assert!(!ucan.can("gitlawb://repos/test/repo", caps::PR_MERGE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_honors_resource_wildcard() {
|
||||
let issuer = Keypair::generate();
|
||||
let audience = Keypair::generate().did();
|
||||
|
||||
let ucan = Ucan::issue(
|
||||
&issuer,
|
||||
audience,
|
||||
vec![Capability::new("*", caps::GIT_PUSH)],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(ucan.can("gitlawb://repos/test/repo", caps::GIT_PUSH));
|
||||
assert!(ucan.can("gitlawb://repos/other/repo", caps::GIT_PUSH));
|
||||
assert!(!ucan.can("gitlawb://repos/test/repo", caps::PR_MERGE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_honors_repo_admin_action_wildcard() {
|
||||
let issuer = Keypair::generate();
|
||||
let audience = Keypair::generate().did();
|
||||
|
||||
let ucan = Ucan::issue(
|
||||
&issuer,
|
||||
audience,
|
||||
vec![Capability::new(
|
||||
"gitlawb://repos/test/repo",
|
||||
caps::REPO_ADMIN,
|
||||
)],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(ucan.can("gitlawb://repos/test/repo", caps::GIT_PUSH));
|
||||
assert!(ucan.can("gitlawb://repos/test/repo", caps::PR_MERGE));
|
||||
assert!(!ucan.can("gitlawb://repos/other/repo", caps::GIT_PUSH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_honors_action_wildcard() {
|
||||
let issuer = Keypair::generate();
|
||||
let audience = Keypair::generate().did();
|
||||
|
||||
let ucan = Ucan::issue(
|
||||
&issuer,
|
||||
audience,
|
||||
vec![Capability::new("gitlawb://repos/test/repo", "*")],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(ucan.can("gitlawb://repos/test/repo", caps::GIT_PUSH));
|
||||
assert!(ucan.can("gitlawb://repos/test/repo", caps::PR_MERGE));
|
||||
assert!(!ucan.can("gitlawb://repos/other/repo", caps::GIT_PUSH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_ucan() {
|
||||
let issuer = Keypair::generate();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-node"
|
||||
description = "The gitlawb node daemon — git hosting over HTTP with DID auth"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.5.1" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -77,6 +77,3 @@ libp2p-dns = { version = "0.44.0", features = ["tokio"] }
|
||||
[dev-dependencies]
|
||||
mockito = "1"
|
||||
tempfile = "3"
|
||||
# `test-util` for `#[tokio::test(start_paused = true)]`: lets the deadline tests assert
|
||||
# on which timer fired instead of on wall clock.
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -26,61 +26,14 @@ pub async fn list_anchors(
|
||||
Query(q): Query<ListAnchorsQuery>,
|
||||
) -> Result<Json<serde_json::Value>> {
|
||||
let limit = q.limit.min(200);
|
||||
// Bare `?` so connection-class sqlx failures downcast to `AppError::Db` and
|
||||
// map to 503 `db_unavailable` (not 500 via `.map_err(AppError::Internal)`) (#251).
|
||||
let anchors = state
|
||||
.db
|
||||
.list_arweave_anchors(q.repo.as_deref(), limit)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(crate::error::AppError::Internal)?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"anchors": anchors,
|
||||
"count": anchors.len(),
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod closed_pool_tests {
|
||||
use super::*;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::Router;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
/// #251: a closed pool on /api/v1/arweave/anchors must be 503 db_unavailable.
|
||||
#[sqlx::test]
|
||||
async fn list_anchors_closed_pool_returns_503_db_unavailable(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
pool.close().await;
|
||||
|
||||
let resp = Router::new()
|
||||
.route("/api/v1/arweave/anchors", axum::routing::get(list_anchors))
|
||||
.with_state(state)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/v1/arweave/anchors")
|
||||
.body(axum::body::Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"closed-pool outage must be retryable 503, not 500"
|
||||
);
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read body");
|
||||
let v: Value = serde_json::from_slice(&bytes).expect("json body");
|
||||
assert_eq!(
|
||||
v,
|
||||
serde_json::json!({
|
||||
"error": crate::error::DB_UNAVAILABLE_CODE,
|
||||
"message": crate::error::DB_UNAVAILABLE_MESSAGE,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -138,33 +138,9 @@ pub async fn list_ref_updates(
|
||||
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
|
||||
let updates = collect_visible_ref_updates(&state.db, None, limit, caller).await?;
|
||||
|
||||
// Resolve the trusted display owner_did per row. The stored wire value is
|
||||
// untrusted (arrives over gossip / unsigned peer notify), so it is echoed
|
||||
// only when it matches the canonical owner of the local repo the slug
|
||||
// names (#P1); legacy None rows are attributed via an exact unique local
|
||||
// match (#P3). Both surfaces share this resolver so they cannot drift.
|
||||
// The batch resolver issues at most one query per distinct local repo
|
||||
// rather than one per event row (#P2).
|
||||
let raw_dids: Vec<Option<String>> = state
|
||||
.db
|
||||
.resolve_ref_update_owner_dids(
|
||||
&updates
|
||||
.iter()
|
||||
.map(|u| (u.repo.as_str(), u.owner_did.as_deref()))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let owner_dids: Vec<serde_json::Value> = raw_dids
|
||||
.into_iter()
|
||||
.map(|o| o.map_or(serde_json::Value::Null, |s| serde_json::json!(s)))
|
||||
.collect();
|
||||
|
||||
let events: Vec<serde_json::Value> = updates
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, u)| {
|
||||
let owner_did = owner_dids[i].clone();
|
||||
.map(|u| {
|
||||
serde_json::json!({
|
||||
"id": u.id,
|
||||
"node_did": u.node_did,
|
||||
@@ -177,7 +153,6 @@ pub async fn list_ref_updates(
|
||||
"cert_id": u.cert_id,
|
||||
"received_at": u.received_at,
|
||||
"from_peer": u.from_peer,
|
||||
"owner_did": owner_did,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -250,7 +225,6 @@ pub async fn list_repo_events(
|
||||
"pusher_did": c.pusher_did,
|
||||
"node_did": c.node_did,
|
||||
"timestamp": c.issued_at,
|
||||
"owner_did": record.owner_did,
|
||||
"source": "local",
|
||||
})
|
||||
})
|
||||
@@ -266,46 +240,28 @@ pub async fn list_repo_events(
|
||||
// collect_visible_ref_updates drops any row whose slug matches a local repo the
|
||||
// caller cannot read (fail-closed), and propagates DB errors instead of swallowing
|
||||
// them.
|
||||
let gossip_updates =
|
||||
collect_visible_ref_updates(&state.db, Some(&repo_id_str), limit, caller).await?;
|
||||
let gossip_raw: Vec<Option<String>> = state
|
||||
.db
|
||||
.resolve_ref_update_owner_dids(
|
||||
&gossip_updates
|
||||
.iter()
|
||||
.map(|u| (u.repo.as_str(), u.owner_did.as_deref()))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let gossip_owner_dids: Vec<serde_json::Value> = gossip_raw
|
||||
.into_iter()
|
||||
.map(|o| o.map_or(serde_json::Value::Null, |s| serde_json::json!(s)))
|
||||
.collect();
|
||||
|
||||
let gossip_events: Vec<serde_json::Value> = gossip_updates
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, u)| {
|
||||
let owner_did = gossip_owner_dids[i].clone();
|
||||
serde_json::json!({
|
||||
"type": "gossipsub",
|
||||
"id": u.id,
|
||||
"repo": u.repo,
|
||||
"ref_name": u.ref_name,
|
||||
"old_sha": u.old_sha,
|
||||
"new_sha": u.new_sha,
|
||||
"pusher_did": u.pusher_did,
|
||||
"node_did": u.node_did,
|
||||
"timestamp": u.timestamp,
|
||||
"cert_id": u.cert_id,
|
||||
"received_at": u.received_at,
|
||||
"from_peer": u.from_peer,
|
||||
"owner_did": owner_did,
|
||||
"source": "gossipsub",
|
||||
let gossip_events: Vec<serde_json::Value> =
|
||||
collect_visible_ref_updates(&state.db, Some(&repo_id_str), limit, caller)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|u| {
|
||||
serde_json::json!({
|
||||
"type": "gossipsub",
|
||||
"id": u.id,
|
||||
"repo": u.repo,
|
||||
"ref_name": u.ref_name,
|
||||
"old_sha": u.old_sha,
|
||||
"new_sha": u.new_sha,
|
||||
"pusher_did": u.pusher_did,
|
||||
"node_did": u.node_did,
|
||||
"timestamp": u.timestamp,
|
||||
"cert_id": u.cert_id,
|
||||
"received_at": u.received_at,
|
||||
"from_peer": u.from_peer,
|
||||
"source": "gossipsub",
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
.collect();
|
||||
|
||||
// Merge both lists
|
||||
let mut all_events: Vec<serde_json::Value> = cert_events;
|
||||
@@ -370,7 +326,6 @@ mod ref_updates_feed_tests {
|
||||
cert_id: None,
|
||||
received_at: Utc::now().to_rfc3339(),
|
||||
from_peer: "peer1".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1150,14 +1105,7 @@ mod ref_updates_feed_tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = body_json(resp).await;
|
||||
assert_eq!(count(&body), 2);
|
||||
for event in body["events"].as_array().unwrap() {
|
||||
assert_eq!(
|
||||
event["owner_did"], OWNER,
|
||||
"each event must carry the local owner_did"
|
||||
);
|
||||
}
|
||||
assert_eq!(count(&body_json(resp).await), 2);
|
||||
}
|
||||
|
||||
// Anon reads a quarantined mirror → 404 (withheld without disclosing existence
|
||||
@@ -1440,8 +1388,7 @@ mod ref_updates_feed_tests {
|
||||
|
||||
// A DB error in the gate fails closed as 500, not swallowed into an empty 200 (the
|
||||
// regression the old get_repo().ok().flatten() allowed). Inject by dropping a
|
||||
// column get_repo selects so its query errors. Also pin the anonymous body to
|
||||
// the exact opaque object (#226).
|
||||
// column get_repo selects so its query errors.
|
||||
#[sqlx::test]
|
||||
async fn repo_events_db_error_fails_closed_500(pool: PgPool) {
|
||||
let state = test_state(pool.clone()).await;
|
||||
@@ -1464,18 +1411,6 @@ mod ref_updates_feed_tests {
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"a DB error must fail closed (500), never serve an empty 200"
|
||||
);
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read body");
|
||||
let body = String::from_utf8_lossy(&body);
|
||||
let v: serde_json::Value = serde_json::from_str(&body).expect("json body");
|
||||
assert_eq!(
|
||||
v,
|
||||
serde_json::json!({
|
||||
"error": "db_error",
|
||||
"message": crate::error::DB_ERROR_MESSAGE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Symmetric to the gate DB-error test: a DB error in the CERT fetch (after the gate
|
||||
|
||||
+389
-8578
File diff suppressed because it is too large.
Load diff
@@ -61,30 +61,20 @@ pub async fn create_issue(
|
||||
let json_str = serde_json::to_string(&issue)
|
||||
.map_err(|e| AppError::BadRequest(format!("serialization error: {e}")))?;
|
||||
|
||||
// Shed 503 + Retry-After on an exhausted write-lock POOL instead of a generic
|
||||
// git 500 (#173 F1). This path holds no admission permit, so it reaches the pool
|
||||
// unthrottled; reuse the push handler's mapping so the two cannot drift.
|
||||
let guard = state
|
||||
.repo_store
|
||||
.acquire_write(&record.owner_did, &record.name)
|
||||
.await
|
||||
.map_err(|e| crate::api::repos::acquire_write_app_error(&e, &repo))?;
|
||||
let disk_path = guard.path().to_path_buf();
|
||||
|
||||
let create_result = git_issues::create_issue(guard.path(), &issue_id, &json_str);
|
||||
let create_result = git_issues::create_issue(&disk_path, &issue_id, &json_str);
|
||||
|
||||
let git_timeout = std::time::Duration::from_secs(state.config.git_service_timeout_secs);
|
||||
let deadline = std::time::Instant::now() + git_timeout;
|
||||
let git_bin = state.git_bin.clone();
|
||||
let issue_id_for_comp = issue_id.clone();
|
||||
|
||||
let release_result = if create_result.is_ok() {
|
||||
guard
|
||||
.release_compensating(true, move |path| {
|
||||
git_issues::delete_issue_ref(&git_bin, path, &issue_id_for_comp, deadline)
|
||||
})
|
||||
.await
|
||||
.into_result()
|
||||
} else {
|
||||
guard.release(false).await.into_result()
|
||||
};
|
||||
release_result?;
|
||||
// Always release the advisory lock — even on error; upload to Tigris only on success.
|
||||
guard.release(create_result.is_ok()).await;
|
||||
|
||||
create_result.map_err(|e| AppError::Git(e.to_string()))?;
|
||||
|
||||
@@ -235,8 +225,6 @@ pub async fn close_issue(
|
||||
State(state): State<AppState>,
|
||||
Extension(auth): Extension<AuthenticatedDid>,
|
||||
Path((owner, repo, issue_id)): Path<(String, String, String)>,
|
||||
headers: axum::http::HeaderMap,
|
||||
crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr,
|
||||
) -> Result<Json<serde_json::Value>> {
|
||||
let record = state
|
||||
.db
|
||||
@@ -244,161 +232,8 @@ pub async fn close_issue(
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
|
||||
|
||||
// READ-GATE before any snapshot work or rate charging. The author fallback below
|
||||
// needs the issue blob, which needs the repo tree, so authorship cannot be established
|
||||
// without a download; but a caller who cannot even READ the repo must be
|
||||
// stopped here, cheaply, before any Tigris transfer or extraction happens.
|
||||
// Without this, any signed non-owner could issue parallel close requests for
|
||||
// arbitrary issue ids and drive unbounded downloads and blocking extraction
|
||||
// (a disposable-identity DoS), because the route has no other pre-authorization.
|
||||
//
|
||||
// Rate limiting runs AFTER this gate so a 429 cannot distinguish a hidden repo
|
||||
// from a missing one (INV-12 read-denial status contract).
|
||||
//
|
||||
// mirror-rows-handled: a repo row synced from a peer is stored public and
|
||||
// carries none of the owner's visibility rules, so for such a row this check
|
||||
// can only return allow. That is deliberate rather than overlooked, and it is
|
||||
// the same verdict every other read gate in this API reaches for one. Refusing
|
||||
// instead would deny the repo's real owner and the issue's real author on any
|
||||
// node whose only copy of the repo is a synced one, which is an ordinary state
|
||||
// here, and it would not buy the protection it appears to, because a synced
|
||||
// row's recorded owner comes from the peer that sent it. The expensive work
|
||||
// this check guards is bounded ahead of it by the per-IP limiter and the read
|
||||
// pool slot taken below, and the authoritative owner-or-author decision still
|
||||
// runs below and again under the write lock.
|
||||
{
|
||||
// mirror-rows-handled: synced mirror rows carry no owner rules; read gate only.
|
||||
let rules = state.db.list_visibility_rules(&record.id).await?;
|
||||
let caller = auth.0.as_str();
|
||||
if crate::visibility::visibility_check(
|
||||
&rules,
|
||||
record.is_public,
|
||||
&record.owner_did,
|
||||
Some(caller),
|
||||
"/",
|
||||
) == crate::visibility::Decision::Deny
|
||||
{
|
||||
return Err(AppError::RepoNotFound(format!("{owner}/{repo}")));
|
||||
}
|
||||
}
|
||||
|
||||
// Per-IP flood brake, layered on the same shared limiter and trusted-proxy
|
||||
// policy as the push advertisement. The pre-lock snapshot downloads the
|
||||
// whole archive and runs a blocking extraction, so an unlimited route would
|
||||
// let disposable identities drive unbounded transfer/CPU/disk with parallel
|
||||
// close requests for arbitrary issue ids. Applied after the read gate so a
|
||||
// denied reader still sees 404, not 429.
|
||||
if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) {
|
||||
if !state.close_issue_rate_limiter.check(&key).await {
|
||||
tracing::warn!(repo = %repo, key = %key, "close_issue rate limited");
|
||||
return Err(AppError::TooManyRequests(
|
||||
"rate limit exceeded — try again later".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// AUTHORIZE BEFORE ACQUIRING. The per-repo advisory lock genuinely excludes
|
||||
// now, so taking it first would hand any caller with read access a way to hold
|
||||
// that lock on demand and be refused afterwards, while a legitimate writer
|
||||
// burned its retry budget against it. On a public repo that is every
|
||||
// permissionless identity. The lock must not be reachable by a caller who is
|
||||
// about to be refused the write.
|
||||
let is_owner = crate::api::require_repo_owner(&record, &auth.0).is_ok();
|
||||
if !is_owner {
|
||||
// Cap concurrent snapshot work on the shared read pool. The hourly rate
|
||||
// bucket above is not a concurrent-work brake; without this, parallel close
|
||||
// attempts from read-capable callers could each drive a full archive
|
||||
// download and blocking extraction before the author denial below.
|
||||
let _read_permit = state
|
||||
.git_read_semaphore
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| {
|
||||
tracing::warn!(
|
||||
repo = %repo,
|
||||
"close_issue snapshot refused — git read pool at capacity"
|
||||
);
|
||||
AppError::Overloaded("git service at capacity, retry shortly".into())
|
||||
})?;
|
||||
|
||||
// Not the owner, so the author fallback decides it, and the author lives in
|
||||
// the issue's git-JSON blob rather than a DB column.
|
||||
//
|
||||
// Read it WITHOUT the write lock, from a NON-MUTATING SNAPSHOT. The
|
||||
// justification is NOT that authorship is immutable — it is not:
|
||||
// `refs/gitlawb/**` is pushable, so a forged author blob can be pushed
|
||||
// (tracked separately; it is what makes this fallback only as trustworthy
|
||||
// as push authorization). The justification is that this read is only a
|
||||
// PRE-CHECK, deciding whether to take the lock at all. It is NOT the
|
||||
// authorization decision: `acquire_write` re-downloads the archive after
|
||||
// locking, so the tree that gets mutated is routinely not this one, and the
|
||||
// authoritative owner-or-author check runs again under the guard below.
|
||||
// Refusing here early just keeps a caller who is already visibly
|
||||
// unauthorized from reaching the lock.
|
||||
//
|
||||
// `read_snapshot`, not `acquire_fresh`: acquire's fast path returns as soon
|
||||
// as the directory exists and never contacts object storage, so on a node
|
||||
// with a stale copy the author's own issue would be invisible and the
|
||||
// cannot-establish-authorship arm below would 403 a legitimate author.
|
||||
// read_snapshot refreshes the same way, but unpacks into a throwaway temp
|
||||
// dir instead of publishing into the live repo path — an unlocked
|
||||
// pre-check must not delete or swap the directory under a concurrent
|
||||
// guarded write on the same path.
|
||||
// Pre-lock authorization only: bound with the read acquire budget, not the
|
||||
// under-lock transfer timeout a guarded write may hold for minutes.
|
||||
let snapshot_bound_secs = state.config.git_acquire_timeout_secs;
|
||||
let snapshot = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(snapshot_bound_secs),
|
||||
state
|
||||
.repo_store
|
||||
.read_snapshot(&record.owner_did, &record.name),
|
||||
)
|
||||
.await
|
||||
.map_err(|_elapsed| {
|
||||
tracing::warn!(
|
||||
repo = %repo,
|
||||
bound_secs = snapshot_bound_secs,
|
||||
"close_issue snapshot exceeded the read acquire bound — shedding as a retryable refusal"
|
||||
);
|
||||
AppError::RepoUnavailable
|
||||
})??;
|
||||
let snapshot_path = snapshot.path().to_path_buf();
|
||||
|
||||
let author_did: Option<String> = match git_issues::get_issue(&snapshot_path, &issue_id) {
|
||||
Ok(Some(raw)) => serde_json::from_str::<IssueRecord>(&raw)
|
||||
.ok()
|
||||
.and_then(|i| i.author),
|
||||
// Cannot establish authorship, so fail closed. Deliberately 403 rather
|
||||
// than 404 for a non-owner: a caller who is not authorized to write
|
||||
// should not learn from this route whether the issue exists. Both arms
|
||||
// below return None; they are split only so a read failure is visible
|
||||
// to operators, since a genuinely absent issue and an unreadable one
|
||||
// are the same answer to the client but not the same event.
|
||||
Ok(None) => None,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
repo = %repo,
|
||||
issue = %issue_id,
|
||||
err = %e,
|
||||
"get_issue failed during close_issue authorship pre-check"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
let is_author = author_did
|
||||
.as_deref()
|
||||
.is_some_and(|a| crate::api::did_matches(&auth.0, a));
|
||||
if !is_author {
|
||||
return Err(AppError::Forbidden(
|
||||
"only the repo owner or the issue author can close this issue".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Authorized. Only now is the lock taken.
|
||||
// Propagate rather than stringify: AppError's From<anyhow::Error> downcasts to
|
||||
// sqlx::Error so a pool timeout or a database outage surfaces as a retryable
|
||||
// 503. Calling .to_string() first destroys that and reports both as a 500.
|
||||
// Same capacity shed as create_issue above (#173 F1): an exhausted write-lock
|
||||
// pool is a 503 + Retry-After, not a 500 git error.
|
||||
let guard = state
|
||||
.repo_store
|
||||
.acquire_write(&record.owner_did, &record.name)
|
||||
@@ -406,56 +241,37 @@ pub async fn close_issue(
|
||||
.map_err(|e| crate::api::repos::acquire_write_app_error(&e, &repo))?;
|
||||
let disk_path = guard.path().to_path_buf();
|
||||
|
||||
// Re-read under the guard and RE-AUTHORIZE against what we read, rather than
|
||||
// only confirming the issue still exists. The pre-lock read decided whether to
|
||||
// take the lock; it cannot be the authorization decision, because acquire_write
|
||||
// re-downloads the archive after locking, so this is frequently a different tree
|
||||
// than the one the author was read from. Checking existence alone would leave the
|
||||
// whole decision resting on the earlier read of a tree we are no longer looking
|
||||
// at. The blob is already in hand here, so this costs a deserialize.
|
||||
match git_issues::get_issue(&disk_path, &issue_id) {
|
||||
Ok(Some(raw)) => {
|
||||
let author_now: Option<String> = serde_json::from_str::<IssueRecord>(&raw)
|
||||
.ok()
|
||||
.and_then(|i| i.author);
|
||||
let is_author_now = author_now
|
||||
.as_deref()
|
||||
.is_some_and(|a| crate::api::did_matches(&auth.0, a));
|
||||
if !is_owner && !is_author_now {
|
||||
// Consumed, NOT propagated, and that is deliberate at all three
|
||||
// `release(false)` sites below. These release without
|
||||
// publishing, so there is nothing for the store to refuse, and
|
||||
// mapping the outcome here would let a 503 shadow the
|
||||
// authorization answer this route exists to give.
|
||||
let _ = guard.release(false).await;
|
||||
return Err(AppError::Forbidden(
|
||||
"only the repo owner or the issue author can close this issue".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Owner OR issue author may close. The author lives in the issue's git-JSON
|
||||
// blob (not a DB column); a None author (legacy issues) falls back to
|
||||
// owner-only. Read it under the write guard, before mutating.
|
||||
let author_did: Option<String> = match git_issues::get_issue(&disk_path, &issue_id) {
|
||||
Ok(Some(raw)) => serde_json::from_str::<IssueRecord>(&raw)
|
||||
.ok()
|
||||
.and_then(|i| i.author),
|
||||
Ok(None) => {
|
||||
let _ = guard.release(false).await;
|
||||
// The owner keeps the informative 404; a non-owner must not learn from
|
||||
// this route whether the issue exists, matching the pre-check above.
|
||||
return Err(if is_owner {
|
||||
AppError::NotFound(format!("issue {issue_id} not found"))
|
||||
} else {
|
||||
AppError::Forbidden(
|
||||
"only the repo owner or the issue author can close this issue".into(),
|
||||
)
|
||||
});
|
||||
guard.release(false).await;
|
||||
return Err(AppError::NotFound(format!("issue {issue_id} not found")));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = guard.release(false).await;
|
||||
guard.release(false).await;
|
||||
return Err(AppError::Git(e.to_string()));
|
||||
}
|
||||
};
|
||||
let is_owner = crate::api::require_repo_owner(&record, &auth.0).is_ok();
|
||||
let is_author = author_did
|
||||
.as_deref()
|
||||
.is_some_and(|a| crate::api::did_matches(&auth.0, a));
|
||||
if !is_owner && !is_author {
|
||||
guard.release(false).await;
|
||||
return Err(AppError::Forbidden(
|
||||
"only the repo owner or the issue author can close this issue".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let close_result = git_issues::close_issue(&disk_path, &issue_id);
|
||||
|
||||
// Always release the advisory lock — even on error; upload to Tigris only on success.
|
||||
// Same short-circuit as create_issue, and before the 200 body below.
|
||||
guard.release(close_result.is_ok()).await.into_result()?;
|
||||
guard.release(close_result.is_ok()).await;
|
||||
|
||||
let updated = close_result
|
||||
.map_err(|e| AppError::Git(e.to_string()))?
|
||||
@@ -469,344 +285,12 @@ pub async fn close_issue(
|
||||
Ok(Json(issue))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// U7: once the advisory lock actually excludes, taking it BEFORE authorizing
|
||||
/// turns close_issue into a wedge primitive. Any caller with repo read access
|
||||
/// (on a public repo, any permissionless identity) could take the per-repo
|
||||
/// write lock on demand and be refused the write afterwards, while the owner's
|
||||
/// push burned its retry budget against a lock held by someone with no write
|
||||
/// authorization.
|
||||
///
|
||||
/// The observable: hold the lock from an independent session, then call the
|
||||
/// handler as a stranger. If it authorizes first it refuses immediately; if it
|
||||
/// acquires first it sits in the 60-attempt retry loop and the deadline fires.
|
||||
#[sqlx::test]
|
||||
async fn stranger_is_refused_without_waiting_on_the_write_lock(pool: PgPool) {
|
||||
use sqlx::Connection;
|
||||
let opts = (*pool.connect_options()).clone();
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
|
||||
let owner = "did:key:z6MkU7Owner";
|
||||
state
|
||||
.db
|
||||
.upsert_mirror_repo("z6MkU7Owner", "u7repo", "/tmp/u7repo", None, true)
|
||||
.await
|
||||
.expect("seed repo");
|
||||
let record = state
|
||||
.db
|
||||
.get_repo("z6MkU7Owner", "u7repo")
|
||||
.await
|
||||
.expect("get_repo")
|
||||
.expect("repo exists");
|
||||
|
||||
// An independent session holds the repo's write lock for the whole call.
|
||||
let key = crate::git::repo_store::advisory_lock_key_for_test(
|
||||
&record.owner_did.replace([':', '/'], "_"),
|
||||
&record.name,
|
||||
);
|
||||
let mut holder = sqlx::PgConnection::connect_with(&opts).await.unwrap();
|
||||
let held: (bool,) = sqlx::query_as("SELECT pg_try_advisory_lock($1)")
|
||||
.bind(key)
|
||||
.fetch_one(&mut holder)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
held.0,
|
||||
"the test must hold the lock for this to mean anything"
|
||||
);
|
||||
let _ = owner;
|
||||
|
||||
let stranger = crate::auth::AuthenticatedDid("did:key:z6MkU7Stranger".to_string());
|
||||
let outcome = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(3),
|
||||
close_issue(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Extension(stranger),
|
||||
axum::extract::Path((
|
||||
"z6MkU7Owner".to_string(),
|
||||
"u7repo".to_string(),
|
||||
"1".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some("203.0.113.64:5000".parse().unwrap())),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let refused = outcome.expect(
|
||||
"a caller with no write authorization must be refused WITHOUT waiting on the \
|
||||
write lock; hitting this deadline means the handler tried to acquire first, \
|
||||
which is the wedge primitive",
|
||||
);
|
||||
assert!(
|
||||
matches!(refused, Err(AppError::Forbidden(_))),
|
||||
"expected 403 Forbidden for a stranger, got {:?}",
|
||||
refused.err().map(|e| format!("{e:?}"))
|
||||
);
|
||||
}
|
||||
|
||||
/// The read-gate's blind spot, pinned rather than left to be rediscovered.
|
||||
///
|
||||
/// A repo row synced from a peer is stored public and carries none of the
|
||||
/// owner's visibility rules, so the gate's own inputs can only produce allow
|
||||
/// for it. The gate above therefore does not carry this class of row, and the
|
||||
/// test that does cover it (`non_reader_is_refused_before_the_snapshot`) seeds
|
||||
/// a locally created repo, which cannot observe this: a passing test there is
|
||||
/// not coverage here.
|
||||
///
|
||||
/// Two things are asserted, and the second is why the first is acceptable.
|
||||
/// The gate's verdict for such a row is allow for an arbitrary caller, and the
|
||||
/// handler still refuses that caller afterwards, because the decision that
|
||||
/// matters is the owner-or-author check rather than this one. If a later change
|
||||
/// makes the gate the load-bearing decision for this route, the first assertion
|
||||
/// breaks and this comment is where to start.
|
||||
#[sqlx::test]
|
||||
async fn a_synced_row_is_not_gated_by_its_own_visibility(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
|
||||
// Only a synced row exists for this repo, with no locally created twin.
|
||||
state
|
||||
.db
|
||||
.upsert_mirror_repo("z6MkSyncOwner", "syncrepo", "/tmp/syncrepo", None, false)
|
||||
.await
|
||||
.expect("seed synced repo"); // false = not quarantined, the ordinary case
|
||||
let record = state
|
||||
.db
|
||||
.get_repo("z6MkSyncOwner", "syncrepo")
|
||||
.await
|
||||
.expect("get_repo")
|
||||
.expect("repo exists")
|
||||
.clone();
|
||||
assert!(
|
||||
record.id.contains('/'),
|
||||
"this test is only meaningful against a synced row; got id {}",
|
||||
record.id
|
||||
);
|
||||
|
||||
// The gate's two inputs, and what they force.
|
||||
let rules = state
|
||||
.db
|
||||
.list_visibility_rules(&record.id)
|
||||
.await
|
||||
.expect("list rules");
|
||||
assert!(rules.is_empty(), "a synced row carries no rules of its own");
|
||||
assert!(record.is_public, "a synced row is stored public");
|
||||
assert_eq!(
|
||||
crate::visibility::visibility_check(
|
||||
&rules,
|
||||
record.is_public,
|
||||
&record.owner_did,
|
||||
Some("did:key:z6MkSyncStranger"),
|
||||
"/",
|
||||
),
|
||||
crate::visibility::Decision::Allow,
|
||||
"the gate can only allow for a synced row, which is the property the \
|
||||
handler's mirror-rows-handled note records",
|
||||
);
|
||||
|
||||
// So the refusal has to come from the decision that is actually load-bearing.
|
||||
let stranger = crate::auth::AuthenticatedDid("did:key:z6MkSyncStranger".to_string());
|
||||
let outcome = close_issue(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Extension(stranger),
|
||||
axum::extract::Path((
|
||||
"z6MkSyncOwner".to_string(),
|
||||
"syncrepo".to_string(),
|
||||
"1".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some("203.0.113.99:5000".parse().unwrap())),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
outcome.is_err(),
|
||||
"a stranger must still be refused on a synced row, gate or no gate",
|
||||
);
|
||||
let body = format!("{:?}", outcome.err().unwrap());
|
||||
assert!(
|
||||
!body.contains("syncrepo/") && !body.to_lowercase().contains("issue body"),
|
||||
"the refusal must not leak repo contents: {body}",
|
||||
);
|
||||
}
|
||||
|
||||
/// The read-gate added for the pre-lock snapshot: a caller who cannot READ
|
||||
/// the repo (private repo, no rule granting them access) must be refused with
|
||||
/// a not-found BEFORE any snapshot download or extraction happens. The
|
||||
/// observable is the refusal itself; the cheaper part (no Tigris work) is
|
||||
/// structural (the gate precedes the snapshot call in the handler).
|
||||
#[sqlx::test]
|
||||
async fn non_reader_is_refused_before_the_snapshot(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
let now = chrono::Utc::now();
|
||||
state
|
||||
.db
|
||||
.create_repo(&crate::db::RepoRecord {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
name: "priv-close".to_string(),
|
||||
owner_did: "z6MkT3Owner".to_string(),
|
||||
description: None,
|
||||
is_public: false,
|
||||
default_branch: "main".to_string(),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
disk_path: "/tmp/priv-close".to_string(),
|
||||
forked_from: None,
|
||||
machine_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("seed private repo");
|
||||
|
||||
let stranger = crate::auth::AuthenticatedDid("did:key:z6MkT3Stranger".to_string());
|
||||
let res = close_issue(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Extension(stranger),
|
||||
axum::extract::Path((
|
||||
"z6MkT3Owner".to_string(),
|
||||
"priv-close".to_string(),
|
||||
"1".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some("203.0.113.67:5000".parse().unwrap())),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(res, Err(AppError::RepoNotFound(_))),
|
||||
"a non-reader must be refused as not-found, got {:?}",
|
||||
res.err().map(|e| format!("{e:?}"))
|
||||
);
|
||||
}
|
||||
|
||||
async fn seed_repo_with_issue(
|
||||
state: &crate::state::AppState,
|
||||
owner_slug: &str,
|
||||
owner_did: &str,
|
||||
repo: &str,
|
||||
issue_id: &str,
|
||||
author_did: &str,
|
||||
) -> std::path::PathBuf {
|
||||
state
|
||||
.db
|
||||
.upsert_mirror_repo(owner_slug, repo, "/unused", None, true)
|
||||
.await
|
||||
.expect("seed repo row");
|
||||
// Seed at the path the HANDLER will resolve. upsert_mirror_repo stores the
|
||||
// bare slug in owner_did, and close_issue resolves from record.owner_did, so
|
||||
// seeding from the full did:key would create the repo in a different
|
||||
// directory and the handler would find nothing.
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(owner_slug, repo)
|
||||
.await
|
||||
.expect("get_repo")
|
||||
.expect("seeded repo exists");
|
||||
let _ = owner_did;
|
||||
let path = state
|
||||
.repo_store
|
||||
.acquire(&record.owner_did, &record.name)
|
||||
.await
|
||||
.expect("resolve disk path");
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
crate::git::store::init_bare(&path).expect("init bare repo");
|
||||
// Must deserialize as a real IssueRecord: `created_at` and `status` are
|
||||
// required, and a parse failure would silently drop the author (the
|
||||
// `.ok()` on from_str), which reads as a 403 rather than as a broken fixture.
|
||||
let json = serde_json::to_string(&IssueRecord {
|
||||
id: issue_id.to_string(),
|
||||
title: "seeded".to_string(),
|
||||
body: Some(String::new()),
|
||||
author: Some(author_did.to_string()),
|
||||
created_at: chrono::Utc::now().to_rfc3339(),
|
||||
status: "open".to_string(),
|
||||
signed_payload: None,
|
||||
})
|
||||
.expect("serialize seeded issue");
|
||||
crate::git::issues::create_issue(&path, issue_id, &json).expect("seed issue blob");
|
||||
path
|
||||
}
|
||||
|
||||
/// INV-21(c) positive twin 1: the OWNER can still close. The reorder moved the
|
||||
/// owner check above the lock, so this is the arm most likely to have broken,
|
||||
/// and the deny test alone could not see it.
|
||||
///
|
||||
/// The issue is seeded with a THIRD party as its author, deliberately. Seeding
|
||||
/// the owner as their own author made this test unable to fail: with the owner
|
||||
/// check disabled, the author fallback granted the close anyway and the test
|
||||
/// stayed green. Only the owner arm can grant here now.
|
||||
#[sqlx::test]
|
||||
async fn owner_can_still_close_after_the_reorder(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
let owner_did = "did:key:z6MkT1Owner";
|
||||
seed_repo_with_issue(
|
||||
&state,
|
||||
"z6MkT1Owner",
|
||||
owner_did,
|
||||
"t1repo",
|
||||
"1",
|
||||
"did:key:z6MkT1Stranger",
|
||||
)
|
||||
.await;
|
||||
|
||||
let res = close_issue(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Extension(crate::auth::AuthenticatedDid(owner_did.to_string())),
|
||||
axum::extract::Path((
|
||||
"z6MkT1Owner".to_string(),
|
||||
"t1repo".to_string(),
|
||||
"1".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some("203.0.113.65:5000".parse().unwrap())),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
res.is_ok(),
|
||||
"the owner must still be able to close: {:?}",
|
||||
res.err().map(|e| format!("{e:?}"))
|
||||
);
|
||||
}
|
||||
|
||||
/// INV-21(c) positive twin 2: the non-owner AUTHOR can still close, through both
|
||||
/// the pre-lock check and the re-assertion under the guard.
|
||||
///
|
||||
/// It does NOT cover the acquire-vs-acquire_fresh distinction, despite that being
|
||||
/// the reason the call changed. `RepoStore::for_testing` hardcodes `tigris: None`,
|
||||
/// which makes `acquire` and `acquire_fresh` identical in every test here, so
|
||||
/// reverting that line leaves this green. Separating them needs an object-storage
|
||||
/// seam, which is out of scope for this change and tracked separately. Claiming
|
||||
/// the coverage here would be worse than admitting the gap.
|
||||
#[sqlx::test]
|
||||
async fn issue_author_who_is_not_the_owner_can_still_close(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
let owner_did = "did:key:z6MkT2Owner";
|
||||
let author_did = "did:key:z6MkT2Author";
|
||||
seed_repo_with_issue(&state, "z6MkT2Owner", owner_did, "t2repo", "1", author_did).await;
|
||||
|
||||
let res = close_issue(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Extension(crate::auth::AuthenticatedDid(author_did.to_string())),
|
||||
axum::extract::Path((
|
||||
"z6MkT2Owner".to_string(),
|
||||
"t2repo".to_string(),
|
||||
"1".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some("203.0.113.66:5000".parse().unwrap())),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
res.is_ok(),
|
||||
"the issue author, who is NOT the repo owner, must still be able to close: {:?}",
|
||||
res.err().map(|e| format!("{e:?}"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #173 F1 follow-up: issue write paths reach `acquire_write` with no admission
|
||||
/// permit, so an exhausted write-lock pool must shed 503 + Retry-After.
|
||||
/// #173 F1 follow-up: the two issue write paths reach `acquire_write` holding NO
|
||||
/// admission permit (unlike the push handler, which is capped by the git-push
|
||||
/// semaphore), so they are the callers most likely to meet an exhausted write-lock
|
||||
/// POOL under load. An exhausted pool is a capacity signal, so both must shed
|
||||
/// 503 + Retry-After (`AppError::Overloaded`) the way the push handler does, not
|
||||
/// report the generic 500 git error that says nothing about retrying.
|
||||
#[cfg(test)]
|
||||
mod lock_pool_shed_tests {
|
||||
use super::*;
|
||||
@@ -830,17 +314,22 @@ mod lock_pool_shed_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// State whose repo store draws write locks from a ONE-connection pool with a
|
||||
/// short checkout timeout, so a single held guard exhausts it promptly rather
|
||||
/// than at the pool default.
|
||||
async fn one_connection_lock_pool_state(pool: &PgPool) -> AppState {
|
||||
let mut state = crate::test_support::test_state(pool.clone()).await;
|
||||
state.repo_store = crate::git::repo_store::RepoStore::new(
|
||||
std::path::PathBuf::from("/tmp/gitlawb-issues-lockpool"),
|
||||
None,
|
||||
crate::git::repo_store::build_lock_pool(pool, 1, std::time::Duration::from_secs(1)),
|
||||
std::time::Duration::from_secs(300),
|
||||
);
|
||||
state
|
||||
}
|
||||
|
||||
/// The shed must be a real 503 carrying Retry-After, not just an internal enum
|
||||
/// variant: assert on the rendered response so a remapping of `Overloaded` is
|
||||
/// caught here too.
|
||||
fn assert_sheds_503_with_retry_after(err: AppError, what: &str) {
|
||||
let resp = err.into_response();
|
||||
assert_eq!(
|
||||
@@ -857,6 +346,10 @@ mod lock_pool_shed_tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// RED-before/GREEN-after for `create_issue`. Both directions: the shed while the
|
||||
/// only lock-pool connection is held by a guard on a DIFFERENT repo (so this is
|
||||
/// pool capacity, not advisory-lock contention on this repo), and the must-not
|
||||
/// case once that connection is back.
|
||||
#[sqlx::test]
|
||||
async fn create_issue_lock_pool_exhaustion_sheds_503_not_500(pool: PgPool) {
|
||||
let owner = "did:key:zISSUECREATELOCKPOOLAAAAAAAAAAAAAAAAAAAA";
|
||||
@@ -887,7 +380,9 @@ mod lock_pool_shed_tests {
|
||||
let err = shed.expect_err("an exhausted lock pool must fail the call");
|
||||
assert_sheds_503_with_retry_after(err, "create_issue");
|
||||
|
||||
let _ = held.release(false).await;
|
||||
// MUST-NOT: with the pool free again the call is not shed as capacity (it
|
||||
// fails later on the nonexistent on-disk repo, which is a git 500).
|
||||
held.release(false).await;
|
||||
let admitted = create_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
@@ -906,38 +401,7 @@ mod lock_pool_shed_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn close_issue_read_pool_exhaustion_sheds_before_snapshot(pool: PgPool) {
|
||||
use std::sync::Arc;
|
||||
let owner = "did:key:zISSUECLOSEREADPOOLBBBBBBBBBBBBBBBBBBBBB";
|
||||
let mut state = crate::test_support::test_state(pool.clone()).await;
|
||||
state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0));
|
||||
state
|
||||
.db
|
||||
.create_repo(&seed_repo(owner, "read-cap"))
|
||||
.await
|
||||
.expect("seed repo");
|
||||
|
||||
let shed = close_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(
|
||||
"did:key:zISSUECLOSEREADSTRANGER".to_string(),
|
||||
)),
|
||||
Path((
|
||||
owner.to_string(),
|
||||
"read-cap".to_string(),
|
||||
"deadbeef".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(None),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(shed, Err(AppError::Overloaded(_))),
|
||||
"an exhausted read pool must shed before snapshot work; got {shed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// RED-before/GREEN-after for `close_issue`, same two directions.
|
||||
#[sqlx::test]
|
||||
async fn close_issue_lock_pool_exhaustion_sheds_503_not_500(pool: PgPool) {
|
||||
let owner = "did:key:zISSUECLOSELOCKPOOLBBBBBBBBBBBBBBBBBBBBB";
|
||||
@@ -962,14 +426,12 @@ mod lock_pool_shed_tests {
|
||||
"lp-close".to_string(),
|
||||
"deadbeef".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(None),
|
||||
)
|
||||
.await;
|
||||
let err = shed.expect_err("an exhausted lock pool must fail the call");
|
||||
assert_sheds_503_with_retry_after(err, "close_issue");
|
||||
|
||||
let _ = held.release(false).await;
|
||||
held.release(false).await;
|
||||
let admitted = close_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
@@ -978,8 +440,6 @@ mod lock_pool_shed_tests {
|
||||
"lp-close".to_string(),
|
||||
"deadbeef".to_string(),
|
||||
)),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(None),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
@@ -988,244 +448,4 @@ mod lock_pool_shed_tests {
|
||||
admitted.err()
|
||||
);
|
||||
}
|
||||
|
||||
async fn assert_retryable_repo_acquire(err: AppError, what: &str, code: &str) {
|
||||
let resp = err.into_response();
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"{what}: a transient acquire refusal must shed 503, not a 500 git error"
|
||||
);
|
||||
let body = axum::body::to_bytes(resp.into_body(), 64 * 1024)
|
||||
.await
|
||||
.expect("body");
|
||||
let body = String::from_utf8_lossy(&body);
|
||||
assert!(
|
||||
body.contains(code),
|
||||
"{what}: the 503 must carry the {code} code, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Advisory-lock contention on a non-push mutation must map through the shared
|
||||
/// `acquire_write_app_error` classifier to `repo_busy`, not a 500 git_error.
|
||||
#[sqlx::test]
|
||||
async fn create_issue_contention_sheds_repo_busy_not_500(pool: PgPool) {
|
||||
let owner = "did:key:zISSUECREATEBUSYAAAAAAAAAAAAAAAAAAAAA";
|
||||
let repo_name = "busy-create";
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
state
|
||||
.db
|
||||
.create_repo(&seed_repo(owner, repo_name))
|
||||
.await
|
||||
.expect("seed repo");
|
||||
|
||||
let held = state
|
||||
.repo_store
|
||||
.acquire_write(owner, repo_name)
|
||||
.await
|
||||
.expect("the first writer takes the advisory lock");
|
||||
|
||||
let shed = create_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
Path((owner.to_string(), repo_name.to_string())),
|
||||
Json(CreateIssueRequest {
|
||||
title: "t".to_string(),
|
||||
body: None,
|
||||
signed_payload: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let err = shed.expect_err("contention must refuse the second writer");
|
||||
assert_retryable_repo_acquire(err, "create_issue", "repo_busy").await;
|
||||
|
||||
let _ = held.release(false).await;
|
||||
}
|
||||
|
||||
/// A refused under-lock refresh on a non-push mutation must map to
|
||||
/// `repo_unavailable`, not expose the storage error as a 500 git_error.
|
||||
#[sqlx::test]
|
||||
async fn create_issue_unavailable_sheds_repo_unavailable_not_500(pool: PgPool) {
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
let app = axum::Router::new().route(
|
||||
"/{*key}",
|
||||
axum::routing::any(|method: axum::http::Method| async move {
|
||||
if method == axum::http::Method::HEAD {
|
||||
let mut resp = axum::http::StatusCode::OK.into_response();
|
||||
resp.headers_mut()
|
||||
.insert("etag", axum::http::HeaderValue::from_static("\"gen-1\""));
|
||||
resp
|
||||
} else {
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let owner = "did:key:zISSUEUNAVAILAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
let repo_name = "unavail-create";
|
||||
let mut state = crate::test_support::test_state(pool.clone()).await;
|
||||
state.repo_store = crate::git::repo_store::RepoStore::for_testing_with_tigris(
|
||||
std::path::PathBuf::from("/tmp/gitlawb-issue-unavail"),
|
||||
crate::git::repo_store::build_lock_pool(&pool, 2, std::time::Duration::from_secs(1)),
|
||||
crate::git::tigris::TigrisClient::for_testing_with_endpoint("test-bucket", &endpoint),
|
||||
);
|
||||
state
|
||||
.db
|
||||
.create_repo(&seed_repo(owner, repo_name))
|
||||
.await
|
||||
.expect("seed repo");
|
||||
|
||||
let shed = create_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
Path((owner.to_string(), repo_name.to_string())),
|
||||
Json(CreateIssueRequest {
|
||||
title: "t".to_string(),
|
||||
body: None,
|
||||
signed_payload: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let err = shed.expect_err("a failed archive download must refuse the write");
|
||||
assert_retryable_repo_acquire(err, "create_issue", "repo_unavailable").await;
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// A denied reader on a private repo must see 404 even when the caller's rate
|
||||
/// bucket is exhausted. Rate limiting runs after the read gate.
|
||||
#[sqlx::test]
|
||||
async fn close_issue_rate_limit_runs_after_the_read_gate(pool: PgPool) {
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
let owner = "did:key:zCLOSERATEOWNERAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
let stranger = "did:key:zCLOSERATESTRANGERBBBBBBBBBBBBBBBBBB";
|
||||
let mut state = crate::test_support::test_state(pool).await;
|
||||
state.close_issue_rate_limiter =
|
||||
crate::rate_limit::RateLimiter::new(1, Duration::from_secs(60));
|
||||
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
|
||||
|
||||
let mut repo = seed_repo(owner, "priv-close");
|
||||
repo.is_public = false;
|
||||
state.db.create_repo(&repo).await.expect("seed repo");
|
||||
|
||||
let peer: SocketAddr = "203.0.113.88:7000".parse().unwrap();
|
||||
assert!(
|
||||
state
|
||||
.close_issue_rate_limiter
|
||||
.check(&peer.ip().to_string())
|
||||
.await,
|
||||
"exhaust the close_issue bucket before close_issue"
|
||||
);
|
||||
|
||||
let res = close_issue(
|
||||
State(state),
|
||||
Extension(AuthenticatedDid(stranger.to_string())),
|
||||
Path((owner.to_string(), "priv-close".to_string(), "1".to_string())),
|
||||
axum::http::HeaderMap::new(),
|
||||
crate::rate_limit::PeerAddr(Some(peer)),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
matches!(res, Err(AppError::RepoNotFound(_))),
|
||||
"a non-reader must see 404, not 429, even when rate limited: {:?}",
|
||||
res
|
||||
);
|
||||
}
|
||||
|
||||
/// close_issue and receive-pack must not share one per-IP bucket.
|
||||
#[sqlx::test]
|
||||
async fn close_issue_rate_limit_does_not_drain_push_bucket(pool: PgPool) {
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
let mut state = crate::test_support::test_state(pool).await;
|
||||
state.close_issue_rate_limiter =
|
||||
crate::rate_limit::RateLimiter::new(1, Duration::from_secs(60));
|
||||
state.push_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(60));
|
||||
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
|
||||
|
||||
let peer: SocketAddr = "203.0.113.99:7000".parse().unwrap();
|
||||
let key = peer.ip().to_string();
|
||||
assert!(
|
||||
state.close_issue_rate_limiter.check(&key).await,
|
||||
"exhaust only the close_issue bucket"
|
||||
);
|
||||
assert!(
|
||||
state.push_rate_limiter.check(&key).await,
|
||||
"push traffic must keep its own bucket after close_issue is exhausted"
|
||||
);
|
||||
}
|
||||
|
||||
/// A refused publish must roll back the local issue ref so a retry does not
|
||||
/// mint a second id for the same logical filing attempt.
|
||||
#[sqlx::test]
|
||||
async fn create_issue_rolls_back_local_ref_when_publish_refuses(pool: PgPool) {
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
let app = axum::Router::new().route(
|
||||
"/{*key}",
|
||||
axum::routing::any(|method: axum::http::Method| async move {
|
||||
if method == axum::http::Method::HEAD {
|
||||
let mut resp = axum::http::StatusCode::OK.into_response();
|
||||
resp.headers_mut()
|
||||
.insert("etag", axum::http::HeaderValue::from_static("\"gen-1\""));
|
||||
resp
|
||||
} else {
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let owner = "did:key:zISSUEROLLBACKAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
let repo_name = "rollback-create";
|
||||
let mut state = crate::test_support::test_state(pool.clone()).await;
|
||||
let disk = tempfile::TempDir::new().unwrap();
|
||||
crate::git::store::init_bare(&disk.path().join("repo.git")).expect("bare repo");
|
||||
let mut seeded = seed_repo(owner, repo_name);
|
||||
seeded.disk_path = disk.path().join("repo.git").to_string_lossy().to_string();
|
||||
state.db.create_repo(&seeded).await.expect("seed repo");
|
||||
state.repo_store = crate::git::repo_store::RepoStore::for_testing_with_tigris(
|
||||
disk.path().to_path_buf(),
|
||||
crate::git::repo_store::build_lock_pool(&pool, 2, std::time::Duration::from_secs(1)),
|
||||
crate::git::tigris::TigrisClient::for_testing_with_endpoint("test-bucket", &endpoint),
|
||||
);
|
||||
|
||||
let shed = create_issue(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
Path((owner.to_string(), repo_name.to_string())),
|
||||
Json(CreateIssueRequest {
|
||||
title: "t".to_string(),
|
||||
body: None,
|
||||
signed_payload: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
shed.is_err(),
|
||||
"a failed archive upload must refuse the write"
|
||||
);
|
||||
|
||||
let issues = git_issues::list_issues(&disk.path().join("repo.git")).expect("list issues");
|
||||
assert!(
|
||||
issues.is_empty(),
|
||||
"the local issue ref must be rolled back after a refused publish, got {issues:?}"
|
||||
);
|
||||
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
@@ -71,10 +71,6 @@ pub async fn remove_label(
|
||||
}
|
||||
|
||||
/// GET /api/v1/repos/:owner/:repo/labels
|
||||
///
|
||||
/// Read-visibility-gated (INV-2 root listing): a public repo's labels stay
|
||||
/// anonymously listable; a private repo's label names are hidden (404) from
|
||||
/// anyone who cannot read it at the root.
|
||||
pub async fn list_labels(
|
||||
State(state): State<AppState>,
|
||||
Path((owner, name)): Path<(String, String)>,
|
||||
|
||||
@@ -172,7 +172,6 @@ mod authz_guard {
|
||||
let issues = include_str!("issues.rs");
|
||||
let bounties = include_str!("bounties.rs");
|
||||
let replicas = include_str!("replicas.rs");
|
||||
let events = include_str!("events.rs");
|
||||
let tasks = include_str!("tasks.rs");
|
||||
let stars = include_str!("stars.rs");
|
||||
let protect = include_str!("protect.rs");
|
||||
@@ -188,13 +187,6 @@ mod authz_guard {
|
||||
(pulls, "merge_pr", "require_repo_owner("),
|
||||
(webhooks, "create_webhook", "require_repo_owner("),
|
||||
(webhooks, "delete_webhook", "require_repo_owner("),
|
||||
// Bucket A/B hybrid — list_webhooks is read-visibility THEN owner:
|
||||
// authorize_repo_read 404s a non-reader of a private repo, then
|
||||
// require_repo_owner 403s a non-owner of a public one. Both halves
|
||||
// are pinned: the authorize_repo_read marker guards the read half
|
||||
// (existence hiding) and require_repo_owner guards the owner half.
|
||||
(webhooks, "list_webhooks", "authorize_repo_read("),
|
||||
(webhooks, "list_webhooks", "require_repo_owner("),
|
||||
(labels, "add_label", "require_repo_owner("),
|
||||
(labels, "remove_label", "require_repo_owner("),
|
||||
// Bucket A' — owner OR author (did_matches against the author)
|
||||
@@ -209,18 +201,10 @@ mod authz_guard {
|
||||
(bounties, "create_bounty", "authorize_repo_read("),
|
||||
(repos, "fork_repo", "authorize_repo_read("),
|
||||
// get_by_cid resolves each candidate (provenance path + legacy scan) through
|
||||
// the shared `gate_and_serve`; the gate markers themselves are asserted
|
||||
// below. This row proves the delegation is real, so the gate is actually
|
||||
// reached rather than dead code. The delegated gate still calls
|
||||
// `visibility_check` directly and never `authorize_repo_read`, so it keeps
|
||||
// the property the pre-merge marker enforced: no fuzzy re-resolve.
|
||||
// the shared `gate_and_serve` (#173 round 2); the gate markers themselves are
|
||||
// asserted below. This row proves the delegation is real — the gate is
|
||||
// actually reached, not dead code.
|
||||
(ipfs, "get_by_cid", "gate_and_serve("),
|
||||
// Sibling read surfaces: gate private-repo metadata on read visibility
|
||||
// (public repos stay anonymous; private repos 404).
|
||||
(replicas, "list_replicas", "authorize_repo_read("),
|
||||
(protect, "list_protected_branches", "authorize_repo_read("),
|
||||
(labels, "list_labels", "authorize_repo_read("),
|
||||
(events, "list_repo_events", "authorize_repo_read("),
|
||||
// Bucket C — signer-self: the acting DID is matched/bound to auth.0
|
||||
(tasks, "create_task", "did_matches("),
|
||||
(tasks, "claim_task", "did_matches("),
|
||||
@@ -543,7 +527,11 @@ mod authz_guard {
|
||||
|
||||
// Repo-scoped reads known to be ungated today, each tracked by an issue.
|
||||
// Remove an entry the moment its gate lands (the staleness assert enforces it).
|
||||
let known_ungated: &[(&str, &str)] = &[];
|
||||
let known_ungated: &[(&str, &str)] = &[
|
||||
("list_webhooks", "#94 (PR #113)"),
|
||||
("list_replicas", "PR #113"),
|
||||
("list_protected_branches", "PR #113"),
|
||||
];
|
||||
let is_known = |n: &str| known_ungated.iter().any(|(k, _)| *k == n);
|
||||
// Any one of these = the handler binds the caller to an authz decision: the
|
||||
// first two are read gates, the rest are the write/owner/self-binding forms.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -79,14 +79,12 @@ pub async fn unprotect_branch(
|
||||
pub async fn list_protected_branches(
|
||||
State(state): State<AppState>,
|
||||
Path((owner, repo)): Path<(String, String)>,
|
||||
auth: Option<Extension<AuthenticatedDid>>,
|
||||
) -> Result<Json<serde_json::Value>> {
|
||||
// Read-visibility-gated (INV-2 root listing): a public repo's protected
|
||||
// branches stay anonymously listable; a private repo's branch names are
|
||||
// hidden (404) from anyone who cannot read it at the root.
|
||||
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
|
||||
let (record, _rules) =
|
||||
crate::api::authorize_repo_read(&state, &owner, &repo, caller, "/").await?;
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(&owner, &repo)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
|
||||
|
||||
let branches = state.db.list_protected_branches(&record.id).await?;
|
||||
|
||||
|
||||
@@ -209,6 +209,9 @@ pub async fn merge_pr(
|
||||
return Err(AppError::BadRequest(format!("PR is already {}", pr.status)));
|
||||
}
|
||||
|
||||
// Shed 503 + Retry-After on an exhausted write-lock POOL instead of a generic
|
||||
// git 500 (#173 F1). Merging holds no admission permit, so it reaches the pool
|
||||
// unthrottled; reuse the push handler's mapping so the two cannot drift.
|
||||
let guard = state
|
||||
.repo_store
|
||||
.acquire_write(&record.owner_did, &record.name)
|
||||
@@ -225,10 +228,7 @@ pub async fn merge_pr(
|
||||
);
|
||||
|
||||
// Always release the advisory lock — even on error; upload to Tigris only on success.
|
||||
// Short-circuit on a refused publish before the PR is marked merged and
|
||||
// before the webhook fires. Both are irreversible announcements of a merge
|
||||
// commit that only exists on this node's disk.
|
||||
guard.release(merge_result.is_ok()).await.into_result()?;
|
||||
guard.release(merge_result.is_ok()).await;
|
||||
|
||||
let merge_sha = merge_result.map_err(|e| AppError::Git(e.to_string()))?;
|
||||
|
||||
@@ -428,8 +428,12 @@ pub async fn list_comments(
|
||||
Ok(Json(serde_json::json!({ "comments": comments })))
|
||||
}
|
||||
|
||||
/// #173 F1 follow-up: merge holds no admission permit, so an exhausted write-lock
|
||||
/// pool must shed 503 + Retry-After.
|
||||
/// #173 F1 follow-up: `merge_pr` reaches `acquire_write` holding NO admission permit
|
||||
/// (unlike the push handler, which is capped by the git-push semaphore), so it is one
|
||||
/// of the callers most likely to meet an exhausted write-lock POOL under load. An
|
||||
/// exhausted pool is a capacity signal, so the merge must shed 503 + Retry-After
|
||||
/// (`AppError::Overloaded`) the way the push handler does, not report the generic
|
||||
/// 500 git error that says nothing about retrying.
|
||||
#[cfg(test)]
|
||||
mod lock_pool_shed_tests {
|
||||
use super::*;
|
||||
@@ -453,15 +457,20 @@ mod lock_pool_shed_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// RED-before/GREEN-after for `merge_pr`. Both directions: the shed while the only
|
||||
/// lock-pool connection is held by a guard on a DIFFERENT repo (so this is pool
|
||||
/// capacity, not advisory-lock contention on this repo), and the must-not case
|
||||
/// once that connection is back.
|
||||
#[sqlx::test]
|
||||
async fn merge_pr_lock_pool_exhaustion_sheds_503_not_500(pool: PgPool) {
|
||||
let owner = "did:key:zMERGELOCKPOOLOWNERAAAAAAAAAAAAAAAAAAAAA";
|
||||
let mut state = crate::test_support::test_state(pool.clone()).await;
|
||||
// One lock-pool connection with a short checkout timeout, so a single held
|
||||
// guard exhausts it promptly rather than at the pool default.
|
||||
state.repo_store = crate::git::repo_store::RepoStore::new(
|
||||
std::path::PathBuf::from("/tmp/gitlawb-pulls-lockpool"),
|
||||
None,
|
||||
crate::git::repo_store::build_lock_pool(&pool, 1, std::time::Duration::from_secs(1)),
|
||||
std::time::Duration::from_secs(300),
|
||||
);
|
||||
|
||||
let repo = seed_repo(owner, "lp-merge");
|
||||
@@ -515,7 +524,9 @@ mod lock_pool_shed_tests {
|
||||
"merge_pr: a capacity shed must tell the client when to retry"
|
||||
);
|
||||
|
||||
let _ = held.release(false).await;
|
||||
// MUST-NOT: with the pool free again the merge is not shed as capacity (it
|
||||
// fails later on the nonexistent on-disk repo, which is a git 500).
|
||||
held.release(false).await;
|
||||
let admitted = merge_pr(
|
||||
State(state.clone()),
|
||||
Extension(AuthenticatedDid(owner.to_string())),
|
||||
|
||||
@@ -113,17 +113,16 @@ pub async fn unregister_replica(
|
||||
}
|
||||
|
||||
/// GET /api/v1/repos/:owner/:repo/replicas
|
||||
/// Read-visibility-gated: a PUBLIC repo's replica list stays anonymously
|
||||
/// listable (mirror-discovery), but a PRIVATE repo's replica URLs are hidden
|
||||
/// (404) from anyone who cannot read the repo at its root.
|
||||
/// Public — returns the list of replicas (DID + URL + registration timestamp).
|
||||
pub async fn list_replicas(
|
||||
State(state): State<AppState>,
|
||||
Path((owner, repo)): Path<(String, String)>,
|
||||
auth: Option<Extension<AuthenticatedDid>>,
|
||||
) -> Result<Json<serde_json::Value>> {
|
||||
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
|
||||
let (record, _rules) =
|
||||
crate::api::authorize_repo_read(&state, &owner, &repo, caller, "/").await?;
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(&owner, &repo)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
|
||||
|
||||
let replicas = state.db.list_replicas(&record.id).await?;
|
||||
|
||||
|
||||
+677
-6043
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
//! Webhook CRUD API.
|
||||
//!
|
||||
//! POST /api/v1/repos/:owner/:repo/hooks — create (owner only)
|
||||
//! GET /api/v1/repos/:owner/:repo/hooks — list (owner only; auth required)
|
||||
//! DELETE /api/v1/repos/:owner/:repo/hooks/:id — delete (owner only)
|
||||
//! POST /api/v1/repos/:owner/:repo/hooks — create (auth required)
|
||||
//! GET /api/v1/repos/:owner/:repo/hooks — list
|
||||
//! DELETE /api/v1/repos/:owner/:repo/hooks/:id — delete (auth required)
|
||||
|
||||
use axum::extract::{Extension, Path, State};
|
||||
use axum::http::StatusCode;
|
||||
@@ -73,26 +73,12 @@ pub async fn create_webhook(
|
||||
pub async fn list_webhooks(
|
||||
State(state): State<AppState>,
|
||||
Path((owner, name)): Path<(String, String)>,
|
||||
auth: Option<Extension<AuthenticatedDid>>,
|
||||
) -> Result<Json<serde_json::Value>> {
|
||||
// This route sits on `optional_signature`, so the DID is optional. Webhook
|
||||
// callback URLs are owner-secret config and there is no anonymous form, so a
|
||||
// headerless caller is rejected before any lookup (401, which fires for an
|
||||
// existing-private and an absent repo alike, so it leaks no existence).
|
||||
let Some(Extension(AuthenticatedDid(caller))) = auth else {
|
||||
return Err(AppError::Unauthorized(
|
||||
"listing webhooks requires authentication".into(),
|
||||
));
|
||||
};
|
||||
|
||||
// Read-visibility first, then owner. authorize_repo_read returns 404 on a
|
||||
// visibility deny, so a non-reader of a private repo cannot tell it exists
|
||||
// (uniform with the sibling read surfaces); require_repo_owner then yields
|
||||
// 403 only for a non-owner of a public/readable repo, where existence is not
|
||||
// secret.
|
||||
let (record, _rules) =
|
||||
crate::api::authorize_repo_read(&state, &owner, &name, Some(&caller), "/").await?;
|
||||
crate::api::require_repo_owner(&record, &caller)?;
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(&owner, &name)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
|
||||
|
||||
let hooks = state.db.list_webhooks(&record.id).await?;
|
||||
// Redact secrets in list response
|
||||
|
||||
@@ -490,7 +490,6 @@ mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
let keypair = Keypair::generate();
|
||||
let scan_token_key = crate::state::AppState::derive_scan_token_key(&keypair);
|
||||
let (ref_tx, _) = tokio::sync::broadcast::channel(1);
|
||||
let (task_tx, _) = tokio::sync::broadcast::channel(1);
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
@@ -517,16 +516,10 @@ mod tests {
|
||||
rate_limiter: RateLimiter::new(100, Duration::from_secs(60)),
|
||||
create_ip_rate_limiter: RateLimiter::new(1000, Duration::from_secs(3600)),
|
||||
push_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)),
|
||||
close_issue_rate_limiter: RateLimiter::new(120, Duration::from_secs(3600)),
|
||||
ipfs_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)),
|
||||
ipfs_work_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)),
|
||||
ipfs_max_history_walks: crate::api::ipfs::MAX_HISTORY_WALKS_PER_REQUEST,
|
||||
ipfs_max_legacy_probes: crate::api::ipfs::MAX_LEGACY_PROBES_PER_REQUEST,
|
||||
ipfs_legacy_scan_page_rows: crate::api::ipfs::LEGACY_SCAN_PAGE_ROWS,
|
||||
ipfs_max_legacy_scan_rows: crate::api::ipfs::MAX_LEGACY_SCAN_ROWS_PER_REQUEST,
|
||||
ipfs_max_legacy_scan_rule_bytes:
|
||||
crate::api::ipfs::MAX_LEGACY_SCAN_RULE_BYTES_PER_REQUEST,
|
||||
ipfs_scan_token_key: Arc::new(scan_token_key),
|
||||
ipfs_max_served_object_bytes: crate::api::ipfs::MAX_SERVED_OBJECT_BYTES,
|
||||
push_limiter_trust: crate::rate_limit::TrustedProxy::None,
|
||||
sync_trigger_rate_limiter: RateLimiter::new(60, Duration::from_secs(3600)),
|
||||
@@ -536,9 +529,7 @@ mod tests {
|
||||
git_write_semaphore: Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
git_push_advert_semaphore: Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
git_encrypt_semaphore: Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
pin_semaphore: Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
encrypt_inflight: crate::state::EncryptInflight::new(),
|
||||
repo_write_leases: crate::state::RepoWriteLeases::new(8),
|
||||
git_read_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys(16),
|
||||
git_push_advert_per_caller:
|
||||
crate::rate_limit::PerCallerConcurrency::with_default_max_keys(8),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+91
-2849
File diff suppressed because it is too large.
Load diff
@@ -170,7 +170,7 @@ pub async fn encrypt_and_pin(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let cid = match crate::ipfs_pin::pin_git_object(ipfs_api, oid, &envelope, None).await {
|
||||
let cid = match crate::ipfs_pin::pin_git_object(ipfs_api, oid, &envelope).await {
|
||||
Ok(c) if !c.is_empty() => c,
|
||||
Ok(_) => {
|
||||
tracing::warn!(oid = %oid, "pin_git_object returned no cid; skipping");
|
||||
|
||||
@@ -35,30 +35,14 @@ pub enum AppError {
|
||||
#[error("invalid request: {0}")]
|
||||
BadRequest(String),
|
||||
|
||||
/// A DID was well-formed enough to carry to a resolver but no verifying key
|
||||
/// could be derived from it. Its own code rather than plain `bad_request`
|
||||
/// because the auth middleware already answers `unresolvable_did` for the
|
||||
/// same failure on a request's keyid, and a client should not have to
|
||||
/// substring-match a message to tell this apart from the other validation
|
||||
/// failures on the same route.
|
||||
#[error("unresolvable did: {0}")]
|
||||
UnresolvableDid(String),
|
||||
|
||||
#[error("too many requests: {0}")]
|
||||
TooManyRequests(String),
|
||||
|
||||
#[error("incomplete: {0}")]
|
||||
Incomplete(String),
|
||||
|
||||
/// A bounded search that could not complete. `continuation`, when present, is the
|
||||
/// sealed scan position the caller echoes as `?scan=` to resume where the search
|
||||
/// stopped (#173 round 13, F2). It is AEAD-sealed at the mint site, never plaintext:
|
||||
/// the row it names is by construction one the caller was denied (INV-13).
|
||||
#[error("search incomplete: {message}")]
|
||||
SearchIncomplete {
|
||||
message: String,
|
||||
continuation: Option<String>,
|
||||
},
|
||||
#[error("search incomplete: {0}")]
|
||||
SearchIncomplete(String),
|
||||
|
||||
#[error("git error: {0}")]
|
||||
Git(String),
|
||||
@@ -69,15 +53,6 @@ pub enum AppError {
|
||||
#[error("server overloaded: {0}")]
|
||||
Overloaded(String),
|
||||
|
||||
#[error("repository is busy")]
|
||||
RepoBusy,
|
||||
|
||||
#[error("repository is temporarily unavailable")]
|
||||
RepoUnavailable,
|
||||
|
||||
#[error("repository write was fenced by a concurrent publish")]
|
||||
RepoWriteFenced,
|
||||
|
||||
#[error("database error: {0}")]
|
||||
Db(#[from] sqlx::Error),
|
||||
|
||||
@@ -91,14 +66,6 @@ pub enum AppError {
|
||||
pub const DB_UNAVAILABLE_CODE: &str = "db_unavailable";
|
||||
pub const DB_UNAVAILABLE_MESSAGE: &str = "database is temporarily unavailable";
|
||||
|
||||
/// Generic client-facing message for `AppError::Internal`. The real error is
|
||||
/// logged server-side; never put sqlx/anyhow detail in the HTTP body (#226).
|
||||
pub const INTERNAL_ERROR_MESSAGE: &str = "an internal error occurred";
|
||||
|
||||
/// Generic client-facing message for non-unavailable `AppError::Db`. Query /
|
||||
/// schema errors stay in logs; the HTTP body must not leak them (#226).
|
||||
pub const DB_ERROR_MESSAGE: &str = "a database error occurred";
|
||||
|
||||
/// Connection-level sqlx failures that mean the database is unreachable right
|
||||
/// now (retryable, 503), as opposed to server-reported query errors.
|
||||
fn db_unavailable(e: &sqlx::Error) -> bool {
|
||||
@@ -119,31 +86,7 @@ impl From<anyhow::Error> for AppError {
|
||||
fn from(err: anyhow::Error) -> Self {
|
||||
match err.downcast::<sqlx::Error>() {
|
||||
Ok(sql) => AppError::Db(sql),
|
||||
// Lock contention is transient and ordinary, so it must not land as a
|
||||
// 500. The internal message names the owner slug and repo, so the
|
||||
// variant carries nothing: the detail stays in the log at the raise
|
||||
// site and the client gets a fixed retryable body.
|
||||
Err(err) => match err.downcast::<crate::git::repo_store::LockPoolBusy>() {
|
||||
Ok(_) => AppError::Overloaded("git write locks at capacity, retry shortly".into()),
|
||||
Err(err) => match err.downcast::<crate::git::repo_store::RepoBusy>() {
|
||||
Ok(_) => AppError::RepoBusy,
|
||||
// Same reasoning one rung down: a refused under-lock refresh is a
|
||||
// transient storage condition, and its internal message names the
|
||||
// owner slug and repo, so the variant carries nothing.
|
||||
Err(err) => match err.downcast::<crate::git::repo_store::RepoUnavailable>() {
|
||||
Ok(_) => AppError::RepoUnavailable,
|
||||
// And one more rung: a publish the store refused twice is
|
||||
// transient in the same way, and the retry is the client's
|
||||
// to make. The variant carries nothing for the same reason
|
||||
// as the two above.
|
||||
Err(err) => match err.downcast::<crate::git::repo_store::RepoWriteFenced>()
|
||||
{
|
||||
Ok(_) => AppError::RepoWriteFenced,
|
||||
Err(err) => AppError::Internal(err),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Err(err) => AppError::Internal(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,9 +138,6 @@ impl IntoResponse for AppError {
|
||||
// IcaptchaProofRequired is handled above (it carries extra headers/fields).
|
||||
AppError::IcaptchaProofRequired { .. } => unreachable!("handled before this match"),
|
||||
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "bad_request", msg.clone()),
|
||||
AppError::UnresolvableDid(msg) => {
|
||||
(StatusCode::BAD_REQUEST, "unresolvable_did", msg.clone())
|
||||
}
|
||||
AppError::TooManyRequests(msg) => {
|
||||
(StatusCode::TOO_MANY_REQUESTS, "rate_limited", msg.clone())
|
||||
}
|
||||
@@ -208,38 +148,15 @@ impl IntoResponse for AppError {
|
||||
// legacy-probe or walk ceiling), distinct from the 404 that asserts a
|
||||
// definitive not-found: absence was NOT proven, so the caller should
|
||||
// retry rather than treat it as gone (#173, F2). 503, retryable.
|
||||
AppError::SearchIncomplete { message, .. } => (
|
||||
AppError::SearchIncomplete(msg) => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"search_incomplete",
|
||||
message.clone(),
|
||||
msg.clone(),
|
||||
),
|
||||
AppError::Git(msg) => (StatusCode::INTERNAL_SERVER_ERROR, "git_error", msg.clone()),
|
||||
// 504, distinct from the 500 git_error and from the read-gate's 404 /
|
||||
// the auth 401, so the client can tell a deadline from a failure.
|
||||
AppError::Timeout(msg) => (StatusCode::GATEWAY_TIMEOUT, "git_timeout", msg.clone()),
|
||||
// 503 with a FIXED body: the caller should retry, and must not be told
|
||||
// which repo is contended or for how long.
|
||||
AppError::RepoBusy => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"repo_busy",
|
||||
"repository is busy — retry".into(),
|
||||
),
|
||||
// 503 with a FIXED body for the same reason: the caller should retry, and
|
||||
// must not be told which repo could not be refreshed or why.
|
||||
AppError::RepoUnavailable => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"repo_unavailable",
|
||||
"repository is temporarily unavailable, retry".into(),
|
||||
),
|
||||
// 503 with a FIXED body again, and its own code: the caller should
|
||||
// retry, but the condition is not contention, so a client that
|
||||
// distinguishes them should be able to. The body must not say which
|
||||
// repo lost its publish or to whom.
|
||||
AppError::RepoWriteFenced => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"repo_write_fenced",
|
||||
"repository changed underneath this write, retry".into(),
|
||||
),
|
||||
AppError::Db(e) if db_unavailable(e) => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
DB_UNAVAILABLE_CODE,
|
||||
@@ -251,60 +168,27 @@ impl IntoResponse for AppError {
|
||||
AppError::Overloaded(msg) => {
|
||||
(StatusCode::SERVICE_UNAVAILABLE, "overloaded", msg.clone())
|
||||
}
|
||||
// Opaque body + server log: bare `?` on sqlx paths becomes `AppError::Db`
|
||||
// via `From`, so this arm (not `Internal`) is the common leak for open
|
||||
// routes like GET /api/v1/repos and GET /api/v1/peers (#226).
|
||||
AppError::Db(e) => {
|
||||
tracing::error!(error = %e, "database error");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"db_error",
|
||||
DB_ERROR_MESSAGE.into(),
|
||||
)
|
||||
}
|
||||
// Opaque body: handlers that map with `.map_err(AppError::Internal)`
|
||||
// (e.g. GET /ipfs/{cid}) land here; other DB failures usually hit `Db`.
|
||||
// Log `{e:#}` so context-wrapped anyhow chains keep the leaf cause
|
||||
// (Display alone is only the outermost layer; see api/repos.rs).
|
||||
AppError::Internal(e) => {
|
||||
tracing::error!(error = %format!("{e:#}"), "internal error");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"internal_error",
|
||||
INTERNAL_ERROR_MESSAGE.into(),
|
||||
)
|
||||
}
|
||||
AppError::Db(e) => (StatusCode::INTERNAL_SERVER_ERROR, "db_error", e.to_string()),
|
||||
AppError::Internal(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"internal_error",
|
||||
e.to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
let mut body = json!({
|
||||
let body = Json(json!({
|
||||
"error": code,
|
||||
"message": message,
|
||||
});
|
||||
// A truncated CID search may carry the sealed position the caller echoes as
|
||||
// `?scan=` to resume. Rendered as a third body field, present only when the
|
||||
// shed actually left something to resume: a wrapped scan and a throttled
|
||||
// request both omit it, and its ABSENCE is what tells a caller the ladder is
|
||||
// over. It is opaque ciphertext; see `gitlawb_core::scan_token`.
|
||||
if let AppError::SearchIncomplete {
|
||||
continuation: Some(token),
|
||||
..
|
||||
} = &self
|
||||
{
|
||||
body["continuation"] = json!(token);
|
||||
}
|
||||
}));
|
||||
|
||||
let mut resp = (status, Json(body)).into_response();
|
||||
let mut resp = (status, body).into_response();
|
||||
// Both retryable 503s advertise when to retry: Overloaded (capacity shed) and
|
||||
// SearchIncomplete (a bounded CID search cut short by a cap — retry may complete
|
||||
// it). They ride the shared tail above for body/status, so the header is attached
|
||||
// here rather than in bespoke early returns, keeping each variant handled once.
|
||||
if matches!(
|
||||
self,
|
||||
AppError::Overloaded(_)
|
||||
| AppError::SearchIncomplete { .. }
|
||||
| AppError::RepoBusy
|
||||
| AppError::RepoUnavailable
|
||||
| AppError::RepoWriteFenced
|
||||
AppError::Overloaded(_) | AppError::SearchIncomplete(_)
|
||||
) {
|
||||
resp.headers_mut().insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
@@ -343,110 +227,4 @@ mod tests {
|
||||
"1"
|
||||
);
|
||||
}
|
||||
|
||||
/// #226: raw sqlx/DB detail must never appear in the Internal 500 body.
|
||||
#[tokio::test]
|
||||
async fn internal_error_body_is_opaque() {
|
||||
use serde_json::{json, Value};
|
||||
|
||||
let leak = "error returned from database: relation \"repos\" does not exist";
|
||||
let resp = AppError::Internal(anyhow::anyhow!("{leak}")).into_response();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read body");
|
||||
let v: Value = serde_json::from_slice(&bytes).expect("json body");
|
||||
// Exact object: a new `detail` field with different sensitive text must
|
||||
// also fail, not only a repeat of the original error string.
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({
|
||||
"error": "internal_error",
|
||||
"message": INTERNAL_ERROR_MESSAGE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// #226: `AppError::Db` query errors (the common `?` path) must also be opaque.
|
||||
#[tokio::test]
|
||||
async fn db_error_body_is_opaque() {
|
||||
use serde_json::{json, Value};
|
||||
|
||||
let resp = AppError::Db(sqlx::Error::Protocol(
|
||||
"error returned from database: column \"is_public\" does not exist".into(),
|
||||
))
|
||||
.into_response();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read body");
|
||||
let v: Value = serde_json::from_slice(&bytes).expect("json body");
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({
|
||||
"error": "db_error",
|
||||
"message": DB_ERROR_MESSAGE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Connection-level failures must stay 503 `db_unavailable`, not collapse
|
||||
/// into the opaque 500 `db_error` arm if `db_unavailable` loses a variant.
|
||||
#[tokio::test]
|
||||
async fn db_pool_timeout_stays_503_unavailable() {
|
||||
use serde_json::{json, Value};
|
||||
|
||||
let resp = AppError::Db(sqlx::Error::PoolTimedOut).into_response();
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read body");
|
||||
let v: Value = serde_json::from_slice(&bytes).expect("json body");
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({
|
||||
"error": DB_UNAVAILABLE_CODE,
|
||||
"message": DB_UNAVAILABLE_MESSAGE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// #251: bare `?` on anyhow-wrapped sqlx relies on this downcast so a
|
||||
/// closed pool becomes 503 `db_unavailable`, not 500 `internal_error`.
|
||||
#[test]
|
||||
fn pool_closed_via_anyhow_from_is_503_db_unavailable() {
|
||||
let err: AppError = anyhow::Error::from(sqlx::Error::PoolClosed).into();
|
||||
let resp = err.into_response();
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_pool_busy_via_anyhow_from_is_503_overloaded() {
|
||||
let err: AppError = anyhow::Error::new(crate::git::repo_store::LockPoolBusy).into();
|
||||
let resp = err.into_response();
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(
|
||||
resp.headers().get("retry-after").unwrap().to_str().unwrap(),
|
||||
"1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_busy_unavailable_and_fenced_advertise_retry_after() {
|
||||
for err in [
|
||||
AppError::RepoBusy,
|
||||
AppError::RepoUnavailable,
|
||||
AppError::RepoWriteFenced,
|
||||
] {
|
||||
let resp = err.into_response();
|
||||
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(
|
||||
resp.headers().get("retry-after").unwrap().to_str().unwrap(),
|
||||
"1"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,27 +61,6 @@ pub fn create_issue(repo_path: &Path, issue_id: &str, json: &str) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a single issue ref while the write guard still holds the advisory lock,
|
||||
/// after a definite publish refusal. Best-effort: a failed delete leaves a
|
||||
/// local-only orphan, which is still better than telling the client to retry into a
|
||||
/// duplicate id. Not used on `UploadUnknowable`, where the PUT may still land.
|
||||
pub fn delete_issue_ref(
|
||||
git_bin: &str,
|
||||
repo_path: &Path,
|
||||
issue_id: &str,
|
||||
deadline: std::time::Instant,
|
||||
) -> Result<()> {
|
||||
let ref_name = format!("refs/gitlawb/issues/{issue_id}");
|
||||
crate::git::visibility_pack::run_bounded_git(
|
||||
git_bin,
|
||||
&["update-ref", "-d", &ref_name],
|
||||
repo_path,
|
||||
b"",
|
||||
deadline,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all issue refs and return their JSON content.
|
||||
pub fn list_issues(repo_path: &Path) -> Result<Vec<String>> {
|
||||
// List all refs under refs/gitlawb/issues/
|
||||
@@ -299,27 +278,6 @@ mod tests {
|
||||
assert!(result.unwrap_err().to_string().contains("ambiguous"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_issue_ref_removes_a_created_ref() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
init_repo(&dir);
|
||||
let full_id = "eee88888-0000-0000-0000-000000000000";
|
||||
create_issue(
|
||||
dir.path(),
|
||||
full_id,
|
||||
r#"{"id":"eee88888-0000-0000-0000-000000000000","status":"open"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
delete_issue_ref(
|
||||
"git",
|
||||
dir.path(),
|
||||
full_id,
|
||||
std::time::Instant::now() + std::time::Duration::from_secs(30),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(resolve_issue_id(dir.path(), full_id).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_close_issue_via_prefix() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -282,61 +282,19 @@ pub struct PinCandidateSet {
|
||||
/// it can never leak because the withheld/fail-closed filter still runs on
|
||||
/// whatever set is returned. `full_scan` rides on the returned set so the caller
|
||||
/// knows when the dangling-inclusive filter is required.
|
||||
///
|
||||
/// `scan_sem` is the post-receive scan admission pool (`git_encrypt_semaphore`,
|
||||
/// #174 F4): both git-spawning stages — the per-tip `cat-file` probe + delta
|
||||
/// rev-list, and the full-scan fallback — run under ONE permit held for the
|
||||
/// whole blocking scan. The deletion-only fast path (no new tips) spawns no git
|
||||
/// and never parks.
|
||||
///
|
||||
/// `force_full_scan` forces the full-scan fallback regardless of the tips — the
|
||||
/// coalesced-drain `PendingWork::FullScan` marker (#174 F5). It composes with
|
||||
/// the env kill-switch (either forces), and it disqualifies the empty-tips fast
|
||||
/// path: a forced-scan call with no tips must still enumerate the repo, never
|
||||
/// silently resolve to an empty delta (which would pin nothing and lose the
|
||||
/// drained pushes' work — the F5 bug shape).
|
||||
pub async fn resolve_candidates_for_push(
|
||||
scan_sem: std::sync::Arc<tokio::sync::Semaphore>,
|
||||
repo_path: PathBuf,
|
||||
new_tips: Vec<String>,
|
||||
old_tips: Vec<String>,
|
||||
git_bin: String,
|
||||
timeout: Duration,
|
||||
force_full_scan: bool,
|
||||
) -> PinCandidateSet {
|
||||
let force = force_full_scan || self::force_full_scan();
|
||||
// No-git fast path: a deletion-only push resolves to an empty delta without
|
||||
// spawning any git child, so it must not park on the scan pool. A forced
|
||||
// full scan (caller flag or kill-switch) disqualifies it — the scan spawns git.
|
||||
if new_tips.is_empty() && !force {
|
||||
tracing::info!(delta = 0usize, repo = %repo_path.display(), "pin candidate set from push delta");
|
||||
return PinCandidateSet {
|
||||
candidates: Vec::new(),
|
||||
full_scan: false,
|
||||
};
|
||||
}
|
||||
// Scan admission (#174 F4): DEFER, never shed — a dropped scan would
|
||||
// silently under-pin this push. The permit moves into the blocking closure
|
||||
// so a started scan always completes holding it. Residuals at
|
||||
// `acquire_scan_permit`.
|
||||
let permit =
|
||||
crate::state::acquire_scan_permit(scan_sem, &repo_path, "pin-candidate scan").await;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
// ONE shared deadline for the whole scan, per jatmn ("the same deadline").
|
||||
let deadline = Instant::now() + timeout;
|
||||
let new_refs: Vec<&str> = new_tips.iter().map(String::as_str).collect();
|
||||
let old_refs: Vec<&str> = old_tips.iter().map(String::as_str).collect();
|
||||
// `force` already folds in the env kill-switch, so the forced arm skips the
|
||||
// delta machinery outright; the unforced arm goes through the normal
|
||||
// resolver (whose own env read is false here by construction).
|
||||
let resolved = if force {
|
||||
tracing::debug!("full scan forced (coalesced-drain marker or kill-switch)");
|
||||
PinCandidates::FullScanRequired
|
||||
} else {
|
||||
resolve_push_delta(&repo_path, &new_refs, &old_refs, &git_bin, deadline)
|
||||
};
|
||||
match resolved {
|
||||
match resolve_push_delta(&repo_path, &new_refs, &old_refs, &git_bin, deadline) {
|
||||
PinCandidates::Delta(objs) => {
|
||||
tracing::info!(delta = objs.len(), repo = %repo_path.display(), "pin candidate set from push delta");
|
||||
PinCandidateSet { candidates: objs, full_scan: false }
|
||||
@@ -589,13 +547,11 @@ mod tests {
|
||||
let c1 = repo.commit_file("a.txt", "one\n");
|
||||
let c2 = repo.commit_file("b.txt", "two\n");
|
||||
let set = resolve_candidates_for_push(
|
||||
std::sync::Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
repo.path.clone(),
|
||||
vec![c2.clone()],
|
||||
vec![c1.clone()],
|
||||
"git".to_string(),
|
||||
std::time::Duration::from_secs(600),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(!set.full_scan, "happy-path delta is not a full scan");
|
||||
@@ -620,13 +576,11 @@ mod tests {
|
||||
.into_iter()
|
||||
.collect();
|
||||
let set = resolve_candidates_for_push(
|
||||
std::sync::Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
repo.path.clone(),
|
||||
vec![blob],
|
||||
vec![],
|
||||
"git".to_string(),
|
||||
std::time::Duration::from_secs(600),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(set.full_scan, "non-commit tip is signalled as a full scan");
|
||||
@@ -634,180 +588,6 @@ mod tests {
|
||||
assert_eq!(got, all, "non-commit tip falls back to full repo scan");
|
||||
}
|
||||
|
||||
/// F4 defer proof 2: `resolve_candidates_for_push`'s git stages (the per-tip
|
||||
/// cat-file type probe + delta rev-list, and the full-scan fallback) run under a
|
||||
/// scan-admission permit: with a zero-permit pool the call parks and spawns no
|
||||
/// git; once a permit is available the SAME call runs (defer, not shed). On
|
||||
/// ungated code the git runs regardless of the pool (RED).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn resolve_candidates_defers_when_scan_pool_exhausted() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let marker = dir.path().join("git.ran");
|
||||
// Fake git records ANY invocation; cat-file reports a commit tip so the
|
||||
// delta stage proceeds, rev-list yields an empty delta.
|
||||
let fake = dir.path().join("fakegit");
|
||||
std::fs::write(
|
||||
&fake,
|
||||
format!(
|
||||
"#!/bin/sh\necho ran >> \"{}\"\ncase \"$1\" in\n cat-file) echo commit ;;\n *) : ;;\nesac\nexit 0\n",
|
||||
marker.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let mut perm = std::fs::metadata(&fake).unwrap().permissions();
|
||||
perm.set_mode(0o755);
|
||||
std::fs::set_permissions(&fake, perm).unwrap();
|
||||
let git_bin = fake.to_str().unwrap().to_string();
|
||||
let tip = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string();
|
||||
|
||||
let sem: Arc<Semaphore> = Arc::new(Semaphore::new(0));
|
||||
let blocked = tokio::time::timeout(
|
||||
Duration::from_millis(500),
|
||||
resolve_candidates_for_push(
|
||||
sem.clone(),
|
||||
dir.path().to_path_buf(),
|
||||
vec![tip.clone()],
|
||||
vec![],
|
||||
git_bin.clone(),
|
||||
Duration::from_secs(5),
|
||||
false,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
blocked.is_err(),
|
||||
"the pin-candidate scan must defer (park on admission) when the pool is exhausted"
|
||||
);
|
||||
assert!(
|
||||
!marker.exists(),
|
||||
"the scan's git must not spawn while its admission permit is unavailable (F4)"
|
||||
);
|
||||
|
||||
// Release admission: the SAME scan now runs (defer, not shed).
|
||||
sem.add_permits(1);
|
||||
let set = resolve_candidates_for_push(
|
||||
sem,
|
||||
dir.path().to_path_buf(),
|
||||
vec![tip],
|
||||
vec![],
|
||||
git_bin,
|
||||
Duration::from_secs(5),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
marker.exists(),
|
||||
"once admission is available the deferred scan runs its git"
|
||||
);
|
||||
assert!(!set.full_scan, "commit tip + empty rev-list is a delta");
|
||||
assert!(set.candidates.is_empty());
|
||||
}
|
||||
|
||||
/// F4 fast-path negative arm: a deletion-only push (no new tips, kill-switch
|
||||
/// off) computes its empty delta without spawning ANY git child, so it must
|
||||
/// complete without acquiring from the scan pool — even at zero permits. The
|
||||
/// per-tip cat-file probe means every push with a non-empty new tip DOES spawn
|
||||
/// git, so this is the only genuinely git-free stage.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn resolve_candidates_no_git_fast_path_skips_admission() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let marker = dir.path().join("git.ran");
|
||||
let fake = dir.path().join("fakegit");
|
||||
std::fs::write(
|
||||
&fake,
|
||||
format!("#!/bin/sh\necho ran >> \"{}\"\nexit 0\n", marker.display()),
|
||||
)
|
||||
.unwrap();
|
||||
let mut perm = std::fs::metadata(&fake).unwrap().permissions();
|
||||
perm.set_mode(0o755);
|
||||
std::fs::set_permissions(&fake, perm).unwrap();
|
||||
|
||||
let set = tokio::time::timeout(
|
||||
Duration::from_millis(500),
|
||||
resolve_candidates_for_push(
|
||||
Arc::new(Semaphore::new(0)),
|
||||
dir.path().to_path_buf(),
|
||||
vec![],
|
||||
vec!["deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string()],
|
||||
fake.to_str().unwrap().to_string(),
|
||||
Duration::from_secs(5),
|
||||
false,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("the no-new-tips fast path must not park on the scan pool");
|
||||
assert_eq!(
|
||||
set,
|
||||
PinCandidateSet {
|
||||
candidates: Vec::new(),
|
||||
full_scan: false
|
||||
}
|
||||
);
|
||||
assert!(!marker.exists(), "the fast path must spawn no git at all");
|
||||
}
|
||||
|
||||
/// #174 F5: the coalesced-drain FullScan marker is signalled via the explicit
|
||||
/// `force_full_scan` flag, and a flagged call with NO tips must still enumerate
|
||||
/// the whole repo (full_scan=true, non-empty candidates). The RED arm of the
|
||||
/// encoding question: if the marker were encoded as a plain empty-tips call
|
||||
/// (flag off — the fast path), the drain would resolve to an empty delta and
|
||||
/// pin nothing, silently losing the coalesced pushes' work.
|
||||
#[tokio::test]
|
||||
async fn forced_full_scan_with_no_tips_enumerates_the_repo() {
|
||||
let repo = Repo::new();
|
||||
repo.commit_file("a.txt", "one\n");
|
||||
let all: HashSet<String> = list_all_objects(&repo.path, "git", td())
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert!(!all.is_empty(), "fixture repo has objects");
|
||||
|
||||
let set = resolve_candidates_for_push(
|
||||
std::sync::Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
repo.path.clone(),
|
||||
vec![],
|
||||
vec![],
|
||||
"git".to_string(),
|
||||
std::time::Duration::from_secs(600),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(set.full_scan, "the forced call is signalled as a full scan");
|
||||
let got: HashSet<String> = set.candidates.into_iter().collect();
|
||||
assert_eq!(
|
||||
got, all,
|
||||
"a forced full scan with no tips enumerates the repo — never an empty delta"
|
||||
);
|
||||
|
||||
// The discriminator: the SAME empty-tips call without the flag is the
|
||||
// deletion-only fast path (empty delta, pin nothing). The two must differ,
|
||||
// or the marker encoding has collapsed into the silent-loss shape.
|
||||
let unforced = resolve_candidates_for_push(
|
||||
std::sync::Arc::new(tokio::sync::Semaphore::new(64)),
|
||||
repo.path.clone(),
|
||||
vec![],
|
||||
vec![],
|
||||
"git".to_string(),
|
||||
std::time::Duration::from_secs(600),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(!unforced.full_scan);
|
||||
assert!(unforced.candidates.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_oid_tip_forces_full_scan() {
|
||||
let repo = Repo::new();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,9 +24,7 @@ use tokio::process::Command;
|
||||
///
|
||||
/// The `be0cdd6` path-scoped upload-pack walk already applies this discipline by
|
||||
/// moving its permits into the `spawn_blocking`; this generalizes it to the plain
|
||||
/// (non-path-scoped) `info_refs` / `run_git_service` spawn paths and, via the
|
||||
/// hand-back contract on `drive_git_child`, across both stages of the filtered
|
||||
/// (`upload_pack_excluding`) pack build (F1).
|
||||
/// (non-path-scoped) `info_refs` / `run_git_service` spawn paths.
|
||||
pub struct AdmissionGuard {
|
||||
// Boxed so the concrete permit types stay private to the caller (repos.rs) — the
|
||||
// guard only needs to hold them and drop them, never inspect them. `Send +
|
||||
@@ -35,29 +33,16 @@ pub struct AdmissionGuard {
|
||||
_caller: Option<Box<dyn Send + 'static>>,
|
||||
// Any further work-scoped hold that must outlive the process group; see `with_hold`.
|
||||
_hold: Option<Box<dyn Send + 'static>>,
|
||||
// Per-repo write lease (#174 U2/F3), `Some` ONLY on the receive-pack write path
|
||||
// (via [`with_lease`](Self::with_lease)); `None` on every read path and every
|
||||
// non-receive-pack write path. It rides this guard into `KillGroupOnDrop`'s detached
|
||||
// reaper, so on a client disconnect the lease frees only after the disconnected
|
||||
// push's git group is reaped — serializing a second same-node push against the
|
||||
// still-writing group. A `RepoWriteLease` clone is `Send + 'static` and holds no pg
|
||||
// connection, so it travels with the reaper cleanly. A stray `Some` on a READ path
|
||||
// would wrongly serialize upload-pack against pushes, hence the None-everywhere-else
|
||||
// discipline.
|
||||
_lease: Option<crate::state::RepoWriteLease>,
|
||||
}
|
||||
|
||||
impl AdmissionGuard {
|
||||
/// Take ownership of the global permit and an optional per-caller permit. Both are
|
||||
/// erased to `Box<dyn Send>` — the guard's only job is to hold them until it drops.
|
||||
/// No lease is attached here; the receive-pack write path adds one via
|
||||
/// [`with_lease`](Self::with_lease), so every other call site is lease-free.
|
||||
pub fn new(global: impl Send + 'static, caller: Option<impl Send + 'static>) -> Self {
|
||||
Self {
|
||||
_global: Some(Box::new(global)),
|
||||
_caller: caller.map(|c| Box::new(c) as Box<dyn Send + 'static>),
|
||||
_hold: None,
|
||||
_lease: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +60,6 @@ impl AdmissionGuard {
|
||||
self._hold = Some(Box::new(hold));
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the per-repo write lease (#174 U2/F3). Called ONLY on the receive-pack
|
||||
/// write path, so the lease rides the disconnect reaper; read paths never call this.
|
||||
pub fn with_lease(mut self, lease: crate::state::RepoWriteLease) -> Self {
|
||||
self._lease = Some(lease);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle `GET /:owner/:repo/info/refs?service=git-upload-pack`
|
||||
@@ -110,12 +88,10 @@ pub async fn info_refs(
|
||||
.arg("--stateless-rpc")
|
||||
.arg("--advertise-refs")
|
||||
.arg(repo_path);
|
||||
// No request body: advertise-refs does not read stdin.
|
||||
let (stdout, admission) =
|
||||
// No request body — advertise-refs does not read stdin. Single stage: the returned
|
||||
// guard is dropped here (advertise-refs holds admission for its own child only).
|
||||
let (stdout, _admission) =
|
||||
drive_git_child(command, Bytes::new(), timeout, "advertise-refs", admission).await?;
|
||||
// Single-stage op: the advertisement's group is reaped by now; release admission
|
||||
// rather than holding it across the pure response framing below.
|
||||
drop(admission);
|
||||
|
||||
let content_type = format!("application/x-{service}-advertisement");
|
||||
|
||||
@@ -139,18 +115,13 @@ pub async fn info_refs(
|
||||
///
|
||||
/// Serves pack data for a clone or fetch. This is stateless — the entire
|
||||
/// negotiation happens in a single request/response.
|
||||
///
|
||||
/// Returns `(response, served_pack)` where `served_pack` is whether the
|
||||
/// git-upload-pack-result actually delivered a packfile (vs a negotiation-only
|
||||
/// ACK/NAK round). The handler counts a completed fetch from this outcome rather
|
||||
/// than from the request's `done` flag (#192 F1).
|
||||
pub async fn upload_pack(
|
||||
git_bin: &str,
|
||||
repo_path: &Path,
|
||||
request_body: Bytes,
|
||||
timeout: Duration,
|
||||
admission: Option<AdmissionGuard>,
|
||||
) -> Result<(Response, bool)> {
|
||||
) -> Result<Response> {
|
||||
let output = run_git_service(
|
||||
git_bin,
|
||||
"git-upload-pack",
|
||||
@@ -161,59 +132,11 @@ pub async fn upload_pack(
|
||||
)
|
||||
.await?;
|
||||
|
||||
let served_pack = response_served_pack(&output);
|
||||
let resp = Response::builder()
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", "application/x-git-upload-pack-result")
|
||||
.header("Cache-Control", "no-cache")
|
||||
.body(Body::from(output))?;
|
||||
Ok((resp, served_pack))
|
||||
}
|
||||
|
||||
/// True when a `git-upload-pack-result` stream actually delivered a packfile,
|
||||
/// as opposed to a negotiation-only response (ACK/NAK with no pack).
|
||||
///
|
||||
/// Lets the fetch-completion metric key off the response outcome instead of the
|
||||
/// request's `done` flag (#192 F1): a `no-done` fetch that the server answers
|
||||
/// with `ACK <oid> ready` + pack is a completion; a flush-terminated negotiation
|
||||
/// round (the server replies only ACK/NAK, or nothing) is not.
|
||||
///
|
||||
/// Handles both framings the serve paths emit:
|
||||
/// - side-band-64k: the pack rides in band-1 (`0x01`) pkt-lines; the first such
|
||||
/// chunk begins with the `PACK` magic (band-2 progress lines can precede it).
|
||||
/// - non-sideband: the raw packfile follows the ACK/NAK pkt-lines and begins with
|
||||
/// the `PACK` magic (which is not valid pkt-line hex, so parsing falls through
|
||||
/// to the raw-stream check).
|
||||
///
|
||||
/// Fails closed (returns false) on a truncated or malformed stream.
|
||||
pub fn response_served_pack(output: &[u8]) -> bool {
|
||||
let mut i = 0;
|
||||
while i + 4 <= output.len() {
|
||||
let Ok(hdr) = std::str::from_utf8(&output[i..i + 4]) else {
|
||||
// Not a pkt-line header: the raw (non-sideband) pack stream has begun.
|
||||
return output[i..].starts_with(b"PACK");
|
||||
};
|
||||
let Ok(len) = usize::from_str_radix(hdr, 16) else {
|
||||
// `PACK` (and any other non-hex 4 bytes) lands here: the raw pack
|
||||
// follows the NAK pkt-line in the non-sideband framing.
|
||||
return output[i..].starts_with(b"PACK");
|
||||
};
|
||||
// 0000/0001/0002 are flush/delim/response-end markers, no payload.
|
||||
if len < 4 {
|
||||
i += 4;
|
||||
continue;
|
||||
}
|
||||
if i + len > output.len() {
|
||||
return false; // truncated
|
||||
}
|
||||
let payload = &output[i + 4..i + len];
|
||||
// side-band-64k: band 1 carries pack data; its first chunk is the PACK magic.
|
||||
if payload.first() == Some(&0x01) && payload[1..].starts_with(b"PACK") {
|
||||
return true;
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
false
|
||||
.body(Body::from(output))?)
|
||||
}
|
||||
|
||||
/// Handle `POST /:owner/:repo/git-receive-pack`
|
||||
@@ -270,12 +193,11 @@ struct KillGroupOnDrop {
|
||||
// own SIGCHLD-driven orphan reaper.
|
||||
child: Option<tokio::process::Child>,
|
||||
pgid: Option<i32>,
|
||||
// The global + per-source admission permits for this op, if any. repos.rs moves
|
||||
// its permits in here (directly on the plain spawn paths, via the stage threading
|
||||
// on the filtered rev-list/pack-objects ones) so admission is released only when
|
||||
// the group is confirmed reaped, on every exit: complete, timeout, or
|
||||
// client-disconnect (#174 P1-a, F1). `None` when the op carries no admission
|
||||
// (e.g. the smart_http test harness).
|
||||
// The global + per-source admission permits for this op, if any. On the plain
|
||||
// (non-path-scoped) spawn paths repos.rs moves its permits in here so admission is
|
||||
// released only when the group is confirmed reaped, on every exit — complete,
|
||||
// timeout, or client-disconnect (#174 P1-a). The rev-list/pack-objects
|
||||
// visibility-walk callers hold no admission and pass `None`.
|
||||
admission: Option<AdmissionGuard>,
|
||||
}
|
||||
|
||||
@@ -288,10 +210,9 @@ impl KillGroupOnDrop {
|
||||
|
||||
/// Disarm on the success/timeout path: the body has already reaped the child (its
|
||||
/// `wait()` returned, or `reap_group_on_timeout` ran), so drop the handle and clear
|
||||
/// the pgid, leaving the guard's Drop a no-op. Returns the admission guard: the
|
||||
/// group is already reaped on both callers of this, so the success path hands it
|
||||
/// back to drive_git_child's caller (a multi-stage build carries it to the next
|
||||
/// stage) and the timeout path drops it there and then.
|
||||
/// the pgid, leaving the guard's Drop a no-op. Returns the admission guard so the
|
||||
/// caller drops it at the earliest provably-free point (the group is already reaped
|
||||
/// on both callers of this) rather than at end-of-bookkeeping.
|
||||
fn disarm(&mut self) -> Option<AdmissionGuard> {
|
||||
self.pgid = None;
|
||||
self.child = None;
|
||||
@@ -429,29 +350,27 @@ async fn run_git_service(
|
||||
.arg(service_to_command(service))
|
||||
.arg("--stateless-rpc")
|
||||
.arg(repo_path);
|
||||
let (out, admission) = drive_git_child(command, input, timeout, service, admission).await?;
|
||||
// Single-stage op: the child group is already reaped when drive_git_child
|
||||
// returns, so releasing admission here keeps the permits held exactly for the
|
||||
// process lifetime, no longer.
|
||||
drop(admission);
|
||||
// Single stage: drop the returned guard when this function returns (its permits are
|
||||
// released once the child's group is reaped, per drive_git_child).
|
||||
let (out, _admission) = drive_git_child(command, input, timeout, service, admission).await?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Drive a spawned git child under `timeout` with process-group teardown, returning
|
||||
/// its stdout together with the admission guard. Shared core for
|
||||
/// [`run_git_service`], [`info_refs`], and the filtered-pack stages: the caller
|
||||
/// passes a `Command` with its args set; this adds piped stdio and `process_group(0)`.
|
||||
/// On the deadline the whole group is torn down and reaped before returning
|
||||
/// [`GitServiceTimeout`]; on a dropped future (client disconnect) the
|
||||
/// [`KillGroupOnDrop`] guard fires. `input` is written to the child's stdin (empty
|
||||
/// for the advertise-refs path, which has no request body); `what` labels errors.
|
||||
/// its stdout AND the disarmed admission guard on success. Shared core for
|
||||
/// [`run_git_service`] and [`info_refs`]: the caller passes a `Command` with its args
|
||||
/// set; this adds piped stdio and `process_group(0)`. On the deadline the whole group
|
||||
/// is torn down and reaped before returning [`GitServiceTimeout`]; on a dropped future
|
||||
/// (client disconnect) the [`KillGroupOnDrop`] guard fires. `input` is written to the
|
||||
/// child's stdin (empty for the advertise-refs path, which has no request body); `what`
|
||||
/// labels errors.
|
||||
///
|
||||
/// Admission contract: on success the guard is handed BACK so a multi-stage caller
|
||||
/// (the filtered-pack build) can carry one admission across consecutive children
|
||||
/// instead of releasing it between stages. On every Err return (timeout, spawn
|
||||
/// failure, interaction error, non-zero exit) the guard is dropped internally, and
|
||||
/// only after the child is reaped: an Err cannot carry the guard, and by then the
|
||||
/// group is confirmed gone, so releasing admission there is correct.
|
||||
/// On success the guard is RETURNED rather than dropped internally (#174 KTD3), so a
|
||||
/// caller running two sequential git stages under one admission — `build_filtered_pack`'s
|
||||
/// rev-list then pack-objects — can hand the same guard from the first stage to the
|
||||
/// second and keep the permits held across both, releasing them only when the second
|
||||
/// stage's process group is reaped. Callers that run a single stage just let the
|
||||
/// returned guard drop.
|
||||
async fn drive_git_child(
|
||||
mut command: Command,
|
||||
input: Bytes,
|
||||
@@ -493,10 +412,10 @@ async fn drive_git_child(
|
||||
pgid,
|
||||
admission,
|
||||
};
|
||||
// On non-unix there is no process-group teardown; the `admission` parameter
|
||||
// itself stays live for the child's whole interaction (nothing moves it until
|
||||
// the match below), so the success path hands it back like the unix path and
|
||||
// the timeout path drops it after the child is waited on.
|
||||
// On non-unix there is no process-group teardown, so hold the admission guard here
|
||||
// for the child's whole interaction; it is returned to the caller below.
|
||||
#[cfg(not(unix))]
|
||||
let admission_holder = admission;
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut err = Vec::new();
|
||||
@@ -530,18 +449,25 @@ async fn drive_git_child(
|
||||
};
|
||||
|
||||
let timed = tokio::time::timeout(timeout, interact).await;
|
||||
let (write_result, status, admission) = match timed {
|
||||
// The disarmed admission guard, handed back to the caller on success so it can ride
|
||||
// a following sequential git stage (#174 KTD3) instead of releasing between stages.
|
||||
let admission_out: Option<AdmissionGuard>;
|
||||
let (write_result, status) = match timed {
|
||||
Ok(result) => {
|
||||
// The join runs all arms to completion, so the child is reaped: disarm
|
||||
// before surfacing any interaction error (a read/wait error), else the
|
||||
// guard's drop would reap an already-reaped child / signal a reused pgid.
|
||||
// Disarming hands the admission guard back; it rides to the Ok return
|
||||
// below, and every error return between here and there drops it, always
|
||||
// AFTER the reap, the earliest provably-free point.
|
||||
// The guard is returned (not dropped) so a two-stage caller keeps the
|
||||
// permits held across both stages; a single-stage caller drops it on return.
|
||||
#[cfg(unix)]
|
||||
let admission = group_guard.disarm();
|
||||
let (write_result, status) = result?;
|
||||
(write_result, status, admission)
|
||||
{
|
||||
admission_out = group_guard.disarm();
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
admission_out = admission_holder;
|
||||
}
|
||||
result?
|
||||
}
|
||||
Err(_elapsed) => {
|
||||
// Timeout: tear the whole group down and reap it before returning so a
|
||||
@@ -557,7 +483,6 @@ async fn drive_git_child(
|
||||
{
|
||||
let _ = child.start_kill();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), child.wait()).await;
|
||||
drop(admission);
|
||||
}
|
||||
return Err(GitServiceTimeout.into());
|
||||
}
|
||||
@@ -566,8 +491,7 @@ async fn drive_git_child(
|
||||
// Surface git's own failure (its stderr, which the handler may classify as a
|
||||
// 400) before any stdin-write error: when git rejects a malformed body it
|
||||
// exits non-zero and closes stdin, so the write's EPIPE would otherwise mask
|
||||
// the real cause. `admission` drops on these error returns; the child is
|
||||
// already reaped by the completed join above.
|
||||
// the real cause.
|
||||
if !status.success() {
|
||||
let stderr = String::from_utf8_lossy(&err);
|
||||
bail!("{what} failed: {stderr}");
|
||||
@@ -575,7 +499,7 @@ async fn drive_git_child(
|
||||
|
||||
write_result.context("failed to write to git stdin")?;
|
||||
|
||||
Ok((out, admission))
|
||||
Ok((out, admission_out))
|
||||
}
|
||||
|
||||
fn service_to_command(service: &str) -> &str {
|
||||
@@ -619,9 +543,10 @@ async fn rev_list_keep(
|
||||
command
|
||||
.args(["rev-list", "--objects", "--all"])
|
||||
.current_dir(repo_path);
|
||||
// The filtered-serve caller's admission rides through drive_git_child so a
|
||||
// disconnect mid-enumeration keeps the permits held until the rev-list group is
|
||||
// reaped; on success the guard comes back for the pack-objects stage (F1).
|
||||
// First of `build_filtered_pack`'s two sequential stages: it holds the caller's
|
||||
// admission for the rev-list child and hands the disarmed guard back so the same
|
||||
// permits ride the pack-objects stage (#174 KTD3, R2). The inter-stage window holds
|
||||
// no live git group, so nothing is reaped-late by carrying the guard between them.
|
||||
let (stdout, admission) =
|
||||
drive_git_child(command, Bytes::new(), timeout, "rev-list", admission).await?;
|
||||
let mut keep = Vec::new();
|
||||
@@ -645,24 +570,20 @@ async fn rev_list_keep(
|
||||
/// disconnect. An outer `tokio::time::timeout` around a `spawn_blocking` cannot
|
||||
/// cancel the blocking thread, so neither stage may live off the async side
|
||||
/// (#174, KTD5).
|
||||
///
|
||||
/// `admission` carries the filtered-serve permits across BOTH stages: stage 1 hands
|
||||
/// it back on success, stage 2 takes it, and the caller receives it after stage 2 so
|
||||
/// release happens only once the last child group is reaped. On a disconnect the
|
||||
/// guard rides the active stage's detached reaper instead of dropping with the
|
||||
/// future (F1). A stage that fails or times out (including a stage 2 whose
|
||||
/// remaining budget has saturated to zero) drops the guard inside drive_git_child,
|
||||
/// after that stage's reap.
|
||||
pub async fn build_filtered_pack(
|
||||
git_bin: &str,
|
||||
repo_path: &Path,
|
||||
withheld: &HashSet<String>,
|
||||
timeout: Duration,
|
||||
admission: Option<AdmissionGuard>,
|
||||
) -> Result<(Vec<u8>, Option<AdmissionGuard>)> {
|
||||
) -> Result<Vec<u8>> {
|
||||
// One deadline spans both git stages so a slow rev-list eats into the pack
|
||||
// budget rather than granting each stage a fresh `timeout` (2x the permit hold).
|
||||
let deadline = Instant::now() + timeout;
|
||||
// The caller's admission rides both stages: rev-list holds it, hands it back, then
|
||||
// pack-objects holds it until ITS process group is reaped on disconnect. That closes
|
||||
// the path-scoped cap bypass — permits release on group reap, not the instant the
|
||||
// request future drops (#174 R2, KTD3). The plain upload-pack path already does this.
|
||||
let (keep, admission) = rev_list_keep(
|
||||
git_bin,
|
||||
repo_path,
|
||||
@@ -677,7 +598,7 @@ pub async fn build_filtered_pack(
|
||||
command
|
||||
.args(["pack-objects", "--stdout"])
|
||||
.current_dir(repo_path);
|
||||
let (out, admission) = drive_git_child(
|
||||
let (out, _admission) = drive_git_child(
|
||||
command,
|
||||
Bytes::from(data),
|
||||
deadline.saturating_duration_since(Instant::now()),
|
||||
@@ -685,7 +606,7 @@ pub async fn build_filtered_pack(
|
||||
admission,
|
||||
)
|
||||
.await?;
|
||||
Ok((out, admission))
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Serve a clone/fetch with the withheld blobs removed from the response pack.
|
||||
@@ -712,24 +633,19 @@ pub async fn build_filtered_pack(
|
||||
/// instead of a thin delta. Honoring negotiation for smaller fetch packs is an
|
||||
/// optimization follow-up, not a correctness requirement.
|
||||
pub async fn upload_pack_excluding(
|
||||
git_bin: &str,
|
||||
repo_path: &Path,
|
||||
request_body: Bytes,
|
||||
withheld: &HashSet<String>,
|
||||
timeout: Duration,
|
||||
admission: Option<AdmissionGuard>,
|
||||
) -> Result<(Response, bool)> {
|
||||
// Both filtered-pack stages run async under drive_git_child (duration-bounded,
|
||||
// process group reaped on disconnect, #174), and `admission` threads through
|
||||
// them so the caller's permits release only after the active stage's group is
|
||||
// reaped, never the instant a disconnect drops this future (F1). `git_bin` is
|
||||
// injectable for the same fake-git testing reason as `run_git_service`
|
||||
// (production passes the configured git binary).
|
||||
let (pack, admission) =
|
||||
build_filtered_pack(git_bin, repo_path, withheld, timeout, admission).await?;
|
||||
// Both git stages are done and their groups reaped; release admission before the
|
||||
// pure in-memory response framing below.
|
||||
drop(admission);
|
||||
) -> Result<Response> {
|
||||
// Both git stages are duration-bounded and their process groups are reaped on
|
||||
// disconnect via drive_git_child (#174), so a hung build no longer pins its
|
||||
// concurrency slot and a client disconnect no longer orphans the git child. The
|
||||
// caller's read + per-caller admission is threaded through both stages so the
|
||||
// permits are held until the pack-objects group is reaped, matching the plain path
|
||||
// (#174 R2).
|
||||
let pack = build_filtered_pack("git", repo_path, withheld, timeout, admission).await?;
|
||||
|
||||
// The client lists its capabilities on the first `want` line. Honor
|
||||
// side-band-64k when offered (every modern smart-HTTP client offers it);
|
||||
@@ -753,19 +669,11 @@ pub async fn upload_pack_excluding(
|
||||
body.extend_from_slice(&pack);
|
||||
}
|
||||
|
||||
// The filtered path always builds and serves a self-contained pack, so this
|
||||
// is always true; computing it (rather than hardcoding) keeps the signal
|
||||
// honest if the framing ever changes. The handler does NOT count off this
|
||||
// flag alone — a filtered response can't distinguish an accepted fresh clone
|
||||
// from a rejected mid-negotiation one, so the count is gated on `done` too
|
||||
// (#192 F2, see `should_count_fetch`).
|
||||
let served_pack = response_served_pack(&body);
|
||||
let resp = Response::builder()
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", "application/x-git-upload-pack-result")
|
||||
.header("Cache-Control", "no-cache")
|
||||
.body(Body::from(body))?;
|
||||
Ok((resp, served_pack))
|
||||
.body(Body::from(body))?)
|
||||
}
|
||||
|
||||
/// True if `needle` occurs anywhere in `haystack`. Small substring scan used to
|
||||
@@ -779,87 +687,6 @@ fn memmem(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
.any(|window| window == needle)
|
||||
}
|
||||
|
||||
/// Build real `git upload-pack --stateless-rpc` result fixtures for tests:
|
||||
/// `(pack_bearing, negotiation_only)`. The first is a completing clone request
|
||||
/// (`want` + flush + `done`) which git answers with `NAK` + a packfile; the
|
||||
/// second is a negotiation round (`want` + flush + an unknown `have` + flush, no
|
||||
/// `done`) which git answers with `NAK` and no pack. Used to exercise
|
||||
/// [`response_served_pack`] and the completion-count rule against real protocol
|
||||
/// output rather than a hand-rolled approximation.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn upload_pack_result_fixtures() -> (Vec<u8>, Vec<u8>) {
|
||||
use std::io::Write as _;
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let work = dir.path().join("work");
|
||||
let bare = dir.path().join("bare.git");
|
||||
std::fs::create_dir_all(work.join("sub")).unwrap();
|
||||
std::fs::write(work.join("a.txt"), b"hello\n").unwrap();
|
||||
std::fs::write(work.join("sub/b.txt"), b"world\n").unwrap();
|
||||
let g = |args: &[&str], d: &Path| {
|
||||
assert!(std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(d)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success());
|
||||
};
|
||||
g(&["init", "-q"], &work);
|
||||
g(&["config", "user.email", "t@t"], &work);
|
||||
g(&["config", "user.name", "t"], &work);
|
||||
g(&["add", "."], &work);
|
||||
g(&["commit", "-qm", "init"], &work);
|
||||
g(
|
||||
&[
|
||||
"clone",
|
||||
"-q",
|
||||
"--bare",
|
||||
work.to_str().unwrap(),
|
||||
bare.to_str().unwrap(),
|
||||
],
|
||||
dir.path(),
|
||||
);
|
||||
let sha = {
|
||||
let o = std::process::Command::new("git")
|
||||
.args(["rev-parse", "HEAD"])
|
||||
.current_dir(&work)
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&o.stdout).trim().to_string()
|
||||
};
|
||||
let caps = "multi_ack_detailed side-band-64k thin-pack ofs-delta agent=git/test";
|
||||
let run = |req: &[u8]| -> Vec<u8> {
|
||||
let mut child = std::process::Command::new("git")
|
||||
.args(["upload-pack", "--stateless-rpc"])
|
||||
.arg(&bare)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.stdin.take().unwrap().write_all(req).unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"upload-pack failed: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
out.stdout
|
||||
};
|
||||
// Completing: want + flush + done -> NAK + pack.
|
||||
let mut completing = pkt_line(&format!("want {sha} {caps}\n"));
|
||||
completing.extend_from_slice(b"0000");
|
||||
completing.extend_from_slice(&pkt_line("done\n"));
|
||||
let pack_bearing = run(&completing);
|
||||
// Negotiation-only: want + flush + an unknown have + flush, no done -> NAK,
|
||||
// no pack.
|
||||
let mut nego = pkt_line(&format!("want {sha} {caps}\n"));
|
||||
nego.extend_from_slice(b"0000");
|
||||
nego.extend_from_slice(&pkt_line("have 0000000000000000000000000000000000000000\n"));
|
||||
nego.extend_from_slice(b"0000");
|
||||
let negotiation_only = run(&nego);
|
||||
(pack_bearing, negotiation_only)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -937,10 +764,9 @@ mod tests {
|
||||
let mut withheld = std::collections::HashSet::new();
|
||||
withheld.insert(secret.clone());
|
||||
|
||||
let (pack, _admission) =
|
||||
build_filtered_pack("git", &bare, &withheld, Duration::from_secs(30), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let pack = build_filtered_pack("git", &bare, &withheld, Duration::from_secs(30), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let ids = pack_object_ids(&pack);
|
||||
assert!(ids.contains(&public), "public blob must be in the pack");
|
||||
assert!(
|
||||
@@ -1002,14 +828,9 @@ mod tests {
|
||||
b"0098want 0000000000000000000000000000000000000000 \
|
||||
side-band-64k ofs-delta agent=git/2\n00000009done\n",
|
||||
);
|
||||
let (resp, served_pack) =
|
||||
upload_pack_excluding("git", &bare, req, &withheld, Duration::from_secs(30), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
served_pack,
|
||||
"the filtered serve path always delivers a pack"
|
||||
);
|
||||
let resp = upload_pack_excluding(&bare, req, &withheld, Duration::from_secs(30), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
||||
let ids = pack_object_ids(&extract_pack(&body));
|
||||
assert!(
|
||||
@@ -1068,17 +889,9 @@ mod tests {
|
||||
axum::extract::State(st): axum::extract::State<std::sync::Arc<FilterState>>,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
upload_pack_excluding(
|
||||
"git",
|
||||
&st.repo,
|
||||
body,
|
||||
&st.withheld,
|
||||
Duration::from_secs(30),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.0
|
||||
upload_pack_excluding(&st.repo, body, &st.withheld, Duration::from_secs(30), None)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Spawn the server for `bare`, withholding `withheld`. Returns the clone URL
|
||||
@@ -1605,12 +1418,7 @@ mod tests {
|
||||
"build_filtered_pack must return within the watchdog — the git stage \
|
||||
must be timeout-bounded, not an uncancellable spawn_blocking",
|
||||
);
|
||||
// `match` rather than `expect_err`: the Ok arm carries an
|
||||
// AdmissionGuard, which has no Debug impl for expect_err to print.
|
||||
let err = match result {
|
||||
Ok(_) => panic!("a hung git stage must return an error, not hang"),
|
||||
Err(e) => e,
|
||||
};
|
||||
let err = result.expect_err("a hung git stage must return an error, not hang");
|
||||
if is_transient_exec_race(&err) {
|
||||
// Fresh-fake-git ETXTBSY: back off (growing) so a bursty fork-pressure
|
||||
// spike subsides before retrying, per fake_git_run_with_pids.
|
||||
@@ -2036,296 +1844,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// ── F1: filtered-serve admission threaded through both pack stages ──────
|
||||
//
|
||||
// The handler-level disconnect regression lives in api/repos.rs
|
||||
// (upload_pack_filtered_permit_held_through_group_reap_after_disconnect); these
|
||||
// exercise the guard contract at the smart_http seam: held through a
|
||||
// mid-rev-list disconnect, handed back on success, and recovered (post-reap)
|
||||
// on every error return.
|
||||
|
||||
/// F1: a client disconnect mid-REV-LIST (stage 1 of the filtered build) must
|
||||
/// keep the threaded admission held until the rev-list group is reaped, and
|
||||
/// stage 2 (pack-objects) must never spawn, since the dropped future cannot
|
||||
/// advance to it.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn build_filtered_pack_holds_admission_through_rev_list_reap_on_disconnect() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let descfile = tmp.path().join("desc.pid");
|
||||
let packfile = tmp.path().join("pack.ran");
|
||||
// rev-list: SIGTERM-trapping descendant records its pid and loops (bounded
|
||||
// so a broken fix leaks no permanent orphan); the leader waits, keeping the
|
||||
// interaction pending. pack-objects: records that it ran (it must never run).
|
||||
let body = format!(
|
||||
"#!/bin/sh\n\
|
||||
case \"$1\" in\n\
|
||||
rev-list)\n\
|
||||
sh -c 'trap \"\" TERM; echo $$ > \"{desc}\"; i=0; while [ $i -lt 20 ]; do sleep 1; i=$((i+1)); done' &\n\
|
||||
wait ;;\n\
|
||||
pack-objects) : > \"{pack}\" ;;\n\
|
||||
*) : ;;\n\
|
||||
esac\n\
|
||||
exit 0\n",
|
||||
desc = descfile.display(),
|
||||
pack = packfile.display()
|
||||
);
|
||||
let git_bin = write_fake_git(tmp.path(), &body);
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
|
||||
let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>);
|
||||
let withheld = HashSet::new();
|
||||
|
||||
let mut fut = Box::pin(build_filtered_pack(
|
||||
git_bin.to_str().unwrap(),
|
||||
tmp.path(),
|
||||
&withheld,
|
||||
Duration::from_secs(60),
|
||||
Some(guard),
|
||||
));
|
||||
// Drive until the rev-list descendant records its pid.
|
||||
let mut desc: Option<i32> = None;
|
||||
for _ in 0..500 {
|
||||
let _ = tokio::time::timeout(Duration::from_millis(10), &mut fut).await;
|
||||
if let Some(p) = std::fs::read_to_string(&descfile)
|
||||
.ok()
|
||||
.and_then(|s| s.trim().parse::<i32>().ok())
|
||||
{
|
||||
desc = Some(p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let desc = desc.expect("the fake rev-list must have spawned its descendant");
|
||||
let _cleanup = ReapOnPanic(vec![desc]);
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
0,
|
||||
"admission held while rev-list runs"
|
||||
);
|
||||
|
||||
// Client disconnect mid-enumeration.
|
||||
drop(fut);
|
||||
|
||||
// Load-bearing: the permit must stay held while the SIGTERM-ignoring group
|
||||
// member is still alive (check before the reaper's ~2s SIGKILL escalation).
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(
|
||||
alive(desc),
|
||||
"the SIGTERM-ignoring descendant must still be alive during the hold window"
|
||||
);
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
0,
|
||||
"on disconnect mid-rev-list the admission must be held until the group is \
|
||||
reaped, not released the instant the future drops (F1)"
|
||||
);
|
||||
|
||||
let mut freed = false;
|
||||
for _ in 0..400 {
|
||||
if sem.available_permits() == 1 {
|
||||
freed = true;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(
|
||||
freed,
|
||||
"the reaper must release admission once the rev-list group is gone"
|
||||
);
|
||||
assert!(
|
||||
!packfile.exists(),
|
||||
"pack-objects must never spawn after a disconnect mid-rev-list"
|
||||
);
|
||||
}
|
||||
|
||||
/// F1 success path: a filtered serve that completes hands the guard back
|
||||
/// through both stages and releases admission when the serve returns. No leak,
|
||||
/// no double-release.
|
||||
#[tokio::test]
|
||||
async fn upload_pack_excluding_releases_admission_after_success() {
|
||||
let td = TempDir::new().unwrap();
|
||||
let (_work, bare, secret_oid, _public_oid) = fixture_with_secret(&td);
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
|
||||
let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>);
|
||||
let withheld = HashSet::from([secret_oid]);
|
||||
let (resp, _served_pack) = upload_pack_excluding(
|
||||
"git",
|
||||
&bare,
|
||||
Bytes::from_static(b"0000"),
|
||||
&withheld,
|
||||
Duration::from_secs(30),
|
||||
Some(guard),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
1,
|
||||
"admission must be released once the filtered serve returns"
|
||||
);
|
||||
}
|
||||
|
||||
/// F1 error path: a rev-list that exits non-zero fails the build AND recovers
|
||||
/// the threaded admission: drive_git_child drops the guard only after the
|
||||
/// completed join has reaped the child, and the error return must not leak it.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn build_filtered_pack_releases_admission_after_rev_list_failure() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let body =
|
||||
"#!/bin/sh\ncase \"$1\" in\n rev-list) echo boom >&2; exit 2 ;;\n *) : ;;\nesac\nexit 0\n";
|
||||
let git_bin = write_fake_git(tmp.path(), body);
|
||||
let withheld = HashSet::new();
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
|
||||
|
||||
for i in 0..FAKE_GIT_RETRY_ATTEMPTS {
|
||||
let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>);
|
||||
let result = build_filtered_pack(
|
||||
git_bin.to_str().unwrap(),
|
||||
tmp.path(),
|
||||
&withheld,
|
||||
Duration::from_secs(30),
|
||||
Some(guard),
|
||||
)
|
||||
.await;
|
||||
let err = match result {
|
||||
Ok(_) => panic!("a non-zero rev-list exit must fail the build"),
|
||||
Err(e) => e,
|
||||
};
|
||||
// Load-bearing on EVERY attempt: even a transient spawn-failure return
|
||||
// must recover the permit (the guard drops before the Err surfaces).
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
1,
|
||||
"the admission permit must be recovered on the error return, not leaked"
|
||||
);
|
||||
if is_transient_exec_race(&err) {
|
||||
tokio::time::sleep(Duration::from_millis(FAKE_GIT_BACKOFF_STEP_MS * (i + 1))).await;
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
err.to_string().contains("rev-list failed"),
|
||||
"the failure must surface rev-list's own error, got: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
panic!(
|
||||
"fake git kept hitting ETXTBSY after {FAKE_GIT_RETRY_ATTEMPTS} attempts \
|
||||
(persistent exec failure, not a transient parallel-runner miss)"
|
||||
);
|
||||
}
|
||||
|
||||
/// F1: a pack-objects stage that times out (stage 2 of the filtered build,
|
||||
/// guard threaded through) recovers the admission after the reap: the timeout
|
||||
/// Err cannot carry the guard, so drive_git_child must drop it post-reap.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn build_filtered_pack_recovers_admission_after_pack_objects_timeout() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
// rev-list returns one oid fast (guard handed back); pack-objects hangs.
|
||||
let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) echo deadbeefdeadbeefdeadbeefdeadbeefdeadbeef ;;\n pack-objects) sleep 300 ;;\n *) exit 1 ;;\nesac\n";
|
||||
let git_bin = write_fake_git(tmp.path(), body);
|
||||
let withheld = HashSet::new();
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
|
||||
|
||||
for i in 0..FAKE_GIT_RETRY_ATTEMPTS {
|
||||
let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>);
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
build_filtered_pack(
|
||||
git_bin.to_str().unwrap(),
|
||||
tmp.path(),
|
||||
&withheld,
|
||||
Duration::from_millis(200),
|
||||
Some(guard),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect(
|
||||
"build_filtered_pack must return within the watchdog; the git stage \
|
||||
must be timeout-bounded",
|
||||
);
|
||||
let err = match result {
|
||||
Ok(_) => panic!("a hung pack-objects must fail the build"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
1,
|
||||
"admission must be recovered after the stage-2 timeout reap, not leaked"
|
||||
);
|
||||
if is_transient_exec_race(&err) {
|
||||
tokio::time::sleep(Duration::from_millis(FAKE_GIT_BACKOFF_STEP_MS * (i + 1))).await;
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
err.downcast_ref::<GitServiceTimeout>().is_some(),
|
||||
"a hung pack-objects must abort with GitServiceTimeout, got: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
panic!(
|
||||
"fake git kept hitting ETXTBSY after {FAKE_GIT_RETRY_ATTEMPTS} attempts \
|
||||
(persistent exec failure, not a transient parallel-runner miss)"
|
||||
);
|
||||
}
|
||||
|
||||
/// F1 zero-budget contract: build_filtered_pack hands pack-objects
|
||||
/// `deadline.saturating_duration_since(now)`, which saturates to ZERO once
|
||||
/// rev-list has consumed the whole budget. A zero-budget stage must still route
|
||||
/// the guard through the timeout's reap-then-drop rather than leak it: the
|
||||
/// child spawns, the deadline fires immediately, the group is reaped, and only
|
||||
/// then does the guard drop.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn drive_git_child_zero_budget_drops_admission_after_reap() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let git_bin = write_fake_git(tmp.path(), "#!/bin/sh\nsleep 300\n");
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
|
||||
|
||||
for i in 0..FAKE_GIT_RETRY_ATTEMPTS {
|
||||
let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>);
|
||||
let mut command = tokio::process::Command::new(git_bin.to_str().unwrap());
|
||||
command
|
||||
.args(["pack-objects", "--stdout"])
|
||||
.current_dir(tmp.path());
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
drive_git_child(
|
||||
command,
|
||||
Bytes::new(),
|
||||
Duration::ZERO,
|
||||
"pack-objects",
|
||||
Some(guard),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a zero-budget stage must abort via its own deadline, not hang");
|
||||
let err = match result {
|
||||
Ok(_) => panic!("a zero-budget stage must return an error"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(
|
||||
sem.available_permits(),
|
||||
1,
|
||||
"the guard must drop after the zero-budget timeout reap, not leak"
|
||||
);
|
||||
if is_transient_exec_race(&err) {
|
||||
tokio::time::sleep(Duration::from_millis(FAKE_GIT_BACKOFF_STEP_MS * (i + 1))).await;
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
err.downcast_ref::<GitServiceTimeout>().is_some(),
|
||||
"a zero-budget stage must abort with GitServiceTimeout, got: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
panic!(
|
||||
"fake git kept hitting ETXTBSY after {FAKE_GIT_RETRY_ATTEMPTS} attempts \
|
||||
(persistent exec failure, not a transient parallel-runner miss)"
|
||||
);
|
||||
}
|
||||
|
||||
// A request that runs to completion must DISARM the guard after reaping, so
|
||||
// no stray group SIGTERM fires. The fake exits non-zero (surfacing as Err)
|
||||
// but leaves a grandchild alive; the grandchild must survive. Goes RED if the
|
||||
@@ -2620,58 +2138,4 @@ mod tests {
|
||||
stdin-write EPIPE (a generic 500); got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
// ── #192 F1: response_served_pack detector (real git output) ────────────
|
||||
|
||||
// A completing request (want+flush+done) yields NAK + a real packfile;
|
||||
// response_served_pack must detect the delivered pack. A negotiation-only
|
||||
// round (want+flush+have+flush, no done) yields NAK with no pack and must
|
||||
// detect false. Fixtures are captured from real `git upload-pack
|
||||
// --stateless-rpc`, so the detector is validated against protocol output, not
|
||||
// a hand-rolled approximation.
|
||||
#[test]
|
||||
fn response_served_pack_detects_real_pack_vs_negotiation_only() {
|
||||
let (pack_bearing, negotiation_only) = upload_pack_result_fixtures();
|
||||
|
||||
// Sanity-check the fixtures are the shapes we think (a served pack carries
|
||||
// the PACK magic; a NAK-only round does not).
|
||||
assert!(
|
||||
pack_bearing.windows(4).any(|w| w == b"PACK"),
|
||||
"the completing fixture must carry a packfile"
|
||||
);
|
||||
assert!(
|
||||
!negotiation_only.windows(4).any(|w| w == b"PACK"),
|
||||
"the negotiation-only fixture must carry no packfile"
|
||||
);
|
||||
|
||||
assert!(
|
||||
response_served_pack(&pack_bearing),
|
||||
"a real NAK + pack response must be detected as a served pack"
|
||||
);
|
||||
assert!(
|
||||
!response_served_pack(&negotiation_only),
|
||||
"a real ACK/NAK-only negotiation round must be detected as no pack"
|
||||
);
|
||||
// An empty response (git produced nothing for a want+flush with no done)
|
||||
// is a negotiation round, not a completion.
|
||||
assert!(!response_served_pack(b""));
|
||||
}
|
||||
|
||||
// The non-sideband framing (raw pack after the NAK pkt-line) must also detect
|
||||
// true: the raw PACK magic is not valid pkt-line hex, so parsing falls through
|
||||
// to the raw-stream check. Built by hand to pin that branch independent of the
|
||||
// client's advertised capabilities.
|
||||
#[test]
|
||||
fn response_served_pack_detects_non_sideband_raw_pack() {
|
||||
let mut raw = pkt_line("NAK\n");
|
||||
raw.extend_from_slice(b"PACK\x00\x00\x00\x02\x00\x00\x00\x00");
|
||||
assert!(
|
||||
response_served_pack(&raw),
|
||||
"a raw (non-sideband) pack after NAK must be detected"
|
||||
);
|
||||
|
||||
// NAK with no following pack is a negotiation round.
|
||||
let nak_only = pkt_line("NAK\n");
|
||||
assert!(!response_served_pack(&nak_only));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,41 +5,12 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use aws_sdk_s3::Client as S3Client;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// The precondition an upload is fenced on.
|
||||
///
|
||||
/// Object storage is the only place a fence can hold. Dropping the future of an
|
||||
/// in-flight PUT does not cancel the request the server is already processing,
|
||||
/// so no amount of local locking stops an abandoned writer's bytes from landing
|
||||
/// after a successor has published. A conditional PUT the store itself refuses
|
||||
/// is what actually stops it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum UploadPrecondition {
|
||||
/// Publish only if the stored object is still the generation we observed.
|
||||
IfMatch(String),
|
||||
/// Publish only if nothing is stored under the key yet.
|
||||
IfAbsent,
|
||||
/// No fence. Last writer wins.
|
||||
Unconditional,
|
||||
}
|
||||
|
||||
/// Why an upload failed, split so a caller can tell "someone else already
|
||||
/// published this key" (expected, and dropping our bytes is the correct
|
||||
/// outcome) from a real storage failure.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum UploadError {
|
||||
#[error("upload precondition lost (HTTP {status})")]
|
||||
PreconditionLost { status: u16 },
|
||||
#[error(transparent)]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
/// Wrapper around the S3 client with the configured bucket.
|
||||
#[derive(Clone)]
|
||||
pub struct TigrisClient {
|
||||
@@ -60,33 +31,6 @@ impl TigrisClient {
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a client pointed at an arbitrary endpoint, for tests.
|
||||
///
|
||||
/// The production constructor reads the endpoint and credentials from the
|
||||
/// environment, which a test cannot steer without mutating process-global
|
||||
/// state. This takes both explicitly so a test can aim the client at a
|
||||
/// closed port and get a prompt transport error out of `exists()`.
|
||||
///
|
||||
/// `RetryConfig::disabled()` is load-bearing, not tidiness: the SDK's default
|
||||
/// policy retries a connection refusal with backoff, which turns each failing
|
||||
/// call into seconds of waiting.
|
||||
#[cfg(test)]
|
||||
pub fn for_testing_with_endpoint(bucket: &str, endpoint: &str) -> Self {
|
||||
use aws_sdk_s3::config::{retry::RetryConfig, Credentials, Region};
|
||||
|
||||
let config = aws_sdk_s3::config::Config::builder()
|
||||
.endpoint_url(endpoint)
|
||||
.credentials_provider(Credentials::new("test", "test", None, None, "test"))
|
||||
.region(Region::new("auto"))
|
||||
.retry_config(RetryConfig::disabled())
|
||||
.behavior_version_latest()
|
||||
.build();
|
||||
Self {
|
||||
s3: S3Client::from_conf(config),
|
||||
bucket: bucket.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// S3 key for a given repo: `repos/v1/{owner_slug}/{repo_name}.tar.zst`
|
||||
fn repo_key(owner_slug: &str, repo_name: &str) -> String {
|
||||
format!("repos/v1/{owner_slug}/{repo_name}.tar.zst")
|
||||
@@ -114,47 +58,8 @@ impl TigrisClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the ETag of a repo archive, or `None` when nothing is stored under
|
||||
/// the key. The ETag identifies the generation a later conditional upload
|
||||
/// can fence itself on.
|
||||
///
|
||||
/// Separate from `exists` rather than folded into it: `exists` has callers
|
||||
/// that only want the boolean, and widening its return type would churn
|
||||
/// every one of them for no benefit.
|
||||
pub async fn head_etag(&self, owner_slug: &str, repo_name: &str) -> Result<Option<String>> {
|
||||
let key = Self::repo_key(owner_slug, repo_name);
|
||||
match self
|
||||
.s3
|
||||
.head_object()
|
||||
.bucket(&self.bucket)
|
||||
.key(&key)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(out) => Ok(Some(
|
||||
out.e_tag()
|
||||
.context(format!("tigris HEAD {key}: hit carried no ETag"))?
|
||||
.to_string(),
|
||||
)),
|
||||
Err(e) => {
|
||||
if e.as_service_error().is_some_and(|e| e.is_not_found()) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(anyhow::anyhow!("tigris HEAD {key}: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upload a local bare repo directory to Tigris as a tar.zst archive,
|
||||
/// fenced by `precondition`.
|
||||
pub async fn upload(
|
||||
&self,
|
||||
owner_slug: &str,
|
||||
repo_name: &str,
|
||||
local_path: &Path,
|
||||
precondition: UploadPrecondition,
|
||||
) -> std::result::Result<(), UploadError> {
|
||||
/// Upload a local bare repo directory to Tigris as a tar.zst archive.
|
||||
pub async fn upload(&self, owner_slug: &str, repo_name: &str, local_path: &Path) -> Result<()> {
|
||||
let key = Self::repo_key(owner_slug, repo_name);
|
||||
debug!(key = %key, path = %local_path.display(), "uploading repo to tigris");
|
||||
|
||||
@@ -169,57 +74,15 @@ impl TigrisClient {
|
||||
|
||||
let body = aws_sdk_s3::primitives::ByteStream::from(archive_bytes);
|
||||
|
||||
let mut req = self
|
||||
.s3
|
||||
self.s3
|
||||
.put_object()
|
||||
.bucket(&self.bucket)
|
||||
.key(&key)
|
||||
.body(body)
|
||||
.content_type("application/zstd");
|
||||
match &precondition {
|
||||
UploadPrecondition::IfMatch(etag) => req = req.if_match(etag),
|
||||
UploadPrecondition::IfAbsent => req = req.if_none_match("*"),
|
||||
UploadPrecondition::Unconditional => {}
|
||||
}
|
||||
|
||||
if let Err(e) = req.send().await {
|
||||
// `PutObjectError` models no PreconditionFailed variant (its arms are
|
||||
// EncryptionTypeMismatch, InvalidRequest, InvalidWriteOffset,
|
||||
// TooManyParts, Unhandled), so a refused precondition arrives as
|
||||
// `Unhandled` and matching the enum would classify it as a generic
|
||||
// failure. The raw HTTP status off the response is the only place the
|
||||
// answer actually lives.
|
||||
//
|
||||
// Read it via `raw_response()`, not a `ServiceError`-only match: the
|
||||
// SDK exposes the raw response for BOTH `ServiceError` and
|
||||
// `ResponseError`, and a refused conditional PUT whose error body the
|
||||
// SDK cannot parse (malformed XML, premature close) surfaces as
|
||||
// `ResponseError`. Matching only `ServiceError` would classify that
|
||||
// unparsable 409/412 as a generic failure, and `RepoWriteGuard::release`
|
||||
// would log-and-succeed instead of taking the supersede retry,
|
||||
// acknowledging a write that was definitively not published.
|
||||
let status = e.raw_response().map(|raw| raw.status().as_u16());
|
||||
// 412 is always a lost precondition. 409 is one only when we asked
|
||||
// for create-only, which is how S3-compatible stores report "the key
|
||||
// already exists". Everything else, 404 included, is a real failure:
|
||||
// archive keys are never deleted (`delete` has no callers), so a 404
|
||||
// here means something permanent like a missing bucket or a
|
||||
// misrouted endpoint, and reporting that as a lost precondition
|
||||
// would tell a caller to expect a successor that does not exist.
|
||||
let lost = match status {
|
||||
Some(412) => true,
|
||||
Some(409) => matches!(precondition, UploadPrecondition::IfAbsent),
|
||||
_ => false,
|
||||
};
|
||||
if lost {
|
||||
return Err(UploadError::PreconditionLost {
|
||||
status: status.expect("a lost precondition came from a status"),
|
||||
});
|
||||
}
|
||||
return Err(UploadError::Other(
|
||||
anyhow::Error::new(e).context(format!("tigris PUT {key}")),
|
||||
));
|
||||
}
|
||||
.content_type("application/zstd")
|
||||
.send()
|
||||
.await
|
||||
.context(format!("tigris PUT {key}"))?;
|
||||
|
||||
info!(key = %key, "uploaded repo to tigris");
|
||||
Ok(())
|
||||
@@ -230,32 +93,10 @@ impl TigrisClient {
|
||||
&self,
|
||||
owner_slug: &str,
|
||||
repo_name: &str,
|
||||
local_path: &super::repo_store::ValidatedRepoDiskPath,
|
||||
swap_authority: Option<Arc<AtomicBool>>,
|
||||
local_path: &Path,
|
||||
) -> Result<()> {
|
||||
self.download_to(owner_slug, repo_name, local_path, true, swap_authority)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Download a repo archive from Tigris and extract it, returning the
|
||||
/// directory that was populated.
|
||||
///
|
||||
/// `publish` controls whether the extract is swapped into `target` in place
|
||||
/// (the live-path mutation used by writes; returns `target`) or unpacked
|
||||
/// into a fresh temp directory under `target`'s parent (a non-mutating
|
||||
/// snapshot read; returns the temp dir, which the caller owns and cleans
|
||||
/// up). The snapshot form never touches the live repo path.
|
||||
pub async fn download_to(
|
||||
&self,
|
||||
owner_slug: &str,
|
||||
repo_name: &str,
|
||||
target: &super::repo_store::ValidatedRepoDiskPath,
|
||||
publish: bool,
|
||||
swap_authority: Option<Arc<AtomicBool>>,
|
||||
) -> Result<DownloadExtract> {
|
||||
let key = Self::repo_key(owner_slug, repo_name);
|
||||
debug!(key = %key, path = %target.as_path().display(), "downloading repo from tigris");
|
||||
debug!(key = %key, path = %local_path.display(), "downloading repo from tigris");
|
||||
|
||||
let resp = self
|
||||
.s3
|
||||
@@ -273,62 +114,21 @@ impl TigrisClient {
|
||||
.context("reading tigris response body")?
|
||||
.into_bytes();
|
||||
|
||||
// The snapshot temp dir is decided HERE, in the async layer, before the
|
||||
// extraction runs. Cleanup ownership moves into the blocking task so a
|
||||
// cancelled async future cannot drop it while extraction is still running.
|
||||
let snapshot_tmp = if publish {
|
||||
None
|
||||
} else {
|
||||
let parent = target.parent().context("snapshot path has no parent")?;
|
||||
std::fs::create_dir_all(parent).context("creating parent dir")?;
|
||||
let file_name = target
|
||||
.file_name()
|
||||
.context("snapshot path has no file name")?
|
||||
.to_string_lossy();
|
||||
Some(parent.join(format!(
|
||||
".{file_name}.tmp-snapshot.{}",
|
||||
uuid::Uuid::new_v4()
|
||||
)))
|
||||
};
|
||||
|
||||
// Extract tar.zst to a directory.
|
||||
let extracted = tokio::task::spawn_blocking({
|
||||
let target = target.clone();
|
||||
let snapshot_tmp = snapshot_tmp.clone();
|
||||
move || -> Result<DownloadExtract> {
|
||||
let result = (|| -> Result<DownloadExtract> {
|
||||
if publish {
|
||||
decompress_repo(&data, &target, swap_authority.as_ref())?;
|
||||
return Ok(DownloadExtract::Published(()));
|
||||
}
|
||||
// Non-mutating snapshot: unpack into the temp dir decided above.
|
||||
// The live repo path is never touched.
|
||||
let tmp_dir = snapshot_tmp.expect("snapshot path was decided above");
|
||||
std::fs::create_dir_all(&tmp_dir).context("creating temp extract dir")?;
|
||||
let unpack = (|| -> Result<()> {
|
||||
let decoder = zstd::stream::Decoder::new(&data[..])?;
|
||||
let mut archive = tar::Archive::new(decoder);
|
||||
archive.unpack(&tmp_dir).context("unpacking tar.zst")?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = unpack {
|
||||
let _ = std::fs::remove_dir_all(&tmp_dir);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(DownloadExtract::Snapshot(TempSnapshotDir { path: tmp_dir }))
|
||||
})();
|
||||
result
|
||||
}
|
||||
// Extract tar.zst to local path
|
||||
tokio::task::spawn_blocking({
|
||||
let local_path = local_path.to_path_buf();
|
||||
move || decompress_repo(&data, &local_path)
|
||||
})
|
||||
.await
|
||||
.context("extract task panicked")?
|
||||
.context("extracting repo")?;
|
||||
|
||||
info!(key = %key, path = %target.as_path().display(), "downloaded repo from tigris");
|
||||
Ok(extracted)
|
||||
info!(key = %key, path = %local_path.display(), "downloaded repo from tigris");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a repo archive from Tigris.
|
||||
#[allow(dead_code)]
|
||||
pub async fn delete(&self, owner_slug: &str, repo_name: &str) -> Result<()> {
|
||||
let key = Self::repo_key(owner_slug, repo_name);
|
||||
self.s3
|
||||
@@ -361,7 +161,7 @@ fn compress_repo(repo_path: &Path) -> Result<Vec<u8>> {
|
||||
/// `decompress_repo`. Concurrent extractions unpack into isolated temp dirs in
|
||||
/// parallel, but the final `remove_dir_all` + `rename` must not interleave for
|
||||
/// the same `local_path`, or they race to a nondeterministic overwrite/failure.
|
||||
pub(crate) fn publish_lock(local_path: &Path) -> Arc<Mutex<()>> {
|
||||
fn publish_lock(local_path: &Path) -> Arc<Mutex<()>> {
|
||||
// KNOWN LIMITATION: this map is never evicted — one (PathBuf, Arc<Mutex>)
|
||||
// entry accrues per distinct repo path for the process lifetime. Bounded by
|
||||
// the number of repos a node hosts, so it's negligible for normal use, but
|
||||
@@ -374,35 +174,6 @@ pub(crate) fn publish_lock(local_path: &Path) -> Arc<Mutex<()>> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Owns a snapshot temp dir from extraction through handoff to [`RepoSnapshot`].
|
||||
/// Dropped when the `spawn_blocking` join result is abandoned, so cancellation
|
||||
/// before the outer future resumes still removes the directory.
|
||||
pub(crate) struct TempSnapshotDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempSnapshotDir {
|
||||
pub(crate) fn into_repo_snapshot(self) -> super::repo_store::RepoSnapshot {
|
||||
let path = self.path.clone();
|
||||
std::mem::forget(self);
|
||||
super::repo_store::RepoSnapshot::from_owned_path(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempSnapshotDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`TigrisClient::download_to`] produced.
|
||||
pub enum DownloadExtract {
|
||||
/// Published into the validated live repo path.
|
||||
Published(()),
|
||||
/// Unpacked into a throwaway temp dir that cleans up on drop until adopted.
|
||||
Snapshot(TempSnapshotDir),
|
||||
}
|
||||
|
||||
/// Decompress a tar.zst byte vector into a local directory.
|
||||
///
|
||||
/// Extraction is atomic with respect to `local_path`: the archive is unpacked
|
||||
@@ -410,16 +181,11 @@ pub enum DownloadExtract {
|
||||
/// fully succeeds. A corrupt or truncated archive therefore can never clobber a
|
||||
/// good existing copy at `local_path` — on failure we discard the temp dir and
|
||||
/// leave `local_path` exactly as it was.
|
||||
fn decompress_repo(
|
||||
data: &[u8],
|
||||
local_path: &super::repo_store::ValidatedRepoDiskPath,
|
||||
swap_authority: Option<&Arc<AtomicBool>>,
|
||||
) -> Result<()> {
|
||||
let live = local_path.as_path();
|
||||
let parent = live.parent().context("repo path has no parent")?;
|
||||
fn decompress_repo(data: &[u8], local_path: &Path) -> Result<()> {
|
||||
let parent = local_path.parent().context("repo path has no parent")?;
|
||||
std::fs::create_dir_all(parent).context("creating parent dir")?;
|
||||
|
||||
let file_name = live
|
||||
let file_name = local_path
|
||||
.file_name()
|
||||
.context("repo path has no file name")?
|
||||
.to_string_lossy();
|
||||
@@ -444,218 +210,17 @@ fn decompress_repo(
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Swap through the validated-path helper so CodeQL sees the barrier before the
|
||||
// remove/rename sink (`rust/path-injection`).
|
||||
super::repo_store::swap_extracted_into_validated_repo(local_path, &tmp_dir, swap_authority)?;
|
||||
// Swap the freshly-extracted repo into place. rename within the same parent
|
||||
// is effectively atomic, but most platforms refuse to rename onto a
|
||||
// non-empty dir, so remove the old copy first. Serialize this per repo path:
|
||||
// concurrent extractions unpack into isolated temp dirs, but their swaps
|
||||
// must not interleave or they race to a nondeterministic overwrite/failure.
|
||||
let lock = publish_lock(local_path);
|
||||
let _publish = lock.lock().expect("publish lock poisoned");
|
||||
if local_path.exists() {
|
||||
std::fs::remove_dir_all(local_path).context("removing stale repo dir")?;
|
||||
}
|
||||
std::fs::rename(&tmp_dir, local_path).context("swapping extracted repo into place")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use futures::FutureExt;
|
||||
|
||||
/// The envs the probe needs, all of them, or it does not run.
|
||||
///
|
||||
/// `AWS_ENDPOINT_URL_S3` is included on purpose: without it the SDK resolves
|
||||
/// to real AWS S3, and a probe that passed there would say nothing about
|
||||
/// Tigris.
|
||||
fn probe_env() -> Option<String> {
|
||||
if std::env::var("GITLAWB_TIGRIS_PROBE").ok().as_deref() != Some("1") {
|
||||
return None;
|
||||
}
|
||||
for name in [
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_SECRET_ACCESS_KEY",
|
||||
"AWS_ENDPOINT_URL_S3",
|
||||
] {
|
||||
if std::env::var(name).is_err() {
|
||||
eprintln!("tigris conditional-write probe: {name} is unset, skipping");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
match std::env::var("GITLAWB_TIGRIS_BUCKET") {
|
||||
Ok(b) if !b.is_empty() => Some(b),
|
||||
_ => {
|
||||
eprintln!(
|
||||
"tigris conditional-write probe: GITLAWB_TIGRIS_BUCKET is unset, skipping"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One conditional PUT, reported as the status that REFUSED it, or `None`
|
||||
/// when the store accepted the write.
|
||||
///
|
||||
/// Accepted is the interesting answer here, not an error: it means the
|
||||
/// endpoint ignored the header we fenced on.
|
||||
async fn conditional_put(
|
||||
s3: &S3Client,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
body: &'static [u8],
|
||||
if_match: Option<&str>,
|
||||
if_none_match: Option<&str>,
|
||||
) -> Result<Option<u16>, String> {
|
||||
let mut req = s3
|
||||
.put_object()
|
||||
.bucket(bucket)
|
||||
.key(key)
|
||||
.body(ByteStream::from_static(body));
|
||||
if let Some(v) = if_match {
|
||||
req = req.if_match(v);
|
||||
}
|
||||
if let Some(v) = if_none_match {
|
||||
req = req.if_none_match(v);
|
||||
}
|
||||
match req.send().await {
|
||||
Ok(_) => Ok(None),
|
||||
Err(e) => match e.raw_response() {
|
||||
// Same raw-response rule as `upload`: a refused conditional PUT
|
||||
// whose body the SDK cannot parse surfaces as `ResponseError`, and
|
||||
// the status has to come off the raw response for both variants.
|
||||
// Without it, an unparsable 409/412 would report "no HTTP
|
||||
// response" here and skip the supersede retry.
|
||||
Some(raw) => Ok(Some(raw.status().as_u16())),
|
||||
None => Err(format!("conditional PUT {key}: no HTTP response: {e}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe body, written to RETURN its failures rather than panic on
|
||||
/// them, so the caller's cleanup is reached on every arm.
|
||||
async fn conditional_write_probe(s3: &S3Client, bucket: &str, key: &str) -> Result<(), String> {
|
||||
// 1. A plain PUT under a throwaway key.
|
||||
let seeded = s3
|
||||
.put_object()
|
||||
.bucket(bucket)
|
||||
.key(key)
|
||||
.body(ByteStream::from_static(b"probe-one"))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("seeding PUT {key}: {e}"))?;
|
||||
|
||||
// 2. Its ETag, which is the generation the next arm fences against.
|
||||
let etag = seeded
|
||||
.e_tag()
|
||||
.ok_or_else(|| format!("seeding PUT {key} returned no ETag"))?
|
||||
.to_string();
|
||||
|
||||
// 3. A deliberately wrong If-Match. A store honoring it answers 412.
|
||||
let wrong = format!("\"{}\"", "0".repeat(32));
|
||||
if etag.trim_matches('"') == wrong.trim_matches('"') {
|
||||
return Err(format!(
|
||||
"the seeded ETag {etag} collides with the deliberately wrong one, \
|
||||
so this arm would prove nothing"
|
||||
));
|
||||
}
|
||||
match conditional_put(s3, bucket, key, b"probe-two", Some(&wrong), None).await? {
|
||||
Some(412) => {}
|
||||
Some(status) => {
|
||||
return Err(format!(
|
||||
"a stale If-Match must be refused with 412, the endpoint answered {status}"
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(
|
||||
"a stale If-Match was ACCEPTED: this endpoint does not honor If-Match, so \
|
||||
the release fence cannot hold here"
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. If-None-Match `*` over the object that now exists. This arm matters
|
||||
// MORE than the one above. An ignored If-Match eventually surfaces as
|
||||
// odd behavior, because a stale writer overwrites and someone notices
|
||||
// the lost tree. An ignored If-None-Match just returns 200, so a publish
|
||||
// that should have been fenced lands with no error anywhere: the silent
|
||||
// no-op the bucket-type caveat on this test describes.
|
||||
match conditional_put(s3, bucket, key, b"probe-three", None, Some("*")).await? {
|
||||
// Either status is a pass, and the asymmetry with the If-Match arm
|
||||
// above mirrors `upload`'s classifier exactly: 412 is always a lost
|
||||
// precondition, and 409 is one too when we asked for create-only.
|
||||
// AWS documents 409 for a create-only conflict racing a delete, so a
|
||||
// store answering it is enforcing the precondition and we already
|
||||
// handle it. Pinning 412 alone here would fail the probe against a
|
||||
// backend that is behaving correctly, which sends whoever runs it
|
||||
// chasing a fault that is not there.
|
||||
Some(412) | Some(409) => {}
|
||||
Some(status) => {
|
||||
return Err(format!(
|
||||
"create-only over an existing object must be refused with 412 or 409, \
|
||||
the endpoint answered {status}"
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(
|
||||
"If-None-Match * was ACCEPTED over an existing object: this endpoint does \
|
||||
not honor create-only, so a fenced publish lands silently"
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Probe the REAL Tigris endpoint for the conditional-write semantics the
|
||||
/// release fence depends on.
|
||||
///
|
||||
/// UNTIL THIS IS RUN AGAINST REAL CREDENTIALS, the fence is verified against
|
||||
/// vendor documentation and an in-process mock, not against the backend it
|
||||
/// runs on. The mock implements the semantics we believe Tigris has; it
|
||||
/// cannot tell us whether Tigris actually has them.
|
||||
///
|
||||
/// The bucket matters, not just the endpoint. Tigris documents conditional
|
||||
/// operations as supported on Single-region and Multi-region buckets only.
|
||||
/// Global and Dual-region buckets are eventually consistent, and a
|
||||
/// conditional PUT evaluated against a stale replica would make the fence a
|
||||
/// silent no-op rather than an error. So point `GITLAWB_TIGRIS_BUCKET` at a
|
||||
/// throwaway bucket of the SAME type production uses.
|
||||
///
|
||||
/// Ignored by default and additionally gated on `GITLAWB_TIGRIS_PROBE=1`,
|
||||
/// because it writes to a real bucket and costs real requests. Run with:
|
||||
/// `GITLAWB_TIGRIS_PROBE=1 cargo test -p gitlawb-node --bin gitlawb-node
|
||||
/// tigris_honors_conditional_writes -- --ignored --nocapture`
|
||||
#[tokio::test]
|
||||
#[ignore = "writes to a real Tigris bucket; needs GITLAWB_TIGRIS_PROBE=1 plus credentials"]
|
||||
async fn tigris_honors_conditional_writes() {
|
||||
let Some(bucket) = probe_env() else {
|
||||
eprintln!(
|
||||
"tigris conditional-write probe: skipped. Set GITLAWB_TIGRIS_PROBE=1, \
|
||||
GITLAWB_TIGRIS_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and \
|
||||
AWS_ENDPOINT_URL_S3 to run it."
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
|
||||
let s3 = S3Client::new(&config);
|
||||
// A fresh key per run, so a probe that somehow orphaned an object on an
|
||||
// earlier run cannot change what this one observes.
|
||||
let key = format!("probe/conditional-write-{}.bin", uuid::Uuid::new_v4());
|
||||
|
||||
// CLEANUP MUST RUN ON EVERY ARM, and a failing assertion is precisely
|
||||
// the case this probe exists to catch, so the delete cannot sit after
|
||||
// the checks. The body returns its failures rather than panicking, and
|
||||
// `catch_unwind` covers the panic an SDK call could still raise; either
|
||||
// way the delete below is reached before the verdict is re-raised.
|
||||
let outcome = std::panic::AssertUnwindSafe(conditional_write_probe(&s3, &bucket, &key))
|
||||
.catch_unwind()
|
||||
.await;
|
||||
|
||||
if let Err(e) = s3.delete_object().bucket(&bucket).key(&key).send().await {
|
||||
eprintln!("tigris conditional-write probe: cleanup of {key} failed: {e}");
|
||||
}
|
||||
|
||||
match outcome {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(msg)) => panic!("tigris conditional-write probe: {msg}"),
|
||||
Err(payload) => std::panic::resume_unwind(payload),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,13 +67,13 @@ fn child_terminated_without_reaping(pid: i32) -> bool {
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn run_bounded_git_raw(
|
||||
pub(crate) fn run_bounded_git(
|
||||
git_bin: &str,
|
||||
args: &[&str],
|
||||
repo_path: &Path,
|
||||
stdin_bytes: &[u8],
|
||||
deadline: Instant,
|
||||
) -> Result<(std::process::ExitStatus, Vec<u8>, Vec<u8>)> {
|
||||
) -> Result<Vec<u8>> {
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
@@ -191,23 +191,6 @@ pub(crate) fn run_bounded_git_raw(
|
||||
if killed && !status.success() {
|
||||
return Err(crate::git::smart_http::GitServiceTimeout.into());
|
||||
}
|
||||
Ok((status, out, err))
|
||||
}
|
||||
|
||||
/// Bounded git returning only stdout, `bail!`ing on any nonzero exit. The thin
|
||||
/// wrapper the walk callers use. Probes that must distinguish exit classes —
|
||||
/// `git cat-file` absence vs an object-store access failure — call
|
||||
/// [`run_bounded_git_raw`] and classify the status/stderr themselves.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn run_bounded_git(
|
||||
git_bin: &str,
|
||||
args: &[&str],
|
||||
repo_path: &Path,
|
||||
stdin_bytes: &[u8],
|
||||
deadline: Instant,
|
||||
) -> Result<Vec<u8>> {
|
||||
let label = args.first().copied().unwrap_or("git");
|
||||
let (status, out, err) = run_bounded_git_raw(git_bin, args, repo_path, stdin_bytes, deadline)?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("git {label} failed: {}", String::from_utf8_lossy(&err));
|
||||
}
|
||||
@@ -227,13 +210,13 @@ pub(crate) fn run_bounded_git(
|
||||
/// the Unix version's signature and result semantics so every caller compiles on all
|
||||
/// targets (#174).
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn run_bounded_git_raw(
|
||||
pub(crate) fn run_bounded_git(
|
||||
git_bin: &str,
|
||||
args: &[&str],
|
||||
repo_path: &Path,
|
||||
stdin_bytes: &[u8],
|
||||
deadline: Instant,
|
||||
) -> Result<(std::process::ExitStatus, Vec<u8>, Vec<u8>)> {
|
||||
) -> Result<Vec<u8>> {
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
|
||||
@@ -300,20 +283,6 @@ pub(crate) fn run_bounded_git_raw(
|
||||
if killed && !status.success() {
|
||||
return Err(crate::git::smart_http::GitServiceTimeout.into());
|
||||
}
|
||||
Ok((status, out, err))
|
||||
}
|
||||
|
||||
/// Non-Unix thin wrapper matching the Unix [`run_bounded_git`] semantics.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn run_bounded_git(
|
||||
git_bin: &str,
|
||||
args: &[&str],
|
||||
repo_path: &Path,
|
||||
stdin_bytes: &[u8],
|
||||
deadline: Instant,
|
||||
) -> Result<Vec<u8>> {
|
||||
let label = args.first().copied().unwrap_or("git");
|
||||
let (status, out, err) = run_bounded_git_raw(git_bin, args, repo_path, stdin_bytes, deadline)?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("git {label} failed: {}", String::from_utf8_lossy(&err));
|
||||
}
|
||||
@@ -1272,10 +1241,7 @@ mod tests {
|
||||
assert!(
|
||||
err.downcast_ref::<crate::git::smart_http::GitServiceTimeout>()
|
||||
.is_some(),
|
||||
// `{err:#}` prints the whole anyhow chain. Plain `{err}` shows only the top
|
||||
// context ("failed to spawn git for-each-ref") and drops the underlying io
|
||||
// error, which left a real beta-lane CI failure undiagnosable.
|
||||
"a hung walk must abort with GitServiceTimeout (mapped to 504), got: {err:#}"
|
||||
"a hung walk must abort with GitServiceTimeout (mapped to 504), got: {err}"
|
||||
);
|
||||
|
||||
// The recorded process-group leader must be gone: the watchdog reaps the
|
||||
@@ -1466,17 +1432,6 @@ esac\n";
|
||||
// rev-list records its (leader) pid, closes stdout+stderr so the drain EOFs
|
||||
// immediately, then sleeps without trapping TERM. `sleep 30` bounds the worst
|
||||
// case so a RED run cannot wedge the suite; the recv budget fires first.
|
||||
//
|
||||
// The deadline below is deliberately far larger than the work it bounds: the
|
||||
// watchdog tears the whole group down at the deadline, so a deadline tight
|
||||
// enough to race `/bin/sh` reaching its first statement kills the leader
|
||||
// BEFORE it records its pid, and the `leader.pid` read below then fails with
|
||||
// NotFound. That is a harness race, not a product failure, and it is exactly
|
||||
// what a loaded CI runner reproduced (test (beta), 2026-08-04). Sizing it at
|
||||
// 2s keeps the property under test intact, since the pre-fix build blocks on
|
||||
// `child.wait()` for the child's full `sleep 30` and still trips the 10s recv
|
||||
// budget below (RED), while leaving a 20x margin over the ~100ms that a
|
||||
// healthy start actually needs.
|
||||
let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) echo $$ > leader.pid; exec 1>&- 2>&-; sleep 30 ;;\n *) : ;;\nesac\nexit 0\n";
|
||||
let git_bin = write_fake_git(tmp.path(), body);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
@@ -1487,7 +1442,7 @@ esac\n";
|
||||
&["rev-list"],
|
||||
&path,
|
||||
b"",
|
||||
Instant::now() + Duration::from_secs(2),
|
||||
Instant::now() + Duration::from_millis(100),
|
||||
));
|
||||
});
|
||||
let out = rx.recv_timeout(Duration::from_secs(10)).expect(
|
||||
|
||||
@@ -14,68 +14,6 @@ use subscription::SubscriptionRoot;
|
||||
|
||||
pub type GitlawbSchema = Schema<QueryRoot, MutationRoot, SubscriptionRoot>;
|
||||
|
||||
/// 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).
|
||||
///
|
||||
/// Kept as its own constant on this PR's base (main still renders
|
||||
/// `AppError::Db` with `e.to_string()`). If/when #247's `DB_ERROR_MESSAGE`
|
||||
/// lands, fold this into that shared constant.
|
||||
pub const GRAPHQL_DB_ERROR_MESSAGE: &str = "a database error occurred";
|
||||
|
||||
fn anyhow_has_sqlx(e: &anyhow::Error) -> bool {
|
||||
e.chain().any(|c| c.downcast_ref::<sqlx::Error>().is_some())
|
||||
}
|
||||
|
||||
/// Map an `anyhow` failure from the db layer to a GraphQL error.
|
||||
///
|
||||
/// - Real DB faults (`sqlx::Error` anywhere in the chain) → opaque client
|
||||
/// message + `error!` log with the full `{e:#}` cause chain.
|
||||
/// - Application/business errors (e.g. claim race, not-in-claimed-state) →
|
||||
/// keep the actionable message; log at `warn!` so they are not mistaken for
|
||||
/// infrastructure failures (#250 review).
|
||||
pub(crate) fn graphql_db_err(e: anyhow::Error) -> async_graphql::Error {
|
||||
if anyhow_has_sqlx(&e) {
|
||||
tracing::error!(error = %format!("{e:#}"), "graphql database error");
|
||||
async_graphql::Error::new(GRAPHQL_DB_ERROR_MESSAGE)
|
||||
} else {
|
||||
tracing::warn!(error = %format!("{e:#}"), "graphql application error");
|
||||
async_graphql::Error::new(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Map an `AppError` from a shared collector (e.g. ref-update feed) to a
|
||||
/// GraphQL error.
|
||||
///
|
||||
/// Fail closed: only explicitly curated variants surface their `Display`
|
||||
/// text. Unnamed variants (including `Git`, which may embed on-disk paths)
|
||||
/// render opaque so a future addition cannot leak by default (#255 review).
|
||||
pub(crate) fn graphql_app_err(e: crate::error::AppError) -> async_graphql::Error {
|
||||
match e {
|
||||
crate::error::AppError::Db(sql) => graphql_db_err(sql.into()),
|
||||
crate::error::AppError::Internal(err) => {
|
||||
tracing::error!(error = %format!("{err:#}"), "graphql internal error");
|
||||
async_graphql::Error::new(GRAPHQL_DB_ERROR_MESSAGE)
|
||||
}
|
||||
// Curated client-safe variants — `Display` is intentional API text.
|
||||
safe @ (crate::error::AppError::RepoNotFound(_)
|
||||
| crate::error::AppError::RepoExists(_)
|
||||
| crate::error::AppError::NotFound(_)
|
||||
| crate::error::AppError::Unauthorized(_)
|
||||
| crate::error::AppError::Forbidden(_)
|
||||
| crate::error::AppError::BadRequest(_)
|
||||
| crate::error::AppError::TooManyRequests(_)
|
||||
| crate::error::AppError::Incomplete(_)) => {
|
||||
tracing::warn!(error = %safe, "graphql application error");
|
||||
async_graphql::Error::new(safe.to_string())
|
||||
}
|
||||
other => {
|
||||
tracing::error!(error = %other, "graphql unclassified AppError (opaque)");
|
||||
async_graphql::Error::new(GRAPHQL_DB_ERROR_MESSAGE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_schema(
|
||||
db: Arc<Db>,
|
||||
ref_update_tx: tokio::sync::broadcast::Sender<RefUpdateBroadcast>,
|
||||
@@ -87,105 +25,3 @@ pub fn build_schema(
|
||||
.data(task_event_tx)
|
||||
.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn graphql_db_err_opaques_sqlx_chain() {
|
||||
let leak = "error returned from database: column \"is_public\" does not exist";
|
||||
// Context layer must not hide sqlx from the chain walk (db helpers
|
||||
// wrap with `.context(...)` in several places).
|
||||
let err = graphql_db_err(
|
||||
anyhow::Error::from(sqlx::Error::Protocol(leak.into())).context("loading repos"),
|
||||
);
|
||||
assert_eq!(err.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
assert!(!err.message.contains("is_public"));
|
||||
assert!(!err.message.contains(leak));
|
||||
assert!(!err.message.contains("loading repos"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphql_db_err_keeps_business_message() {
|
||||
let msg = "task not claimable: not found or already claimed";
|
||||
let err = graphql_db_err(anyhow::anyhow!("{msg}"));
|
||||
assert_eq!(err.message, msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphql_app_err_opaques_db_and_internal() {
|
||||
let leak = "column \"is_public\" does not exist";
|
||||
let db_err = graphql_app_err(crate::error::AppError::Db(sqlx::Error::Protocol(
|
||||
leak.into(),
|
||||
)));
|
||||
assert_eq!(db_err.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
assert!(!db_err.message.contains("is_public"));
|
||||
|
||||
let internal = graphql_app_err(crate::error::AppError::Internal(anyhow::anyhow!(
|
||||
"loading repo: {leak}"
|
||||
)));
|
||||
assert_eq!(internal.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
assert!(!internal.message.contains("is_public"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphql_app_err_keeps_safe_variant_messages() {
|
||||
let err = graphql_app_err(crate::error::AppError::NotFound("widget".into()));
|
||||
assert!(
|
||||
err.message.contains("widget"),
|
||||
"safe NotFound message must reach the client: {}",
|
||||
err.message
|
||||
);
|
||||
assert_ne!(err.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
|
||||
let err = graphql_app_err(crate::error::AppError::BadRequest("bad cid".into()));
|
||||
assert!(
|
||||
err.message.contains("bad cid"),
|
||||
"safe BadRequest message must reach the client: {}",
|
||||
err.message
|
||||
);
|
||||
assert_ne!(err.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphql_app_err_opaques_unclassified_variants() {
|
||||
// `Git` may embed on-disk paths from libgit2; fail closed.
|
||||
let path = "/var/lib/gitlawb/repos/owner/secret.git";
|
||||
let err = graphql_app_err(crate::error::AppError::Git(format!(
|
||||
"failed to open '{path}'"
|
||||
)));
|
||||
assert_eq!(err.message, GRAPHQL_DB_ERROR_MESSAGE);
|
||||
assert!(!err.message.contains(path));
|
||||
assert!(!err.message.contains("failed to open"));
|
||||
}
|
||||
|
||||
/// Every `.map_err(` in the GraphQL query/mutation resolvers must route
|
||||
/// 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 [
|
||||
("query.rs", include_str!("query.rs")),
|
||||
("mutation.rs", include_str!("mutation.rs")),
|
||||
] {
|
||||
for (lineno, line) in src.lines().enumerate() {
|
||||
let code = line.split("//").next().unwrap_or(line);
|
||||
let Some(idx) = code.find(".map_err(") else {
|
||||
continue;
|
||||
};
|
||||
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("|_|")
|
||||
|| after.starts_with("|_ ");
|
||||
assert!(
|
||||
ok,
|
||||
"{file}:{}: `.map_err(` must use graphql_db_err / graphql_app_err \
|
||||
or discard (`|_|`): {line}",
|
||||
lineno + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ impl MutationRoot {
|
||||
};
|
||||
db.create_task(&task)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
Ok(AgentTaskType::from(task))
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ impl MutationRoot {
|
||||
let task = db
|
||||
.claim_task(&id, &assignee_did)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "pending".to_string(),
|
||||
@@ -108,7 +108,7 @@ impl MutationRoot {
|
||||
let existing = db
|
||||
.get_task(&id)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?
|
||||
.ok_or_else(|| async_graphql::Error::new("task not found"))?;
|
||||
if !crate::api::did_matches(caller, existing.assignee_did.as_deref().unwrap_or_default()) {
|
||||
return Err(async_graphql::Error::new(
|
||||
@@ -118,7 +118,7 @@ impl MutationRoot {
|
||||
let task = db
|
||||
.finish_task(&id, "completed", input.result.as_deref())
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
@@ -149,7 +149,7 @@ impl MutationRoot {
|
||||
let existing = db
|
||||
.get_task(&id)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?
|
||||
.ok_or_else(|| async_graphql::Error::new("task not found"))?;
|
||||
if !crate::api::did_matches(caller, existing.assignee_did.as_deref().unwrap_or_default()) {
|
||||
return Err(async_graphql::Error::new(
|
||||
@@ -160,7 +160,7 @@ impl MutationRoot {
|
||||
let task = db
|
||||
.finish_task(&id, "failed", Some(&reason))
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
let _ = tx.send(TaskEventBroadcast {
|
||||
task_id: id,
|
||||
old_status: "claimed".to_string(),
|
||||
@@ -218,9 +218,8 @@ mod tests {
|
||||
errors(&resp)
|
||||
);
|
||||
|
||||
// 3. Signed as the claimed assignee → passes the auth gate. The missing
|
||||
// task is a business error from claim_task, not a sqlx fault, so the
|
||||
// actionable message must survive (not the opaque DB string) (#250).
|
||||
// 3. Signed as the claimed assignee → passes the auth gate (any remaining
|
||||
// error is the missing task, not an auth error).
|
||||
let resp = schema
|
||||
.execute(Request::new(&q).data(AuthenticatedDid(assignee.into())))
|
||||
.await;
|
||||
@@ -229,47 +228,6 @@ mod tests {
|
||||
!errs.contains("authentication required") && !errs.contains("authenticated signer"),
|
||||
"matching signer must pass the auth gate: {errs}"
|
||||
);
|
||||
assert!(
|
||||
errs.contains("task not claimable"),
|
||||
"claim race / missing task must keep its business message: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"business error must not be rewritten as opaque DB error: {errs}"
|
||||
);
|
||||
}
|
||||
|
||||
/// #250: mutation DB faults must be opaque; create_task hits agent_tasks.
|
||||
#[sqlx::test]
|
||||
async fn create_task_db_error_message_is_opaque(pool: PgPool) {
|
||||
let state = crate::test_support::test_state(pool.clone()).await;
|
||||
sqlx::query("ALTER TABLE agent_tasks DROP COLUMN status")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let delegator = "did:key:zGQLDELEGATORAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
let q = format!(
|
||||
r#"mutation {{
|
||||
createTask(
|
||||
delegatorDid: "{delegator}",
|
||||
input: {{ kind: "build", capability: "repo:write" }}
|
||||
) {{ id }}
|
||||
}}"#
|
||||
);
|
||||
let resp = state
|
||||
.graphql_schema
|
||||
.execute(Request::new(&q).data(AuthenticatedDid(delegator.into())))
|
||||
.await;
|
||||
let errs = errors(&resp);
|
||||
assert!(
|
||||
errs.contains(crate::graphql::GRAPHQL_DB_ERROR_MESSAGE),
|
||||
"sqlx fault must be opaque: {errs}"
|
||||
);
|
||||
assert!(
|
||||
!errs.contains("column") && !errs.contains("status"),
|
||||
"schema text leaked: {errs}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Adversarial-review GATE-1 (GraphQL): completing a task requires being its
|
||||
|
||||
@@ -14,7 +14,7 @@ impl QueryRoot {
|
||||
let repos = db
|
||||
.list_all_repos_deduped()
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
|
||||
// Apply the same "/" visibility gate the REST/per-repo endpoints use so
|
||||
// this surface does not enumerate private repos (#97). The caller DID is
|
||||
@@ -27,7 +27,7 @@ impl QueryRoot {
|
||||
let rules_by_repo = db
|
||||
.list_visibility_rules_for_repos(&ids)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
|
||||
Ok(repos
|
||||
.into_iter()
|
||||
@@ -71,27 +71,11 @@ impl QueryRoot {
|
||||
let updates =
|
||||
crate::api::events::collect_visible_ref_updates(db, repo.as_deref(), limit, caller)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_app_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
|
||||
// Resolve the trusted display owner_did per row, identical to the REST
|
||||
// feed: the stored wire value is untrusted, so it is echoed only when it
|
||||
// matches the canonical owner of the local repo the slug names (#P1);
|
||||
// legacy None rows are attributed via an exact unique local match (#P3).
|
||||
// The batch resolver issues at most one query per distinct local repo
|
||||
// rather than one per event row (#P2).
|
||||
let pairs: Vec<(&str, Option<&str>)> = updates
|
||||
.iter()
|
||||
.map(|u| (u.repo.as_str(), u.owner_did.as_deref()))
|
||||
.collect();
|
||||
let owner_dids = db
|
||||
.resolve_ref_update_owner_dids(&pairs)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
|
||||
let resolved: Vec<RefUpdateType> = updates
|
||||
Ok(updates
|
||||
.into_iter()
|
||||
.zip(owner_dids)
|
||||
.map(|(u, owner_did)| RefUpdateType {
|
||||
.map(|u| RefUpdateType {
|
||||
repo: u.repo,
|
||||
ref_name: u.ref_name,
|
||||
old_sha: u.old_sha,
|
||||
@@ -99,10 +83,8 @@ impl QueryRoot {
|
||||
pusher_did: u.pusher_did,
|
||||
node_did: u.node_did,
|
||||
timestamp: u.timestamp,
|
||||
owner_did,
|
||||
})
|
||||
.collect();
|
||||
Ok(resolved)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn tasks(
|
||||
@@ -110,21 +92,13 @@ impl QueryRoot {
|
||||
ctx: &Context<'_>,
|
||||
status: Option<String>,
|
||||
assignee_did: Option<String>,
|
||||
#[graphql(
|
||||
default = 50,
|
||||
desc = "Max 200; larger requests are clamped to 200 (no error). Negative values clamp to 0."
|
||||
)]
|
||||
limit: i64,
|
||||
#[graphql(default = 50)] limit: i64,
|
||||
) -> Result<Vec<AgentTaskType>> {
|
||||
let db = ctx.data_unchecked::<Arc<Db>>();
|
||||
// Clamp before SQL: a negative LIMIT is a client fault that Postgres
|
||||
// rejects with 2201W, which would otherwise trip the opaque DB path
|
||||
// and write an error-level log on every probe (#250 review).
|
||||
let limit = limit.clamp(0, 200);
|
||||
let tasks = db
|
||||
.list_tasks(status.as_deref(), assignee_did.as_deref(), limit)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
Ok(tasks.into_iter().map(AgentTaskType::from).collect())
|
||||
}
|
||||
|
||||
@@ -133,7 +107,7 @@ impl QueryRoot {
|
||||
let t = db
|
||||
.get_task(&id)
|
||||
.await
|
||||
.map_err(crate::graphql::graphql_db_err)?;
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
Ok(t.map(AgentTaskType::from))
|
||||
}
|
||||
}
|
||||
@@ -188,7 +162,6 @@ mod tests {
|
||||
cert_id: None,
|
||||
received_at: Utc::now().to_rfc3339(),
|
||||
from_peer: "peer1".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,10 +245,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
let schema = schema(db);
|
||||
let q = r#"{ refUpdates { repo refName ownerDid } }"#;
|
||||
let q = r#"{ refUpdates { repo refName } }"#;
|
||||
let resp = anon(&schema, q).await;
|
||||
assert_eq!(count(&resp), 1);
|
||||
// The one row returned must be the public repo's with owner_did echoed.
|
||||
// The one row returned must be the public repo's.
|
||||
let async_graphql::Value::Object(obj) = &resp.data else {
|
||||
unreachable!()
|
||||
};
|
||||
@@ -289,11 +262,6 @@ mod tests {
|
||||
row.get("repo").unwrap(),
|
||||
&async_graphql::Value::from("z6MkOwner/openrepo")
|
||||
);
|
||||
assert_eq!(
|
||||
row.get("ownerDid").unwrap(),
|
||||
&async_graphql::Value::from(OWNER),
|
||||
"ownerDid must fall back to the local record's owner for legacy rows"
|
||||
);
|
||||
}
|
||||
|
||||
// Scenario 4 — alias fail-closed: private repo's row stored full-DID form.
|
||||
@@ -427,91 +395,4 @@ mod tests {
|
||||
let q = r#"{ refUpdates { repo } }"#;
|
||||
assert_eq!(count(&authed(&schema, q, "did:key:z6MkQuar").await), 0);
|
||||
}
|
||||
|
||||
/// #250: anonymous GraphQL query DB failures must not leak sqlx/schema text.
|
||||
#[sqlx::test]
|
||||
async fn repos_query_db_error_message_is_opaque(pool: PgPool) {
|
||||
let db = db(pool.clone()).await;
|
||||
db.create_repo(&repo("r1", OWNER, "widget", true))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("ALTER TABLE repos DROP COLUMN is_public")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let schema = schema(db);
|
||||
let resp = anon(&schema, "{ repos { name ownerDid } }").await;
|
||||
assert!(
|
||||
!resp.errors.is_empty(),
|
||||
"DB failure must surface as a GraphQL error"
|
||||
);
|
||||
for err in &resp.errors {
|
||||
assert_eq!(
|
||||
err.message,
|
||||
crate::graphql::GRAPHQL_DB_ERROR_MESSAGE,
|
||||
"raw DB detail leaked into GraphQL error: {}",
|
||||
err.message
|
||||
);
|
||||
assert!(
|
||||
!err.message.contains("is_public") && !err.message.contains("column"),
|
||||
"schema text leaked: {}",
|
||||
err.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #250: negative tasks(limit) must not hit Postgres (and must not 500-log).
|
||||
#[sqlx::test]
|
||||
async fn tasks_negative_limit_clamped(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
let schema = schema(db);
|
||||
let resp = anon(&schema, "{ tasks(limit: -1) { id } }").await;
|
||||
assert!(
|
||||
resp.errors.is_empty(),
|
||||
"negative limit must clamp, not fail: {:?}",
|
||||
resp.errors
|
||||
);
|
||||
assert_eq!(count_tasks(&resp), 0);
|
||||
}
|
||||
|
||||
/// #255: ceiling of the tasks(limit) clamp must be held (schema promises Max 200).
|
||||
#[sqlx::test]
|
||||
async fn tasks_limit_ceiling_clamped_to_200(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
let now = Utc::now().to_rfc3339();
|
||||
for i in 0..201 {
|
||||
db.create_task(&crate::db::AgentTask {
|
||||
id: format!("task-ceil-{i}"),
|
||||
repo_id: None,
|
||||
kind: "build".into(),
|
||||
status: "pending".into(),
|
||||
delegator_did: OWNER.into(),
|
||||
assignee_did: None,
|
||||
capability: "repo:write".into(),
|
||||
ucan_token: None,
|
||||
payload: None,
|
||||
result: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now.clone(),
|
||||
deadline: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let schema = schema(db);
|
||||
let resp = anon(&schema, "{ tasks(limit: 5000) { id } }").await;
|
||||
assert_eq!(count_tasks(&resp), 200, "limit above 200 must clamp to 200");
|
||||
}
|
||||
|
||||
fn count_tasks(resp: &async_graphql::Response) -> usize {
|
||||
assert!(resp.errors.is_empty(), "graphql errors: {:?}", resp.errors);
|
||||
let async_graphql::Value::Object(obj) = &resp.data else {
|
||||
panic!("data not an object: {:?}", resp.data);
|
||||
};
|
||||
let async_graphql::Value::List(rows) = obj.get("tasks").expect("tasks key") else {
|
||||
panic!("tasks not a list");
|
||||
};
|
||||
rows.len()
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,6 @@ impl SubscriptionRoot {
|
||||
pusher_did: ev.pusher_did,
|
||||
node_did: ev.node_did,
|
||||
timestamp: ev.timestamp,
|
||||
owner_did: Some(ev.owner_did),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -57,7 +57,6 @@ pub struct RefUpdateType {
|
||||
pub pusher_did: String,
|
||||
pub node_did: String,
|
||||
pub timestamp: String,
|
||||
pub owner_did: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(SimpleObject, Clone)]
|
||||
|
||||
+78
-3003
File diff suppressed because it is too large.
Load diff
+274
-562
File diff suppressed because it is too large.
Load diff
@@ -57,15 +57,10 @@ static PEERS_CONNECTED: OnceLock<IntGauge> = OnceLock::new();
|
||||
/// more than once is a silent no-op. MUST be called from `main()` after
|
||||
/// the node DID is known.
|
||||
pub fn init(version: &str, node_did: &str) {
|
||||
// Guard with Once so two concurrent callers cannot both pass an unsynchronized
|
||||
// `REGISTRY.get()` check and then race on `OnceLock::set(...).expect(...)`,
|
||||
// panicking the loser (#192 F4). Once runs the body exactly once, so the
|
||||
// `.expect("set X once")` calls below can never observe an already-set slot.
|
||||
static INIT: std::sync::Once = std::sync::Once::new();
|
||||
INIT.call_once(|| init_inner(version, node_did));
|
||||
}
|
||||
if REGISTRY.get().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
fn init_inner(version: &str, node_did: &str) {
|
||||
let registry = Registry::new();
|
||||
|
||||
let info = IntGaugeVec::new(
|
||||
@@ -223,17 +218,6 @@ pub fn record_fetch(repo: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Test-only: current `gitlawb_fetches_total` value for `repo` (0 if the registry
|
||||
/// is not initialized). Lets api-layer tests assert the completed-fetch count with
|
||||
/// a unique label instead of scraping the encoded text.
|
||||
#[cfg(test)]
|
||||
pub fn fetch_count_for_test(repo: &str) -> u64 {
|
||||
FETCHES
|
||||
.get()
|
||||
.map(|c| c.with_label_values(&[repo]).get())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Record one HTTP signature check that passed.
|
||||
#[allow(dead_code)] // wired in a follow-up; helpers are part of the public metrics surface
|
||||
pub fn record_auth_success(route: &str) {
|
||||
@@ -251,11 +235,7 @@ pub fn record_auth_failure(route: &str, reason: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one sync_queue item outcome. `status` ∈ {done, failed, skipped,
|
||||
/// rejected, deferred}. `rejected` is terminal and caused by a guard (a
|
||||
/// malformed slug, or a path resolving outside repos_dir); `deferred` leaves
|
||||
/// the row pending for a later pass, so a queue stalled on an operator
|
||||
/// condition is visible rather than looking idle.
|
||||
/// Record one sync_queue item outcome. `status` ∈ {done, failed, skipped}.
|
||||
pub fn record_sync_processed(status: &str) {
|
||||
if let Some(c) = SYNC_PROCESSED.get() {
|
||||
c.with_label_values(&[status]).inc();
|
||||
@@ -302,11 +282,11 @@ pub fn encode() -> Result<String, prometheus::Error> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Note: cargo runs tests in a binary in parallel via threads, and several
|
||||
// tests here call init(). init() is guarded by std::sync::Once, so concurrent
|
||||
// callers run the body exactly once and never race on the OnceLock setters
|
||||
// (#192 F4). The encode test below is structured so it's safe to run alongside
|
||||
// other tests in the same binary regardless of ordering.
|
||||
// Note: these tests are not run in parallel by default (cargo runs
|
||||
// tests in a binary in parallel via threads but the OnceLock guard
|
||||
// means only the first init() call succeeds; subsequent ones are
|
||||
// no-ops). The encode test below is structured so it's safe to run
|
||||
// alongside other tests in the same binary.
|
||||
|
||||
#[test]
|
||||
fn encode_after_init_returns_prometheus_text() {
|
||||
@@ -337,24 +317,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// #192 F4: `init` is idempotent and safe to call repeatedly. The panic that
|
||||
/// hit concurrent callers (both passing the old unsynchronized `REGISTRY.get()`
|
||||
/// check, then racing on `OnceLock::set(...).expect(...)`) is fixed by the
|
||||
/// `Once` guard. That race is inherently non-deterministic to assert in the
|
||||
/// shared-binary suite — a 32-thread barrier stress-test reproduces it only in
|
||||
/// isolation (verified: RED before the `Once` fix, GREEN after). This guard
|
||||
/// covers the deterministic half of the contract: a repeat call is a no-op,
|
||||
/// never a panic, and the registry stays usable.
|
||||
#[test]
|
||||
fn init_is_idempotent_no_panic_on_repeat() {
|
||||
init("0.0.0-a", "did:key:a");
|
||||
init("0.0.0-b", "did:key:b");
|
||||
assert!(
|
||||
encode().is_ok(),
|
||||
"registry must stay usable after a repeated init"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_helpers_are_noops_before_init() {
|
||||
// These don't panic. They also don't show up in encode() output
|
||||
|
||||
@@ -39,11 +39,6 @@ pub struct RefUpdateEvent {
|
||||
pub pusher_did: String,
|
||||
/// Repository identifier (owner/name)
|
||||
pub repo: String,
|
||||
/// Full owner DID — added in #144 for display and storage; not yet
|
||||
/// wired into the feed gate matcher. Optional for backward compat with
|
||||
/// older peers that don't include it.
|
||||
#[serde(default)]
|
||||
pub owner_did: Option<String>,
|
||||
/// Git ref that changed (e.g., "refs/heads/main")
|
||||
pub ref_name: String,
|
||||
/// SHA before the push (all-zeros for new ref)
|
||||
@@ -312,7 +307,6 @@ pub async fn start(
|
||||
node_did: event.node_did.clone(),
|
||||
pusher_did: event.pusher_did.clone(),
|
||||
repo: event.repo.clone(),
|
||||
owner_did: event.owner_did.clone(),
|
||||
ref_name: event.ref_name.clone(),
|
||||
old_sha: event.old_sha.clone(),
|
||||
new_sha: event.new_sha.clone(),
|
||||
@@ -438,67 +432,3 @@ pub async fn start(
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ref_update_event_round_trip_with_owner_did() {
|
||||
let event = RefUpdateEvent {
|
||||
node_did: "did:key:zNode".into(),
|
||||
pusher_did: "did:key:zPusher".into(),
|
||||
repo: "zOwner/myrepo".into(),
|
||||
owner_did: Some("did:key:zOwner".into()),
|
||||
ref_name: "refs/heads/main".into(),
|
||||
old_sha: "0000000000000000000000000000000000000000".into(),
|
||||
new_sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
|
||||
timestamp: "2026-07-02T12:00:00Z".into(),
|
||||
cert_id: None,
|
||||
cid: None,
|
||||
};
|
||||
let json = serde_json::to_value(&event).unwrap();
|
||||
// owner_did must be present in the serialized output
|
||||
assert_eq!(json["owner_did"], "did:key:zOwner");
|
||||
assert_eq!(json["repo"], "zOwner/myrepo");
|
||||
|
||||
let deserialized: RefUpdateEvent = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(deserialized.owner_did, Some("did:key:zOwner".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_update_event_backward_compat_no_owner_did() {
|
||||
let old_json = serde_json::json!({
|
||||
"node_did": "did:key:zNode",
|
||||
"pusher_did": "did:key:zPusher",
|
||||
"repo": "zOwner/myrepo",
|
||||
"ref_name": "refs/heads/main",
|
||||
"old_sha": "0000000000000000000000000000000000000000",
|
||||
"new_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"timestamp": "2026-07-02T12:00:00Z",
|
||||
"cert_id": null,
|
||||
"cid": null
|
||||
});
|
||||
let deserialized: RefUpdateEvent = serde_json::from_value(old_json).unwrap();
|
||||
assert_eq!(deserialized.owner_did, None);
|
||||
assert_eq!(deserialized.repo, "zOwner/myrepo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_update_event_backward_compat_null_owner_did() {
|
||||
let with_null = serde_json::json!({
|
||||
"node_did": "did:key:zNode",
|
||||
"pusher_did": "did:key:zPusher",
|
||||
"repo": "zOwner/myrepo",
|
||||
"owner_did": null,
|
||||
"ref_name": "refs/heads/main",
|
||||
"old_sha": "0000000000000000000000000000000000000000",
|
||||
"new_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"timestamp": "2026-07-02T12:00:00Z",
|
||||
"cert_id": null,
|
||||
"cid": null
|
||||
});
|
||||
let deserialized: RefUpdateEvent = serde_json::from_value(with_null).unwrap();
|
||||
assert_eq!(deserialized.owner_did, None);
|
||||
}
|
||||
}
|
||||
+27
-1425
File diff suppressed because it is too large.
Load diff
@@ -154,28 +154,13 @@ impl RateLimiter {
|
||||
}
|
||||
|
||||
/// Number of distinct keys currently tracked. Test-only introspection so a
|
||||
/// cross-module test can assert that a sweep actually evicted expired entries
|
||||
/// and observe what it reclaimed. There is no production reader.
|
||||
/// cross-module test can assert that a sweep actually evicted expired entries.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn tracked_keys(&self) -> usize {
|
||||
self.state.lock().await.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-source concurrency cap derived from the write-pool size: one resolved client
|
||||
/// key (see [`client_key`]) may hold at most an eighth of the pool, so saturating it
|
||||
/// takes ~8 distinct keys. Real for an IPv4 or single-address caller; a caller with a
|
||||
/// routed IPv6 /64 has 2^64 keys, because `client_key` returns the full address with
|
||||
/// no prefix folding. Narrowing that keying is a deferred decision, so this cap is a
|
||||
/// bound per key, not a bound per operator.
|
||||
///
|
||||
/// Floored at 1 because the value feeds [`PerCallerConcurrency`], where a cap of 0
|
||||
/// would shed EVERY receive-pack advertisement and break all pushes. The floor is
|
||||
/// load-bearing at the minimum write-pool size (1), which integer-divides to 0.
|
||||
pub(crate) fn per_source_push_cap(max_concurrent_git_pushes: usize) -> usize {
|
||||
(max_concurrent_git_pushes / 8).max(1)
|
||||
}
|
||||
|
||||
/// A bounded per-caller CONCURRENCY limiter — distinct from [`RateLimiter`], which
|
||||
/// caps request RATE. Each caller key may hold at most `per_caller` in-flight
|
||||
/// permits at once; beyond that [`try_acquire`](Self::try_acquire) returns `None`
|
||||
|
||||
+108
-1224
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+422
-6380
File diff suppressed because it is too large.
Load diff
@@ -85,24 +85,21 @@ fn inv22_concurrency_gates_present_and_not_bypassed() {
|
||||
is reaped on disconnect (the path-scoped half of #174 P1-a)"
|
||||
);
|
||||
|
||||
// U2 / R1: a cancelled or timed-out `GET /ipfs/{cid}` must release admission only
|
||||
// after the blocking work it admitted has finished, not the instant the handler
|
||||
// future drops (the /ipfs half of #174 P1-a). The mechanism is the shared
|
||||
// `Arc<WalkAdmission>`: both walk permits are moved into it once per request and a
|
||||
// clone rides every `spawn_blocking`, so the permits release when the LAST holder
|
||||
// drops. Reverting to handler-local permits trips this; the per-site clones are
|
||||
// bound separately by `inv22_ipfs_walk_admission_reaches_every_blocking_site`.
|
||||
//
|
||||
// This previously required the permits to be owned by a detached `tokio::spawn`
|
||||
// running the whole pipeline. That closed the same bypass but kept an abandoned
|
||||
// request's full legacy scan running against a held slot, so the merge of #173 and
|
||||
// #174 kept the Arc and dropped the detached task.
|
||||
// U2 / R1 (#173 round-10): the `GET /ipfs/{cid}` serve pipeline must run in a
|
||||
// DETACHED tokio task that OWNS the AdmissionGuard built from BOTH walk permits, so a
|
||||
// cancelled or timed-out request releases admission only after the spawned (bounded)
|
||||
// work completes — not the instant the handler future drops (the /ipfs half of #174
|
||||
// P1-a). Two load-bearing markers: the guard is constructed from the two named
|
||||
// permits, and the whole pipeline is moved into a `tokio::spawn`. Reverting to
|
||||
// handler-local permits (dropping the guard/spawn) trips this.
|
||||
assert!(
|
||||
ipfs.contains("struct WalkAdmission")
|
||||
&& ipfs.contains("let admission = std::sync::Arc::new(WalkAdmission {"),
|
||||
"U2/R1 gate missing: get_by_cid must move both /ipfs admission permits into a \
|
||||
shared Arc<WalkAdmission> whose clones ride the blocking work, so admission is \
|
||||
released only once that work completes (the /ipfs half of #174 P1-a)"
|
||||
ipfs.contains("AdmissionGuard::new(ipfs_walk_permit, ipfs_caller_permit)")
|
||||
&& ipfs.contains(
|
||||
"let serve: tokio::task::JoinHandle<Result<Response>> = tokio::spawn(async move {"
|
||||
),
|
||||
"U2/R1 gate missing: get_by_cid must move both /ipfs admission permits into an \
|
||||
AdmissionGuard owned by a detached tokio::spawn task so admission is released \
|
||||
only after the spawned serve work completes (the /ipfs half of #174 P1-a)"
|
||||
);
|
||||
|
||||
// U2 / KTD2 (#173 round-10): the probe/read children on the /ipfs path must be the
|
||||
@@ -139,436 +136,4 @@ fn inv22_concurrency_gates_present_and_not_bypassed() {
|
||||
"U4/P2-2 gate missing: the detached post-push encryption spawn must consult \
|
||||
encrypt_inflight.try_begin to coalesce per repo (bound the outstanding-task set)"
|
||||
);
|
||||
|
||||
// F5: coalescing must REQUEUE, not shed. The in-flight task pins only its own
|
||||
// pre-spawn snapshot, so a coalesced push's tip pairs are recorded on its key and
|
||||
// the task must loop-drain them (`finish_or_take_pending`) before releasing it.
|
||||
// Removing the drain reverts to the silent loss: a coalesced push's pins and
|
||||
// recovery copies are absent until an unrelated later push. Scan only the
|
||||
// production half of the file — the u5 tests in its `mod tests` also name the
|
||||
// drain call, and matching them would make this check vacuous.
|
||||
// Split at the TEST MODULE, not at the first `#[cfg(test)]`. api/repos.rs carries
|
||||
// test-only items (the drain fault seam, the task entry point) ABOVE the production
|
||||
// code these gates scan for, so splitting on the attribute truncated the production
|
||||
// half above every line being checked and the gate went vacuously blind.
|
||||
let repos_production = repos
|
||||
.split("\nmod tests {")
|
||||
.next()
|
||||
.expect("split always yields a first chunk");
|
||||
assert!(
|
||||
repos_production.contains("finish_or_take_pending"),
|
||||
"F5 gate missing: the post-push encryption task must loop-drain coalesced \
|
||||
pushes via finish_or_take_pending before releasing its repo key"
|
||||
);
|
||||
|
||||
// F4: every post-receive scan helper admits itself to the shared scan pool via
|
||||
// `crate::state::acquire_scan_permit` BEFORE its spawn_blocking git walk, so a
|
||||
// push burst cannot accumulate unbounded concurrent scans once the write permit
|
||||
// is released. Two halves, both load-bearing: the helper body must actually
|
||||
// acquire the pool (state.rs sits the helper at the end of the file, so the
|
||||
// definition tail contains no other `acquire_owned` to match vacuously), and
|
||||
// within each scan helper the first qualified call precedes the first
|
||||
// `spawn_blocking`. Severing a call site pushes the next occurrence past the
|
||||
// helper's own `spawn_blocking` (or off the end of the file), turning the
|
||||
// assertion red; comments name the helper without the `crate::state::` prefix,
|
||||
// so this targets the real call sites.
|
||||
let state_rs = src("state.rs");
|
||||
let helper_def = state_rs
|
||||
.find("fn acquire_scan_permit")
|
||||
.expect("F4 gate missing: state.rs no longer defines acquire_scan_permit");
|
||||
assert!(
|
||||
state_rs[helper_def..].contains("acquire_owned"),
|
||||
"F4 gate gutted: acquire_scan_permit must acquire the scan pool via acquire_owned"
|
||||
);
|
||||
let push_delta = src("git/push_delta.rs");
|
||||
for (file_src, file, helper) in [
|
||||
(&repos, "api/repos.rs", "fn replication_withheld_set"),
|
||||
(&repos, "api/repos.rs", "fn fail_closed_full_scan_objects"),
|
||||
(
|
||||
&push_delta,
|
||||
"git/push_delta.rs",
|
||||
"fn resolve_candidates_for_push",
|
||||
),
|
||||
] {
|
||||
let start = file_src
|
||||
.find(helper)
|
||||
.unwrap_or_else(|| panic!("{file}: `{helper}` not found"));
|
||||
let tail = &file_src[start..];
|
||||
let acquire = tail
|
||||
.find("crate::state::acquire_scan_permit(")
|
||||
.unwrap_or_else(|| {
|
||||
panic!("F4 gate missing: {file} `{helper}` no longer acquires a scan permit")
|
||||
});
|
||||
let spawn = tail.find("spawn_blocking").unwrap_or_else(|| {
|
||||
panic!("{file}: `{helper}` lost its spawn_blocking walk — update this guard")
|
||||
});
|
||||
assert!(
|
||||
acquire < spawn,
|
||||
"F4 gate bypassed: {file} `{helper}` must acquire its git_encrypt_semaphore \
|
||||
permit BEFORE dispatching the blocking git scan"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// F4 (repo_store advisory-unlock cancellation safety): `RepoWriteGuard::release`
|
||||
/// must await `pg_advisory_unlock` while `self` still owns the pooled connection,
|
||||
/// and must not mark itself `released` until that await resolves. Either shape,
|
||||
/// reintroduced, re-opens the mid-unlock cancellation leak: taking the connection
|
||||
/// early leaves `Drop` with `conn == None`, and setting `released = true` early
|
||||
/// leaves the `Drop` backstop inert — both strand the session lock on cancellation.
|
||||
///
|
||||
/// Scoped to the `release` fn body: the `Drop` impl legitimately takes the
|
||||
/// connection and unlocks, so a whole-file scan would match it and read as a false
|
||||
/// pass. Reverting either ordering turns this red (proven load-bearing).
|
||||
#[test]
|
||||
fn f4_release_keeps_conn_owned_until_unlock_resolves() {
|
||||
let repo_store = src("git/repo_store.rs");
|
||||
|
||||
let rel_start = repo_store
|
||||
.find("pub async fn release(self")
|
||||
.or_else(|| repo_store.find("pub async fn release(mut self"))
|
||||
.expect("F4 gate: repo_store.rs no longer defines RepoWriteGuard::release");
|
||||
let rel_end = repo_store[rel_start..]
|
||||
.find("impl Drop for RepoWriteGuard")
|
||||
.map(|off| rel_start + off)
|
||||
.expect("F4 gate: release fn / Drop impl markers moved — update this guard");
|
||||
let release_body = &repo_store[rel_start..rel_end];
|
||||
|
||||
let unlock = release_body
|
||||
.find("pg_advisory_unlock")
|
||||
.expect("F4 gate: release must still issue pg_advisory_unlock");
|
||||
let before_unlock = &release_body[..unlock];
|
||||
|
||||
// (a) the connection must still be owned by `self` at the unlock await.
|
||||
assert!(
|
||||
!before_unlock.contains("self.conn.take()"),
|
||||
"F4 regression: RepoWriteGuard::release takes self.conn BEFORE awaiting \
|
||||
pg_advisory_unlock. A cancellation during the unlock await then strands the \
|
||||
session advisory lock (Drop sees conn == None and skips its backstop). \
|
||||
Unlock through the still-owned connection instead."
|
||||
);
|
||||
// (b) `released` must not be set before the unlock await — the other
|
||||
// reintroduction shape a single-reorder check on (a) alone is blind to.
|
||||
assert!(
|
||||
!before_unlock.contains("released = true"),
|
||||
"F4 regression: RepoWriteGuard::release sets `released = true` BEFORE awaiting \
|
||||
pg_advisory_unlock. A cancellation during the await then leaves the Drop \
|
||||
backstop inert (it early-returns on released). Set released only AFTER the \
|
||||
unlock await resolves."
|
||||
);
|
||||
}
|
||||
|
||||
/// F6/KTD-5 (IPFS metadata queries deadline-wrapped): `get_by_cid` acquires
|
||||
/// the scarce walk permits (RAII, held for the whole request) BEFORE its metadata
|
||||
/// queries, and the per-repo loop's first budget gate runs only later. So
|
||||
/// both `list_repos_page_for_scan` and `list_visibility_rules_for_repos` must be clamped to the
|
||||
/// remaining request budget — otherwise a query blocked in Postgres pins the walk slot
|
||||
/// for the whole stall, past the budget. This scans the PRODUCTION half of `api/ipfs.rs`
|
||||
/// (the `mod tests` half names the same calls in its own harness and would make the
|
||||
/// check vacuous) and asserts each query call is immediately preceded by a
|
||||
/// `tokio::time::timeout(` wrapper. Removing either wrapper turns this red (proven
|
||||
/// load-bearing).
|
||||
#[test]
|
||||
fn f6_ipfs_metadata_queries_are_deadline_wrapped() {
|
||||
let ipfs = src("api/ipfs.rs");
|
||||
// Split at the TEST MODULE, not at the first `#[cfg(test)]`: the handler carries
|
||||
// in-line `#[cfg(test)]` query counters, so splitting on the attribute cut the
|
||||
// production half off above the calls this guard exists to check and the scan went
|
||||
// vacuously quiet (found 0 of each rather than failing on a missing wrapper).
|
||||
let production = ipfs
|
||||
.split("\nmod tests {")
|
||||
.next()
|
||||
.expect("split always yields a first chunk");
|
||||
|
||||
// EVERY occurrence must be wrapped, not just the first. The handler now reaches
|
||||
// these queries from two places (the provenance fast path, one repo at a time, and
|
||||
// the legacy scan's preload), and an exact-count check would have to be relaxed
|
||||
// every time a call site is added, which is how a guard quietly stops covering the
|
||||
// site that matters. Requiring all of them scales with the code instead.
|
||||
for call in [
|
||||
".list_repos_page_for_scan(",
|
||||
".list_visibility_rules_for_repos(",
|
||||
".get_repo_by_id(",
|
||||
".is_repo_quarantined(",
|
||||
] {
|
||||
let occurrences = production.matches(call).count();
|
||||
assert!(
|
||||
occurrences >= 1,
|
||||
"F6 guard stale: api/ipfs.rs no longer calls `{call}` — update this guard"
|
||||
);
|
||||
for (n, (idx, _)) in production.match_indices(call).enumerate() {
|
||||
// The wrapper opens a few lines above the call (match tokio::time::timeout(
|
||||
// ... remaining budget ..., <query> )); a 240-char lookback covers it
|
||||
// without reaching the previous statement.
|
||||
let window = &production[idx.saturating_sub(240)..idx];
|
||||
assert!(
|
||||
window.contains("tokio::time::timeout("),
|
||||
"F6 gate missing: occurrence {n} of `{call}` (of {occurrences}) is not \
|
||||
wrapped in tokio::time::timeout(...) clamped to the remaining request \
|
||||
budget. An unwrapped await pins the held walk permit for the whole DB \
|
||||
stall, past GITLAWB_IPFS_REQUEST_BUDGET_SECS."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #174 F2 / KTD-3: the detached post-receive Pinata replication task must enqueue
|
||||
/// only the push's `(ref, old, new)` tuples and RE-DERIVE its object set inside the
|
||||
/// worker once a pin slot frees — it must NOT move the full per-push object list into
|
||||
/// the closure and hold it across the `pin_semaphore` acquire. Retaining the list makes
|
||||
/// every parked task (under a slow Pinata backend) hold an MB-scale OID list, so
|
||||
/// outstanding memory grows O(pushes x object-list). Coalescing/shedding the task is
|
||||
/// forbidden (its per-ref effects are non-idempotent), so the fix bounds the retained
|
||||
/// data, not the task count.
|
||||
///
|
||||
/// Two load-bearing checks, both against the PRODUCTION half of `api/repos.rs` (the
|
||||
/// `mod tests` half names the same identifiers in its own harness and would make the
|
||||
/// scan vacuous): (a) the closure-local `object_list_pinata` binding — the retain form —
|
||||
/// must be gone; reintroducing `let object_list_pinata = object_list;` turns this red.
|
||||
/// (b) the re-derivation (`pinata_object_list_for_refs`) must appear AFTER the Pinata
|
||||
/// pin permit is acquired, so the object list is materialized only inside the pin-bounded
|
||||
/// section and a parked task holds O(ref tuples).
|
||||
#[test]
|
||||
fn f2_pinata_enqueues_refs_not_retained_object_lists() {
|
||||
let repos = src("api/repos.rs");
|
||||
// Split at the TEST MODULE, not at the first `#[cfg(test)]`. api/repos.rs carries
|
||||
// test-only items (the drain fault seam, the task entry point) ABOVE the production
|
||||
// code these gates scan for, so splitting on the attribute truncated the production
|
||||
// half above every line being checked and the gate went vacuously blind.
|
||||
let production = repos
|
||||
.split("\nmod tests {")
|
||||
.next()
|
||||
.expect("split always yields a first chunk");
|
||||
|
||||
// (a) the retained-list form must be gone from production.
|
||||
assert!(
|
||||
!production.contains("object_list_pinata"),
|
||||
"F2/KTD-3 regression: the Pinata task retains a full per-push object list \
|
||||
(`object_list_pinata`) across the pin-permit acquire. Enqueue only the ref \
|
||||
tuples and re-derive the object set inside the worker (pinata_object_list_for_refs)."
|
||||
);
|
||||
|
||||
// (b) the re-derivation runs AFTER the pin permit is acquired. Anchor on the
|
||||
// Pinata pin-admission clone so the window is the Pinata task, not the sibling
|
||||
// IPFS/encrypt spawn (which shares `pin_semaphore` but never re-derives).
|
||||
let anchor = production
|
||||
.find("let pin_sem_pinata")
|
||||
.expect("F2 gate stale: the Pinata pin-admission clone (pin_sem_pinata) moved");
|
||||
let tail = &production[anchor..];
|
||||
let acquire = tail
|
||||
.find(".acquire_owned()")
|
||||
.expect("F2 gate: the Pinata task no longer acquires a pin permit (acquire_owned)");
|
||||
let rederive = tail.find("pinata_object_list_for_refs(").expect(
|
||||
"F2 gate missing: the Pinata task must re-derive its object set via \
|
||||
pinata_object_list_for_refs; it can no longer move a pre-resolved list into the closure",
|
||||
);
|
||||
assert!(
|
||||
acquire < rederive,
|
||||
"F2 gate bypassed: the Pinata object-set re-derivation must run AFTER the pin \
|
||||
permit is acquired, so a parked task never holds the MB-scale object list"
|
||||
);
|
||||
|
||||
// The re-derivation is driven by the push's ref tuples (the enqueued unit), not a
|
||||
// retained object list — tie "enqueue ref_updates" to the call explicitly.
|
||||
assert!(
|
||||
tail[rederive..].starts_with("pinata_object_list_for_refs(")
|
||||
&& tail[rederive..]
|
||||
.get(..400)
|
||||
.map(|w| w.contains("ref_updates_clone"))
|
||||
.unwrap_or(false),
|
||||
"F2 gate: pinata_object_list_for_refs must re-derive from the push's ref tuples \
|
||||
(ref_updates_clone), the small unit the parked task retains"
|
||||
);
|
||||
}
|
||||
|
||||
/// #174 U2 / F3 (second same-repo writer serialized until a disconnected first push's
|
||||
/// git group is reaped): `git_receive_pack` must take the per-repo in-process write
|
||||
/// lease and CARRY it on the write-path `AdmissionGuard` (via `.with_lease`), so the
|
||||
/// lease rides `KillGroupOnDrop`'s detached reaper and frees only after the group is
|
||||
/// reaped — supplementing the pg advisory lock, which `RepoWriteGuard::Drop` releases at
|
||||
/// the disconnect instant. Tying the lease to `RepoWriteGuard` instead (or dropping the
|
||||
/// `.with_lease` carry) reopens the race; the behavioral RED/GREEN test
|
||||
/// (`f3_second_push_serialized_until_disconnected_group_reaped`) is the real bar, this
|
||||
/// is the completeness tripwire. Scanned against the PRODUCTION half of `api/repos.rs`
|
||||
/// (the `mod tests` half names these identifiers in its own harness).
|
||||
#[test]
|
||||
fn f3_second_writer_leased_until_reap() {
|
||||
let repos = src("api/repos.rs");
|
||||
let smart_http = src("git/smart_http.rs");
|
||||
// Split at the TEST MODULE, not at the first `#[cfg(test)]`. api/repos.rs carries
|
||||
// test-only items (the drain fault seam, the task entry point) ABOVE the production
|
||||
// code these gates scan for, so splitting on the attribute truncated the production
|
||||
// half above every line being checked and the gate went vacuously blind.
|
||||
let repos_production = repos
|
||||
.split("\nmod tests {")
|
||||
.next()
|
||||
.expect("split always yields a first chunk");
|
||||
|
||||
// The lease is acquired, then carried by the AdmissionGuard (.with_lease), before
|
||||
// receive_pack runs the write. Severing any of the three turns this red.
|
||||
let lease_acquire = repos_production.find("repo_write_leases").expect(
|
||||
"F3 gate missing: git_receive_pack no longer takes the per-repo write lease \
|
||||
(state.repo_write_leases)",
|
||||
);
|
||||
let with_lease = repos_production.find(".with_lease(").expect(
|
||||
"F3 gate missing: the write-path AdmissionGuard no longer carries the lease \
|
||||
(.with_lease). The lease must ride the disconnect reaper via the AdmissionGuard, \
|
||||
NOT RepoWriteGuard (which drops at the disconnect instant, reopening F3).",
|
||||
);
|
||||
let receive = repos_production
|
||||
.find("smart_http::receive_pack(")
|
||||
.expect("F3 gate stale: git_receive_pack no longer calls smart_http::receive_pack");
|
||||
assert!(
|
||||
lease_acquire < with_lease && with_lease < receive,
|
||||
"F3 gate bypassed: the write lease must be acquired, then carried by the \
|
||||
AdmissionGuard (.with_lease), BEFORE receive_pack runs the write"
|
||||
);
|
||||
|
||||
// The AdmissionGuard must actually hold the lease (Option<RepoWriteLease>) via a
|
||||
// with_lease setter, so it travels into the detached reaper. Removing the field or
|
||||
// method turns this red.
|
||||
assert!(
|
||||
smart_http.contains("_lease: Option<crate::state::RepoWriteLease>")
|
||||
&& smart_http.contains("pub fn with_lease("),
|
||||
"F3 gate missing: AdmissionGuard must hold an Option<RepoWriteLease> set via \
|
||||
with_lease, so the lease rides the guard into KillGroupOnDrop's reaper"
|
||||
);
|
||||
}
|
||||
|
||||
/// #174 U1 — every blocking walk in the `/ipfs` scan carries the request's walk
|
||||
/// admission.
|
||||
///
|
||||
/// The admission is an `Arc<WalkAdmission>` cloned into each `spawn_blocking`
|
||||
/// closure, so the global + per-source permits release only when the last holder
|
||||
/// drops: a client disconnect leaves the abandoned closure holding the slot, and a
|
||||
/// panicking closure leaves the handler holding it.
|
||||
///
|
||||
/// Only the walk site runs under `state.git_bin`, so only it can be pinned by the
|
||||
/// fake-git harness and mutation-verified dynamically (see
|
||||
/// `get_by_cid_walk_permit_held_through_blocking_walk`). The probe and the content
|
||||
/// read deliberately shell to the real `git`, which is why this structural check
|
||||
/// exists: it binds all three sites, and any blocking site added to this loop
|
||||
/// later, without reversing that deliberate independence.
|
||||
///
|
||||
/// MUTATION (RED): delete any one `Arc::clone(ctx.admission)` binding, or drop the
|
||||
/// clone from inside its closure, and the count falls below three.
|
||||
#[test]
|
||||
fn inv22_ipfs_walk_admission_reaches_every_blocking_site() {
|
||||
let ipfs = src("api/ipfs.rs");
|
||||
|
||||
// The shared owner must exist and be built once per request.
|
||||
assert!(
|
||||
ipfs.contains("struct WalkAdmission") && ipfs.contains("Arc::new(WalkAdmission {"),
|
||||
"U1 gate missing: the /ipfs walk admission must be a shared WalkAdmission, \
|
||||
not a handler-local permit pair"
|
||||
);
|
||||
|
||||
// Every blocking site in the scan takes its own clone...
|
||||
// `Arc::clone(ctx.admission)` in the gate, `Arc::clone(&admission)` if a site is
|
||||
// ever added back in the handler body itself; count both spellings.
|
||||
let clones = ipfs.matches("Arc::clone(ctx.admission)").count()
|
||||
+ ipfs.matches("Arc::clone(&admission)").count();
|
||||
assert!(
|
||||
clones >= 3,
|
||||
"U1 gate bypassed: expected an admission clone for each of the three \
|
||||
/ipfs spawn_blocking sites (probe, walk, read); found {clones}. A blocking \
|
||||
walk that does not hold the admission lets a disconnect or a panic free the \
|
||||
slot while its git child is still running."
|
||||
);
|
||||
|
||||
// ...and each clone is actually moved INTO the blocking closure, not merely
|
||||
// created in the async frame (which would hold nothing across the join).
|
||||
let held = ipfs.matches("let _admission = ").count();
|
||||
assert!(
|
||||
held >= 3,
|
||||
"U1 gate bypassed: each admission clone must be bound inside its \
|
||||
spawn_blocking closure so the blocking work owns it; found {held} of 3."
|
||||
);
|
||||
|
||||
// The count of blocking sites is itself the thing being covered: if a fourth
|
||||
// appears, it needs an admission clone too and this gate must be revisited.
|
||||
let sites = ipfs.matches("spawn_blocking(move ||").count();
|
||||
assert_eq!(
|
||||
sites, 3,
|
||||
"the /ipfs scan grew or lost a spawn_blocking site ({sites} found, expected 3); \
|
||||
give any new blocking walk its own Arc::clone(&admission) and update this gate"
|
||||
);
|
||||
}
|
||||
|
||||
/// #174 U5: the post-receive replication tail is spawned at the DURABILITY BOUNDARY,
|
||||
/// which is the moment receive-pack returns success, not the end of the handler and
|
||||
/// not after `guard.release()`.
|
||||
///
|
||||
/// The tail owes this push its pins, recovery copy, and announcements. Everything
|
||||
/// below the spawn stays in the cancellable request future, so anything the tail is
|
||||
/// spawned after is a window where a client disconnect drops that work while the pack
|
||||
/// is already durable on disk. `guard.release()` is such a window: on success it
|
||||
/// awaits the Tigris upload and then the advisory unlock.
|
||||
///
|
||||
/// The lower bound matters just as much as the upper one: `release` runs on failure
|
||||
/// too, so an ungated spawn would fire for a push git rejected, pinning and announcing
|
||||
/// a half-applied repo. Above `release` the `?` on `receive_result` can no longer be
|
||||
/// what gates it, so the success check is explicit and this gate binds it: the spawn
|
||||
/// must sit inside `if push_succeeded`, and `release` must consume the same flag so
|
||||
/// the two cannot drift apart.
|
||||
///
|
||||
/// This is an ordering check rather than a cancellation-race test on purpose: it is
|
||||
/// the companion to `receive_pack_tail_survives_a_disconnect_during_release`, which
|
||||
/// drives the actual disconnect through a parked `release`. Same instrument the F3
|
||||
/// gate above uses.
|
||||
///
|
||||
/// MUTATION (RED): move the `tokio::spawn(post_receive_replication_tail` call below
|
||||
/// `guard.release(` and the ordering assertion fails; take it out of the
|
||||
/// `if push_succeeded` block and the failed-push assertion fails.
|
||||
#[test]
|
||||
fn inv22_replication_tail_spawns_at_the_durability_boundary() {
|
||||
let repos = src("api/repos.rs");
|
||||
// Production half only — the tests below name these identifiers too.
|
||||
// Split at the TEST MODULE, not at the first `#[cfg(test)]`. api/repos.rs carries
|
||||
// test-only items (the drain fault seam, the task entry point) ABOVE the production
|
||||
// code these gates scan for, so splitting on the attribute truncated the production
|
||||
// half above every line being checked and the gate went vacuously blind.
|
||||
let production = repos
|
||||
.split("\nmod tests {")
|
||||
.next()
|
||||
.expect("split always yields a first chunk");
|
||||
|
||||
let success_flag = production
|
||||
.find("let push_succeeded = receive_result.is_ok();")
|
||||
.expect(
|
||||
"U5 gate missing: the tail's success gate must be bound from receive_result.is_ok()",
|
||||
);
|
||||
let gate_open = production
|
||||
.find("if push_succeeded {")
|
||||
.expect("U5 gate missing: the tail spawn must be gated on the push having succeeded");
|
||||
let spawn = production
|
||||
.find("tokio::spawn(post_receive_replication_tail(")
|
||||
.expect("U5 gate missing: the replication tail must be spawned by git_receive_pack");
|
||||
let release = production
|
||||
.find(".release(push_succeeded)")
|
||||
.expect("U5 gate stale: release must consume the same success flag as the tail gate");
|
||||
let touch = production
|
||||
.find("state.db.touch_repo(")
|
||||
.expect("U5 gate stale: git_receive_pack no longer calls touch_repo");
|
||||
let webhook = production
|
||||
.find("webhooks::fire_event(")
|
||||
.expect("U5 gate stale: git_receive_pack no longer fires push webhooks");
|
||||
|
||||
assert!(
|
||||
success_flag < gate_open && gate_open < spawn,
|
||||
"U5 gate bypassed: the tail must be spawned inside `if push_succeeded`, or a \
|
||||
rejected push spawns a tail that pins and announces a half-applied repo"
|
||||
);
|
||||
// Still inside that block: no `}` may close it between the gate and the spawn.
|
||||
assert!(
|
||||
!production[gate_open + "if push_succeeded {".len()..spawn].contains('}'),
|
||||
"U5 gate bypassed: the tail spawn left the `if push_succeeded` block, so a \
|
||||
rejected push now spawns a tail"
|
||||
);
|
||||
assert!(
|
||||
spawn < release && spawn < touch && spawn < webhook,
|
||||
"U5 gate bypassed: the tail must be spawned BEFORE guard.release, touch_repo \
|
||||
and the webhook fan-out, so a disconnect in any of those windows cannot drop \
|
||||
this push's pins, recovery copy, and announcements"
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gl"
|
||||
description = "The gitlawb CLI — identity management, node control, MCP server"
|
||||
version = "0.7.1" # x-release-please-version
|
||||
version = "0.5.1" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -11,9 +11,8 @@ name = "gl"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
gitlawb-core = { path = "../gitlawb-core", features = ["redirect"] }
|
||||
gitlawb-core = { path = "../gitlawb-core" }
|
||||
icaptcha-client = { path = "../icaptcha-client" }
|
||||
base64 = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+27
-216
@@ -41,16 +41,6 @@ pub enum CertCmd {
|
||||
node: String,
|
||||
#[arg(long)]
|
||||
dir: Option<PathBuf>,
|
||||
/// Exit non-zero unless the Ed25519 signature verifies AND the
|
||||
/// issuing node matches the queried node (or --expect-node)
|
||||
#[arg(long)]
|
||||
verify: bool,
|
||||
/// Expected issuing node DID for --verify. A valid signature alone
|
||||
/// only proves the cert is internally consistent — signed by whatever
|
||||
/// key it names — so --verify also anchors the issuer to a DID you
|
||||
/// trust: this value when given, else the queried node's DID.
|
||||
#[arg(long, requires = "verify")]
|
||||
expect_node: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -62,9 +52,7 @@ pub async fn run(args: CertArgs) -> Result<()> {
|
||||
id,
|
||||
node,
|
||||
dir,
|
||||
verify,
|
||||
expect_node,
|
||||
} => cmd_show(repo, id, node, dir, verify, expect_node).await,
|
||||
} => cmd_show(repo, id, node, dir).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,14 +114,7 @@ async fn cmd_list(repo: String, node: String, dir: Option<PathBuf>) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_show(
|
||||
repo: String,
|
||||
id: String,
|
||||
node: String,
|
||||
dir: Option<PathBuf>,
|
||||
require_valid: bool,
|
||||
expect_node: Option<String>,
|
||||
) -> Result<()> {
|
||||
async fn cmd_show(repo: String, id: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let (owner, name) = resolve_repo(&repo, &node, dir.as_deref()).await?;
|
||||
|
||||
let client = signed_client(&node, dir.as_deref());
|
||||
@@ -167,124 +148,39 @@ async fn cmd_show(
|
||||
println!(" Signature: {signature}");
|
||||
println!();
|
||||
|
||||
// Verify the Ed25519 signature: rebuild the exact canonical payload the
|
||||
// node signed (see gitlawb-node/src/cert.rs::issue_ref_certificate) and
|
||||
// check it against the public key embedded in the certificate's node DID.
|
||||
// This proves the cert is internally authentic — signed by the key it
|
||||
// names; the node-DID comparison below covers *which* node that is.
|
||||
let repo_id = cert["repo_id"].as_str().unwrap_or("");
|
||||
let verdict = verify_signature(
|
||||
repo_id, ref_name, old_sha, new_sha, pusher, node_did, issued_at, signature,
|
||||
);
|
||||
// Reconstruct the signing payload and verify
|
||||
// Fetch the node's current public key to verify
|
||||
let info: Value = client
|
||||
.get("/")
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to fetch node info")?;
|
||||
let current_node_did = info["did"].as_str().unwrap_or("");
|
||||
|
||||
println!("Signature verification:");
|
||||
match &verdict {
|
||||
Ok(()) => {
|
||||
println!(
|
||||
" VALID — Ed25519 signature verified against the key the certificate names ({node_did})"
|
||||
);
|
||||
}
|
||||
Err(reason) => {
|
||||
println!(" INVALID — {reason}");
|
||||
}
|
||||
println!(" Signing payload would be:");
|
||||
println!(" {{\"repo_id\": ..., \"ref\": \"{ref_name}\", \"old\": \"{old_sha}\",");
|
||||
println!(" \"new\": \"{new_sha}\", \"pusher\": \"{pusher}\",");
|
||||
println!(" \"node\": \"{node_did}\", \"ts\": \"{issued_at}\"}}");
|
||||
println!();
|
||||
|
||||
if current_node_did == node_did {
|
||||
println!(" Node DID matches current node. Signature is an Ed25519/base64url value.");
|
||||
println!(" To verify offline, use the node's Ed25519 public key derived from:");
|
||||
println!(" did:key → {node_did}");
|
||||
} else {
|
||||
println!(" WARNING: Certificate node DID ({node_did}) does not match");
|
||||
println!(" current node DID ({current_node_did}).");
|
||||
println!(" This certificate was issued by a different node.");
|
||||
}
|
||||
|
||||
// Contextual only — the verdict above stands on its own, so a node-info
|
||||
// hiccup here must not turn a successfully displayed certificate into an
|
||||
// error exit.
|
||||
let current_node_did = match client.get("/").await {
|
||||
Ok(resp) => resp
|
||||
.json::<Value>()
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|info| info["did"].as_str().map(str::to_string)),
|
||||
Err(_) => None,
|
||||
};
|
||||
match current_node_did.as_deref() {
|
||||
Some(current) if current == node_did => {
|
||||
println!(" Issuing node DID matches the node being queried.");
|
||||
}
|
||||
Some(current) => {
|
||||
println!(" WARNING: Certificate node DID ({node_did}) does not match");
|
||||
println!(" current node DID ({current}).");
|
||||
println!(" This certificate was issued by a different node.");
|
||||
}
|
||||
None => {
|
||||
println!(" NOTE: could not fetch current node info — skipping node-DID comparison.");
|
||||
}
|
||||
}
|
||||
|
||||
if require_valid {
|
||||
if let Err(reason) = verdict {
|
||||
anyhow::bail!("certificate signature did not verify: {reason}");
|
||||
}
|
||||
// A valid signature proves internal consistency only: the payload was
|
||||
// signed by whatever key the certificate itself names. A hostile
|
||||
// source can mint a keypair, put its DID in node_did, and self-sign.
|
||||
// --verify therefore also anchors the issuer to a trusted DID:
|
||||
// --expect-node when given, else the DID of the node being queried.
|
||||
let expected = expect_node.as_deref().or(current_node_did.as_deref());
|
||||
match expected {
|
||||
Some(expected) if expected == node_did => {}
|
||||
Some(expected) => anyhow::bail!(
|
||||
"certificate is signed by {node_did}, but the expected issuer is {expected} — \
|
||||
a valid signature alone proves internal consistency, not a trusted issuer"
|
||||
),
|
||||
None => anyhow::bail!(
|
||||
"cannot anchor the issuer: node info is unreachable and no --expect-node was given"
|
||||
),
|
||||
}
|
||||
}
|
||||
println!();
|
||||
println!(" Signature (base64url): {signature}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rebuild the node's canonical signing payload (field order must match
|
||||
/// gitlawb-node/src/cert.rs::issue_ref_certificate exactly) and verify the
|
||||
/// certificate's Ed25519 signature against the key embedded in `node_did`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn verify_signature(
|
||||
repo_id: &str,
|
||||
ref_name: &str,
|
||||
old_sha: &str,
|
||||
new_sha: &str,
|
||||
pusher: &str,
|
||||
node_did: &str,
|
||||
issued_at: &str,
|
||||
signature_b64: &str,
|
||||
) -> std::result::Result<(), String> {
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
|
||||
use std::str::FromStr;
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"repo_id": repo_id,
|
||||
"ref": ref_name,
|
||||
"old": old_sha,
|
||||
"new": new_sha,
|
||||
"pusher": pusher,
|
||||
"node": node_did,
|
||||
"ts": issued_at,
|
||||
});
|
||||
let payload_bytes =
|
||||
serde_json::to_vec(&payload).map_err(|e| format!("could not serialize payload: {e}"))?;
|
||||
|
||||
let did =
|
||||
gitlawb_core::did::Did::from_str(node_did).map_err(|e| format!("bad node DID: {e}"))?;
|
||||
let verifying_key = did
|
||||
.to_verifying_key()
|
||||
.map_err(|e| format!("cannot derive a public key from {node_did}: {e}"))?;
|
||||
|
||||
let sig_vec = URL_SAFE_NO_PAD
|
||||
.decode(signature_b64)
|
||||
.map_err(|e| format!("signature is not valid base64url: {e}"))?;
|
||||
let sig_bytes: [u8; 64] = sig_vec
|
||||
.try_into()
|
||||
.map_err(|_| "signature is not 64 bytes".to_string())?;
|
||||
|
||||
gitlawb_core::identity::verify(&verifying_key, &payload_bytes, &sig_bytes)
|
||||
.map_err(|_| "Ed25519 signature does not match the signed payload".to_string())
|
||||
}
|
||||
|
||||
async fn resolve_cert_id(client: &NodeClient, owner: &str, name: &str, id: &str) -> Result<String> {
|
||||
if id.len() >= 36 {
|
||||
return Ok(id.to_string());
|
||||
@@ -313,88 +209,3 @@ async fn resolve_cert_id(client: &NodeClient, owner: &str, name: &str, id: &str)
|
||||
_ => anyhow::bail!("certificate prefix {id} matches multiple certificates"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Pins gl's payload reconstruction to the frozen canonical byte form the
|
||||
/// node signs (default serde_json maps = alphabetically ordered keys). If
|
||||
/// serialization drifts — a field added, or a preserve_order feature
|
||||
/// landing anywhere in the workspace (feature unification flips every
|
||||
/// crate at once) — this literal stops matching and the test fails,
|
||||
/// instead of every real certificate silently rendering INVALID.
|
||||
#[test]
|
||||
fn payload_serialization_matches_frozen_canonical_form() {
|
||||
let payload = serde_json::json!({
|
||||
"repo_id": "repo-1",
|
||||
"ref": "refs/heads/main",
|
||||
"old": "oldsha",
|
||||
"new": "newsha",
|
||||
"pusher": "did:key:z6MkPusher",
|
||||
"node": "did:key:z6MkNode",
|
||||
"ts": "2026-07-22T00:00:00+00:00",
|
||||
});
|
||||
let frozen = concat!(
|
||||
r#"{"new":"newsha","node":"did:key:z6MkNode","old":"oldsha","#,
|
||||
r#""pusher":"did:key:z6MkPusher","ref":"refs/heads/main","#,
|
||||
r#""repo_id":"repo-1","ts":"2026-07-22T00:00:00+00:00"}"#,
|
||||
);
|
||||
assert_eq!(serde_json::to_string(&payload).unwrap(), frozen);
|
||||
}
|
||||
|
||||
/// Signing exactly as the node does must round-trip through
|
||||
/// verify_signature; any field tampering must fail it.
|
||||
#[test]
|
||||
fn verify_signature_round_trip_and_tamper() {
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let node_did = kp.did().as_str().to_string();
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"repo_id": "repo-1",
|
||||
"ref": "refs/heads/main",
|
||||
"old": "0".repeat(40),
|
||||
"new": "a".repeat(40),
|
||||
"pusher": "did:key:z6MkPusher",
|
||||
"node": node_did,
|
||||
"ts": "2026-07-22T00:00:00+00:00",
|
||||
});
|
||||
let sig = kp.sign_b64(&serde_json::to_vec(&payload).unwrap());
|
||||
|
||||
let ok = verify_signature(
|
||||
"repo-1",
|
||||
"refs/heads/main",
|
||||
&"0".repeat(40),
|
||||
&"a".repeat(40),
|
||||
"did:key:z6MkPusher",
|
||||
&node_did,
|
||||
"2026-07-22T00:00:00+00:00",
|
||||
&sig,
|
||||
);
|
||||
assert!(ok.is_ok(), "expected valid signature, got: {ok:?}");
|
||||
|
||||
let tampered = verify_signature(
|
||||
"repo-1",
|
||||
"refs/heads/main",
|
||||
&"0".repeat(40),
|
||||
&"b".repeat(40), // new_sha changed after signing
|
||||
"did:key:z6MkPusher",
|
||||
&node_did,
|
||||
"2026-07-22T00:00:00+00:00",
|
||||
&sig,
|
||||
);
|
||||
assert!(tampered.is_err(), "tampered payload must not verify");
|
||||
|
||||
let garbage = verify_signature(
|
||||
"repo-1",
|
||||
"refs/heads/main",
|
||||
&"0".repeat(40),
|
||||
&"a".repeat(40),
|
||||
"did:key:z6MkPusher",
|
||||
&node_did,
|
||||
"2026-07-22T00:00:00+00:00",
|
||||
"not-base64url!!!",
|
||||
);
|
||||
assert!(garbage.is_err(), "malformed signature must not verify");
|
||||
}
|
||||
}
|
||||
+8
-259
@@ -12,58 +12,9 @@ use serde::Deserialize;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::http::{sanitize_node_msg, NodeClient};
|
||||
use crate::http::NodeClient;
|
||||
use crate::identity::load_keypair_from_dir;
|
||||
|
||||
/// Report why one candidate blob could not be recovered, in the register of the
|
||||
/// recovery loop's other warnings.
|
||||
///
|
||||
/// Both halves are gateway-supplied text on their way to a terminal: the oid comes
|
||||
/// out of a manifest fetched from a caller-chosen Arweave gateway, and a transport
|
||||
/// error carries the URL the same manifest chose. So the whole line is defanged and
|
||||
/// length-capped, like every other node/gateway string this crate prints.
|
||||
///
|
||||
/// Under `cfg(test)` the line is also mirrored into a per-thread buffer, so a test
|
||||
/// can assert the loop actually says what it skipped rather than only that it
|
||||
/// returned nothing.
|
||||
fn warn_skip(oid: &str, why: &str) {
|
||||
emit_warning(&format!(
|
||||
"warning: could not fetch encrypted blob {oid}: {why}; skipping"
|
||||
));
|
||||
}
|
||||
|
||||
/// The same report for a manifest rather than a blob. The manifest is one step
|
||||
/// earlier in the same recovery: losing it silently means every blob it would have
|
||||
/// named is missing with no reason given anywhere.
|
||||
fn warn_skip_manifest(id: &str, why: &str) {
|
||||
emit_warning(&format!(
|
||||
"warning: could not fetch blob manifest {id}: {why}; skipping"
|
||||
));
|
||||
}
|
||||
|
||||
/// Sanitize a warning and write it, once.
|
||||
///
|
||||
/// The write goes to [`warn_sink`], which is stderr in a normal build and the tests'
|
||||
/// per-thread mirror under `cfg(test)`. That indirection is the point: the mirror
|
||||
/// used to sit BESIDE an `eprintln!`, so deleting the user-visible write left every
|
||||
/// assertion on the mirror green and the shipped behaviour could be removed with the
|
||||
/// tests unchanged. There is one write now, and the tests observe it.
|
||||
fn emit_warning(line: &str) {
|
||||
use std::io::Write;
|
||||
let line = sanitize_node_msg(line);
|
||||
let _ = writeln!(warn_sink(), "{line}");
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn warn_sink() -> impl std::io::Write {
|
||||
std::io::stderr()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn warn_sink() -> impl std::io::Write {
|
||||
tests::WarnMirror
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct CloneArgs {
|
||||
/// Repo to clone: gitlawb://<owner_did>/<name> or <owner>/<name>.
|
||||
@@ -361,25 +312,10 @@ async fn recover_encrypted_blobs(
|
||||
.await
|
||||
{
|
||||
Ok(r) if r.status().is_success() => r,
|
||||
// The node path has the same silent exit the gateway path had: a 403, a
|
||||
// 404, or a dead connection all reached the caller as "blob not
|
||||
// recoverable" with no reason attached. One unreachable blob still must
|
||||
// not end the recovery of the rest, so it warns and moves on.
|
||||
Ok(r) => {
|
||||
warn_skip(oid, &format!("node returned {}", r.status()));
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
warn_skip(oid, &format!("node request failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let envelope = match env_resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
warn_skip(oid, &format!("reading the envelope failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
let Ok(envelope) = env_resp.bytes().await else {
|
||||
continue;
|
||||
};
|
||||
let plaintext = match open_blob(&envelope, keypair) {
|
||||
Ok(p) => p,
|
||||
@@ -706,14 +642,7 @@ async fn recover_from_arweave(
|
||||
for r in refs {
|
||||
let m = match client.get(format!("{ag}/{}", r.id)).send().await {
|
||||
Ok(resp) if resp.status().is_success() => resp,
|
||||
Ok(resp) => {
|
||||
warn_skip_manifest(&r.id, &format!("gateway returned {}", resp.status()));
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
warn_skip_manifest(&r.id, &format!("gateway request failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
if let Ok(parsed) = m.json::<Manifest>().await {
|
||||
manifests.push((parsed, r.height));
|
||||
@@ -755,31 +684,10 @@ async fn recover_from_arweave(
|
||||
}
|
||||
let env_resp = match client.get(format!("{ig}/ipfs/{cid}")).send().await {
|
||||
Ok(r) if r.status().is_success() => r,
|
||||
// Every other outcome used to leave through a bare `continue`, so a
|
||||
// gateway that answered 503, 404, or nothing at all was reported to the
|
||||
// caller as "blob not recoverable" with no reason attached. This is the
|
||||
// second in-repo client of GET /ipfs/{cid} and it has no resume ladder,
|
||||
// so saying what happened is all the recourse there is. It still skips to
|
||||
// the next candidate either way: one unreachable blob must not end the
|
||||
// recovery of the rest.
|
||||
Ok(r) => {
|
||||
warn_skip(&oid, &format!("gateway returned {}", r.status()));
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
warn_skip(&oid, &format!("gateway request failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
// A body that dies part-way through is the same mid-read failure the capped
|
||||
// read exists to stop rendering as silence, and it sits INSIDE the loop whose
|
||||
// status arms were already fixed.
|
||||
let envelope = match env_resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
warn_skip(&oid, &format!("reading the envelope failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
let Ok(envelope) = env_resp.bytes().await else {
|
||||
continue;
|
||||
};
|
||||
// open_blob succeeds only if this caller is a recipient: this is the
|
||||
// authorization gate (no node, no DID check needed).
|
||||
@@ -893,42 +801,9 @@ pub async fn run(args: CloneArgs) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
thread_local! {
|
||||
/// Test-visible copy of the stderr warnings `warn_skip` emits.
|
||||
/// `#[tokio::test]` runs the future on the test's own thread, so a
|
||||
/// thread-local is enough.
|
||||
static WARNINGS: RefCell<String> = const { RefCell::new(String::new()) };
|
||||
}
|
||||
|
||||
/// The `cfg(test)` warning sink. `emit_warning` writes here instead of to
|
||||
/// stderr, so the assertions below observe the shipped write rather than a copy
|
||||
/// made beside it: delete that write and they go red.
|
||||
pub(super) struct WarnMirror;
|
||||
|
||||
impl std::io::Write for WarnMirror {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let text = String::from_utf8_lossy(buf).into_owned();
|
||||
WARNINGS.with(|w| w.borrow_mut().push_str(&text));
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn reset_warnings() {
|
||||
WARNINGS.with(|w| w.borrow_mut().clear());
|
||||
}
|
||||
|
||||
fn warnings() -> String {
|
||||
WARNINGS.with(|w| w.borrow().clone())
|
||||
}
|
||||
|
||||
fn g(args: &[&str], dir: &Path) {
|
||||
assert!(Command::new("git")
|
||||
.args(args)
|
||||
@@ -1380,132 +1255,6 @@ mod tests {
|
||||
assert_eq!(a.get("o1").map(String::as_str), Some("cidTS"));
|
||||
}
|
||||
|
||||
/// A gateway that refuses one blob must SAY so, and must not take the rest of the
|
||||
/// recovery down with it.
|
||||
///
|
||||
/// The IPFS fetch used to leave through a bare `_ => continue` on every
|
||||
/// non-success, so a 503 (the truncation status a tuned node makes more likely),
|
||||
/// a 404, and a dead connection all reached the caller as the same silent "blob
|
||||
/// not recoverable". Two withheld blobs here: the gateway answers 503 for the
|
||||
/// first and serves the second. The recovered path proves the loop continued; the
|
||||
/// warning proves the skip was reported and names both the object and the status.
|
||||
#[tokio::test]
|
||||
async fn recover_from_arweave_reports_a_refusing_gateway_and_continues() {
|
||||
use gitlawb_core::encrypt::seal_blob;
|
||||
use gitlawb_core::identity::Keypair;
|
||||
|
||||
reset_warnings();
|
||||
let (td, url) = bare_remote(&[
|
||||
("public/a.txt", b"pub\n"),
|
||||
("secret/b.txt", b"SECRET B\n"),
|
||||
("secret/c.txt", b"SECRET C\n"),
|
||||
]);
|
||||
let dest = td.path().join("dest");
|
||||
let bare = url.strip_prefix("file://").unwrap();
|
||||
assert!(Command::new("git")
|
||||
.args(["-C", bare, "config", "uploadpack.allowFilter", "true"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success());
|
||||
setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap();
|
||||
|
||||
let oid_of = |path: &str| {
|
||||
let out = Command::new("git")
|
||||
.args([
|
||||
"-C",
|
||||
dest.to_str().unwrap(),
|
||||
"rev-parse",
|
||||
&format!("HEAD:{path}"),
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
};
|
||||
let refused_oid = oid_of("secret/b.txt");
|
||||
let served_oid = oid_of("secret/c.txt");
|
||||
|
||||
// Origin death, so recovery has to go through the gateways.
|
||||
std::fs::remove_dir_all(bare).unwrap();
|
||||
|
||||
let reader = Keypair::generate();
|
||||
let envelope = seal_blob(b"SECRET C\n", &[reader.verifying_key()]).unwrap();
|
||||
|
||||
let refused_cid = "cidrefused";
|
||||
let served_cid = "cidserved";
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _gql = server
|
||||
.mock("POST", "/graphql")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"TX1"}}]}}}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
let manifest_body = serde_json::json!({
|
||||
"timestamp": "2026-06-11T00:00:00Z",
|
||||
"blobs": [
|
||||
{ "oid": refused_oid, "cid": refused_cid },
|
||||
{ "oid": served_oid, "cid": served_cid },
|
||||
],
|
||||
})
|
||||
.to_string();
|
||||
let _tx = server
|
||||
.mock("GET", "/TX1")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(manifest_body)
|
||||
.create_async()
|
||||
.await;
|
||||
let refusal = server
|
||||
.mock("GET", format!("/ipfs/{refused_cid}").as_str())
|
||||
.with_status(503)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"error":"search_incomplete","message":"scan truncated"}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
let ok = server
|
||||
.mock("GET", format!("/ipfs/{served_cid}").as_str())
|
||||
.with_status(200)
|
||||
.with_body(envelope)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let paths = recover_from_arweave(
|
||||
&server.url(),
|
||||
&server.url(),
|
||||
"alice",
|
||||
"myrepo",
|
||||
&dest,
|
||||
&reader,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
refusal.assert_async().await;
|
||||
ok.assert_async().await;
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec!["secret/c.txt".to_string()],
|
||||
"a refused candidate must not stop the loop reaching the next one"
|
||||
);
|
||||
|
||||
let warnings = warnings();
|
||||
assert!(
|
||||
warnings.contains(&refused_oid),
|
||||
"the skip must name the object it could not fetch, got: {warnings}"
|
||||
);
|
||||
assert!(
|
||||
warnings.contains("503"),
|
||||
"the skip must name the gateway's status rather than failing silently, \
|
||||
got: {warnings}"
|
||||
);
|
||||
assert!(
|
||||
!warnings.contains(&served_oid),
|
||||
"the blob that was served must not be reported as skipped, got: {warnings}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Read-path end-to-end over a mocked Arweave + IPFS gateway: discover the
|
||||
/// manifest via GraphQL, fetch it, fetch the envelope, decrypt with the
|
||||
/// caller's key, and install the previously-withheld blob.
|
||||
|
||||
+11
-238
@@ -16,7 +16,6 @@ use std::path::PathBuf;
|
||||
use crate::http::NodeClient;
|
||||
|
||||
const PUBLIC_NODE: &str = "https://node.gitlawb.com";
|
||||
const GITHUB_API_BASE: &str = "https://api.github.com";
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct DoctorArgs {
|
||||
@@ -142,20 +141,18 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
|
||||
// ── 3. GITLAWB_NODE env var ───────────────────────────────────────────
|
||||
match std::env::var("GITLAWB_NODE") {
|
||||
// A loopback host is a legitimate setup (self-hosted node, dev
|
||||
// harness) — the connectivity check below fails loudly if it is not
|
||||
// actually reachable, so don't red-flag the configuration itself.
|
||||
Ok(v) if is_loopback_url(&v) => {
|
||||
checks.push(Check::pass(
|
||||
Ok(v) if !v.is_empty() && !v.contains("127.0.0.1") && !v.contains("localhost") => {
|
||||
checks.push(Check::pass("GITLAWB_NODE", v.to_string()));
|
||||
}
|
||||
Ok(v) if v.contains("127.0.0.1") || v.contains("localhost") => {
|
||||
checks.push(Check::fail(
|
||||
"GITLAWB_NODE",
|
||||
format!(
|
||||
"{v} (local node — intentional for self-hosting/dev; unset to target the public network)"
|
||||
"set to local address ({v}) — git push/clone will fail against remote nodes"
|
||||
),
|
||||
"export GITLAWB_NODE=https://node.gitlawb.com",
|
||||
));
|
||||
}
|
||||
Ok(v) if !v.is_empty() => {
|
||||
checks.push(Check::pass("GITLAWB_NODE", v.to_string()));
|
||||
}
|
||||
_ => {
|
||||
checks.push(Check::fail(
|
||||
"GITLAWB_NODE",
|
||||
@@ -245,15 +242,6 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
));
|
||||
}
|
||||
|
||||
// ── 5b. shell alias shadowing ─────────────────────────────────────────
|
||||
// oh-my-zsh's default `git` plugin aliases gl='git pull', which silently
|
||||
// shadows this binary in every interactive zsh — the classic symptom is
|
||||
// `gl` printing "fatal: not a git repository". Aliases beat PATH, so no
|
||||
// install method can fix it; the user's rc file has to unalias.
|
||||
if let Some(check) = check_shell_alias_shadowing(dirs::home_dir()) {
|
||||
checks.push(check);
|
||||
}
|
||||
|
||||
// ── 6. git ────────────────────────────────────────────────────────────
|
||||
match std::process::Command::new("git")
|
||||
.arg("--version")
|
||||
@@ -275,7 +263,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
|
||||
// ── 7. Version up to date ─────────────────────────────────────────────
|
||||
let current = env!("CARGO_PKG_VERSION");
|
||||
checks.push(check_version(current, GITHUB_API_BASE).await);
|
||||
checks.push(check_version(current).await);
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────
|
||||
for check in &checks {
|
||||
@@ -320,83 +308,6 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Check if a binary name exists anywhere on PATH.
|
||||
/// True when the rc file contains a real `unalias` command naming `gl` —
|
||||
/// not a comment, and not a longer word like `unalias global`. Ordering
|
||||
/// relative to oh-my-zsh loading is not modeled (an unalias placed before the
|
||||
/// plugin loads would be ineffective); acceptable slack for a warning check.
|
||||
fn rc_unaliases_gl(rc: &str) -> bool {
|
||||
rc.lines().any(|line| {
|
||||
let line = line.trim_start();
|
||||
if line.starts_with('#') {
|
||||
return false;
|
||||
}
|
||||
line.split([';', '&', '|']).any(|cmd| {
|
||||
// A trailing comment must not count: `unalias foo # gl`
|
||||
let cmd = cmd.split('#').next().unwrap_or("");
|
||||
let mut tokens = cmd.split_whitespace();
|
||||
tokens.next() == Some("unalias") && tokens.any(|t| t == "gl")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// True when the URL's host is exactly a loopback address. Substring checks
|
||||
/// misclassify hosts like `localhost.example` or URLs with "localhost" in the
|
||||
/// path, so parse and compare the actual host.
|
||||
fn is_loopback_url(value: &str) -> bool {
|
||||
reqwest::Url::parse(value)
|
||||
.ok()
|
||||
.and_then(|u| {
|
||||
u.host_str()
|
||||
.map(|h| h == "localhost" || h == "127.0.0.1" || h == "[::1]" || h == "::1")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Detect interactive-shell setups where an alias shadows `gl` (aliases beat
|
||||
/// PATH, so no install method can fix this). Best-effort heuristic over
|
||||
/// ~/.zshrc: an explicit `alias gl=`, or oh-my-zsh's `git` plugin (which
|
||||
/// ships gl='git pull'). Returns None when nothing suspicious is found or the
|
||||
/// rc file already contains an `unalias gl`.
|
||||
fn check_shell_alias_shadowing(home: Option<PathBuf>) -> Option<Check> {
|
||||
let home = home?;
|
||||
let rc = std::fs::read_to_string(home.join(".zshrc")).ok()?;
|
||||
if rc_unaliases_gl(&rc) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let explicit_alias = rc.lines().any(|l| l.trim_start().starts_with("alias gl="));
|
||||
// Single-line `plugins=(git ...)` is the overwhelmingly common form; a
|
||||
// multi-line plugins array slips past this heuristic, which is acceptable
|
||||
// for a warning-level check.
|
||||
let omz_git_plugin = home.join(".oh-my-zsh/plugins/git").exists()
|
||||
&& rc.lines().any(|l| {
|
||||
let l = l.trim_start();
|
||||
l.starts_with("plugins=")
|
||||
&& l.trim_start_matches("plugins=(")
|
||||
.trim_end_matches(')')
|
||||
.split_whitespace()
|
||||
.any(|p| p == "git")
|
||||
});
|
||||
|
||||
if explicit_alias || omz_git_plugin {
|
||||
let source = if explicit_alias {
|
||||
"~/.zshrc defines `alias gl=`"
|
||||
} else {
|
||||
"oh-my-zsh's git plugin aliases gl='git pull'"
|
||||
};
|
||||
Some(Check::warn(
|
||||
"shell alias",
|
||||
format!(
|
||||
"{source} — interactive shells run that instead of this binary \
|
||||
(symptom: `gl` prints \"fatal: not a git repository\")"
|
||||
),
|
||||
"echo 'unalias gl 2>/dev/null' >> ~/.zshrc && source ~/.zshrc (must come after oh-my-zsh loads)",
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn which_in_path(name: &str) -> bool {
|
||||
std::env::var_os("PATH")
|
||||
.map(|paths| {
|
||||
@@ -408,9 +319,8 @@ fn which_in_path(name: &str) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Fetch the latest release tag from Gitlawb/node (the actual release repo — see install.sh's
|
||||
/// `GITLAWB_RELEASE_REPO` default) and compare to current version.
|
||||
async fn check_version(current: &'static str, github_api_base: &str) -> Check {
|
||||
/// Fetch the latest release tag from gitlawb/releases and compare to current version.
|
||||
async fn check_version(current: &'static str) -> Check {
|
||||
let client = match reqwest::Client::builder()
|
||||
.user_agent(format!("gl/{current}"))
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
@@ -421,9 +331,7 @@ async fn check_version(current: &'static str, github_api_base: &str) -> Check {
|
||||
};
|
||||
|
||||
let resp = match client
|
||||
.get(format!(
|
||||
"{github_api_base}/repos/Gitlawb/node/releases/latest"
|
||||
))
|
||||
.get("https://api.github.com/repos/gitlawb/releases/releases/latest")
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
@@ -431,13 +339,6 @@ async fn check_version(current: &'static str, github_api_base: &str) -> Check {
|
||||
Err(_) => return Check::pass("version", format!("v{current} (offline — could not check)")),
|
||||
};
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Check::pass(
|
||||
"version",
|
||||
format!("v{current} (GitHub API returned HTTP {})", resp.status()),
|
||||
);
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Check::pass("version", format!("v{current} (invalid response)")),
|
||||
@@ -481,88 +382,6 @@ fn is_newer(latest: &str, current: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fake_home(zshrc: Option<&str>, with_omz_git: bool) -> tempfile::TempDir {
|
||||
let home = tempfile::TempDir::new().unwrap();
|
||||
if let Some(rc) = zshrc {
|
||||
std::fs::write(home.path().join(".zshrc"), rc).unwrap();
|
||||
}
|
||||
if with_omz_git {
|
||||
std::fs::create_dir_all(home.path().join(".oh-my-zsh/plugins/git")).unwrap();
|
||||
}
|
||||
home
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_shadowing_flags_omz_git_plugin() {
|
||||
let home = fake_home(Some("plugins=(git z)\nsource $ZSH/oh-my-zsh.sh\n"), true);
|
||||
let check = check_shell_alias_shadowing(Some(home.path().to_path_buf()));
|
||||
assert!(check.is_some(), "omz git plugin without unalias must warn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_shadowing_flags_explicit_alias() {
|
||||
let home = fake_home(Some("alias gl='git pull'\n"), false);
|
||||
assert!(check_shell_alias_shadowing(Some(home.path().to_path_buf())).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_shadowing_silent_when_unaliased() {
|
||||
let home = fake_home(
|
||||
Some("plugins=(git z)\nsource $ZSH/oh-my-zsh.sh\nunalias gl 2>/dev/null\n"),
|
||||
true,
|
||||
);
|
||||
assert!(check_shell_alias_shadowing(Some(home.path().to_path_buf())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_shadowing_ignores_fake_unaliases() {
|
||||
// None of these actually free `gl` — the warning must survive them.
|
||||
for rc in [
|
||||
"plugins=(git)\n# unalias gl\n", // commented out
|
||||
"plugins=(git)\nunalias global\n", // longer word
|
||||
"plugins=(git)\nunalias foo # gl\n", // gl only in a comment
|
||||
"plugins=(git)\necho unalias-gl-later\n", // not an unalias command
|
||||
] {
|
||||
let home = fake_home(Some(rc), true);
|
||||
assert!(
|
||||
check_shell_alias_shadowing(Some(home.path().to_path_buf())).is_some(),
|
||||
"must still warn for rc: {rc:?}"
|
||||
);
|
||||
}
|
||||
// Real unalias forms that do free it — all must silence the warning.
|
||||
for rc in [
|
||||
"plugins=(git)\nunalias gl\n",
|
||||
"plugins=(git)\nunalias gl 2>/dev/null\n",
|
||||
"plugins=(git)\ntrue; unalias gl\n",
|
||||
"plugins=(git)\nunalias glog gl gst\n",
|
||||
] {
|
||||
let home = fake_home(Some(rc), true);
|
||||
assert!(
|
||||
check_shell_alias_shadowing(Some(home.path().to_path_buf())).is_none(),
|
||||
"must be silent for rc: {rc:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_url_detection_is_host_exact() {
|
||||
assert!(is_loopback_url("http://127.0.0.1:7545"));
|
||||
assert!(is_loopback_url("http://localhost:7545"));
|
||||
assert!(is_loopback_url("http://[::1]:7545"));
|
||||
assert!(!is_loopback_url("https://localhost.example"));
|
||||
assert!(!is_loopback_url("https://node.gitlawb.com/localhost"));
|
||||
assert!(!is_loopback_url("not a url"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_shadowing_silent_without_signals() {
|
||||
let home = fake_home(Some("plugins=(z)\nexport EDITOR=vim\n"), false);
|
||||
assert!(check_shell_alias_shadowing(Some(home.path().to_path_buf())).is_none());
|
||||
let no_rc = fake_home(None, false);
|
||||
assert!(check_shell_alias_shadowing(Some(no_rc.path().to_path_buf())).is_none());
|
||||
assert!(check_shell_alias_shadowing(None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_newer_minor_bump() {
|
||||
assert!(is_newer("0.2.0", "0.1.0"));
|
||||
@@ -598,50 +417,4 @@ mod tests {
|
||||
fn test_which_in_path_missing_binary() {
|
||||
assert!(!which_in_path("this-binary-does-not-exist-gl-test-12345"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_check_version_queries_gitlawb_node_releases() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", "/repos/Gitlawb/node/releases/latest")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tag_name":"v9.9.9"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let check = check_version("0.1.0", &server.url()).await;
|
||||
assert!(matches!(check.state, CheckState::Warn));
|
||||
assert!(check.detail.contains("v9.9.9"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_check_version_up_to_date() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", "/repos/Gitlawb/node/releases/latest")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"tag_name":"v0.1.0"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let check = check_version("0.1.0", &server.url()).await;
|
||||
assert!(matches!(check.state, CheckState::Ok));
|
||||
assert!(check.detail.contains("up to date"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_check_version_http_error() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", "/repos/Gitlawb/node/releases/latest")
|
||||
.with_status(403)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let check = check_version("0.1.0", &server.url()).await;
|
||||
assert!(matches!(check.state, CheckState::Ok));
|
||||
assert!(check.detail.contains("GitHub API returned HTTP 403"));
|
||||
}
|
||||
}
|
||||
+1
-699
@@ -15,47 +15,6 @@ use icaptcha_client::IcaptchaCfg;
|
||||
/// (absorbs proof expiry / first-seen replay).
|
||||
const MAX_ICAPTCHA_RETRIES: usize = 2;
|
||||
|
||||
/// Total request timeout: from the start of connecting through the end of the
|
||||
/// response body, so it bounds a slow download and not just a slow handshake.
|
||||
const TOTAL_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// Follow a redirect only when it stays on the origin that issued it AND re-issues the
|
||||
/// identical request-target, and only for as long as the chain bound allows.
|
||||
///
|
||||
/// The decision itself is [`gitlawb_core::redirect::may_follow`], shared with
|
||||
/// `git-remote-gitlawb` so the two signing clients cannot drift apart on it. Refusal
|
||||
/// is `stop`, not `error`: the 3xx comes back as an ordinary response and each caller
|
||||
/// reports it through the status path it already has.
|
||||
///
|
||||
/// `Policy::custom` replaces reqwest's built-in limit, so the chain bound is restated
|
||||
/// here. Same-origin redirects can cycle, and this is what stops a node answering 302
|
||||
/// to itself from being followed indefinitely. It is not what makes the request
|
||||
/// finite: `.timeout(...)` on the same builder is a TOTAL request timeout covering the
|
||||
/// whole chain, so without this bound the worst case is a 30 second spin, not an
|
||||
/// endless one. The bound is what keeps that spin from costing the node a request per
|
||||
/// round trip for the full 30 seconds.
|
||||
///
|
||||
/// `>` and not `>=`: reqwest pushes the redirecting URL onto `previous` before
|
||||
/// consulting the policy, so on the first redirect `previous.len()` is already 1, and
|
||||
/// `>=` would permit `MAX_REDIRECTS - 1` follows. `Policy::limited(max)` refuses at
|
||||
/// `previous.len() > max`, and matching it is the point of reusing its value.
|
||||
fn same_origin_redirect(attempt: reqwest::redirect::Attempt<'_>) -> reqwest::redirect::Action {
|
||||
let Some(previous) = attempt.previous().last() else {
|
||||
// No previous URL to compare against. Unreachable through reqwest, which
|
||||
// pushes the redirecting URL before consulting the policy, but the safe
|
||||
// reading of "cannot prove same-origin" is to refuse.
|
||||
return attempt.stop();
|
||||
};
|
||||
if attempt.previous().len() > gitlawb_core::redirect::MAX_REDIRECTS {
|
||||
return attempt.stop();
|
||||
}
|
||||
if gitlawb_core::redirect::may_follow(previous, attempt.url()) {
|
||||
attempt.follow()
|
||||
} else {
|
||||
attempt.stop()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NodeClient {
|
||||
inner: reqwest::Client,
|
||||
pub node_url: String,
|
||||
@@ -64,20 +23,8 @@ pub struct NodeClient {
|
||||
|
||||
impl NodeClient {
|
||||
pub fn new(node_url: impl Into<String>, keypair: Option<Keypair>) -> Self {
|
||||
Self::with_timeout(node_url, keypair, TOTAL_REQUEST_TIMEOUT)
|
||||
}
|
||||
|
||||
/// `new` with the total request timeout as a parameter, so a test can drive the
|
||||
/// timeout's behaviour without waiting out the shipped value. `new` supplies the
|
||||
/// shipped one, which is what makes the scaled-down test cover the real client.
|
||||
fn with_timeout(
|
||||
node_url: impl Into<String>,
|
||||
keypair: Option<Keypair>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Self {
|
||||
let inner = reqwest::Client::builder()
|
||||
.timeout(timeout)
|
||||
.redirect(reqwest::redirect::Policy::custom(same_origin_redirect))
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.user_agent(format!("gl/{} gitlawb-cli", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.expect("failed to build HTTP client");
|
||||
@@ -125,23 +72,6 @@ impl NodeClient {
|
||||
req.send().await.with_context(|| format!("GET {url}"))
|
||||
}
|
||||
|
||||
/// GET that signs when an identity keypair is present and falls back to an
|
||||
/// anonymous GET otherwise — for read-visibility endpoints, where a public
|
||||
/// repo is readable anonymously but a private repo requires the owner/reader
|
||||
/// to be authenticated. Mirrors the conditional signing of post/put/delete.
|
||||
pub async fn get_maybe_signed(&self, path: &str) -> Result<reqwest::Response> {
|
||||
let url = format!("{}{}", self.node_url, path);
|
||||
let mut req = self.inner.get(&url);
|
||||
if let Some(kp) = &self.keypair {
|
||||
let signed = sign_request(kp, "GET", path, b"");
|
||||
req = req
|
||||
.header("Content-Digest", signed.content_digest)
|
||||
.header("Signature-Input", signed.signature_input)
|
||||
.header("Signature", signed.signature);
|
||||
}
|
||||
req.send().await.with_context(|| format!("GET {url}"))
|
||||
}
|
||||
|
||||
/// POST with JSON body + RFC 9421 signing + transparent iCaptcha solve/retry.
|
||||
pub async fn post(&self, path: &str, body: &[u8]) -> Result<reqwest::Response> {
|
||||
self.send_signed("POST", path, body).await
|
||||
@@ -256,79 +186,6 @@ async fn obtain_proof(cfg: IcaptchaCfg) -> Result<String> {
|
||||
.context("iCaptcha solver task panicked")?
|
||||
}
|
||||
|
||||
/// What a capped body read produced. `text` is the bytes that arrived; the two flags
|
||||
/// say why the read stopped where it did, which a caller that CLASSIFIES on the body
|
||||
/// cannot work out from the text alone.
|
||||
pub(crate) struct CappedBody {
|
||||
/// The bytes read, lossily decoded.
|
||||
pub(crate) text: String,
|
||||
/// The cap cut the body short.
|
||||
pub(crate) truncated: bool,
|
||||
/// A chunk read FAILED part-way through, so the body is not merely short, it is
|
||||
/// unfinished and the node may have had more to say.
|
||||
pub(crate) read_failed: bool,
|
||||
}
|
||||
|
||||
/// Read at most `cap` bytes of a response body. Bounds the allocation from a
|
||||
/// hostile or broken node returning a huge error body — the display is capped
|
||||
/// separately, but the read itself must not be unbounded (INV-6, read half).
|
||||
///
|
||||
/// `truncated` reports whether the cap cut the body short. A caller that CLASSIFIES
|
||||
/// on the body needs it: a cut body fails JSON parse, and a parse failure is
|
||||
/// indistinguishable from a node that sent no code at all, so without this flag an
|
||||
/// oversized body silently picks a different arm.
|
||||
///
|
||||
/// `read_failed` reports the other way a body can end early. A mid-body read error
|
||||
/// used to leave through the same exit as a clean end of stream, so a 500 whose body
|
||||
/// died in transit surfaced as an empty message and the caller was told
|
||||
/// `node returned 500: ` with nothing after the colon. That is a report of what the
|
||||
/// node said, and the node never got to say it.
|
||||
pub(crate) async fn read_body_capped(mut resp: reqwest::Response, cap: usize) -> CappedBody {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let mut truncated = false;
|
||||
let mut read_failed = false;
|
||||
while buf.len() < cap {
|
||||
match resp.chunk().await {
|
||||
Ok(Some(chunk)) => {
|
||||
let take = (cap - buf.len()).min(chunk.len());
|
||||
buf.extend_from_slice(&chunk[..take]);
|
||||
if take < chunk.len() {
|
||||
truncated = true;
|
||||
break; // hit the cap mid-chunk
|
||||
}
|
||||
}
|
||||
Ok(None) => break, // clean end of body
|
||||
Err(_) => {
|
||||
read_failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A body that lands exactly on the cap may or may not have more behind it;
|
||||
// report it as cut, since the classification that follows cannot tell either.
|
||||
if buf.len() >= cap {
|
||||
truncated = true;
|
||||
}
|
||||
CappedBody {
|
||||
text: String::from_utf8_lossy(&buf).into_owned(),
|
||||
truncated,
|
||||
read_failed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip terminal-dangerous characters from (and cap the length of) a
|
||||
/// node-supplied error string before surfacing it. The node a caller talks to
|
||||
/// could be hostile and embed escape sequences in its error body; those must not
|
||||
/// reach the terminal verbatim (INV-6). We drop the C0/C1 control bytes (which
|
||||
/// defangs ANSI/OSC escapes) AND the Unicode bidi/format controls (which
|
||||
/// `char::is_control` does not cover — they can reorder the displayed line).
|
||||
pub(crate) fn sanitize_node_msg(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| !c.is_control() && !gitlawb_core::sanitize::is_bidi_format(*c))
|
||||
.take(200)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -713,559 +570,4 @@ mod tests {
|
||||
ic.challenge.assert();
|
||||
ic.answer.assert();
|
||||
}
|
||||
|
||||
// ── redirect policy ─────────────────────────────────────────────────
|
||||
|
||||
/// The signed headers must not survive a redirect off the node's origin.
|
||||
///
|
||||
/// reqwest strips only `Authorization`, `Cookie`, `Proxy-Authorization` and
|
||||
/// `WWW-Authenticate` across hosts, so `Signature` and `Signature-Input` used to
|
||||
/// ride a 302 straight to whatever origin the node named. The signature binds
|
||||
/// `@method`, `@path` and `content-digest` and nothing about the authority, so the
|
||||
/// receiving host holds a credential that reads path-scoped objects as the caller
|
||||
/// at any node until the clock-skew window closes.
|
||||
///
|
||||
/// Two mockito servers are two ports on one host, which is exactly the boundary
|
||||
/// this policy draws (and the one reqwest's own header stripping draws). The
|
||||
/// second server answers everything and expects nothing: a followed redirect
|
||||
/// fails the expectation whether or not the signature came with it. MUTATION
|
||||
/// (RED): drop the `.redirect(...)` line and the second server is hit.
|
||||
#[tokio::test]
|
||||
async fn cross_origin_redirect_is_not_followed() {
|
||||
let mut elsewhere = Server::new_async().await;
|
||||
let never = elsewhere
|
||||
.mock("GET", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_body("bytes from the redirect target")
|
||||
.expect(0)
|
||||
.create_async()
|
||||
.await;
|
||||
let signature_seen = elsewhere
|
||||
.mock("GET", mockito::Matcher::Any)
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.expect(0)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let mut node = Server::new_async().await;
|
||||
let bounce = node
|
||||
.mock("GET", "/api/v1/thing")
|
||||
.with_status(302)
|
||||
.with_header("location", &format!("{}/api/v1/thing", elsewhere.url()))
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let client = NodeClient::new(node.url(), Some(test_keypair()));
|
||||
let resp = client.get_signed("/api/v1/thing").await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
302,
|
||||
"a refused redirect stops rather than errors, so the caller sees the 3xx \
|
||||
and reports it through the status path it already has"
|
||||
);
|
||||
let body = resp.text().await.unwrap();
|
||||
assert!(
|
||||
!body.contains("bytes from the redirect target"),
|
||||
"the redirect target's bytes must never reach the caller, got: {body}"
|
||||
);
|
||||
bounce.assert_async().await;
|
||||
never.assert_async().await;
|
||||
signature_seen.assert_async().await;
|
||||
}
|
||||
|
||||
/// A node redirecting to itself is same-origin, so the origin predicate follows it
|
||||
/// every time and only the chain bound ends the loop. Deleting the bound left the
|
||||
/// whole suite green, because nothing here had ever built a cycle.
|
||||
///
|
||||
/// It has a second job now. A redirect back to the identical path and query is the
|
||||
/// only same-origin hop the predicate still follows, so the eleven hits below are
|
||||
/// also this crate's executed proof that such a hop IS followed. The old positive
|
||||
/// fixture drove a trailing-slash rewrite, which the request-target rule refuses,
|
||||
/// and an http-to-https upgrade cannot be mocked over mockito's plain http.
|
||||
///
|
||||
/// The route answers 301 pointing back at itself. Bounded, the handler is hit
|
||||
/// once for the original request plus `MAX_REDIRECTS` follows and the call returns
|
||||
/// the 301 (a refused redirect stops rather than errors). Unbounded, it runs until
|
||||
/// the client's total request timeout cuts it off, which is a 30 second spin at the
|
||||
/// shipped value and a request per round trip for the node.
|
||||
///
|
||||
/// MUTATION (RED): delete the `previous().len()` check.
|
||||
#[tokio::test]
|
||||
async fn a_self_redirect_stops_at_the_chain_bound() {
|
||||
let mut node = Server::new_async().await;
|
||||
let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let h = hits.clone();
|
||||
let loop_route = node
|
||||
.mock("GET", "/api/v1/loop")
|
||||
.with_status(301)
|
||||
.with_header("location", "/api/v1/loop")
|
||||
.with_body_from_request(move |_req| {
|
||||
h.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Vec::new()
|
||||
})
|
||||
.expect_at_least(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let client = NodeClient::with_timeout(
|
||||
node.url(),
|
||||
Some(test_keypair()),
|
||||
std::time::Duration::from_secs(5),
|
||||
);
|
||||
let resp = client
|
||||
.get_signed("/api/v1/loop")
|
||||
.await
|
||||
.expect("the bound must end the chain, not the timeout");
|
||||
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
301,
|
||||
"the chain ends by refusing the next hop, so the last 3xx is what comes back"
|
||||
);
|
||||
assert_eq!(
|
||||
hits.load(std::sync::atomic::Ordering::SeqCst),
|
||||
gitlawb_core::redirect::MAX_REDIRECTS + 1,
|
||||
"one original request plus MAX_REDIRECTS follows, matching what \
|
||||
Policy::limited(MAX_REDIRECTS) would have permitted"
|
||||
);
|
||||
loop_route.assert_async().await;
|
||||
}
|
||||
|
||||
/// A same-origin hop that REWRITES the request-target is refused, even though the
|
||||
/// origin never changes.
|
||||
///
|
||||
/// The signature binds `@path` as the literal path-and-query the client signed, and
|
||||
/// the node rebuilds it from the URI it received. A `/api/v1/thing` to
|
||||
/// `/api/v1/thing/` bounce therefore presents a signature over a target the node
|
||||
/// never saw, and every signed read behind such a proxy 401s. Refusing the hop
|
||||
/// hands the caller the 3xx that names what happened instead.
|
||||
///
|
||||
/// The target mock expects zero hits and is asserted: mockito only checks
|
||||
/// `.expect(N)` when `.assert()` runs, so an unbound or unasserted mock passes
|
||||
/// vacuously.
|
||||
#[tokio::test]
|
||||
async fn same_origin_path_changing_redirect_is_refused() {
|
||||
let mut node = Server::new_async().await;
|
||||
let bounce = node
|
||||
.mock("GET", "/api/v1/thing")
|
||||
.with_status(301)
|
||||
.with_header("location", "/api/v1/thing/")
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
let target = node
|
||||
.mock("GET", "/api/v1/thing/")
|
||||
.with_status(200)
|
||||
.with_body("bytes from the rewritten target")
|
||||
.expect(0)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let client = NodeClient::new(node.url(), Some(test_keypair()));
|
||||
let resp = client.get_signed("/api/v1/thing").await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
301,
|
||||
"a refused redirect stops rather than errors, so the caller sees the 3xx \
|
||||
and reports it through the status path it already has"
|
||||
);
|
||||
let body = resp.text().await.unwrap();
|
||||
assert!(
|
||||
!body.contains("bytes from the rewritten target"),
|
||||
"the rewritten target's bytes must never reach the caller, got: {body}"
|
||||
);
|
||||
bounce.assert_async().await;
|
||||
target.assert_async().await;
|
||||
}
|
||||
|
||||
// ── the node's own verification, run over what the client actually sent ──
|
||||
|
||||
/// What the verifying mock made of a request that reached it.
|
||||
///
|
||||
/// The empty slot (`None`) is its own state and means the mock was never hit at
|
||||
/// all, which is what the refusal test asserts. It must stay distinguishable from
|
||||
/// [`Verdict::WrongIdentity`], because "nobody verified anything" and "something
|
||||
/// verified against the wrong key" are opposite findings.
|
||||
///
|
||||
/// The payloads are read through `Debug` in the assertion messages and nowhere
|
||||
/// else, which the dead-code pass does not count; they carry the detail that makes
|
||||
/// a failure legible, so they stay.
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum Verdict {
|
||||
/// The chain accepted the signature AND the key it resolved is the test's DID.
|
||||
Accepted,
|
||||
/// The chain refused it. Carries the error so a failure reads as the actual
|
||||
/// rejection rather than a bare hit count.
|
||||
Rejected(String),
|
||||
/// The chain accepted a signature made by somebody else. A key resolved from
|
||||
/// the parsed `key_id` is read out of the artifact under verification, so an
|
||||
/// accept on it alone proves consistency, never authenticity.
|
||||
WrongIdentity { expected: String, got: String },
|
||||
}
|
||||
|
||||
/// The node's `require_signature` verification, over a request this crate did not
|
||||
/// build: parse the headers, recompute the content-digest from the body, rebuild
|
||||
/// the signing string over `@method`/`@path`/`content-digest`, Ed25519-verify.
|
||||
/// Returns the DID the signature resolved to, so a caller can pin the identity.
|
||||
///
|
||||
/// A hand-copy of its twin in `crates/git-remote-gitlawb/src/main.rs`, which gl
|
||||
/// cannot import (`git-remote-gitlawb` is a binary crate and this is its test
|
||||
/// module). Keep the two textually identical apart from the mockito seam around
|
||||
/// them, so an edit to one is visibly an edit to both.
|
||||
///
|
||||
/// The production verifier both copies mirror is `crate::auth::require_signature` in
|
||||
/// `crates/gitlawb-node/src/auth/mod.rs`. This is a re-implementation, not a call, so
|
||||
/// an edit to that middleware has to land here too: otherwise the copies drift and
|
||||
/// this test keeps passing against a rule the node has stopped applying.
|
||||
///
|
||||
/// It asserts internally, which is deliberate but constrains its callers: inside
|
||||
/// `with_body_from_request` those assertions fire on the server thread and reach
|
||||
/// the client as a transport error, not as a recorded verdict. So the identity
|
||||
/// check lives in the caller as a [`Verdict`] variant, never as an assert in here.
|
||||
fn node_verifies(
|
||||
method: &str,
|
||||
path_and_query: &str,
|
||||
body: &[u8],
|
||||
sig_input: &str,
|
||||
sig_header: &str,
|
||||
content_digest: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
use gitlawb_core::http_sig::{build_signing_string, compute_content_digest, HttpSignature};
|
||||
use gitlawb_core::identity::verify;
|
||||
use std::collections::HashMap;
|
||||
|
||||
let sig = HttpSignature::parse(sig_input, sig_header)?;
|
||||
sig.check_created()?;
|
||||
assert!(
|
||||
sig.missing_components().is_empty(),
|
||||
"signature must cover all required components"
|
||||
);
|
||||
assert_eq!(sig.alg, "ed25519");
|
||||
assert_eq!(
|
||||
content_digest,
|
||||
compute_content_digest(body),
|
||||
"content-digest must match the body"
|
||||
);
|
||||
let vk = sig.key_id.to_verifying_key()?;
|
||||
let mut values = HashMap::new();
|
||||
values.insert("@method".to_string(), method.to_uppercase());
|
||||
values.insert("@path".to_string(), path_and_query.to_string());
|
||||
values.insert("content-digest".to_string(), content_digest.to_string());
|
||||
let sig_params_value = sig_input.strip_prefix("sig1=").unwrap_or(sig_input);
|
||||
let components: Vec<&str> = sig.components.iter().map(String::as_str).collect();
|
||||
let signing_string = build_signing_string(&components, sig_params_value, &values)?;
|
||||
let sig_array: [u8; 64] = sig.signature_bytes.as_slice().try_into()?;
|
||||
verify(&vk, signing_string.as_bytes(), &sig_array)?;
|
||||
Ok(sig.key_id.to_string())
|
||||
}
|
||||
|
||||
/// Pull a header value off a received mockito request, or explain which one the
|
||||
/// client failed to send.
|
||||
fn received_header(req: &mockito::Request, name: &str) -> String {
|
||||
req.header(name)
|
||||
.first()
|
||||
.unwrap_or_else(|| panic!("the client sent no {name} header"))
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Run [`node_verifies`] over a GET that arrived at the mock and record what the
|
||||
/// node would have made of it, pinned to `expected_did`.
|
||||
fn record_get_verdict(
|
||||
req: &mockito::Request,
|
||||
expected_did: &str,
|
||||
slot: &std::sync::Arc<std::sync::Mutex<Option<Verdict>>>,
|
||||
) {
|
||||
let verdict = match node_verifies(
|
||||
"GET",
|
||||
req.path_and_query(),
|
||||
b"",
|
||||
&received_header(req, "signature-input"),
|
||||
&received_header(req, "signature"),
|
||||
&received_header(req, "content-digest"),
|
||||
) {
|
||||
Ok(did) if did == expected_did => Verdict::Accepted,
|
||||
Ok(did) => Verdict::WrongIdentity {
|
||||
expected: expected_did.to_string(),
|
||||
got: did,
|
||||
},
|
||||
Err(e) => Verdict::Rejected(e.to_string()),
|
||||
};
|
||||
*slot.lock().unwrap() = Some(verdict);
|
||||
}
|
||||
|
||||
/// The finding's repro, now a guard: a rewritten same-origin target must never
|
||||
/// receive the signature, and the proof is the node's own verification, not a hit
|
||||
/// count.
|
||||
///
|
||||
/// The target mock runs the full `require_signature` chain over the request it
|
||||
/// receives. Post-fix the hop is refused, so the slot stays empty. Pre-fix the hop
|
||||
/// is followed and the slot records the Ed25519 rejection of a signature made over
|
||||
/// `/api/v1/thing` and presented at `/api/v1/thing/`, which is the 401 an operator
|
||||
/// behind such a proxy actually sees. The verdict is asserted first, so a failure
|
||||
/// speaks about verification rather than about reachability.
|
||||
///
|
||||
/// Its paired positive control is
|
||||
/// `a_direct_signed_get_verifies_under_the_node_verifier`: without it, an empty
|
||||
/// slot would be satisfied just as well by a harness that can never record
|
||||
/// anything.
|
||||
#[tokio::test]
|
||||
async fn a_rewritten_target_never_receives_the_signature() {
|
||||
let kp = test_keypair();
|
||||
let expected_did = kp.did().to_string();
|
||||
let slot = std::sync::Arc::new(std::sync::Mutex::new(None::<Verdict>));
|
||||
|
||||
let mut node = Server::new_async().await;
|
||||
let bounce = node
|
||||
.mock("GET", "/api/v1/thing")
|
||||
.with_status(301)
|
||||
.with_header("location", "/api/v1/thing/")
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
let recorder = slot.clone();
|
||||
let did_for_target = expected_did.clone();
|
||||
let target = node
|
||||
.mock("GET", "/api/v1/thing/")
|
||||
.with_status(200)
|
||||
.with_body_from_request(move |req| {
|
||||
record_get_verdict(req, &did_for_target, &recorder);
|
||||
Vec::new()
|
||||
})
|
||||
.expect(0)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let client = NodeClient::new(node.url(), Some(kp));
|
||||
let resp = client.get_signed("/api/v1/thing").await.unwrap();
|
||||
|
||||
let verdict = slot.lock().unwrap().take();
|
||||
assert!(
|
||||
verdict.is_none(),
|
||||
"the node's own verifier must never see this request: the signature covers \
|
||||
/api/v1/thing and the rewritten target is /api/v1/thing/, so what arrives \
|
||||
there is a stale request-target; recorded verdict: {verdict:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
301,
|
||||
"the caller sees the 3xx, not the rewritten target's answer"
|
||||
);
|
||||
bounce.assert_async().await;
|
||||
target.assert_async().await;
|
||||
}
|
||||
|
||||
/// The positive control for the test above, and the proof that the client signs
|
||||
/// the query it sends.
|
||||
///
|
||||
/// A direct signed GET, no redirect anywhere, through the same verifying mock. The
|
||||
/// verdict must be `Accepted`, which is what makes the refusal test's empty slot
|
||||
/// attributable to the refusal rather than to a harness that cannot record. The
|
||||
/// path carries a query, so a client that signed the bare path would land here as
|
||||
/// `Rejected`.
|
||||
#[tokio::test]
|
||||
async fn a_direct_signed_get_verifies_under_the_node_verifier() {
|
||||
let kp = test_keypair();
|
||||
let expected_did = kp.did().to_string();
|
||||
let slot = std::sync::Arc::new(std::sync::Mutex::new(None::<Verdict>));
|
||||
|
||||
let mut node = Server::new_async().await;
|
||||
let recorder = slot.clone();
|
||||
let did_for_target = expected_did.clone();
|
||||
let route = node
|
||||
.mock("GET", "/api/v1/thing?x=1")
|
||||
.with_status(200)
|
||||
.with_body_from_request(move |req| {
|
||||
record_get_verdict(req, &did_for_target, &recorder);
|
||||
Vec::new()
|
||||
})
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let client = NodeClient::new(node.url(), Some(kp));
|
||||
let resp = client.get_signed("/api/v1/thing?x=1").await.unwrap();
|
||||
assert_eq!(resp.status(), 200);
|
||||
|
||||
let verdict = slot.lock().unwrap().take();
|
||||
assert!(
|
||||
matches!(verdict, Some(Verdict::Accepted)),
|
||||
"a direct signed GET must verify under the node's own chain and resolve to \
|
||||
{expected_did}, or the refusal test's empty slot proves nothing; recorded \
|
||||
verdict: {verdict:?}"
|
||||
);
|
||||
route.assert_async().await;
|
||||
}
|
||||
|
||||
// ── read_body_capped ────────────────────────────────────────────────
|
||||
|
||||
/// A body whose read FAILS mid-stream must be distinguishable from a body that
|
||||
/// ended. Both used to leave through the same `_ => break`, so a 500 whose body
|
||||
/// died in transit produced an empty message and the caller was told
|
||||
/// `node returned 500: ` with nothing after the colon.
|
||||
///
|
||||
/// The fixture is a raw listener that promises 64 bytes in `Content-Length`,
|
||||
/// writes 5, and closes. mockito cannot express that: it always completes the
|
||||
/// response it advertises. MUTATION (RED): restore the single `_ => break` arm
|
||||
/// (or hard-code `read_failed: false`) and the flag reads false.
|
||||
#[tokio::test]
|
||||
async fn read_body_capped_flags_a_mid_body_read_failure() {
|
||||
let addr = spawn_short_body_listener().await;
|
||||
let resp = reqwest::get(format!("http://{addr}/truncated"))
|
||||
.await
|
||||
.expect("headers arrive before the body is cut");
|
||||
let body = read_body_capped(resp, 8192).await;
|
||||
|
||||
assert!(
|
||||
body.read_failed,
|
||||
"a body cut off mid-stream must be reported as a failed read, not as a \
|
||||
body that ended: got {:?}",
|
||||
body.text
|
||||
);
|
||||
assert!(
|
||||
!body.truncated,
|
||||
"the cap did not cut this one; 5 bytes are nowhere near 8 KiB"
|
||||
);
|
||||
}
|
||||
|
||||
/// The must-not half: a body that ends cleanly must NOT be flagged, or the flag
|
||||
/// means nothing and every terminal starts claiming the node went quiet.
|
||||
#[tokio::test]
|
||||
async fn read_body_capped_does_not_flag_a_clean_body() {
|
||||
let mut server = Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", "/ok")
|
||||
.with_status(500)
|
||||
.with_body("node said this")
|
||||
.create_async()
|
||||
.await;
|
||||
let resp = reqwest::get(format!("{}/ok", server.url())).await.unwrap();
|
||||
let body = read_body_capped(resp, 8192).await;
|
||||
|
||||
assert_eq!(body.text, "node said this");
|
||||
assert!(!body.read_failed, "a complete body is not a failed read");
|
||||
assert!(!body.truncated, "a complete body is not a truncated one");
|
||||
}
|
||||
|
||||
/// Answer one request with headers promising more body than gets written, then
|
||||
/// close the connection. Returns the listener's address.
|
||||
async fn spawn_short_body_listener() -> std::net::SocketAddr {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut sock, _) = listener.accept().await.unwrap();
|
||||
let mut scratch = [0u8; 1024];
|
||||
let _ = sock.read(&mut scratch).await;
|
||||
let _ = sock
|
||||
.write_all(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 64\r\n\r\nshort")
|
||||
.await;
|
||||
let _ = sock.flush().await;
|
||||
// Drop closes the socket with 59 of the promised bytes never sent.
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
// ── total request timeout ───────────────────────────────────────────
|
||||
|
||||
/// The client's timeout is a TOTAL request timeout, so it bounds a download and
|
||||
/// not just the handshake. `gl ipfs get`'s documentation leans on exactly that:
|
||||
/// the wall-clock deadline covers the search and deliberately stops at the
|
||||
/// response headers, and this timeout is the only thing left bounding the body.
|
||||
///
|
||||
/// Driven at 250ms through `with_timeout`, the seam `new` itself calls with
|
||||
/// `TOTAL_REQUEST_TIMEOUT`, because a test at the shipped 30s has no place in this
|
||||
/// suite. What that costs is the value; what it proves is the SHAPE, which is the
|
||||
/// part in doubt: that the deadline keeps running once the headers have landed. A
|
||||
/// timeout that covered only the handshake would let this request hang until the
|
||||
/// listener gives up.
|
||||
#[tokio::test]
|
||||
async fn total_timeout_cuts_off_a_body_that_outruns_it() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut sock, _) = listener.accept().await.unwrap();
|
||||
let mut scratch = [0u8; 1024];
|
||||
let _ = sock.read(&mut scratch).await;
|
||||
// Headers land immediately, then the body stalls indefinitely.
|
||||
let _ = sock
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1024\r\n\r\nfirst")
|
||||
.await;
|
||||
let _ = sock.flush().await;
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
});
|
||||
|
||||
let client = NodeClient::with_timeout(
|
||||
format!("http://{addr}"),
|
||||
None,
|
||||
std::time::Duration::from_millis(250),
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
let resp = client.get("/slow").await.expect("headers arrive promptly");
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
200,
|
||||
"the stall is in the body, not the status"
|
||||
);
|
||||
let err = resp
|
||||
.bytes()
|
||||
.await
|
||||
.expect_err("a body still arriving past the total timeout must be cut off");
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(
|
||||
err.is_timeout(),
|
||||
"the body read must end in a timeout, got: {err}"
|
||||
);
|
||||
assert!(
|
||||
elapsed < std::time::Duration::from_secs(5),
|
||||
"the timeout must fire on its own schedule, not wait out the listener; \
|
||||
took {elapsed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shipped_client_uses_the_documented_total_timeout() {
|
||||
// The scaled-down test above proves the shape at 250ms. This pins the value
|
||||
// `new` actually ships, so the two together cover the documented behaviour.
|
||||
assert_eq!(TOTAL_REQUEST_TIMEOUT, std::time::Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_strips_controls_bidi_and_caps_length() {
|
||||
// C0 (ESC/BEL) and the Cf bidi override (U+202E) are both removed; the
|
||||
// printable text survives. (Note: a stripped ESC leaves any following
|
||||
// "[31m" as inert literal text — that is the point, so the input here
|
||||
// avoids that residue to keep the expectation unambiguous.)
|
||||
let out = sanitize_node_msg("a\u{1b}\u{07}b\u{202e}c");
|
||||
assert!(
|
||||
!out.chars().any(|c| c.is_control()),
|
||||
"control char leaked: {out:?}"
|
||||
);
|
||||
assert!(
|
||||
!out.contains('\u{202e}'),
|
||||
"RLO bidi override leaked: {out:?}"
|
||||
);
|
||||
assert_eq!(out, "abc");
|
||||
// Length is capped at 200 chars regardless of input size.
|
||||
let long = "x".repeat(250);
|
||||
assert_eq!(sanitize_node_msg(&long).chars().count(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_preserves_legitimate_and_rtl_text() {
|
||||
// Must not over-strip: a plain word, a genuine RTL SCRIPT letter (Arabic
|
||||
// U+0627, category Lo — NOT a format char), and ZWJ (U+200D, a legitimate
|
||||
// Cf char, e.g. emoji sequences) all survive. Guards the shared predicate
|
||||
// against being widened into a blanket Cf stripper.
|
||||
let out = sanitize_node_msg("ok \u{0627}\u{200D}b");
|
||||
assert_eq!(out, "ok \u{0627}\u{200D}b");
|
||||
}
|
||||
}
|
||||
+4
-52
@@ -38,23 +38,13 @@ pub async fn run(args: InitArgs) -> Result<()> {
|
||||
let git_dir = cwd.join(".git");
|
||||
if !git_dir.exists() {
|
||||
println!("Initializing git repository...");
|
||||
// -b main: the push flow targets `main`; without it a fresh repo uses
|
||||
// the user's init.defaultBranch (often `master`). Older git (<2.28)
|
||||
// lacks the flag, so fall back to a plain init.
|
||||
let status = std::process::Command::new("git")
|
||||
.args(["init", "-b", "main"])
|
||||
.args(["init"])
|
||||
.current_dir(&cwd)
|
||||
.status()
|
||||
.context("failed to run git init")?;
|
||||
if !status.success() {
|
||||
let status = std::process::Command::new("git")
|
||||
.args(["init"])
|
||||
.current_dir(&cwd)
|
||||
.status()
|
||||
.context("failed to run git init")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("git init failed");
|
||||
}
|
||||
anyhow::bail!("git init failed");
|
||||
}
|
||||
} else {
|
||||
println!("Git repository detected.");
|
||||
@@ -175,47 +165,9 @@ pub async fn run(args: InitArgs) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
// The hint must match the repo's actual state: with no commits yet, a bare
|
||||
// `git push` fails with "src refspec ... does not match any" — exactly the
|
||||
// trap a zero-to-push command must not set.
|
||||
let has_commits = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--verify", "HEAD"])
|
||||
.current_dir(&cwd)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
// symbolic-ref succeeds on a branch (including an unborn one) and fails
|
||||
// on a detached HEAD — where guessing "main" could push the wrong ref.
|
||||
let branch = std::process::Command::new("git")
|
||||
.args(["symbolic-ref", "--short", "HEAD"])
|
||||
.current_dir(&cwd)
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
println!();
|
||||
match (branch, has_commits) {
|
||||
(Some(branch), true) => {
|
||||
println!("Ready! Push with:");
|
||||
println!(" git push gitlawb {branch}");
|
||||
}
|
||||
(Some(branch), false) => {
|
||||
println!("Ready! Nothing is committed yet — commit, then push:");
|
||||
println!(" git add -A && git commit -m \"initial commit\"");
|
||||
println!(" git push gitlawb {branch}");
|
||||
}
|
||||
(None, _) => {
|
||||
println!("Ready! HEAD is detached — create or switch to a branch, then push:");
|
||||
println!(" git switch -c main");
|
||||
println!(" git push gitlawb main");
|
||||
}
|
||||
}
|
||||
println!("Ready! Push with:");
|
||||
println!(" git push gitlawb main");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+34
-1931
File diff suppressed because it is too large.
Load diff
+6
-207
@@ -932,33 +932,13 @@ async fn call_tool(
|
||||
|
||||
"webhook_list" => {
|
||||
let repo = args["repo"].as_str().context("missing 'repo'")?;
|
||||
// Owner-gated route: an explicit `owner` arg wins, otherwise default to
|
||||
// the signing keypair's short DID (NOT the node DID). The request is
|
||||
// signed by this keypair, so the path owner must match it or the node
|
||||
// returns 403/404.
|
||||
let owner = if let Some(o) = args.get("owner").and_then(|v| v.as_str()) {
|
||||
o.to_string()
|
||||
} else {
|
||||
let kp = keypair
|
||||
.as_ref()
|
||||
.context("no identity found — run `gl identity new` first")?;
|
||||
let did = kp.did().to_string();
|
||||
did.split(':').next_back().unwrap_or(&did).to_string()
|
||||
};
|
||||
// Owner-gated route: must be signed (get_signed), not a plain get().
|
||||
let resp = client
|
||||
.get_signed(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
|
||||
let owner = resolve_owner(&args, &client).await?;
|
||||
let resp: Value = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
|
||||
.await?
|
||||
.json()
|
||||
.await?;
|
||||
// Check the HTTP status before deserializing: a 401/403/404 JSON error
|
||||
// body (missing identity, wrong owner, private/deleted repo) must fail
|
||||
// the tool call, not be returned as a successful result.
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await?;
|
||||
if !status.is_success() {
|
||||
let msg = body["message"].as_str().unwrap_or("unknown error");
|
||||
anyhow::bail!("webhook_list failed ({status}): {msg}");
|
||||
}
|
||||
Ok(serde_json::to_string_pretty(&body)?)
|
||||
Ok(serde_json::to_string_pretty(&resp)?)
|
||||
}
|
||||
|
||||
"webhook_delete" => {
|
||||
@@ -1845,187 +1825,6 @@ mod tests {
|
||||
assert_eq!(parsed["body"], "looks good");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_webhook_list_via_mcp_signs_the_request() {
|
||||
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();
|
||||
|
||||
// /hooks is owner-gated, so the MCP webhook_list tool must send a SIGNED
|
||||
// request (get_signed). Requiring the header catches a regression to get().
|
||||
// Passing `owner` in args makes resolve_owner skip the node-root lookup.
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/hooks$".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#"{"webhooks":[],"count":0}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool(
|
||||
"webhook_list",
|
||||
json!({"owner": "alice", "repo": "myrepo"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.contains("webhooks"), "got: {result}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_webhook_list_default_owner_is_keypair_not_node_did() {
|
||||
// When `owner` is omitted, the owner segment must come from the signing
|
||||
// keypair's short DID, NOT the node root DID. The "/" mock returns a
|
||||
// different DID; the /hooks mock only matches the keypair's short DID,
|
||||
// so a regression to the node DID would leave the request unmatched.
|
||||
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 _root = server
|
||||
.mock("GET", "/")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"did":"did:key:z6MkNodeRootDid"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let did = kp.did().to_string();
|
||||
let short = did.split(':').next_back().unwrap_or(&did).to_string();
|
||||
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(format!(r"/api/v1/repos/{short}/myrepo/hooks$")),
|
||||
)
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"webhooks":[],"count":0}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool(
|
||||
"webhook_list",
|
||||
json!({"repo": "myrepo"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.contains("webhooks"), "got: {result}");
|
||||
_m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_webhook_list_explicit_owner_overrides_keypair() {
|
||||
// An explicit `owner` arg must win over the keypair default and the node
|
||||
// DID. The path must use the supplied owner; "/" must not even be hit.
|
||||
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/repos/someoneelse/myrepo/hooks$".to_string()),
|
||||
)
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"webhooks":[],"count":0}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let result = call_tool(
|
||||
"webhook_list",
|
||||
json!({"repo": "myrepo", "owner": "someoneelse"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.contains("webhooks"), "got: {result}");
|
||||
_m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_webhook_list_non_success_status_errors() {
|
||||
// A 403 (or any non-2xx) JSON error body for a missing identity, wrong
|
||||
// owner, or private/deleted repo must fail the tool call, NOT be returned
|
||||
// as a successful result. Mirrors the `gl webhook list` status check.
|
||||
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"/hooks$".to_string()))
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.with_status(403)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"only the repo owner can perform this action"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = call_tool(
|
||||
"webhook_list",
|
||||
json!({"owner": "alice", "repo": "myrepo"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.expect_err("non-2xx must error, not return the error body as success");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("webhook_list failed (403"), "got: {msg}");
|
||||
assert!(
|
||||
msg.contains("only the repo owner"),
|
||||
"must surface the node message, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_webhook_list_without_keypair_errors() {
|
||||
// No identity loaded and no explicit owner → the tool must error rather
|
||||
// than fall back to the node DID and issue an unsigned, mis-scoped GET.
|
||||
let server = mockito::Server::new_async().await;
|
||||
let dir = tempfile::TempDir::new().unwrap(); // empty: no identity.pem
|
||||
|
||||
let err = call_tool(
|
||||
"webhook_list",
|
||||
json!({"repo": "myrepo"}),
|
||||
&server.url(),
|
||||
Some(dir.path()),
|
||||
)
|
||||
.await
|
||||
.expect_err("must error without an identity");
|
||||
assert!(err.to_string().contains("no identity found"), "got: {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tool_count_is_42() {
|
||||
let tools = tool_definitions();
|
||||
|
||||
+12
-406
@@ -7,7 +7,7 @@ use clap::{Args, Subcommand};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::http::{read_body_capped, sanitize_node_msg, NodeClient};
|
||||
use crate::http::NodeClient;
|
||||
use crate::identity::load_keypair_from_dir;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -97,74 +97,6 @@ async fn cmd_list(node: String) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The warning text for a local peer-add reply, or `None` when the node
|
||||
/// accepted it.
|
||||
///
|
||||
/// Split out so the refusal path is assertable. The node now answers 403 when
|
||||
/// an unproven caller tries to repoint an existing peer's `http_url`, so a
|
||||
/// reply that arrived and refused must not reach the success line.
|
||||
fn local_add_refusal(status: reqwest::StatusCode, body: &Value) -> Option<String> {
|
||||
if status.is_success() {
|
||||
return None;
|
||||
}
|
||||
// The message is the node's, not ours, so it is defanged before it reaches
|
||||
// the terminal. Only the message: the status and the prose are ours.
|
||||
let msg = sanitize_node_msg(body["message"].as_str().unwrap_or("unknown error"));
|
||||
Some(format!(
|
||||
"warning: local peer list not updated ({status}): {msg}"
|
||||
))
|
||||
}
|
||||
|
||||
/// The error text for a remote announce reply, or `None` when the peer accepted
|
||||
/// it.
|
||||
///
|
||||
/// Split out so the ordering is assertable: the status has to reach the caller
|
||||
/// even when the body does not parse. That case is reachable rather than
|
||||
/// theoretical, because the read above is capped, so a peer answering with a
|
||||
/// body past the cap leaves truncated JSON behind, and `peer_url` is whatever
|
||||
/// the caller passed, so a non-JSON error page is just as easy. Parsing first
|
||||
/// and failing on the parse would swallow the status the user needs.
|
||||
fn remote_announce_failure(status: reqwest::StatusCode, raw: &str) -> Option<String> {
|
||||
if status.is_success() {
|
||||
return None;
|
||||
}
|
||||
// Falls back to the body itself when there is no `message` field, which is
|
||||
// what a truncated or non-JSON reply leaves. Sanitized either way: it is the
|
||||
// peer's text and it is headed for the terminal.
|
||||
let parsed: Value = serde_json::from_str(raw).unwrap_or(Value::Null);
|
||||
let msg = sanitize_node_msg(parsed["message"].as_str().unwrap_or(raw));
|
||||
Some(format!("announce failed ({status}): {msg}"))
|
||||
}
|
||||
|
||||
/// Which line the local peer-add prints, and whether it is a warning.
|
||||
///
|
||||
/// Split out because the SELECTION is what the fix is: `local_add_refusal` was
|
||||
/// already unit-tested six ways, and replacing this whole match with an
|
||||
/// unconditional "Added to local peer list." still left 312 tests green. The
|
||||
/// helper was pinned; the wiring was not, which is the shape
|
||||
/// `unit-test-on-helper-does-not-prove-handler-wiring` names. With the choice
|
||||
/// extracted, the call site is a two-line dispatch carrying no logic.
|
||||
fn local_add_report(status: reqwest::StatusCode, body: &Value) -> (bool, String) {
|
||||
match local_add_refusal(status, body) {
|
||||
Some(warning) => (true, warning),
|
||||
None => (false, " Added to local peer list.".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The block printed after a peer accepts our announce. Split out so the
|
||||
/// defanging is assertable: the DID and URL are the remote peer's own strings,
|
||||
/// and `peer_url` is caller-chosen, so this is the least trusted body the
|
||||
/// command handles. Only the display is sanitized; the values sent on to our
|
||||
/// local node stay verbatim, since that is data rather than terminal output and
|
||||
/// the node runs its own validation on them.
|
||||
fn announced_peer_summary(their_did: &str, their_url: &str, peer_count: u64) -> String {
|
||||
format!(
|
||||
"Announced to peer node:\n DID: {}\n URL: {}\n Their peers: {peer_count}\n",
|
||||
sanitize_node_msg(their_did),
|
||||
sanitize_node_msg(their_url),
|
||||
)
|
||||
}
|
||||
|
||||
async fn cmd_add(peer_url: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let keypair = load_keypair_from_dir(dir.as_deref())?;
|
||||
let my_did = keypair.did().to_string();
|
||||
@@ -195,26 +127,21 @@ async fn cmd_add(peer_url: String, node: String, dir: Option<PathBuf>) -> Result
|
||||
.await
|
||||
.context("failed to connect to peer")?;
|
||||
let status = resp.status();
|
||||
// `peer_url` is fully caller-chosen, so this body is the least trusted one
|
||||
// in the command: bound the read, and defang the message before it reaches
|
||||
// the terminal through the error return. An announce reply is a DID, a URL
|
||||
// and a count, so 8 KiB is well past what the shape needs.
|
||||
let raw = read_body_capped(resp, 8 * 1024).await.text;
|
||||
let result: Value = resp.json().await.context("invalid JSON response")?;
|
||||
|
||||
if let Some(failure) = remote_announce_failure(status, &raw) {
|
||||
anyhow::bail!("{failure}");
|
||||
if !status.is_success() {
|
||||
let msg = result["message"].as_str().unwrap_or("unknown error");
|
||||
anyhow::bail!("announce failed ({status}): {msg}");
|
||||
}
|
||||
|
||||
let result: Value = serde_json::from_str(&raw).context("invalid JSON response")?;
|
||||
|
||||
let their_did = result["node_did"].as_str().unwrap_or("?");
|
||||
let their_url = result["node_url"].as_str().unwrap_or("?");
|
||||
let peer_count = result["peer_count"].as_u64().unwrap_or(0);
|
||||
|
||||
print!(
|
||||
"{}",
|
||||
announced_peer_summary(their_did, their_url, peer_count)
|
||||
);
|
||||
println!("Announced to peer node:");
|
||||
println!(" DID: {their_did}");
|
||||
println!(" URL: {their_url}");
|
||||
println!(" Their peers: {peer_count}");
|
||||
|
||||
// Also add their info to our local node's peer list
|
||||
// (the peer's /announce response includes their did + url)
|
||||
@@ -223,31 +150,9 @@ async fn cmd_add(peer_url: String, node: String, dir: Option<PathBuf>) -> Result
|
||||
"did": their_did,
|
||||
"http_url": their_url,
|
||||
}))?;
|
||||
// This requires the local node to be running, so a transport failure
|
||||
// stays a warning rather than failing the command. A reply that
|
||||
// ARRIVED and refused is different: the announce route answers 403
|
||||
// when an unproven caller tries to repoint an existing peer, and
|
||||
// printing the success line over that reports a completed add that
|
||||
// never happened. Same status handling as the remote announce above,
|
||||
// except best effort.
|
||||
match local_client.post("/api/v1/peers/announce", &add_body).await {
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
// Same bound as the remote announce above: a compromised local
|
||||
// node (or a MITM on plain http) must not force an unbounded
|
||||
// read. A body that does not parse stays `Null`, which still
|
||||
// routes a non-success status to the warning.
|
||||
let raw = read_body_capped(resp, 8 * 1024).await.text;
|
||||
let result: Value = serde_json::from_str(&raw).unwrap_or(Value::Null);
|
||||
let (is_warning, line) = local_add_report(status, &result);
|
||||
if is_warning {
|
||||
eprintln!("{line}");
|
||||
} else {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
Err(e) => eprintln!("warning: local peer list not updated: {e}"),
|
||||
}
|
||||
// This requires the local node to be running; ignore errors here
|
||||
let _ = local_client.post("/api/v1/peers/announce", &add_body).await;
|
||||
println!(" Added to local peer list.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -305,302 +210,3 @@ async fn cmd_resolve(did: String, node: String) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
announced_peer_summary, cmd_add, local_add_refusal, local_add_report,
|
||||
remote_announce_failure,
|
||||
};
|
||||
use reqwest::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
/// The node's 403 for repointing an existing peer must surface, not print
|
||||
/// as a completed add. Without the status check the command prints "Added
|
||||
/// to local peer list." over a refusal.
|
||||
///
|
||||
/// The fixture body is the real wire shape, not an invented one: the
|
||||
/// message is the Display of `PeerWriteDenied::UnprovenRepoint`, declared
|
||||
/// in `crates/gitlawb-node/src/db/mod.rs`. The executable detector for a
|
||||
/// wording change is the node-side pin
|
||||
/// `announce_unsigned_repoint_is_a_403_denial` in
|
||||
/// `crates/gitlawb-node/src/api/peers.rs`, which asserts this same
|
||||
/// substring against a response driven through the real router, so
|
||||
/// rewording the Display turns that test red and the grep for the old
|
||||
/// phrase lands here.
|
||||
///
|
||||
/// The assertion bites rather than echoing its own input because the
|
||||
/// substring is reachable only through the helper's `body["message"]`
|
||||
/// extraction; the fixture's `error` field carries a different string, so
|
||||
/// reading `body["error"]` instead fails this test.
|
||||
#[test]
|
||||
fn a_refused_local_add_warns_with_the_node_reason() {
|
||||
let warning = local_add_refusal(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({
|
||||
"error": "forbidden",
|
||||
"message": "unproven announce cannot change an existing peer's http_url: did:key:z6MkuMqUm4i228K9qXidJ57zqSWAcQLgrcbMxB8RKVLuqitj"
|
||||
}),
|
||||
)
|
||||
.expect("a refusal must not render as success");
|
||||
|
||||
assert!(warning.contains("403"), "must name the status: {warning}");
|
||||
assert!(
|
||||
warning.contains("unproven announce cannot change an existing peer"),
|
||||
"must carry the node's own reason: {warning}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A refusal with no message body still warns rather than passing silently.
|
||||
#[test]
|
||||
fn a_refusal_without_a_message_still_warns() {
|
||||
let warning = local_add_refusal(StatusCode::BAD_REQUEST, &serde_json::Value::Null)
|
||||
.expect("a refusal must not render as success");
|
||||
assert!(warning.contains("400"), "must name the status: {warning}");
|
||||
}
|
||||
|
||||
/// The accepted case stays quiet, so the success line still prints.
|
||||
#[test]
|
||||
fn an_accepted_local_add_produces_no_warning() {
|
||||
assert!(local_add_refusal(StatusCode::OK, &json!({ "peer_count": 3 })).is_none());
|
||||
}
|
||||
|
||||
/// The warning is printed straight to a terminal, so a node-supplied message
|
||||
/// carrying an OSC title-rewrite plus a C0 escape must reach it defanged.
|
||||
#[test]
|
||||
fn a_refusal_message_cannot_carry_terminal_escapes() {
|
||||
let warning = local_add_refusal(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({ "message": "\u{1b}]2;pwned\u{7}legit-looking text" }),
|
||||
)
|
||||
.expect("a refusal must not render as success");
|
||||
|
||||
assert!(
|
||||
!warning.chars().any(|c| c.is_control()),
|
||||
"control char leaked to the terminal: {warning:?}"
|
||||
);
|
||||
assert!(
|
||||
warning.contains("legit-looking text"),
|
||||
"printable text dropped: {warning:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Bidi format chars are not `char::is_control`, yet they reorder the
|
||||
/// displayed line, so a refusal must not carry them either.
|
||||
#[test]
|
||||
fn a_refusal_message_cannot_carry_bidi_overrides() {
|
||||
let warning = local_add_refusal(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({ "message": "peer \u{202e}refused\u{202c} here" }),
|
||||
)
|
||||
.expect("a refusal must not render as success");
|
||||
|
||||
assert!(
|
||||
!warning.chars().any(gitlawb_core::sanitize::is_bidi_format),
|
||||
"bidi format char leaked to the terminal: {warning:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A hostile node must not be able to dump an arbitrary amount of text into
|
||||
/// the user's scrollback through the warning line.
|
||||
#[test]
|
||||
fn a_refusal_message_is_length_bounded() {
|
||||
let warning = local_add_refusal(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({ "message": "x".repeat(5000) }),
|
||||
)
|
||||
.expect("a refusal must not render as success");
|
||||
|
||||
assert!(
|
||||
warning.chars().count() < 500,
|
||||
"warning not bounded: {} chars",
|
||||
warning.chars().count()
|
||||
);
|
||||
}
|
||||
|
||||
/// The status is the part the user can act on, so it must survive a body
|
||||
/// that does not parse. The read is capped, so a peer answering past the cap
|
||||
/// leaves exactly this: a valid status and truncated JSON.
|
||||
#[test]
|
||||
fn a_remote_announce_failure_keeps_the_status_when_the_body_does_not_parse() {
|
||||
let truncated = r#"{"error":"service_unavailable","message":"backend is do"#;
|
||||
let failure = remote_announce_failure(StatusCode::SERVICE_UNAVAILABLE, truncated)
|
||||
.expect("a non-success status must produce a failure");
|
||||
|
||||
assert!(
|
||||
failure.contains("503"),
|
||||
"the status must survive an unparseable body: {failure:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A parseable error body still reports the peer's own message.
|
||||
#[test]
|
||||
fn a_remote_announce_failure_carries_the_peers_message() {
|
||||
let failure = remote_announce_failure(
|
||||
StatusCode::FORBIDDEN,
|
||||
r#"{"error":"forbidden","message":"unproven announce cannot change an existing peer"}"#,
|
||||
)
|
||||
.expect("a non-success status must produce a failure");
|
||||
|
||||
assert!(
|
||||
failure.contains("403")
|
||||
&& failure.contains("unproven announce cannot change an existing peer"),
|
||||
"status and reason must both survive: {failure:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The fallback path prints the raw body, so it is defanged like every other
|
||||
/// peer-supplied string headed for the terminal.
|
||||
#[test]
|
||||
fn a_remote_announce_failure_defangs_an_unparseable_body() {
|
||||
let failure = remote_announce_failure(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"\u{1b}]2;pwned\u{7}<html>gateway error</html>",
|
||||
)
|
||||
.expect("a non-success status must produce a failure");
|
||||
|
||||
assert!(
|
||||
!failure.chars().any(|c| c.is_control()),
|
||||
"control char leaked to the terminal: {failure:?}"
|
||||
);
|
||||
assert!(failure.contains("502"), "status dropped: {failure:?}");
|
||||
assert!(
|
||||
failure.contains("gateway error"),
|
||||
"the body is all the user gets when there is no message field: {failure:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The unit tests above bind the helper. This one binds the CALL SITE: the
|
||||
/// failure check has to run before the parse, or a body past the read cap
|
||||
/// turns a 503 into "invalid JSON response" and the status the user needs is
|
||||
/// gone. Reordering the two statements in `cmd_add` compiles and passes every
|
||||
/// other test in this file, so only driving the command catches it.
|
||||
#[tokio::test]
|
||||
async fn a_peer_failure_past_the_read_cap_still_reports_its_status() {
|
||||
let mut peer = mockito::Server::new_async().await;
|
||||
let mut local = 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 _local_info = local
|
||||
.mock("GET", "/")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"public_url":"https://me.example"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
// Valid JSON, but past the 8 KiB read cap, so what survives the read is
|
||||
// truncated and unparseable. This is the shape the cap itself creates.
|
||||
let oversized = format!(r#"{{"message":"{}"}}"#, "x".repeat(16 * 1024));
|
||||
let _peer_refusal = peer
|
||||
.mock("POST", "/api/v1/peers/announce")
|
||||
.with_status(503)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(oversized)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_add(peer.url(), local.url(), Some(dir.path().to_path_buf()))
|
||||
.await
|
||||
.expect_err("a 503 from the peer must fail the command");
|
||||
|
||||
let rendered = format!("{err:#}");
|
||||
assert!(
|
||||
rendered.contains("503"),
|
||||
"the status must survive a body past the read cap: {rendered:?}"
|
||||
);
|
||||
assert!(
|
||||
!rendered.contains("invalid JSON response"),
|
||||
"the parse failure must not stand in for the status: {rendered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An accepted announce produces no error, so the caller proceeds to parse.
|
||||
#[test]
|
||||
fn an_accepted_remote_announce_produces_no_failure() {
|
||||
assert!(remote_announce_failure(StatusCode::OK, r#"{"peer_count":3}"#).is_none());
|
||||
}
|
||||
|
||||
/// The selection, not the helper. A refusal must never yield the success
|
||||
/// line, and the success line must never carry the warning prefix. This is
|
||||
/// what stayed green when the entire match was replaced with an
|
||||
/// unconditional "Added to local peer list."
|
||||
#[test]
|
||||
fn a_local_add_refusal_never_selects_the_success_line() {
|
||||
let (is_warning, line) = local_add_report(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({ "message": "unproven announce cannot change an existing peer's http_url: did:key:zAbc" }),
|
||||
);
|
||||
|
||||
assert!(is_warning, "a 403 must select the warning stream: {line:?}");
|
||||
assert!(
|
||||
!line.contains("Added to local peer list"),
|
||||
"a refusal rendered as the success line: {line:?}"
|
||||
);
|
||||
assert!(
|
||||
line.contains("unproven announce cannot change an existing peer"),
|
||||
"the node's reason must reach the user: {line:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The other direction, so the fix cannot be satisfied by always warning.
|
||||
#[test]
|
||||
fn an_accepted_local_add_selects_the_success_line() {
|
||||
let (is_warning, line) = local_add_report(StatusCode::OK, &json!({ "peer_count": 3 }));
|
||||
|
||||
assert!(!is_warning, "a 200 must not select the warning stream");
|
||||
assert!(
|
||||
line.contains("Added to local peer list"),
|
||||
"the success line must still print: {line:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The accepted-announce block prints the remote peer's own DID and URL, so
|
||||
/// a hostile peer answering 200 must not get escapes onto the terminal that
|
||||
/// way either. The refusal path is not the only sink in this command.
|
||||
#[test]
|
||||
fn an_accepted_announce_summary_cannot_carry_terminal_escapes() {
|
||||
let summary = announced_peer_summary(
|
||||
"did:key:z6Mk\u{1b}]2;pwned\u{7}abc",
|
||||
"https://peer.example\u{202e}moc.live//:sptth",
|
||||
3,
|
||||
);
|
||||
|
||||
assert!(
|
||||
!summary.chars().any(|c| c.is_control() && c != '\n'),
|
||||
"control char leaked to the terminal: {summary:?}"
|
||||
);
|
||||
assert!(
|
||||
!summary.chars().any(gitlawb_core::sanitize::is_bidi_format),
|
||||
"bidi format char leaked to the terminal: {summary:?}"
|
||||
);
|
||||
assert!(
|
||||
summary.contains("did:key:z6Mk") && summary.contains("Their peers: 3"),
|
||||
"printable content dropped: {summary:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The counterweight to the stripping tests: a legitimate message with RTL
|
||||
/// script letters and a ZWJ must survive intact, so the sanitizer is not
|
||||
/// proven by over-stripping.
|
||||
#[test]
|
||||
fn a_legitimate_refusal_message_survives_intact() {
|
||||
let warning = local_add_refusal(
|
||||
StatusCode::FORBIDDEN,
|
||||
&json!({ "message": "peer refused \u{0627}\u{200D}b" }),
|
||||
)
|
||||
.expect("a refusal must not render as success");
|
||||
|
||||
assert!(
|
||||
warning.contains("peer refused \u{0627}\u{200D}b"),
|
||||
"legitimate text mangled: {warning:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -154,12 +154,10 @@ async fn cmd_remove(
|
||||
|
||||
async fn cmd_list(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let (owner, name) = resolve_owner_repo(&repo, &node, dir.as_deref()).await?;
|
||||
// Read-visibility-gated on the node: public repos list anonymously, private
|
||||
// repos need the owner's signature. Sign when an identity is available.
|
||||
let client = NodeClient::new(&node, load_keypair_from_dir(dir.as_deref()).ok());
|
||||
let client = NodeClient::new(&node, None);
|
||||
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
|
||||
@@ -309,9 +307,6 @@ mod tests {
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"branches/protected".to_string()),
|
||||
)
|
||||
// An identity is supplied, so get_maybe_signed must sign the request.
|
||||
.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#"{"protected_branches":[],"count":0}"#)
|
||||
@@ -343,8 +338,6 @@ mod tests {
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"branches/protected".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#"{"protected_branches":["main","release"],"count":2}"#)
|
||||
|
||||
+34
-431
@@ -146,8 +146,6 @@ pub enum RepoCmd {
|
||||
repo: String,
|
||||
#[arg(long, default_value = "https://node.gitlawb.com", env = "GITLAWB_NODE")]
|
||||
node: String,
|
||||
#[arg(long)]
|
||||
dir: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -205,7 +203,7 @@ pub async fn run(args: RepoArgs) -> Result<()> {
|
||||
RepoCmd::ReplicaUnregister { repo, node, dir } => {
|
||||
cmd_replica_unregister(repo, node, dir).await
|
||||
}
|
||||
RepoCmd::Replicas { repo, node, dir } => cmd_replicas(repo, node, dir).await,
|
||||
RepoCmd::Replicas { repo, node } => cmd_replicas(repo, node).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,10 +329,7 @@ async fn cmd_clone(name: String, node: String, dir: Option<PathBuf>) -> Result<(
|
||||
}
|
||||
|
||||
async fn cmd_info(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
// Sign when an identity is available so the read-visibility-gated replica
|
||||
// sub-fetch below resolves for a private repo's owner (public repos still
|
||||
// work anonymously).
|
||||
let client = NodeClient::new(&node, load_keypair_from_dir(dir.as_deref()).ok());
|
||||
let client = NodeClient::new(&node, None);
|
||||
|
||||
let (owner, name) = if repo.contains('/') {
|
||||
let (o, n) = repo.split_once('/').unwrap();
|
||||
@@ -344,10 +339,7 @@ async fn cmd_info(repo: String, node: String, dir: Option<PathBuf>) -> Result<()
|
||||
(short, repo)
|
||||
};
|
||||
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let resp = client.get(&format!("/api/v1/repos/{owner}/{name}")).await?;
|
||||
// A non-existent (or unreadable/quarantined) repo is a real 404 from the
|
||||
// node — surface it plainly instead of printing a stub card with `?` fields
|
||||
// and a placeholder owner DID.
|
||||
@@ -387,7 +379,7 @@ async fn cmd_info(repo: String, node: String, dir: Option<PathBuf>) -> Result<()
|
||||
|
||||
// Replica count — failure to fetch is non-fatal (older nodes don't expose this).
|
||||
if let Ok(resp) = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.await
|
||||
{
|
||||
if resp.status().is_success() {
|
||||
@@ -467,17 +459,15 @@ async fn cmd_replica_unregister(repo: String, node: String, dir: Option<PathBuf>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_replicas(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
async fn cmd_replicas(repo: String, node: String) -> Result<()> {
|
||||
let (owner, name) = repo
|
||||
.split_once('/')
|
||||
.map(|(o, n)| (o.to_string(), n.to_string()))
|
||||
.context("use owner/repo format")?;
|
||||
|
||||
// Read-visibility-gated: public repos list anonymously, private repos need
|
||||
// the owner's signature. Sign when an identity is available.
|
||||
let client = NodeClient::new(&node, load_keypair_from_dir(dir.as_deref()).ok());
|
||||
let client = NodeClient::new(&node, None);
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let status = resp.status();
|
||||
@@ -595,7 +585,7 @@ async fn cmd_fork(
|
||||
}
|
||||
|
||||
/// Returns (owner, repo_name) — if repo contains '/', splits on it; otherwise uses caller's DID.
|
||||
pub(crate) async fn resolve_owner_repo_pair(
|
||||
async fn resolve_owner_repo_pair(
|
||||
repo: &str,
|
||||
node: &str,
|
||||
dir: Option<&std::path::Path>,
|
||||
@@ -668,23 +658,16 @@ async fn cmd_label_remove(
|
||||
|
||||
async fn cmd_label_list(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let (owner, name) = resolve_owner_repo_pair(&repo, &node, dir.as_deref()).await?;
|
||||
// Read-visibility-gated like the sibling read surfaces (replicas, protected
|
||||
// branches): sign when an identity is available so a private-repo owner can
|
||||
// read their own labels, while public repos stay anonymously listable.
|
||||
let client = NodeClient::new(&node, load_keypair_from_dir(dir.as_deref()).ok());
|
||||
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/labels"))
|
||||
let resp: Value = client
|
||||
.get_authed(&format!("/api/v1/repos/{owner}/{name}/labels"))
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await.unwrap_or_default();
|
||||
if !status.is_success() {
|
||||
let msg = body["message"].as_str().unwrap_or("unknown error");
|
||||
anyhow::bail!("list labels failed ({status}): {msg}");
|
||||
}
|
||||
.context("invalid JSON")?;
|
||||
|
||||
let labels = body["labels"].as_array().cloned().unwrap_or_default();
|
||||
let labels = resp["labels"].as_array().cloned().unwrap_or_default();
|
||||
if labels.is_empty() {
|
||||
println!("No labels on {owner}/{name}");
|
||||
} else {
|
||||
@@ -696,39 +679,17 @@ async fn cmd_label_list(repo: String, node: String, dir: Option<PathBuf>) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse the protected-branch list from the node's `GET /branches/protected`
|
||||
/// response. The endpoint returns `{"protected_branches": [...], "count": N}`
|
||||
/// (see `crates/gitlawb-node/src/api/protect.rs`); each entry may be a plain
|
||||
/// branch-name string or an object carrying a `name` field.
|
||||
fn parse_protected_branches(val: &Value) -> Vec<String> {
|
||||
val["protected_branches"]
|
||||
.as_array()
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|b| {
|
||||
b.as_str()
|
||||
.map(String::from)
|
||||
.or_else(|| b["name"].as_str().map(String::from))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn cmd_owner(repo: String, node: String, dir: Option<PathBuf>, json_out: bool) -> Result<()> {
|
||||
let keypair = load_keypair_from_dir(dir.as_deref())?;
|
||||
let my_did = keypair.did().to_string();
|
||||
let my_short = my_did.split(':').next_back().unwrap_or(&my_did).to_string();
|
||||
|
||||
let (owner, name) = resolve_owner_repo_pair(&repo, &node, dir.as_deref()).await?;
|
||||
// Sign with the loaded identity so the read-visibility-gated protected-branch
|
||||
// fetch below works on the owner's own private repos.
|
||||
let client = NodeClient::new(&node, Some(keypair));
|
||||
let client = NodeClient::new(&node, None);
|
||||
|
||||
// Fetch repo info (get_repo is read-visibility-gated; sign so the owner can
|
||||
// inspect their own private repo).
|
||||
// Fetch repo info
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
if !resp.status().is_success() {
|
||||
@@ -743,14 +704,25 @@ async fn cmd_owner(repo: String, node: String, dir: Option<PathBuf>, json_out: b
|
||||
.to_string();
|
||||
let is_owner = my_did == owner_did || my_short == owner_short;
|
||||
|
||||
// Fetch protected branches (read-visibility-gated; signed via the client).
|
||||
// Fetch protected branches
|
||||
let protected: Vec<String> = match client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.await
|
||||
{
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
let val: Value = resp.json().await.unwrap_or_default();
|
||||
parse_protected_branches(&val)
|
||||
val.as_array()
|
||||
.or_else(|| val["branches"].as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|b| {
|
||||
b.as_str()
|
||||
.map(String::from)
|
||||
.or_else(|| b["name"].as_str().map(String::from))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
@@ -788,20 +760,6 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn parse_protected_branches_reads_node_shape() {
|
||||
use serde_json::json;
|
||||
assert_eq!(
|
||||
parse_protected_branches(&json!({"protected_branches":["main","release"],"count":2})),
|
||||
vec!["main".to_string(), "release".to_string()]
|
||||
);
|
||||
assert!(parse_protected_branches(&json!({"count":0})).is_empty());
|
||||
assert_eq!(
|
||||
parse_protected_branches(&json!({"protected_branches":[{"name":"main"}]})),
|
||||
vec!["main".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
fn write_identity(dir: &TempDir) {
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
@@ -1139,10 +1097,6 @@ mod tests {
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/labels$".to_string()),
|
||||
)
|
||||
// Identity is loaded, so get_maybe_signed must sign — requiring the
|
||||
// header guards against a regression back to bare get().
|
||||
.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#"{"labels":[]}"#)
|
||||
@@ -1169,10 +1123,6 @@ mod tests {
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/labels$".to_string()),
|
||||
)
|
||||
// Identity is loaded, so get_maybe_signed must sign — requiring the
|
||||
// header guards against a regression back to bare get().
|
||||
.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#"{"labels":["language:rust","topic:defi"]}"#)
|
||||
@@ -1188,97 +1138,6 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_label_list_anonymous_when_no_identity() {
|
||||
// Empty dir → no identity → get_maybe_signed must fall back to an
|
||||
// anonymous GET (the public-repo path). Assert NO signature header.
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/labels$".to_string()))
|
||||
.match_header("signature", mockito::Matcher::Missing)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"labels":[]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_label_list(
|
||||
"owner/pubrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_label_list_404_errors() {
|
||||
// A non-reader of a private repo gets 404 from the now-gated endpoint.
|
||||
// The client must surface that as an error, not print "No labels" and
|
||||
// exit 0 (the error body has no `labels` key).
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/labels$".to_string()),
|
||||
)
|
||||
.with_status(404)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"repo not found"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_label_list(
|
||||
"myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("list labels failed (404")
|
||||
&& err.to_string().contains("repo not found"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_label_list_non_json_error_surfaces_status() {
|
||||
// A non-2xx response with a non-JSON body (e.g. a proxy 502) must still
|
||||
// surface the HTTP status, not collapse to a bare JSON-parse error.
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/[^/]+/myrepo/labels$".to_string()),
|
||||
)
|
||||
.with_status(502)
|
||||
.with_header("content-type", "text/html")
|
||||
.with_body("<html>502 Bad Gateway</html>")
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_label_list(
|
||||
"myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("list labels failed (502"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_owner_is_owner() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -1289,15 +1148,11 @@ mod tests {
|
||||
let short = did.split(':').next_back().unwrap().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
// Both fetches are read-visibility-gated; with an identity loaded they
|
||||
// must be signed. Requiring the header guards a regression to get().
|
||||
let _repo = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(format!(r"^/api/v1/repos/{short}/myrepo$")),
|
||||
)
|
||||
.match_header("signature", mockito::Matcher::Any)
|
||||
.match_header("signature-input", mockito::Matcher::Any)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(format!(
|
||||
@@ -1312,11 +1167,9 @@ mod tests {
|
||||
r"^/api/v1/repos/{short}/myrepo/branches/protected$"
|
||||
)),
|
||||
)
|
||||
.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#"{"protected_branches":["main"],"count":1}"#)
|
||||
.with_body(r#"["main"]"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1357,7 +1210,7 @@ mod tests {
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"protected_branches":["main","release"],"count":2}"#)
|
||||
.with_body(r#"["main","release"]"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1398,7 +1251,7 @@ mod tests {
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"protected_branches":["main"],"count":1}"#)
|
||||
.with_body(r#"["main"]"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1439,254 +1292,4 @@ mod tests {
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("not found"), "got: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_replicas_signs_when_identity_present() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
// Read-visibility-gated: with an identity the request must be signed.
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/replicas$".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#"{"repo":"owner/myrepo","replica_count":0,"replicas":[]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_replicas(
|
||||
"owner/myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_replicas_anonymous_when_no_identity() {
|
||||
// Empty dir → no identity → get_maybe_signed must fall back to an
|
||||
// anonymous GET (the public-repo path). Assert NO signature header.
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/replicas$".to_string()))
|
||||
.match_header("signature", mockito::Matcher::Missing)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"repo":"owner/pubrepo","replica_count":0,"replicas":[]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_replicas(
|
||||
"owner/pubrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_info_signs_repo_and_replica_fetches() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
// Both the primary repo fetch and the replica sub-fetch are
|
||||
// read-visibility-gated; with an identity loaded both must be signed.
|
||||
let _repo = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/owner/myrepo$".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#"{"id":"r1","name":"myrepo","owner_did":"did:key:zOwner","is_public":false,"default_branch":"main"}"#,
|
||||
)
|
||||
.create_async()
|
||||
.await;
|
||||
let _replicas = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/replicas$".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#"{"replica_count":0,"replicas":[]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_info(
|
||||
"owner/myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_info_404_surfaces_error_not_fake_repo() {
|
||||
// A non-reader of a private repo gets a JSON 404 from the now-gated
|
||||
// GET /api/v1/repos/{owner}/{name}. The command must surface that as an
|
||||
// error, not parse the error body and print a fabricated repo summary
|
||||
// (owner / "?" / public=true / main) before exiting 0.
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _repo = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/owner/myrepo$".to_string()),
|
||||
)
|
||||
.with_status(404)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"repo not found"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_info(
|
||||
"owner/myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
// The merged cmd_info maps a 404 to a generic "not found" (it does not
|
||||
// echo the server's message body on 404), which still surfaces the error
|
||||
// rather than fabricating a repo card, and avoids leaking any
|
||||
// server-provided detail on a private-repo denial.
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("repository 'owner/myrepo' not found"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cmd_info_non_json_error_surfaces_status() {
|
||||
// A non-2xx response with a non-JSON body (e.g. a proxy 502) must still
|
||||
// surface the HTTP status, not collapse to a bare JSON-parse error.
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _repo = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/owner/myrepo$".to_string()),
|
||||
)
|
||||
.with_status(502)
|
||||
.with_header("content-type", "text/html")
|
||||
.with_body("<html>502 Bad Gateway</html>")
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_info(
|
||||
"owner/myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("repo info failed (502"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Drives the three deny/negative arms that the merge reconciliation changed but
|
||||
// that no existing test executed (they were only reasoned): resolve_owner_did
|
||||
// with no identity, cmd_info on an authenticated-but-denied 403, and
|
||||
// get_maybe_signed with no keypair. Each asserts the must-not case.
|
||||
#[cfg(test)]
|
||||
mod vet_merge_deny_arms {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn write_identity(dir: &TempDir) {
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
// No local identity must hard-error, never fall back to the node's own DID.
|
||||
// (Load-bearing: #113's pre-merge resolve_owner_did returned Ok via a node
|
||||
// fetch here; a reintroduced fallback makes this go red.)
|
||||
#[tokio::test]
|
||||
async fn resolve_owner_did_no_identity_errors_not_fallback() {
|
||||
let empty = TempDir::new().unwrap(); // no identity.pem written
|
||||
let err = resolve_owner_did("http://unused.invalid", Some(empty.path()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("no local identity to resolve the repo owner"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// An authenticated caller DENIED with a 403 must surface an error, never
|
||||
// render a repo card (deny-as-success is the INV-8 client-contract break).
|
||||
#[tokio::test]
|
||||
async fn cmd_info_403_denied_surfaces_error_not_card() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
write_identity(&dir);
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"^/api/v1/repos/owner/myrepo$".to_string()),
|
||||
)
|
||||
.with_status(403)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"forbidden"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
let err = cmd_info(
|
||||
"owner/myrepo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("repo info failed (403"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// No keypair must send an unsigned GET; the mock only matches when the
|
||||
// Signature header is absent, so a wrongly-signed request fails to match.
|
||||
#[tokio::test]
|
||||
async fn get_maybe_signed_no_keypair_sends_unsigned() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _m = server
|
||||
.mock("GET", "/api/v1/repos/owner/pub")
|
||||
.match_header("signature", mockito::Matcher::Missing)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body("{}")
|
||||
.create_async()
|
||||
.await;
|
||||
let client = NodeClient::new(server.url(), None);
|
||||
let resp = client
|
||||
.get_maybe_signed("/api/v1/repos/owner/pub")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
resp.status().is_success(),
|
||||
"unsigned GET should match the Missing-signature mock; got {}",
|
||||
resp.status()
|
||||
);
|
||||
}
|
||||
}
|
||||
+13
-52
@@ -59,7 +59,7 @@ pub async fn run(args: StatusArgs) -> Result<()> {
|
||||
println!(" repo {short_did}/{repo}");
|
||||
}
|
||||
None => {
|
||||
println!(" repo (not in a gitlawb repo — no gitlawb:// remote)");
|
||||
println!(" repo (not in a gitlawb repo — no gitlawb:// origin)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,68 +143,29 @@ fn trust_bar(score: f64) -> String {
|
||||
format!("{}{}", "█".repeat(filled), "░".repeat(empty))
|
||||
}
|
||||
|
||||
/// Find a `gitlawb://<did>/<repo>` remote in the current repo.
|
||||
///
|
||||
/// Checks `origin` first (clones), then `gitlawb` (the name `gl init` adds),
|
||||
/// then any other remote with a gitlawb:// URL.
|
||||
/// Parse `gitlawb://<did>/<repo>` from the git origin remote.
|
||||
fn detect_gitlawb_remote() -> Option<(String, String)> {
|
||||
let out = std::process::Command::new("git")
|
||||
.args(["remote"])
|
||||
.args(["remote", "get-url", "origin"])
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<String> = String::from_utf8(out.stdout)
|
||||
.ok()?
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
|
||||
let preferred = ["origin", "gitlawb"];
|
||||
let ordered = preferred
|
||||
.iter()
|
||||
.filter(|p| names.iter().any(|n| n == *p))
|
||||
.map(|p| p.to_string())
|
||||
.chain(
|
||||
names
|
||||
.iter()
|
||||
.filter(|n| !preferred.contains(&n.as_str()))
|
||||
.cloned(),
|
||||
);
|
||||
|
||||
for name in ordered {
|
||||
// A remote can carry several URLs, and the gitlawb:// one may be a
|
||||
// push URL behind an https fetch URL — check every fetch and push URL.
|
||||
for extra in [&["--all"][..], &["--push", "--all"][..]] {
|
||||
let mut args = vec!["remote", "get-url"];
|
||||
args.extend_from_slice(extra);
|
||||
args.push(&name);
|
||||
let Ok(out) = std::process::Command::new("git")
|
||||
.args(&args)
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !out.status.success() {
|
||||
continue;
|
||||
}
|
||||
let Ok(urls) = String::from_utf8(out.stdout) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(parsed) = urls.lines().find_map(parse_gitlawb_url) {
|
||||
return Some(parsed);
|
||||
}
|
||||
}
|
||||
let url = String::from_utf8(out.stdout).ok()?;
|
||||
let rest = url.trim().strip_prefix("gitlawb://")?;
|
||||
let slash = rest.rfind('/')?;
|
||||
let did = rest[..slash].to_string();
|
||||
let repo = rest[slash + 1..].to_string();
|
||||
if did.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
None
|
||||
Some((did, repo))
|
||||
}
|
||||
|
||||
/// Parse a gitlawb:// URL string into (did, repo).
|
||||
/// Parse a gitlawb:// URL string into (did, repo) — extracted for testing.
|
||||
#[cfg(test)]
|
||||
fn parse_gitlawb_url(url: &str) -> Option<(String, String)> {
|
||||
let rest = url.trim().strip_prefix("gitlawb://")?;
|
||||
let slash = rest.rfind('/')?;
|
||||
|
||||
+69
-3
@@ -2,7 +2,7 @@ use anyhow::{Context, Result};
|
||||
use clap::{Args, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::http::{read_body_capped, sanitize_node_msg, NodeClient};
|
||||
use crate::http::NodeClient;
|
||||
use crate::identity::load_keypair_from_dir;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -46,7 +46,7 @@ pub async fn run(args: SyncArgs) -> Result<()> {
|
||||
if !status.is_success() {
|
||||
// Bound the read: a hostile or broken node must not force an
|
||||
// unbounded allocation just to surface a denial (INV-6, read half).
|
||||
let raw = read_body_capped(resp, 8 * 1024).await.text;
|
||||
let raw = read_body_capped(resp, 8 * 1024).await;
|
||||
let msg = serde_json::from_str::<serde_json::Value>(&raw)
|
||||
.ok()
|
||||
.and_then(|v| {
|
||||
@@ -104,6 +104,51 @@ fn trigger_counts(resp: &serde_json::Value) -> (u64, u64) {
|
||||
)
|
||||
}
|
||||
|
||||
/// Read at most `cap` bytes of a response body. Bounds the allocation from a
|
||||
/// hostile or broken node returning a huge error body — the display is capped
|
||||
/// separately, but the read itself must not be unbounded (INV-6, read half).
|
||||
async fn read_body_capped(mut resp: reqwest::Response, cap: usize) -> String {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
while buf.len() < cap {
|
||||
match resp.chunk().await {
|
||||
Ok(Some(chunk)) => {
|
||||
let take = (cap - buf.len()).min(chunk.len());
|
||||
buf.extend_from_slice(&chunk[..take]);
|
||||
if take < chunk.len() {
|
||||
break; // hit the cap mid-chunk
|
||||
}
|
||||
}
|
||||
_ => break, // end of body or read error — return what we have
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
}
|
||||
|
||||
/// Strip terminal-dangerous characters from (and cap the length of) a
|
||||
/// node-supplied error string before surfacing it. The node a caller talks to
|
||||
/// could be hostile and embed escape sequences in its error body; those must not
|
||||
/// reach the terminal verbatim (INV-6). We drop the C0/C1 control bytes (which
|
||||
/// defangs ANSI/OSC escapes) AND the Unicode bidi/format controls (which
|
||||
/// `char::is_control` does not cover — they can reorder the displayed line).
|
||||
fn sanitize_node_msg(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| !c.is_control() && !is_bidi_format(*c))
|
||||
.take(200)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Unicode bidirectional and directional-isolate format characters (category
|
||||
/// `Cf`). These are not `char::is_control()` (that is category `Cc` only), but a
|
||||
/// right-to-left override or isolate can visually reorder a terminal line to
|
||||
/// spoof the error text, so they are stripped alongside the control bytes.
|
||||
fn is_bidi_format(c: char) -> bool {
|
||||
matches!(c,
|
||||
'\u{200E}' | '\u{200F}' | '\u{061C}' // LRM, RLM, ALM
|
||||
| '\u{202A}'..='\u{202E}' // LRE, RLE, PDF, LRO, RLO
|
||||
| '\u{2066}'..='\u{2069}' // LRI, RLI, FSI, PDI
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -227,6 +272,27 @@ mod tests {
|
||||
run(args).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_strips_controls_bidi_and_caps_length() {
|
||||
// C0 (ESC/BEL) and the Cf bidi override (U+202E) are both removed; the
|
||||
// printable text survives. (Note: a stripped ESC leaves any following
|
||||
// "[31m" as inert literal text — that is the point, so the input here
|
||||
// avoids that residue to keep the expectation unambiguous.)
|
||||
let out = sanitize_node_msg("a\u{1b}\u{07}b\u{202e}c");
|
||||
assert!(
|
||||
!out.chars().any(|c| c.is_control()),
|
||||
"control char leaked: {out:?}"
|
||||
);
|
||||
assert!(
|
||||
!out.contains('\u{202e}'),
|
||||
"RLO bidi override leaked: {out:?}"
|
||||
);
|
||||
assert_eq!(out, "abc");
|
||||
// Length is capped at 200 chars regardless of input size.
|
||||
let long = "x".repeat(250);
|
||||
assert_eq!(sanitize_node_msg(&long).chars().count(), 200);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn trigger_handles_oversized_error_body_without_unbounded_output() {
|
||||
// A hostile/broken node returns a 2 MB error body. The command must still
|
||||
@@ -261,7 +327,7 @@ mod tests {
|
||||
.create_async()
|
||||
.await;
|
||||
let resp = reqwest::get(format!("{}/big", server.url())).await.unwrap();
|
||||
let out = read_body_capped(resp, 8192).await.text;
|
||||
let out = read_body_capped(resp, 8192).await;
|
||||
assert!(out.len() <= 8192, "read not bounded: {} bytes", out.len());
|
||||
assert!(!out.is_empty(), "expected some body");
|
||||
}
|
||||
|
||||
+26
-169
@@ -42,8 +42,6 @@ pub enum WebhookCmd {
|
||||
repo: String,
|
||||
#[arg(long, default_value = "https://node.gitlawb.com", env = "GITLAWB_NODE")]
|
||||
node: String,
|
||||
#[arg(long)]
|
||||
dir: Option<PathBuf>,
|
||||
},
|
||||
/// Delete a webhook
|
||||
Delete {
|
||||
@@ -68,7 +66,7 @@ pub async fn run(args: WebhookArgs) -> Result<()> {
|
||||
node,
|
||||
dir,
|
||||
} => cmd_create(repo, url, events, secret, node, dir).await,
|
||||
WebhookCmd::List { repo, node, dir } => cmd_list(repo, node, dir).await,
|
||||
WebhookCmd::List { repo, node } => cmd_list(repo, node).await,
|
||||
WebhookCmd::Delete {
|
||||
repo,
|
||||
id,
|
||||
@@ -78,6 +76,15 @@ pub async fn run(args: WebhookArgs) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_owner(client: &NodeClient) -> Result<String> {
|
||||
let info: Value = client.get("/").await?.json().await?;
|
||||
let did = info["did"]
|
||||
.as_str()
|
||||
.context("node missing DID")?
|
||||
.to_string();
|
||||
Ok(did.split(':').next_back().unwrap_or(&did).to_string())
|
||||
}
|
||||
|
||||
async fn cmd_create(
|
||||
repo: String,
|
||||
url: String,
|
||||
@@ -87,8 +94,8 @@ async fn cmd_create(
|
||||
dir: Option<PathBuf>,
|
||||
) -> Result<()> {
|
||||
let keypair = load_keypair_from_dir(dir.as_deref())?;
|
||||
let (owner, name) = crate::repo::resolve_owner_repo_pair(&repo, &node, dir.as_deref()).await?;
|
||||
let client = NodeClient::new(&node, Some(keypair));
|
||||
let owner = resolve_owner(&client).await?;
|
||||
|
||||
let event_list: Vec<&str> = events.split(',').map(str::trim).collect();
|
||||
|
||||
@@ -99,7 +106,7 @@ async fn cmd_create(
|
||||
}))?;
|
||||
|
||||
let resp = client
|
||||
.post(&format!("/api/v1/repos/{owner}/{name}/hooks"), &payload)
|
||||
.post(&format!("/api/v1/repos/{owner}/{repo}/hooks"), &payload)
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let status = resp.status();
|
||||
@@ -136,31 +143,18 @@ async fn cmd_create(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_list(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
// The node owner-gates GET /hooks (callback URLs are owner-secret), so the
|
||||
// list request must be signed — anonymous callers get 401.
|
||||
let keypair = load_keypair_from_dir(dir.as_deref())?;
|
||||
let (owner, name) = crate::repo::resolve_owner_repo_pair(&repo, &node, dir.as_deref()).await?;
|
||||
let client = NodeClient::new(&node, Some(keypair));
|
||||
async fn cmd_list(repo: String, node: String) -> Result<()> {
|
||||
let client = NodeClient::new(&node, None);
|
||||
let owner = resolve_owner(&client).await?;
|
||||
|
||||
// get_signed (not get) attaches the RFC 9421 signature — plain get() never
|
||||
// signs, and the node owner-gates this route, so an unsigned GET 401s.
|
||||
let resp = client
|
||||
.get_signed(&format!("/api/v1/repos/{owner}/{name}/hooks"))
|
||||
.await?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await.context("invalid JSON")?;
|
||||
let resp: Value = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.context("invalid JSON")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body["message"].as_str().unwrap_or("unknown error");
|
||||
anyhow::bail!("list webhooks failed ({status}): {msg}");
|
||||
}
|
||||
|
||||
let hooks = body
|
||||
.get("webhooks")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.context("node response missing webhooks array")?;
|
||||
let hooks = resp["webhooks"].as_array().cloned().unwrap_or_default();
|
||||
if hooks.is_empty() {
|
||||
println!("No webhooks for {repo}");
|
||||
return Ok(());
|
||||
@@ -191,13 +185,13 @@ async fn cmd_list(repo: String, node: String, dir: Option<PathBuf>) -> Result<()
|
||||
|
||||
async fn cmd_delete(repo: String, id: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let keypair = load_keypair_from_dir(dir.as_deref())?;
|
||||
let (owner, name) = crate::repo::resolve_owner_repo_pair(&repo, &node, dir.as_deref()).await?;
|
||||
let client = NodeClient::new(&node, Some(keypair));
|
||||
let owner = resolve_owner(&client).await?;
|
||||
|
||||
let payload = serde_json::to_vec(&serde_json::json!({}))?;
|
||||
let resp = client
|
||||
.delete(
|
||||
&format!("/api/v1/repos/{owner}/{name}/hooks/{id}"),
|
||||
&format!("/api/v1/repos/{owner}/{repo}/hooks/{id}"),
|
||||
&payload,
|
||||
)
|
||||
.await
|
||||
@@ -343,170 +337,33 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn test_list_webhooks_empty() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, _kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/hooks$".to_string()))
|
||||
// The route is owner-gated, so the list request must be signed.
|
||||
// Requiring the header here is what catches a regression to plain get().
|
||||
.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#"{"webhooks":[]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
cmd_list("my-repo".to_string(), server.url()).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_webhooks_with_items() {
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, _kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/hooks$".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#"{"webhooks":[{"id":"h1","url":"https://a.com","events":["push"],"active":true},{"id":"h2","url":"https://b.com","events":["*"],"active":false}]}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_owner_comes_from_keypair_not_node_did() {
|
||||
// The owner segment must be derived from the caller's keypair (loaded
|
||||
// from --dir), NOT the node root DID. mock_root returns a different DID;
|
||||
// if the code regressed to using it, this path mock would not match.
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let did = kp.did().to_string();
|
||||
let short = did.split(':').next_back().unwrap_or(&did).to_string();
|
||||
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(format!(r"/api/v1/repos/{short}/my-repo/hooks$")),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"webhooks":[]}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
_m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_honors_owner_repo_arg() {
|
||||
// An explicit `owner/repo` argument is split and used verbatim.
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, _kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let _m = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(r"/api/v1/repos/someoneelse/their-repo/hooks$".to_string()),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"webhooks":[]}"#)
|
||||
.expect(1)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
cmd_list(
|
||||
"someoneelse/their-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
_m.assert_async().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_webhooks_non_success_status_errors() {
|
||||
// A 403 (or any non-2xx) JSON body has no `webhooks` field; cmd_list must
|
||||
// surface the failure, not print "No webhooks" and exit 0.
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, _kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/hooks$".to_string()))
|
||||
.with_status(403)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"not the owner"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("not the owner"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_webhooks_2xx_missing_array_errors() {
|
||||
// A 2xx body without a `webhooks` array signals a node/API contract
|
||||
// regression. cmd_list must error rather than print "No webhooks".
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let (dir, _kp) = tmp_identity();
|
||||
let _root = mock_root(&mut server).await;
|
||||
|
||||
let _m = server
|
||||
.mock("GET", mockito::Matcher::Regex(r"/hooks$".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#"{"ok":true}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let err = cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("missing webhooks array"));
|
||||
cmd_list("my-repo".to_string(), server.url()).await.unwrap();
|
||||
}
|
||||
|
||||
// ── delete ───────────────────────────────────────────────────────
|
||||
|
||||
+14
-334
@@ -1,11 +1,11 @@
|
||||
//! `gl whoami` — print current identity and optional node registration info.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::Result;
|
||||
use clap::Args;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::http::{read_body_capped, sanitize_node_msg, NodeClient};
|
||||
use crate::http::NodeClient;
|
||||
use crate::identity::load_keypair_from_dir;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -22,10 +22,6 @@ pub struct WhoamiArgs {
|
||||
}
|
||||
|
||||
pub async fn run(args: WhoamiArgs) -> Result<()> {
|
||||
run_to_writer(args, &mut std::io::stdout()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run_to_writer(args: WhoamiArgs, w: &mut impl std::io::Write) -> Result<()> {
|
||||
let keypair = load_keypair_from_dir(args.dir.as_deref())?;
|
||||
let did = keypair.did().to_string();
|
||||
let short = did.split(':').next_back().unwrap_or(&did).to_string();
|
||||
@@ -45,7 +41,7 @@ pub(crate) async fn run_to_writer(args: WhoamiArgs, w: &mut impl std::io::Write)
|
||||
if let Some(caps) = info["capabilities"].as_array() {
|
||||
capabilities = caps
|
||||
.iter()
|
||||
.filter_map(|c| c.as_str().map(sanitize_node_msg))
|
||||
.filter_map(|c| c.as_str().map(String::from))
|
||||
.collect();
|
||||
}
|
||||
// Try to get repo count
|
||||
@@ -55,35 +51,11 @@ pub(crate) async fn run_to_writer(args: WhoamiArgs, w: &mut impl std::io::Write)
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(resp) if resp.status().as_u16() == 404 => {
|
||||
Ok(_) => {
|
||||
registered = Some(false);
|
||||
}
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
let raw = read_body_capped(resp, 8 * 1024).await.text;
|
||||
let msg = serde_json::from_str::<Value>(&raw)
|
||||
.ok()
|
||||
.and_then(|v| {
|
||||
let non_empty = |m: Option<&Value>| {
|
||||
m.and_then(|m| m.as_str())
|
||||
.map(String::from)
|
||||
.filter(|s| !s.is_empty())
|
||||
};
|
||||
non_empty(v.get("message")).or_else(|| non_empty(v.get("error")))
|
||||
})
|
||||
.unwrap_or(raw);
|
||||
bail!(
|
||||
"agent lookup failed ({status}): {}",
|
||||
sanitize_node_msg(&msg)
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
let detail: String = e
|
||||
.chain()
|
||||
.map(|e| sanitize_node_msg(&e.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(": ");
|
||||
bail!("agent lookup failed: {detail}");
|
||||
Err(_) => {
|
||||
registered = Some(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,21 +77,21 @@ pub(crate) async fn run_to_writer(args: WhoamiArgs, w: &mut impl std::io::Write)
|
||||
if let Some(rc) = repo_count {
|
||||
out["repos"] = json!(rc);
|
||||
}
|
||||
writeln!(w, "{}", serde_json::to_string_pretty(&out)?)?;
|
||||
println!("{}", serde_json::to_string_pretty(&out)?);
|
||||
} else {
|
||||
writeln!(w, "DID: {did}")?;
|
||||
writeln!(w, "Short: {short}")?;
|
||||
println!("DID: {did}");
|
||||
println!("Short: {short}");
|
||||
if let Some(reg) = registered {
|
||||
writeln!(w, "Registered: {}", if reg { "yes" } else { "no" })?;
|
||||
println!("Registered: {}", if reg { "yes" } else { "no" });
|
||||
}
|
||||
if let Some(ts) = trust_score {
|
||||
writeln!(w, "Trust: {ts:.2}")?;
|
||||
println!("Trust: {ts:.2}");
|
||||
}
|
||||
if !capabilities.is_empty() {
|
||||
writeln!(w, "Caps: {}", capabilities.join(", "))?;
|
||||
println!("Caps: {}", capabilities.join(", "));
|
||||
}
|
||||
if let Some(rc) = repo_count {
|
||||
writeln!(w, "Repos: {rc}")?;
|
||||
println!("Repos: {rc}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -220,236 +192,7 @@ mod tests {
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
run_to_writer(args, &mut out).await.unwrap();
|
||||
let out = String::from_utf8(out).unwrap();
|
||||
assert!(out.contains("Registered: no"), "unexpected output: {out}");
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: true,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
run_to_writer(args, &mut out).await.unwrap();
|
||||
let out = String::from_utf8(out).unwrap();
|
||||
assert!(
|
||||
out.contains("\"registered\": false"),
|
||||
"unexpected output: {out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_with_node_forbidden() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(403)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"forbidden"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(msg.contains("403"), "expected 403 error, got: {msg}");
|
||||
assert!(
|
||||
msg.contains("forbidden"),
|
||||
"expected 'forbidden' in error, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_with_node_server_error() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(500)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"internal error"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(msg.contains("500"), "expected 500 error, got: {msg}");
|
||||
assert!(
|
||||
msg.contains("internal error"),
|
||||
"expected 'internal error' in error, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_server_error_unusable_message_uses_error() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(500)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"message":"","error":"boom"}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(
|
||||
msg.contains("boom"),
|
||||
"expected 'boom' from error field, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_with_node_transport_error() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let node = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(node),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(
|
||||
msg.contains("agent lookup failed"),
|
||||
"expected transport error, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_transport_sanitizes_control_chars_in_node_url() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
|
||||
let node = format!("http://127.0.0.1:{port}/\u{1b}]0;PWNED\u{7} \u{202e}gnitirw");
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(node),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(
|
||||
msg.contains("agent lookup failed"),
|
||||
"expected transport error, got: {msg}"
|
||||
);
|
||||
assert!(!msg.contains('\u{1b}'), "ESC leaked into output: {msg:?}");
|
||||
assert!(!msg.contains('\u{7}'), "BEL leaked into output: {msg:?}");
|
||||
assert!(!msg.contains('\u{202e}'), "RLO leaked into output: {msg:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_server_error_body_display_bounded() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(502)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body("x".repeat(100_000))
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(
|
||||
msg.contains("502"),
|
||||
"expected 502 error with bounded body, got: {msg}"
|
||||
);
|
||||
let display = format!("{err}");
|
||||
assert!(
|
||||
display.len() < 1000,
|
||||
"error message too long ({} bytes) — body was not capped",
|
||||
display.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_server_error_sanitizes_controls() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(500)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body("{\"message\":\"\\u001b[31mowned\\u0007\\u202eevil\"}")
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
let err = run(args).await.unwrap_err();
|
||||
let msg = format!("{err:?}");
|
||||
assert!(
|
||||
msg.contains("owned"),
|
||||
"expected sanitized error body, got: {msg}"
|
||||
);
|
||||
assert!(!msg.contains('\u{1b}'), "ESC control char leaked: {msg}");
|
||||
assert!(!msg.contains('\u{07}'), "BEL control char leaked: {msg}");
|
||||
assert!(!msg.contains('\u{202e}'), "RTL override leaked: {msg}");
|
||||
run(args).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -487,67 +230,4 @@ mod tests {
|
||||
};
|
||||
run(args).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_whoami_sanitizes_hostile_capabilities() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let kp = gitlawb_core::identity::Keypair::generate();
|
||||
let pem = kp.to_pem().unwrap();
|
||||
std::fs::write(dir.path().join("identity.pem"), pem.as_bytes()).unwrap();
|
||||
let did = kp.did().to_string();
|
||||
let short = did.split(':').next_back().unwrap().to_string();
|
||||
|
||||
let mut server = mockito::Server::new_async().await;
|
||||
let _agent = server
|
||||
.mock("GET", format!("/api/v1/agents/{did}").as_str())
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(
|
||||
"{\"trust_score\":0.5,\"capabilities\":[\"\\u001b]0;PWNED\\u0007repo:write\",\"\\u202egnitirw-tfel\"]}",
|
||||
)
|
||||
.create_async()
|
||||
.await;
|
||||
let _repos = server
|
||||
.mock(
|
||||
"GET",
|
||||
mockito::Matcher::Regex(format!(r"^/api/v1/repos\?owner={short}")),
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body("[]")
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
// Human mode: no control bytes or bidi overrides reach the terminal
|
||||
let mut buf = Vec::new();
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: false,
|
||||
};
|
||||
run_to_writer(args, &mut buf).await.unwrap();
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
assert!(!out.contains('\u{1b}'), "ESC leaked in human mode: {out:?}");
|
||||
assert!(!out.contains('\u{07}'), "BEL leaked in human mode: {out:?}");
|
||||
assert!(
|
||||
!out.contains('\u{202e}'),
|
||||
"RLO leaked in human mode: {out:?}"
|
||||
);
|
||||
assert!(out.contains("repo:write"), "benign text missing: {out:?}");
|
||||
assert!(out.contains("tfel"), "reversed text missing: {out:?}");
|
||||
|
||||
// JSON mode: serde escapes C0 but passes bidi — ensure no U+202E
|
||||
let mut buf = Vec::new();
|
||||
let args = WhoamiArgs {
|
||||
dir: Some(dir.path().to_path_buf()),
|
||||
node: Some(server.url()),
|
||||
json: true,
|
||||
};
|
||||
run_to_writer(args, &mut buf).await.unwrap();
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
assert!(
|
||||
!out.contains('\u{202e}'),
|
||||
"RLO leaked in JSON mode: {out:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,3 @@ anyhow = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
mockito = "1"
|
||||
@@ -64,12 +64,6 @@ fn sanitize_excerpt(s: &str) -> String {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if gitlawb_core::sanitize::is_bidi_format(ch) {
|
||||
// Drop Cf bidi/format controls (INV-6, #183) without setting
|
||||
// pending_space: they are not whitespace, so stripping leaves no
|
||||
// phantom gap.
|
||||
continue;
|
||||
}
|
||||
if ch.is_whitespace() {
|
||||
pending_space = true;
|
||||
continue;
|
||||
@@ -427,34 +421,6 @@ mod tests {
|
||||
assert!(clean.contains("owned") && clean.contains("done"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_strips_bidi_format_controls() {
|
||||
// The Cc-only test above is vacuous for Cf: it passes whether or not bidi
|
||||
// controls survive, which is why this gap shipped (#183). Here every Cf
|
||||
// bidi class is stripped — override (RLO), embedding + pop (LRE/PDF),
|
||||
// isolate (LRI/PDI), marks (LRM/ALM) — asserted per code point, and the
|
||||
// visible words JOIN with no phantom space (a bidi char is dropped like a
|
||||
// control byte, but unlike a newline/tab it is not whitespace). The leading
|
||||
// bidi char (index 0) also exercises the empty-out path.
|
||||
let out = sanitize_excerpt("\u{202e}err\u{202a}\u{202c}\u{2066}\u{2069}\u{200e}\u{061c}ok");
|
||||
for c in [
|
||||
'\u{202e}', '\u{202a}', '\u{202c}', '\u{2066}', '\u{2069}', '\u{200e}', '\u{061c}',
|
||||
] {
|
||||
assert!(!out.contains(c), "bidi U+{:04X} leaked: {out:?}", c as u32);
|
||||
}
|
||||
assert_eq!(out, "errok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_preserves_legitimate_and_rtl_text() {
|
||||
// Must not over-strip: plain text, a genuine RTL SCRIPT letter (Arabic
|
||||
// U+0627, category Lo), and ZWJ (U+200D, a legitimate Cf char) survive.
|
||||
assert_eq!(
|
||||
sanitize_excerpt("ok \u{0627}\u{200D}b"),
|
||||
"ok \u{0627}\u{200D}b"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_collapses_whitespace_and_caps_length() {
|
||||
let collapsed = sanitize_excerpt("a\n\n\t b");
|
||||
@@ -463,18 +429,6 @@ mod tests {
|
||||
assert_eq!(sanitize_excerpt(&long).chars().count(), MAX_ERR_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_bidi_chars_do_not_consume_the_length_cap() {
|
||||
// A dropped bidi char must not count toward MAX_ERR_CHARS: it is dropped
|
||||
// before `kept` increments, so interleaving bidi controls cannot truncate
|
||||
// the visible output early. MAX_ERR_CHARS + 100 visible 'x', each trailed by
|
||||
// a bidi override, must still yield exactly MAX_ERR_CHARS visible 'x' with
|
||||
// no phantom spaces. (Would regress to fewer 'x' if bidi consumed budget, or
|
||||
// to spaces if the drop branch wrongly set pending_space.)
|
||||
let body = "x\u{202e}".repeat(MAX_ERR_CHARS + 100);
|
||||
assert_eq!(sanitize_excerpt(&body), "x".repeat(MAX_ERR_CHARS));
|
||||
}
|
||||
|
||||
// ── P2: never talk to (or hand a key to) an untrusted node-chosen URL ──
|
||||
|
||||
#[test]
|
||||
@@ -550,215 +504,4 @@ mod tests {
|
||||
);
|
||||
assert!(key_trusted, "key stays trusted with operator origin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_withholds_key_from_untrusted_origin_but_attaches_for_operator() {
|
||||
let guard = ICAPTCHA_ENV_LOCK.lock().unwrap();
|
||||
let prev_key = std::env::var_os("GITLAWB_ICAPTCHA_API_KEY");
|
||||
let prev_op = std::env::var_os("GITLAWB_ICAPTCHA_URL");
|
||||
std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", "secret-bearer");
|
||||
|
||||
// Arm 1: No operator configured, node advertises an attacker origin.
|
||||
// The key has no trusted destination; the advert is rejected.
|
||||
std::env::remove_var("GITLAWB_ICAPTCHA_URL");
|
||||
let untrusted =
|
||||
IcaptchaCfg::new("did:key:zTEST", Some("https://evil.example".into()), None);
|
||||
|
||||
// Arm 1b: No operator configured, no URL advertised. The fallback goes
|
||||
// to the default public origin, and with no operator to trust, the key
|
||||
// must not ride.
|
||||
let no_operator_no_advert = IcaptchaCfg::new("did:key:zTEST", None, None);
|
||||
|
||||
// Arm 2: Operator origin configured and advertised — key attached.
|
||||
std::env::set_var("GITLAWB_ICAPTCHA_URL", "https://icap.mynode.example");
|
||||
let operator_match = IcaptchaCfg::new(
|
||||
"did:key:zTEST",
|
||||
Some("https://icap.mynode.example/v1".into()),
|
||||
None,
|
||||
);
|
||||
|
||||
// Arm 3: Operator configured, default host advertised. The default host
|
||||
// is allowlisted and selected, but its origin differs from the
|
||||
// operator's, so key must not ride.
|
||||
let default_advert = IcaptchaCfg::new(
|
||||
"did:key:zTEST",
|
||||
Some("https://icaptcha.gitlawb.com/v2".into()),
|
||||
None,
|
||||
);
|
||||
|
||||
// Arm 4: Operator configured, no URL advertised (the node sent only
|
||||
// x-icaptcha-level, not x-icaptcha-url). resolve_solver_url falls back
|
||||
// to the operator origin and marks the key trusted. This is the common
|
||||
// API-key deployment path — a regression that additionally required
|
||||
// url.is_some() for key attachment would leave all current tests green
|
||||
// but make these fallback challenge/answer requests omit Authorization
|
||||
// and fail against the protected operator service.
|
||||
let operator_fallback = IcaptchaCfg::new("did:key:zTEST", None, Some(3));
|
||||
|
||||
// Arm 5: Operator configured, node advertises an attacker origin.
|
||||
// The advert is rejected and the solver falls back to the operator's
|
||||
// own origin, which keeps the key trusted — this is the exfiltration
|
||||
// scenario the test name describes (withhold key from *untrusted*
|
||||
// origin, not from the operator's fallback).
|
||||
let operator_hostile_advert =
|
||||
IcaptchaCfg::new("did:key:zTEST", Some("https://evil.example".into()), None);
|
||||
|
||||
// Arm 6: Operator configured, same host but different port.
|
||||
// origin_key includes the port, so :8443 must not match the
|
||||
// operator origin at the default :443 — the advert is rejected
|
||||
// and the solver falls back to the operator origin.
|
||||
let operator_diff_port = IcaptchaCfg::new(
|
||||
"did:key:zTEST",
|
||||
Some("https://icap.mynode.example:8443/evil".into()),
|
||||
None,
|
||||
);
|
||||
|
||||
// Restore env and release the lock BEFORE asserting, so a failing
|
||||
// assertion can't poison the shared lock or cascade into a sibling.
|
||||
match prev_key {
|
||||
Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", v),
|
||||
None => std::env::remove_var("GITLAWB_ICAPTCHA_API_KEY"),
|
||||
}
|
||||
match prev_op {
|
||||
Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_URL", v),
|
||||
None => std::env::remove_var("GITLAWB_ICAPTCHA_URL"),
|
||||
}
|
||||
drop(guard);
|
||||
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
|
||||
if untrusted.api_key.is_some() {
|
||||
failures.push(format!(
|
||||
"arm 1 (no operator, attacker advert): expected api_key=None, got {:?}",
|
||||
untrusted.api_key
|
||||
));
|
||||
}
|
||||
if untrusted.url != DEFAULT_URL {
|
||||
failures.push(format!(
|
||||
"arm 1 (no operator, attacker advert): expected url={DEFAULT_URL}, got {}",
|
||||
untrusted.url
|
||||
));
|
||||
}
|
||||
|
||||
if no_operator_no_advert.api_key.is_some() {
|
||||
failures.push(format!(
|
||||
"arm 1b (no operator, no advert): expected api_key=None, got {:?}",
|
||||
no_operator_no_advert.api_key
|
||||
));
|
||||
}
|
||||
if no_operator_no_advert.url != DEFAULT_URL {
|
||||
failures.push(format!(
|
||||
"arm 1b (no operator, no advert): expected url={DEFAULT_URL}, got {}",
|
||||
no_operator_no_advert.url
|
||||
));
|
||||
}
|
||||
|
||||
if operator_match.api_key.as_deref() != Some("secret-bearer") {
|
||||
failures.push(format!(
|
||||
"arm 2 (operator match): expected api_key=Some(\"secret-bearer\"), got {:?}",
|
||||
operator_match.api_key
|
||||
));
|
||||
}
|
||||
if operator_match.url != "https://icap.mynode.example/v1" {
|
||||
failures.push(format!(
|
||||
"arm 2 (operator match): expected url=https://icap.mynode.example/v1, got {}",
|
||||
operator_match.url
|
||||
));
|
||||
}
|
||||
|
||||
if default_advert.api_key.is_some() {
|
||||
failures.push(format!(
|
||||
"arm 3 (operator + default advert): expected api_key=None, got {:?}",
|
||||
default_advert.api_key
|
||||
));
|
||||
}
|
||||
if default_advert.url != "https://icaptcha.gitlawb.com/v2" {
|
||||
failures.push(format!(
|
||||
"arm 3 (operator + default advert): expected url=https://icaptcha.gitlawb.com/v2, got {}",
|
||||
default_advert.url
|
||||
));
|
||||
}
|
||||
|
||||
if operator_fallback.api_key.as_deref() != Some("secret-bearer") {
|
||||
failures.push(format!(
|
||||
"arm 4 (operator fallback, no advert): expected api_key=Some(\"secret-bearer\"), got {:?}",
|
||||
operator_fallback.api_key
|
||||
));
|
||||
}
|
||||
if operator_fallback.url != "https://icap.mynode.example" {
|
||||
failures.push(format!(
|
||||
"arm 4 (operator fallback, no advert): expected url=https://icap.mynode.example, got {}",
|
||||
operator_fallback.url
|
||||
));
|
||||
}
|
||||
|
||||
if operator_hostile_advert.api_key.as_deref() != Some("secret-bearer") {
|
||||
failures.push(format!(
|
||||
"arm 5 (operator + hostile advert): expected api_key=Some(\"secret-bearer\"), got {:?}",
|
||||
operator_hostile_advert.api_key
|
||||
));
|
||||
}
|
||||
if operator_hostile_advert.url != "https://icap.mynode.example" {
|
||||
failures.push(format!(
|
||||
"arm 5 (operator + hostile advert): expected url=https://icap.mynode.example, got {}",
|
||||
operator_hostile_advert.url
|
||||
));
|
||||
}
|
||||
|
||||
if operator_diff_port.api_key.as_deref() != Some("secret-bearer") {
|
||||
failures.push(format!(
|
||||
"arm 6 (operator + different port advert): expected api_key=Some(\"secret-bearer\"), got {:?}",
|
||||
operator_diff_port.api_key
|
||||
));
|
||||
}
|
||||
if operator_diff_port.url != "https://icap.mynode.example" {
|
||||
failures.push(format!(
|
||||
"arm 6 (operator + different port advert): expected url=https://icap.mynode.example, got {}",
|
||||
operator_diff_port.url
|
||||
));
|
||||
}
|
||||
|
||||
assert!(failures.is_empty(), "\n{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_normalizes_empty_api_key_to_none_on_trusted_origin() {
|
||||
let guard = ICAPTCHA_ENV_LOCK.lock().unwrap();
|
||||
let prev_key = std::env::var_os("GITLAWB_ICAPTCHA_API_KEY");
|
||||
let prev_op = std::env::var_os("GITLAWB_ICAPTCHA_URL");
|
||||
|
||||
// Operator origin configured and resolved as trusted (no advert), so
|
||||
// api_key reaches the env read and the emptiness filter is the only
|
||||
// thing standing between a blank var and an empty bearer token.
|
||||
std::env::set_var("GITLAWB_ICAPTCHA_URL", "https://icap.mynode.example");
|
||||
|
||||
// "Operator set the var but left it blank" must stay keyless: a
|
||||
// Some("") would attach `Authorization: Bearer ` (empty token) to the
|
||||
// challenge and answer requests instead of omitting the header.
|
||||
std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", "");
|
||||
let empty = IcaptchaCfg::new("did:key:zTEST", None, None);
|
||||
|
||||
// Contrast arm: a real key on the same trusted path must survive the
|
||||
// filter, so the filter can't regress to dropping every key.
|
||||
std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", "secret-bearer");
|
||||
let non_empty = IcaptchaCfg::new("did:key:zTEST", None, None);
|
||||
|
||||
// Restore env and release the lock BEFORE asserting, so a failing
|
||||
// assertion can't poison the shared lock or cascade into a sibling.
|
||||
match prev_key {
|
||||
Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", v),
|
||||
None => std::env::remove_var("GITLAWB_ICAPTCHA_API_KEY"),
|
||||
}
|
||||
match prev_op {
|
||||
Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_URL", v),
|
||||
None => std::env::remove_var("GITLAWB_ICAPTCHA_URL"),
|
||||
}
|
||||
drop(guard);
|
||||
|
||||
assert_eq!(
|
||||
empty.api_key, None,
|
||||
"empty GITLAWB_ICAPTCHA_API_KEY must normalize to None"
|
||||
);
|
||||
assert_eq!(non_empty.api_key.as_deref(), Some("secret-bearer"));
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
//! Tripwire: a committed negative case that locks the blackhole mechanism.
|
||||
//!
|
||||
//! The guard against non-loopback egress works because `obtain_proof` builds a
|
||||
//! stock `reqwest::blocking::Client` that inherits the process's proxy env vars.
|
||||
//! If the builder later gains `.no_proxy()` or a custom connector, the guard
|
||||
//! disarms silently and every existing test stays green (no live call is made
|
||||
//! during the normal mock-consumed run because the mock is on loopback and
|
||||
//! `NO_PROXY` covers it — the blackhole isn't even exercised).
|
||||
//!
|
||||
//! This test asserts that a destination the blackhole's `NO_PROXY` does NOT
|
||||
//! cover fails *while the blackhole is armed*. The destination is a local HTTP
|
||||
//! server on `[::1]` (IPv6 loopback), which `NO_PROXY` (`127.0.0.1, localhost`)
|
||||
//! does not list. With the blackhole active the proxy intercepts the
|
||||
//! connection and blocks it; without the blackhole the request would reach the
|
||||
//! server directly and succeed, turning this test RED.
|
||||
//!
|
||||
//! A positive control (disarmed blackhole) runs first, proving the fixture is
|
||||
//! valid and `[::1]` is reachable.
|
||||
//!
|
||||
//! Design constraints (see issue #211):
|
||||
//! - An unresolvable host would keep the request failing even when the guard
|
||||
//! is disarmed (DNS failure masquerading as the blackhole), so we must use
|
||||
//! a reachable address.
|
||||
//! - A real external host would make a live network call the moment the guard
|
||||
//! disarms, and on any runner that cannot reach that host the connect error
|
||||
//! again masquerades as the blackhole. A local loopback address avoids both
|
||||
//! problems — it is always reachable when unblocked and never reaches the
|
||||
//! real network.
|
||||
//! - The address must NOT be covered by `NO_PROXY`, yet must exist on every
|
||||
//! platform. An arbitrary `127/8` alias is not portable: macOS only binds
|
||||
//! `127.0.0.1` by default. `[::1]` (IPv6 loopback) is present by default
|
||||
//! on Linux, macOS, and Windows, and `NO_PROXY` only lists `127.0.0.1` and
|
||||
//! `localhost`, so the blackhole still intercepts it.
|
||||
//! - This depends on hyper-util's proxy matcher having no implicit loopback
|
||||
//! bypass — a host is only proxied-around when literally listed in
|
||||
//! `NO_PROXY` (verified in the pinned hyper-util; recheck on upgrade).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
use icaptcha_client::{obtain_proof, Challenge, IcaptchaCfg};
|
||||
|
||||
mod support;
|
||||
|
||||
/// A minimal HTTP server that responds to iCaptcha challenge and answer
|
||||
/// requests on the IPv6 loopback address NOT covered by NO_PROXY.
|
||||
///
|
||||
/// When the blackhole is working, the proxy should intercept these requests
|
||||
/// and `obtain_proof` should fail. When the blackhole is disarmed, the
|
||||
/// requests reach this server and the flow succeeds.
|
||||
fn serve_icaptcha(listener: TcpListener) {
|
||||
thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { continue };
|
||||
// Read until the first \n (end of request line) so TCP
|
||||
// segmentation cannot split the path out of a single read.
|
||||
let mut buf = [0u8; 4096];
|
||||
let mut n = 0usize;
|
||||
while n < buf.len() {
|
||||
match stream.read(&mut buf[n..]) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(read) => {
|
||||
n += read;
|
||||
if buf[..n].contains(&b'\n') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let request = String::from_utf8_lossy(&buf[..n]);
|
||||
let body = if request.contains("/v1/answer") {
|
||||
r#"{"status":"passed","proof":"PROOF-TRIP"}"#
|
||||
} else {
|
||||
r#"{"challengeId":"c1","type":"anagram","difficulty":1,"prompt":"listen","token":"tok-1"}"#
|
||||
};
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len(),
|
||||
);
|
||||
let _ = stream.write_all(response.as_bytes());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn make_cfg(url: &str) -> IcaptchaCfg {
|
||||
IcaptchaCfg {
|
||||
url: url.to_string(),
|
||||
did: "did:key:zTEST".to_string(),
|
||||
level: 1,
|
||||
api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obtain_proof_blackhole_tripwire() {
|
||||
// Bind to [::1], IPv6 loopback, which NO_PROXY (127.0.0.1, localhost)
|
||||
// does not cover. Unlike an arbitrary 127/8 alias, IPv6 loopback is
|
||||
// present by default on Linux, macOS, and Windows, so the fixture is
|
||||
// portable across platforms. Fail loudly if it cannot be bound: a
|
||||
// silent skip would report this tripwire as green while exercising
|
||||
// none of the negative control, recreating the very gap it exists to
|
||||
// close.
|
||||
let listener = TcpListener::bind(("::1", 0)).expect(
|
||||
"cannot bind [::1] for the blackhole tripwire. IPv6 loopback (::1) \
|
||||
is present by default on Linux, macOS, and Windows. This test fails \
|
||||
rather than silently skipping so a platform without it cannot count \
|
||||
the negative control as passed.",
|
||||
);
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let url = format!("http://[::1]:{port}");
|
||||
serve_icaptcha(listener);
|
||||
|
||||
// ── Positive control: disarmed blackhole → obtain_proof succeeds ──────
|
||||
let _disarmed_guard = support::disarm_proxy_env();
|
||||
|
||||
let solve: &dyn Fn(&Challenge) -> Option<String> = &|_c| Some("silent".to_string());
|
||||
let cfg = make_cfg(&url);
|
||||
let proof = obtain_proof(&cfg, Some(solve))
|
||||
.expect("positive control: obtain_proof should succeed when the proxy is disarmed");
|
||||
assert_eq!(
|
||||
proof, "PROOF-TRIP",
|
||||
"positive control: unexpected proof value"
|
||||
);
|
||||
drop(_disarmed_guard);
|
||||
|
||||
// ── Negative control: armed blackhole → obtain_proof fails with connect error ──
|
||||
let _armed_guard = support::arm_blackhole("http://127.0.0.1:1");
|
||||
|
||||
let result = obtain_proof(&cfg, Some(solve));
|
||||
|
||||
let err = result.expect_err(
|
||||
"blackhole tripwire: obtain_proof succeeded against [::1], \
|
||||
meaning the proxy blackhole did not intercept the request; \
|
||||
the no-live-call guard is disarmed",
|
||||
);
|
||||
assert!(
|
||||
err.chain().any(|c| c
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.is_some_and(|e| e.is_connect())),
|
||||
"expected a connect/proxy error, got: {err:#}",
|
||||
);
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
//! INV-19 guard: the icaptcha flow must actually call the service (consuming the
|
||||
//! mock), not short-circuit or make a live call. If a future change let
|
||||
//! `obtain_proof` skip the network (e.g. a stray `cfg(test)` relaxation, which
|
||||
//! INV-19/INV-20 warn is inert across crates), the `.assert()` calls below go
|
||||
//! RED because the mocked endpoints were never hit.
|
||||
//!
|
||||
//! The mock-consumed assertions alone only prove the mock was hit; they cannot
|
||||
//! see a request that ALSO leaks the DID / answer / API key to `DEFAULT_URL` or
|
||||
//! any other origin (a different host the mock never observes). To make the
|
||||
//! "no live call" half of the guard load-bearing, the test blackholes every
|
||||
//! non-loopback destination via a proxy observer: `NO_PROXY` lets the loopback
|
||||
//! mock through while every proxy variable routes any other host through a TCP
|
||||
//! listener that counts connections. Zero observed connections proves no leak
|
||||
//! reached the network on the exercised path.
|
||||
//!
|
||||
//! The observer design counts every accepted connection regardless of whether
|
||||
//! the caller propagates the transport error, so it catches leaks that a
|
||||
//! closed-port blackhole (which only surfaces propagating errors) would miss.
|
||||
//! To close the timing race inherent in a detached accept loop, the count is
|
||||
//! read only after a bounded drain: the test opens a flush connection and
|
||||
//! blocks until the accept thread has accepted *that specific connection*
|
||||
//! (tagged by its source port), not merely until any next counter tick.
|
||||
//! Because `accept()` hands out connections FIFO, every leak connection that
|
||||
//! completed its TCP handshake before the flush is counted before the flush —
|
||||
//! the assertion therefore covers all egress in flight when `obtain_proof`
|
||||
//! returned. A leak that starts its handshake after the drain is outside the
|
||||
//! window; that is the irreducible limit of observing a detached accept loop,
|
||||
//! and it is the remaining, well-defined gap this guard accepts.
|
||||
//!
|
||||
//! SCOPE: The observer only witnesses leaks issued on the path this test drives
|
||||
//! (a single passing round, 200 on both endpoints, no PoW, no Continue/Failed,
|
||||
//! no non-2xx response). A leak living on an error or retry branch makes no
|
||||
//! connection during the run and the zero-count assertion stays green. The
|
||||
//! guarantee covers only the exercised happy path and proxy-honoring transports;
|
||||
//! a future `.no_proxy()` or raw `TcpStream` bypasses the observer entirely.
|
||||
//!
|
||||
//! `ALL_PROXY` alone is NOT enough: reqwest honors the scheme-specific
|
||||
//! `HTTPS_PROXY` / `https_proxy` (and the http equivalents) OVER `ALL_PROXY`, so
|
||||
//! a runner with a working `HTTPS_PROXY` in its environment would route an https
|
||||
//! leak to `DEFAULT_URL` (which is https) through that proxy while the loopback
|
||||
//! mock is still consumed and this test stayed green. So we blackhole the
|
||||
//! scheme-specific variables too.
|
||||
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
|
||||
use icaptcha_client::{obtain_proof, Challenge, IcaptchaCfg};
|
||||
|
||||
mod support;
|
||||
|
||||
/// A TCP listener that counts every accepted connection.
|
||||
///
|
||||
/// Acts as the proxy target: any leaked connection to a non-loopback
|
||||
/// destination will be routed through this listener and counted. Every
|
||||
/// accepted connection is recorded by its source port so the test's own
|
||||
/// flush connection ([`ProxyObserver::drain`]) can be recognised and
|
||||
/// excluded from the leak count.
|
||||
struct ProxyObserver {
|
||||
_listener: Arc<TcpListener>,
|
||||
port: u16,
|
||||
/// Source ports of every accepted connection, in accept order.
|
||||
accepted: Arc<Mutex<Vec<u16>>>,
|
||||
/// Source ports of the test's own flush connections (never counted).
|
||||
flush_ports: Arc<Mutex<Vec<u16>>>,
|
||||
/// Signalled after each accept so `drain` can wait on the flush.
|
||||
ack: Arc<Condvar>,
|
||||
}
|
||||
|
||||
impl ProxyObserver {
|
||||
fn bind() -> Self {
|
||||
let listener = Arc::new(TcpListener::bind("127.0.0.1:0").expect("bind proxy observer"));
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let accepted = Arc::new(Mutex::new(Vec::new()));
|
||||
let flush_ports = Arc::new(Mutex::new(Vec::new()));
|
||||
let ack = Arc::new(Condvar::new());
|
||||
let a = Arc::clone(&accepted);
|
||||
let c = Arc::clone(&ack);
|
||||
let l = Arc::clone(&listener);
|
||||
std::thread::spawn(move || {
|
||||
for stream in l.incoming() {
|
||||
let Ok(stream) = stream else { continue };
|
||||
a.lock()
|
||||
.unwrap()
|
||||
.push(stream.peer_addr().map(|a| a.port()).unwrap_or(0));
|
||||
c.notify_all();
|
||||
}
|
||||
});
|
||||
ProxyObserver {
|
||||
_listener: listener,
|
||||
port,
|
||||
accepted,
|
||||
flush_ports,
|
||||
ack,
|
||||
}
|
||||
}
|
||||
|
||||
fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Number of accepted connections that are not the test's own flush
|
||||
/// connections — i.e. the leak count.
|
||||
fn count(&self) -> usize {
|
||||
let flush = self.flush_ports.lock().unwrap();
|
||||
let accepted = self.accepted.lock().unwrap();
|
||||
accepted.iter().filter(|p| !flush.contains(p)).count()
|
||||
}
|
||||
|
||||
/// Bounded acknowledgement barrier for the accept loop.
|
||||
///
|
||||
/// Opens a flush connection and blocks until the accept thread has
|
||||
/// accepted *that connection* (identified by its source port), bounded by
|
||||
/// a timeout. Because `accept()` hands out connections FIFO, once the
|
||||
/// flush is accepted every connection that completed its handshake before
|
||||
/// it has been accepted and recorded too — so counting on afterwards
|
||||
/// cannot miss a leak that was already in flight. The flush connection
|
||||
/// itself is never counted.
|
||||
///
|
||||
/// A counter-tick barrier would be unsound here: sampling "current + 1"
|
||||
/// and waiting for any increment lets a leak accepted after the sample
|
||||
/// satisfy the wait, and the flush is then miscounted as that leak.
|
||||
fn drain(&self) {
|
||||
let flush =
|
||||
TcpStream::connect(("127.0.0.1", self.port)).expect("observer flush connection");
|
||||
let flush_port = flush.local_addr().unwrap().port();
|
||||
self.flush_ports.lock().unwrap().push(flush_port);
|
||||
let mut accepted = self.accepted.lock().unwrap();
|
||||
while !accepted.contains(&flush_port) {
|
||||
let (guard, timed_out) = self
|
||||
.ack
|
||||
.wait_timeout(accepted, std::time::Duration::from_secs(5))
|
||||
.unwrap();
|
||||
accepted = guard;
|
||||
assert!(
|
||||
!timed_out.timed_out(),
|
||||
"proxy observer drain timed out; accept loop stalled"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obtain_proof_consumes_the_mocked_service_and_makes_no_live_call() {
|
||||
let observer = ProxyObserver::bind();
|
||||
let _guard = support::arm_blackhole(&format!("http://127.0.0.1:{}", observer.port()));
|
||||
|
||||
let mut server = mockito::Server::new();
|
||||
|
||||
let challenge = server
|
||||
.mock("POST", "/v1/challenge")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(
|
||||
r#"{"challengeId":"c1","type":"anagram","difficulty":1,"prompt":"listen","token":"tok-1"}"#,
|
||||
)
|
||||
.expect(1)
|
||||
.create();
|
||||
|
||||
let answer = server
|
||||
.mock("POST", "/v1/answer")
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"{"status":"passed","proof":"PROOF-XYZ"}"#)
|
||||
.expect(1)
|
||||
.create();
|
||||
|
||||
let cfg = IcaptchaCfg {
|
||||
url: server.url(),
|
||||
did: "did:key:zTEST".to_string(),
|
||||
level: 1,
|
||||
api_key: None,
|
||||
};
|
||||
|
||||
let solve = |_c: &Challenge| Some("silent".to_string());
|
||||
let solver: &dyn Fn(&Challenge) -> Option<String> = &solve;
|
||||
|
||||
let count_before = observer.count();
|
||||
|
||||
let proof = obtain_proof(&cfg, Some(solver))
|
||||
.expect("obtain_proof should complete against the mocked service");
|
||||
assert_eq!(proof, "PROOF-XYZ");
|
||||
|
||||
challenge.assert();
|
||||
answer.assert();
|
||||
|
||||
// Drain the accept loop before asserting: the flush connection is not
|
||||
// counted, and because accept() is FIFO every leak connection that
|
||||
// completed its handshake before the flush is recorded before the flush
|
||||
// is — so the count after drain reflects all egress in flight during the
|
||||
// call.
|
||||
observer.drain();
|
||||
let leak_count = observer.count() - count_before;
|
||||
|
||||
assert_eq!(
|
||||
leak_count, 0,
|
||||
"proxy observer caught leaked connections; \
|
||||
the blackhole failed to contain egress"
|
||||
);
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
//! Shared helpers for the icaptcha-client integration tests.
|
||||
//!
|
||||
//! CONCURRENCY CONSTRAINT: [`arm_blackhole`] and [`disarm_proxy_env`] mutate
|
||||
//! process-wide proxy env vars and restore them on drop. Each test binary
|
||||
//! that consumes this module currently has exactly one `#[test]`, so there is
|
||||
//! no concurrent use. `cargo test` runs tests within a binary in parallel by
|
||||
//! default, so the NEXT test added to either file MUST be serialized against
|
||||
//! these helpers (e.g. a shared `Mutex` in this module, or the `serial_test`
|
||||
//! crate) or it will race on the proxy vars.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
const PROXY_VARS: &[&str] = &[
|
||||
"NO_PROXY",
|
||||
"no_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"REQUEST_METHOD",
|
||||
];
|
||||
|
||||
/// Captures the current values of a set of env vars and restores them on drop.
|
||||
pub struct EnvSnapshot(Vec<(String, Option<OsString>)>);
|
||||
|
||||
impl EnvSnapshot {
|
||||
pub fn capture(vars: &[&str]) -> Self {
|
||||
EnvSnapshot(
|
||||
vars.iter()
|
||||
.map(|v| (v.to_string(), std::env::var_os(v)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EnvSnapshot {
|
||||
fn drop(&mut self) {
|
||||
for (var, val) in &self.0 {
|
||||
match val {
|
||||
Some(v) => std::env::set_var(var, v),
|
||||
None => std::env::remove_var(var),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard that restores env vars captured at construction time.
|
||||
pub struct EnvGuard {
|
||||
_prev: EnvSnapshot,
|
||||
}
|
||||
|
||||
/// Override every proxy-related env var so that non-loopback destinations are
|
||||
/// forced through `proxy_url`, with NO_PROXY covering loopback. Also clears
|
||||
/// REQUEST_METHOD, which causes hyper-util to ignore all proxy variables when
|
||||
/// set. Restores prior values on drop.
|
||||
///
|
||||
/// Not safe to call from concurrent tests (see module docs).
|
||||
pub fn arm_blackhole(proxy_url: &str) -> EnvGuard {
|
||||
let prev = EnvSnapshot::capture(PROXY_VARS);
|
||||
|
||||
std::env::set_var("NO_PROXY", "127.0.0.1,localhost");
|
||||
std::env::set_var("no_proxy", "127.0.0.1,localhost");
|
||||
for var in [
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
] {
|
||||
std::env::set_var(var, proxy_url);
|
||||
}
|
||||
std::env::remove_var("REQUEST_METHOD");
|
||||
|
||||
EnvGuard { _prev: prev }
|
||||
}
|
||||
|
||||
/// Clear every proxy-related env var so connections go direct. Restores
|
||||
/// prior values on drop.
|
||||
///
|
||||
/// Not safe to call from concurrent tests (see module docs).
|
||||
#[allow(dead_code)]
|
||||
pub fn disarm_proxy_env() -> EnvGuard {
|
||||
let prev = EnvSnapshot::capture(PROXY_VARS);
|
||||
|
||||
for var in PROXY_VARS {
|
||||
std::env::remove_var(var);
|
||||
}
|
||||
|
||||
EnvGuard { _prev: prev }
|
||||
}
|
||||
@@ -44,10 +44,6 @@ services:
|
||||
GITLAWB_BOOTSTRAP_PEERS: ${GITLAWB_BOOTSTRAP_PEERS:-}
|
||||
GITLAWB_BOOTSTRAP_DISABLE_SEEDS: ${GITLAWB_BOOTSTRAP_DISABLE_SEEDS:-false}
|
||||
GITLAWB_REQUIRE_SIGNED_PEER_WRITES: ${GITLAWB_REQUIRE_SIGNED_PEER_WRITES:-false}
|
||||
# Owner-only push. The default matches the node's own, so the container path
|
||||
# behaves like a source build; forwarding it is what makes the documented
|
||||
# rolling-upgrade opt-out reachable for an operator running compose.
|
||||
GITLAWB_ENFORCE_OWNER_PUSH: ${GITLAWB_ENFORCE_OWNER_PUSH:-true}
|
||||
GITLAWB_P2P_BOOTSTRAP: ${GITLAWB_P2P_BOOTSTRAP:-}
|
||||
GITLAWB_PUBLIC_READ: ${GITLAWB_PUBLIC_READ:-true}
|
||||
GITLAWB_MAX_PACK_BYTES: ${GITLAWB_MAX_PACK_BYTES:-2147483648}
|
||||
|
||||
@@ -38,8 +38,8 @@ Owner focus: node reliability.
|
||||
|
||||
Owner focus: protocol/auth.
|
||||
|
||||
- Close default-open repo write authorization and wire trusted UCAN delegation into repository permissions.
|
||||
- Close the remaining visibility gaps: restrict or document task, pin, and anchor metadata routes, and publish an irreversible-publication policy.
|
||||
- Implement repo write authorization: repo owner checks, protected branches, UCAN capability checks, and clear delegation semantics.
|
||||
- Implement private-read enforcement or remove private-repo affordances until it exists.
|
||||
- Add UCAN revocation or blocklisting, with an emergency compromised-key runbook.
|
||||
- Add mutation-aware GraphQL auth before GraphQL becomes a public write API surface.
|
||||
- Harden peer registration and outbound peer calls against SSRF and peer-list poisoning.
|
||||
|
||||
@@ -3,11 +3,6 @@
|
||||
Date: 2026-05-28
|
||||
Repo state inspected: `main` tracking `origin/main`, starting at `b12c6bc feat: per-DID rate limiting on creation endpoints (10/hour) (#13)`.
|
||||
|
||||
> **Historical snapshot.** This audit describes the repository at the commit above. Its
|
||||
> statements about incomplete UCAN chain validation and absent per-repository read
|
||||
> enforcement have been superseded; see [`SECURITY.md`](../SECURITY.md) for the current
|
||||
> security posture.
|
||||
|
||||
## Commands run
|
||||
|
||||
```sh
|
||||
@@ -93,7 +88,7 @@ Fixed or staged in this pass:
|
||||
Live-network blockers to prioritize:
|
||||
|
||||
- GraphQL POST is still open for compatibility; GraphQL mutations should get mutation-aware auth before it becomes a public write API surface.
|
||||
- Push authorization is still not capability-complete. A valid DID signature is authentication, not authorization. Owner checks are now enforced on every branch, protected or not (`GITLAWB_ENFORCE_OWNER_PUSH`, on by default); what remains is that a UCAN `git/push` capability is not yet honored, so a delegated or CI key cannot push.
|
||||
- Push authorization is still not capability-complete. A valid DID signature is authentication, not authorization; unprotected repo branches do not yet enforce owner/UCAN capability checks.
|
||||
- UCAN chain validation is incomplete and UCAN revocation/blocklisting is not implemented as an operator feature.
|
||||
- Private repository reads are not enforced. `is_public` and `GITLAWB_PUBLIC_READ` exist, but per-repository private-read behavior is not wired.
|
||||
- Peer URLs are self-asserted by DIDs. Signatures prove control of the DID key when present, not ownership/safety of the announced URL.
|
||||
|
||||
+20
-35
@@ -141,43 +141,31 @@ During the cooldown your node still earns rewards if it keeps heartbeating.
|
||||
|
||||
---
|
||||
|
||||
## Owner-only push
|
||||
## Hardening: owner-only push
|
||||
|
||||
The node requires the authenticated pusher to be the repo owner on **every**
|
||||
branch. A push whose authenticated DID is not the repo owner is rejected with
|
||||
HTTP 403 before any ref update is applied. The owner is matched in both the full
|
||||
`did:key:z6Mk…` form and its bare `z6Mk…` suffix.
|
||||
By default the node authenticates every `git-receive-pack` push (a valid RFC 9421
|
||||
`did:key` signature) but does **not** check that the pusher owns the repo, except
|
||||
on branches that are explicitly protected. Because `did:key` is self-certifying,
|
||||
any party can generate a key, derive its DID, sign, and push to an unprotected
|
||||
branch — authentication is not authorization.
|
||||
|
||||
This is on by default, and the default is the point. The node authenticates every
|
||||
`git-receive-pack` push with a valid RFC 9421 `did:key` signature, but `did:key`
|
||||
is self-certifying: any party can generate a key, derive its DID and sign.
|
||||
Authentication is not authorization, so without this gate every signed caller can
|
||||
push to every repository — private ones included — on any branch that is not
|
||||
explicitly protected.
|
||||
|
||||
### Turning it off
|
||||
To require the authenticated pusher to be the repo owner on **every** branch, set:
|
||||
|
||||
```bash
|
||||
GITLAWB_ENFORCE_OWNER_PUSH=false
|
||||
GITLAWB_ENFORCE_OWNER_PUSH=true
|
||||
```
|
||||
|
||||
Both the environment variable and `--enforce-owner-push false` disable it; the
|
||||
bare `--enforce-owner-push` flag still means `true`.
|
||||
|
||||
Do this only for a rolling upgrade whose pushers are not yet the repo owner, and
|
||||
treat it as temporary: while it is off, your node accepts a push to any repository
|
||||
from anyone who can generate a keypair.
|
||||
|
||||
### Caution: delegated and CI keys are non-owners
|
||||
|
||||
Push authorization is owner-only today. A UCAN `git/push` capability is verified
|
||||
but **not yet honored for authorization**, so a delegated key cannot push while
|
||||
this gate is on, even when it holds a valid capability for the repo.
|
||||
|
||||
If your automation pushes under its own DID rather than the owner's, it will start
|
||||
getting 403s. Either have it push as the owner, or set
|
||||
`GITLAWB_ENFORCE_OWNER_PUSH=false` until scoped collaborator / UCAN-delegated push
|
||||
rights land — that work is what removes this trade-off.
|
||||
- **Default `false`** — preserves current behavior so live nodes are unaffected by
|
||||
an upgrade. Turn it on once you're ready for owner-only writes.
|
||||
- **When `true`** — a push whose authenticated DID is not the repo owner is
|
||||
rejected (HTTP 403) before any ref update is applied. The owner is matched in
|
||||
both the full `did:key:z6Mk…` form and its bare `z6Mk…` suffix.
|
||||
- **Caution: this blocks every non-owner pusher, including your own delegated and
|
||||
CI agents.** Push authorization is owner-only today — a UCAN `git/push`
|
||||
capability is verified but not yet honored for authorization, so delegated keys
|
||||
cannot push while this is on. Don't enable it until every identity that pushes
|
||||
to your repos is the owner, or you'll lock out your own automation. Scoped
|
||||
collaborator / UCAN-delegated push rights are a planned follow-up.
|
||||
|
||||
---
|
||||
|
||||
@@ -189,8 +177,7 @@ rights land — that work is what removes this trade-off.
|
||||
| Missed heartbeats | After 3 days without one, you're excluded from rewards until you beat again |
|
||||
| Operator key | Dedicated wallet, small ETH balance, not your main treasury |
|
||||
| Monitoring | Watch `lastHeartbeat` on-chain; alert if > 22h since last beat |
|
||||
| Public URL | Must resolve and serve `/health` for liveness and DB-aware `/ready` for peer readiness |
|
||||
| Rolling upgrade (advisory-lock algorithm) | The SHA-256 advisory-lock key swap (replacing `DefaultHasher`) re-keys every repo in the first release that carries it. During a shared-Postgres rolling upgrade, old nodes compute a different `i64` key than new nodes for the same repo, so PostgreSQL treats them as independent locks and cross-machine write-exclusion is lost. **Drain in-flight writes** or cut over through a **single node** before bringing new-binary nodes online. |
|
||||
| Public URL | Must resolve and serve `/health` — peers will ping it |
|
||||
|
||||
---
|
||||
|
||||
@@ -200,8 +187,6 @@ rights land — that work is what removes this trade-off.
|
||||
|
||||
**Node refuses to start with "strict-mode operator check failed"** — either `gl node register` first, or unset `GITLAWB_OPERATOR_STRICT_MODE`.
|
||||
|
||||
**Node refuses to start with "GITLAWB_DB_MAX_CONNECTIONS (20) must be at least max_concurrent_git_pushes (32) + 8 headroom"**: raise `GITLAWB_DB_MAX_CONNECTIONS` to at least the push cap plus 8 (40 with the default cap of 32; 48 is the shipped default and the recommended value), or lower `GITLAWB_MAX_CONCURRENT_GIT_PUSHES`. This bites a node upgraded in place that still sets the old pool size of 20. The check is deliberate: each concurrent push pins one pooled connection for its whole receive-pack, so a pool that does not clear the push cap lets a burst of slow pushes starve every other database path.
|
||||
|
||||
**Rewards are 0 after a week** — run `gl node onchain-status`. If `currentlyActive: false`, check your heartbeat loop (node logs for `operator heartbeat sent`).
|
||||
|
||||
**Want to rotate operator wallet** — requires unstake → re-register with new wallet. No in-place rotation in v1.
|
||||
|
||||
+11
-60
@@ -91,39 +91,13 @@ User-data only runs at first boot, so upgrades go through SSM:
|
||||
$(terraform output -raw upgrade_command)
|
||||
```
|
||||
|
||||
This reinstalls the rendered `/opt/gitlawb/compose.yaml`, then runs
|
||||
`docker compose pull && docker compose up -d` on the instance.
|
||||
|
||||
**Run `terraform apply` before the upgrade command.** The command is an SSM
|
||||
document managed by Terraform, and it embeds the compose file rendered from your
|
||||
current variables. An instance that has not had a fresh `apply` still holds the
|
||||
previous document and will reinstall the previous compose file.
|
||||
This runs `docker compose pull && docker compose up -d` on the instance.
|
||||
|
||||
- With `image_tag = "latest"` (default) that picks up the newest release.
|
||||
- With a **pinned tag**, set `image_tag` in `terraform.tfvars` and `apply` — the
|
||||
rendered compose carries it, so the upgrade installs the right version.
|
||||
- **`compose.yaml` is Terraform-owned and is overwritten on every upgrade.**
|
||||
Per-instance settings belong in `/opt/gitlawb/.env`, which is never touched.
|
||||
- **The upgrade reconciles the service set, not just the image.** The rendering is
|
||||
conditional — `postgres` exists only when `db_host` is empty, `caddy` only when
|
||||
`domain_name` is set — and the command runs `--remove-orphans`. So setting
|
||||
`use_rds`, or clearing `domain_name`, and then upgrading will **stop and remove**
|
||||
the local postgres or the TLS terminator. That is the intended outcome of those
|
||||
variables, but it happens on the upgrade rather than on `apply`. Data survives
|
||||
either way: both bind-mount under `/mnt/data`.
|
||||
|
||||
### Why the upgrade rewrites the compose file
|
||||
|
||||
`aws_instance` deliberately ignores `user_data` drift, so an instance keeps the
|
||||
compose file it was created with. Compose passes only the variables named in a
|
||||
service's `environment:` block into the container, so **a node setting added to
|
||||
the template never reaches an existing instance** — writing it to
|
||||
`/opt/gitlawb/.env` and restarting leaves the node on its built-in default, with
|
||||
no error to indicate it. `pull && up -d` alone cannot fix that, because the file
|
||||
on disk is the authoritative one.
|
||||
|
||||
Reinstalling the rendering first makes the upgrade a real migration. It is
|
||||
idempotent: on an already-current instance it writes identical bytes.
|
||||
- With a **pinned tag**, first edit the tag in `/opt/gitlawb/compose.yaml` on
|
||||
the instance (via SSM session), then run the upgrade command — and keep
|
||||
`image_tag` in terraform.tfvars in sync so a future instance replacement
|
||||
boots the same version.
|
||||
|
||||
Replace the instance itself (OS/AMI/instance-type changes) with
|
||||
`terraform apply -replace=aws_instance.node` — the data volume reattaches and
|
||||
@@ -131,24 +105,12 @@ Replace the instance itself (OS/AMI/instance-type changes) with
|
||||
|
||||
## Changing configuration
|
||||
|
||||
`terraform apply` alone never changes a running instance: user-data runs once and
|
||||
the instance ignores `user_data` drift. How a change rolls out depends on which
|
||||
of the two files carries it.
|
||||
|
||||
**Rendered into `compose.yaml`** — `image_tag`, `gitlawb_port`, `metrics_port`,
|
||||
`domain_name`, `db_host`, the `icaptcha_*` values. `apply`, then run
|
||||
`upgrade_command`: it installs the new rendering and restarts.
|
||||
|
||||
```sh
|
||||
terraform apply
|
||||
$(terraform output -raw upgrade_command)
|
||||
```
|
||||
|
||||
**Written into `/opt/gitlawb/.env` at first boot** — `public_url`,
|
||||
`bootstrap_peers`, `auto_sync`, `max_pack_bytes`, and the integration secrets.
|
||||
Editing these in `terraform.tfvars` does **not** reach a running instance, because
|
||||
nothing rewrites `.env` after the first boot. Either edit `/opt/gitlawb/.env` on
|
||||
the instance and `docker compose up -d`, or replace it:
|
||||
User-data only runs at first boot, and the instance ignores `user_data` drift
|
||||
(`ignore_changes`), so editing terraform.tfvars values that feed the bootstrap
|
||||
(`bootstrap_peers`, `public_url`, integrations, `image_tag`) does **not**
|
||||
affect a running instance on `terraform apply`. To roll out such changes,
|
||||
either edit `/opt/gitlawb/.env` on the instance (SSM session, then
|
||||
`docker compose up -d`), or replace the instance:
|
||||
|
||||
```sh
|
||||
terraform apply -replace=aws_instance.node
|
||||
@@ -156,17 +118,6 @@ terraform apply -replace=aws_instance.node
|
||||
|
||||
The data volume reattaches; repos, postgres data, and the identity key survive.
|
||||
|
||||
**A node setting the installed `compose.yaml` does not already name** —
|
||||
`GITLAWB_ENFORCE_OWNER_PUSH` on an instance created before it was added, for
|
||||
example. Editing `.env` is **not enough**: compose only passes through the
|
||||
variables its `environment:` block lists, so the value is read from `.env` and
|
||||
then dropped. Run `apply` plus `upgrade_command` first, which installs a compose
|
||||
file that names the key; after that, `.env` governs it like any other.
|
||||
|
||||
That last case is the one worth remembering: `.env` reaches the container only for
|
||||
keys the *installed* compose interpolates, and the upgrade is what makes a newly
|
||||
added key one of them.
|
||||
|
||||
## Remote state (optional)
|
||||
|
||||
Local state is the default. To move state to S3: create a versioned bucket,
|
||||
|
||||
@@ -72,9 +72,6 @@ services:
|
||||
GITLAWB_BOOTSTRAP_PEERS: $${GITLAWB_BOOTSTRAP_PEERS}
|
||||
GITLAWB_AUTO_SYNC: $${GITLAWB_AUTO_SYNC}
|
||||
GITLAWB_MAX_PACK_BYTES: $${GITLAWB_MAX_PACK_BYTES}
|
||||
# Owner-only push. Matches the node's own default; forwarding it is what makes
|
||||
# the documented rolling-upgrade opt-out reachable on the container path.
|
||||
GITLAWB_ENFORCE_OWNER_PUSH: $${GITLAWB_ENFORCE_OWNER_PUSH:-true}
|
||||
# On-chain PoS (optional — empty unless set in terraform.tfvars)
|
||||
GITLAWB_CHAIN_RPC_URL: $${GITLAWB_CHAIN_RPC_URL}
|
||||
GITLAWB_CONTRACT_NODE_STAKING: $${GITLAWB_CONTRACT_NODE_STAKING}
|
||||
|
||||
+7
-62
@@ -350,16 +350,10 @@ resource "aws_instance" "node" {
|
||||
# ami: new AL2023 releases shouldn't churn the instance; replace
|
||||
# deliberately for OS upgrades.
|
||||
# user_data: only runs at first boot, so re-rendering it on a live
|
||||
# instance is a pointless stop/start. How a config change reaches a running
|
||||
# instance depends on which file carries it:
|
||||
# - rendered into compose.yaml (image_tag, ports, domain_name, db_host,
|
||||
# icaptcha_*): `terraform apply` then `upgrade_command`, which
|
||||
# reinstalls the rendering and restarts.
|
||||
# - written into /opt/gitlawb/.env at first boot (public_url,
|
||||
# bootstrap_peers, integrations): nothing rewrites .env afterwards, so
|
||||
# these need an edit on the instance or
|
||||
# `terraform apply -replace=aws_instance.node`.
|
||||
# See README "Changing configuration".
|
||||
# instance is a pointless stop/start. Config changes that feed user-data
|
||||
# (bootstrap peers, integrations, image tag) require a deliberate
|
||||
# `terraform apply -replace=aws_instance.node` — see README "Changing
|
||||
# configuration".
|
||||
ignore_changes = [ami, user_data]
|
||||
}
|
||||
}
|
||||
@@ -443,62 +437,13 @@ resource "aws_ssm_document" "upgrade" {
|
||||
|
||||
content = jsonencode({
|
||||
schemaVersion = "2.2"
|
||||
description = "Reinstall the rendered compose file, pull the latest image, and restart"
|
||||
description = "Pull the latest gitlawb node image and restart the compose stack"
|
||||
mainSteps = [{
|
||||
action = "aws:runShellScript"
|
||||
name = "upgrade"
|
||||
inputs = {
|
||||
# Reinstall the CURRENT rendering before restarting.
|
||||
#
|
||||
# `aws_instance` ignores user_data drift, so an instance created before a
|
||||
# template change keeps the compose file it was born with. Compose passes
|
||||
# only the variables named in its `environment:` block into the container,
|
||||
# so a node setting added to the template never reaches an existing
|
||||
# instance — the operator writes it to /opt/gitlawb/.env, restarts, and the
|
||||
# node silently keeps the built-in default. `docker compose pull && up -d`
|
||||
# cannot fix that: the authoritative file is the one on disk.
|
||||
#
|
||||
# Idempotent: writing the same bytes and restarting is a no-op. This does
|
||||
# overwrite hand-edits to compose.yaml, which is intended — the file is
|
||||
# Terraform-owned; per-instance settings belong in /opt/gitlawb/.env.
|
||||
#
|
||||
# One shell step, under flock, writing through mktemp. Two overlapping
|
||||
# executions — a double run, a retry while the first is still pulling, two
|
||||
# operators — otherwise share one fixed temp path: the second truncates the
|
||||
# file the first is about to install, and once the first renames, the
|
||||
# second's open descriptor keeps writing into the live compose.yaml inode.
|
||||
# Both outcomes stay valid YAML, so the `up -d --remove-orphans` on the next
|
||||
# line accepts a blended or truncated service set and deletes whatever fell
|
||||
# off — on a live node, the local postgres or the TLS terminator. The lock
|
||||
# also covers pull and up, so a second run cannot restart against a file the
|
||||
# first is mid-install.
|
||||
runCommand = [<<-UPGRADE
|
||||
set -euo pipefail
|
||||
install -d -m 0755 /opt/gitlawb
|
||||
|
||||
exec 9>/opt/gitlawb/.upgrade.lock
|
||||
if ! flock -n 9; then
|
||||
echo "another upgrade is already running on this instance" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
tmp="$(mktemp /opt/gitlawb/compose.yaml.XXXXXX)"
|
||||
trap 'rm -f "$tmp"' EXIT
|
||||
# base64 rather than a nested heredoc: the rendered compose contains
|
||||
# `$${VAR}` passthroughs that must reach the file unexpanded, and a
|
||||
# heredoc inside an indented Terraform heredoc depends on the dedent
|
||||
# landing the delimiter at column 0. Decoding a single line has neither
|
||||
# failure mode, and no delimiter can collide with the content.
|
||||
echo '${base64encode(local.compose_yaml)}' | base64 -d > "$tmp"
|
||||
chmod 0644 "$tmp"
|
||||
mv "$tmp" /opt/gitlawb/compose.yaml
|
||||
trap - EXIT
|
||||
|
||||
cd /opt/gitlawb
|
||||
docker compose pull
|
||||
docker compose up -d --remove-orphans
|
||||
docker image prune -f
|
||||
UPGRADE
|
||||
runCommand = [
|
||||
"cd /opt/gitlawb && docker compose pull && docker compose up -d --remove-orphans && docker image prune -f"
|
||||
]
|
||||
}
|
||||
}]
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
# fly.toml app configuration file generated for gitlawb-node-2 on 2026-07-22T09:47:18+08:00
|
||||
#
|
||||
# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
|
||||
#
|
||||
|
||||
app = 'gitlawb-node-2'
|
||||
primary_region = 'sjc'
|
||||
|
||||
[build]
|
||||
dockerfile = '../../Dockerfile'
|
||||
|
||||
[env]
|
||||
GITLAWB_AUTO_SYNC = 'true'
|
||||
GITLAWB_BOOTSTRAP_PEERS = 'https://node.gitlawb.com,https://node3.gitlawb.com'
|
||||
GITLAWB_HOST = '0.0.0.0'
|
||||
GITLAWB_KEY = '/data/keys/identity.pem'
|
||||
GITLAWB_MAX_PACK_BYTES = '524288000'
|
||||
GITLAWB_P2P_PORT = '7546'
|
||||
GITLAWB_PORT = '7545'
|
||||
GITLAWB_PUBLIC_URL = 'https://node2.gitlawb.com'
|
||||
GITLAWB_REPOS_DIR = '/data/repos'
|
||||
ICAPTCHA_MODE = 'enforce'
|
||||
ICAPTCHA_PUBKEY = 'xjyPNqIbvc9U-kwXW6u9mDqRJ7E2UUMOaJdUWhpEXq8'
|
||||
ICAPTCHA_REQUIRED_LEVEL = '3'
|
||||
|
||||
[[mounts]]
|
||||
source = 'gitlawb_data'
|
||||
destination = '/data'
|
||||
|
||||
[http_service]
|
||||
internal_port = 7545
|
||||
force_https = true
|
||||
auto_stop_machines = 'off'
|
||||
auto_start_machines = true
|
||||
min_machines_running = 1
|
||||
|
||||
[http_service.concurrency]
|
||||
type = 'connections'
|
||||
hard_limit = 500
|
||||
soft_limit = 400
|
||||
|
||||
[http_service.http_options]
|
||||
idle_timeout = 120
|
||||
|
||||
[[http_service.checks]]
|
||||
interval = '15s'
|
||||
timeout = '5s'
|
||||
grace_period = '30s'
|
||||
method = 'GET'
|
||||
path = '/ready'
|
||||
|
||||
[[services]]
|
||||
protocol = 'udp'
|
||||
internal_port = 7546
|
||||
|
||||
[[services.ports]]
|
||||
port = 7546
|
||||
|
||||
[[vm]]
|
||||
size = 'shared-cpu-1x'
|
||||
memory = '1024'
|
||||
|
||||
[[metrics]]
|
||||
port = 9091
|
||||
path = '/metrics'
|
||||
@@ -1,65 +0,0 @@
|
||||
# fly.toml app configuration file generated for gitlawb-node-3 on 2026-07-22T09:47:19+08:00
|
||||
#
|
||||
# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
|
||||
#
|
||||
|
||||
app = 'gitlawb-node-3'
|
||||
primary_region = 'nrt'
|
||||
|
||||
[build]
|
||||
dockerfile = '../../Dockerfile'
|
||||
|
||||
[env]
|
||||
GITLAWB_AUTO_SYNC = 'true'
|
||||
GITLAWB_BOOTSTRAP_PEERS = 'https://node.gitlawb.com,https://node2.gitlawb.com'
|
||||
GITLAWB_HOST = '0.0.0.0'
|
||||
GITLAWB_KEY = '/data/keys/identity.pem'
|
||||
GITLAWB_MAX_PACK_BYTES = '524288000'
|
||||
GITLAWB_P2P_PORT = '7546'
|
||||
GITLAWB_PORT = '7545'
|
||||
GITLAWB_PUBLIC_URL = 'https://node3.gitlawb.com'
|
||||
GITLAWB_REPOS_DIR = '/data/repos'
|
||||
ICAPTCHA_MODE = 'enforce'
|
||||
ICAPTCHA_PUBKEY = 'xjyPNqIbvc9U-kwXW6u9mDqRJ7E2UUMOaJdUWhpEXq8'
|
||||
ICAPTCHA_REQUIRED_LEVEL = '3'
|
||||
|
||||
[[mounts]]
|
||||
source = 'gitlawb_data'
|
||||
destination = '/data'
|
||||
|
||||
[http_service]
|
||||
internal_port = 7545
|
||||
force_https = true
|
||||
auto_stop_machines = 'off'
|
||||
auto_start_machines = true
|
||||
min_machines_running = 1
|
||||
|
||||
[http_service.concurrency]
|
||||
type = 'connections'
|
||||
hard_limit = 500
|
||||
soft_limit = 400
|
||||
|
||||
[http_service.http_options]
|
||||
idle_timeout = 120
|
||||
|
||||
[[http_service.checks]]
|
||||
interval = '15s'
|
||||
timeout = '5s'
|
||||
grace_period = '30s'
|
||||
method = 'GET'
|
||||
path = '/ready'
|
||||
|
||||
[[services]]
|
||||
protocol = 'udp'
|
||||
internal_port = 7546
|
||||
|
||||
[[services.ports]]
|
||||
port = 7546
|
||||
|
||||
[[vm]]
|
||||
size = 'shared-cpu-1x'
|
||||
memory = '1024'
|
||||
|
||||
[[metrics]]
|
||||
port = 9091
|
||||
path = '/metrics'
|
||||
-14
@@ -193,19 +193,5 @@ else
|
||||
echo " gl quickstart"
|
||||
fi
|
||||
|
||||
# oh-my-zsh's default git plugin aliases gl='git pull', which silently shadows
|
||||
# the gl binary in every interactive zsh (aliases beat PATH). Detect the common
|
||||
# setup and say so now, at install time, instead of letting the first `gl`
|
||||
# print git's baffling "fatal: not a git repository".
|
||||
if [ -f "$HOME/.zshrc" ] && [ -d "$HOME/.oh-my-zsh/plugins/git" ] \
|
||||
&& grep -Eq '^[[:space:]]*plugins=\(([^)]*[[:space:]])?git([[:space:]][^)]*)?\)' "$HOME/.zshrc" \
|
||||
&& ! grep -Eq '^([^#]*[[:space:];&|])?unalias[[:space:]]+([^;&|#]*[[:space:]])?gl([[:space:]]|$)' "$HOME/.zshrc"; then
|
||||
echo ""
|
||||
echo "NOTE: oh-my-zsh's git plugin aliases gl='git pull', which will shadow"
|
||||
echo "the gl command in interactive shells. To use gl by name, run:"
|
||||
echo ""
|
||||
echo " echo 'unalias gl 2>/dev/null' >> ~/.zshrc && source ~/.zshrc"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Docs: https://docs.gitlawb.com"
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user