mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
test(fuzz): fuzz targets with properties, fuzzed nightly
Twenty-three new fuzz targets, built-in Go fuzzing, each checking a property rather than only that nothing panics: parsers of what a VM or the network sends fail closed and keep to their caps, a secret goes only where it's bound, and no planted secret survives a redaction. - internal/proxy: FuzzCursorFrames (passes only what came; no message over frameMax or holding a JWT's start, decompressed and unescaped), FuzzInject (a binding's value only to a host it names, judged apart from the matcher in NormHost's form, for its path and methods, in its own header, which held the exact placeholder once; other headers untouched), FuzzParseBindings, FuzzLinkList, FuzzParseUpstream (errors hold no more of the URL than its scheme), FuzzNoProxy, FuzzParseNarinfo (only cache.nixos.org-1's signed narinfo is taken). - internal/agentlogin: FuzzParseTokenRequest, FuzzRedact (secrets planted eight ways in JSON and TOML settings), FuzzCapture (the VM's reply holds none of the endpoint's tokens). - internal/redact: FuzzSplit (a password written in parts through Split, as the run log writes it, never survives). - internal/jsonc: FuzzStrip, differential against encoding/json. - internal/upgrade: FuzzParsePublicKey, FuzzVerify, FuzzEntryName, FuzzUnpack. - internal/vmssh: FuzzParseHostKeys, FuzzParsePorts. - internal/vm: FuzzParseCloneState, FuzzParseInit, FuzzParseKept, FuzzParseLFSPointer. - internal/desktop: FuzzHandshakeVM. What they found, each fixed with a regression test: - NO_PROXY: an entry with port 0 (git.test:0) was read as the host on every port, and git.test:080 or :+80 as port 80, which Go's clients match against nothing; an entry whose port no request has, or that isn't plain decimal, now matches nothing (TestNoProxy, testdata/fuzz/FuzzNoProxy). FuzzHostSites' NO_PROXY site allows this difference from its frozen copy, and the design note lists it. - A JSON token request with more after its object was judged by its first object; it's refused now (TestCaptureRefuses). The Fuzz workflow runs nightly rather than two minutes weekly: five minutes a target, eight at a time, each target's corpus restored from and saved to a cache of its own (a failing input added to it, so it fails nightly until fixed), new inputs minimized in at most 1,000 runs, and one issue, "Fuzzing found failing inputs", opened, commented on when the failing targets change and closed on a clean night, by a separate job with issues: write that runs no repo code, on main alone. Target names must be unique across packages. bump.sh moves an action in a folder of its repo (actions/cache/restore, /save) with its repo's releases. Docs: Contributing's Fuzzing (running a target, the nightly run, every target's property), Maintaining's Fuzzing failures and its actions bump, the proxy README, the NO_PROXY and token request facts in How it works' network page and the design note. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
29 files changed
+1848
-30
No files matched your search
+148
-12
@@ -1,11 +1,16 @@
|
||||
name: Fuzz
|
||||
|
||||
# go test runs only each fuzz target's seeds; this runs every target for a
|
||||
# few minutes a week. The list is read from the tests, so a new target is
|
||||
# fuzzed without editing this file.
|
||||
# go test runs only each fuzz target's seeds; this fuzzes every target for
|
||||
# five minutes each night, starting from the inputs its earlier nights found
|
||||
# (its corpus, which a cache keeps). The list is read from the tests, so a
|
||||
# new target is fuzzed without editing this file. The targets that fail go in
|
||||
# one open issue, which closes once a night's targets all pass: a failing
|
||||
# input is kept in its target's corpus, so it fails again each night until
|
||||
# the code is fixed. The fuzz jobs have only read access; the issue job,
|
||||
# which can write issues, runs no code of the repo's.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 6 * * 1"
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -18,13 +23,17 @@ concurrency:
|
||||
jobs:
|
||||
targets:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
matrix: ${{ steps.list.outputs.matrix }}
|
||||
count: ${{ steps.list.outputs.count }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# Each target as {"pkg","name"}, the proxy's first.
|
||||
# Each target as {"pkg","name"}, the proxy's first. A name is a
|
||||
# target's alone, as its artifacts and its line in the issue are
|
||||
# named by it.
|
||||
- id: list
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -32,34 +41,161 @@ jobs:
|
||||
| sed -E 's#^(.*)/[^/]*:func (Fuzz[A-Za-z0-9_]*)$#\1 \2#' \
|
||||
| sort -u | awk '{print ($1 ~ /^internal\/proxy$/ ? 0 : 1), $0}' | sort -k1,1n -k2 | cut -d' ' -f2-)
|
||||
test -n "$lines"
|
||||
dup=$(printf '%s\n' "$lines" | cut -d' ' -f2 | sort | uniq -d)
|
||||
if [[ -n $dup ]]; then
|
||||
echo "fuzz targets of one name in two packages: $dup" >&2
|
||||
exit 1
|
||||
fi
|
||||
matrix=$(printf '%s\n' "$lines" | awk 'BEGIN{printf "["} {if (NR>1) printf ","; printf "{\"pkg\":\"./%s\",\"name\":\"%s\"}", $1, $2} END{printf "]"}')
|
||||
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
|
||||
echo "count=$(printf '%s\n' "$lines" | wc -l)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
fuzz:
|
||||
needs: targets
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 4
|
||||
max-parallel: 8
|
||||
matrix:
|
||||
target: ${{ fromJSON(needs.targets.outputs.matrix) }}
|
||||
name: ${{ matrix.target.name }}
|
||||
env:
|
||||
NAME: ${{ matrix.target.name }}
|
||||
PKG: ${{ matrix.target.pkg }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# Only Go, cached apart from the other workflows' tools.
|
||||
- uses: jdx/mise-action@d5574b52816a478f9d4e6529a3f6ff17a8a36785 # v5.2.8
|
||||
with:
|
||||
version: 2026.11.8
|
||||
- run: go test -run '^$' -fuzz "^${NAME}\$" -fuzztime 2m "$PKG"
|
||||
env:
|
||||
NAME: ${{ matrix.target.name }}
|
||||
PKG: ${{ matrix.target.pkg }}
|
||||
install_args: go
|
||||
cache_key_prefix: mise-v1-fuzz
|
||||
# go test keeps a target's corpus in GOCACHE's fuzz folder, under the
|
||||
# package's import path and the target's name.
|
||||
- id: corpus
|
||||
run: |
|
||||
set -euo pipefail
|
||||
dir="$(go env GOCACHE)/fuzz/$(go list "$PKG")/$NAME"
|
||||
echo "dir=$dir" >> "$GITHUB_OUTPUT"
|
||||
echo "key=fuzz-${PKG#./}-$NAME" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ${{ steps.corpus.outputs.dir }}
|
||||
key: ${{ steps.corpus.outputs.key }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: ${{ steps.corpus.outputs.key }}-
|
||||
# Each new input is minimized in at most 1,000 runs: by time, a
|
||||
# target whose runs write files, such as FuzzUnpack, spends its five
|
||||
# minutes minimizing.
|
||||
- id: fuzz
|
||||
run: go test -run '^$' -fuzz "^${NAME}\$" -fuzztime 5m -fuzzminimizetime 1000x "$PKG"
|
||||
# A failing input lands in the package's testdata/fuzz/<target>/;
|
||||
# committed there, go test runs it as a seed.
|
||||
- if: failure()
|
||||
# committed there, go test runs it as a seed. It goes in the corpus
|
||||
# too, so the next night starts with it and fails until it's fixed.
|
||||
- if: failure() && steps.fuzz.outcome == 'failure'
|
||||
env:
|
||||
DIR: ${{ steps.corpus.outputs.dir }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
shopt -s nullglob
|
||||
mkdir -p "$DIR"
|
||||
for f in "$PKG/testdata/fuzz/$NAME"/*; do
|
||||
cp "$f" "$DIR/"
|
||||
done
|
||||
- if: failure() && steps.fuzz.outcome == 'failure'
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: crash-${{ matrix.target.name }}
|
||||
path: ${{ matrix.target.pkg }}/testdata/fuzz/${{ matrix.target.name }}/
|
||||
if-no-files-found: ignore
|
||||
# Saved whatever the night found, a failure included.
|
||||
- if: always() && steps.corpus.outputs.dir != ''
|
||||
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ${{ steps.corpus.outputs.dir }}
|
||||
key: ${{ steps.corpus.outputs.key }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
# The target's line for the issue job: its package, its name and how
|
||||
# its run ended.
|
||||
- if: always()
|
||||
env:
|
||||
OUTCOME: ${{ steps.fuzz.outcome }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p "$RUNNER_TEMP/result"
|
||||
echo "$PKG $NAME $OUTCOME" > "$RUNNER_TEMP/result/$NAME.txt"
|
||||
- if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: result-${{ matrix.target.name }}
|
||||
path: ${{ runner.temp }}/result/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
# Only main's run reports, so a run started on another branch never
|
||||
# closes the issue as main's.
|
||||
issue:
|
||||
needs: [targets, fuzz]
|
||||
if: always() && github.ref == 'refs/heads/main' && needs.targets.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
issues: write # to open, update and close the one issue of the failing targets
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
pattern: result-*
|
||||
merge-multiple: true
|
||||
path: ${{ runner.temp }}/results
|
||||
- name: Open, update or close the issue
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
COUNT: ${{ needs.targets.outputs.count }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
shopt -s nullglob
|
||||
title="Fuzzing found failing inputs"
|
||||
# Each target's line, with only the characters a package path, a
|
||||
# target's name and an outcome have.
|
||||
files=("$RUNNER_TEMP"/results/*.txt)
|
||||
cat ${files[@]+"${files[@]}"} /dev/null | LC_ALL=C tr -cd '0-9A-Za-z._/ \n-' > "$RUNNER_TEMP/all.txt"
|
||||
awk '$3 != "success" { print "- `" $2 "` in `" $1 "`: " $3 }' "$RUNNER_TEMP/all.txt" | sort > "$RUNNER_TEMP/failed.txt"
|
||||
# A target whose job reported nothing failed too.
|
||||
reported=$(wc -l < "$RUNNER_TEMP/all.txt")
|
||||
if (( reported < COUNT )); then
|
||||
echo "- $((COUNT - reported)) targets didn't report" >> "$RUNNER_TEMP/failed.txt"
|
||||
fi
|
||||
number=$(gh issue list --state open --search "in:title \"$title\"" --json number,title \
|
||||
--jq "map(select(.title == \"$title\")) | .[0].number // empty")
|
||||
if [[ ! -s $RUNNER_TEMP/failed.txt ]]; then
|
||||
if [[ -n $number ]]; then
|
||||
gh issue close "$number" --comment "Every fuzz target passed tonight, its failing inputs included: $RUN_URL"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
{
|
||||
echo "The nightly fuzzing found inputs that fail these targets:"
|
||||
echo
|
||||
cat "$RUNNER_TEMP/failed.txt"
|
||||
echo
|
||||
echo "The run, with each failing input as an artifact named \`crash-<target>\`: $RUN_URL"
|
||||
echo
|
||||
echo "Put each input in its package's \`testdata/fuzz/<target>/\` folder, fix the code, and commit both."
|
||||
echo "The input stays in the target's corpus, so it fails each night until the fix is on main,"
|
||||
echo "and this issue closes on the first night every target passes:"
|
||||
echo "see [Fuzzing](https://next.devvm.dev/docs/contributing/testing/#fuzzing)."
|
||||
} > "$RUNNER_TEMP/body.md"
|
||||
if [[ -z $number ]]; then
|
||||
gh issue create --title "$title" --label bug --body-file "$RUNNER_TEMP/body.md"
|
||||
exit 0
|
||||
fi
|
||||
# A night's new failures get a comment, which notifies; the same
|
||||
# targets failing again only update the run's link.
|
||||
gh issue view "$number" --json body --jq .body | tr -d '\r' > "$RUNNER_TEMP/old.md"
|
||||
if ! grep '^- ' "$RUNNER_TEMP/old.md" | cmp -s - "$RUNNER_TEMP/failed.txt"; then
|
||||
gh issue comment "$number" --body "The failing targets changed: the description lists tonight's."
|
||||
fi
|
||||
gh issue edit "$number" --body-file "$RUNNER_TEMP/body.md"
|
||||
@@ -138,3 +138,4 @@ These changes are on `main` and go out in the next release.
|
||||
- **A VM can't fill a Linux host with processes:** on a Linux host, each connection that a VM confined to its proxy made to the proxy started a devvm process on this machine, with no limit, so a VM that opened connections without end could start thousands of them. devvm now carries at most 256 of a VM's connections to its proxy at once, and answers any past that with `503` before it reaches the proxy. A VM that's running when you upgrade has no limit until its next start ([the QEMU wrapper](https://next.devvm.dev/docs/internals/processes/#the-qemu-wrapper-and-its-keeper)).
|
||||
- **A forwarded port answers after a burst:** when the port forwarder ran out of open files while accepting a connection, it stopped accepting connections on that port while it still listened there, so the port took connections that nothing answered until the server in the VM restarted. It now tries again shortly after, and so do a link's socket and a browser login's forward, which also carries at most 16 connections at once ([how it reaches the VM](https://next.devvm.dev/docs/internals/ports/#how-it-reaches-the-vm)).
|
||||
- **A VM's proxy lets go of what a VM leaves:** a VM's proxy counted only its tunnels toward its limit, kept idle connections open without end, kept a plain HTTP request running after its client had gone, and took 1 MiB of a request's headers inside an intercepted tunnel. It now holds at most 2048 of the VM's connections of every kind at once, where one without the VM's password doesn't count, has at most 2048 requests to hosts under way at once, closes a connection that waits 10 minutes for its next request, or that lacked the VM's password, ends a plain HTTP request a minute after its client has stopped sending and nothing has come back, takes at most 64 KiB of headers everywhere, and carries at most 100 HTTP/2 requests at once in a tunnel. A plain `ws://` WebSocket through the proxy, which got `502`, now connects. Long downloads, WebSockets and slow streams go on as long as they last ([the proxy](https://next.devvm.dev/docs/internals/network/#the-proxy)).
|
||||
- **A `NO_PROXY` entry with port 0 matches nothing:** the proxy read an entry such as `git.test:0` as `git.test` on every port, so it sent those hosts directly rather than through your company proxy, and it read `git.test:080` or `git.test:+80` as port 80, which Go's clients don't. An entry whose port no request has, or whose port isn't in plain decimal, now matches no host, as one past 65535 already didn't ([through a company proxy](https://next.devvm.dev/docs/internals/network/#through-a-company-proxy)).
|
||||
@@ -37,7 +37,7 @@ The tools, by group, as `--check` prints them:
|
||||
- `go` moves Go to its newest patch release of the minor that `go.mod` names: the `go` lines of `go.mod` and `docs/go.mod`, `mise.toml`'s `go`, and its `mise.lock` entries, from `go.dev/dl`. `--check` reports a newer minor on the `go-minor` line, and `scripts/bump.sh go-minor` moves the same files to it.
|
||||
- `go-mods` moves `go.mod`'s direct modules, the ones the depguard allowlist allows and the tests' own, to their newest patch or minor release from the Go module proxy, with `go get` and `go mod tidy`. The indirect ones move as `go mod tidy` needs them. A module's next major has a new path, so `--check` reports it and you move it by hand. `deadcode` moves the deadcode task's version in `mise.toml` to golang.org/x/tools' newest release.
|
||||
- `dev-tools` moves each of `mise.toml`'s tools but Go to mise's newest version of it, edits its line and runs `mise lock`, so `mise.lock` keeps every platform's checksum, and markdownlint-cli2's lock folder in `.mise/locks/` moves with it. nilaway has no releases, so its pin is a pseudo-version, and `dev-tools` moves it to the one for its newest commit.
|
||||
- `ci-mise` moves the `version` that the workflows give jdx/mise-action to base's mise, as the run leaves it, so `scripts/bump.sh mise ci-mise` moves both. `actions` moves each workflow's `uses:` to its newest release's tag, as the tag's commit from `gh api`, with the tag in the comment after it, and reports a newer major without applying it.
|
||||
- `ci-mise` moves the `version` that the workflows give jdx/mise-action to base's mise, as the run leaves it, so `scripts/bump.sh mise ci-mise` moves both. `actions` moves each workflow's `uses:` to its newest release's tag, as the tag's commit from `gh api`, with the tag in the comment after it, and reports a newer major without applying it. An action in a folder of its repo, such as `actions/cache/restore`, moves with its repo's releases.
|
||||
- `hextra` moves the docs site's theme in `docs/go.mod`, and it reminds you to compare the copies of Hextra's files in `docs/layouts/` with the new release's. `pele` moves pele, only when named, because the diagrams need a look on the built site: it runs `npm install` in `docs/` with the exact version and no install scripts, which writes `docs/package.json` and `docs/package-lock.json`, and then draws the diagrams again with `mise run docs:diagrams`. The drawing script's self-check fails that step when the new pele no longer measures and writes its small text, such as edge labels, as the script expects ([diagrams](docs.md#writing-docs)).
|
||||
- `cursor` moves Cursor's CLI, only when named, to the release that Cursor's install script fetches, with each platform's SHA-256 computed from its download, because Cursor publishes no checksums. devvm's login and proxy code was read against the pinned release, so read the new one where that code names it, then run `e2e-tools`.
|
||||
- A hold keeps a pin below a version, and `--check` shows the newest version beside it. Go modules and actions take Dependabot's ignore list in `.github/dependabot.yml`, which keeps pflag below 1.1.0, because pflag 1.1 prints every boolean flag with `[=true|false]` in the help. The other holds are in `bump.sh`'s `holds`, which keeps Node, the one in `mise.toml`, on its major.
|
||||
@@ -75,6 +75,17 @@ scripts/bump.sh go-mods # the direct modules' newest patches and minors, fo
|
||||
|
||||
A module that only `go.mod`'s indirect requirements hold moves with `go get <module>@<fixed version>` and `go mod tidy`. Once `main` is fixed, its scan passes, but the issue stays open while the latest release or the newest release still has the vulnerability, and it closes only when a release with the fix is the latest. A vulnerability that affects devvm's users calls for a release ([Releasing](#releasing)), and one that devvm's code reaches only in a way that doesn't matter can wait for the next one.
|
||||
|
||||
## Fuzzing failures
|
||||
|
||||
The Fuzz workflow (`.github/workflows/fuzz.yml`) fuzzes every target each night and keeps its failures in one issue, "Fuzzing found failing inputs", which names each failing target and links the night's run. For each target there, download its `crash-<target>` artifact from that run, and fix it as [Fuzzing](testing.md#fuzzing) says:
|
||||
|
||||
```sh
|
||||
cp ~/Downloads/crash-FuzzNoProxy/* internal/proxy/testdata/fuzz/FuzzNoProxy/ # the input, in its target's seeds
|
||||
go test -run '^FuzzNoProxy$' ./internal/proxy # fails until the code is fixed
|
||||
```
|
||||
|
||||
Commit the input with the fix and its test. The input stays in the target's corpus, so the target fails on it each night until the fix is on `main`, and the issue closes on the first night every target passes ([the nightly run](testing.md#the-nightly-run)).
|
||||
|
||||
## Checking base against Ubuntu's newest
|
||||
|
||||
The end-to-end tests pin base to `e2eUbuntuRelease`, so they never build base the way a user's first build does, from Ubuntu's newest cloud image and the mirrors' newest packages. An upstream change can break those builds before any test sees it. For example, vz's direct kernel boot needs an uncompressed arm64 kernel, and a VM shuts down only when its kernel has `gpio_keys`. `mise run e2e -- --newest-base` builds base as a user's first build does and runs the checks that prove it works: `images`, then `project` (a VM that boots, stops, starts again and shuts down) and `tools`. `--only` chooses other sections in their place.
|
||||
|
||||
@@ -290,7 +290,71 @@ TZ=Australia/Lord_Howe mise run test
|
||||
|
||||
## Fuzzing
|
||||
|
||||
`go test` runs only the seed inputs of each fuzz target, so the Fuzz workflow in `.github/workflows/fuzz.yml` fuzzes every target for two minutes each Monday, and you can start it by hand from the Actions tab. It finds the targets by reading each `func Fuzz` in the tests, so a new target is fuzzed without any change to the workflow, and the proxy's targets run first. When a target fails, the workflow uploads the input that broke it as an artifact named `crash-<target>`. Put that file in the package's `testdata/fuzz/<target>/` folder, fix the code, and commit both, because `go test` then runs the input as a seed every time. To fuzz one target on your machine, run `go test -run '^$' -fuzz '^FuzzParseRule$' -fuzztime 1m ./internal/proxy`.
|
||||
devvm's fuzz targets use Go's built-in fuzzing, and each one checks a property of what it fuzzes, not only that nothing panics. `go test` runs only each target's seed inputs, the ones its `f.Add` lines give and the files in its package's `testdata/fuzz/<target>/` folder, so every run of the tests checks them. To fuzz one target on your machine, or to run one failing input again:
|
||||
|
||||
```sh
|
||||
go test -run '^$' -fuzz '^FuzzNoProxy$' -fuzztime 2m ./internal/proxy # fuzz one target for two minutes
|
||||
go test -run '^$' -fuzz '^FuzzNoProxy$' -parallel 2 ./internal/proxy # with two workers, on a busy machine
|
||||
go test -run '^$' -fuzz '^FuzzUnpack$' -fuzzminimizetime 1000x ./internal/upgrade # minimizing each new input in 1,000 runs
|
||||
go test -run '^FuzzNoProxy/e9e4d242dc7b413a$' ./internal/proxy # one input in testdata/fuzz/FuzzNoProxy/
|
||||
```
|
||||
|
||||
When a target fails, `go test` writes the input that broke it to the package's `testdata/fuzz/<target>/` folder. Fix the code, add a test of the fix beside the code's other tests, and commit the input with them, because `go test` then runs it as a seed every time.
|
||||
|
||||
### The nightly run
|
||||
|
||||
The Fuzz workflow (`.github/workflows/fuzz.yml`) fuzzes every target for five minutes each night, eight targets at a time, and you can start it by hand from the Actions tab. It minimizes each new input in at most 1,000 runs (`-fuzzminimizetime 1000x`), because by default `go test` minimizes each one for up to a minute, and a target whose runs write files, such as `FuzzUnpack`, would spend its five minutes doing that. It finds the targets by reading each `func Fuzz` in the tests, so a new target is fuzzed without any change to the workflow, and the proxy's targets run first. A target's name must be its own across the packages, because its artifacts and its line in the issue are named by it, and two targets of one name fail the run.
|
||||
|
||||
Each target starts from its corpus, the inputs that its earlier nights found reaching new code, so each night goes further than the last rather than starting again from the seeds. `go test` keeps a target's corpus in the `fuzz` folder of `GOCACHE`, and the workflow restores it from a cache of the target's own before fuzzing and saves it afterwards, whether the target failed or not. When a target fails, the workflow uploads the input that broke it as an artifact named `crash-<target>`, and it adds the input to the target's corpus, so the target fails on it again each night until the fix is on `main`.
|
||||
|
||||
The workflow keeps the failures in one issue, "Fuzzing found failing inputs":
|
||||
|
||||
- **It opens the issue** on the first night a target fails. The issue lists each failing target with its package and how its run ended, and links the night's run, where the `crash-<target>` artifacts are. A target whose job reported nothing counts as failing too.
|
||||
- **It comments on the issue** when the failing targets change, so a new failure notifies you, and otherwise it only updates the issue's link to the latest run.
|
||||
- **It closes the issue** on the first night every target passes, the inputs that failed included.
|
||||
- **Only a run on `main` updates the issue,** so a run started on another branch never closes it. The fuzz jobs run the repo's code with read access alone, and the issue job, the only one that can write issues, runs none of it.
|
||||
|
||||
### What each target checks
|
||||
|
||||
The parsers of what a VM can write, its output and its files, and of what comes from the network fail closed: what they take is only what their format allows, within its caps. A secret's value goes only where it's bound, and a redaction leaves no planted secret behind. The host readers' targets are differential: each checks one reader against a frozen copy of how it read a host before devvm read every host in one form, and allows only the differences that [One form of a host](../internals/design.md#one-form-of-a-host) lists.
|
||||
|
||||
| Target | Package | What it checks |
|
||||
| --- | --- | --- |
|
||||
| `FuzzCursorFrames` | `internal/proxy` | A reply from a Cursor host, of any type, encodings, body and trailers, read in reads of any size, passes only what came, from its start. A Connect or gRPC stream passes whole messages alone, none over `frameMax` as it came or as it decompresses, so a gzip bomb is refused, and none holding a JWT's start once decompressed and, in JSON, with its escapes undone. Another body passes no JWT's start of up to `jwtWindow` bytes, and a trailer holding one never lets the body end cleanly. |
|
||||
| `FuzzInject` | `internal/proxy` | Whatever a request's host, method, path and headers, each binding's value goes in only for a host the binding names, judged apart from the policy's matcher, in `NormHost`'s form, for a path and methods it allows. It goes in its own header alone, once, and only when exactly one of that header's values held its exact placeholder. Every other header stays as it came. |
|
||||
| `FuzzParseBindings` | `internal/proxy` | A bindings file is read only at a version the proxy knows, with each binding's kind, path, methods and scheme ones it takes, and none of version 1 that a proxy of that version reads otherwise. A file that's read reads back as itself from what `Encode` writes. |
|
||||
| `FuzzLinkList` | `internal/proxy` | A links list is read only at its version, and a host and port find only an entry that names them, at a link's address in `127.77.0.0/16` as `netip` writes it, whose socket is this VM's link's for that address and port. |
|
||||
| `FuzzParseUpstream` | `internal/proxy` | A company proxy's URL is taken only as `http://`, with a host, a port that is one or none, and no path but `/` or query, and the upstream made of it has that host and port and Basic credentials only when it names a user. Its errors hold no more of the URL than its scheme. |
|
||||
| `FuzzNoProxy` | `internal/proxy` | Each `NO_PROXY` entry sends directly only what it names: every host for `*`, addresses alone for an address or a CIDR, a name and the names under it, only those after a leading `.` or `*.`, and only the port an entry names. A list sends directly what any of its entries does. |
|
||||
| `FuzzParseNarinfo` | `internal/proxy` | A narinfo is taken only when `cache.nixos.org-1` signed it, for the path asked for, and what the signature doesn't cover keeps to its forms: a NAR's URL named by its `NarHash` or `FileHash`, and sizes from 1 byte to 1 TiB. |
|
||||
| `FuzzParseTokenRequest` | `internal/agentlogin` | A token request is read only as a form, or with no type, or as one JSON object alone, with no field named twice however its name is written, and its fields are what it sent. |
|
||||
| `FuzzRedact` | `internal/agentlogin` | No secret planted in an agent's settings file, JSON or TOML, survives into the VM's copy, which reads back: a known key's shape as a value or among other words, a URL's password or query value, a value under a secret-looking key, an env or headers table's value, and a flag's argument. Claude Code's own settings in its top-level `env` stay, as Redact keeps them. |
|
||||
| `FuzzCapture` | `internal/agentlogin` | Whatever an agent's token endpoint replies to whatever request, for every agent whose login devvm captures, the VM's reply is a JSON object holding none of the reply's tokens, and a reply that isn't captured leaves the store unwritten. |
|
||||
| `FuzzSplit` | `internal/redact` | A password that `String` finds in a line, in a URL of at most the tail's length, never reaches the log when the line comes in parts of any size and is written after each part as far as `Split` lets it, as the run log writes it. |
|
||||
| `FuzzStrip` | `internal/jsonc` | `Strip` keeps every offset, blanking bytes with spaces and keeping newlines, leaves JSON as it is, and, against `encoding/json`, makes JSON with comments, trailing commas and a byte order mark read as the same value as the JSON without them. |
|
||||
| `FuzzParsePublicKey` | `internal/upgrade` | A minisign public key is read only from one base64 line, alone or after its untrusted comment, as exactly its key ID and its Ed25519 key. |
|
||||
| `FuzzVerify` | `internal/upgrade` | A signature verifies only the data its key's holder signed, with the trusted comment that was signed. |
|
||||
| `FuzzEntryName` | `internal/upgrade` | An archive's entry is taken only as the release's folder or as a regular file right in it, which lands in the folder `unpack` makes and nowhere else. |
|
||||
| `FuzzUnpack` | `internal/upgrade` | `unpack` writes only regular files right in the folder it makes, `devvm` among them, each as the archive has it, `devvm` executable and the rest not, at most `unpackCap` in all and nothing outside the folder. An archive it refuses leaves no folder. |
|
||||
| `FuzzParseHostKeys` | `internal/vmssh` | Each host key taken from what a VM shows is of a type ssh has, with no certificate, marker or pattern, in strict base64 of at most `keyMax` that names its own type, from a line of the VM's own, in order. Its line in the record is three fields, which read back as that key. |
|
||||
| `FuzzParsePorts` | `internal/vmssh` | A forwarder's record, which other VMs' forwarders read, gives only ports that are ones, each an entry of its line, in order, and the ports it writes read back as themselves. |
|
||||
| `FuzzParseCloneState` | `internal/vm` | A `--clone` VM's answer to the check is taken only whole: every repo asked for is gone or has its branches and status, within `cloneRefsMax` branches in all and `cloneWorktreesMax` worktrees a repo, each worktree once, at a clean path below the project folder, with a commit's name or none for its HEAD. Nothing taken is more than the answer. |
|
||||
| `FuzzParseInit` | `internal/vm` | The VM's answer to its repos' setup names a seed as landed, or of another format, only when a line names that seed's path, and an old git only by what `git --version` prints, else as unknown. |
|
||||
| `FuzzParseKept` | `internal/vm` | What a seed's apply kept, which devvm only shows, is the VM's own lines and names as it wrote them, none of them empty. |
|
||||
| `FuzzParseLFSPointer` | `internal/vm` | A blob is taken as a Git LFS pointer only as the spec writes one, with its version line first and each line ended, one oid of 64 lowercase hex digits, which names its object's path, and one size of at least 0. |
|
||||
| `FuzzHandshakeVM` | `internal/desktop` | The relay's handshake with the VM's VNC server succeeds only for version 3.8 or later, a list of security types that has None, and an OK result, and reads no more than those. It writes only version 3.8, then None, and None only from a list that has it, and its error, which goes in the log, stays short. |
|
||||
| `FuzzHostSites` | `internal/proxy` | Each of the proxy's readers of a host reads it as its frozen copy did, but for the listed differences. |
|
||||
| `FuzzClaudeHostSite`, `FuzzPromisorHostSite`, `FuzzPublicHostSite`, `FuzzRiskSites`, `FuzzCheckHostSite` | `internal/agentlogin`, `internal/vm`, `internal/from`, `internal/netpolicy`, `internal/secrets` | The other readers of a host, an MCP server's, a promisor remote's, `--from`'s registry's, `devvm network lock`'s and a secret's `--host`, read it as their frozen copies did, but for the listed differences. |
|
||||
| `FuzzParseRule` | `internal/proxy` | A rule's text parses back to the same rule, a host rule never holds a space or a slash, and `ParsePolicy` marks a line a rule exactly when `ValidRule` takes it. |
|
||||
| `FuzzRequest` | `internal/proxy` | A request target the proxy accepts is a plain host, and the allow command it suggests allows exactly that host and port. |
|
||||
| `FuzzDenyBypass` | `internal/proxy` | A deny of `/gists/` and of `POST` holds however a request spells the path or the method. |
|
||||
| `FuzzClientHello` | `internal/proxy` | Reading a tunnel's first bytes never hangs, a stream whose first byte starts a TLS record counts as TLS, and only a whole record of TLS's version is returned. |
|
||||
| `FuzzTransparent` | `internal/proxy` | Whatever its first bytes, a transparent connection to a proxy whose policy allows nothing reaches nothing. |
|
||||
| `FuzzNixPath` | `internal/proxy` | What `nixPath` takes is one of the cache's exact forms and names a file inside its folder. |
|
||||
| `FuzzParse` | `internal/devcontainer` | A `devcontainer.json` refuses `${localEnv:…}`, its variables are names and shell words the environment file holds as they are, and nothing it keeps has a NUL. |
|
||||
| `FuzzParseRef` | `internal/from` | Any image reference parses into a tag without `/` or `:`, and a valid one parses the same once written out in full. |
|
||||
| `FuzzRestrictNetdev` | `internal/backend/lima` | `RestrictNetdev` refuses, or returns at most one network, restricted, with nothing else changed. |
|
||||
| `FuzzQuote` | `internal/shell` | A string that `Quote` quotes reaches a shell as itself. |
|
||||
|
||||
## Manual checks
|
||||
|
||||
|
||||
@@ -316,6 +316,7 @@ Every check that judges or compares a host reads it in one form, `proxy.NormHost
|
||||
- **A line that isn't a rule**, which devvm network rm and its duplicate check compare as text, is the same as another in ASCII letters' case and one trailing dot alone, so a Kelvin sign typed for a `k` never names the rule with the `k`, such as the deny `!kubernetes.io`.
|
||||
- **An SNI's trailing dot** on the transparent path is dropped, as a request's is. `crypto/tls` refuses such a ClientHello, so none reaches it.
|
||||
- **A `NO_PROXY` name that isn't ASCII** matches no host, so the Kelvin sign's `kubernetes.io` doesn't send `kubernetes.io` directly, and the request goes through the company proxy.
|
||||
- **A `NO_PROXY` entry with port `0`**, which no request has, sends nothing directly, as one with a port past `65535` doesn't, where the copy read `git.test:0` as `git.test` on every port (found by `FuzzNoProxy`). Neither does an entry whose port isn't in plain decimal, such as `git.test:080` or `git.test:+80`, which Go's clients match against no request, where the copy read it as port 80.
|
||||
- **A secret's `--host` or an MCP server's host that isn't ASCII** is refused, as the proxy refuses it, rather than taken as the ASCII host its letters fold into.
|
||||
- **`--from`'s registry** isn't on the internet when its name is one the proxy doesn't take (`HostOK`), such as one with anything but printable ASCII, a bracket that a trailing dot hid (`[::1].`) or a shorthand address (`10.1`), none of which a registry's name is, so a registry is never more public than the copy finds it.
|
||||
- **A partial clone's promisor remote** loses its trailing dot, so a warning names `example.com` rather than `example.com.`, and `localhost.` or `127.0.0.1.` counts as private, as the proxy refuses it. The Kelvin sign isn't folded.
|
||||
|
||||
@@ -126,7 +126,7 @@ The proxy decides each request as it does without a company proxy, by the host n
|
||||
- A plain HTTP request goes to `HTTP_PROXY`'s proxy in absolute form, with its `Proxy-Authorization` in place of the VM's. The company proxy's address in the request has no password, so no error the proxy logs holds one.
|
||||
- Without `HTTPS_PROXY` or `HTTP_PROXY`, those requests go directly.
|
||||
|
||||
`NO_PROXY` is a comma-separated list, which the proxy reads as Go's clients read it. In it, `*` matches every host, and an address or a CIDR matches addresses. A name matches itself and its subdomains, while a name with a leading `.` or `*.` matches only its subdomains. Any entry can end in a port, which limits it to that port. The proxy reads a name in `NO_PROXY` as it reads the host of every request, lowercased in ASCII alone and without one trailing dot, so a name with a character that isn't printable ASCII matches no host, because Unicode's case folding would turn the Kelvin sign into `k`.
|
||||
`NO_PROXY` is a comma-separated list, which the proxy reads as Go's clients read it. In it, `*` matches every host, and an address or a CIDR matches addresses. A name matches itself and its subdomains, while a name with a leading `.` or `*.` matches only its subdomains. Any entry can end in a port, which limits it to that port, and an entry whose port no request has, such as `git.test:0`, or whose port isn't in plain decimal, such as `git.test:080`, matches nothing. The proxy reads a name in `NO_PROXY` as it reads the host of every request, lowercased in ASCII alone and without one trailing dot, so a name with a character that isn't printable ASCII matches no host, because Unicode's case folding would turn the Kelvin sign into `k`.
|
||||
|
||||
The company proxy resolves the names it's sent, so the proxy can't hold it to the addresses it checked, and the floor changes for those requests. An address in the VM's request is checked as before, and a host whose last label is all digits or starts with `0x`, such as `127.1`, gets `400`, because a company proxy may read it as an address. For a name, the proxy asks this machine's resolver, for at most three seconds, and refuses the request when any answer is internal or denied, unless a rule names the address. A name this machine can't resolve, which is common behind a company proxy, goes to the company proxy unchecked when a rule names it, as itself or under `*.domain`. When only `**` allows it, the proxy refuses it with `403`, and the event log says that this machine can't resolve it and only `**` allows it. The proxy reads at most 64 KiB of the company proxy's answer to `CONNECT`. [The design note](design.md#a-company-proxy) explains what that leaves open, which [Attack vectors](../safety/attack-vectors.md#network) lists, and how builds reach the company proxy through a proxy of their own.
|
||||
|
||||
@@ -325,7 +325,7 @@ Each VM's placeholders end in its own random value, so no other VM's placeholder
|
||||
|
||||
A login that an agent makes inside a VM goes to devvm's store too, and the VM gets only placeholders for it. The VM's proxy does this at the agent's OAuth token endpoint, the one request of a login whose reply holds its tokens. Codex and opencode both log in to OpenAI at `auth.openai.com/oauth/token`, whether the code comes from a browser's redirect or from a device code typed into a browser elsewhere. For opencode 2, those are its Codex logins, the methods `chatgpt-browser` and `chatgpt-headless`. Its Sign in with ChatGPT, `chatgpt-token-sharing`, registers a client of its own and gets its tokens from `auth.openai.com/api/accounts/oauth/token`, then checks the `id_token`'s signature against OpenAI's keys, which a placeholder can't pass, so devvm doesn't capture that endpoint, and its replies get `502`, as the next paragraph says. Every VM's proxy config lists that endpoint in `captures`, for Codex and for opencode, whatever the VM's image holds, because a program in the VM could install either agent itself, and the proxy refuses that agent's login rather than let its tokens reach the VM. The endpoint's host joins the VM's `secrets.policy` on port 443 only when its image has one of them, so that agent can log in on every tier. The proxy intercepts the host's `:443` tunnels as it does a bound host's, with a certificate from [the VM's CA](#the-vms-ca), and forwards every request to it. Only a request of the endpoint's method to its path is captured, a `POST` for every OAuth token endpoint, and the proxy compares the path once it's cleaned, each segment without its path parameters, a backslash read as a slash, and in any case, as a host that normalizes paths reads it, so a request for `/oauth//token`, `/OAuth/Token/`, `/oauth/token;x` or `/x;/../oauth/token` is captured too. A captured request goes to the endpoint's own path whatever the VM's spelling of it, and a `POST` goes without a query. An endpoint can be a `GET` instead, for a login that the agent polls for, whose request is its query. The proxy then refuses a query that isn't a form or that names a field twice, which devvm and the endpoint could read apart, and a `GET` with a body, and the query goes on in a canonical form, its fields sorted, so the endpoint reads what devvm read. Any other successful reply from that host that names an `access_token`, a `refresh_token` or an `id_token` anywhere gets `502`, whatever its type, so no other path there, such as another token endpoint's, hands the VM a login, and so does one that names a field that the endpoint's agent keeps its tokens in, such as `accessToken`. The proxy passes only a web page and its parts unread, which are HTML, CSS, JavaScript, images and fonts, and it refuses a reply it can't read for that, one that's encoded or longer than 1 MiB, and an upgrade (`101`). No informational reply (`1xx`) from the host reaches the VM, because its headers could hold a cookie. When the host serves an API of its own beside the endpoint, which these checks would break, with its streamed, encoded or long replies, the endpoint names a path prefix that the endpoint is below, its guard, and the proxy checks only the replies below it. It checks the reply to any path that isn't already clean too, such as one with path parameters, encoded characters or `..`, because the host could read it as below the guard where devvm doesn't. The API's replies elsewhere pass as they are, their informational replies, upgrades and encodings included. A path there that handed out tokens would hand them to the VM, and the VM's requests to that API carry the agent's real login, which the proxy puts in, so the agent's section names the paths that could.
|
||||
|
||||
The proxy reads a captured request's body whole, up to 64 KiB, and refuses one that names a field twice, which devvm and the endpoint could read apart. It drops the VM's `Accept-Encoding` header from every request to the host, so each reply comes as it is, or as gzip that Go's transport undoes. The request goes on unchanged, with two exceptions. After a code's login, Codex exchanges the login's `id_token` for an API key, with a token-exchange grant that asks for `openai-api-key`. The VM's request carries the VM's placeholder of the `id_token`, so the proxy puts the store's `id_token` in its place, and only when the placeholder is that VM's for the store's current login. An error reply to that request reaches the VM with its OAuth error code alone, such as `{"error":"invalid_grant"}`, in case the endpoint's message quotes the `id_token`. A refresh whose refresh token is the VM's own, `devvm-proxy-managed`, or for opencode its access token's placeholder, goes nowhere, and the VM gets the store's login as placeholders again, because the host refreshes the login itself. devvm refuses any other grant than a code's, a refresh's or Codex's exchange before the request leaves the host, because it couldn't read the reply. The proxy reads at most 8 requests and replies to and from the host whole at once.
|
||||
The proxy reads a captured request's body whole, up to 64 KiB, and refuses one that names a field twice, or a JSON body with more after its object, which devvm and the endpoint could read apart. It drops the VM's `Accept-Encoding` header from every request to the host, so each reply comes as it is, or as gzip that Go's transport undoes. The request goes on unchanged, with two exceptions. After a code's login, Codex exchanges the login's `id_token` for an API key, with a token-exchange grant that asks for `openai-api-key`. The VM's request carries the VM's placeholder of the `id_token`, so the proxy puts the store's `id_token` in its place, and only when the placeholder is that VM's for the store's current login. An error reply to that request reaches the VM with its OAuth error code alone, such as `{"error":"invalid_grant"}`, in case the endpoint's message quotes the `id_token`. A refresh whose refresh token is the VM's own, `devvm-proxy-managed`, or for opencode its access token's placeholder, goes nowhere, and the VM gets the store's login as placeholders again, because the host refreshes the login itself. devvm refuses any other grant than a code's, a refresh's or Codex's exchange before the request leaves the host, because it couldn't read the reply. The proxy reads at most 8 requests and replies to and from the host whole at once.
|
||||
|
||||
A successful reply never reaches the VM as it is. The proxy reads it whole, up to 1 MiB, and `agentlogin.File.Capture` saves its tokens in the store's login file, in the agent's own format, under the file's lock, so a refresh on the host never runs at the same time. Codex's goes in `tokens` of its `auth.json`, with the account from the `id_token`, and the exchange's API key in `OPENAI_API_KEY`. opencode's goes in the `openai` entry of its `auth.json`, as an OAuth login with its expiry in milliseconds and its account. A code's reply replaces the login, and for Codex the API key of the login before it too. A refresh's reply adds to the login, so the store keeps only the newest refresh token. Then devvm writes the VM's bindings again, so its proxy puts the new login into requests at once. When that write fails, the login is saved still, the VM gets its reply, its proxy's own log says why, and the VM's next launch writes its bindings.
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -188,7 +189,7 @@ func (t tokenRequest) withSubject(id redact.Secret) []byte {
|
||||
var errRepeated = errors.New("the token request repeats a field")
|
||||
|
||||
// parseTokenRequest reads a token request's body of Content-Type ctype: a form (or no type) or a
|
||||
// JSON object, each field once.
|
||||
// JSON object alone, each field once.
|
||||
func parseTokenRequest(ctype string, body []byte) (tokenRequest, error) {
|
||||
mt, _, _ := mime.ParseMediaType(ctype)
|
||||
switch mt {
|
||||
@@ -210,6 +211,11 @@ func parseTokenRequest(ctype string, body []byte) (tokenRequest, error) {
|
||||
if d.Decode(&m) != nil || m == nil {
|
||||
return tokenRequest{}, errors.New("the token request isn't a JSON object")
|
||||
}
|
||||
// One object alone: the endpoint would read another after it, or refuse the request, and
|
||||
// devvm would have judged the first.
|
||||
if _, err := d.Token(); !errors.Is(err, io.EOF) {
|
||||
return tokenRequest{}, errors.New("the token request has more after its JSON object")
|
||||
}
|
||||
if n, err := topKeys(body); err != nil || n != len(m) {
|
||||
return tokenRequest{}, errRepeated
|
||||
}
|
||||
|
||||
@@ -182,6 +182,8 @@ func TestCaptureRefuses(t *testing.T) {
|
||||
{"no access token", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code"}`), reply(map[string]any{"refresh_token": "r"})},
|
||||
{"a field twice in a form", Codex, formType, append(form("grant_type", grantCode), "&grant_type=refresh_token"...), reply(map[string]any{"access_token": "a"})},
|
||||
{"a field twice in JSON", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code","grant_type":"refresh_token"}`), reply(map[string]any{"access_token": "a", "refresh_token": "r"})},
|
||||
// Found by FuzzParseTokenRequest: devvm judged the first object, which the endpoint may not read.
|
||||
{"more after the JSON object", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code"}{"grant_type":"refresh_token"}`), reply(map[string]any{"access_token": "sk-ant-oat01-a", "refresh_token": "r", "scope": "user:inference"})},
|
||||
{"a Console login", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code"}`), reply(map[string]any{"access_token": "a", "refresh_token": "r", "scope": "org:create_api_key user:profile"})},
|
||||
{"a login that makes API keys", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code"}`), reply(map[string]any{"access_token": "sk-ant-oat01-a", "refresh_token": "r", "scope": "user:inference org:create_api_key"})},
|
||||
{"a refresh to a login that makes API keys", ClaudeOAuth, jsonType, []byte(`{"grant_type":"refresh_token","refresh_token":"r"}`), reply(map[string]any{"access_token": "sk-ant-oat01-a", "scope": "user:inference org:create_api_key"})},
|
||||
@@ -353,3 +355,139 @@ func TestPick(t *testing.T) {
|
||||
t.Errorf("Pick(nil) = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzParseTokenRequest: a token request is read only when it's a form (or has no type) or a JSON
|
||||
// object alone, in which no field is named twice, however its name is written; its fields are
|
||||
// then the form's, or the JSON object's strings and numbers as they're written.
|
||||
func FuzzParseTokenRequest(f *testing.F) {
|
||||
for _, s := range [][2]string{
|
||||
{formType, string(form("grant_type", grantCode, "code", "c"))},
|
||||
{"", "grant_type=refresh_token&refresh_token=r&grant_type=x"},
|
||||
{formType, "a=1;b=2"},
|
||||
{jsonType, `{"grant_type":"authorization_code","expires_in":3600,"x":{"y":1}}`},
|
||||
{jsonType, `{"grant_type":"a","grant_type":"b"}`},
|
||||
{jsonType, `{"grant_type":"a"}{"grant_type":"b"}`},
|
||||
{jsonType + "; charset=utf-8", `{"a":"1"} `},
|
||||
{"text/plain", "a=1"},
|
||||
} {
|
||||
f.Add(s[0], []byte(s[1]))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, ctype string, body []byte) {
|
||||
tr, err := parseTokenRequest(ctype, body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if tr.form {
|
||||
seen := map[string]bool{}
|
||||
for pair := range strings.SplitSeq(string(body), "&") {
|
||||
k, _, _ := strings.Cut(pair, "=")
|
||||
if k, err := url.QueryUnescape(k); err == nil && pair != "" {
|
||||
if seen[k] {
|
||||
t.Fatalf("a form naming %q twice read: %q", k, body)
|
||||
}
|
||||
seen[k] = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
var top map[string]json.RawMessage
|
||||
if !json.Valid(body) || json.Unmarshal(body, &top) != nil {
|
||||
t.Fatalf("a JSON request that isn't one object read: %q", body)
|
||||
}
|
||||
d := json.NewDecoder(strings.NewReader(string(body)))
|
||||
d.UseNumber()
|
||||
_, _ = d.Token()
|
||||
seen := map[string]bool{}
|
||||
for d.More() {
|
||||
k, _ := d.Token()
|
||||
name, _ := k.(string)
|
||||
var v any
|
||||
if seen[name] || d.Decode(&v) != nil {
|
||||
t.Fatalf("a JSON request naming %q twice read: %q", name, body)
|
||||
}
|
||||
seen[name] = true
|
||||
switch v := v.(type) {
|
||||
case string:
|
||||
if tr.fields.Get(name) != v {
|
||||
t.Fatalf("field %q read as %q, sent as %q", name, tr.fields.Get(name), v)
|
||||
}
|
||||
case json.Number:
|
||||
if tr.fields.Get(name) != v.String() {
|
||||
t.Fatalf("field %q read as %q, sent as %s", name, tr.fields.Get(name), v)
|
||||
}
|
||||
default:
|
||||
if tr.fields.Has(name) {
|
||||
t.Fatalf("field %q, neither a string nor a number, read as %q", name, tr.fields.Get(name))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// replyTokens are the fields of an endpoint's reply that hold a login's tokens, in every format.
|
||||
func replyTokens() []string {
|
||||
return []string{"access_token", "refresh_token", "id_token", "accessToken", "refreshToken"}
|
||||
}
|
||||
|
||||
// FuzzCapture: whatever an agent's endpoint replies to whatever token request, for every agent
|
||||
// whose login devvm captures, the VM's reply, when there is one, holds none of the reply's tokens,
|
||||
// only placeholders, and isn't anything but a JSON object; a reply that isn't captured leaves the
|
||||
// store as it was.
|
||||
//
|
||||
//nolint:gosec // a test's fake tokens
|
||||
func FuzzCapture(f *testing.F) {
|
||||
var kinds []string
|
||||
for k, ft := range formats() {
|
||||
if _, ok := ft.(captureFormat); ok {
|
||||
kinds = append(kinds, k)
|
||||
}
|
||||
}
|
||||
slices.Sort(kinds)
|
||||
idToken, accessToken := openaiTokens()
|
||||
code := form("grant_type", grantCode, "code", "c", "client_id", openaiClientID, "code_verifier", "v")
|
||||
for i := range kinds {
|
||||
f.Add(uint8(i), formType, code, reply(map[string]any{"id_token": idToken, "access_token": accessToken, "refresh_token": "rt-real-0123456789", "token_type": "Bearer"}))
|
||||
f.Add(uint8(i), jsonType, []byte(`{"grant_type":"authorization_code"}`), reply(map[string]any{"access_token": "sk-ant-oat01-real-0123456789", "refresh_token": "rt-real-0123456789", "scope": "user:inference"}))
|
||||
f.Add(uint8(i), jsonType, []byte(`{"grant_type":"refresh_token","refresh_token":"r"}`), reply(map[string]any{"accessToken": accessToken, "refreshToken": "rt-real-0123456789", "scope": "x"}))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, kind uint8, ctype string, req, rep []byte) {
|
||||
var r map[string]any
|
||||
if json.Unmarshal(rep, &r) != nil {
|
||||
return
|
||||
}
|
||||
var tokens []string
|
||||
for _, k := range replyTokens() {
|
||||
if s, ok := r[k].(string); ok && len(strings.TrimSpace(s)) >= 16 {
|
||||
tokens = append(tokens, strings.TrimSpace(s))
|
||||
}
|
||||
}
|
||||
fl := File{Kind: kinds[int(kind)%len(kinds)], Path: filepath.Join(t.TempDir(), "logins", "auth.json"), Salt: salt}
|
||||
out, err := fl.Capture(ctype, req, rep)
|
||||
if err != nil {
|
||||
if _, serr := os.Stat(fl.Path); !errors.Is(serr, os.ErrNotExist) {
|
||||
t.Fatalf("refused (%v), and the store was written", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
var vm map[string]any
|
||||
if err := json.Unmarshal(out, &vm); err != nil || vm == nil {
|
||||
t.Fatalf("the VM's reply isn't a JSON object: %q", out)
|
||||
}
|
||||
for _, tok := range tokens {
|
||||
if strings.Contains(string(out), tok) && !keptElsewhere(r, tok) {
|
||||
t.Fatalf("the VM's reply holds the token %q: %s", tok, out)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// keptElsewhere reports whether a field of r besides its tokens holds tok, which the VM's reply
|
||||
// may then have from it: its token type or scope.
|
||||
func keptElsewhere(r map[string]any, tok string) bool {
|
||||
for k, v := range r {
|
||||
if s, ok := v.(string); ok && !slices.Contains(replyTokens(), k) && strings.Contains(s, tok) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package agentlogin
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
@@ -274,3 +276,101 @@ func TestRedactJSON(t *testing.T) {
|
||||
t.Errorf("names = %q, want %q", names, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The secrets FuzzRedact plants: one of a known key's shape, and one that only where it is says
|
||||
// is a secret.
|
||||
const (
|
||||
plantedShape = "ghp_Zq8vX2mK9pL4wR7tY1nB3c"
|
||||
plantedPlain = "Zq8vX2mK9pL4wR7tY1nB"
|
||||
)
|
||||
|
||||
// plant puts a secret in the settings file m, below its keys k1 and k2, in the place how picks:
|
||||
// a known key's shape as a value and among other words, a URL's password and query, a value under
|
||||
// a secret-looking key, an env or headers table's value, and a flag's argument. It returns the
|
||||
// secret, and false when Redact keeps what it planted by design: one of Claude Code's own
|
||||
// settings in its top-level env (agentSetting).
|
||||
func plant(m map[string]any, k1, k2, key, around string, how uint8) (string, bool) {
|
||||
at := func(keys ...string) map[string]any {
|
||||
cur := m
|
||||
for _, k := range keys {
|
||||
next, ok := cur[k].(map[string]any)
|
||||
if !ok {
|
||||
next = map[string]any{}
|
||||
cur[k] = next
|
||||
}
|
||||
cur = next
|
||||
}
|
||||
return cur
|
||||
}
|
||||
switch how % 8 {
|
||||
case 0:
|
||||
at(k1, k2)[key] = plantedShape
|
||||
return plantedShape, true
|
||||
case 1:
|
||||
at(k1, k2)[key] = around + " " + plantedShape + " " + around
|
||||
return plantedShape, true
|
||||
case 2:
|
||||
at(k1, k2)[key] = "https://user:" + plantedPlain + "@proxy.example/x"
|
||||
return plantedPlain, true
|
||||
case 3:
|
||||
at(k1, k2)[key] = "https://h.example/p?" + url.QueryEscape(around) + "=" + plantedShape
|
||||
return plantedShape, true
|
||||
case 4:
|
||||
at(k1, k2)[key+"_token"] = plantedPlain
|
||||
return plantedPlain, true
|
||||
case 5:
|
||||
at(k1, "env")[key] = plantedPlain
|
||||
return plantedPlain, k1 != "" || !agentSetting("env."+key, key)
|
||||
case 6:
|
||||
at(k1, k2)["args"] = []any{"--api-key", plantedPlain}
|
||||
return plantedPlain, true
|
||||
default:
|
||||
at(k1, "headers")["Authorization"] = "Bearer " + plantedPlain
|
||||
return plantedPlain, true
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzRedact: no secret planted anywhere in an agent's settings file, JSON or TOML, survives into
|
||||
// the VM's copy, which is the format's own and reads back.
|
||||
func FuzzRedact(f *testing.F) {
|
||||
for i := range uint8(8) {
|
||||
f.Add(false, []byte(`{"mcp":{"m":{"command":"x","env":{"A":"b"}}},"model":"sonnet"}`), "mcp", "m", "TOKEN", "run it", i)
|
||||
f.Add(true, []byte("[mcp_servers.m]\ncommand = \"x\"\nargs = [\"-y\"]\n"), "mcp_servers", "m", "x", "", i)
|
||||
f.Add(false, []byte(`{}`), "", "", "CLAUDE_CODE_X", "Bearer", i)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, isTOML bool, doc []byte, k1, k2, key, around string, how uint8) {
|
||||
// A file that isn't UTF-8 is refused before Redact reads it.
|
||||
if strings.Contains(string(doc), plantedPlain) || strings.Contains(around, plantedPlain) || !utf8.ValidString(k1+k2+key+around) {
|
||||
return
|
||||
}
|
||||
format := "json"
|
||||
if isTOML {
|
||||
format = "toml"
|
||||
}
|
||||
m := tableOf(format, doc)
|
||||
secret, gone := plant(m, k1, k2, key, around, how)
|
||||
in, err := encode(format, m)
|
||||
if err != nil || !utf8.Valid(in) {
|
||||
return
|
||||
}
|
||||
out, _, err := Redact(format, in)
|
||||
if err != nil {
|
||||
t.Fatalf("Redact refused what it wrote itself: %v\n%s", err, in)
|
||||
}
|
||||
if gone && strings.Contains(string(out), secret) {
|
||||
t.Fatalf("the secret survived:\n%s\nfrom\n%s", out, in)
|
||||
}
|
||||
if _, err := decode(format, out); err != nil {
|
||||
t.Fatalf("the copy doesn't read back: %v\n%s", err, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// tableOf is the settings file doc as a table, or an empty one when it isn't one.
|
||||
func tableOf(format string, doc []byte) map[string]any {
|
||||
v, err := decode(format, doc)
|
||||
if m, ok := v.(map[string]any); err == nil && ok {
|
||||
return m
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
@@ -268,3 +269,61 @@ func TestRelayVMAsksForPassword(t *testing.T) {
|
||||
t.Errorf("result %d %q", res, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// scriptedVM is the VM's side of its server's handshake, as FuzzHandshakeVM plays it: what it
|
||||
// says, and what the relay wrote to it.
|
||||
type scriptedVM struct {
|
||||
says *bytes.Reader
|
||||
wrote bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *scriptedVM) Read(p []byte) (int, error) { return s.says.Read(p) }
|
||||
func (s *scriptedVM) Write(p []byte) (int, error) { return s.wrote.Write(p) }
|
||||
|
||||
// FuzzHandshakeVM: whatever the VM's server says, the relay's handshake with it succeeds only for
|
||||
// version 3.8 or later, a list of security types that has None, and an OK result, reading no more
|
||||
// than those; it writes only version 3.8, then None, and None only from a list that has it; and
|
||||
// its error, which goes in the log, stays short.
|
||||
func FuzzHandshakeVM(f *testing.F) {
|
||||
ok := func(version string, types ...byte) []byte {
|
||||
b := append([]byte(version), byte(len(types))) //nolint:gosec // G115: a seed's few types
|
||||
return binary.BigEndian.AppendUint32(append(b, types...), resultOK)
|
||||
}
|
||||
f.Add(ok("RFB 003.008\n", secNone))
|
||||
f.Add(ok("RFB 003.889\n", secVncAuth, secNone))
|
||||
f.Add(ok("RFB 003.007\n", secNone))
|
||||
f.Add(ok("RFB 003.008\n", secVncAuth))
|
||||
f.Add(ok("RFB 003.008\n"))
|
||||
f.Add([]byte("RFB 003.008\n\x01\x01\x00\x00\x00\x01"))
|
||||
f.Add([]byte("HTTP/1.1 200"))
|
||||
f.Fuzz(func(t *testing.T, says []byte) {
|
||||
vm := &scriptedVM{says: bytes.NewReader(says)}
|
||||
err := handshakeVM(vm)
|
||||
read := len(says) - vm.says.Len()
|
||||
const hello = "RFB 003.008\n"
|
||||
w := vm.wrote.String()
|
||||
if w != "" && w != hello && w != hello+string([]byte{secNone}) {
|
||||
t.Fatalf("wrote %q", w)
|
||||
}
|
||||
if err != nil {
|
||||
if len(err.Error()) > 2048 { // at most 255 types, a number each
|
||||
t.Fatalf("an error of %d bytes", len(err.Error()))
|
||||
}
|
||||
if w == hello+string([]byte{secNone}) && !bytes.Contains(says[min(13, len(says)):min(read, len(says))], []byte{secNone}) {
|
||||
t.Fatalf("chose None from a list without it: %q", says[:read])
|
||||
}
|
||||
return
|
||||
}
|
||||
var major, minor int
|
||||
n := int(says[12])
|
||||
_, serr := fmt.Sscanf(string(says[:12]), "RFB %03d.%03d\n", &major, &minor)
|
||||
switch {
|
||||
case serr != nil || major != 3 || minor < 8:
|
||||
t.Fatalf("took the version %q", says[:12])
|
||||
case read != 12+1+n+4 || n == 0 || !bytes.Contains(says[13:13+n], []byte{secNone}):
|
||||
t.Fatalf("took %q, reading %d bytes", says, read)
|
||||
case binary.BigEndian.Uint32(says[13+n:]) != resultOK || w != hello+string([]byte{secNone}):
|
||||
t.Fatalf("took %q, writing %q", says, w)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
package jsonc
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStrip(t *testing.T) {
|
||||
for _, tc := range []struct{ name, in, want string }{
|
||||
@@ -25,3 +31,86 @@ func TestStrip(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// withComments is the JSON in, indented a value a line, with a comment after each line marks
|
||||
// says (a line's, or a block's) and a trailing comma before each } or ] that ends an object or a
|
||||
// list, and a byte order mark first with bom.
|
||||
func withComments(in []byte, comment string, marks []byte, bom bool) []byte {
|
||||
var b bytes.Buffer
|
||||
if json.Indent(&b, in, "", " ") != nil {
|
||||
return nil
|
||||
}
|
||||
lines := strings.Split(b.String(), "\n")
|
||||
var out strings.Builder
|
||||
if bom {
|
||||
out.WriteString("\xef\xbb\xbf")
|
||||
}
|
||||
for i, l := range lines {
|
||||
out.WriteString(l)
|
||||
if i+1 < len(lines) {
|
||||
next := strings.TrimSpace(lines[i+1])
|
||||
if l != "" && !strings.HasSuffix(l, "{") && !strings.HasSuffix(l, "[") && (strings.HasPrefix(next, "}") || strings.HasPrefix(next, "]")) {
|
||||
out.WriteString(",")
|
||||
}
|
||||
}
|
||||
var m byte
|
||||
if i < len(marks) {
|
||||
m = marks[i]
|
||||
}
|
||||
switch {
|
||||
case m%3 == 1 && !strings.ContainsAny(comment, "\r\n"):
|
||||
out.WriteString(" //" + comment)
|
||||
case m%3 == 2 && !strings.Contains(comment, "*/"):
|
||||
out.WriteString(" /*" + comment + "*/")
|
||||
}
|
||||
if i+1 < len(lines) {
|
||||
out.WriteString("\n")
|
||||
}
|
||||
}
|
||||
return []byte(out.String())
|
||||
}
|
||||
|
||||
// decoded is b as encoding/json reads it, its numbers as written.
|
||||
func decoded(b []byte) (any, error) {
|
||||
d := json.NewDecoder(bytes.NewReader(b))
|
||||
d.UseNumber()
|
||||
var v any
|
||||
err := d.Decode(&v)
|
||||
return v, err
|
||||
}
|
||||
|
||||
// FuzzStrip: Strip keeps every offset, blanking bytes with spaces but newlines; leaves JSON as it
|
||||
// is; and, against encoding/json, makes JSON with comments, trailing commas and a byte order mark
|
||||
// the value the JSON without them is.
|
||||
func FuzzStrip(f *testing.F) {
|
||||
for _, s := range []string{`{"a": [1, 2], "b": {"c": "//x/*y*/\""}}`, `[]`, `"s"`, `{"a":{"b":[{"c":null}]}}`, "{} /* x", `{"a":1,}`} {
|
||||
f.Add([]byte(s), "c", []byte{1, 2, 0, 1}, false)
|
||||
f.Add([]byte(s), "a\"b*", []byte{2, 2, 2}, true)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, data []byte, comment string, marks []byte, bom bool) {
|
||||
got := Strip(data)
|
||||
if len(got) != len(data) {
|
||||
t.Fatalf("Strip(%q) = %q: another length", data, got)
|
||||
}
|
||||
for i := range data {
|
||||
if got[i] != data[i] && (got[i] != ' ' || data[i] == '\n' || data[i] == '\r') {
|
||||
t.Fatalf("Strip(%q) = %q: byte %d", data, got, i)
|
||||
}
|
||||
}
|
||||
if !json.Valid(data) {
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(got, data) {
|
||||
t.Fatalf("Strip(%q) = %q: JSON changed", data, got)
|
||||
}
|
||||
in := withComments(data, comment, marks, bom)
|
||||
want, err := decoded(data)
|
||||
if err != nil || in == nil {
|
||||
t.Fatalf("%q: %v", data, err)
|
||||
}
|
||||
v, err := decoded(Strip(in))
|
||||
if err != nil || !reflect.DeepEqual(v, want) {
|
||||
t.Fatalf("Strip(%q) reads as %v, %v; want %v", in, v, err, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -49,7 +49,7 @@ Once it listens, it says so with the address it listens on (`daemon.Ready`) in t
|
||||
| `nixcache.go` | `nix_cache`: the shared Nix cache at `http://devvm.proxy/nix/` (`nixCache`), its path pattern (`nixPath`), narinfo checks (`parseNarinfo`), NAR checks, the cap and its trim (`NixCacheUsage`, `TrimNixCache`) |
|
||||
| `agent.go` | the SSH agent's relay (`agentRelay`): its socket (`listenAgent`), the requests it passes on (`agentAllowed`), and the agent protocol's messages, read and written whole (`readAgentMsg`, `writeAgentMsg`) |
|
||||
| `links.go` | `links`: the VM's links' list (`LinkList`, `LinkEntry`) and the proxy's way to them (`links`), their sockets' names (`LinkSocket`, `LinkHash`), their addresses and domain, which devvm's other packages use too (`IsLinkAddr`, `LinkAddr`, `LinkDomain`), matching (`links.find`), `CONNECT` and absolute-form requests to a link |
|
||||
| `*_test.go` | unit tests, and fuzz targets for policy rules (`FuzzParseRule`), request targets (`FuzzRequest`), a deny's path and method however a request spells them (`FuzzDenyBypass`), ClientHellos (`FuzzClientHello`), a transparent connection's first bytes (`FuzzTransparent`) and the Nix cache's paths (`FuzzNixPath`); `testdata/nix/` holds a narinfo and its NAR from cache.nixos.org |
|
||||
| `*_test.go` | unit tests, and fuzz targets for policy rules (`FuzzParseRule`), request targets (`FuzzRequest`), a deny's path and method however a request spells them (`FuzzDenyBypass`), ClientHellos (`FuzzClientHello`), a transparent connection's first bytes (`FuzzTransparent`), the Nix cache's paths (`FuzzNixPath`) and narinfos (`FuzzParseNarinfo`), every reader of a host (`FuzzHostSites`), Cursor's replies (`FuzzCursorFrames`), where a binding's value goes (`FuzzInject`), the bindings file (`FuzzParseBindings`), the links list (`FuzzLinkList`), the company proxy's URL (`FuzzParseUpstream`) and `NO_PROXY` (`FuzzNoProxy`), each with the property it checks in [Fuzzing](../../docs/content/docs/contributing/testing.md#fuzzing); `testdata/nix/` holds a narinfo and its NAR from cache.nixos.org, and `testdata/fuzz/` the inputs that failed a target once |
|
||||
|
||||
## How devvm runs it
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
|
||||
// frame is one enveloped message as Connect and gRPC send them: flags, a big-endian length and
|
||||
// the message, gzipped first when its flags say so.
|
||||
func frame(t *testing.T, flags byte, msg string) []byte {
|
||||
func frame(t testing.TB, flags byte, msg string) []byte {
|
||||
t.Helper()
|
||||
data := []byte(msg)
|
||||
if flags&frameCompressed != 0 {
|
||||
@@ -80,7 +81,9 @@ func TestCursorStreams(t *testing.T) {
|
||||
body []byte
|
||||
header []string
|
||||
}{
|
||||
"a token, compressed": {append(append([]byte{}, first...), frame(t, frameCompressed, cursorJWT)...), nil},
|
||||
"a token, compressed": {append(append([]byte{}, first...), frame(t, frameCompressed, cursorJWT)...), nil},
|
||||
// Text that deflate codes, so the token's bytes aren't in the message as it came.
|
||||
"a token, deflated": {append(append([]byte{}, first...), frame(t, frameCompressed, strings.Repeat("hello world ", 50)+cursorJWT)...), nil},
|
||||
"a token, plain": {append(append([]byte{}, first...), frame(t, 0, cursorJWT)...), nil},
|
||||
"a token at the end": {append(append([]byte{}, first...), frame(t, frameEnd, `{"metadata":{"t":["`+cursorJWT[2:54]+`"]}}`)...), nil},
|
||||
"a token at the end, escaped": {append(append([]byte{}, first...), frame(t, frameEnd|frameCompressed, `{"error":{"message":"eyJ`+cursorJWT[5:54]+`"}}`)...), nil},
|
||||
@@ -139,3 +142,131 @@ func TestCursorStreams(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzCursorFrames: a reply from a Cursor host, of any type, encodings, body and trailers, read
|
||||
// in reads of any size, passes only what came, from its start, or is refused before any of it. A
|
||||
// stream passes whole messages alone, none over frameMax, compressed or as it decompresses, and
|
||||
// none holding a JWT's start once decompressed and, in JSON, with its escapes undone; any other
|
||||
// body passes no JWT's start of up to jwtWindow bytes; and a trailer holding one never lets the
|
||||
// body end cleanly.
|
||||
func FuzzCursorFrames(f *testing.F) {
|
||||
const connect, grpc = "application/connect+proto", "application/grpc"
|
||||
hello, end := frame(f, frameCompressed, "\x0a\x05hello"), frame(f, frameEnd, `{"metadata":{"x":["1"]}}`)
|
||||
clean := bytes.Join([][]byte{hello, frame(f, 0, "\x12\x02ok"), end}, nil)
|
||||
// A message that decompresses to one byte past frameMax: a gzip bomb, small as it comes.
|
||||
bomb := frame(f, frameCompressed, strings.Repeat("\x00", frameMax+1))
|
||||
for _, s := range []struct {
|
||||
ctype, cenc, genc, trailer string
|
||||
body []byte
|
||||
}{
|
||||
{connect, "gzip", "", "", clean},
|
||||
{grpc, "", "gzip", "", clean[:len(clean)-len(end)]},
|
||||
{grpc, "", "", cursorJWT, frame(f, 0, "\x0a\x02hi")},
|
||||
{connect, "gzip", "", "", append(bytes.Clone(hello), frame(f, frameCompressed, cursorJWT)...)},
|
||||
{"application/connect+json", "", "", "", append(frame(f, 0, `{"a":"eyJ`+cursorJWT[5:54]+`"}`), frame(f, frameEnd, `{}`)...)},
|
||||
{connect, "gzip", "", "", bomb},
|
||||
{connect, "gzip", "", "", frame(f, frameCompressed, strings.Repeat("hello world ", 50)+cursorJWT)},
|
||||
{connect, "identity", "", "", append(bytes.Clone(hello), 0, 0xff, 0xff, 0xff, 0xff)},
|
||||
{"application/proto", "", "", "", []byte(strings.Repeat("x", 100) + cursorJWT)},
|
||||
{"application/json", "", "", "", []byte(`{"token":"` + cursorJWT[2:54] + `"}`)},
|
||||
} {
|
||||
f.Add(s.ctype, s.cenc, s.genc, s.trailer, s.body, uint16(1))
|
||||
f.Add(s.ctype, s.cenc, s.genc, s.trailer, s.body, uint16(4096))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, ctype, cenc, genc, trailer string, body []byte, chunk uint16) {
|
||||
resp := stream(body)
|
||||
for k, v := range map[string]string{"Content-Type": ctype, "Connect-Content-Encoding": cenc, "Grpc-Encoding": genc} {
|
||||
if v != "" {
|
||||
resp.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
s := &server{captures: newCaptures(nil, nil)}
|
||||
if s.cursorReply(resp) != nil {
|
||||
return // refused, before any of it
|
||||
}
|
||||
// Trailers come once the body ends.
|
||||
resp.Trailer.Set("X-Trailer", trailer)
|
||||
got, err := readIn(resp.Body, int(chunk)%(64<<10)+1)
|
||||
_ = resp.Body.Close()
|
||||
switch {
|
||||
case !bytes.HasPrefix(body, got):
|
||||
t.Fatalf("passed %q, which isn't the start of %q", got, body)
|
||||
case err == nil && jwtStart.MatchString(trailer):
|
||||
t.Fatalf("a trailer holding a JWT's start, %q, and the body ended cleanly", trailer)
|
||||
}
|
||||
kind, isJSON := streamKind(ctype)
|
||||
if kind == "" {
|
||||
for _, m := range jwtStart.FindAllIndex(got, -1) {
|
||||
if m[1]-m[0] <= jwtWindow {
|
||||
t.Fatalf("a JWT's start passed: %q", got[m[0]:m[1]])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
checkFrames(t, got, kind == "grpc", isJSON)
|
||||
})
|
||||
}
|
||||
|
||||
// readIn reads r whole in reads of size n, returning what came before any error but io.EOF.
|
||||
func readIn(r io.Reader, n int) ([]byte, error) {
|
||||
var out []byte
|
||||
buf := make([]byte, n)
|
||||
for {
|
||||
k, err := r.Read(buf)
|
||||
out = append(out, buf[:k]...)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return out, nil
|
||||
}
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkFrames reads the messages a stream passed, b, apart again, as a client would: each one
|
||||
// whole, of a flag the stream's protocol has, at most frameMax as it came and as it decompresses,
|
||||
// and without a JWT's start, also, for one in JSON (the stream's every message, or Connect's end),
|
||||
// once its escapes are undone.
|
||||
func checkFrames(t *testing.T, b []byte, grpc, isJSON bool) {
|
||||
t.Helper()
|
||||
known := byte(frameCompressed)
|
||||
if !grpc {
|
||||
known |= frameEnd
|
||||
}
|
||||
for len(b) > 0 {
|
||||
if len(b) < 5 {
|
||||
t.Fatalf("an envelope cut off passed: %q", b)
|
||||
}
|
||||
flags, size := b[0], binary.BigEndian.Uint32(b[1:5])
|
||||
if flags&^known != 0 || size > frameMax || len(b)-5 < int(size) {
|
||||
t.Fatalf("a message flagged %#x of %d bytes passed, with %d left", flags, size, len(b)-5)
|
||||
}
|
||||
plain := b[5 : 5+size]
|
||||
b = b[5+size:]
|
||||
if flags&frameCompressed != 0 {
|
||||
zr, err := gzip.NewReader(bytes.NewReader(plain))
|
||||
if err != nil {
|
||||
t.Fatalf("a compressed message that isn't gzip passed: %v", err)
|
||||
}
|
||||
if plain, err = io.ReadAll(io.LimitReader(zr, frameMax+1)); err != nil || len(plain) > frameMax {
|
||||
t.Fatalf("a compressed message passed that decompresses to %d bytes: %v", len(plain), err)
|
||||
}
|
||||
}
|
||||
if jwtStart.Match(plain) {
|
||||
t.Fatalf("a message holding a JWT's start passed: %q", plain)
|
||||
}
|
||||
if !isJSON && (grpc || flags&frameEnd == 0) {
|
||||
continue
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(plain, &v); err != nil {
|
||||
t.Fatalf("a JSON message that isn't JSON passed: %q", plain)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
e := json.NewEncoder(&out)
|
||||
e.SetEscapeHTML(false)
|
||||
if err := e.Encode(v); err != nil || jwtStart.Match(out.Bytes()) {
|
||||
t.Fatalf("a JSON message holding a JWT's start passed: %q (%v)", out.Bytes(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,11 +357,23 @@ func sniSites(t *testing.T, sni, other string) {
|
||||
// noProxySite: NO_PROXY's entries and the hosts they send directly. Divergence: an entry with
|
||||
// anything but printable ASCII isn't folded, where strings.ToLower folded it in Unicode, so it
|
||||
// matches no host the proxy takes (the Kelvin sign's kubernetes.io no longer matches
|
||||
// kubernetes.io). An entry of dots alone is no entry, as "" and "." weren't.
|
||||
// kubernetes.io). An entry of dots alone is no entry, as "" and "." weren't. An entry with a port
|
||||
// no request has (0, or past 65535), or one not in plain decimal (080, +80), is no entry, where
|
||||
// port 0 was read as every port and 080 as 80.
|
||||
func noProxySite(t *testing.T, entry, other string) {
|
||||
entry = strings.ReplaceAll(entry, ",", "") // one entry
|
||||
list := entry + ",*." + entry + ",." + entry
|
||||
rs, lrs := parseNoProxy(list), slices.DeleteFunc(legacyParseNoProxy(list), func(r noProxyRule) bool {
|
||||
var kept []string
|
||||
for e := range strings.SplitSeq(list, ",") {
|
||||
e = strings.ToLower(strings.TrimSpace(e))
|
||||
_, perr := netip.ParsePrefix(e)
|
||||
_, p, err := net.SplitHostPort(e)
|
||||
n, nerr := strconv.Atoi(p)
|
||||
if perr == nil || err != nil || nerr != nil || n >= 1 && n <= 65535 && strconv.Itoa(n) == p {
|
||||
kept = append(kept, e)
|
||||
}
|
||||
}
|
||||
rs, lrs := parseNoProxy(list), slices.DeleteFunc(legacyParseNoProxy(strings.Join(kept, ",")), func(r noProxyRule) bool {
|
||||
return !r.all && !r.prefix.IsValid() && strings.Trim(r.name, ".") == ""
|
||||
})
|
||||
var hosts []string
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -438,3 +439,50 @@ func TestLinkSocket(t *testing.T) {
|
||||
t.Error("the parts aren't kept apart")
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzLinkList: a links list is read only at LinkListVersion, and of what's read, a host and port
|
||||
// find only an entry that names them, at a link's address in 127.77.0.0/16 written as netip
|
||||
// writes it, on a port that is one, whose socket is this VM's link's for that address and port.
|
||||
func FuzzLinkList(f *testing.F) {
|
||||
const dir = "/run/devvm"
|
||||
good := func(addr string, port int, hosts ...string) []byte {
|
||||
b, _ := json.Marshal(LinkList{Version: LinkListVersion, Links: []LinkEntry{linkEntry(dir, addr, port, hosts...)}})
|
||||
return b
|
||||
}
|
||||
f.Add(good("127.77.0.1", 5432, "db", "db.devvm.internal"), "db", 5432)
|
||||
f.Add(good("127.77.0.1", 5432, "db"), "db", 5433)
|
||||
f.Add(good("127.0.0.1", 5432, "db"), "db", 5432)
|
||||
f.Add(good("::ffff:127.77.0.1", 443, "db"), "db", 443)
|
||||
f.Add([]byte(`{"version":1,"links":[{"hosts":["db"],"addr":"127.77.0.1","port":5432,"socket":"/tmp/x.sock"}]}`), "db", 5432)
|
||||
f.Add([]byte(`{"version":2,"links":[]}`), "db", 1)
|
||||
f.Add([]byte(`{"version":1,"links":null}`), "", 0)
|
||||
f.Fuzz(func(t *testing.T, b []byte, host string, port int) {
|
||||
l, err := parseLinkList("links.json", b)
|
||||
if err != nil {
|
||||
if l.Version != 0 || l.Links != nil {
|
||||
t.Fatalf("refused with links: %+v", l)
|
||||
}
|
||||
return
|
||||
}
|
||||
if l.Version != LinkListVersion {
|
||||
t.Fatalf("read a list of version %d", l.Version)
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "links.json")
|
||||
must(t, os.WriteFile(file, b, 0o600))
|
||||
e, ok := newLinks(file, dir, linkVM, quiet(), nil).find(host, port)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a, err := netip.ParseAddr(e.Addr)
|
||||
switch {
|
||||
case e.Port != port || !slices.Contains(e.Hosts, host):
|
||||
t.Fatalf("%s:%d found %+v", host, port, e)
|
||||
case err != nil || a.String() != e.Addr || !a.Is4() || a.As4()[0] != 127 || a.As4()[1] != 77:
|
||||
t.Fatalf("%s:%d found a link at %q", host, port, e.Addr)
|
||||
case port < 1 || port > 65535:
|
||||
t.Fatalf("found a link on port %d", port)
|
||||
case e.Socket != LinkSocket(dir, linkVM, a, port):
|
||||
t.Fatalf("%s:%d found a link at socket %q", host, port, e.Socket)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -476,3 +478,40 @@ func FuzzNixPath(f *testing.F) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzParseNarinfo: a narinfo the proxy takes, from the cache or anything between, is one
|
||||
// cache.nixos.org-1 signed, of the path asked for: what the signature covers (its store path,
|
||||
// NarHash, NarSize and references) is the fixture's, the only signed one the fuzzer has, and what it
|
||||
// doesn't is held to its forms: a NAR's URL named by its NarHash or FileHash, and sizes from 1 byte
|
||||
// to 1 TiB.
|
||||
func FuzzParseNarinfo(f *testing.F) {
|
||||
good, err := os.ReadFile(filepath.Join("testdata", "nix", fixHash+".narinfo"))
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
want, err := parseNarinfo(good, fixHash)
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
f.Add(good, fixHash)
|
||||
f.Add(good, "0p7ahb9j02av0zx4hqmwqdpbdas9i25q")
|
||||
f.Add(append(bytes.Clone(good), "FileSize: 1\n"...), fixHash)
|
||||
f.Add([]byte(strings.Replace(string(good), "URL: nar/0p7", "URL: nar/1jrm0rjd3i5vxv2sjm6zgqqi87ikb3fjqg3myg7wj0x4q5psb550.nar.zst\nX: ", 1)), fixHash)
|
||||
f.Add([]byte(strings.Replace(string(good), "References: ", "References: 00000000000000000000000000000000-evil ", 1)), fixHash)
|
||||
f.Fuzz(func(t *testing.T, data []byte, hash string) {
|
||||
ni, err := parseNarinfo(data, hash)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
refs := slices.Sorted(slices.Values(ni.refs))
|
||||
switch {
|
||||
case hash != fixHash || ni.storePath != want.storePath || ni.narHash != want.narHash || ni.narSize != want.narSize ||
|
||||
!slices.Equal(refs, slices.Sorted(slices.Values(want.refs))):
|
||||
t.Fatalf("took a narinfo no one signed, for %q: %+v", hash, ni)
|
||||
case nixPath(ni.url) != nixNar || ni.url[4:56] != ni.narHash[7:] && ni.url[4:56] != ni.fileHash[7:]:
|
||||
t.Fatalf("took a NAR's URL %q", ni.url)
|
||||
case ni.fileSize < 1 || ni.fileSize > 1<<40 || ni.narSize < 1 || ni.narSize > 1<<40:
|
||||
t.Fatalf("took sizes %d and %d", ni.fileSize, ni.narSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -1215,3 +1217,245 @@ func TestMintsCredential(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fuzzBound is a binding FuzzInject's proxy has, its value, and the hosts it may go to, judged
|
||||
// apart from the policy's rules: each a host in NormHost's form, or a suffix after a *.
|
||||
type fuzzBound struct {
|
||||
b Binding
|
||||
value string
|
||||
to func(h Host) bool
|
||||
}
|
||||
|
||||
func fuzzBindings() []fuzzBound {
|
||||
exact := func(name string) func(Host) bool { return func(h Host) bool { return h.String() == name } }
|
||||
return []fuzzBound{
|
||||
{
|
||||
Binding{Name: "gh", Kind: KindSecret, Hosts: []string{"api.github.com"}, Header: "Authorization", Placeholder: "devvm-ph-gh-1f2e"},
|
||||
"VALgh0q7Zx", exact("api.github.com"),
|
||||
},
|
||||
{
|
||||
Binding{Name: "svc", Kind: KindSecret, Hosts: []string{"*.svc.example"}, Header: "X-Api-Key", Placeholder: "devvm-ph-svc-3c4d"},
|
||||
"VALsvc8w2Ky", func(h Host) bool { return strings.HasSuffix(h.String(), ".svc.example") },
|
||||
},
|
||||
{
|
||||
Binding{Name: "stripe", Kind: KindSecret, Hosts: []string{"api.stripe.com"}, Header: "Authorization", Placeholder: "devvm-ph-st-5a6b", Scheme: "ApiKey", BasicUser: true},
|
||||
"VALst4n6Jv", exact("api.stripe.com"),
|
||||
},
|
||||
{
|
||||
Binding{Name: "codex", Kind: KindLogin, Agent: "codex", Hosts: []string{"chatgpt.com"}, Header: "Authorization", Placeholder: "devvm-ph-cx-7e8f"},
|
||||
"VALcx1m3Hp", exact("chatgpt.com"),
|
||||
},
|
||||
{
|
||||
Binding{Name: "or", Kind: KindSecret, Hosts: []string{"openrouter.ai"}, Path: "/api/", Methods: "POST", Header: "Authorization", Placeholder: "devvm-ph-or-9a0b"},
|
||||
"VALor5r9Lt", exact("openrouter.ai"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// fuzzHeaders reads FuzzInject's headers, a "Name: value" a line.
|
||||
func fuzzHeaders(s string) http.Header {
|
||||
h := http.Header{}
|
||||
for line := range strings.SplitSeq(s, "\n") {
|
||||
if k, v, ok := strings.Cut(line, ":"); ok {
|
||||
h.Add(k, strings.TrimPrefix(v, " "))
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// holdsText reports whether the header value v holds s, as it is or inside Basic credentials,
|
||||
// read leniently: padded, unpadded or with spaces around them.
|
||||
func holdsText(v, s string) bool {
|
||||
if strings.Contains(v, s) {
|
||||
return true
|
||||
}
|
||||
if len(v) < 6 || !strings.EqualFold(v[:6], "basic ") {
|
||||
return false
|
||||
}
|
||||
rest := strings.TrimSpace(v[6:])
|
||||
for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding} {
|
||||
if raw, err := enc.DecodeString(rest); err == nil && strings.Contains(string(raw), s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// FuzzInject: whatever a request's host, method, path and headers, each binding's value goes in
|
||||
// only to a host the binding names, for a request its path and methods allow, in its own header
|
||||
// alone, which held its exact placeholder in exactly one of its values, once; every other header
|
||||
// stays as it came, and the secrets inject says it put in are the ones that went in.
|
||||
func FuzzInject(f *testing.F) {
|
||||
bound := fuzzBindings()
|
||||
file := filepath.Join(f.TempDir(), "bindings.json")
|
||||
var bs []Binding
|
||||
for _, fb := range bound {
|
||||
bs = append(bs, fb.b)
|
||||
}
|
||||
if err := os.WriteFile(file, BindingList{Bindings: bs}.Encode(), 0o600); err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
enc := func(s string) string { return "Basic " + base64.StdEncoding.EncodeToString([]byte(s)) }
|
||||
for _, h := range append(hostSeeds(), "api.github.com", "API.GitHub.com.", "x.svc.example", "svc.example", "api.stripe.com", "chatgpt.com", "openrouter.ai") {
|
||||
f.Add(h, "GET", "/", "Authorization: token devvm-ph-gh-1f2e\nX-Api-Key: devvm-ph-svc-3c4d\nX-Echo: devvm-ph-gh-1f2e")
|
||||
}
|
||||
for _, s := range [][3]string{
|
||||
{"api.stripe.com", "GET", "Authorization: " + enc("devvm-ph-st-5a6b:")},
|
||||
{"api.stripe.com", "GET", "Authorization: ApiKey devvm-ph-st-5a6b"},
|
||||
{"api.github.com", "GET", "Authorization: " + enc("x-access-token:devvm-ph-gh-1f2e")},
|
||||
{"api.github.com", "GET", "Authorization: xx devvm-ph-gh-1f2e\nAuthorization: token devvm-ph-gh-1f2e"},
|
||||
{"chatgpt.com", "GET", "Authorization: Bearer devvm-ph-cx-7e8f"},
|
||||
{"chatgpt.com", "GET", "Authorization: Bearer devvm-ph-cx-7e8f\nAuthorization: Bearer devvm-ph-cx-7e8f"},
|
||||
{"openrouter.ai", "POST", "Authorization: Bearer devvm-ph-or-9a0b\nX-HTTP-Method-Override: DELETE"},
|
||||
} {
|
||||
f.Add(s[0], s[1], "/api/v1/chat", s[2])
|
||||
f.Add(s[0], s[1], "/api/../settings", s[2])
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, host, method, p, headers string) {
|
||||
in := fuzzHeaders(headers)
|
||||
for _, fb := range bound {
|
||||
for _, vs := range in {
|
||||
if slices.ContainsFunc(vs, func(v string) bool { return holdsText(v, fb.value) }) {
|
||||
return // a value the request already holds: nothing to tell apart
|
||||
}
|
||||
}
|
||||
}
|
||||
s := newSecrets(file, nil, quiet())
|
||||
s.lookup = func(_ context.Context, b Binding) (redact.Secret, error) {
|
||||
for _, fb := range bound {
|
||||
if fb.b.Name == b.Name {
|
||||
return redact.NewSecret(fb.value), nil
|
||||
}
|
||||
}
|
||||
return redact.Secret{}, errors.New("no such binding")
|
||||
}
|
||||
r := &http.Request{Method: method, URL: &url.URL{Path: p}, Header: in.Clone()}
|
||||
used := s.inject(t.Context(), r.Header, s.forRequest(host, r))
|
||||
headersOf := map[string]bool{}
|
||||
for _, fb := range bound {
|
||||
headersOf[http.CanonicalHeaderKey(fb.b.Header)] = true
|
||||
}
|
||||
for k, vs := range r.Header {
|
||||
if !headersOf[k] && !slices.Equal(vs, in[k]) {
|
||||
t.Fatalf("header %q, bound to no secret, changed: %q, was %q", k, vs, in[k])
|
||||
}
|
||||
}
|
||||
for _, fb := range bound {
|
||||
checkInjected(t, fb, host, r, in, slices.Contains(used, fb.b.Name))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// checkInjected checks where fb's value went in r, the request as it goes out of in's headers,
|
||||
// to host, and that inject said it put it in (said) exactly when it did.
|
||||
func checkInjected(t *testing.T, fb fuzzBound, host string, r *http.Request, in http.Header, said bool) {
|
||||
t.Helper()
|
||||
b := fb.b
|
||||
n := 0
|
||||
for k, vs := range r.Header {
|
||||
for _, v := range vs {
|
||||
if !holdsText(v, fb.value) {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if k != http.CanonicalHeaderKey(b.Header) {
|
||||
t.Fatalf("%s's value went in header %q", b.Name, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
if said {
|
||||
t.Fatalf("inject said %s went in, and it didn't", b.Name)
|
||||
}
|
||||
return
|
||||
}
|
||||
held := 0
|
||||
for _, v := range in.Values(b.Header) {
|
||||
if holdsText(v, b.Placeholder) {
|
||||
held++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case !said:
|
||||
t.Fatalf("%s's value went in, and inject didn't say so", b.Name)
|
||||
case n > 1:
|
||||
t.Fatalf("%s's value went in %d times", b.Name, n)
|
||||
case held != 1:
|
||||
t.Fatalf("%s's value went in, for %d of its header's values holding its placeholder", b.Name, held)
|
||||
case !fb.to(NormHost(host)):
|
||||
t.Fatalf("%s's value went to %q", b.Name, host)
|
||||
case b.Methods != "" && (r.Method != b.Methods || overridden(r.Header, b.Methods)):
|
||||
t.Fatalf("%s's value went in a %q request, its headers %q", b.Name, r.Method, r.Header)
|
||||
case b.Path != "" && (!strings.HasPrefix(r.URL.Path, b.Path) || !plainFuzzPath(r.URL.Path)):
|
||||
t.Fatalf("%s's value went in a request for %q", b.Name, r.URL.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// overridden reports whether h says, in a method override header, a method other than method.
|
||||
func overridden(h http.Header, method string) bool {
|
||||
for _, k := range []string{"X-HTTP-Method-Override", "X-HTTP-Method", "X-Method-Override"} {
|
||||
if slices.ContainsFunc(h.Values(k), func(v string) bool { return v != method }) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// plainFuzzPath reports whether p is a path every server reads as itself: no escape, \ or ;, and
|
||||
// already clean (a trailing / kept).
|
||||
func plainFuzzPath(p string) bool {
|
||||
clean := path.Clean(p)
|
||||
if strings.HasSuffix(p, "/") && clean != "/" {
|
||||
clean += "/"
|
||||
}
|
||||
return !strings.ContainsAny(p, `%\;`) && clean == p
|
||||
}
|
||||
|
||||
// FuzzParseBindings: a bindings file is read only when it's a version the proxy knows, each
|
||||
// binding of a kind it knows, with a path, methods and scheme it takes, and none of version 1
|
||||
// that a proxy of that version reads otherwise; one that's read reads back as itself from what
|
||||
// Encode writes of it.
|
||||
func FuzzParseBindings(f *testing.F) {
|
||||
var bs []Binding
|
||||
for _, fb := range fuzzBindings() {
|
||||
bs = append(bs, fb.b)
|
||||
f.Add(BindingList{Bindings: []Binding{fb.b}}.Encode())
|
||||
}
|
||||
f.Add(BindingList{Bindings: bs}.Encode())
|
||||
for _, s := range []string{
|
||||
`{"version":1,"bindings":[{"name":"or","kind":"login","agent":"pi","hosts":["openrouter.ai"],"path":"/api/","header":"Authorization","placeholder":"PH"}]}`,
|
||||
`{"version":1,"bindings":[{"name":"x","kind":"login","methods":"GET"}]}`,
|
||||
`{"version":2,"bindings":[{"name":"x","kind":"secret","path":"/a**/","scheme":"Basic"}]}`,
|
||||
`{"version":2,"bindings":[{"name":"x","kind":"secret","methods":"head,get","Kind":"env"}]}`,
|
||||
`{"version":3,"bindings":[]}`, `[]`, `null`, `{}`,
|
||||
} {
|
||||
f.Add([]byte(s))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
l, err := parseBindings("bindings.json", b)
|
||||
if err != nil {
|
||||
if l.Version != 0 || l.Bindings != nil {
|
||||
t.Fatalf("refused with bindings: %+v", l)
|
||||
}
|
||||
return
|
||||
}
|
||||
if l.Version != 1 && l.Version != BindingListVersion {
|
||||
t.Fatalf("read a file of version %d", l.Version)
|
||||
}
|
||||
for _, x := range l.Bindings {
|
||||
m, mok := ParseMethods(x.Methods)
|
||||
switch {
|
||||
case x.Kind != KindSecret && x.Kind != KindLogin,
|
||||
x.Path != "" && !PathOK(x.Path),
|
||||
x.Methods != "" && (!mok || m != x.Methods),
|
||||
x.Scheme != "" && !SchemeOK(x.Scheme),
|
||||
l.Version == 1 && !v1Binding(x):
|
||||
t.Fatalf("read a binding it can't take: %+v, version %d", x, l.Version)
|
||||
}
|
||||
}
|
||||
again, err := parseBindings("again", l.Encode())
|
||||
if err != nil || !reflect.DeepEqual(again.Bindings, l.Bindings) && len(l.Bindings) > 0 {
|
||||
t.Fatalf("Encode of %+v reads back as %+v, %v", l, again, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
go test fuzz v1
|
||||
string("[0]:0")
|
||||
string("0")
|
||||
@@ -0,0 +1,4 @@
|
||||
go test fuzz v1
|
||||
string("0:0")
|
||||
string("0")
|
||||
int(443)
|
||||
@@ -316,6 +316,12 @@ func parseNoProxy(s string) []noProxyRule {
|
||||
}
|
||||
if h, p, err := net.SplitHostPort(e); err == nil {
|
||||
if n, err := strconv.Atoi(p); err == nil {
|
||||
// A port no request has, or one written otherwise than in plain decimal (080, +80),
|
||||
// which Go's clients match against no request's: the entry names nothing, rather
|
||||
// than every port (0) or another spelling's.
|
||||
if n < 1 || n > 65535 || strconv.Itoa(n) != p {
|
||||
continue
|
||||
}
|
||||
e, r.port = h, n
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
@@ -15,6 +16,9 @@ import (
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -282,6 +286,13 @@ func TestNoProxy(t *testing.T) {
|
||||
if ups.route("github.com", 443, false) != nil {
|
||||
t.Error("NO_PROXY=* sent a host upstream")
|
||||
}
|
||||
// A port no request has, or one not in plain decimal, names nothing, as in Go's clients: port 0
|
||||
// was read as every port (found by FuzzNoProxy).
|
||||
for _, e := range []string{"git.test:0", "git.test:65536", "[::1]:0", "git.test:080", "git.test:+80"} {
|
||||
if got := parseNoProxy(e); len(got) != 0 {
|
||||
t.Errorf("NO_PROXY=%s: %+v", e, got)
|
||||
}
|
||||
}
|
||||
// Without HTTP_PROXY, plain HTTP goes direct; tunnels still go upstream.
|
||||
ups.noProxy, ups.http = nil, nil
|
||||
if ups.route("github.com", 80, true) != nil || ups.route("github.com", 80, false) == nil {
|
||||
@@ -728,3 +739,118 @@ func TestUpstreamRouteAuthorizes(t *testing.T) {
|
||||
t.Errorf("the company proxy got %q, %q", line, auth)
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzParseUpstream: a company proxy's URL is taken only as http://, with a host and no
|
||||
// whitespace in it, a port that is one or none, and no path but / or query, and the upstream made
|
||||
// of it is that host and port, 80 without one, with Basic credentials exactly when it names a user;
|
||||
// its errors are the form's or the scheme's alone, never any more of the URL.
|
||||
func FuzzParseUpstream(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
"http://user:[email protected]:8080", "proxy.corp:3128", "proxy.corp", "HTTP://10.0.0.1:8080/",
|
||||
"https://user:[email protected]:443", "socks5h://proxy.corp:1080", "http://proxy.corp:99999",
|
||||
"http://proxy.corp:8080/path", "", "alice:[email protected]:8080", "http://[::1]:3128", "http://u%40corp:p%[email protected]:8080",
|
||||
"http://proxy.corp:8080?x", "http://pr oxy:1", "user:p/w@proxy:1", "http://:0", "http://proxy.corp:+80",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
// Every error ParseUpstream gives: the URL's form, or the scheme alone.
|
||||
upstreamErr := regexp.MustCompile(`^(not a proxy URL|only http:// proxies can be an upstream: [a-z0-9+.-]*://)$`)
|
||||
f.Fuzz(func(t *testing.T, raw string) {
|
||||
u, err := ParseUpstream(raw)
|
||||
if err != nil {
|
||||
if u != nil || !upstreamErr.MatchString(err.Error()) {
|
||||
t.Fatalf("%q: %v, %v", raw, u, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
port := u.Port()
|
||||
n, perr := strconv.Atoi(cmp.Or(port, "80"))
|
||||
switch {
|
||||
case strings.ToLower(u.Scheme) != "http":
|
||||
t.Fatalf("%q: took scheme %q", raw, u.Scheme)
|
||||
case u.Hostname() == "" || strings.ContainsAny(u.Host, " \t\r\n"):
|
||||
t.Fatalf("%q: took host %q", raw, u.Host)
|
||||
case perr != nil || n < 1 || n > 65535:
|
||||
t.Fatalf("%q: took port %q", raw, port)
|
||||
case u.Path != "" && u.Path != "/" || u.RawQuery != "":
|
||||
t.Fatalf("%q: took path %q and query %q", raw, u.Path, u.RawQuery)
|
||||
}
|
||||
up, err := newUpstream(raw, redact.NewSecret("looked-up"))
|
||||
if err != nil || up == nil || up.addr != net.JoinHostPort(u.Hostname(), cmp.Or(port, "80")) || up.auth.Empty() != (u.User == nil) {
|
||||
t.Fatalf("%q: an upstream of %+v, %v", raw, up, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzNoProxy: each NO_PROXY entry sends direct only what it names: * every host; an address or
|
||||
// CIDR, addresses alone; a name, itself and the names under it, or only those after a leading .
|
||||
// or *.; and with a port, that port alone. A list sends direct what any of its entries does.
|
||||
func FuzzNoProxy(f *testing.F) {
|
||||
for _, h := range hostSeeds() {
|
||||
f.Add(" Corp.Example , .internal.test,*.wild.test, 10.0.0.0/8, 192.0.2.7, git.test:22, [2001:db8::1]", h, 443)
|
||||
}
|
||||
for _, s := range [][2]string{
|
||||
{"corp.example", "api.corp.example"},
|
||||
{".internal.test", "internal.test"},
|
||||
{"git.test:22", "git.test"},
|
||||
{"[::1]:8080", "::1"},
|
||||
{"*", "evil.test"},
|
||||
{"..", "a."},
|
||||
{"*.", "x"},
|
||||
{"10.0.0.0/8:443", "10.1.1.1"},
|
||||
} {
|
||||
f.Add(s[0], s[1], 22)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, list, host string, port int) {
|
||||
h := NormHost(host)
|
||||
some := false
|
||||
for _, e := range strings.Split(list, ",") {
|
||||
hit := slices.ContainsFunc(parseNoProxy(e), func(r noProxyRule) bool { return r.matches(h, port) })
|
||||
some = some || hit
|
||||
if hit {
|
||||
checkNoProxyHit(t, strings.TrimSpace(e), h, port)
|
||||
}
|
||||
}
|
||||
whole := slices.ContainsFunc(parseNoProxy(list), func(r noProxyRule) bool { return r.matches(h, port) })
|
||||
if whole != some {
|
||||
t.Fatalf("NO_PROXY %q sends %q:%d direct %v, its entries %v", list, h, port, whole, some)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// checkNoProxyHit checks that the NO_PROXY entry e names h on port, read apart from parseNoProxy.
|
||||
func checkNoProxyHit(t *testing.T, e string, h Host, port int) {
|
||||
t.Helper()
|
||||
if e == "*" {
|
||||
return
|
||||
}
|
||||
if p, err := netip.ParsePrefix(e); err == nil {
|
||||
if a, ok := h.Addr(); !ok || !p.Masked().Contains(a.Unmap()) {
|
||||
t.Fatalf("CIDR %q sent %q direct", e, h)
|
||||
}
|
||||
return
|
||||
}
|
||||
if hp, p, err := net.SplitHostPort(e); err == nil {
|
||||
if n, err := strconv.Atoi(p); err == nil {
|
||||
if n != port || strconv.Itoa(n) != p {
|
||||
t.Fatalf("%q sent %q:%d direct", e, h, port)
|
||||
}
|
||||
e = hp
|
||||
}
|
||||
}
|
||||
e = strings.Trim(e, "[]")
|
||||
if want, err := netip.ParseAddr(e); err == nil {
|
||||
if a, ok := h.Addr(); !ok || a.Unmap() != want.Unmap() {
|
||||
t.Fatalf("address %q sent %q direct", e, h)
|
||||
}
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(e, "*.") {
|
||||
e = e[1:]
|
||||
}
|
||||
name := NormHost(e).String()
|
||||
sub, subOnly := strings.CutPrefix(name, ".")
|
||||
if !strings.HasSuffix(h.String(), "."+sub) && (subOnly || h.String() != name) {
|
||||
t.Fatalf("%q sent %q direct", e, h)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package redact
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -58,6 +59,86 @@ func TestSplit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// splitWriter is how a writer uses Split, as devvm's run log does: what comes is held; each line
|
||||
// that ends is written whole, redacted; and at each of the writer's flush points it writes the
|
||||
// line still to come as far as Split lets it, redacted, holding the rest. At the end it writes
|
||||
// what it holds.
|
||||
func splitWriter(line string, sizes []byte, tail int) string {
|
||||
var out strings.Builder
|
||||
var buf []byte
|
||||
for len(line) > 0 {
|
||||
n := 1
|
||||
if len(sizes) > 0 {
|
||||
n, sizes = int(sizes[0])+1, sizes[1:]
|
||||
}
|
||||
n = min(n, len(line))
|
||||
buf, line = append(buf, line[:n]...), line[n:]
|
||||
if i := bytes.LastIndexAny(buf, "\n\r"); i >= 0 {
|
||||
out.WriteString(String(string(buf[:i+1])))
|
||||
buf = buf[i+1:]
|
||||
}
|
||||
i := Split(buf, tail)
|
||||
out.WriteString(String(string(buf[:i])))
|
||||
buf = buf[i:]
|
||||
}
|
||||
out.WriteString(String(string(buf)))
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// FuzzSplit: a password that String finds in a line whole, in a URL of up to tail bytes, isn't
|
||||
// written by a writer that writes the line in parts, however it comes and wherever Split lets it
|
||||
// cut, with a flush after every part.
|
||||
func FuzzSplit(f *testing.F) {
|
||||
const pw = "Pw0rdZ9qXk" //nolint:gosec // a fake password
|
||||
for _, s := range [][3]string{
|
||||
{"HTTPS_PROXY=", "alice:", "@proxy.corp:8080 next"},
|
||||
{"get ", "http://alice:", "@proxy:3128/x"},
|
||||
{`"`, "https://u:", `@h:1"`},
|
||||
{"x ", "devvm:", "@127.0.0.1:3128"},
|
||||
{"\n", "bob:", "@[::1]:80\r"},
|
||||
{"x ", "http://alice:", "@proxy:3128/" + strings.Repeat("a", 300)},
|
||||
{"=", "alice:", "@proxy.corp:8080" + strings.Repeat("b", 300)},
|
||||
} {
|
||||
f.Add(s[0], s[1], s[2], []byte{3, 7, 20}, uint16(64))
|
||||
f.Add(s[0], s[1], s[2], []byte{0}, uint16(8))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, before, url, after string, sizes []byte, tailN uint16) {
|
||||
line := before + url + pw + after
|
||||
tail := int(tailN)%256 + 1
|
||||
// Split itself: in every start of the line, it cuts outside every secret already whole there.
|
||||
for n := range min(len(line), 2048) + 1 { // each start: quadratic, so the first 2 KiB
|
||||
b := []byte(line[:n])
|
||||
i := Split(b, tail)
|
||||
if i < 0 || i > n {
|
||||
t.Fatalf("Split(%q, %d) = %d", b, tail, i)
|
||||
}
|
||||
for _, re := range secrets() {
|
||||
for _, m := range re.FindAllIndex(b, -1) {
|
||||
if m[0] < i && i < m[1] {
|
||||
t.Fatalf("Split(%q, %d) = %d, inside %q", b, tail, i, b[m[0]:m[1]])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.Count(line, pw) != 1 || strings.Contains(String(line), pw) {
|
||||
return // the password twice, or one String doesn't find whole
|
||||
}
|
||||
at := strings.Index(line, pw)
|
||||
within := false
|
||||
for _, re := range secrets() {
|
||||
for _, m := range re.FindAllStringSubmatchIndex(line, -1) {
|
||||
within = within || m[len(m)-2] <= at && at+len(pw) <= m[len(m)-1] && m[1]-m[0] <= tail
|
||||
}
|
||||
}
|
||||
if !within {
|
||||
return // in a URL longer than tail: Split cuts it, as it says
|
||||
}
|
||||
if out := splitWriter(line, sizes, tail); strings.Contains(out, pw) {
|
||||
t.Fatalf("written in parts of %v with tail %d, the password survives: %q", sizes, tail, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// File overwrites each secret with as many stars in place, so the file keeps its length, and a
|
||||
// writer that still has it open at its own offset, as Lima's hostagent does, goes on where it was.
|
||||
func TestFile(t *testing.T) {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package upgrade_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -86,3 +89,47 @@ func TestParsePublicKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzParsePublicKey: a public key is read only from one base64 line, alone or after an
|
||||
// untrusted comment, that is "Ed", a key ID and an Ed25519 key, and is read as exactly those.
|
||||
func FuzzParsePublicKey(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
fixturePub, strings.Split(fixturePub, "\n")[1], upgradetest.NewKey().Public(), "untrusted comment: x\nnope\n", "a\nb\nc",
|
||||
"RUQl2wfR8/HGRBjOIm1RjKIjqVhIHEUrlNvdrBt9LF4WGpsLpyP5rtoa", " RWQl2wfR8/HGRBjOIm1RjKIjqVhIHEUrlNvdrBt9LF4WGpsLpyP5rtoa\r\n",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, s string) {
|
||||
k, err := upgrade.ParsePublicKey(s)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(s), "\n")
|
||||
if len(lines) > 2 || len(lines) == 2 && !strings.HasPrefix(lines[0], "untrusted comment: ") {
|
||||
t.Fatalf("read a key from %d lines: %q", len(lines), s)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(lines[len(lines)-1]))
|
||||
want := append(append([]byte("Ed"), k.ID[:]...), k.Key...)
|
||||
if err != nil || len(k.Key) != ed25519.PublicKeySize || !bytes.Equal(raw, want) {
|
||||
t.Fatalf("%q read as %x, %x", s, k.ID, k.Key)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzVerify: whatever the data and the signature file, a signature verifies only for what the
|
||||
// key's holder signed, the fixture's data with its trusted comment, which Verify returns as signed.
|
||||
func FuzzVerify(f *testing.F) {
|
||||
k, err := upgrade.ParsePublicKey(fixturePub)
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
for _, sig := range []string{fixtureSig, fixtureLegacy, strings.ReplaceAll(fixtureSig, "\n", "\r\n"), fixtureSig + "\n\n", "nope\n"} {
|
||||
f.Add([]byte(fixtureData), []byte(sig))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, data, sig []byte) {
|
||||
trusted, err := k.Verify(data, sig)
|
||||
if err == nil && (string(data) != fixtureData || trusted != "devvm 0.2.0") {
|
||||
t.Fatalf("verified %q with the trusted comment %q", data, trusted)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package upgrade
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fuzzTop is the top-level folder the fuzzed archives' release has.
|
||||
const fuzzTop = "devvm-1.0.0-darwin-arm64"
|
||||
|
||||
// tarOf is a tar of hs, each regular file's body as many x's as its size.
|
||||
func tarOf(tb testing.TB, hs ...*tar.Header) []byte {
|
||||
tb.Helper()
|
||||
var b bytes.Buffer
|
||||
tw := tar.NewWriter(&b)
|
||||
for _, h := range hs {
|
||||
if err := tw.WriteHeader(h); err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
if h.Typeflag == tar.TypeReg {
|
||||
if _, err := tw.Write(bytes.Repeat([]byte("x"), int(h.Size))); err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// FuzzEntryName: an archive's entry is taken only as its top-level folder, a folder, or as a
|
||||
// regular file right in it, whose name, joined to the folder unpack makes, is a file in that
|
||||
// folder and nowhere else.
|
||||
func FuzzEntryName(f *testing.F) {
|
||||
for _, n := range []string{
|
||||
fuzzTop, fuzzTop + "/", "./" + fuzzTop + "/devvm", fuzzTop + "/devvm", fuzzTop + "/a/b", fuzzTop + "/..",
|
||||
fuzzTop + "/.", "/" + fuzzTop + "/devvm", "../" + fuzzTop + "/devvm", fuzzTop + `/a\b`, fuzzTop + "//devvm", fuzzTop + "/README.md/",
|
||||
} {
|
||||
f.Add(n, byte(tar.TypeReg))
|
||||
f.Add(n, byte(tar.TypeDir))
|
||||
f.Add(n, byte(tar.TypeSymlink))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, name string, flag byte) {
|
||||
rest, ok := entryName(&tar.Header{Name: name, Typeflag: flag}, fuzzTop)
|
||||
switch {
|
||||
case !ok:
|
||||
case rest == "":
|
||||
if flag != tar.TypeDir {
|
||||
t.Fatalf("%q of type %q taken as the top-level folder", name, flag)
|
||||
}
|
||||
default:
|
||||
const dir = "/v"
|
||||
p := filepath.Join(dir, rest)
|
||||
if flag != tar.TypeReg || filepath.Dir(p) != dir || filepath.Base(p) != rest || !filepath.IsLocal(rest) {
|
||||
t.Fatalf("%q of type %q taken as the file %q", name, flag, p)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzUnpack: whatever a release's archive holds, unpack writes only regular files right in the
|
||||
// folder it makes, devvm among them, each as the archive has it, devvm executable and the rest
|
||||
// not, at most unpackCap in all, and nothing outside that folder; an archive it refuses leaves
|
||||
// no folder.
|
||||
func FuzzUnpack(f *testing.F) {
|
||||
dir := &tar.Header{Name: fuzzTop + "/", Typeflag: tar.TypeDir, Mode: 0o755}
|
||||
file := func(name string, size int64) *tar.Header {
|
||||
return &tar.Header{Name: fuzzTop + "/" + name, Typeflag: tar.TypeReg, Mode: 0o755, Size: size}
|
||||
}
|
||||
f.Add(tarOf(f, dir, file("devvm", 10), file("README.md", 3)))
|
||||
f.Add(tarOf(f, file("devvm", 1)))
|
||||
f.Add(tarOf(f, dir, file("README.md", 3)))
|
||||
f.Add(tarOf(f, dir, file("devvm", 1), file("devvm", 2)))
|
||||
f.Add(tarOf(f, dir, file("devvm", 1), &tar.Header{Name: fuzzTop + "/link", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd"}))
|
||||
f.Add(tarOf(f, dir, file("devvm", 1), file("../evil", 1)))
|
||||
f.Add(tarOf(f, dir, file("devvm", 1), &tar.Header{Name: fuzzTop + "/sub/", Typeflag: tar.TypeDir, Mode: 0o755}, file("sub/x", 1)))
|
||||
f.Fuzz(func(t *testing.T, tarball []byte) {
|
||||
// A sparse entry's holes need no bytes in the archive, so a tiny one can unpack hundreds
|
||||
// of MiB, within unpackCap: past a MiB, the fuzzer would spend its time writing zeros.
|
||||
tr := tar.NewReader(bytes.NewReader(tarball))
|
||||
for h, err := tr.Next(); err == nil; h, err = tr.Next() {
|
||||
if h.Size > 1<<20 {
|
||||
return
|
||||
}
|
||||
}
|
||||
root := t.TempDir()
|
||||
var gz bytes.Buffer
|
||||
zw := gzip.NewWriter(&gz)
|
||||
_, _ = zw.Write(tarball)
|
||||
_ = zw.Close()
|
||||
archive, out := filepath.Join(root, "a.tar.gz"), filepath.Join(root, "v")
|
||||
if err := os.WriteFile(archive, gz.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := unpack(archive, fuzzTop, out)
|
||||
if names := dirNames(t, root); !slices.Equal(names, []string{"a.tar.gz", "v"}) && !slices.Equal(names, []string{"a.tar.gz"}) {
|
||||
t.Fatalf("unpack left %q", names)
|
||||
}
|
||||
if err != nil {
|
||||
if _, serr := os.Lstat(out); !errors.Is(serr, os.ErrNotExist) {
|
||||
t.Fatalf("refused (%v), and left its folder: %v", err, serr)
|
||||
}
|
||||
return
|
||||
}
|
||||
checkUnpacked(t, out, filesOf(tarball))
|
||||
})
|
||||
}
|
||||
|
||||
// filesOf is the regular files right in fuzzTop of the tar b, by name: its own reading of it.
|
||||
func filesOf(b []byte) map[string][]byte {
|
||||
files := map[string][]byte{}
|
||||
tr := tar.NewReader(bytes.NewReader(b))
|
||||
for {
|
||||
h, err := tr.Next()
|
||||
if err != nil {
|
||||
return files
|
||||
}
|
||||
if rest, ok := entryName(h, fuzzTop); ok && rest != "" {
|
||||
files[rest], _ = io.ReadAll(tr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkUnpacked checks the folder out unpack made against want, the archive's files.
|
||||
func checkUnpacked(t *testing.T, out string, want map[string][]byte) {
|
||||
t.Helper()
|
||||
var total int64
|
||||
names := dirNames(t, out)
|
||||
if !slices.Contains(names, "devvm") || len(names) != len(want) {
|
||||
t.Fatalf("unpacked %q, from an archive of %d files", names, len(want))
|
||||
}
|
||||
for _, n := range names {
|
||||
p := filepath.Join(out, n)
|
||||
fi, err := os.Lstat(p)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
t.Fatalf("%s: %v, %v", n, fi.Mode(), err)
|
||||
}
|
||||
if perm := fi.Mode().Perm(); n == "devvm" && perm != 0o755 || n != "devvm" && perm != 0o644 {
|
||||
t.Fatalf("%s: mode %v", n, perm)
|
||||
}
|
||||
b, err := os.ReadFile(p) //nolint:gosec // the test's own folder
|
||||
if err != nil || !bytes.Equal(b, want[n]) {
|
||||
t.Fatalf("%s: %d bytes, want %d: %v", n, len(b), len(want[n]), err)
|
||||
}
|
||||
total += fi.Size()
|
||||
}
|
||||
if total > unpackCap {
|
||||
t.Fatalf("unpacked %d bytes", total)
|
||||
}
|
||||
}
|
||||
|
||||
func dirNames(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
es, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := make([]string, len(es))
|
||||
for i, e := range es {
|
||||
names[i] = e.Name()
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package vm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The parsers of what a --clone VM prints, each of which the VM's own programs can write: each
|
||||
// fails closed and keeps to its bounds, whatever the VM says.
|
||||
|
||||
// FuzzParseCloneState: a clone's answer to the check is taken only whole, with every repo asked
|
||||
// for gone or with its branches and status, at most cloneRefsMax branches in all and
|
||||
// cloneWorktreesMax worktrees a repo, each worktree once, at a clean path below the project
|
||||
// folder, with a commit's name or none for its HEAD; and nothing taken is more than the answer.
|
||||
func FuzzParseCloneState(f *testing.F) {
|
||||
const ws = "/p/ws"
|
||||
sha := strings.Repeat("a", 40)
|
||||
f.Add([]byte(rec("refs", 0, "abc refs/heads/main\n")+rec("status", 0, "")+rec("path", 0, ".worktrees/a/api")+rec("wstatus", 0, "?? x\n")+
|
||||
rec("path", 0, ".worktrees/b/api")+rec("whead", 0, sha+"\n")+rec("wstatus", 0, "")+rec("gone", 1, "")+rec("refs", 2, "")+rec("status", 2, " M y\n")), uint8(3))
|
||||
f.Add([]byte(rec("same", 0, "a\x00b\x00")+rec("refs", 0, "")+rec("status", 0, "")), uint8(1))
|
||||
f.Add([]byte(rec("refs", 0, "")+rec("status", 0, "")+rec("path", 0, "../x")+rec("wstatus", 0, "")), uint8(1))
|
||||
f.Add([]byte(rec("refs", 0, "")+"status 0 99999999\nabc"), uint8(1))
|
||||
f.Add([]byte(rec("refs", 0, "")+rec("status", 0, "")+rec("path", 0, "a")+rec("wstatus", 0, "")+rec("path", 0, "./a")+rec("wstatus", 0, "")), uint8(1))
|
||||
f.Fuzz(func(t *testing.T, out []byte, repos uint8) {
|
||||
n := int(repos%4) + 1
|
||||
got, err := parseCloneState(out, ws, n)
|
||||
if err != nil {
|
||||
if got != nil {
|
||||
t.Fatalf("refused with %+v", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(got) != n {
|
||||
t.Fatalf("%d repos, asked for %d", len(got), n)
|
||||
}
|
||||
kinds := recordKinds(out)
|
||||
for i := range n {
|
||||
k := kinds[i]
|
||||
if !k["gone"] && (!k["refs"] || !k["status"]) || got[i].gone != k["gone"] {
|
||||
t.Fatalf("repo %d taken, gone %v, from records %v", i, got[i].gone, k)
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
refs, size := 0, 0
|
||||
for _, r := range got {
|
||||
refs += bytes.Count(r.refs, []byte("\n"))
|
||||
size += len(r.refs) + len(r.status)
|
||||
if len(r.trees) > cloneWorktreesMax {
|
||||
t.Fatalf("%d worktrees", len(r.trees))
|
||||
}
|
||||
for _, w := range r.trees {
|
||||
rel, ok := strings.CutPrefix(w.path, ws+"/")
|
||||
switch {
|
||||
case !ok || rel == "" || path.Clean(w.path) != w.path || seen[w.path]:
|
||||
t.Fatalf("a worktree at %q", w.path)
|
||||
case w.head != "" && !objectName.MatchString(w.head):
|
||||
t.Fatalf("a worktree's HEAD %q", w.head)
|
||||
}
|
||||
seen[w.path] = true
|
||||
size += len(w.status)
|
||||
}
|
||||
}
|
||||
if refs > cloneRefsMax || size > len(out) {
|
||||
t.Fatalf("%d branches and %d bytes, from %d", refs, size, len(out))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// recordKinds reads cloneState's records in out apart from parseCloneState: the kinds each repo's
|
||||
// index has, as far as the records are whole.
|
||||
func recordKinds(out []byte) map[int]map[string]bool {
|
||||
kinds := map[int]map[string]bool{}
|
||||
for len(out) > 0 {
|
||||
line, rest, ok := bytes.Cut(out, []byte("\n"))
|
||||
f := strings.Fields(string(line))
|
||||
if !ok || len(f) != 3 {
|
||||
return kinds
|
||||
}
|
||||
i, err1 := strconv.Atoi(f[1])
|
||||
size, err2 := strconv.Atoi(f[2])
|
||||
if err1 != nil || err2 != nil || size < 0 || size > len(rest) {
|
||||
return kinds
|
||||
}
|
||||
if kinds[i] == nil {
|
||||
kinds[i] = map[string]bool{}
|
||||
}
|
||||
kinds[i][f[0]] = true
|
||||
out = rest[size:]
|
||||
}
|
||||
return kinds
|
||||
}
|
||||
|
||||
// FuzzParseInit: the VM's answer to its repos' setup names a seed as landed, or of another
|
||||
// format, only when a line names that seed's path as it was asked; and an old git is named only
|
||||
// by what git --version prints, else as unknown.
|
||||
func FuzzParseInit(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
"landed .\nformat a b\n", "landed elsewhere\nformat ../x\nlanded\n", "oldgit git version 2.25.1 (Apple Git-99)\n",
|
||||
"oldgit \x1b[31mred\n", "landed a b\r\nlanded .\n",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
seeds := []repoSeed{{path: "."}, {path: "a b"}}
|
||||
f.Fuzz(func(t *testing.T, out string) {
|
||||
a := parseInit(out, seeds)
|
||||
lines := strings.Split(out, "\n")
|
||||
for i, l := range lines {
|
||||
lines[i] = strings.TrimSuffix(l, "\r") // a line may end with CRLF
|
||||
}
|
||||
for kind, paths := range map[string][]string{"landed": a.landed, "format": a.format} {
|
||||
for _, p := range paths {
|
||||
if !slices.ContainsFunc(seeds, func(s repoSeed) bool { return s.path == p }) || !slices.Contains(lines, kind+" "+p) {
|
||||
t.Fatalf("%s %q, from %q", kind, p, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
if a.oldGit != "" && a.oldGit != "unknown" && (!gitVersion.MatchString(a.oldGit) || !slices.Contains(lines, "oldgit "+a.oldGit)) {
|
||||
t.Fatalf("an old git %q, from %q", a.oldGit, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzParseKept: what a seed's apply kept, which is only shown, is the VM's own lines and names as
|
||||
// it wrote them: each branch from a kept-ref line, without refs/heads/, and each file and each of
|
||||
// pre's a name of the NUL-separated list after kept-files, none empty and none holding a NUL; pre
|
||||
// only after applied-tree.
|
||||
func FuzzParseKept(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
"kept-ref refs/heads/agent/x\nkept-ref refs/remotes/origin/main\nkept-ref\nother line\nkept-head\nkept-files\na\tb\x00line\nbreak\x00\x00dir/f\x00",
|
||||
"applied-tree\nkept-files\na\x00b\x00\x00p\x00", "kept-files\nkept-ref x\x00kept-head\x00", "lfs-setup-failed\nkept-files\nkept-files\n\x00",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, out string) {
|
||||
k := parseKept(out)
|
||||
head, names, _ := strings.Cut("\n"+out, "\nkept-files\n")
|
||||
lines := strings.Split(head, "\n")
|
||||
for _, r := range k.refs {
|
||||
if !slices.Contains(lines, "kept-ref "+r) && !slices.Contains(lines, "kept-ref refs/heads/"+r) {
|
||||
t.Fatalf("a branch %q, from %q", r, out)
|
||||
}
|
||||
}
|
||||
list := strings.Split(names, "\x00")
|
||||
for _, n := range slices.Concat(k.files, k.pre) {
|
||||
if n == "" || strings.Contains(n, "\x00") || !slices.Contains(list, n) {
|
||||
t.Fatalf("a file %q, from %q", n, out)
|
||||
}
|
||||
}
|
||||
if len(k.pre) > 0 && !k.tree {
|
||||
t.Fatalf("pre's files without applied-tree: %q", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzParseLFSPointer: a blob is taken as a Git LFS pointer only as the spec writes one, its
|
||||
// version line first and each line ended, with one oid, 64 lowercase hex digits, which names its
|
||||
// object's path in .git/lfs/objects, and one size, a decimal of at least 0.
|
||||
func FuzzParseLFSPointer(f *testing.F) {
|
||||
const v = "version https://git-lfs.github.com/spec/v1\n"
|
||||
oid := strings.Repeat("ab", 32)
|
||||
for _, s := range []string{
|
||||
v + "oid sha256:" + oid + "\nsize 12345\n", v + "ext-0-foo sha256:" + oid + "\noid sha256:" + oid + "\nsize 1\n",
|
||||
v + "oid sha256:" + oid + "\nsize -1\n", v + "oid sha256:" + oid + "\noid sha256:" + oid + "\nsize 1\n", v + "oid sha256:../" + oid[3:] + "\nsize 1\n",
|
||||
} {
|
||||
f.Add([]byte(s))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
o, ok := parseLFSPointer(b)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s := string(b)
|
||||
lines := strings.Split(strings.TrimSuffix(s, "\n"), "\n")
|
||||
oids, sizes := 0, 0
|
||||
for _, l := range lines[1:] {
|
||||
oids += strings.Count(l+" ", "oid sha256:"+o.oid+" ") * boolInt(strings.HasPrefix(l, "oid "))
|
||||
sizes += boolInt(l == "size "+strconv.FormatInt(o.size, 10) || strings.HasPrefix(l, "size ") && strings.TrimLeft(l[5:], "+0") == strconv.FormatInt(o.size, 10))
|
||||
}
|
||||
switch {
|
||||
case !strings.HasPrefix(s, v) || !strings.HasSuffix(s, "\n"):
|
||||
t.Fatalf("took %q", s)
|
||||
case len(o.oid) != 64 || strings.Trim(o.oid, "0123456789abcdef") != "" || path.Base(o.oid) != o.oid:
|
||||
t.Fatalf("took the oid %q", o.oid)
|
||||
case o.size < 0 || oids != 1 || sizes != 1:
|
||||
t.Fatalf("took %q as %+v", s, o)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func boolInt(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -402,3 +403,33 @@ func TestSplitPorts(t *testing.T) {
|
||||
t.Errorf("taken %v, want %v", taken, want)
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzParsePorts: a forwarder's record, which another VM's forwarder reads, gives only ports that
|
||||
// are ones, each an entry of its line as it's written, in order; and the ports record writes read
|
||||
// back as themselves.
|
||||
func FuzzParsePorts(f *testing.F) {
|
||||
for _, s := range []string{"5173,8080", "", ",", "0,65535,65536,-1", "+80, 81,0x50,8080 ", "99999999999999999999"} {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, s string) {
|
||||
got := parsePorts(s)
|
||||
es := strings.Split(s, ",")
|
||||
at := 0
|
||||
for _, n := range got {
|
||||
for at < len(es) && es[at] != strconv.Itoa(n) && strings.TrimLeft(es[at], "+0") != strconv.Itoa(n) {
|
||||
at++
|
||||
}
|
||||
if !backend.ValidPort(n) || at == len(es) {
|
||||
t.Fatalf("parsePorts(%q) = %v: %d", s, got, n)
|
||||
}
|
||||
at++
|
||||
}
|
||||
line := make([]string, len(got))
|
||||
for i, n := range got {
|
||||
line[i] = strconv.Itoa(n)
|
||||
}
|
||||
if again := parsePorts(strings.Join(line, ",")); !slices.Equal(again, got) {
|
||||
t.Fatalf("%v read back as %v", got, again)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package vmssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
@@ -241,3 +243,70 @@ func readFile(t *testing.T, path string) string {
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// typeChars reports whether typ has only the characters a key type ssh has may have, written out
|
||||
// apart from keyType: a letter or digit first, then letters, digits and @ . _ + -, at most 64.
|
||||
func typeChars(typ string) bool {
|
||||
if typ == "" || len(typ) > 64 {
|
||||
return false
|
||||
}
|
||||
for i, c := range typ {
|
||||
alnum := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
|
||||
if !alnum && (i == 0 || !strings.ContainsRune("@._+-", c)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// FuzzParseHostKeys: whatever a VM shows for its host keys, each key taken is a type ssh could
|
||||
// have, no certificate, marker or pattern, with a key in strict base64 of at most keyMax that names
|
||||
// its own type; as the record's line under the VM's name, it is three fields, which read back as
|
||||
// that key; and the keys are the VM's lines' own, in order, at most one a line.
|
||||
func FuzzParseHostKeys(f *testing.F) {
|
||||
// blobOf is a key in ssh's wire format that names typ, and its base64.
|
||||
blobOf := func(typ string) string {
|
||||
b := binary.BigEndian.AppendUint32(nil, uint32(len(typ))) //nolint:gosec // G115: a seed's short type
|
||||
b = append(append(b, typ...), 0, 0, 0, 3, 'k', 'e', 'y')
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
for _, s := range []string{
|
||||
"ssh-ed25519 " + keyED + " root@vm\necdsa-sha2-nistp256 " + keyEC + "\r\n",
|
||||
"[email protected] " + keySK + " a comment",
|
||||
"@cert-authority ssh-ed25519 " + keyED + "\n*-evil " + keyED + "\nssh-rsa " + keyED,
|
||||
"[email protected] " + keyED + "\nssh-ed25519\"x " + keyED,
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\nssh-ed25519 AAAA\n\x00ssh-ed25519 " + keyED,
|
||||
// Blobs that name their own type, which isn't one a known hosts line may have.
|
||||
"[email protected] " + blobOf("[email protected]"),
|
||||
`x"y ` + blobOf(`x"y`),
|
||||
"@cert-authority " + blobOf("@cert-authority"),
|
||||
} {
|
||||
f.Add([]byte(s))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, out []byte) {
|
||||
keys := ParseHostKeys(out)
|
||||
lines := strings.Split(string(out), "\n")
|
||||
at := 0
|
||||
for _, k := range keys {
|
||||
blob, err := base64.StdEncoding.Strict().DecodeString(k.Key)
|
||||
switch {
|
||||
case !typeChars(k.Type) || strings.Contains(k.Type, "-cert-"):
|
||||
t.Fatalf("took the key type %q", k.Type)
|
||||
case err != nil || len(blob) > keyMax || len(blob) < 4+len(k.Type) || string(blob[4:4+len(k.Type)]) != k.Type ||
|
||||
int(binary.BigEndian.Uint32(blob)) != len(k.Type):
|
||||
t.Fatalf("took the key %q of type %q", k.Key, k.Type)
|
||||
}
|
||||
rec := "devvm-app-0123456789abcd " + k.Type + " " + k.Key
|
||||
if fields := strings.Fields(rec); len(fields) != 3 || !slices.Equal(ParseHostKeys([]byte(k.Type+" "+k.Key)), []HostKey{k}) {
|
||||
t.Fatalf("the record's line %q doesn't read back", rec)
|
||||
}
|
||||
for at < len(lines) && !slices.Equal(strings.Fields(lines[at])[:min(2, len(strings.Fields(lines[at])))], []string{k.Type, k.Key}) {
|
||||
at++
|
||||
}
|
||||
if at == len(lines) {
|
||||
t.Fatalf("took %q, which isn't a line of its own, in order", k)
|
||||
}
|
||||
at++
|
||||
}
|
||||
})
|
||||
}
|
||||
+6
-4
@@ -760,17 +760,19 @@ bump_ci-mise() {
|
||||
}
|
||||
|
||||
# Every workflow's uses:, pinned by a release's tag's commit with the tag as a comment: moved to the
|
||||
# newest release's (within its major, the next major only reported), the commit from gh api.
|
||||
# newest release's (within its major, the next major only reported), the commit from gh api. An
|
||||
# action in a folder of its repo (actions/cache/restore) moves with its repo's releases.
|
||||
bump_actions() {
|
||||
need gh
|
||||
local repo sha tag newest within f new
|
||||
local repo sha tag newest within f new gh_repo
|
||||
while read -r repo sha tag; do
|
||||
gh api "repos/$repo/releases?per_page=100" --jq '.[] | select((.draft or .prerelease) | not) | .tag_name' > "$tmp/tags"
|
||||
gh_repo=$(cut -d/ -f1-2 <<<"$repo")
|
||||
gh api "repos/$gh_repo/releases?per_page=100" --jq '.[] | select((.draft or .prerelease) | not) | .tag_name' > "$tmp/tags"
|
||||
newest=$(newest_of < "$tmp/tags")
|
||||
within=$(newest_of "$(sed 's/^v//; s/\..*//' <<<"$tag")" < "$tmp/tags")
|
||||
choose "$repo" "$tag" "${newest:-$tag}" "$within" || continue
|
||||
valid action_version "$target"
|
||||
new=$(gh api "repos/$repo/commits/$target" --jq .sha)
|
||||
new=$(gh api "repos/$gh_repo/commits/$target" --jq .sha)
|
||||
valid action_commit "$new"
|
||||
for f in "$root"/.github/workflows/*.yml; do
|
||||
set_text "${f#"$root"/}" text "uses: $repo@$sha # $tag" "uses: $repo@$new # $target"
|
||||
|
||||
Vendored
+3
-3
@@ -1,7 +1,7 @@
|
||||
# Each package's test coverage, in percent: the unit tests and the CLI tests together.
|
||||
# mise run test fails when a package drops below its line; mise run coverage raises them.
|
||||
cmd/devvm 100.0
|
||||
internal/agentlogin 95.3
|
||||
internal/agentlogin 95.4
|
||||
internal/agents 100.0
|
||||
internal/backend 97.1
|
||||
internal/backend/backendtest 74.4
|
||||
@@ -11,7 +11,7 @@ internal/build 88.5
|
||||
internal/cli 91.2
|
||||
internal/cli/docgen 86.5
|
||||
internal/daemon 97.9
|
||||
internal/desktop 77.2
|
||||
internal/desktop 78.8
|
||||
internal/devcontainer 96.8
|
||||
internal/fetch 96.6
|
||||
internal/from 91.3
|
||||
@@ -46,7 +46,7 @@ internal/tools 90.9
|
||||
internal/trust 95.0
|
||||
internal/ubuntu 97.3
|
||||
internal/ui 97.2
|
||||
internal/upgrade 93.2
|
||||
internal/upgrade 93.8
|
||||
internal/upgrade/upgradetest 97.4
|
||||
internal/vm 88.4
|
||||
internal/vmname 100.0
|
||||
|
||||
Reference in new issue
Block a user