mirror of
https://github.com/Twigpine/node.git
synced 2026-11-08 17:55:53 -10:00
Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9da517fde | ||
|
|
9ca94c4d47 | ||
|
|
c0ad500b55 | ||
|
|
e9d6aadd58 | ||
|
|
b484a24955 | ||
|
|
32006b26a2 | ||
|
|
b75aa2f1da | ||
|
|
c681af70db | ||
|
|
3fa38dce4e | ||
|
|
c71bba5cd1 | ||
|
|
e3df51d76c | ||
|
|
0765c42fef | ||
|
|
94c61f7942 | ||
|
|
b0a2ed8308 | ||
|
|
cb42a4830d | ||
|
|
2d88937fba | ||
|
|
e14c2d3f3f | ||
|
|
4465beb0c2 | ||
|
|
82efd60229 | ||
|
|
e8f193a5df | ||
|
|
07d76ba556 | ||
|
|
05e434d906 | ||
|
|
7593540f62 | ||
|
|
ccc2cf46f2 | ||
|
|
1fddc81b7c | ||
|
|
62d73c4165 | ||
|
|
2f622ae5fa | ||
|
|
f9506b466e | ||
|
|
d5ec4695f4 | ||
|
|
98d728c325 | ||
|
|
b6877a6598 | ||
|
|
b07d41ea97 | ||
|
|
c7427e943d | ||
|
|
69a62e51c2 | ||
|
|
ee8d7c03b2 |
No files matched your search
@@ -0,0 +1,121 @@
|
||||
# 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,6 +2,10 @@ 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:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
@@ -212,3 +216,63 @@ 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 -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
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Label and guide
|
||||
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
|
||||
+223
-52
@@ -4,6 +4,20 @@ 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 }}
|
||||
@@ -14,7 +28,10 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
if: ${{ github.repository == 'Gitlawb/node' }}
|
||||
# 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' }}
|
||||
name: Release Please
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -31,24 +48,61 @@ jobs:
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# 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
|
||||
name: Build & Push Docker Image (${{ matrix.arch }})
|
||||
needs: release-please
|
||||
if: ${{ needs.release-please.outputs.release_created == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
# 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 }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- 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
|
||||
TAG="${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
case "$TAG" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "::error::'$TAG' does not look like a release tag (vX.Y.Z)"; exit 1 ;;
|
||||
esac
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
# 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: ${{ needs.release-please.outputs.tag_name }}
|
||||
ref: ${{ steps.rel.outputs.tag }}
|
||||
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
|
||||
|
||||
@@ -59,45 +113,130 @@ 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
|
||||
cache-from: type=gha,scope=docker-${{ matrix.arch }}
|
||||
|
||||
# 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
|
||||
run: docker run --rm gitlawb-node:smoke --version
|
||||
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
|
||||
}
|
||||
|
||||
- name: Build and push (multi-arch)
|
||||
# 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
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v6.16.0
|
||||
with:
|
||||
context: .
|
||||
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
|
||||
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:
|
||||
packages: write
|
||||
steps:
|
||||
- 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
|
||||
TAG="${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
case "$TAG" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "::error::'$TAG' does not look like a release tag (vX.Y.Z)"; exit 1 ;;
|
||||
esac
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- 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"
|
||||
|
||||
- name: Release summary
|
||||
env:
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
TAG: ${{ steps.rel.outputs.tag }}
|
||||
run: |
|
||||
{
|
||||
echo "## Released ${{ needs.release-please.outputs.tag_name }}"
|
||||
echo "## Released $TAG"
|
||||
echo
|
||||
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 }}"
|
||||
echo "- Image: \`ghcr.io/${GITHUB_REPOSITORY,,}:$VERSION\` (linux/amd64 + linux/arm64)"
|
||||
echo "- GitHub: https://github.com/$GITHUB_REPOSITORY/releases/tag/$TAG"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
release-binaries:
|
||||
@@ -248,37 +387,62 @@ jobs:
|
||||
npm-publish:
|
||||
name: Publish to npm
|
||||
needs: [release-please, release-binaries]
|
||||
if: ${{ needs.release-please.outputs.release_created == 'true' }}
|
||||
# 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 != '')
|
||||
) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # npm provenance
|
||||
id-token: write # npm trusted publishing (OIDC) + provenance
|
||||
steps:
|
||||
- name: Guard on secret
|
||||
id: guard
|
||||
- name: Resolve release tag
|
||||
id: rel
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
DISPATCH_TAG: ${{ inputs.npm_backfill_tag }}
|
||||
RELEASE_TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
run: |
|
||||
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
|
||||
set -euo pipefail
|
||||
TAG="${DISPATCH_TAG:-$RELEASE_TAG}"
|
||||
case "$TAG" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "::error::'$TAG' does not look like a release tag (vX.Y.Z)"; exit 1 ;;
|
||||
esac
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Checkout release tag
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ needs.release-please.outputs.tag_name }}
|
||||
ref: ${{ steps.rel.outputs.tag }}
|
||||
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: ${{ needs.release-please.outputs.version }}
|
||||
TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
TAG: ${{ steps.rel.outputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# npm platform package -> Rust target triple (unix only; Windows is not
|
||||
@@ -305,9 +469,8 @@ jobs:
|
||||
done
|
||||
|
||||
- name: Set versions
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
env:
|
||||
VERSION: ${{ needs.release-please.outputs.version }}
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node -e '
|
||||
@@ -327,13 +490,12 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Publish
|
||||
if: ${{ steps.guard.outputs.enabled == 'true' }}
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
VERSION: ${{ needs.release-please.outputs.version }}
|
||||
VERSION: ${{ steps.rel.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
|
||||
# No token: npm exchanges this job's GitHub OIDC identity with the
|
||||
# registry (trusted publishing); provenance is attested automatically.
|
||||
# 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.
|
||||
@@ -429,6 +591,15 @@ 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.5.1"
|
||||
".": "0.7.0"
|
||||
}
|
||||
@@ -1,5 +1,39 @@
|
||||
# Changelog
|
||||
|
||||
## [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)
|
||||
|
||||
|
||||
|
||||
Generated
+7
-5
@@ -3300,7 +3300,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "git-remote-gitlawb"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
@@ -3312,7 +3312,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-attest"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"ed25519-dalek",
|
||||
@@ -3329,7 +3329,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-core"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
@@ -3356,7 +3356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gitlawb-node"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
@@ -3412,7 +3412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gl"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
@@ -3821,9 +3821,11 @@ version = "0.4.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gitlawb-core",
|
||||
"mockito",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# 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.5.1" # x-release-please-version
|
||||
version = "0.7.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -570,6 +570,13 @@ fn safe_error_body_excerpt(body: &str) -> String {
|
||||
continue;
|
||||
}
|
||||
|
||||
if gitlawb_core::sanitize::is_bidi_format(ch) {
|
||||
// Drop Cf bidi/format controls (INV-6, #183) without marking
|
||||
// pending_space: unlike a newline/tab they are not whitespace, so
|
||||
// "a\u{202e}c" collapses to "ac" with no phantom gap.
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch.is_whitespace() {
|
||||
pending_space = true;
|
||||
continue;
|
||||
@@ -1159,6 +1166,55 @@ mod tests {
|
||||
assert!(!message.contains('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_error_message_strips_bidi_format_controls() {
|
||||
// Each Cf bidi class must be stripped (INV-6, #183), not just U+202E:
|
||||
// override (RLO), embedding + pop (LRE/PDF), isolate (LRI/PDI), and marks
|
||||
// (LRM/ALM). Asserted per code point so a partial predicate fails loudly.
|
||||
// The visible words must survive and JOIN with no phantom space at the
|
||||
// strip points: a bidi char is dropped like a control byte, but unlike a
|
||||
// newline/tab it is not whitespace, so it must not set pending_space. The
|
||||
// leading bidi char (index 0) also exercises the empty-excerpt path.
|
||||
let body = "\u{202e}err\u{202a}\u{202c}\u{2066}\u{2069}\u{200e}\u{061c}ok";
|
||||
let message = http_error_message(
|
||||
"GET",
|
||||
"/info/refs",
|
||||
reqwest::StatusCode::BAD_GATEWAY,
|
||||
body,
|
||||
None,
|
||||
);
|
||||
for c in [
|
||||
'\u{202e}', '\u{202a}', '\u{202c}', '\u{2066}', '\u{2069}', '\u{200e}', '\u{061c}',
|
||||
] {
|
||||
assert!(
|
||||
!message.contains(c),
|
||||
"bidi U+{:04X} leaked: {message:?}",
|
||||
c as u32
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
message.contains("errok"),
|
||||
"words should join with no phantom space: {message:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_error_message_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.
|
||||
let message = http_error_message(
|
||||
"GET",
|
||||
"/info/refs",
|
||||
reqwest::StatusCode::BAD_GATEWAY,
|
||||
"ok \u{0627}\u{200D}b",
|
||||
None,
|
||||
);
|
||||
assert!(
|
||||
message.ends_with("ok \u{0627}\u{200D}b"),
|
||||
"legitimate text was altered: {message:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_error_message_truncates_long_response_body() {
|
||||
let body = "x".repeat(MAX_ERROR_BODY_CHARS + 100);
|
||||
@@ -1194,6 +1250,33 @@ mod tests {
|
||||
assert_eq!(requests.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_error_strips_bidi_from_response_body() {
|
||||
// Transport-path proof: a bidi override in the node's real HTTP error body
|
||||
// must not reach the surfaced error text. Drives the full handle_connect
|
||||
// error path, not just the safe_error_body_excerpt unit boundary (INV-6).
|
||||
let (base_url, server) = serve_http(vec![TestResponse {
|
||||
request_line: "GET /z6Mk/myrepo/info/refs?service=git-upload-pack HTTP/1.1",
|
||||
status: "404 Not Found",
|
||||
body: "not\u{202e}found",
|
||||
}]);
|
||||
|
||||
let repo_base = format!("{base_url}/z6Mk/myrepo");
|
||||
let mut stdin = std::io::Cursor::new(Vec::<u8>::new());
|
||||
let err = handle_connect(&repo_base, "git-upload-pack", None, &mut stdin).unwrap_err();
|
||||
let message = err.to_string();
|
||||
|
||||
assert!(
|
||||
!message.contains('\u{202e}'),
|
||||
"bidi override reached the terminal: {message:?}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("notfound"),
|
||||
"body should survive with the bidi char stripped: {message:?}"
|
||||
);
|
||||
let _ = server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_post_error_includes_response_body() {
|
||||
let (base_url, server) = serve_http(vec![
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-attest"
|
||||
description = "External Attestation v1: pluggable provenance attachments for gitlawb ref-update certs"
|
||||
version = "0.5.1" # x-release-please-version
|
||||
version = "0.7.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gitlawb-core"
|
||||
description = "Core cryptographic primitives for the gitlawb network: DIDs, CIDs, UCAN, HTTP Signatures, ref-update certificates"
|
||||
version = "0.5.1" # x-release-please-version
|
||||
version = "0.7.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod encrypt;
|
||||
pub mod error;
|
||||
pub mod http_sig;
|
||||
pub mod identity;
|
||||
pub mod sanitize;
|
||||
pub mod ucan;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//! 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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,11 +187,17 @@ 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| cap.with == resource && cap.can == action)
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode to a compact JSON string (the wire format).
|
||||
@@ -312,6 +318,63 @@ 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.5.1" # x-release-please-version
|
||||
version = "0.7.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -138,9 +138,33 @@ 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()
|
||||
.map(|u| {
|
||||
.enumerate()
|
||||
.map(|(i, u)| {
|
||||
let owner_did = owner_dids[i].clone();
|
||||
serde_json::json!({
|
||||
"id": u.id,
|
||||
"node_did": u.node_did,
|
||||
@@ -153,6 +177,7 @@ 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();
|
||||
@@ -225,6 +250,7 @@ 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",
|
||||
})
|
||||
})
|
||||
@@ -240,28 +266,46 @@ 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_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",
|
||||
})
|
||||
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",
|
||||
})
|
||||
.collect();
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Merge both lists
|
||||
let mut all_events: Vec<serde_json::Value> = cert_events;
|
||||
@@ -326,6 +370,7 @@ mod ref_updates_feed_tests {
|
||||
cert_id: None,
|
||||
received_at: Utc::now().to_rfc3339(),
|
||||
from_peer: "peer1".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1105,7 +1150,14 @@ mod ref_updates_feed_tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(count(&body_json(resp).await), 2);
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Anon reads a quarantined mirror → 404 (withheld without disclosing existence
|
||||
|
||||
@@ -71,6 +71,10 @@ 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,6 +172,7 @@ 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");
|
||||
@@ -187,6 +188,13 @@ 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)
|
||||
@@ -203,6 +211,12 @@ mod authz_guard {
|
||||
// get_by_cid gates each iterated repo row directly via visibility_check
|
||||
// (KTD2a: it must NOT route through authorize_repo_read's fuzzy re-resolve).
|
||||
(ipfs, "get_by_cid", "visibility_check("),
|
||||
// #94 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("),
|
||||
@@ -509,11 +523,7 @@ 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)] = &[
|
||||
("list_webhooks", "#94 (PR #113)"),
|
||||
("list_replicas", "PR #113"),
|
||||
("list_protected_branches", "PR #113"),
|
||||
];
|
||||
let known_ungated: &[(&str, &str)] = &[];
|
||||
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.
|
||||
|
||||
@@ -347,6 +347,10 @@ pub struct NotifyRequest {
|
||||
pub timestamp: Option<String>,
|
||||
#[serde(default)]
|
||||
pub cert_id: Option<String>,
|
||||
/// Full owner DID — added in #144 for DID-aware feed gating.
|
||||
/// Optional for backward compat with older senders.
|
||||
#[serde(default)]
|
||||
pub owner_did: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn notify_sync(
|
||||
@@ -391,6 +395,7 @@ pub async fn notify_sync(
|
||||
node_did: req.node_did.clone(),
|
||||
pusher_did: req.pusher_did.clone().unwrap_or_default(),
|
||||
repo: req.repo.clone(),
|
||||
owner_did: req.owner_did.clone(),
|
||||
ref_name: req.ref_name.clone(),
|
||||
old_sha: req.old_sha.clone().unwrap_or_default(),
|
||||
new_sha: req.new_sha.clone(),
|
||||
|
||||
@@ -79,12 +79,14 @@ 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>> {
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(&owner, &repo)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
|
||||
// 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 branches = state.db.list_protected_branches(&record.id).await?;
|
||||
|
||||
|
||||
@@ -113,16 +113,17 @@ pub async fn unregister_replica(
|
||||
}
|
||||
|
||||
/// GET /api/v1/repos/:owner/:repo/replicas
|
||||
/// Public — returns the list of replicas (DID + URL + registration timestamp).
|
||||
/// 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.
|
||||
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 record = state
|
||||
.db
|
||||
.get_repo(&owner, &repo)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
|
||||
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 replicas = state.db.list_replicas(&record.id).await?;
|
||||
|
||||
|
||||
@@ -772,6 +772,7 @@ async fn notify_peer_of_ref(
|
||||
new_sha: &str,
|
||||
node_did: &str,
|
||||
pusher_did: &str,
|
||||
owner_did: &str,
|
||||
) {
|
||||
let body = serde_json::json!({
|
||||
"repo": repo_slug,
|
||||
@@ -781,6 +782,7 @@ async fn notify_peer_of_ref(
|
||||
"pusher_did": pusher_did,
|
||||
"old_sha": old_sha,
|
||||
"timestamp": chrono::Utc::now().to_rfc3339(),
|
||||
"owner_did": owner_did,
|
||||
});
|
||||
let body_bytes = match serde_json::to_vec(&body) {
|
||||
Ok(bytes) => bytes,
|
||||
@@ -828,6 +830,7 @@ async fn notify_peer_of_refs(
|
||||
ref_updates: &[(String, String, String)],
|
||||
node_did: &str,
|
||||
pusher_did: &str,
|
||||
owner_did: &str,
|
||||
) {
|
||||
for (ref_name, old_sha, new_sha) in ref_updates {
|
||||
notify_peer_of_ref(
|
||||
@@ -841,6 +844,7 @@ async fn notify_peer_of_refs(
|
||||
new_sha,
|
||||
node_did,
|
||||
pusher_did,
|
||||
owner_did,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -1261,6 +1265,7 @@ pub async fn git_receive_pack(
|
||||
node_did: node_did_str.clone(),
|
||||
pusher_did: pusher_did_clone.clone(),
|
||||
repo: repo_slug.clone(),
|
||||
owner_did: Some(record.owner_did.clone()),
|
||||
ref_name: ref_name.clone(),
|
||||
old_sha: old_sha.clone(),
|
||||
new_sha: new_sha.clone(),
|
||||
@@ -1292,6 +1297,7 @@ pub async fn git_receive_pack(
|
||||
pusher_did: pusher_did_clone.clone(),
|
||||
node_did: node_did_str.clone(),
|
||||
timestamp: now_ts.clone(),
|
||||
owner_did: record.owner_did.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1362,6 +1368,7 @@ pub async fn git_receive_pack(
|
||||
&ref_updates_clone,
|
||||
&node_did_str,
|
||||
&pusher_did_clone,
|
||||
&record.owner_did,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -2402,6 +2409,9 @@ mod tests {
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"ref_name":"{ref_a}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"old_sha":"{old_a}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"new_sha":"{new_a}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(
|
||||
r#"{"owner_did":"did:key:zOwner"}"#.to_string(),
|
||||
),
|
||||
]))
|
||||
.with_status(200)
|
||||
.expect(1)
|
||||
@@ -2413,6 +2423,9 @@ mod tests {
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"ref_name":"{ref_b}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"old_sha":"{old_b}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"new_sha":"{new_b}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(
|
||||
r#"{"owner_did":"did:key:zOwner"}"#.to_string(),
|
||||
),
|
||||
]))
|
||||
.with_status(200)
|
||||
.expect(1)
|
||||
@@ -2434,6 +2447,7 @@ mod tests {
|
||||
&ref_updates,
|
||||
"did:key:zNode",
|
||||
"did:key:zPusher",
|
||||
"did:key:zOwner",
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -2456,6 +2470,9 @@ mod tests {
|
||||
.match_body(mockito::Matcher::AllOf(vec![
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"old_sha":"{zero}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(format!(r#"{{"new_sha":"{new_sha}"}}"#)),
|
||||
mockito::Matcher::PartialJsonString(
|
||||
r#"{"owner_did":"did:key:zOwner"}"#.to_string(),
|
||||
),
|
||||
]))
|
||||
.with_status(200)
|
||||
.expect(1)
|
||||
@@ -2478,6 +2495,7 @@ mod tests {
|
||||
&ref_updates,
|
||||
"did:key:zNode",
|
||||
"did:key:zPusher",
|
||||
"did:key:zOwner",
|
||||
)
|
||||
.await;
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Webhook CRUD API.
|
||||
//!
|
||||
//! 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)
|
||||
//! 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)
|
||||
|
||||
use axum::extract::{Extension, Path, State};
|
||||
use axum::http::StatusCode;
|
||||
@@ -73,12 +73,26 @@ 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>> {
|
||||
let record = state
|
||||
.db
|
||||
.get_repo(&owner, &name)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
|
||||
// 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 hooks = state.db.list_webhooks(&record.id).await?;
|
||||
// Redact secrets in list response
|
||||
|
||||
@@ -175,6 +175,9 @@ pub struct ReceivedRefUpdate {
|
||||
pub cert_id: Option<String>,
|
||||
pub received_at: String,
|
||||
pub from_peer: String,
|
||||
/// Full owner DID — populated by new peers; None for events from older
|
||||
/// peers that predate the wire-format change (#144).
|
||||
pub owner_did: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -872,6 +875,14 @@ const MIGRATIONS: &[Migration] = &[
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_ref_certs_repo_ref ON ref_certificates(repo_id, ref_name)",
|
||||
],
|
||||
},
|
||||
Migration {
|
||||
version: 11,
|
||||
name: "ref_update_owner_did",
|
||||
stmts: &[
|
||||
// Index deferred — the feed gate (#144) does not read owner_did yet.
|
||||
"ALTER TABLE received_ref_updates ADD COLUMN IF NOT EXISTS owner_did TEXT",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// ── Repos ─────────────────────────────────────────────────────────────────────
|
||||
@@ -2304,8 +2315,8 @@ impl Db {
|
||||
sqlx::query(
|
||||
"INSERT INTO received_ref_updates
|
||||
(id, node_did, pusher_did, repo, ref_name, old_sha, new_sha, timestamp,
|
||||
cert_id, received_at, from_peer)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
|
||||
cert_id, received_at, from_peer, owner_did)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
|
||||
ON CONFLICT(id) DO NOTHING",
|
||||
)
|
||||
.bind(&update.id)
|
||||
@@ -2319,11 +2330,138 @@ impl Db {
|
||||
.bind(&update.cert_id)
|
||||
.bind(&update.received_at)
|
||||
.bind(&update.from_peer)
|
||||
.bind(&update.owner_did)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the trusted display `owner_did` for every ref-update row in a page,
|
||||
/// issuing at most one query per *unique* local repo so the cost scales with
|
||||
/// the number of distinct repos in the page rather than the page size.
|
||||
///
|
||||
/// The stored `owner_did` (and the `repo` slug) arrive over gossipsub or the
|
||||
/// unsigned peer-notify HTTP path, so neither is trusted. This method binds
|
||||
/// the wire `owner_did` to the local repo the slug names before it is ever
|
||||
/// surfaced:
|
||||
///
|
||||
/// * **P1 (untrusted wire value):** a peer-supplied `owner_did` is only
|
||||
/// echoed when it normalizes equal to the canonical owner of the *actual
|
||||
/// local repo* at that slug. A caller asserting `did:key:zVictim` on a
|
||||
/// `zAlice/widget` row is dropped, because `zVictim` does not own the
|
||||
/// local `zAlice/widget` repo. The canonical DID is returned (not the raw
|
||||
/// wire bytes), so the projection is always the local source of truth.
|
||||
/// * **P3 (legacy fallback):** a row stored with `owner_did = None` is
|
||||
/// attributed only via an *exact, normalized, unique* local match —
|
||||
/// `get_repo` matches the slug's owner key and name exactly (`LIMIT 1`,
|
||||
/// preferring canonical rows). The loose prefix-tolerant drop gate
|
||||
/// (`ref_update_row_names_repo`) is never used for attribution, so a
|
||||
/// cross-method slug collision cannot synthesize the wrong owner. When no
|
||||
/// unique local repo proves the owner, `None` is returned.
|
||||
///
|
||||
/// # P2 mirror-only fallback
|
||||
///
|
||||
/// Mirror-only repos store their owner as the bare normalized key (no DID
|
||||
/// method prefix). When a validated wire DID carries a full prefix (e.g.
|
||||
/// `did:key:z…`) and the matching repo is a mirror, the full wire value is
|
||||
/// returned so the API contract preserves the DID method for these rows.
|
||||
///
|
||||
/// The slug must be `"{owner}/{name}"`; a slug without a `/` cannot be
|
||||
/// attributed and yields `None`.
|
||||
pub async fn resolve_ref_update_owner_dids(
|
||||
&self,
|
||||
rows: &[(&str, Option<&str>)],
|
||||
) -> Result<Vec<Option<String>>> {
|
||||
if rows.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// ── 1. Collect unique lookup keys ────────────────────────────────
|
||||
let mut slug_parts: Vec<Option<String>> = Vec::with_capacity(rows.len());
|
||||
// Keys are stored as `format!("{normalized_key}\0{name}")` for cheap
|
||||
// HashMap lookup.
|
||||
let mut unique_keys: Vec<String> = Vec::new();
|
||||
|
||||
for (slug, _wire) in rows {
|
||||
if let Some((owner_part, name)) = slug.rsplit_once('/') {
|
||||
let normalized = normalize_owner_key(owner_part);
|
||||
let key = format!("{normalized}\0{name}");
|
||||
if !unique_keys.contains(&key) {
|
||||
unique_keys.push(key.clone());
|
||||
}
|
||||
slug_parts.push(Some(key));
|
||||
} else {
|
||||
slug_parts.push(None);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Fetch all matching repos in one set-based query ──────────
|
||||
// Build a single SQL with one OR condition per unique key so every
|
||||
// distinct slug is resolved in one round-trip regardless of how many
|
||||
// unique repos the page names.
|
||||
let mut repo_map: std::collections::HashMap<String, RepoRecord> =
|
||||
std::collections::HashMap::new();
|
||||
|
||||
if !unique_keys.is_empty() {
|
||||
let mut sql = String::from(
|
||||
"SELECT id, name, owner_did, description, is_public, default_branch,
|
||||
created_at, updated_at, disk_path, forked_from, machine_id
|
||||
FROM repos WHERE (",
|
||||
);
|
||||
let mut conds: Vec<String> = Vec::with_capacity(unique_keys.len());
|
||||
for i in 0..unique_keys.len() {
|
||||
let p = (2 * i + 1) as i64;
|
||||
let q = (2 * i + 2) as i64;
|
||||
conds.push(format!("({}) = ${p} AND name = ${q}", OWNER_KEY_CASE_SQL));
|
||||
}
|
||||
sql.push_str(&conds.join(" OR "));
|
||||
sql.push_str(
|
||||
") ORDER BY CASE WHEN position('/' in id) > 0 THEN 1 ELSE 0 END, \
|
||||
created_at ASC, id ASC",
|
||||
);
|
||||
|
||||
let mut q = sqlx::query(&sql);
|
||||
for key in &unique_keys {
|
||||
if let Some((owner_part, name)) = key.split_once('\0') {
|
||||
q = q.bind(owner_part).bind(name);
|
||||
}
|
||||
}
|
||||
|
||||
for row in q.fetch_all(&self.pool).await? {
|
||||
let repo = row_to_repo(row);
|
||||
let key = format!("{}\0{}", normalize_owner_key(&repo.owner_did), repo.name);
|
||||
repo_map.entry(key).or_insert(repo);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 3. Resolve every input row ──────────────────────────────────
|
||||
let mut results = Vec::with_capacity(rows.len());
|
||||
for (i, (_slug, wire_owner_did)) in rows.iter().enumerate() {
|
||||
let Some(repo) = slug_parts[i].as_ref().and_then(|k| repo_map.get(k)) else {
|
||||
results.push(None);
|
||||
continue;
|
||||
};
|
||||
|
||||
match (wire_owner_did, repo) {
|
||||
(Some(wire), repo)
|
||||
if normalize_owner_key(wire) == normalize_owner_key(&repo.owner_did) =>
|
||||
{
|
||||
if repo.id.contains('/') && *wire != repo.owner_did {
|
||||
results.push(Some((*wire).to_string()));
|
||||
} else {
|
||||
results.push(Some(repo.owner_did.clone()));
|
||||
}
|
||||
}
|
||||
(None, _) => {
|
||||
results.push(Some(repo.owner_did.clone()));
|
||||
}
|
||||
_ => results.push(None),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// One page of ref updates (newest first), optionally scoped to one repo.
|
||||
/// The `(timestamp DESC, id DESC)` order gives a stable tiebreak so offset
|
||||
/// paging does not skip or duplicate rows when timestamps collide. Used by
|
||||
@@ -2348,7 +2486,7 @@ impl Db {
|
||||
after: Option<(&str, &str)>,
|
||||
) -> Result<Vec<ReceivedRefUpdate>> {
|
||||
const COLS: &str = "id, node_did, pusher_did, repo, ref_name, old_sha, new_sha, \
|
||||
timestamp, cert_id, received_at, from_peer";
|
||||
timestamp, cert_id, received_at, from_peer, owner_did";
|
||||
|
||||
// Positional params in bind order: repo?, after_ts?, after_id?, limit.
|
||||
let mut conds: Vec<String> = Vec::new();
|
||||
@@ -2686,6 +2824,7 @@ fn row_to_ref_update(r: sqlx::postgres::PgRow) -> ReceivedRefUpdate {
|
||||
cert_id: r.get("cert_id"),
|
||||
received_at: r.get("received_at"),
|
||||
from_peer: r.get("from_peer"),
|
||||
owner_did: r.get("owner_did"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3406,6 +3545,115 @@ mod migration_tests {
|
||||
// it, you must also update the backfill.
|
||||
assert_eq!(MIGRATIONS[0].name, MIGRATION_V1_NAME);
|
||||
}
|
||||
|
||||
/// Simulate an existing node at v9 with populated received_ref_updates,
|
||||
/// then apply the v11 migration and verify (a) owner_did IS NULL on
|
||||
/// existing rows, (b) the column exists and is nullable TEXT, and
|
||||
/// (c) idempotent re-run does not error.
|
||||
#[sqlx::test]
|
||||
async fn migration_v11_creates_owner_did_column(pool: sqlx::PgPool) {
|
||||
let db = super::Db::for_testing(pool);
|
||||
|
||||
// Create all tables by running the full migration chain from scratch,
|
||||
// then drop the owner_did column to simulate a pre-v10 schema.
|
||||
db.migrate().await.unwrap();
|
||||
sqlx::query("ALTER TABLE received_ref_updates DROP COLUMN owner_did")
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Truncate schema_migrations and re-seed at v9 — simulate an existing
|
||||
// node that has run v1..v9 but not yet v10.
|
||||
sqlx::query("DELETE FROM schema_migrations")
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for m in MIGRATIONS.iter().take_while(|m| m.version < 10) {
|
||||
sqlx::query(
|
||||
"INSERT INTO schema_migrations (version, name, applied_at)
|
||||
VALUES ($1, $2, $3)",
|
||||
)
|
||||
.bind(m.version)
|
||||
.bind(m.name)
|
||||
.bind("2026-07-01T00:00:00Z")
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// ── Simulate an existing node with rows recorded before v11 ────────
|
||||
// The owner_did column does not exist yet, so we INSERT without it.
|
||||
let row_id = uuid::Uuid::new_v4().to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO received_ref_updates
|
||||
(id, node_did, pusher_did, repo, ref_name, old_sha, new_sha,
|
||||
timestamp, cert_id, received_at, from_peer)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)",
|
||||
)
|
||||
.bind(&row_id)
|
||||
.bind("did:key:zNode")
|
||||
.bind("did:key:zPusher")
|
||||
.bind("z6MkOwner/myrepo")
|
||||
.bind("refs/heads/main")
|
||||
.bind("0000000000000000000000000000000000000000")
|
||||
.bind("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
.bind("2026-07-01T12:00:00Z")
|
||||
.bind::<Option<String>>(None)
|
||||
.bind("2026-07-01T12:00:01Z")
|
||||
.bind("12D3KooWPeer")
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM received_ref_updates")
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1,
|
||||
"pre-migration row must exist"
|
||||
);
|
||||
|
||||
// ── Apply pending migrations (v10 ref_cert_unique_per_ref, v11 owner_did) ──
|
||||
db.migrate().await.unwrap();
|
||||
|
||||
// ── Assertions ────────────────────────────────────────────────────
|
||||
|
||||
// (a) Existing row has owner_did IS NULL (not overwritten).
|
||||
let owner: Option<String> =
|
||||
sqlx::query_scalar("SELECT owner_did FROM received_ref_updates WHERE id = $1")
|
||||
.bind(&row_id)
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(owner, None, "existing row's owner_did must be NULL");
|
||||
|
||||
// (b) Column exists and is nullable TEXT.
|
||||
let col: (String, String, String) = sqlx::query_as(
|
||||
"SELECT column_name, data_type, is_nullable
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'received_ref_updates' AND column_name = 'owner_did'",
|
||||
)
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(col.0, "owner_did");
|
||||
assert_eq!(col.1, "text");
|
||||
assert_eq!(col.2, "YES", "owner_did must be nullable");
|
||||
|
||||
// (c) Version 11 is recorded as applied.
|
||||
let v11_count: (i64,) =
|
||||
sqlx::query_as("SELECT COUNT(*) FROM schema_migrations WHERE version = 11")
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
v11_count.0, 1,
|
||||
"migration v11 must be recorded in schema_migrations"
|
||||
);
|
||||
|
||||
// (d) Re-run: idempotent — ADD COLUMN IF NOT EXISTS must not error.
|
||||
db.migrate().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -4454,6 +4702,7 @@ mod ref_update_keyset_paging_tests {
|
||||
cert_id: None,
|
||||
received_at: ts.into(),
|
||||
from_peer: "peer".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4562,6 +4811,7 @@ mod ref_update_keyset_repo_filtered_tests {
|
||||
cert_id: None,
|
||||
received_at: ts.into(),
|
||||
from_peer: "peer".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4668,6 +4918,7 @@ mod ref_update_keyset_same_timestamp_tests {
|
||||
cert_id: None,
|
||||
received_at: ts.into(),
|
||||
from_peer: "peer".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5263,3 +5514,170 @@ mod ref_certificate_tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod ref_update_db_tests {
|
||||
use super::{Db, ReceivedRefUpdate};
|
||||
use sqlx::PgPool;
|
||||
|
||||
async fn db(pool: PgPool) -> Db {
|
||||
let db = Db::for_testing(pool);
|
||||
db.run_migrations().await.unwrap();
|
||||
db
|
||||
}
|
||||
|
||||
fn update(
|
||||
id: &str,
|
||||
repo: &str,
|
||||
owner_did: Option<&str>,
|
||||
ref_name: &str,
|
||||
sha: &str,
|
||||
) -> ReceivedRefUpdate {
|
||||
ReceivedRefUpdate {
|
||||
id: id.to_string(),
|
||||
node_did: "did:key:zNode".into(),
|
||||
pusher_did: "did:key:zPusher".into(),
|
||||
repo: repo.to_string(),
|
||||
owner_did: owner_did.map(|s| s.to_string()),
|
||||
ref_name: ref_name.to_string(),
|
||||
old_sha: "0000000000000000000000000000000000000000".into(),
|
||||
new_sha: sha.to_string(),
|
||||
timestamp: "2026-07-02T12:00:00Z".into(),
|
||||
cert_id: None,
|
||||
received_at: "2026-07-02T12:00:01Z".into(),
|
||||
from_peer: "12D3KooWTest".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn insert_and_list_with_owner_did(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
db.insert_ref_update(&update(
|
||||
"u1",
|
||||
"zOwner/myrepo",
|
||||
Some("did:key:zOwner"),
|
||||
"refs/heads/main",
|
||||
"aaaa",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let all = db.list_ref_updates_keyset(None, 100, None).await.unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].owner_did.as_deref(), Some("did:key:zOwner"));
|
||||
assert_eq!(all[0].repo, "zOwner/myrepo");
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn insert_and_list_without_owner_did(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
db.insert_ref_update(&update(
|
||||
"u2",
|
||||
"zOwner/myrepo",
|
||||
None,
|
||||
"refs/heads/main",
|
||||
"bbbb",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let all = db.list_ref_updates_keyset(None, 100, None).await.unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].owner_did, None);
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn list_repo_ref_updates_filters_by_repo(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
db.insert_ref_update(&update(
|
||||
"u3",
|
||||
"alice/repo1",
|
||||
Some("did:key:zAlice"),
|
||||
"refs/heads/main",
|
||||
"cccc",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
db.insert_ref_update(&update(
|
||||
"u4",
|
||||
"bob/repo2",
|
||||
Some("did:key:zBob"),
|
||||
"refs/heads/feat",
|
||||
"dddd",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let alice_events = db
|
||||
.list_ref_updates_keyset(Some("alice/repo1"), 100, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(alice_events.len(), 1);
|
||||
assert_eq!(alice_events[0].id, "u3");
|
||||
assert_eq!(alice_events[0].owner_did.as_deref(), Some("did:key:zAlice"));
|
||||
|
||||
let bob_events = db
|
||||
.list_ref_updates_keyset(Some("bob/repo2"), 100, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bob_events.len(), 1);
|
||||
assert_eq!(bob_events[0].id, "u4");
|
||||
assert_eq!(bob_events[0].owner_did.as_deref(), Some("did:key:zBob"));
|
||||
|
||||
let empty = db
|
||||
.list_ref_updates_keyset(Some("other/repo"), 100, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(empty.is_empty());
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn list_ref_updates_filtered_by_repo(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
db.insert_ref_update(&update(
|
||||
"u5",
|
||||
"ownerA/proj",
|
||||
Some("did:key:zA"),
|
||||
"refs/heads/main",
|
||||
"eeee",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
db.insert_ref_update(&update(
|
||||
"u6",
|
||||
"ownerB/proj",
|
||||
Some("did:web:host:zB"),
|
||||
"refs/heads/main",
|
||||
"ffff",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let filtered = db
|
||||
.list_ref_updates_keyset(Some("ownerA/proj"), 100, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(filtered.len(), 1);
|
||||
assert_eq!(filtered[0].id, "u5");
|
||||
|
||||
let all = db.list_ref_updates_keyset(None, 100, None).await.unwrap();
|
||||
assert_eq!(all.len(), 2);
|
||||
}
|
||||
|
||||
#[sqlx::test]
|
||||
async fn insert_update_idempotent_on_conflict(pool: PgPool) {
|
||||
let db = db(pool).await;
|
||||
let u = update(
|
||||
"u7",
|
||||
"repo/x",
|
||||
Some("did:key:zX"),
|
||||
"refs/heads/main",
|
||||
"gggg",
|
||||
);
|
||||
db.insert_ref_update(&u).await.unwrap();
|
||||
db.insert_ref_update(&u).await.unwrap();
|
||||
|
||||
let all = db.list_ref_updates_keyset(None, 100, None).await.unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].new_sha, "gggg");
|
||||
}
|
||||
}
|
||||
@@ -73,9 +73,25 @@ impl QueryRoot {
|
||||
.await
|
||||
.map_err(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
|
||||
Ok(updates
|
||||
// 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(|e| async_graphql::Error::new(e.to_string()))?;
|
||||
|
||||
let resolved: Vec<RefUpdateType> = updates
|
||||
.into_iter()
|
||||
.map(|u| RefUpdateType {
|
||||
.zip(owner_dids)
|
||||
.map(|(u, owner_did)| RefUpdateType {
|
||||
repo: u.repo,
|
||||
ref_name: u.ref_name,
|
||||
old_sha: u.old_sha,
|
||||
@@ -83,8 +99,10 @@ impl QueryRoot {
|
||||
pusher_did: u.pusher_did,
|
||||
node_did: u.node_did,
|
||||
timestamp: u.timestamp,
|
||||
owner_did,
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
async fn tasks(
|
||||
@@ -162,6 +180,7 @@ mod tests {
|
||||
cert_id: None,
|
||||
received_at: Utc::now().to_rfc3339(),
|
||||
from_peer: "peer1".into(),
|
||||
owner_did: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,10 +264,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
let schema = schema(db);
|
||||
let q = r#"{ refUpdates { repo refName } }"#;
|
||||
let q = r#"{ refUpdates { repo refName ownerDid } }"#;
|
||||
let resp = anon(&schema, q).await;
|
||||
assert_eq!(count(&resp), 1);
|
||||
// The one row returned must be the public repo's.
|
||||
// The one row returned must be the public repo's with owner_did echoed.
|
||||
let async_graphql::Value::Object(obj) = &resp.data else {
|
||||
unreachable!()
|
||||
};
|
||||
@@ -262,6 +281,11 @@ 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.
|
||||
|
||||
@@ -39,6 +39,7 @@ impl SubscriptionRoot {
|
||||
pusher_did: ev.pusher_did,
|
||||
node_did: ev.node_did,
|
||||
timestamp: ev.timestamp,
|
||||
owner_did: Some(ev.owner_did),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ pub struct RefUpdateType {
|
||||
pub pusher_did: String,
|
||||
pub node_did: String,
|
||||
pub timestamp: String,
|
||||
pub owner_did: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(SimpleObject, Clone)]
|
||||
|
||||
@@ -39,6 +39,11 @@ 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)
|
||||
@@ -307,6 +312,7 @@ 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(),
|
||||
@@ -432,3 +438,67 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ pub struct RefUpdateBroadcast {
|
||||
pub pusher_did: String,
|
||||
pub node_did: String,
|
||||
pub timestamp: String,
|
||||
pub owner_did: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "gl"
|
||||
description = "The gitlawb CLI — identity management, node control, MCP server"
|
||||
version = "0.5.1" # x-release-please-version
|
||||
version = "0.7.0" # x-release-please-version
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -13,6 +13,7 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
gitlawb-core = { path = "../gitlawb-core" }
|
||||
icaptcha-client = { path = "../icaptcha-client" }
|
||||
base64 = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+216
-27
@@ -41,6 +41,16 @@ 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>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -52,7 +62,9 @@ pub async fn run(args: CertArgs) -> Result<()> {
|
||||
id,
|
||||
node,
|
||||
dir,
|
||||
} => cmd_show(repo, id, node, dir).await,
|
||||
verify,
|
||||
expect_node,
|
||||
} => cmd_show(repo, id, node, dir, verify, expect_node).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +126,14 @@ 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>) -> Result<()> {
|
||||
async fn cmd_show(
|
||||
repo: String,
|
||||
id: String,
|
||||
node: String,
|
||||
dir: Option<PathBuf>,
|
||||
require_valid: bool,
|
||||
expect_node: Option<String>,
|
||||
) -> Result<()> {
|
||||
let (owner, name) = resolve_repo(&repo, &node, dir.as_deref()).await?;
|
||||
|
||||
let client = signed_client(&node, dir.as_deref());
|
||||
@@ -148,39 +167,124 @@ async fn cmd_show(repo: String, id: String, node: String, dir: Option<PathBuf>)
|
||||
println!(" Signature: {signature}");
|
||||
println!();
|
||||
|
||||
// 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("");
|
||||
// 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,
|
||||
);
|
||||
|
||||
println!("Signature verification:");
|
||||
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.");
|
||||
match &verdict {
|
||||
Ok(()) => {
|
||||
println!(
|
||||
" VALID — Ed25519 signature verified against the key the certificate names ({node_did})"
|
||||
);
|
||||
}
|
||||
Err(reason) => {
|
||||
println!(" INVALID — {reason}");
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!(" Signature (base64url): {signature}");
|
||||
// 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"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
@@ -209,3 +313,88 @@ 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");
|
||||
}
|
||||
}
|
||||
+238
-11
@@ -16,6 +16,7 @@ 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 {
|
||||
@@ -141,18 +142,20 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
|
||||
// ── 3. GITLAWB_NODE env var ───────────────────────────────────────────
|
||||
match std::env::var("GITLAWB_NODE") {
|
||||
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(
|
||||
// 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(
|
||||
"GITLAWB_NODE",
|
||||
format!(
|
||||
"set to local address ({v}) — git push/clone will fail against remote nodes"
|
||||
"{v} (local node — intentional for self-hosting/dev; unset to target the public network)"
|
||||
),
|
||||
"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",
|
||||
@@ -242,6 +245,15 @@ 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")
|
||||
@@ -263,7 +275,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> {
|
||||
|
||||
// ── 7. Version up to date ─────────────────────────────────────────────
|
||||
let current = env!("CARGO_PKG_VERSION");
|
||||
checks.push(check_version(current).await);
|
||||
checks.push(check_version(current, GITHUB_API_BASE).await);
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────
|
||||
for check in &checks {
|
||||
@@ -308,6 +320,83 @@ 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| {
|
||||
@@ -319,8 +408,9 @@ fn which_in_path(name: &str) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Fetch the latest release tag from gitlawb/releases and compare to current version.
|
||||
async fn check_version(current: &'static str) -> Check {
|
||||
/// 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 {
|
||||
let client = match reqwest::Client::builder()
|
||||
.user_agent(format!("gl/{current}"))
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
@@ -331,7 +421,9 @@ async fn check_version(current: &'static str) -> Check {
|
||||
};
|
||||
|
||||
let resp = match client
|
||||
.get("https://api.github.com/repos/gitlawb/releases/releases/latest")
|
||||
.get(format!(
|
||||
"{github_api_base}/repos/Gitlawb/node/releases/latest"
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
@@ -339,6 +431,13 @@ async fn check_version(current: &'static 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)")),
|
||||
@@ -382,6 +481,88 @@ 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"));
|
||||
@@ -417,4 +598,50 @@ 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"));
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,23 @@ 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
|
||||
|
||||
+52
-4
@@ -38,13 +38,23 @@ 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"])
|
||||
.args(["init", "-b", "main"])
|
||||
.current_dir(&cwd)
|
||||
.status()
|
||||
.context("failed to run git init")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("git init failed");
|
||||
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");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("Git repository detected.");
|
||||
@@ -165,9 +175,47 @@ 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!();
|
||||
println!("Ready! Push with:");
|
||||
println!(" git push gitlawb main");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+207
-6
@@ -932,13 +932,33 @@ async fn call_tool(
|
||||
|
||||
"webhook_list" => {
|
||||
let repo = args["repo"].as_str().context("missing 'repo'")?;
|
||||
let owner = resolve_owner(&args, &client).await?;
|
||||
let resp: Value = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
|
||||
.await?
|
||||
.json()
|
||||
// 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"))
|
||||
.await?;
|
||||
Ok(serde_json::to_string_pretty(&resp)?)
|
||||
// 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)?)
|
||||
}
|
||||
|
||||
"webhook_delete" => {
|
||||
@@ -1825,6 +1845,187 @@ 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();
|
||||
|
||||
@@ -154,10 +154,12 @@ 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?;
|
||||
let client = NodeClient::new(&node, None);
|
||||
// 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 resp = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
|
||||
@@ -307,6 +309,9 @@ 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}"#)
|
||||
@@ -338,6 +343,8 @@ 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}"#)
|
||||
|
||||
+431
-34
@@ -146,6 +146,8 @@ pub enum RepoCmd {
|
||||
repo: String,
|
||||
#[arg(long, default_value = "https://node.gitlawb.com", env = "GITLAWB_NODE")]
|
||||
node: String,
|
||||
#[arg(long)]
|
||||
dir: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -203,7 +205,7 @@ pub async fn run(args: RepoArgs) -> Result<()> {
|
||||
RepoCmd::ReplicaUnregister { repo, node, dir } => {
|
||||
cmd_replica_unregister(repo, node, dir).await
|
||||
}
|
||||
RepoCmd::Replicas { repo, node } => cmd_replicas(repo, node).await,
|
||||
RepoCmd::Replicas { repo, node, dir } => cmd_replicas(repo, node, dir).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,7 +331,10 @@ async fn cmd_clone(name: String, node: String, dir: Option<PathBuf>) -> Result<(
|
||||
}
|
||||
|
||||
async fn cmd_info(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let client = NodeClient::new(&node, None);
|
||||
// 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 (owner, name) = if repo.contains('/') {
|
||||
let (o, n) = repo.split_once('/').unwrap();
|
||||
@@ -339,7 +344,10 @@ async fn cmd_info(repo: String, node: String, dir: Option<PathBuf>) -> Result<()
|
||||
(short, repo)
|
||||
};
|
||||
|
||||
let resp = client.get(&format!("/api/v1/repos/{owner}/{name}")).await?;
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
// 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.
|
||||
@@ -379,7 +387,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(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.await
|
||||
{
|
||||
if resp.status().is_success() {
|
||||
@@ -459,15 +467,17 @@ async fn cmd_replica_unregister(repo: String, node: String, dir: Option<PathBuf>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_replicas(repo: String, node: String) -> Result<()> {
|
||||
async fn cmd_replicas(repo: String, node: String, dir: Option<PathBuf>) -> Result<()> {
|
||||
let (owner, name) = repo
|
||||
.split_once('/')
|
||||
.map(|(o, n)| (o.to_string(), n.to_string()))
|
||||
.context("use owner/repo format")?;
|
||||
|
||||
let client = NodeClient::new(&node, None);
|
||||
// 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 resp = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/replicas"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let status = resp.status();
|
||||
@@ -585,7 +595,7 @@ async fn cmd_fork(
|
||||
}
|
||||
|
||||
/// Returns (owner, repo_name) — if repo contains '/', splits on it; otherwise uses caller's DID.
|
||||
async fn resolve_owner_repo_pair(
|
||||
pub(crate) async fn resolve_owner_repo_pair(
|
||||
repo: &str,
|
||||
node: &str,
|
||||
dir: Option<&std::path::Path>,
|
||||
@@ -658,16 +668,23 @@ 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: Value = client
|
||||
.get_authed(&format!("/api/v1/repos/{owner}/{name}/labels"))
|
||||
.await?
|
||||
.json()
|
||||
let resp = client
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}/labels"))
|
||||
.await
|
||||
.context("invalid JSON")?;
|
||||
.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}");
|
||||
}
|
||||
|
||||
let labels = resp["labels"].as_array().cloned().unwrap_or_default();
|
||||
let labels = body["labels"].as_array().cloned().unwrap_or_default();
|
||||
if labels.is_empty() {
|
||||
println!("No labels on {owner}/{name}");
|
||||
} else {
|
||||
@@ -679,17 +696,39 @@ 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?;
|
||||
let client = NodeClient::new(&node, None);
|
||||
// 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));
|
||||
|
||||
// Fetch repo info
|
||||
// Fetch repo info (get_repo is read-visibility-gated; sign so the owner can
|
||||
// inspect their own private repo).
|
||||
let resp = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.get_maybe_signed(&format!("/api/v1/repos/{owner}/{name}"))
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
if !resp.status().is_success() {
|
||||
@@ -704,25 +743,14 @@ 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
|
||||
// Fetch protected branches (read-visibility-gated; signed via the client).
|
||||
let protected: Vec<String> = match client
|
||||
.get(&format!("/api/v1/repos/{owner}/{name}/branches/protected"))
|
||||
.get_maybe_signed(&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();
|
||||
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()
|
||||
parse_protected_branches(&val)
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
@@ -760,6 +788,20 @@ 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();
|
||||
@@ -1097,6 +1139,10 @@ 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":[]}"#)
|
||||
@@ -1123,6 +1169,10 @@ 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"]}"#)
|
||||
@@ -1138,6 +1188,97 @@ 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();
|
||||
@@ -1148,11 +1289,15 @@ 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!(
|
||||
@@ -1167,9 +1312,11 @@ 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#"["main"]"#)
|
||||
.with_body(r#"{"protected_branches":["main"],"count":1}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1210,7 +1357,7 @@ mod tests {
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"["main","release"]"#)
|
||||
.with_body(r#"{"protected_branches":["main","release"],"count":2}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1251,7 +1398,7 @@ mod tests {
|
||||
)
|
||||
.with_status(200)
|
||||
.with_header("content-type", "application/json")
|
||||
.with_body(r#"["main"]"#)
|
||||
.with_body(r#"{"protected_branches":["main"],"count":1}"#)
|
||||
.create_async()
|
||||
.await;
|
||||
|
||||
@@ -1292,4 +1439,254 @@ 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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+52
-13
@@ -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:// origin)");
|
||||
println!(" repo (not in a gitlawb repo — no gitlawb:// remote)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,29 +143,68 @@ fn trust_bar(score: f64) -> String {
|
||||
format!("{}{}", "█".repeat(filled), "░".repeat(empty))
|
||||
}
|
||||
|
||||
/// Parse `gitlawb://<did>/<repo>` from the git origin remote.
|
||||
/// 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.
|
||||
fn detect_gitlawb_remote() -> Option<(String, String)> {
|
||||
let out = std::process::Command::new("git")
|
||||
.args(["remote", "get-url", "origin"])
|
||||
.args(["remote"])
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((did, repo))
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse a gitlawb:// URL string into (did, repo) — extracted for testing.
|
||||
#[cfg(test)]
|
||||
/// Parse a gitlawb:// URL string into (did, repo).
|
||||
fn parse_gitlawb_url(url: &str) -> Option<(String, String)> {
|
||||
let rest = url.trim().strip_prefix("gitlawb://")?;
|
||||
let slash = rest.rfind('/')?;
|
||||
|
||||
+11
-13
@@ -132,23 +132,11 @@ async fn read_body_capped(mut resp: reqwest::Response, cap: usize) -> String {
|
||||
/// `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))
|
||||
.filter(|c| !c.is_control() && !gitlawb_core::sanitize::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::*;
|
||||
@@ -293,6 +281,16 @@ mod tests {
|
||||
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");
|
||||
}
|
||||
|
||||
#[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
|
||||
|
||||
+169
-26
@@ -42,6 +42,8 @@ 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 {
|
||||
@@ -66,7 +68,7 @@ pub async fn run(args: WebhookArgs) -> Result<()> {
|
||||
node,
|
||||
dir,
|
||||
} => cmd_create(repo, url, events, secret, node, dir).await,
|
||||
WebhookCmd::List { repo, node } => cmd_list(repo, node).await,
|
||||
WebhookCmd::List { repo, node, dir } => cmd_list(repo, node, dir).await,
|
||||
WebhookCmd::Delete {
|
||||
repo,
|
||||
id,
|
||||
@@ -76,15 +78,6 @@ 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,
|
||||
@@ -94,8 +87,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();
|
||||
|
||||
@@ -106,7 +99,7 @@ async fn cmd_create(
|
||||
}))?;
|
||||
|
||||
let resp = client
|
||||
.post(&format!("/api/v1/repos/{owner}/{repo}/hooks"), &payload)
|
||||
.post(&format!("/api/v1/repos/{owner}/{name}/hooks"), &payload)
|
||||
.await
|
||||
.context("failed to connect to node")?;
|
||||
let status = resp.status();
|
||||
@@ -143,18 +136,31 @@ async fn cmd_create(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_list(repo: String, node: String) -> Result<()> {
|
||||
let client = NodeClient::new(&node, None);
|
||||
let owner = resolve_owner(&client).await?;
|
||||
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));
|
||||
|
||||
let resp: Value = client
|
||||
.get(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.context("invalid JSON")?;
|
||||
// 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 hooks = resp["webhooks"].as_array().cloned().unwrap_or_default();
|
||||
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")?;
|
||||
if hooks.is_empty() {
|
||||
println!("No webhooks for {repo}");
|
||||
return Ok(());
|
||||
@@ -185,13 +191,13 @@ async fn cmd_list(repo: String, node: String) -> 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}/{repo}/hooks/{id}"),
|
||||
&format!("/api/v1/repos/{owner}/{name}/hooks/{id}"),
|
||||
&payload,
|
||||
)
|
||||
.await
|
||||
@@ -337,33 +343,170 @@ 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()).await.unwrap();
|
||||
cmd_list(
|
||||
"my-repo".to_string(),
|
||||
server.url(),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.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()).await.unwrap();
|
||||
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"));
|
||||
}
|
||||
|
||||
// ── delete ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -16,3 +16,6 @@ anyhow = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
mockito = "1"
|
||||
@@ -64,6 +64,12 @@ 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;
|
||||
@@ -421,6 +427,34 @@ 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");
|
||||
@@ -429,6 +463,18 @@ 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]
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! INV-19 guard: the icaptcha flow must actually call the service (consume 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: `NO_PROXY` lets the loopback mock through while a
|
||||
//! closed proxy port routes any other host nowhere, so the client contacting
|
||||
//! anything but the injected mock fails the request instead of silently
|
||||
//! succeeding. Point `cfg.url` at `DEFAULT_URL` and this test goes RED.
|
||||
//!
|
||||
//! `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. No restore is needed: this file has a single
|
||||
//! `#[test]`, so it runs in its own process and the override never races a
|
||||
//! sibling test.
|
||||
|
||||
use icaptcha_client::{obtain_proof, Challenge, IcaptchaCfg};
|
||||
|
||||
#[test]
|
||||
fn obtain_proof_consumes_the_mocked_service_and_makes_no_live_call() {
|
||||
// Blackhole every non-loopback origin: the loopback mock bypasses the proxy
|
||||
// (NO_PROXY); any other host is forced through a closed port and fails.
|
||||
// reqwest reads these at client-build time, and obtain_proof builds its
|
||||
// client fresh, so this bounds the transport for the whole flow.
|
||||
//
|
||||
// Set the scheme-specific vars too (both cases), not just ALL_PROXY: reqwest
|
||||
// gives HTTPS_PROXY/https_proxy precedence over ALL_PROXY for https URLs, so
|
||||
// an ALL_PROXY-only blackhole leaves an https leak to DEFAULT_URL open on a
|
||||
// runner whose environment already has a working HTTPS_PROXY.
|
||||
let blackhole = "http://127.0.0.1:1";
|
||||
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, blackhole);
|
||||
}
|
||||
|
||||
let mut server = mockito::Server::new();
|
||||
|
||||
// The two endpoints the flow hits, each expected exactly once.
|
||||
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,
|
||||
};
|
||||
|
||||
// "anagram" is not a built-in solvable type, so the flow consults this
|
||||
// solver callback. The answer body itself does not matter: the mocked
|
||||
// /v1/answer returns "passed" regardless of what is submitted.
|
||||
let solve = |_c: &Challenge| Some("silent".to_string());
|
||||
let solver: &dyn Fn(&Challenge) -> Option<String> = &solve;
|
||||
|
||||
let proof = obtain_proof(&cfg, Some(solver))
|
||||
.expect("obtain_proof should complete against the mocked service");
|
||||
assert_eq!(proof, "PROOF-XYZ");
|
||||
|
||||
// INV-19: prove the client actually called the mocked endpoints. Had it made
|
||||
// a live call or skipped the network, these would fail (mock never hit).
|
||||
challenge.assert();
|
||||
answer.assert();
|
||||
}
|
||||
+14
@@ -193,5 +193,19 @@ 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"
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Dependency-purity gate for the `gitlawb-core` crate.
|
||||
#
|
||||
# gitlawb-core is embedded by every consumer (the gl CLI, git-remote-gitlawb,
|
||||
# the node daemon), so it must stay lean. This script recomputes gitlawb-core's
|
||||
# NORMAL (non-dev, non-build) transitive dependency set and fails if it contains
|
||||
# any crate not present in ci/gitlawb-core-allowed-deps.txt.
|
||||
#
|
||||
# Hard-fail direction: a crate present now but NOT allowlisted. That is the case
|
||||
# the gate exists to catch (core silently gaining a heavy dependency).
|
||||
# Informational only: an allowlisted crate no longer present (stale entry) — a
|
||||
# legitimate dependency removal should not red CI, so it is reported, not failed.
|
||||
#
|
||||
# Runnable from anywhere in the repo.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(git rev-parse --show-toplevel)"
|
||||
ALLOW="$ROOT/ci/gitlawb-core-allowed-deps.txt"
|
||||
|
||||
if [ ! -f "$ALLOW" ]; then
|
||||
echo "ERROR: allowlist not found at $ALLOW" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# `cargo tree` resolves like the build/test jobs (no --locked): the committed
|
||||
# Cargo.lock can lag the manifests, and --locked would red this gate for
|
||||
# lock-staleness reasons unrelated to gitlawb-core's dependencies. Resolving can
|
||||
# refresh Cargo.lock as a side effect, so snapshot and restore it — this check
|
||||
# must never leave the working tree dirty when run locally.
|
||||
lock_backup="$(mktemp)"
|
||||
cp "$ROOT/Cargo.lock" "$lock_backup"
|
||||
restore_lock() { cp "$lock_backup" "$ROOT/Cargo.lock"; rm -f "$lock_backup"; }
|
||||
trap restore_lock EXIT
|
||||
|
||||
# Current normal-dependency closure of gitlawb-core, one crate name per line.
|
||||
# Must match the regen command documented in the allowlist header exactly.
|
||||
current="$(
|
||||
cargo tree -p gitlawb-core --edges normal --prefix none --manifest-path "$ROOT/Cargo.toml" \
|
||||
| sed -E 's/ v[0-9].*$//' \
|
||||
| grep -v '^gitlawb-core$' \
|
||||
| sort -u
|
||||
)"
|
||||
|
||||
# Allowlist with comments and blank lines stripped.
|
||||
allowed="$(grep -vE '^[[:space:]]*(#|$)' "$ALLOW" | sort -u)"
|
||||
|
||||
# comm needs sorted input; both sides are sorted above.
|
||||
offenders="$(comm -23 <(printf '%s\n' "$current") <(printf '%s\n' "$allowed"))"
|
||||
stale="$(comm -13 <(printf '%s\n' "$current") <(printf '%s\n' "$allowed"))"
|
||||
|
||||
if [ -n "$stale" ]; then
|
||||
echo "NOTE: allowlisted crates no longer in gitlawb-core's dependency tree"
|
||||
echo " (safe to prune from ci/gitlawb-core-allowed-deps.txt):"
|
||||
printf ' %s\n' $stale
|
||||
echo
|
||||
fi
|
||||
|
||||
if [ -n "$offenders" ]; then
|
||||
{
|
||||
echo "ERROR: gitlawb-core gained dependencies not on the allowlist:"
|
||||
printf ' %s\n' $offenders
|
||||
echo
|
||||
echo "gitlawb-core must stay embeddable and lean. If a new dependency is"
|
||||
echo "intentional, add it to ci/gitlawb-core-allowed-deps.txt (regen command"
|
||||
echo "is in that file's header). Otherwise, drop the dependency."
|
||||
} >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "gitlawb-core dependency purity: OK ($(printf '%s\n' "$current" | wc -l | tr -d ' ') normal deps, all allowlisted)."
|
||||
Reference in new issue
Block a user