Compare commits
107
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a34cf20628 | ||
|
|
abb6bfd35d | ||
|
|
dce31c8784 | ||
|
|
32ab0d75ba | ||
|
|
2c5eccae55 | ||
|
|
18b5fac584 | ||
|
|
34bccbd437 | ||
|
|
e036d99f02 | ||
|
|
43a09c158a | ||
|
|
c752fc6d8b | ||
|
|
802f254e9a | ||
|
|
8d48e488bd | ||
|
|
baf19ed6c8 | ||
|
|
6b24c85fce | ||
|
|
95568d7339 | ||
|
|
d612bb6521 | ||
|
|
c1736f65e8 | ||
|
|
553f6a04fb | ||
|
|
e928140351 | ||
|
|
c424f7e192 | ||
|
|
ae7745772a | ||
|
|
28af64daa5 | ||
|
|
871a2cd3f7 | ||
|
|
322766cf63 | ||
|
|
c13db2a5ba | ||
|
|
777322c66b | ||
|
|
629dff22fe | ||
|
|
1d000e037b | ||
|
|
c0df4371f7 | ||
|
|
e2be7ff6de | ||
|
|
88d9b99165 | ||
|
|
361a6f4587 | ||
|
|
e19cc7a66b | ||
|
|
d496742500 | ||
|
|
9d705ec44f | ||
|
|
17e73f246a | ||
|
|
017a0eb22c | ||
|
|
a4f499ce12 | ||
|
|
b9686af9c8 | ||
|
|
e8faf398f5 | ||
|
|
0c9731a8f9 | ||
|
|
148a0ce5e4 | ||
|
|
23a67af7db | ||
|
|
709d07775b | ||
|
|
b59791e0c5 | ||
|
|
5501dfd66d | ||
|
|
ffaa51a092 | ||
|
|
a226191c1c | ||
|
|
9d84b7164e | ||
|
|
e460bdc139 | ||
|
|
a951509350 | ||
|
|
46460fcec3 | ||
|
|
5f6e7dd40d | ||
|
|
c93de9fe41 | ||
|
|
4922e49853 | ||
|
|
c82693e9c1 | ||
|
|
772c4aad11 | ||
|
|
79c6c72fd6 | ||
|
|
e83ced0e20 | ||
|
|
5faeb77411 | ||
|
|
1d0c275a04 | ||
|
|
ea8030b707 | ||
|
|
5aab1e0131 | ||
|
|
f1b4780e2c | ||
|
|
f6889940c3 | ||
|
|
31caf922b8 | ||
|
|
c0f892c539 | ||
|
|
a5fe65021b | ||
|
|
b1eb641729 | ||
|
|
ebea5f5cfd | ||
|
|
024df31e66 | ||
|
|
11c068e03e | ||
|
|
db198c05f6 | ||
|
|
2e6bcd51a1 | ||
|
|
9e01f2d5d3 | ||
|
|
f1f7662afa | ||
|
|
b17c9826c7 | ||
|
|
086ad87296 | ||
|
|
58eeaf1dd4 | ||
|
|
c7df11210a | ||
|
|
c48e7b616d | ||
|
|
c9e5f22d03 | ||
|
|
4cea798651 | ||
|
|
11adff8278 | ||
|
|
ea6dbf3e6c | ||
|
|
bb8e6b3872 | ||
|
|
3d7de8ffb7 | ||
|
|
19a3408912 | ||
|
|
970cf5bb9d | ||
|
|
a2d0365813 | ||
|
|
e9c3f36970 | ||
|
|
98e3b9d6a5 | ||
|
|
5d352139dd | ||
|
|
d3599245f8 | ||
|
|
d1495ff2d5 | ||
|
|
12c00693f8 | ||
|
|
2e88fdb937 | ||
|
|
f49083ee96 | ||
|
|
2c58237e78 | ||
|
|
7a7a5b1612 | ||
|
|
7e687e0d5d | ||
|
|
c5f669b3c0 | ||
|
|
751d8c0bda | ||
|
|
212cb30b97 | ||
|
|
3efc252059 | ||
|
|
bd52429276 | ||
|
|
a404927a78 |
@@ -0,0 +1,7 @@
|
||||
2026-11-10T21:41:18-06:00 1 17293278c1c7 src/web.rs 320 Medium files/file endpoints not token-gated (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 073768bc5201 src/web.rs 389 Medium settings redirect header-splitting via __section/__tab (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 d45a2e52d1ba src/auth.rs 37 Medium RNG fallback to constant csrf/guessable wsid (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 b6701ede5237 src/dashboard.rs 199 Medium settings write error swallowed, reported success (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 1b4915d2c7a6 src/tuning.rs 180 Low set_target kept PID integral across unit-mismatched modes (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 97ba434fdd3a src/console.rs 234 Medium editable-deck new-block id collision (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 0a2a1950ad0d src/web.rs 81 Medium unbounded thread-per-connection DoS (fixed: conn cap)
|
||||
@@ -0,0 +1,44 @@
|
||||
# Code Review Memory
|
||||
|
||||
This file is maintained by the `code-review-harness` skill. It records
|
||||
findings across review sessions so the skill can spot recurring issues
|
||||
and apply more aggressive remediation when an issue persists.
|
||||
|
||||
The skill **reads this file at the start of every review** and **updates
|
||||
it at the end** with new findings.
|
||||
|
||||
## How to use
|
||||
|
||||
- The "Recurring Issues" section is rebuilt automatically each run. Treat
|
||||
it as the high-signal list of things that keep coming back.
|
||||
- The "Session Log" is append-only. Each row is one finding from one
|
||||
session. The log is the source of truth; the index is derived from it.
|
||||
- If a finding has been fixed and you don't want it to count toward
|
||||
recurrence anymore, add a `RESOLVED:` row referencing the finding
|
||||
fingerprint.
|
||||
|
||||
## Recurring Issues
|
||||
|
||||
_(auto-generated — rebuilt at end of each session)_
|
||||
|
||||
<!-- BEGIN RECURRING -->
|
||||
|
||||
_No recurring issues yet — every finding has been a one-off, or memory was just initialized._
|
||||
|
||||
<!-- END RECURRING -->
|
||||
|
||||
## Session Log
|
||||
|
||||
_(append-only)_
|
||||
|
||||
<!-- BEGIN LOG -->
|
||||
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:320` [Medium] files/file endpoints not token-gated (fixed) (fp:17293278c1c7)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:389` [Medium] settings redirect header-splitting via __section/__tab (fixed) (fp:073768bc5201)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/auth.rs:37` [Medium] RNG fallback to constant csrf/guessable wsid (fixed) (fp:d45a2e52d1ba)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/dashboard.rs:199` [Medium] settings write error swallowed, reported success (fixed) (fp:b6701ede5237)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/tuning.rs:180` [Low] set_target kept PID integral across unit-mismatched modes (fixed) (fp:1b4915d2c7a6)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/console.rs:234` [Medium] editable-deck new-block id collision (fixed) (fp:97ba434fdd3a)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:81` [Medium] unbounded thread-per-connection DoS (fixed: conn cap) (fp:0a2a1950ad0d)
|
||||
|
||||
<!-- END LOG -->
|
||||
@@ -1,8 +1,9 @@
|
||||
name: public-benchmark-pages
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/15 * * * *'
|
||||
workflow_run:
|
||||
workflows: [main-release-gate]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -13,15 +14,17 @@ jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install SSH client
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
fi
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: completed-ci-badge
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/15 * * * *'
|
||||
workflow_run:
|
||||
workflows: [main-release-gate, next-build]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -11,7 +12,9 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-ci
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
name: source-pr
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, next]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-source-pr-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
source:
|
||||
runs-on: alkane-fast
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Check runner image pins
|
||||
run: python3 ci/check-runner-image.py
|
||||
- name: Detect README-only change
|
||||
id: surface
|
||||
run: |
|
||||
surface=full
|
||||
if [ "$GITHUB_EVENT_NAME" = pull_request ] &&
|
||||
{ [ "$GITHUB_BASE_REF" = main ] || [ "$GITHUB_BASE_REF" = next ]; } &&
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF" 2>/dev/null)" &&
|
||||
changed="$(git diff --no-renames --name-only "$base" HEAD)" &&
|
||||
[ "$changed" = README.md ]; then
|
||||
surface=documentation
|
||||
fi
|
||||
echo "surface=$surface" >> "$GITHUB_OUTPUT"
|
||||
- name: Check README-only change
|
||||
if: steps.surface.outputs.surface == 'documentation'
|
||||
run: |
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
|
||||
echo "private key material found in tracked source" >&2
|
||||
exit 1
|
||||
else
|
||||
status=$?
|
||||
[ "$status" -eq 1 ]
|
||||
fi
|
||||
- name: Check patch whitespace
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
# Vendored crates (vendor/) and the flare-ui source (third-party/) keep
|
||||
# their upstream bytes (cargo vendor checksums, byte-exact fixtures).
|
||||
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
else
|
||||
git diff --check HEAD^ HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
fi
|
||||
- name: Check CI and evidence tools
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
python3 -m compileall -q ci
|
||||
for test in ci/test-*.py; do python3 "$test"; done
|
||||
python3 ci/evidence_status.py
|
||||
python3 ci/experiment_priority.py
|
||||
- name: Check source
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
rustup component add rustfmt
|
||||
cargo fmt --check
|
||||
cargo test --locked
|
||||
- name: Clean generated source check
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -11,6 +11,8 @@ concurrency:
|
||||
jobs:
|
||||
verify-and-release:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
permissions:
|
||||
@@ -22,12 +24,16 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install Pages SSH client
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
fi
|
||||
- name: Install Rust quality tools
|
||||
run: rustup component add rustfmt clippy
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: .afw format tests
|
||||
run: python3 ci/test-afw.py
|
||||
- name: Formatting
|
||||
run: cargo fmt --check
|
||||
- name: Last-attempt badge checks
|
||||
@@ -66,9 +72,7 @@ jobs:
|
||||
- name: Coverage tool
|
||||
run: |
|
||||
rustup component add llvm-tools-preview
|
||||
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
|
||||
cargo install --locked cargo-llvm-cov --version 0.8.7
|
||||
fi
|
||||
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
|
||||
- name: Unit test coverage
|
||||
run: |
|
||||
mkdir -p coverage
|
||||
|
||||
@@ -4,19 +4,26 @@ on:
|
||||
push:
|
||||
branches: [next]
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-next
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: .afw format tests
|
||||
run: python3 ci/test-afw.py
|
||||
- name: Build release candidate
|
||||
run: cargo build --release --offline --locked
|
||||
- name: Select candidate version
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
name: source-pr
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [next, main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-source-pr-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
source:
|
||||
runs-on: alkane-fast
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Detect changed surface
|
||||
id: surface
|
||||
run: python3 ci/pr_surface.py >> "$GITHUB_OUTPUT"
|
||||
- name: Check patch whitespace
|
||||
run: |
|
||||
if [ "${GITHUB_EVENT_NAME:-}" = pull_request ]; then
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD
|
||||
else
|
||||
git diff --check HEAD^ HEAD
|
||||
fi
|
||||
- name: Check CI and evidence tools
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
python3 -m compileall -q ci
|
||||
for test in ci/test-*.py; do python3 "$test"; done
|
||||
python3 ci/evidence_status.py
|
||||
python3 ci/experiment_priority.py
|
||||
- name: Install source formatter
|
||||
if: steps.surface.outputs.surface == 'rust'
|
||||
run: rustup component add rustfmt
|
||||
- name: Check source formatting
|
||||
if: steps.surface.outputs.surface == 'rust'
|
||||
run: cargo fmt --check
|
||||
- name: Check changed Rust source
|
||||
if: steps.surface.outputs.surface == 'rust'
|
||||
run: |
|
||||
if [ "${GITHUB_BASE_REF:-}" = main ]; then
|
||||
cargo build --release --offline --locked
|
||||
else
|
||||
cargo check --offline --locked
|
||||
fi
|
||||
- name: Clean generated build
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -12,7 +12,10 @@
|
||||
|
||||
Rust mining and tuning core for Alkane control boards. The
|
||||
[SDK](https://gitea.bluefla.re/blueflare/alkane-sdk) builds board images and
|
||||
provides the hardware backend. The miner has no on-board web frontend.
|
||||
provides the hardware backend. The on-board web console is the parameterised
|
||||
`flare-ui`: a sidebar shell with live telemetry (readings) and real controls
|
||||
(mode/target, start/stop) that drive the runtime, with `/api/...` as the
|
||||
interface of record behind every page.
|
||||
|
||||
## Status
|
||||
|
||||
@@ -40,6 +43,14 @@ ALKANE_POOL_PASSWORD="$POOL_PASSWORD" alkane-os --mine-simulator HAL_SOCKET POOL
|
||||
Use `BM1362` for that chip. Set `ALKANE_API_LISTEN=127.0.0.1:4028` for
|
||||
read-only `summary` and `version` commands; reach it remotely through SSH.
|
||||
|
||||
To bring up the full web console on a workstation with no hashboard, run
|
||||
`alkane-os --serve-sim`: a reference HAL runs in-process, the runtime boots
|
||||
against it, and the printed URL serves the live, controllable console (the
|
||||
frequency moves toward the target; start/stop and mode changes take effect).
|
||||
`alkane-os --serve` serves the same console with no backend, for a board whose
|
||||
HAL backend is not written yet. `ALKANE_WEB_LISTEN=ADDR` overrides the bind
|
||||
(default port 80, or 8080 without privilege).
|
||||
|
||||
## Release gate
|
||||
|
||||
`main` runs tests, benchmarks, and conformance before release; `next` builds
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Board profiles used by the .afw producer and the CI checker.
|
||||
|
||||
An .afw is valid for exactly one board family. The arch and bootloader policy
|
||||
come from this table, never from the caller alone, so a bundle cannot claim a
|
||||
board it was not built for. cv1835 and am335x have complete, buildable profiles in this release; the
|
||||
other Antminer families are listed so a wrong-board bundle is rejected by name
|
||||
instead of being accepted as "unknown".
|
||||
"""
|
||||
|
||||
AM335X_PARTITIONS = [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0x0000000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x0020000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd2", "device": "/dev/mtd2", "offset": 0x0040000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd3", "device": "/dev/mtd3", "offset": 0x0060000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd4", "device": "/dev/mtd4", "offset": 0x0080000, "size": 0x1C0000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd5", "device": "/dev/mtd5", "offset": 0x0240000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd6", "device": "/dev/mtd6", "offset": 0x0260000, "size": 0x20000,
|
||||
"secure": False, "boot_critical": True, "write_order": 2, "image": "dtb"},
|
||||
{"name": "mtd7", "device": "/dev/mtd7", "offset": 0x0280000, "size": 0x500000,
|
||||
"secure": False, "boot_critical": True, "write_order": 3, "image": "kernel"},
|
||||
{"name": "mtd8", "device": "/dev/mtd8", "offset": 0x0800000, "size": 0x1400000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "rootfs"},
|
||||
{"name": "mtd9", "device": "/dev/mtd9", "offset": 0x1C00000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
{"name": "mtd10", "device": "/dev/mtd10", "offset": 0x1E00000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
{"name": "mtd11", "device": "/dev/mtd11", "offset": 0x2000000, "size": 0x6000000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
]
|
||||
|
||||
AM335X_IMAGES = [
|
||||
{"name": "kernel", "source": "alkane-am335x.uImage", "role": "kernel",
|
||||
"format": "uimage", "partition": "mtd7", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "am335x-alkane.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "mtd6", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "alkane-am335x-ramdisk.uImage", "role": "rootfs",
|
||||
"format": "uimage", "partition": "mtd8", "install": True, "exact_bytes": None},
|
||||
]
|
||||
|
||||
# Tier-3 from-stock variant: same 12-partition NAND map, but mtd4 is written
|
||||
# with our non-RSA U-Boot (a legacy uImage the preserved SPL chainloads), so its
|
||||
# secure flag is False and it carries the u-boot image at write_order 3; the
|
||||
# kernel moves to write_order 4 (U-Boot lands before the kernel). The SPL copies
|
||||
# (mtd0-3) and bootenv (mtd5) stay preserved and are never write targets.
|
||||
AM335X_STOCK_PARTITIONS = []
|
||||
for _p in AM335X_PARTITIONS:
|
||||
_q = dict(_p)
|
||||
if _q["name"] == "mtd4":
|
||||
_q.update(secure=False, write_order=3, image="u-boot")
|
||||
elif _q["name"] == "mtd7":
|
||||
_q.update(write_order=4)
|
||||
AM335X_STOCK_PARTITIONS.append(_q)
|
||||
|
||||
AM335X_STOCK_IMAGES = [
|
||||
{"name": "u-boot", "source": "alkane-am335x-uboot-mtd4.uImage", "role": "bootloader",
|
||||
"format": "uimage", "partition": "mtd4", "install": True, "exact_bytes": None},
|
||||
] + [dict(_img) for _img in AM335X_IMAGES]
|
||||
|
||||
BOARDS = {
|
||||
"am335x": {
|
||||
"arch": "arm",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["uimage", "fdt", "uimage"],
|
||||
"partitions": AM335X_PARTITIONS,
|
||||
"images": AM335X_IMAGES,
|
||||
},
|
||||
"am335x-stock": {
|
||||
"arch": "arm",
|
||||
"bootloader_policy": "include",
|
||||
"buildable": True,
|
||||
"format_checks": ["uimage", "uimage", "fdt", "uimage"],
|
||||
"partitions": AM335X_STOCK_PARTITIONS,
|
||||
"images": AM335X_STOCK_IMAGES,
|
||||
},
|
||||
"cv1835": {
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["fit", "arm64-image", "fdt", "cpio-gzip"],
|
||||
"partitions": [
|
||||
{
|
||||
"name": "p1",
|
||||
"device": "/dev/mmcblk0p1",
|
||||
"offset": 0,
|
||||
"size": 16 * 1024 * 1024,
|
||||
"secure": False,
|
||||
"boot_critical": True,
|
||||
"write_order": 1,
|
||||
"image": "p1",
|
||||
},
|
||||
{
|
||||
"name": "p3",
|
||||
"device": "/dev/mmcblk0p3",
|
||||
"offset": 0,
|
||||
"size": 32 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": False,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
{
|
||||
"name": "boot0",
|
||||
"device": "/dev/mmcblk0boot0",
|
||||
"offset": 0,
|
||||
"size": 4 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": True,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
{
|
||||
"name": "boot1",
|
||||
"device": "/dev/mmcblk0boot1",
|
||||
"offset": 0,
|
||||
"size": 4 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": True,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
],
|
||||
"images": [
|
||||
{
|
||||
"name": "kernel",
|
||||
"source": "Image",
|
||||
"role": "kernel",
|
||||
"format": "arm64-image",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "dtb",
|
||||
"source": "cv-alkane.dtb",
|
||||
"role": "dtb",
|
||||
"format": "fdt",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "rootfs",
|
||||
"source": "rootfs.cpio.gz",
|
||||
"role": "rootfs",
|
||||
"format": "cpio-gzip",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "p1",
|
||||
"source": "alkane-cv1835-p1.fit",
|
||||
"role": "boot",
|
||||
"format": "fit",
|
||||
"partition": "p1",
|
||||
"install": True,
|
||||
"exact_bytes": 16 * 1024 * 1024,
|
||||
},
|
||||
],
|
||||
},
|
||||
# Antminer families that the seven-board release gate still lists. They are
|
||||
# known, so a wrong-board bundle is refused by identity, but they do not
|
||||
# have a buildable .afw profile in this release.
|
||||
"zynq-7010": {
|
||||
"arch": "armv7",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
# kernel (zImage), dtb (FDT), rootfs (gzip cpio ramdisk)
|
||||
"format_checks": ["zimage", "fdt", "cpio-gzip"],
|
||||
# Both bench Zynq-7010 units (S19, S17) share mtd0 (40 MiB: BOOT.bin +
|
||||
# the kernel slot) and mtd1 (32 MiB: ramfs). BOOT.bin (FSBL + FPGA
|
||||
# bitstream + stock U-Boot) is PRESERVED - the bundle carries no
|
||||
# bootloader member; only the kernel slot in mtd0 and the ramfs in mtd1
|
||||
# are our OS. The exact kernel-slot sub-offset is placed by the install
|
||||
# method (it differs by unit), so this profile gates image formats and
|
||||
# size ceilings, not a fixed offset map.
|
||||
"partitions": [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0, "size": 0x2800000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "kernel"},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x2800000, "size": 0x2000000,
|
||||
"secure": False, "boot_critical": True, "write_order": 2, "image": "rootfs"},
|
||||
],
|
||||
"images": [
|
||||
{"name": "kernel", "source": "zImage", "role": "kernel",
|
||||
"format": "zimage", "partition": "mtd0", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "zynq-alkane.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "mtd0", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "rootfs.cpio.gz", "role": "rootfs",
|
||||
"format": "cpio-gzip", "partition": "mtd1", "install": True, "exact_bytes": None},
|
||||
],
|
||||
},
|
||||
"zynq-s17": {"arch": "armv7", "bootloader_policy": "include", "buildable": False},
|
||||
# Amlogic A113D / AXG (S21 Pro-class) control board. arm64. Our OS is staged
|
||||
# as FILES in the nvdata UBI volume (mtd6): kernel (arm64 Image), dtb, and a
|
||||
# uImage ramdisk. The signed FIP bootloader and the stock boot partition
|
||||
# (mtd0-5) are PRESERVED - zero raw writes outside nvdata, so the stock OS in
|
||||
# mtd4 stays as a one-setenv fallback. Hence bootloader_policy preserve and no
|
||||
# bootloader member.
|
||||
"a113d": {
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["arm64-image", "fdt", "uimage"],
|
||||
"partitions": [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0x0000000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x0800000, "size": 0x800000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd2", "device": "/dev/mtd2", "offset": 0x1000000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd3", "device": "/dev/mtd3", "offset": 0x1200000, "size": 0x1000000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd4", "device": "/dev/mtd4", "offset": 0x2200000, "size": 0x2000000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd5", "device": "/dev/mtd5", "offset": 0x4200000, "size": 0x500000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "nvdata", "device": "/dev/mtd6", "offset": 0x4700000, "size": 0xB900000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "kernel"},
|
||||
],
|
||||
"images": [
|
||||
{"name": "kernel", "source": "vmlinux.bin", "role": "kernel",
|
||||
"format": "arm64-image", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "devicetree.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "uramdisk.image.gz", "role": "rootfs",
|
||||
"format": "uimage", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
],
|
||||
},
|
||||
"a113d-s21pro": {"arch": "arm64", "bootloader_policy": "preserve", "buildable": False},
|
||||
"am335x-bb": {"arch": "armv7", "bootloader_policy": "preserve", "buildable": False},
|
||||
}
|
||||
|
||||
SAFE_IMAGE_FORMATS = {
|
||||
"fit",
|
||||
"arm64-image",
|
||||
"zimage",
|
||||
"fdt",
|
||||
"cpio-gzip",
|
||||
"uimage",
|
||||
"raw",
|
||||
}
|
||||
|
||||
SAFE_IMAGE_ROLES = {
|
||||
"kernel",
|
||||
"dtb",
|
||||
"rootfs",
|
||||
"bootloader",
|
||||
"boot",
|
||||
"component",
|
||||
}
|
||||
|
||||
|
||||
def board(name):
|
||||
"""Return the profile for a board family, or raise KeyError."""
|
||||
return BOARDS[name]
|
||||
|
||||
|
||||
def known_board(name):
|
||||
return name in BOARDS
|
||||
|
||||
|
||||
def expect_arch(name):
|
||||
return BOARDS[name]["arch"]
|
||||
|
||||
|
||||
def expect_policy(name):
|
||||
return BOARDS[name]["bootloader_policy"]
|
||||
Executable
+656
@@ -0,0 +1,656 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Generate an .afw manifest and stage its payload members.
|
||||
|
||||
The output is a full OS install bundle for exactly one board family: the
|
||||
manifest names every image, its size and SHA-256, the partition plan, the
|
||||
bootloader policy, the network recovery path and a liveness marker. Payload
|
||||
members are staged under <staging>/payload/ in manifest order.
|
||||
|
||||
This script does not create the tar. ci/make-afw.sh packs the staged members
|
||||
in the fixed order manifest.json, optional manifest.json.sig, then payload.
|
||||
ci/check-afw.py verifies the finished bundle before it is published.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import afw_boards
|
||||
|
||||
SCHEMA = 2
|
||||
P1_LOAD = 0x100200000
|
||||
GOLDEN_LBA_BYTES = 0x300000 * 512
|
||||
REVISION = 40
|
||||
|
||||
AM335X_MAP = {
|
||||
"mtd0": (0x0000000, 0x20000, True, True, 0, None),
|
||||
"mtd1": (0x0020000, 0x20000, True, True, 0, None),
|
||||
"mtd2": (0x0040000, 0x20000, True, True, 0, None),
|
||||
"mtd3": (0x0060000, 0x20000, True, True, 0, None),
|
||||
"mtd4": (0x0080000, 0x1C0000, True, True, 0, None),
|
||||
"mtd5": (0x0240000, 0x20000, True, True, 0, None),
|
||||
"mtd6": (0x0260000, 0x20000, False, True, 2, "dtb"),
|
||||
"mtd7": (0x0280000, 0x500000, False, True, 3, "kernel"),
|
||||
"mtd8": (0x0800000, 0x1400000, False, True, 1, "rootfs"),
|
||||
"mtd9": (0x1C00000, 0x200000, True, False, 0, None),
|
||||
"mtd10": (0x1E00000, 0x200000, True, False, 0, None),
|
||||
"mtd11": (0x2000000, 0x6000000, True, False, 0, None),
|
||||
}
|
||||
AM335X_HOLE = (0x780000, 0x80000)
|
||||
AM335X_CHIP = 0x8000000
|
||||
AM335X_TARGETS = {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_FORMATS = {"kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# Tier-3 from-stock: same map except mtd4 is a write target (our U-Boot).
|
||||
AM335X_STOCK_MAP = dict(AM335X_MAP)
|
||||
AM335X_STOCK_MAP["mtd4"] = (0x0080000, 0x1C0000, False, True, 3, "u-boot")
|
||||
AM335X_STOCK_MAP["mtd7"] = (0x0280000, 0x500000, False, True, 4, "kernel")
|
||||
AM335X_STOCK_TARGETS = {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_STOCK_FORMATS = {"u-boot": "uimage", "kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_STOCK_CEILINGS = {"u-boot": 0x1C0000, "kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# SPL copies (mtd0-3) and bootenv (mtd5) must never be written on either tier.
|
||||
AM335X_NEVER_WRITE = {"mtd0", "mtd1", "mtd2", "mtd3", "mtd5"}
|
||||
|
||||
# Zynq-7010 (tier 2, preserve): kernel into the mtd0 kernel slot, dtb, rootfs
|
||||
# into mtd1; BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) preserved.
|
||||
ZYNQ_FORMATS = {"kernel": "zimage", "dtb": "fdt", "rootfs": "cpio-gzip"}
|
||||
ZYNQ_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x2000000}
|
||||
|
||||
# Amlogic A113D/AXG (tier 2, preserve): kernel (arm64 Image), dtb and a uImage
|
||||
# ramdisk are staged as FILES in the nvdata UBI (mtd6); the FIP bootloader and
|
||||
# the stock boot partition (mtd0-5) are preserved. Ceilings keep the three well
|
||||
# within the ~185 MiB usable nvdata UBI.
|
||||
A113D_FORMATS = {"kernel": "arm64-image", "dtb": "fdt", "rootfs": "uimage"}
|
||||
A113D_CEILINGS = {"kernel": 0x4000000, "dtb": 0x100000, "rootfs": 0x6000000}
|
||||
A113D_NVDATA_USABLE = 0xB900000 # mtd6 nvdata size; the three images must fit
|
||||
|
||||
|
||||
def die(message):
|
||||
print(f"afw_manifest: error: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def sha256_bytes(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def git_revision(path):
|
||||
try:
|
||||
return subprocess.check_output(
|
||||
["git", "-C", str(path), "rev-parse", "HEAD"],
|
||||
text=True,
|
||||
stderr=subprocess.DEVNULL,
|
||||
).strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
|
||||
|
||||
def check_revision(name, value):
|
||||
if value is None or len(value) != REVISION:
|
||||
die(f"{name} must be a 40-character git revision, got {value!r}")
|
||||
if any(character not in "0123456789abcdef" for character in value):
|
||||
die(f"{name} must be lowercase hexadecimal")
|
||||
return value
|
||||
|
||||
|
||||
def build_date(value):
|
||||
if value is None:
|
||||
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
try:
|
||||
moment = datetime.datetime.fromtimestamp(int(value), datetime.timezone.utc)
|
||||
except (ValueError, OSError):
|
||||
die("SOURCE_DATE_EPOCH must be an integer Unix timestamp")
|
||||
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def magic_ok(fmt, path):
|
||||
with path.open("rb") as source:
|
||||
data = source.read() if fmt == "fit" else source.read(4096)
|
||||
if fmt == "fit":
|
||||
if not data.startswith(b"\xd0\x0d\xfe\xed"):
|
||||
return "does not start with the FIT/FDT magic d00dfeed"
|
||||
if b"config@cv1835_miner_emmc" not in data:
|
||||
return "FIT is missing config@cv1835_miner_emmc"
|
||||
if b"signature@" in data:
|
||||
return "FIT carries signature@ nodes, which this board cannot boot"
|
||||
elif fmt == "fdt":
|
||||
if not data.startswith(b"\xd0\x0d\xfe\xed"):
|
||||
return "does not start with the FDT magic d00dfeed"
|
||||
elif fmt == "arm64-image":
|
||||
if len(data) < 64 or data[0x38:0x3C] != b"ARMd":
|
||||
return "does not carry the arm64 Image ARMd header magic"
|
||||
elif fmt == "cpio-gzip":
|
||||
if not data.startswith(b"\x1f\x8b"):
|
||||
return "is not gzip-compressed"
|
||||
elif fmt == "uimage":
|
||||
if not data.startswith(b"\x27\x05\x19\x56"):
|
||||
return "is not a legacy uImage"
|
||||
return None
|
||||
|
||||
|
||||
def pad_to(source, destination, exact_bytes):
|
||||
size = source.stat().st_size
|
||||
if size > exact_bytes:
|
||||
die(f"{source.name} is {size} bytes, larger than its {exact_bytes}-byte partition")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with source.open("rb") as reader, destination.open("wb") as writer:
|
||||
shutil.copyfileobj(reader, writer)
|
||||
if size < exact_bytes:
|
||||
writer.write(b"\0" * (exact_bytes - size))
|
||||
if destination.stat().st_size != exact_bytes:
|
||||
die(f"{destination.name} did not reach the exact {exact_bytes}-byte size")
|
||||
|
||||
|
||||
def load_plan(path, profile, board):
|
||||
plan = json.loads(Path(path).read_text())
|
||||
if plan.get("board") != board:
|
||||
die(f"plan board {plan.get('board')!r} does not match --board {board!r}")
|
||||
if plan.get("arch") != profile["arch"]:
|
||||
die(f"plan arch {plan.get('arch')!r} does not match {profile['arch']!r}")
|
||||
policy = plan.get("bootloader_policy", profile["bootloader_policy"])
|
||||
if policy != profile["bootloader_policy"]:
|
||||
die(f"plan bootloader_policy {policy!r} does not match {profile['bootloader_policy']!r}")
|
||||
partitions = plan.get("partitions")
|
||||
images = plan.get("images")
|
||||
if not isinstance(partitions, list) or not isinstance(images, list):
|
||||
die("plan must contain partitions and images lists")
|
||||
return partitions, images
|
||||
|
||||
|
||||
def signing_key(path):
|
||||
raw = Path(path).read_bytes()
|
||||
if len(raw) == 64:
|
||||
try:
|
||||
raw = bytes.fromhex(raw.decode("ascii").strip())
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
die("signing key file must be 32 raw bytes or 64 hexadecimal characters")
|
||||
if len(raw) != 32:
|
||||
die("signing key file must be 32 raw bytes or 64 hexadecimal characters")
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
except ImportError:
|
||||
die("Ed25519 signing needs the Python cryptography package")
|
||||
private = Ed25519PrivateKey.from_private_bytes(raw)
|
||||
public = private.public_key().public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
)
|
||||
return private, public.hex()
|
||||
|
||||
|
||||
def validate_am335x(partitions, images):
|
||||
"""Reject the AM335x brick paths before a bundle is packed."""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("am335x must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(AM335X_TARGETS):
|
||||
die("am335x install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered:
|
||||
die(f"am335x bundle carries an spl/u-boot member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != AM335X_FORMATS[name]:
|
||||
die(f"am335x {name} format must be {AM335X_FORMATS[name]}")
|
||||
if image["partition"] != AM335X_TARGETS[name]:
|
||||
die(f"am335x {name} must target {AM335X_TARGETS[name]}")
|
||||
if image["size"] > AM335X_CEILINGS[name]:
|
||||
die(
|
||||
f"am335x {name} is {image['size']} bytes, over the "
|
||||
f"0x{AM335X_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
if name not in AM335X_MAP:
|
||||
die(f"unknown am335x partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_MAP[name]
|
||||
if int(partition["offset"]) != offset:
|
||||
die(f"am335x {name} offset must be 0x{offset:x}")
|
||||
if int(partition["size"]) != size:
|
||||
die(f"am335x {name} size must be 0x{size:x}")
|
||||
if bool(partition["secure"]) is not secure:
|
||||
die(f"am335x {name} secure flag is wrong")
|
||||
if bool(partition["boot_critical"]) is not boot_critical:
|
||||
die(f"am335x {name} boot_critical flag is wrong")
|
||||
if int(partition.get("write_order", 0)) != write_order:
|
||||
die(f"am335x {name} write_order must be {write_order}")
|
||||
if partition.get("image") != image_name:
|
||||
die(f"am335x {name} image must be {image_name!r}")
|
||||
start = int(partition["offset"])
|
||||
end = start + int(partition["size"])
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
if start < hole_start + hole_size and end > hole_start:
|
||||
die(f"am335x {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in {f"mtd{index}" for index in range(0, 6)} and write_order != 0:
|
||||
die(f"am335x {name} is preserved and must not be written")
|
||||
if set(seen) != set(AM335X_MAP):
|
||||
die("am335x manifest partition map is incomplete")
|
||||
if int(seen["mtd7"]["offset"]) + int(seen["mtd7"]["size"]) != AM335X_HOLE[0]:
|
||||
die("am335x mtd7 must end at the 0x780000 hole")
|
||||
if int(seen["mtd8"]["offset"]) != AM335X_HOLE[0] + AM335X_HOLE[1]:
|
||||
die("am335x mtd8 must start at 0x800000 after the hole")
|
||||
total = sum(int(part["size"]) for part in partitions)
|
||||
if total != AM335X_CHIP - AM335X_HOLE[1]:
|
||||
die("am335x partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_am335x_stock(partitions, images):
|
||||
"""Reject the AM335x tier-3 (from-stock) brick paths before packing.
|
||||
|
||||
This bundle DOES write mtd4 (our non-RSA U-Boot), so unlike the tier-2
|
||||
validator it permits a u-boot member - but it still guards every brick
|
||||
path: the four install images are exactly u-boot/kernel/dtb/rootfs, mtd4
|
||||
carries the u-boot and no SPL copy is ever a write target, the 0x780000
|
||||
hole and the 12-partition geometry are exact, and no mtd0-3/mtd5 may hold
|
||||
an image.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 4:
|
||||
die("am335x-stock must install exactly u-boot, kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(AM335X_STOCK_TARGETS):
|
||||
die("am335x-stock install images must be named u-boot, kernel, dtb and rootfs")
|
||||
# The U-Boot member is expected here; a loose 'spl' member never is.
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
if "spl" in lowered:
|
||||
die(f"am335x-stock bundle carries an spl member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != AM335X_STOCK_FORMATS[name]:
|
||||
die(f"am335x-stock {name} format must be {AM335X_STOCK_FORMATS[name]}")
|
||||
if image["partition"] != AM335X_STOCK_TARGETS[name]:
|
||||
die(f"am335x-stock {name} must target {AM335X_STOCK_TARGETS[name]}")
|
||||
if image["size"] > AM335X_STOCK_CEILINGS[name]:
|
||||
die(
|
||||
f"am335x-stock {name} is {image['size']} bytes, over the "
|
||||
f"0x{AM335X_STOCK_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
if installs[[img["name"] for img in installs].index("u-boot")]["role"] != "bootloader":
|
||||
die("am335x-stock u-boot image must have role bootloader")
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
if name not in AM335X_STOCK_MAP:
|
||||
die(f"unknown am335x-stock partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_STOCK_MAP[name]
|
||||
if int(partition["offset"]) != offset:
|
||||
die(f"am335x-stock {name} offset must be 0x{offset:x}")
|
||||
if int(partition["size"]) != size:
|
||||
die(f"am335x-stock {name} size must be 0x{size:x}")
|
||||
if bool(partition["secure"]) is not secure:
|
||||
die(f"am335x-stock {name} secure flag is wrong")
|
||||
if bool(partition["boot_critical"]) is not boot_critical:
|
||||
die(f"am335x-stock {name} boot_critical flag is wrong")
|
||||
if int(partition.get("write_order", 0)) != write_order:
|
||||
die(f"am335x-stock {name} write_order must be {write_order}")
|
||||
if partition.get("image") != image_name:
|
||||
die(f"am335x-stock {name} image must be {image_name!r}")
|
||||
start = int(partition["offset"])
|
||||
end = start + int(partition["size"])
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
if start < hole_start + hole_size and end > hole_start:
|
||||
die(f"am335x-stock {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in AM335X_NEVER_WRITE and (write_order != 0 or partition.get("image") is not None):
|
||||
die(f"am335x-stock {name} is preserved and must not be written")
|
||||
if set(seen) != set(AM335X_STOCK_MAP):
|
||||
die("am335x-stock manifest partition map is incomplete")
|
||||
if int(seen["mtd7"]["offset"]) + int(seen["mtd7"]["size"]) != AM335X_HOLE[0]:
|
||||
die("am335x-stock mtd7 must end at the 0x780000 hole")
|
||||
if int(seen["mtd8"]["offset"]) != AM335X_HOLE[0] + AM335X_HOLE[1]:
|
||||
die("am335x-stock mtd8 must start at 0x800000 after the hole")
|
||||
total = sum(int(part["size"]) for part in partitions)
|
||||
if total != AM335X_CHIP - AM335X_HOLE[1]:
|
||||
die("am335x-stock partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_zynq(partitions, images):
|
||||
"""Reject the Zynq-7010 brick paths before packing (tier 2, preserve).
|
||||
|
||||
The board reuses the stock BOOT.bin (FSBL + FPGA bitstream + stock U-Boot),
|
||||
so the bundle must carry NO bootloader/spl/BOOT.bin member; it installs our
|
||||
kernel (zImage) into the mtd0 kernel slot, the dtb, and the rootfs
|
||||
(gzip cpio) into mtd1. The exact kernel-slot offset is placed per-unit by the
|
||||
install method, so this gate enforces the image set, formats and the
|
||||
size ceilings (so an oversize image cannot overrun the slot) - not a fixed
|
||||
offset map.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("zynq-7010 must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(ZYNQ_FORMATS):
|
||||
die("zynq-7010 install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image.get('role','')}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered \
|
||||
or "boot.bin" in lowered or image.get("role") == "bootloader":
|
||||
die(f"zynq-7010 bundle carries a bootloader/spl member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != ZYNQ_FORMATS[name]:
|
||||
die(f"zynq-7010 {name} format must be {ZYNQ_FORMATS[name]}")
|
||||
if image["size"] > ZYNQ_CEILINGS[name]:
|
||||
die(
|
||||
f"zynq-7010 {name} is {image['size']} bytes, over the "
|
||||
f"0x{ZYNQ_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
# BOOT.bin lives at the front of mtd0 and is never a write target here.
|
||||
for partition in partitions:
|
||||
if partition.get("image") in (None, "kernel", "rootfs"):
|
||||
continue
|
||||
die(f"zynq-7010 partition {partition['name']!r} has an unexpected image target")
|
||||
|
||||
|
||||
def validate_a113d(partitions, images):
|
||||
"""Reject the Amlogic A113D/AXG brick paths before packing (tier 2, preserve).
|
||||
|
||||
Our OS is staged as files in the nvdata UBI; the signed FIP bootloader and the
|
||||
stock boot partition (mtd0-5) are preserved, so the bundle must carry NO
|
||||
bootloader/spl/tpl/fip member. The kernel (arm64 Image), dtb and uImage
|
||||
ramdisk must fit the nvdata UBI both individually (ceilings) and together.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("a113d must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(A113D_FORMATS):
|
||||
die("a113d install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image.get('role','')}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered \
|
||||
or "fip" in lowered or "tpl" in lowered or image.get("role") == "bootloader":
|
||||
die(f"a113d bundle carries a bootloader/spl/fip member: {image['file']!r}")
|
||||
total = 0
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != A113D_FORMATS[name]:
|
||||
die(f"a113d {name} format must be {A113D_FORMATS[name]}")
|
||||
if image["size"] > A113D_CEILINGS[name]:
|
||||
die(f"a113d {name} is {image['size']} bytes, over the 0x{A113D_CEILINGS[name]:x}-byte ceiling")
|
||||
total += image["size"]
|
||||
if total > A113D_NVDATA_USABLE:
|
||||
die(f"a113d images total {total} bytes, over the 0x{A113D_NVDATA_USABLE:x}-byte nvdata UBI")
|
||||
# mtd0-5 (FIP + stock boot) are never a write target.
|
||||
for partition in partitions:
|
||||
if partition["name"] != "nvdata" and partition.get("image") is not None:
|
||||
die(f"a113d partition {partition['name']!r} is preserved and must not carry an image")
|
||||
|
||||
|
||||
def build(args):
|
||||
board = args.board
|
||||
if not afw_boards.known_board(board):
|
||||
die(f"unknown board family {board!r}")
|
||||
profile = afw_boards.board(board)
|
||||
if not profile["buildable"]:
|
||||
die(f"board {board!r} has no buildable .afw profile in this release")
|
||||
|
||||
input_dir = Path(args.input)
|
||||
if not input_dir.is_dir():
|
||||
die(f"input directory does not exist: {input_dir}")
|
||||
|
||||
plan_document = None
|
||||
if args.plan:
|
||||
plan_document = json.loads(Path(args.plan).read_text())
|
||||
partitions, image_specs = load_plan(args.plan, profile, board)
|
||||
else:
|
||||
partitions = profile["partitions"]
|
||||
image_specs = profile["images"]
|
||||
|
||||
staging = Path(args.staging) if args.staging else Path(tempfile.mkdtemp(prefix="afw-manifest."))
|
||||
payload_dir = staging / "payload"
|
||||
payload_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
images = []
|
||||
for spec in image_specs:
|
||||
source_name = spec.get("source", spec.get("file"))
|
||||
if not source_name:
|
||||
die(f"image {spec.get('name')!r} has no source file")
|
||||
source = input_dir / source_name
|
||||
if not source.is_file():
|
||||
die(f"required image is missing: {source}")
|
||||
name = spec["name"]
|
||||
fmt = spec.get("format", "raw")
|
||||
if fmt not in afw_boards.SAFE_IMAGE_FORMATS:
|
||||
die(f"image {name!r} has unsupported format {fmt!r}")
|
||||
role = spec.get("role", "component")
|
||||
if role not in afw_boards.SAFE_IMAGE_ROLES:
|
||||
die(f"image {name!r} has unsupported role {role!r}")
|
||||
target = payload_dir / source.name
|
||||
exact = spec.get("exact_bytes")
|
||||
if exact is not None:
|
||||
pad_to(source, target, int(exact))
|
||||
else:
|
||||
shutil.copyfile(source, target)
|
||||
problem = magic_ok(fmt, target)
|
||||
if problem:
|
||||
die(f"image {name!r} ({target.name}) {problem}")
|
||||
size = target.stat().st_size
|
||||
images.append(
|
||||
{
|
||||
"name": name,
|
||||
"file": f"payload/{target.name}",
|
||||
"role": role,
|
||||
"format": fmt,
|
||||
"size": size,
|
||||
"sha256": sha256_file(target),
|
||||
"partition": spec.get("partition"),
|
||||
"install": bool(spec.get("install", False)),
|
||||
}
|
||||
)
|
||||
|
||||
names = {image["name"] for image in images}
|
||||
for partition in partitions:
|
||||
image_name = partition.get("image")
|
||||
if image_name is not None and image_name not in names:
|
||||
die(f"partition {partition.get('name')!r} references missing image {image_name!r}")
|
||||
if not partition.get("secure", False):
|
||||
size = int(partition.get("size", 0))
|
||||
if size <= 0:
|
||||
die(f"partition {partition.get('name')!r} has no positive size")
|
||||
if partition.get("write_order", 0) > 0 and image_name is None:
|
||||
die(f"installable partition {partition.get('name')!r} has no image")
|
||||
device = partition.get("device", "")
|
||||
if not device.startswith("/dev/"):
|
||||
die(f"partition {partition.get('name')!r} has an invalid device path")
|
||||
if "boot0" in device and not partition.get("secure", False):
|
||||
die("boot0 must be declared secure and must never be a write target")
|
||||
if "boot0" in device and partition.get("write_order", 0) > 0:
|
||||
die("boot0 must not be in the write order")
|
||||
|
||||
for image in images:
|
||||
partition_name = image.get("partition")
|
||||
if partition_name is None:
|
||||
continue
|
||||
matches = [item for item in partitions if item.get("name") == partition_name]
|
||||
if len(matches) != 1:
|
||||
die(f"image {image['name']!r} targets unknown partition {partition_name!r}")
|
||||
partition = matches[0]
|
||||
if partition.get("secure", False):
|
||||
die(f"image {image['name']!r} targets secure partition {partition_name!r}")
|
||||
if image["size"] > int(partition["size"]):
|
||||
die(
|
||||
f"image {image['name']!r} is {image['size']} bytes, larger than "
|
||||
f"partition {partition_name!r} ({partition['size']} bytes)"
|
||||
)
|
||||
exact = image.get("exact_bytes", partition.get("exact_bytes"))
|
||||
if exact is not None and image["size"] != int(exact):
|
||||
die(f"image {image['name']!r} must be exactly {exact} bytes")
|
||||
|
||||
installs = [image for image in images if image["install"]]
|
||||
if not installs:
|
||||
die("bundle has no installable image")
|
||||
if board == "cv1835":
|
||||
if len(installs) != 1 or installs[0]["name"] != "p1":
|
||||
die("cv1835 must install exactly one image, p1")
|
||||
if installs[0]["size"] != 16 * 1024 * 1024:
|
||||
die("cv1835 p1 must be the 16 MiB padded FIT")
|
||||
elif board == "am335x":
|
||||
validate_am335x(partitions, images)
|
||||
elif board == "am335x-stock":
|
||||
validate_am335x_stock(partitions, images)
|
||||
elif board == "zynq-7010":
|
||||
validate_zynq(partitions, images)
|
||||
elif board == "a113d":
|
||||
validate_a113d(partitions, images)
|
||||
|
||||
policy = profile["bootloader_policy"]
|
||||
if policy == "preserve" and any(image["role"] == "bootloader" for image in images):
|
||||
die("bootloader_policy is preserve but the bundle carries a bootloader image")
|
||||
if policy == "include" and not any(image["role"] == "bootloader" for image in images):
|
||||
die("bootloader_policy is include but the bundle has no bootloader image")
|
||||
|
||||
sdk_revision = check_revision(
|
||||
"sdk_revision", args.sdk_revision or (git_revision(args.sdk_dir) if args.sdk_dir else None)
|
||||
)
|
||||
os_revision = check_revision(
|
||||
"os_revision", args.os_revision or (git_revision(args.os_dir) if args.os_dir else None)
|
||||
)
|
||||
|
||||
signature = {
|
||||
"type": "unsigned",
|
||||
"member": None,
|
||||
"public_key_hex": None,
|
||||
}
|
||||
signer = None
|
||||
if args.signing_key:
|
||||
signer, public_hex = signing_key(args.signing_key)
|
||||
signature = {
|
||||
"type": "ed25519",
|
||||
"member": "manifest.json.sig",
|
||||
"public_key_hex": public_hex,
|
||||
}
|
||||
|
||||
if board == "am335x":
|
||||
boot_switch = {
|
||||
"method": "preserved-u-boot-go",
|
||||
"detail": "mtd0-5 (SPL and our non-RSA U-Boot) are preserved and never "
|
||||
"written. The update writes mtd8 root, mtd6 dtb and mtd7 kernel as "
|
||||
"legacy ARM uImages, and the existing boot command loads them.",
|
||||
}
|
||||
preflight = {
|
||||
"required_commands": ["flash_erase", "nandwrite", "nanddump", "md5sum", "sync"],
|
||||
"forbidden_devices": [f"/dev/mtd{index}" for index in range(0, 6)],
|
||||
"min_free_bytes": 32 * 1024 * 1024,
|
||||
"source_os": ["alkane", "ouros", "braiins"],
|
||||
"held_partitions": ["mtd8", "mtd6", "mtd7"],
|
||||
"preserve_partitions": [f"mtd{index}" for index in range(0, 6)],
|
||||
}
|
||||
recovery = {
|
||||
"network": "afw restore --host <ip> --held-backup <mtd8.img> --confirm FLASH",
|
||||
"held_partition": "mtd8",
|
||||
"held_partitions": ["mtd8", "mtd6", "mtd7"],
|
||||
}
|
||||
else:
|
||||
boot_switch = {
|
||||
"method": "partition-overwrite",
|
||||
"detail": "Writing /dev/mmcblk0p1 replaces the FIT. The vendor boot0, "
|
||||
"BL2, BL31 and U-Boot chain is preserved and never written.",
|
||||
}
|
||||
preflight = {
|
||||
"required_commands": ["dd", "md5sum", "sync"],
|
||||
"forbidden_devices": ["/dev/mmcblk0", "/dev/mmcblk0boot0", "/dev/mmcblk0boot1"],
|
||||
"min_free_bytes": 32 * 1024 * 1024,
|
||||
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
|
||||
}
|
||||
recovery = {
|
||||
"network": "afw restore --host <ip> --held-backup <file>",
|
||||
"held_partition": "p1",
|
||||
"golden_lba_bytes": GOLDEN_LBA_BYTES,
|
||||
}
|
||||
|
||||
manifest = {
|
||||
"schema": SCHEMA,
|
||||
"format": "afw",
|
||||
"board": board,
|
||||
"arch": profile["arch"],
|
||||
"version": args.version,
|
||||
"build_date": build_date(os.environ.get("SOURCE_DATE_EPOCH")),
|
||||
"sdk_revision": sdk_revision,
|
||||
"os_revision": os_revision,
|
||||
"payload_type": "os",
|
||||
"bootloader_policy": policy,
|
||||
"signature": signature,
|
||||
"partitions": [
|
||||
{
|
||||
"name": item["name"],
|
||||
"device": item["device"],
|
||||
"offset": int(item.get("offset", 0)),
|
||||
"size": int(item["size"]),
|
||||
"secure": bool(item.get("secure", False)),
|
||||
"boot_critical": bool(item.get("boot_critical", False)),
|
||||
"write_order": int(item.get("write_order", 0)),
|
||||
"image": item.get("image"),
|
||||
}
|
||||
for item in partitions
|
||||
],
|
||||
"images": images,
|
||||
"boot_switch": boot_switch,
|
||||
"preflight": preflight,
|
||||
"recovery": recovery,
|
||||
"marker": (plan_document or {}).get("marker")
|
||||
or args.marker
|
||||
or ("Alkane" if board == "am335x" else "ALKANE"),
|
||||
"kernel_version": (plan_document or {}).get("kernel_version")
|
||||
or args.kernel_version
|
||||
or "6.18.48",
|
||||
}
|
||||
if args.notes:
|
||||
manifest["notes"] = args.notes
|
||||
|
||||
manifest_path = staging / "manifest.json"
|
||||
manifest_bytes = (json.dumps(manifest, indent=2) + "\n").encode()
|
||||
manifest_path.write_bytes(manifest_bytes)
|
||||
|
||||
if signer is not None:
|
||||
signature_bytes = signer.sign(manifest_bytes)
|
||||
(staging / "manifest.json.sig").write_bytes(signature_bytes)
|
||||
(staging / "manifest.pub").write_text(signature["public_key_hex"] + "\n")
|
||||
|
||||
print(str(manifest_path))
|
||||
return staging, manifest_path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--board", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--input", required=True, help="SDK board output directory")
|
||||
parser.add_argument("--staging", help="staging directory for manifest.json and payload/")
|
||||
parser.add_argument("--plan", help="plan JSON emitted by alkane-sdk ci/check-plans.py")
|
||||
parser.add_argument("--sdk-revision")
|
||||
parser.add_argument("--os-revision")
|
||||
parser.add_argument("--sdk-dir")
|
||||
parser.add_argument("--os-dir", default=".")
|
||||
parser.add_argument("--signing-key", help="raw 32-byte or 64-hex Ed25519 seed file")
|
||||
parser.add_argument("--kernel-version")
|
||||
parser.add_argument("--marker")
|
||||
parser.add_argument("--notes")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
build(args)
|
||||
except SystemExit:
|
||||
raise
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
die(str(error))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+709
@@ -0,0 +1,709 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Verify an .afw OS install bundle before it can be published or installed.
|
||||
|
||||
The gate is deliberately strict and offline. It reads the tar itself instead of
|
||||
trusting GNU tar, checks the fixed member order, rejects path traversal and
|
||||
non-regular members, verifies every payload size and SHA-256 against the
|
||||
manifest, checks the board/arch and bootloader policy, checks each image against
|
||||
its partition ceiling, and refuses a signed bundle it cannot verify.
|
||||
|
||||
Exit codes: 0 pass, 1 failure, 2 usage error.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import afw_boards
|
||||
|
||||
BLOCK = 512
|
||||
MAX_MANIFEST = 64 * 1024
|
||||
MAX_ARCHIVE = 512 * 1024 * 1024
|
||||
|
||||
AM335X_MAP = {
|
||||
"mtd0": (0x0000000, 0x20000, True, True, 0, None),
|
||||
"mtd1": (0x0020000, 0x20000, True, True, 0, None),
|
||||
"mtd2": (0x0040000, 0x20000, True, True, 0, None),
|
||||
"mtd3": (0x0060000, 0x20000, True, True, 0, None),
|
||||
"mtd4": (0x0080000, 0x1C0000, True, True, 0, None),
|
||||
"mtd5": (0x0240000, 0x20000, True, True, 0, None),
|
||||
"mtd6": (0x0260000, 0x20000, False, True, 2, "dtb"),
|
||||
"mtd7": (0x0280000, 0x500000, False, True, 3, "kernel"),
|
||||
"mtd8": (0x0800000, 0x1400000, False, True, 1, "rootfs"),
|
||||
"mtd9": (0x1C00000, 0x200000, True, False, 0, None),
|
||||
"mtd10": (0x1E00000, 0x200000, True, False, 0, None),
|
||||
"mtd11": (0x2000000, 0x6000000, True, False, 0, None),
|
||||
}
|
||||
AM335X_HOLE = (0x780000, 0x80000)
|
||||
AM335X_CHIP = 0x8000000
|
||||
AM335X_TARGETS = {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_FORMATS = {"kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# Tier-3 from-stock: same map, mtd4 written with our U-Boot; kernel at order 4.
|
||||
AM335X_STOCK_MAP = dict(AM335X_MAP)
|
||||
AM335X_STOCK_MAP["mtd4"] = (0x0080000, 0x1C0000, False, True, 3, "u-boot")
|
||||
AM335X_STOCK_MAP["mtd7"] = (0x0280000, 0x500000, False, True, 4, "kernel")
|
||||
AM335X_STOCK_TARGETS = {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_STOCK_FORMATS = {"u-boot": "uimage", "kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_STOCK_CEILINGS = {"u-boot": 0x1C0000, "kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
AM335X_NEVER_WRITE = {"mtd0", "mtd1", "mtd2", "mtd3", "mtd5"}
|
||||
ZYNQ_FORMATS = {"kernel": "zimage", "dtb": "fdt", "rootfs": "cpio-gzip"}
|
||||
ZYNQ_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x2000000}
|
||||
A113D_FORMATS = {"kernel": "arm64-image", "dtb": "fdt", "rootfs": "uimage"}
|
||||
A113D_CEILINGS = {"kernel": 0x4000000, "dtb": 0x100000, "rootfs": 0x6000000}
|
||||
A113D_NVDATA_USABLE = 0xB900000
|
||||
|
||||
|
||||
class AfwError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise AfwError(message)
|
||||
|
||||
|
||||
def parse_octal(field, name):
|
||||
text = field.split(b"\0", 1)[0].strip()
|
||||
if not text:
|
||||
return 0
|
||||
if any(byte >= 0x80 for byte in text):
|
||||
fail(f"{name}: base-256 tar numbers are not part of this format")
|
||||
try:
|
||||
return int(text, 8)
|
||||
except ValueError:
|
||||
fail(f"{name}: invalid octal field")
|
||||
|
||||
|
||||
def safe_member_name(name):
|
||||
if not name or len(name) > 255:
|
||||
fail(f"unsafe member name length: {name!r}")
|
||||
if name.startswith("/") or name.startswith("./"):
|
||||
fail(f"absolute or ./-prefixed member is not allowed: {name!r}")
|
||||
if "\\" in name or "\0" in name:
|
||||
fail(f"member name contains a forbidden character: {name!r}")
|
||||
parts = name.split("/")
|
||||
if any(part in ("", ".", "..") for part in parts):
|
||||
fail(f"path traversal or empty component in member name: {name!r}")
|
||||
if any(ord(character) < 0x20 for character in name):
|
||||
fail(f"control character in member name: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
def read_tar(path):
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError as error:
|
||||
fail(f"cannot read {path}: {error}")
|
||||
if size == 0 or size > MAX_ARCHIVE:
|
||||
fail(f"archive size {size} is outside the accepted range")
|
||||
if size % BLOCK:
|
||||
fail(f"archive length {size} is not a multiple of {BLOCK} (truncated tar)")
|
||||
data = path.read_bytes()
|
||||
members = []
|
||||
offset = 0
|
||||
zero_blocks = 0
|
||||
while offset < len(data):
|
||||
block = data[offset : offset + BLOCK]
|
||||
offset += BLOCK
|
||||
if block == b"\0" * BLOCK:
|
||||
zero_blocks += 1
|
||||
if zero_blocks == 2:
|
||||
break
|
||||
continue
|
||||
if zero_blocks:
|
||||
fail("non-zero data appears between end-of-archive blocks")
|
||||
if block[257:262] != b"ustar":
|
||||
fail("member header is not POSIX ustar")
|
||||
stored = parse_octal(block[148:156], "tar checksum")
|
||||
header = bytearray(block)
|
||||
header[148:156] = b" " * 8
|
||||
if sum(header) != stored:
|
||||
fail("tar header checksum mismatch")
|
||||
name = block[0:100].split(b"\0", 1)[0].decode("utf-8", "strict")
|
||||
prefix = block[345:500].split(b"\0", 1)[0].decode("utf-8", "strict")
|
||||
if prefix:
|
||||
name = f"{prefix}/{name}"
|
||||
safe_member_name(name)
|
||||
typeflag = block[156:157]
|
||||
if typeflag not in (b"\0", b"0"):
|
||||
fail(f"member {name!r} is not a regular file (typeflag {typeflag!r})")
|
||||
length = parse_octal(block[124:136], f"size of {name}")
|
||||
if length > MAX_ARCHIVE:
|
||||
fail(f"member {name!r} is too large")
|
||||
padded = (length + BLOCK - 1) // BLOCK * BLOCK
|
||||
if offset + padded > len(data):
|
||||
fail(f"member {name!r} runs past the end of the archive (truncated tar)")
|
||||
payload = data[offset : offset + length]
|
||||
offset += padded
|
||||
members.append((name, payload))
|
||||
if zero_blocks < 2:
|
||||
fail("archive has no two-block end marker (truncated tar)")
|
||||
if any(data[offset:]):
|
||||
fail("non-zero trailing bytes after the end-of-archive marker")
|
||||
if not members:
|
||||
fail("archive has no members")
|
||||
names = [name for name, _ in members]
|
||||
if len(names) != len(set(names)):
|
||||
fail("archive has duplicate member names")
|
||||
return members
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
fail(message)
|
||||
|
||||
|
||||
def is_hex(value, length=64):
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and len(value) == length
|
||||
and all(character in "0123456789abcdef" for character in value)
|
||||
)
|
||||
|
||||
|
||||
def check_format(manifest, image, payload, name):
|
||||
fmt = image["format"]
|
||||
if fmt == "fit":
|
||||
require(payload.startswith(b"\xd0\x0d\xfe\xed"), f"{name} is not a FIT")
|
||||
require(b"config@cv1835_miner_emmc" in payload, f"{name} has no default CV config")
|
||||
require(b"signature@" not in payload, f"{name} carries signature@ nodes")
|
||||
elif fmt == "fdt":
|
||||
require(payload.startswith(b"\xd0\x0d\xfe\xed"), f"{name} is not an FDT")
|
||||
elif fmt == "arm64-image":
|
||||
require(len(payload) >= 64 and payload[0x38:0x3C] == b"ARMd", f"{name} is not an arm64 Image")
|
||||
elif fmt == "zimage":
|
||||
# ARM zImage: magic 0x016f2818 (little-endian) at offset 0x24.
|
||||
require(len(payload) >= 0x28 and payload[0x24:0x28] == b"\x18\x28\x6f\x01",
|
||||
f"{name} is not an ARM zImage")
|
||||
elif fmt == "cpio-gzip":
|
||||
require(payload.startswith(b"\x1f\x8b"), f"{name} is not gzip-compressed")
|
||||
elif fmt == "uimage":
|
||||
require(payload.startswith(b"\x27\x05\x19\x56"), f"{name} is not a legacy uImage")
|
||||
if manifest["board"] in ("am335x", "am335x-stock"):
|
||||
require(len(payload) >= 64, f"{name} has no complete uImage header")
|
||||
# ih_arch (byte 29) ARM = 2; ih_type (byte 30): kernel 2, ramdisk 3,
|
||||
# firmware (our U-Boot in mtd4) 5.
|
||||
require(payload[29] == 2, f"{name} is not an ARM uImage")
|
||||
if image["name"] == "rootfs" or image["role"] == "rootfs":
|
||||
require(payload[30] == 3, f"{name} must be a type-3 ramdisk uImage")
|
||||
elif image["name"] == "u-boot" or image["role"] == "bootloader":
|
||||
require(payload[30] == 5, f"{name} must be a type-5 firmware (U-Boot) uImage")
|
||||
else:
|
||||
require(payload[30] == 2, f"{name} must be a type-2 kernel uImage")
|
||||
|
||||
|
||||
def verify_signature(manifest_bytes, manifest, signature_member, public_key):
|
||||
signature = manifest.get("signature")
|
||||
require(isinstance(signature, dict), "manifest signature is not an object")
|
||||
kind = signature.get("type")
|
||||
if kind == "unsigned":
|
||||
require(signature_member is None, "unsigned manifest carries a signature member")
|
||||
require(signature.get("member") is None, "unsigned manifest names a signature member")
|
||||
return "unsigned"
|
||||
require(kind == "ed25519", f"unsupported signature type {kind!r}")
|
||||
require(signature.get("member") == "manifest.json.sig", "signature member name is wrong")
|
||||
require(signature_member is not None, "ed25519 manifest has no signature member")
|
||||
require(len(signature_member) == 64, "manifest.json.sig must be exactly 64 bytes")
|
||||
key_hex = public_key or signature.get("public_key_hex")
|
||||
require(is_hex(key_hex), "ed25519 manifest needs a 32-byte public key")
|
||||
if public_key and signature.get("public_key_hex") not in (None, public_key):
|
||||
fail("--public-key differs from the manifest public_key_hex")
|
||||
try:
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
except ImportError:
|
||||
fail("Ed25519 verification needs the Python cryptography package")
|
||||
try:
|
||||
Ed25519PublicKey.from_public_bytes(bytes.fromhex(key_hex)).verify(
|
||||
signature_member, manifest_bytes
|
||||
)
|
||||
except InvalidSignature:
|
||||
fail("manifest.json.sig does not verify against the public key")
|
||||
return "ed25519"
|
||||
|
||||
|
||||
def validate_am335x(manifest, images, partitions, install_images):
|
||||
require(manifest["arch"] == "arm", "am335x must be arm")
|
||||
require(
|
||||
manifest["bootloader_policy"] == "preserve",
|
||||
"am335x must preserve mtd0-5",
|
||||
)
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered,
|
||||
f"am335x bundle carries an spl/u-boot member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "am335x installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(AM335X_TARGETS),
|
||||
"am335x install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == AM335X_FORMATS[name],
|
||||
f"am335x {name} format must be {AM335X_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["partition"] == AM335X_TARGETS[name],
|
||||
f"am335x {name} must target {AM335X_TARGETS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= AM335X_CEILINGS[name],
|
||||
f"am335x {name} ({image['size']} B) exceeds the "
|
||||
f"0x{AM335X_CEILINGS[name]:x}-byte mtd ceiling",
|
||||
)
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
require(name in AM335X_MAP, f"unknown am335x partition {name!r}")
|
||||
if name not in AM335X_MAP:
|
||||
continue
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_MAP[name]
|
||||
require(partition["offset"] == offset, f"am335x {name} offset must be 0x{offset:x}")
|
||||
require(partition["size"] == size, f"am335x {name} size must be 0x{size:x}")
|
||||
require(partition["secure"] is secure, f"am335x {name} secure flag is wrong")
|
||||
require(
|
||||
partition["boot_critical"] is boot_critical,
|
||||
f"am335x {name} boot_critical flag is wrong",
|
||||
)
|
||||
require(
|
||||
partition["write_order"] == write_order,
|
||||
f"am335x {name} write_order must be {write_order}",
|
||||
)
|
||||
require(
|
||||
partition.get("image") == image_name,
|
||||
f"am335x {name} image must be {image_name!r}",
|
||||
)
|
||||
start = partition["offset"]
|
||||
end = start + partition["size"]
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
require(
|
||||
not (start < hole_start + hole_size and end > hole_start),
|
||||
f"am335x {name} overlaps the 0x780000-0x800000 hole",
|
||||
)
|
||||
if name in {f"mtd{index}" for index in range(0, 6)}:
|
||||
require(
|
||||
partition["write_order"] == 0 and partition.get("image") is None,
|
||||
f"am335x {name} is preserved and must not be written",
|
||||
)
|
||||
require(set(seen) == set(AM335X_MAP), "am335x manifest partition map is incomplete")
|
||||
require(
|
||||
seen["mtd7"]["offset"] + seen["mtd7"]["size"] == AM335X_HOLE[0],
|
||||
"am335x mtd7 must end at the 0x780000 hole",
|
||||
)
|
||||
require(
|
||||
seen["mtd8"]["offset"] == AM335X_HOLE[0] + AM335X_HOLE[1],
|
||||
"am335x mtd8 must start at 0x800000 after the hole",
|
||||
)
|
||||
total = sum(part["size"] for part in partitions)
|
||||
require(total == AM335X_CHIP - AM335X_HOLE[1], "am335x partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_am335x_stock(manifest, images, partitions, install_images):
|
||||
"""Tier-3 from-stock gate: the bundle writes mtd4 (our U-Boot) but must
|
||||
still never touch an SPL copy, and the geometry/ceilings/hole stay exact."""
|
||||
require(manifest["arch"] == "arm", "am335x-stock must be arm")
|
||||
require(
|
||||
manifest["bootloader_policy"] == "include",
|
||||
"am335x-stock must declare bootloader_policy include",
|
||||
)
|
||||
# A u-boot member is expected; a loose spl member never is.
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
require("spl" not in lowered, f"am335x-stock bundle carries an spl member: {image['file']!r}")
|
||||
require(len(install_images) == 4, "am335x-stock installs exactly u-boot, kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(AM335X_STOCK_TARGETS),
|
||||
"am335x-stock install images must be named u-boot, kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == AM335X_STOCK_FORMATS[name],
|
||||
f"am335x-stock {name} format must be {AM335X_STOCK_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["partition"] == AM335X_STOCK_TARGETS[name],
|
||||
f"am335x-stock {name} must target {AM335X_STOCK_TARGETS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= AM335X_STOCK_CEILINGS[name],
|
||||
f"am335x-stock {name} ({image['size']} B) exceeds the "
|
||||
f"0x{AM335X_STOCK_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
uboot = [image for image in install_images if image["name"] == "u-boot"][0]
|
||||
require(uboot["role"] == "bootloader", "am335x-stock u-boot image must have role bootloader")
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
require(name in AM335X_STOCK_MAP, f"unknown am335x-stock partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_STOCK_MAP[name]
|
||||
require(partition["offset"] == offset, f"am335x-stock {name} offset must be 0x{offset:x}")
|
||||
require(partition["size"] == size, f"am335x-stock {name} size must be 0x{size:x}")
|
||||
require(partition["secure"] is secure, f"am335x-stock {name} secure flag is wrong")
|
||||
require(
|
||||
partition["boot_critical"] is boot_critical,
|
||||
f"am335x-stock {name} boot_critical flag is wrong",
|
||||
)
|
||||
require(
|
||||
partition["write_order"] == write_order,
|
||||
f"am335x-stock {name} write_order must be {write_order}",
|
||||
)
|
||||
require(partition.get("image") == image_name, f"am335x-stock {name} image must be {image_name!r}")
|
||||
start = partition["offset"]
|
||||
end = start + partition["size"]
|
||||
if start < AM335X_HOLE[0] + AM335X_HOLE[1] and end > AM335X_HOLE[0]:
|
||||
fail(f"am335x-stock {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in AM335X_NEVER_WRITE and (write_order != 0 or partition.get("image") is not None):
|
||||
fail(f"am335x-stock {name} is preserved and must not be written")
|
||||
require(set(seen) == set(AM335X_STOCK_MAP), "am335x-stock manifest partition map is incomplete")
|
||||
require(
|
||||
seen["mtd7"]["offset"] + seen["mtd7"]["size"] == AM335X_HOLE[0],
|
||||
"am335x-stock mtd7 must end at the 0x780000 hole",
|
||||
)
|
||||
require(
|
||||
seen["mtd8"]["offset"] == AM335X_HOLE[0] + AM335X_HOLE[1],
|
||||
"am335x-stock mtd8 must start at 0x800000 after the hole",
|
||||
)
|
||||
total = sum(part["size"] for part in partitions)
|
||||
require(total == AM335X_CHIP - AM335X_HOLE[1], "am335x-stock partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate(path, allow_unsigned=False, public_key=None, expect_board=None, plan_path=None):
|
||||
members = read_tar(Path(path))
|
||||
if members[0][0] != "manifest.json":
|
||||
fail("first member must be manifest.json")
|
||||
manifest_bytes = members[0][1]
|
||||
if len(manifest_bytes) > MAX_MANIFEST:
|
||||
fail(f"manifest.json is {len(manifest_bytes)} bytes, over the 64 KiB cap")
|
||||
try:
|
||||
manifest = json.loads(manifest_bytes)
|
||||
except (ValueError, UnicodeDecodeError) as error:
|
||||
fail(f"manifest.json is not valid JSON: {error}")
|
||||
require(isinstance(manifest, dict), "manifest.json must be an object")
|
||||
|
||||
required = (
|
||||
"schema",
|
||||
"format",
|
||||
"board",
|
||||
"arch",
|
||||
"version",
|
||||
"build_date",
|
||||
"sdk_revision",
|
||||
"os_revision",
|
||||
"payload_type",
|
||||
"bootloader_policy",
|
||||
"signature",
|
||||
"partitions",
|
||||
"images",
|
||||
"boot_switch",
|
||||
"preflight",
|
||||
"recovery",
|
||||
"marker",
|
||||
"kernel_version",
|
||||
)
|
||||
for key in required:
|
||||
require(key in manifest, f"manifest is missing {key!r}")
|
||||
|
||||
require(manifest["schema"] == 2, "only .afw schema 2 is accepted")
|
||||
require(manifest["format"] == "afw", "manifest format is not afw")
|
||||
require(manifest["payload_type"] == "os", "payload_type must be os")
|
||||
board = manifest["board"]
|
||||
require(afw_boards.known_board(board), f"unknown board family {board!r}")
|
||||
profile = afw_boards.board(board)
|
||||
require(manifest["arch"] == profile["arch"], f"board {board} must use {profile['arch']}")
|
||||
require(
|
||||
manifest["bootloader_policy"] == profile["bootloader_policy"],
|
||||
f"board {board} requires bootloader_policy {profile['bootloader_policy']}",
|
||||
)
|
||||
require(
|
||||
manifest["bootloader_policy"] in ("include", "preserve"),
|
||||
"bootloader_policy must be include or preserve",
|
||||
)
|
||||
if expect_board is not None:
|
||||
require(board == expect_board, f"bundle is for {board}, expected {expect_board}")
|
||||
for field in ("sdk_revision", "os_revision"):
|
||||
require(is_hex(manifest[field], 40), f"{field} must be a 40-character revision")
|
||||
require(isinstance(manifest["version"], str) and manifest["version"], "version is empty")
|
||||
require(isinstance(manifest["build_date"], str) and manifest["build_date"], "build_date is empty")
|
||||
require(isinstance(manifest["marker"], str) and manifest["marker"], "marker is empty")
|
||||
require(
|
||||
isinstance(manifest["kernel_version"], str) and manifest["kernel_version"],
|
||||
"kernel_version is empty",
|
||||
)
|
||||
for field in ("boot_switch", "preflight", "recovery"):
|
||||
require(isinstance(manifest[field], dict), f"{field} must be an object")
|
||||
|
||||
images = manifest["images"]
|
||||
partitions = manifest["partitions"]
|
||||
require(isinstance(images, list) and images, "images must be a non-empty list")
|
||||
require(isinstance(partitions, list) and partitions, "partitions must be a non-empty list")
|
||||
|
||||
image_names = set()
|
||||
install_images = []
|
||||
for image in images:
|
||||
require(isinstance(image, dict), "image entry is not an object")
|
||||
for key in ("name", "file", "role", "format", "size", "sha256", "install"):
|
||||
require(key in image, f"image entry is missing {key!r}")
|
||||
name = image["name"]
|
||||
require(isinstance(name, str) and name and name not in image_names, f"duplicate image {name!r}")
|
||||
image_names.add(name)
|
||||
require(image["role"] in afw_boards.SAFE_IMAGE_ROLES, f"image {name} has an unknown role")
|
||||
require(image["format"] in afw_boards.SAFE_IMAGE_FORMATS, f"image {name} has an unknown format")
|
||||
require(isinstance(image["size"], int) and image["size"] > 0, f"image {name} has no size")
|
||||
require(is_hex(image["sha256"]), f"image {name} has no sha256")
|
||||
require(isinstance(image["install"], bool), f"image {name} install flag is not a bool")
|
||||
safe_member_name(image["file"])
|
||||
require(image["file"].startswith("payload/"), f"image {name} is outside payload/")
|
||||
require(image["file"] not in ("payload/manifest.json",), f"image {name} reuses a reserved name")
|
||||
if image["install"]:
|
||||
require(image.get("partition"), f"installable image {name} has no partition")
|
||||
install_images.append(image)
|
||||
|
||||
require(install_images, "bundle has no installable image")
|
||||
partition_names = set()
|
||||
for partition in partitions:
|
||||
require(isinstance(partition, dict), "partition entry is not an object")
|
||||
for key in ("name", "device", "offset", "size", "secure", "boot_critical", "write_order"):
|
||||
require(key in partition, f"partition entry is missing {key!r}")
|
||||
name = partition["name"]
|
||||
require(isinstance(name, str) and name and name not in partition_names, f"duplicate partition {name!r}")
|
||||
partition_names.add(name)
|
||||
device = partition["device"]
|
||||
require(isinstance(device, str) and device.startswith("/dev/"), f"partition {name} has a bad device")
|
||||
require(isinstance(partition["size"], int) and partition["size"] > 0, f"partition {name} has no size")
|
||||
require(partition["offset"] >= 0, f"partition {name} has a negative offset")
|
||||
require(isinstance(partition["secure"], bool), f"partition {name} secure is not a bool")
|
||||
require(isinstance(partition["boot_critical"], bool), f"partition {name} boot_critical is not a bool")
|
||||
require(isinstance(partition["write_order"], int) and partition["write_order"] >= 0, f"partition {name} write_order")
|
||||
if "boot0" in device:
|
||||
require(partition["secure"], "boot0 must be declared secure")
|
||||
require(partition["write_order"] == 0, "boot0 must not be in the write order")
|
||||
require(partition.get("image") is None, "boot0 must not carry an install image")
|
||||
image_name = partition.get("image")
|
||||
if image_name is not None:
|
||||
require(image_name in image_names, f"partition {name} names missing image {image_name!r}")
|
||||
|
||||
for image in images:
|
||||
if image.get("partition") is None:
|
||||
continue
|
||||
matches = [item for item in partitions if item["name"] == image["partition"]]
|
||||
require(len(matches) == 1, f"image {image['name']} names an unknown partition")
|
||||
partition = matches[0]
|
||||
require(not partition["secure"], f"image {image['name']} targets a secure partition")
|
||||
require(
|
||||
image["size"] <= partition["size"],
|
||||
f"image {image['name']} ({image['size']} B) exceeds partition "
|
||||
f"{partition['name']} ({partition['size']} B)",
|
||||
)
|
||||
|
||||
if board == "am335x":
|
||||
validate_am335x(manifest, images, partitions, install_images)
|
||||
|
||||
if board == "am335x-stock":
|
||||
validate_am335x_stock(manifest, images, partitions, install_images)
|
||||
|
||||
if board == "a113d":
|
||||
require(manifest["arch"] == "arm64", "a113d must be arm64")
|
||||
require(manifest["bootloader_policy"] == "preserve", "a113d must preserve the FIP bootloader")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image['role']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered
|
||||
and "fip" not in lowered and "tpl" not in lowered and image["role"] != "bootloader",
|
||||
f"a113d bundle carries a bootloader/spl/fip member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "a113d installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(A113D_FORMATS),
|
||||
"a113d install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
total = 0
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(image["format"] == A113D_FORMATS[name], f"a113d {name} format must be {A113D_FORMATS[name]}")
|
||||
require(
|
||||
image["size"] <= A113D_CEILINGS[name],
|
||||
f"a113d {name} ({image['size']} B) exceeds the 0x{A113D_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
total += image["size"]
|
||||
require(total <= A113D_NVDATA_USABLE, f"a113d images total {total} B exceed the nvdata UBI (0x{A113D_NVDATA_USABLE:x})")
|
||||
# Only nvdata (mtd6) may carry an image; mtd0-5 (FIP + stock boot) are preserved.
|
||||
for partition in partitions:
|
||||
if partition["name"] != "nvdata":
|
||||
require(partition.get("image") is None, f"a113d {partition['name']!r} is preserved and must not carry an image")
|
||||
|
||||
if board == "zynq-7010":
|
||||
require(manifest["arch"] == "armv7", "zynq-7010 must be armv7")
|
||||
require(manifest["bootloader_policy"] == "preserve", "zynq-7010 must preserve BOOT.bin")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image['role']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered
|
||||
and "boot.bin" not in lowered and image["role"] != "bootloader",
|
||||
f"zynq-7010 bundle carries a bootloader/spl member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "zynq-7010 installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(ZYNQ_FORMATS),
|
||||
"zynq-7010 install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == ZYNQ_FORMATS[name],
|
||||
f"zynq-7010 {name} format must be {ZYNQ_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= ZYNQ_CEILINGS[name],
|
||||
f"zynq-7010 {name} ({image['size']} B) exceeds the "
|
||||
f"0x{ZYNQ_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
|
||||
if board == "cv1835":
|
||||
require(len(install_images) == 1 and install_images[0]["name"] == "p1", "cv1835 installs only p1")
|
||||
p1 = install_images[0]
|
||||
require(p1["format"] == "fit", "cv1835 p1 must be a FIT")
|
||||
require(p1["size"] == 16 * 1024 * 1024, "cv1835 p1 must be the 16 MiB padded FIT")
|
||||
p1_parts = [item for item in partitions if item["name"] == "p1"]
|
||||
require(len(p1_parts) == 1, "cv1835 manifest must plan p1")
|
||||
require(p1_parts[0]["size"] == 16 * 1024 * 1024, "cv1835 p1 partition must be 16 MiB")
|
||||
require(p1_parts[0]["device"] == "/dev/mmcblk0p1", "cv1835 p1 device is wrong")
|
||||
require(not p1_parts[0]["secure"], "cv1835 p1 must not be secure")
|
||||
require(p1_parts[0]["write_order"] == 1, "cv1835 p1 must be written once")
|
||||
|
||||
if manifest["bootloader_policy"] == "preserve":
|
||||
require(
|
||||
not any(image["role"] == "bootloader" for image in images),
|
||||
"bootloader_policy is preserve but the bundle carries a bootloader image",
|
||||
)
|
||||
else:
|
||||
require(
|
||||
any(image["role"] == "bootloader" for image in images),
|
||||
"bootloader_policy is include but the bundle has no bootloader image",
|
||||
)
|
||||
|
||||
signature = manifest["signature"]
|
||||
require(isinstance(signature, dict), "signature must be an object")
|
||||
kind = signature.get("type")
|
||||
if kind == "unsigned":
|
||||
if not allow_unsigned:
|
||||
fail("bundle is unsigned; pass --allow-unsigned for bench-only use")
|
||||
elif kind != "ed25519":
|
||||
fail(f"unsupported signature type {kind!r}")
|
||||
|
||||
expected = [image["file"] for image in images]
|
||||
signature_member = None
|
||||
body = members[1:]
|
||||
if signature.get("member") is not None:
|
||||
require(len(body) >= 1 and body[0][0] == "manifest.json.sig", "signature member must be second")
|
||||
signature_member = body[0][1]
|
||||
body = body[1:]
|
||||
verify_signature(manifest_bytes, manifest, signature_member, public_key)
|
||||
actual = [name for name, _ in body]
|
||||
require(actual == expected, "payload members are missing, extra, or out of manifest order")
|
||||
|
||||
for (name, payload), image in zip(body, images):
|
||||
require(len(payload) == image["size"], f"size mismatch for {name}")
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
require(digest == image["sha256"], f"sha256 mismatch for {name}")
|
||||
check_format(manifest, image, payload, name)
|
||||
|
||||
summary = {
|
||||
"file": str(path),
|
||||
"board": board,
|
||||
"arch": manifest["arch"],
|
||||
"version": manifest["version"],
|
||||
"bootloader_policy": manifest["bootloader_policy"],
|
||||
"signature": kind,
|
||||
"marker": manifest["marker"],
|
||||
"kernel_version": manifest["kernel_version"],
|
||||
"members": [name for name, _ in members],
|
||||
"payloads": [
|
||||
{"name": image["name"], "file": image["file"], "size": image["size"], "sha256": image["sha256"]}
|
||||
for image in images
|
||||
],
|
||||
"install": [
|
||||
{
|
||||
"image": image["name"],
|
||||
"partition": image["partition"],
|
||||
"size": image["size"],
|
||||
}
|
||||
for image in install_images
|
||||
],
|
||||
}
|
||||
|
||||
if plan_path:
|
||||
plan = json.loads(Path(plan_path).read_text())
|
||||
require(plan.get("board") == board, "plan board differs from manifest board")
|
||||
require(plan.get("arch") == manifest["arch"], "plan arch differs from manifest arch")
|
||||
require(
|
||||
plan.get("bootloader_policy") == manifest["bootloader_policy"],
|
||||
"plan bootloader policy differs from manifest",
|
||||
)
|
||||
plan_parts = {item["name"]: item for item in plan.get("partitions", [])}
|
||||
for partition in partitions:
|
||||
if partition["name"] not in plan_parts:
|
||||
continue
|
||||
require(
|
||||
int(plan_parts[partition["name"]]["size"]) == partition["size"],
|
||||
f"plan size for {partition['name']} differs from the manifest",
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("afw")
|
||||
parser.add_argument("--allow-unsigned", action="store_true")
|
||||
parser.add_argument("--public-key", help="Ed25519 public key hex, or a file containing it")
|
||||
parser.add_argument("--expect-board")
|
||||
parser.add_argument("--plan", help="plan JSON to cross-check")
|
||||
parser.add_argument("--json", action="store_true")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
args = parser.parse_args()
|
||||
public_key = args.public_key
|
||||
if public_key and len(public_key) != 64:
|
||||
try:
|
||||
public_key = Path(public_key).read_text().strip()
|
||||
except OSError as error:
|
||||
parser.error(f"cannot read public key: {error}")
|
||||
try:
|
||||
summary = validate(
|
||||
Path(args.afw),
|
||||
allow_unsigned=args.allow_unsigned,
|
||||
public_key=public_key,
|
||||
expect_board=args.expect_board,
|
||||
plan_path=args.plan,
|
||||
)
|
||||
except AfwError as error:
|
||||
print(f"afw: FAIL {args.afw}: {error}", file=sys.stderr)
|
||||
return 1
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"afw: FAIL {args.afw}: {error}", file=sys.stderr)
|
||||
return 1
|
||||
if args.json:
|
||||
print(json.dumps(summary, indent=2))
|
||||
elif not args.quiet:
|
||||
print(f"afw: OK {args.afw}")
|
||||
print(
|
||||
f" board {summary['board']} arch {summary['arch']} version {summary['version']} "
|
||||
f"bootloader {summary['bootloader_policy']} signature {summary['signature']}"
|
||||
)
|
||||
print(f" marker {summary['marker']} kernel {summary['kernel_version']}")
|
||||
for item in summary["payloads"]:
|
||||
print(f" payload {item['name']}: {item['size']} B sha256 {item['sha256']}")
|
||||
for item in summary["install"]:
|
||||
print(f" install {item['image']} -> {item['partition']} ({item['size']} B)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Keep OS jobs on the verified Alkane runner image."""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = (ROOT / "ci/runner-image.txt").read_text().strip()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not re.fullmatch(
|
||||
r"gitea\.bluefla\.re/blueflare/alkane-ci@sha256:[0-9a-f]{64}", IMAGE
|
||||
):
|
||||
print("Runner image must be pinned by Gitea registry digest", file=sys.stderr)
|
||||
return 1
|
||||
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
|
||||
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
|
||||
for name, job in workflow.get("jobs", {}).items():
|
||||
if (job.get("runs-on") in {"alkane-fast", "alkane-pages"}
|
||||
and "secrets." in str(job)):
|
||||
print(f"{path.name}: {name} exposes a secret to the fast runner", file=sys.stderr)
|
||||
return 1
|
||||
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
|
||||
continue
|
||||
if job.get("container", {}).get("image") != IMAGE:
|
||||
print(f"{path.name}: {name} has a different runner image", file=sys.stderr)
|
||||
return 1
|
||||
print("OS runner image pins: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -55,8 +55,8 @@ def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if os.environ["GITHUB_EVENT_NAME"] not in ("schedule", "workflow_dispatch"):
|
||||
raise RuntimeError("badge publisher must run on a timer or manual dispatch")
|
||||
if os.environ["GITHUB_EVENT_NAME"] not in ("workflow_run", "workflow_dispatch"):
|
||||
raise RuntimeError("badge publisher must follow CI completion or manual dispatch")
|
||||
if os.environ["GITHUB_REF"] != "refs/heads/main":
|
||||
raise RuntimeError("badge publisher must use the main branch")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
|
||||
Regular → Executable
+135
-57
@@ -1,68 +1,146 @@
|
||||
#!/bin/sh
|
||||
# Build an .afw firmware package for one control board and architecture.
|
||||
#!/usr/bin/env bash
|
||||
# Build a full-OS .afw install bundle for one board family.
|
||||
#
|
||||
# Modelled on the Warden `.wfw` bundle (scada/flare-edge/docs/firmware-format.md):
|
||||
# one file, a strict POSIX ustar tar, a JSON manifest first, then the payload,
|
||||
# with the payload's size and sha256 in the manifest so the device can verify
|
||||
# before it touches flash.
|
||||
# A .afw is a strict POSIX ustar with members in this exact order:
|
||||
# manifest.json
|
||||
# manifest.json.sig (only for an Ed25519-signed bundle)
|
||||
# payload/<image>... (in manifest.images order)
|
||||
#
|
||||
# Differences from .wfw, both deliberate:
|
||||
# The manifest carries the board, arch, SDK/OS revisions, every image's size
|
||||
# and SHA-256, the partition plan, bootloader_policy, the network recovery path
|
||||
# and a liveness marker. ci/check-afw.py verifies the finished bundle before
|
||||
# this script returns success. There is no default signing key: unsigned is
|
||||
# allowed only with an explicit --allow-unsigned, and that is bench-only.
|
||||
#
|
||||
# * the payload is COMPRESSED (`payload.tar.gz`) because these images ship to
|
||||
# boards over metered links, and a firmware bundle is mostly redundant;
|
||||
# * the manifest carries `board` and `arch`, and both go in the file name, so a
|
||||
# bundle can never be mistaken for another board family. Flashing the wrong
|
||||
# family is how boards are lost.
|
||||
#
|
||||
# Signature: `.wfw` carries an Ed25519 detached signature. We have no release
|
||||
# key yet, so `.afw` currently ships `members=2` and says so in the manifest
|
||||
# (`signature: "unsigned"`). Do not claim integrity beyond the sha256 until a
|
||||
# key exists.
|
||||
#
|
||||
# usage: make-afw.sh BOARD ARCH VERSION INPUT_DIR [OUTPUT_DIR]
|
||||
# e.g. make-afw.sh am335x-bb armv7 0.1.0 /tmp/release
|
||||
set -eu
|
||||
# usage:
|
||||
# ci/make-afw.sh --board cv1835 --version 0.1.0 \
|
||||
# --input build/out/cv1835 --sdk-dir ../alkane-sdk \
|
||||
# --sdk-revision "$(git -C ../alkane-sdk rev-parse HEAD)" \
|
||||
# --os-revision "$(git rev-parse HEAD)" \
|
||||
# --output dist [--plan plan.json] [--signing-key FILE] [--allow-unsigned]
|
||||
set -euo pipefail
|
||||
|
||||
BOARD=${1:?board family, e.g. am335x-bb}
|
||||
ARCH=${2:?architecture, e.g. armv7 or aarch64}
|
||||
VERSION=${3:?version, e.g. 0.1.0}
|
||||
INPUT=${4:?directory holding the release files}
|
||||
OUTPUT=${5:-dist}
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
BOARD=
|
||||
VERSION=
|
||||
INPUT=
|
||||
OUTPUT=dist
|
||||
PLAN=
|
||||
SIGNING_KEY=
|
||||
SDK_DIR=
|
||||
SDK_REVISION=
|
||||
OS_REVISION=
|
||||
KERNEL_VERSION=
|
||||
ALLOW_UNSIGNED=0
|
||||
|
||||
usage() {
|
||||
sed -n '2,30p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
|
||||
exit "${1:-1}"
|
||||
}
|
||||
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--board) BOARD=${2:?--board needs a value}; shift 2 ;;
|
||||
--version) VERSION=${2:?--version needs a value}; shift 2 ;;
|
||||
--input) INPUT=${2:?--input needs a value}; shift 2 ;;
|
||||
--output) OUTPUT=${2:?--output needs a value}; shift 2 ;;
|
||||
--plan) PLAN=${2:?--plan needs a value}; shift 2 ;;
|
||||
--signing-key) SIGNING_KEY=${2:?--signing-key needs a value}; shift 2 ;;
|
||||
--sdk-dir) SDK_DIR=${2:?--sdk-dir needs a value}; shift 2 ;;
|
||||
--sdk-revision) SDK_REVISION=${2:?--sdk-revision needs a value}; shift 2 ;;
|
||||
--os-revision) OS_REVISION=${2:?--os-revision needs a value}; shift 2 ;;
|
||||
--kernel-version) KERNEL_VERSION=${2:?--kernel-version needs a value}; shift 2 ;;
|
||||
--allow-unsigned) ALLOW_UNSIGNED=1; shift ;;
|
||||
-h|--help) usage 0 ;;
|
||||
*) echo "make-afw: unknown argument: $1" >&2; usage 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$BOARD" ] || { echo "make-afw: --board is required" >&2; usage 2; }
|
||||
[ -n "$VERSION" ] || { echo "make-afw: --version is required" >&2; usage 2; }
|
||||
[ -n "$INPUT" ] || { echo "make-afw: --input is required" >&2; usage 2; }
|
||||
[ -d "$INPUT" ] || { echo "make-afw: input directory not found: $INPUT" >&2; exit 1; }
|
||||
|
||||
if [ -z "$SDK_REVISION" ] && [ -n "$SDK_DIR" ]; then
|
||||
SDK_REVISION=$(git -C "$SDK_DIR" rev-parse HEAD)
|
||||
fi
|
||||
if [ -z "$OS_REVISION" ]; then
|
||||
OS_REVISION=$(git -C "$ROOT" rev-parse HEAD)
|
||||
fi
|
||||
[ -n "$SDK_REVISION" ] || { echo "make-afw: --sdk-revision or --sdk-dir is required" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUTPUT"
|
||||
WORK=$(mktemp -d)
|
||||
OUTPUT="$(cd "$OUTPUT" && pwd)"
|
||||
WORK=$(mktemp -d "${TMPDIR:-/tmp}/make-afw.XXXXXX")
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# The payload is a tar of the release tree, gzipped at maximum.
|
||||
tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$WORK/payload.tar" -C "$INPUT" .
|
||||
gzip -9 -n -c "$WORK/payload.tar" > "$WORK/payload.tar.gz"
|
||||
|
||||
PAYLOAD_SIZE=$(wc -c < "$WORK/payload.tar.gz")
|
||||
PAYLOAD_SHA=$(sha256sum "$WORK/payload.tar.gz" | cut -d' ' -f1)
|
||||
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
cat > "$WORK/manifest.json" <<MANIFEST
|
||||
{
|
||||
"schema": 1,
|
||||
"format": "afw",
|
||||
"board": "$BOARD",
|
||||
"arch": "$ARCH",
|
||||
"version": "$VERSION",
|
||||
"build_date": "$BUILD_DATE",
|
||||
"compression": "gzip",
|
||||
"signature": "unsigned",
|
||||
"payload": {
|
||||
"file": "payload.tar.gz",
|
||||
"size": $PAYLOAD_SIZE,
|
||||
"sha256": "$PAYLOAD_SHA"
|
||||
}
|
||||
}
|
||||
MANIFEST
|
||||
MANIFEST_ARGS=(
|
||||
--board "$BOARD"
|
||||
--version "$VERSION"
|
||||
--input "$INPUT"
|
||||
--staging "$WORK"
|
||||
--sdk-revision "$SDK_REVISION"
|
||||
--os-revision "$OS_REVISION"
|
||||
--os-dir "$ROOT"
|
||||
)
|
||||
[ -n "$PLAN" ] && MANIFEST_ARGS+=(--plan "$PLAN")
|
||||
[ -n "$SIGNING_KEY" ] && MANIFEST_ARGS+=(--signing-key "$SIGNING_KEY")
|
||||
[ -n "$KERNEL_VERSION" ] && MANIFEST_ARGS+=(--kernel-version "$KERNEL_VERSION")
|
||||
python3 "$ROOT/ci/afw_manifest.py" "${MANIFEST_ARGS[@]}" >/dev/null
|
||||
|
||||
ARCH=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["arch"])' "$WORK/manifest.json")
|
||||
NAME="alkane-os-$VERSION-$BOARD-$ARCH.afw"
|
||||
(cd "$WORK" && tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$OUTPUT/$NAME" manifest.json payload.tar.gz)
|
||||
|
||||
MEMBERS="$WORK/members.txt"
|
||||
python3 - "$WORK" >"$MEMBERS" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
stage = Path(sys.argv[1])
|
||||
manifest = json.loads((stage / "manifest.json").read_text())
|
||||
members = ["manifest.json"]
|
||||
if manifest["signature"]["member"]:
|
||||
members.append(manifest["signature"]["member"])
|
||||
members.extend(image["file"] for image in manifest["images"])
|
||||
for member in members:
|
||||
if not (stage / member).is_file():
|
||||
raise SystemExit(f"staged member is missing: {member}")
|
||||
print("\n".join(members))
|
||||
PY
|
||||
|
||||
MTIME=()
|
||||
if [ -n "${SOURCE_DATE_EPOCH:-}" ]; then
|
||||
MTIME=(--mtime="@${SOURCE_DATE_EPOCH}")
|
||||
fi
|
||||
|
||||
tar --format=ustar --owner=0 --group=0 --numeric-owner "${MTIME[@]}" \
|
||||
--create --file "$OUTPUT/$NAME" -C "$WORK" -T "$MEMBERS"
|
||||
|
||||
GOT=$(tar -tf "$OUTPUT/$NAME")
|
||||
WANT=$(cat "$MEMBERS")
|
||||
if [ "$GOT" != "$WANT" ]; then
|
||||
echo "make-afw: FATAL: member order is wrong" >&2
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$WANT" "$GOT" >&2
|
||||
rm -f "$OUTPUT/$NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CHECK=(--expect-board "$BOARD")
|
||||
if [ -f "$WORK/manifest.pub" ]; then
|
||||
CHECK+=(--public-key "$(cat "$WORK/manifest.pub")")
|
||||
elif [ "$ALLOW_UNSIGNED" -eq 1 ]; then
|
||||
CHECK+=(--allow-unsigned)
|
||||
else
|
||||
echo "make-afw: unsigned bundle needs --allow-unsigned (bench-only)" >&2
|
||||
rm -f "$OUTPUT/$NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
python3 "$ROOT/ci/check-afw.py" "$OUTPUT/$NAME" "${CHECK[@]}"
|
||||
|
||||
# Emit a SHA256SUMS covering exactly this bundle, so the release artifact can
|
||||
# never drift from the file it describes. Overwrite, do not append.
|
||||
( cd "$OUTPUT" && sha256sum "$NAME" > SHA256SUMS )
|
||||
|
||||
printf '%s\n' "$OUTPUT/$NAME"
|
||||
printf 'board %s\narch %s\npayload %s bytes\nsha256 %s\n' \
|
||||
"$BOARD" "$ARCH" "$PAYLOAD_SIZE" "$PAYLOAD_SHA"
|
||||
|
||||
@@ -21,8 +21,12 @@ PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO
|
||||
|
||||
def run(*args: str, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=True)
|
||||
result = subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=False)
|
||||
if result.returncode:
|
||||
detail = result.stderr.strip()[:2000]
|
||||
raise RuntimeError(f"{args[0]} {args[1]} exited {result.returncode}: {detail}")
|
||||
return result
|
||||
|
||||
|
||||
def current_main_sha() -> str:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
Executable
+874
@@ -0,0 +1,874 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Offline tests for the .afw producer and the CI brick-prevention gate."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
MAKE = ROOT / "ci" / "make-afw.sh"
|
||||
CHECK = ROOT / "ci" / "check-afw.py"
|
||||
REVISION = "0" * 40
|
||||
P1 = 16 * 1024 * 1024
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
return subprocess.run(command, text=True, capture_output=True, **kwargs)
|
||||
|
||||
|
||||
def fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
image = bytearray(4096)
|
||||
image[0x38:0x3C] = b"ARMd"
|
||||
image[0x08:0x10] = (0x200000).to_bytes(8, "little")
|
||||
(directory / "Image").write_bytes(image)
|
||||
|
||||
dtb = bytearray(1024)
|
||||
dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "cv-alkane.dtb").write_bytes(dtb)
|
||||
|
||||
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs" + b"\0" * 64)
|
||||
|
||||
fit = bytearray(P1)
|
||||
fit[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
marker = b"config@cv1835_miner_emmc"
|
||||
fit[0x100 : 0x100 + len(marker)] = marker
|
||||
(directory / "alkane-cv1835-p1.fit").write_bytes(fit)
|
||||
return directory
|
||||
|
||||
|
||||
def build_afw(work, input_dir, name="good.afw", extra=()):
|
||||
output = work / "dist"
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(input_dir),
|
||||
"--output",
|
||||
str(output),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
def pack_members(directory, members, output):
|
||||
listing = output.with_suffix(".list")
|
||||
listing.write_text("\n".join(members) + "\n")
|
||||
result = run(
|
||||
[
|
||||
"tar",
|
||||
"--format=ustar",
|
||||
"--owner=0",
|
||||
"--group=0",
|
||||
"--numeric-owner",
|
||||
"--create",
|
||||
"--file",
|
||||
str(output),
|
||||
"-C",
|
||||
str(directory),
|
||||
"-T",
|
||||
str(listing),
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(result.stderr)
|
||||
listing.unlink()
|
||||
return output
|
||||
|
||||
|
||||
def rewrite_bundle(source, destination, edit_manifest=None, flip_payload=None):
|
||||
"""Unpack a bundle, edit the manifest or payload, and repack it strictly."""
|
||||
work = destination.parent / (destination.name + ".unpack")
|
||||
if work.exists():
|
||||
shutil.rmtree(work)
|
||||
work.mkdir()
|
||||
with tarfile.open(source, "r:") as archive:
|
||||
names = archive.getnames()
|
||||
archive.extractall(work)
|
||||
manifest_path = work / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
if edit_manifest is not None:
|
||||
edit_manifest(manifest, work)
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
members = ["manifest.json"]
|
||||
if manifest["signature"]["member"]:
|
||||
members.append(manifest["signature"]["member"])
|
||||
members.extend(image["file"] for image in manifest["images"])
|
||||
if flip_payload:
|
||||
for member in members:
|
||||
if member in ("manifest.json", "manifest.json.sig"):
|
||||
continue
|
||||
path = work / member
|
||||
if path.is_file():
|
||||
data = bytearray(path.read_bytes())
|
||||
if data:
|
||||
data[len(data) // 2] ^= 0x01
|
||||
path.write_bytes(data)
|
||||
break
|
||||
pack_members(work, members, destination)
|
||||
shutil.rmtree(work)
|
||||
return destination
|
||||
|
||||
|
||||
class AfwTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="afw-test."))
|
||||
self.input = fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_bundle_passes_and_reports_install(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "cv1835")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("install p1 -> p1", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
summary = json.loads(result.stdout)
|
||||
self.assertEqual(summary["board"], "cv1835")
|
||||
self.assertEqual(summary["arch"], "arm64")
|
||||
self.assertEqual(summary["install"][0]["size"], P1)
|
||||
|
||||
def test_unsigned_bundle_needs_the_flag(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("unsigned", result.stderr)
|
||||
|
||||
def test_one_byte_tampered_payload_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
tampered = rewrite_bundle(bundle, self.temp / "tampered.afw", flip_payload=True)
|
||||
result = self.check(tampered, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("sha256 mismatch", result.stderr)
|
||||
|
||||
def test_wrong_board_is_refused(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("expected zynq-7010", result.stderr)
|
||||
|
||||
def test_manifest_cannot_claim_a_different_arch(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["arch"] = "armv7"
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("must use arm64", result.stderr)
|
||||
|
||||
def test_truncated_tar_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
truncated = self.temp / "truncated.afw"
|
||||
truncated.write_bytes(bundle.read_bytes()[:100])
|
||||
result = self.check(truncated, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("truncated", result.stderr)
|
||||
|
||||
def test_traversal_member_fails(self):
|
||||
stage = self.temp / "traversal"
|
||||
stage.mkdir()
|
||||
(stage / "manifest.json").write_text("{}\n")
|
||||
(stage / "payload").mkdir()
|
||||
(stage / "payload" / "p1.fit").write_bytes(b"\xd0\x0d\xfe\xed")
|
||||
bundle = self.temp / "traversal.afw"
|
||||
import io
|
||||
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, data in (
|
||||
("manifest.json", b"{}\n"),
|
||||
("payload/../escape", b"x"),
|
||||
):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
result = self.check(bundle, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("traversal", result.stderr)
|
||||
|
||||
def test_oversize_fit_is_refused_by_producer(self):
|
||||
fit = self.input / "alkane-cv1835-p1.fit"
|
||||
data = fit.read_bytes()
|
||||
fit.write_bytes(data + b"\0")
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_oversize_fit_is_refused_by_checker(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"][-1]["size"] = P1 + 1
|
||||
manifest["images"][-1]["sha256"] = "0" * 64
|
||||
path = work / manifest["images"][-1]["file"]
|
||||
path.write_bytes(path.read_bytes() + b"\0")
|
||||
|
||||
oversize = rewrite_bundle(bundle, self.temp / "oversize.afw", edit_manifest=edit)
|
||||
result = self.check(oversize, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("exceeds partition", result.stderr)
|
||||
|
||||
def test_bootloader_member_under_preserve_is_refused(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append(
|
||||
{
|
||||
"name": "u-boot",
|
||||
"file": "payload/u-boot.img",
|
||||
"role": "bootloader",
|
||||
"format": "uimage",
|
||||
"size": 4,
|
||||
"sha256": "0" * 64,
|
||||
"partition": None,
|
||||
"install": False,
|
||||
}
|
||||
)
|
||||
(work / "payload" / "u-boot.img").write_bytes(b"\x27\x05\x19\x56")
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "bootloader.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("preserve", result.stderr)
|
||||
|
||||
def test_hash_mismatch_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["images"][0]["sha256"] = "1" * 64
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "hash.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("sha256 mismatch", result.stderr)
|
||||
|
||||
def test_missing_image_fails_producer(self):
|
||||
(self.input / "Image").unlink()
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("required image is missing", result.stderr)
|
||||
|
||||
def test_plan_size_cross_check(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
plan = self.temp / "plan.json"
|
||||
plan.write_text(json.dumps({
|
||||
"board": "cv1835",
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"partitions": [{"name": "p1", "size": P1}],
|
||||
}))
|
||||
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
plan.write_text(json.dumps({
|
||||
"board": "cv1835",
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"partitions": [{"name": "p1", "size": P1 - 1}],
|
||||
}))
|
||||
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("differs from the manifest", result.stderr)
|
||||
|
||||
def test_unknown_board_fails(self):
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"whatsminer-h6",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("unknown board family", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
|
||||
AM_KERNEL_MAX = 0x500000
|
||||
AM_ROOT_MAX = 0x1400000
|
||||
|
||||
|
||||
def uimage_header(kind, payload=b"payload"):
|
||||
header = bytearray(64)
|
||||
header[0:4] = b"\x27\x05\x19\x56"
|
||||
header[12:16] = len(payload).to_bytes(4, "big")
|
||||
header[29] = 2 # ARM
|
||||
header[30] = kind # 2 kernel, 3 ramdisk
|
||||
header[31] = 0 if kind == 2 else 1
|
||||
header[32:48] = b"alkane-am335x\0\0\0"
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
def am_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "alkane-am335x.uImage").write_bytes(uimage_header(2, b"kernel"))
|
||||
dtb = bytearray(2048)
|
||||
dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "am335x-alkane.dtb").write_bytes(dtb)
|
||||
(directory / "alkane-am335x-ramdisk.uImage").write_bytes(
|
||||
uimage_header(3, b"ramdisk")
|
||||
)
|
||||
return directory
|
||||
|
||||
|
||||
def build_am_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-am"
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"am335x",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(input_dir),
|
||||
"--output",
|
||||
str(output),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class Am335xAfwTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="am335x-afw-test."))
|
||||
self.input = am_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_bundle_passes_and_reports_three_installs(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("board am335x arch arm", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
summary = json.loads(result.stdout)
|
||||
installs = {item["image"]: item["partition"] for item in summary["install"]}
|
||||
self.assertEqual(
|
||||
installs, {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
)
|
||||
|
||||
def test_oversize_kernel_is_refused_by_producer(self):
|
||||
path = self.input / "alkane-am335x.uImage"
|
||||
path.write_bytes(path.read_bytes() + b"\0" * (AM_KERNEL_MAX + 1))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_oversize_root_is_refused_by_producer(self):
|
||||
path = self.input / "alkane-am335x-ramdisk.uImage"
|
||||
path.write_bytes(path.read_bytes() + b"\0" * (AM_ROOT_MAX + 1))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_u_boot_member_under_preserve_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append(
|
||||
{
|
||||
"name": "u-boot",
|
||||
"file": "payload/u-boot.img",
|
||||
"role": "component",
|
||||
"format": "uimage",
|
||||
"size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
|
||||
"partition": None,
|
||||
"install": False,
|
||||
}
|
||||
)
|
||||
(work / "payload" / "u-boot.img").write_bytes(b"boot")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "uboot.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("u-boot", result.stderr)
|
||||
|
||||
def test_manifest_cannot_claim_arm64(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["arch"] = "arm64"
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("must use arm", result.stderr)
|
||||
|
||||
def test_mtd4_write_target_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd4":
|
||||
part["write_order"] = 1
|
||||
part["image"] = "kernel"
|
||||
part["secure"] = False
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "mtd4.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("mtd4", result.stderr)
|
||||
|
||||
def test_offset_in_the_0x780000_hole_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd8":
|
||||
part["offset"] = 0x780000
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "hole.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("hole", result.stderr)
|
||||
|
||||
def test_ramdisk_must_be_type_3(self):
|
||||
(self.input / "alkane-am335x-ramdisk.uImage").write_bytes(
|
||||
uimage_header(2, b"not-a-ramdisk")
|
||||
)
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("type-3 ramdisk", result.stderr)
|
||||
|
||||
def test_truncated_tar_fails(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
truncated = self.temp / "truncated.afw"
|
||||
truncated.write_bytes(bundle.read_bytes()[:100])
|
||||
result = self.check(truncated, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("truncated", result.stderr)
|
||||
|
||||
def test_traversal_member_fails(self):
|
||||
import io
|
||||
|
||||
bundle = self.temp / "traversal.afw"
|
||||
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, data in (
|
||||
("manifest.json", b"{}\n"),
|
||||
("payload/../escape", b"x"),
|
||||
):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
result = self.check(bundle, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("traversal", result.stderr)
|
||||
|
||||
def test_plan_json_cross_check(self):
|
||||
sdk = Path("/home/noah/projects/alkane-sdk")
|
||||
plan_yaml = sdk / "install" / "plans" / "am335x.yaml"
|
||||
if not plan_yaml.is_file():
|
||||
self.skipTest("alkane-sdk am335x plan not present")
|
||||
plan_json = self.temp / "am335x-plan.json"
|
||||
result = run(
|
||||
[
|
||||
sys.executable, str(sdk / "ci" / "check-plans.py"),
|
||||
"--plan", str(plan_yaml), "--emit-json", str(plan_json),
|
||||
]
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
bundle = build_am_afw(
|
||||
self.temp, self.input, extra=("--plan", str(plan_json))
|
||||
)
|
||||
result = self.check(
|
||||
bundle, "--allow-unsigned", "--plan", str(plan_json)
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
def am_stock_fixture_input(directory):
|
||||
"""The tier-3 from-stock input: adds our U-Boot (firmware uImage, type 5)
|
||||
alongside the kernel/dtb/ramdisk."""
|
||||
am_fixture_input(directory)
|
||||
(directory / "alkane-am335x-uboot-mtd4.uImage").write_bytes(
|
||||
uimage_header(5, b"u-boot")
|
||||
)
|
||||
return directory
|
||||
|
||||
|
||||
def build_am_stock_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-am-stock"
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class Am335xStockAfwTests(unittest.TestCase):
|
||||
"""Tier-3 from-stock bundle: writes U-Boot to mtd4 but must still refuse
|
||||
every SPL write and a wrongly-typed U-Boot member."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="am335x-stock-afw-test."))
|
||||
self.input = am_stock_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_stock_bundle_passes_with_four_installs(self):
|
||||
bundle = build_am_stock_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x-stock")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader include", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
installs = {item["image"]: item["partition"] for item in json.loads(result.stdout)["install"]}
|
||||
self.assertEqual(
|
||||
installs, {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
)
|
||||
|
||||
def test_u_boot_member_must_be_firmware_type(self):
|
||||
# A U-Boot payload wrongly built as a type-2 kernel uImage must be caught.
|
||||
(self.input / "alkane-am335x-uboot-mtd4.uImage").write_bytes(uimage_header(2, b"u-boot"))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("firmware", result.stderr + result.stdout)
|
||||
|
||||
def test_making_an_spl_copy_a_write_target_is_refused(self):
|
||||
bundle = build_am_stock_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd0":
|
||||
part["secure"] = False
|
||||
part["write_order"] = 5
|
||||
part["image"] = "u-boot"
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "spl-write.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("mtd0", result.stderr)
|
||||
|
||||
|
||||
def zimage_blob(payload=b"zkernel"):
|
||||
# ARM zImage: magic 0x016f2818 (LE) at offset 0x24.
|
||||
b = bytearray(64)
|
||||
b[0x24:0x28] = b"\x18\x28\x6f\x01"
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def zynq_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "zImage").write_bytes(zimage_blob())
|
||||
dtb = bytearray(1024); dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "zynq-alkane.dtb").write_bytes(dtb)
|
||||
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs")
|
||||
return directory
|
||||
|
||||
|
||||
def build_zynq_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-zynq"
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra])
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class ZynqAfwTests(unittest.TestCase):
|
||||
"""zynq-7010 tier-2 bundle: kernel(zImage)/dtb/rootfs, BOOT.bin preserved."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="zynq-afw-test."))
|
||||
self.input = zynq_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_zynq_bundle_passes(self):
|
||||
bundle = build_zynq_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
|
||||
def test_non_zimage_kernel_is_refused(self):
|
||||
(self.input / "zImage").write_bytes(b"\x00" * 4096) # no zImage magic
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "d"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("zImage", result.stderr + result.stdout)
|
||||
|
||||
def test_oversize_kernel_is_refused(self):
|
||||
(self.input / "zImage").write_bytes(zimage_blob(b"\x00" * (0x500000 + 1)))
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "d"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("ceiling", result.stderr + result.stdout)
|
||||
|
||||
def test_bootloader_member_is_refused(self):
|
||||
bundle = build_zynq_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append({
|
||||
"name": "u-boot", "file": "payload/BOOT.bin", "role": "bootloader",
|
||||
"format": "raw", "size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
|
||||
"partition": None, "install": False,
|
||||
})
|
||||
(work / "payload" / "BOOT.bin").write_bytes(b"boot")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "bl.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
|
||||
|
||||
def arm64_image_blob(payload=b"a64kernel"):
|
||||
# arm64 Linux Image: ASCII "ARMd" at offset 0x38.
|
||||
b = bytearray(64)
|
||||
b[0x38:0x3C] = b"ARMd"
|
||||
b[0x08:0x10] = (0x200000).to_bytes(8, "little") # text_offset / image_size hint
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def uramdisk_blob(payload=b"ramdisk"):
|
||||
# legacy uImage ramdisk (magic 0x27051956); a113d does not enforce arch/type.
|
||||
b = bytearray(64)
|
||||
b[0:4] = b"\x27\x05\x19\x56"
|
||||
b[12:16] = len(payload).to_bytes(4, "big")
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def a113d_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "vmlinux.bin").write_bytes(arm64_image_blob())
|
||||
dtb = bytearray(2048); dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "devicetree.dtb").write_bytes(bytes(dtb))
|
||||
(directory / "uramdisk.image.gz").write_bytes(uramdisk_blob())
|
||||
return directory
|
||||
|
||||
|
||||
def build_a113d_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-a113d"
|
||||
result = run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra])
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class A113dAfwTests(unittest.TestCase):
|
||||
"""a113d tier-2 bundle: kernel/dtb/rootfs staged into nvdata; FIP + mtd0-5 preserved."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="a113d-afw-test."))
|
||||
self.input = a113d_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def make(self, outdir="d"):
|
||||
return run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / outdir),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
|
||||
def test_good_a113d_bundle_passes_and_preserves(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "a113d")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
# all three images install into the nvdata UBI, never a raw mtd0-5 write
|
||||
self.assertEqual(result.stdout.count("-> nvdata"), 3)
|
||||
|
||||
def test_non_arm64_kernel_is_refused(self):
|
||||
(self.input / "vmlinux.bin").write_bytes(b"\x00" * 4096) # no ARMd magic
|
||||
result = self.make()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("arm64", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_oversize_kernel_is_refused(self):
|
||||
(self.input / "vmlinux.bin").write_bytes(arm64_image_blob(b"\x00" * (0x4000000 + 1)))
|
||||
result = self.make()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("ceiling", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_fip_member_is_refused(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append({
|
||||
"name": "fip", "file": "payload/fip.bin", "role": "bootloader",
|
||||
"format": "raw", "size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"fip!").hexdigest(),
|
||||
"partition": None, "install": False,
|
||||
})
|
||||
(work / "payload" / "fip.bin").write_bytes(b"fip!")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "fip.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("fip", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_preserved_mtd_carrying_an_image_is_refused(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
for partition in manifest["partitions"]:
|
||||
if partition["name"] != "nvdata":
|
||||
partition["image"] = "kernel" # try to aim a write at the FIP side
|
||||
break
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "pre.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("preserved", (result.stderr + result.stdout).lower())
|
||||
@@ -36,7 +36,7 @@ assert b">fail</text>" in svg
|
||||
assert b"#d1242f" in svg
|
||||
assert b">pass</text>" in module.badge("next", "success", 108)
|
||||
environment = {
|
||||
"GITHUB_EVENT_NAME": "schedule",
|
||||
"GITHUB_EVENT_NAME": "workflow_run",
|
||||
"GITHUB_REF": "refs/heads/main",
|
||||
"GITHUB_REPOSITORY": "owner/repo",
|
||||
"GITHUB_API_URL": "https://example.invalid/api/v1",
|
||||
@@ -49,13 +49,19 @@ with patch.dict(os.environ, environment), \
|
||||
module.main()
|
||||
assert latest.call_count == 2
|
||||
assert [call.args[2] for call in published.call_args_list] == ["main", "next"]
|
||||
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "workflow_run"}):
|
||||
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "workflow_dispatch"}), \
|
||||
patch.object(module, "latest_completed", side_effect=[(201, "success"),
|
||||
(202, "failure")]), \
|
||||
patch.object(module, "publish") as published:
|
||||
module.main()
|
||||
assert published.call_count == 2
|
||||
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "schedule"}):
|
||||
try:
|
||||
module.main()
|
||||
except RuntimeError as error:
|
||||
assert "timer or manual dispatch" in str(error)
|
||||
assert "CI completion or manual dispatch" in str(error)
|
||||
else:
|
||||
raise AssertionError("workflow_run event entered badge publisher")
|
||||
raise AssertionError("scheduled event entered badge publisher")
|
||||
for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"):
|
||||
try:
|
||||
publish_file("https://example.invalid/api/v1", "owner/repo", invalid,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# Code review report - alkane-os console/bus/login/dashboard/image
|
||||
|
||||
Scope: today's work on `feature/afw-os-bundle` (bus, registry, service, web, console,
|
||||
app, main, control, runtime, tuning, auth, dashboard, schema menus, image tooling).
|
||||
Method: code-review-harness, 4 parallel reviewers (correctness, security, reliability,
|
||||
maintainability) at high reasoning effort over the branch diff, then fixes applied and
|
||||
re-verified. Installation-from-stock / restore-to-stock method tooling was out of scope
|
||||
(DeepSeek Harness's domain; not in this repo).
|
||||
|
||||
## Verdict: READY TO SHIP (software checkpoint)
|
||||
|
||||
No Critical or High findings. The HTTP parser, login/session gate, bus semantics, and the
|
||||
crypto (HMAC-SHA256 / PBKDF2 / SHA-256 against RFC 4231 / RFC 7914 vectors) were verified
|
||||
correct; the session gate cannot be bypassed. Every Medium finding has been fixed and
|
||||
re-verified. Remaining items are Low / maintainability and are listed as deferred.
|
||||
|
||||
External tooling: `cargo clippy --all-targets -- -D warnings` clean; 206 lib tests + all
|
||||
integration tests pass; no emojis.
|
||||
|
||||
## Fixed in this pass
|
||||
|
||||
Security
|
||||
- `/api/files` and `/api/file` were reachable with a session but no token, contradicting
|
||||
the module docs and the Security page (arbitrary root-readable file exfiltration). Now
|
||||
token-gated via `authorised()`, matching the advertised control. (web.rs)
|
||||
- Response/header-splitting: `__section`/`__tab` from the settings form were interpolated
|
||||
into the `Location:` header; `%0d%0a` decoded to CRLF. Now constrained to safe slugs
|
||||
(`safe_slug`) before the redirect. (web.rs)
|
||||
- RNG degradation: an unreadable `/dev/urandom` substituted the published constant
|
||||
`"dev-csrf-token"` and second-granular, guessable session ids. Now a single token source
|
||||
(`auth::rand_hex`) that warns loudly and falls back to a per-call, non-constant mix; the
|
||||
CSRF generator delegates to it. (auth.rs, web.rs)
|
||||
- The UI token was compared with `==` (timing oracle). Now `auth::ct_eq` (constant time).
|
||||
(web.rs)
|
||||
- `auth.json` (password hash) was written umask-default (world-readable). Now created 0600
|
||||
with the parent dir 0700. (auth.rs)
|
||||
- Unbounded thread-per-connection + no absolute read deadline (flood DoS on the open :80).
|
||||
Now a 64-connection cap (503 beyond it) and a 10 s head-read deadline, on top of the
|
||||
per-read timeout. (web.rs)
|
||||
|
||||
Reliability / correctness
|
||||
- Settings persistence swallowed its write error and reported success with a misleading
|
||||
comment. Now the error propagates (surfaced as the form's rejection) and the write is
|
||||
atomic (temp + rename). Deck save is atomic too. (dashboard.rs, service.rs)
|
||||
- `Auth::login` returned a cookie even if the session insert failed (redirect loop). Now
|
||||
returns `None` on a poisoned lock. (auth.rs)
|
||||
- `TuningLoop::set_target` carried the PID integral across modes whose error is in
|
||||
different units (watts vs millidegrees vs TH/s), injecting a stale push on a mode switch.
|
||||
Now the accumulator resets on a target change while the operating point is kept. (tuning.rs)
|
||||
- Editable-deck JS: new-block ids collided after remove-then-add (duplicate ids, both
|
||||
deleted on remove); the default new-block source `power_w` wasn't in the live-value map
|
||||
(rendered n/a); drag-drop placement was asymmetric; save didn't re-render the normalized
|
||||
doc. All fixed. (console.rs)
|
||||
- Drivers page showed `"temperature"` with JSON quotes for the stopped reason. Now the bare
|
||||
string. (web.rs)
|
||||
|
||||
Maintainability
|
||||
- `percent_decode` / form-field parsing existed in three divergent copies; consolidated into
|
||||
one `form` module used by web, service and dashboard. The CSPRNG-to-hex helper is now one
|
||||
function (`auth::rand_hex`).
|
||||
- Added a test asserting the published state topics match the registry contract (the
|
||||
"single source of truth" claim for topics was previously unenforced).
|
||||
|
||||
## Deferred (reported, not blocking)
|
||||
|
||||
- `ui.rs` is now largely dead: only `validate_deck` / `default_deck` (+ two consts) are used
|
||||
(by `service.rs`); the legacy console (`page`, `dashboard_page`, `sidebar`, `NAV`, the CSS/JS
|
||||
consts, `icon`/`group_icon_svg` which `Box::leak`) has no callers. Recommend moving the two
|
||||
deck helpers to a `deck` module and deleting the rest. (~34 KB)
|
||||
- `control::target_label` vs `app::target_label` are two implementations of the same mapping;
|
||||
recommend one canonical (e.g. in `tuning`).
|
||||
- `DECK_CSS` / `DECK_JS` / `TERMINAL_JS` are large inline strings; recommend moving to
|
||||
`assets/*.js|css`, `include_str!`, and serving under `/assets` like the stylesheets, so they
|
||||
can be linted.
|
||||
- `web.rs` still owns host-fact gatherers (`system_rows`, ...) that `console.rs` consumes;
|
||||
recommend a `hostfacts` module both depend on.
|
||||
- `route()` is long; the `/api/*` arm could be an `api_route()`.
|
||||
- `Dashboard::page()` is now test-only (console renders pages); remove or mark reference-only.
|
||||
- serve_sim's control loop spins silently if the in-process HAL thread dies; recommend
|
||||
surfacing the fault and dropping `running` (the real-hardware `boot_hal` loop already exits
|
||||
on a HAL write error, so this is dev-path only).
|
||||
- `make-zynq-afw.sh` usage comment omits `--sdk-dir` (doc drift).
|
||||
- No change-password route exists though the login page tells the operator to change
|
||||
admin/admin; wire one or soften the text.
|
||||
|
||||
## Accepted-by-design posture (stated, not defects)
|
||||
|
||||
The box is SSH-guarded and the console is defense-in-depth on a shared network:
|
||||
- No TLS: the console is HTTP on `0.0.0.0:80`, so a passive sniffer can capture the password
|
||||
and session cookie. This is the dominant residual risk and should be made explicit to the
|
||||
operator. A TLS front (or binding the console to a management interface / WireGuard) is the
|
||||
real mitigation.
|
||||
- Factory `admin`/`admin` with nothing forcing a change; the login page prints it.
|
||||
- `/api/terminal` is a gated (session + token) root `/bin/sh` - an accepted diagnostic on an
|
||||
already-root-reachable box. Note the shipped terminal UI does not send the token, so it is
|
||||
fail-closed/unusable until a token is supplied.
|
||||
- The web process runs as root (binds 80); consider a post-bind privilege drop.
|
||||
- `/api/hardware|summary|control` are intentionally open (interface of record, mirror of the
|
||||
cgminer socket).
|
||||
- PBKDF2 at 50k iterations - low by modern standards, accepted behind SSH; matters only if the
|
||||
hash leaks (now 0600).
|
||||
- `make-zynq-afw.sh` always passes `--allow-unsigned` (bench-only helper; do not reuse on a
|
||||
release path).
|
||||
|
||||
## Verification after fixes
|
||||
|
||||
Live `--serve-sim`: unauthenticated GET / serves the login page; admin/admin issues a session
|
||||
and the console renders; `/api/files` returns 403 without a token; a CRLF-injected `__section`
|
||||
is neutralized (303, no header split); the editable deck saves and reloads. clippy -D warnings
|
||||
clean; 206 lib tests + integration pass.
|
||||
@@ -0,0 +1,179 @@
|
||||
# .afw OS install bundle format
|
||||
|
||||
Status: schema 2. Released only by `alkane-os`. One `.afw` is valid for exactly
|
||||
one board family.
|
||||
|
||||
An `.afw` is a full OS install bundle: kernel, device tree, rootfs, the
|
||||
bootable image(s), the partition plan, the boot switch, the preflight rules and
|
||||
the network recovery path. It is not an application package.
|
||||
|
||||
## Container
|
||||
|
||||
A strict POSIX ustar archive. No compression, no directory entries, no leading
|
||||
`./`, no GNU long-name or pax members, and no links. Members are, in this exact
|
||||
order:
|
||||
|
||||
1. `manifest.json`
|
||||
2. `manifest.json.sig` (only for an Ed25519-signed bundle)
|
||||
3. Each payload member named by `manifest.images[].file`, in manifest order.
|
||||
|
||||
Every member is a regular file. The manifest is at most 64 KiB. The verifier
|
||||
reads the tar itself: it checks the header checksum, rejects path traversal,
|
||||
absolute paths, duplicate names, non-regular members and truncated archives,
|
||||
and requires the two-block end marker. It verifies the manifest and every
|
||||
payload hash before any consumer may write to a board.
|
||||
|
||||
## Manifest
|
||||
|
||||
Required members:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `schema` | `2` |
|
||||
| `format` | `afw` |
|
||||
| `board` | One board family, for example `cv1835` |
|
||||
| `arch` | `arm64` or `armv7`; must match the board profile |
|
||||
| `version` | Release version |
|
||||
| `build_date` | UTC ISO-8601 |
|
||||
| `sdk_revision` | 40-character SDK git revision |
|
||||
| `os_revision` | 40-character alkane-os git revision |
|
||||
| `payload_type` | `os` |
|
||||
| `bootloader_policy` | `include` or `preserve` |
|
||||
| `signature` | Signature object, see below |
|
||||
| `partitions` | Partition plan, see below |
|
||||
| `images` | Payload images, see below |
|
||||
| `boot_switch` | How the preserved or written boot path selects the new OS |
|
||||
| `preflight` | Required commands, forbidden devices, free space, source OS list |
|
||||
| `recovery` | Network recovery command, held partition, golden copy location |
|
||||
| `marker` | String served by the installed OS, used by `afw verify-live` |
|
||||
| `kernel_version` | Kernel release the installed OS must report |
|
||||
|
||||
`notes` is optional. Unknown keys are ignored by this schema so a future field
|
||||
does not break old readers.
|
||||
|
||||
### Images
|
||||
|
||||
Each image entry has `name`, `file`, `role`, `format`, `size`, `sha256`,
|
||||
`partition` (or null) and `install` (bool). Roles are `kernel`, `dtb`,
|
||||
`rootfs`, `bootloader`, `boot` and `component`. Formats are `fit`,
|
||||
`arm64-image`, `fdt`, `cpio-gzip`, `uimage` and `raw`.
|
||||
|
||||
An image with `install: true` must name a partition and is the only kind the
|
||||
installer writes. Component images (kernel, dtb, rootfs) are carried for
|
||||
inspection and for boards whose installer composes them; for CV1835 they are
|
||||
also the inputs of the p1 FIT.
|
||||
|
||||
`bootloader_policy: preserve` means no image with role `bootloader` may be
|
||||
present. `include` means exactly one must be present. The toolkit refuses a
|
||||
bundle whose policy does not match its board module.
|
||||
|
||||
### Partitions
|
||||
|
||||
Each partition entry has `name`, `device`, `offset`, `size`, `secure`,
|
||||
`boot_critical`, `write_order` and `image` (or null). Secure partitions and
|
||||
`boot0` are declared so preflight can refuse them, never as write targets.
|
||||
`write_order` is 0 for a region that is not written and a positive order for
|
||||
an install target.
|
||||
|
||||
For CV1835 the plan is:
|
||||
|
||||
| Region | Device | Size | Secure | Written |
|
||||
|---|---|---|---|---|
|
||||
| `p1` | `/dev/mmcblk0p1` | 16 MiB | no | yes, order 1 |
|
||||
| `p3` | `/dev/mmcblk0p3` | 32 MiB | yes | no |
|
||||
| `boot0` | `/dev/mmcblk0boot0` | 4 MiB | yes | no |
|
||||
| `boot1` | `/dev/mmcblk0boot1` | 4 MiB | yes | no |
|
||||
|
||||
The p1 payload is the 16 MiB padded FIT. A FIT larger than the partition is a
|
||||
build failure. A wrong or missing FIT is a boot failure, not a write failure,
|
||||
as long as the held p1 backup is present.
|
||||
|
||||
## Signatures
|
||||
|
||||
`signature` is always an object:
|
||||
|
||||
```json
|
||||
{"type": "unsigned", "member": null, "public_key_hex": null}
|
||||
```
|
||||
|
||||
A signed bundle uses:
|
||||
|
||||
```json
|
||||
{"type": "ed25519", "member": "manifest.json.sig",
|
||||
"public_key_hex": "<64 hex characters>"}
|
||||
```
|
||||
|
||||
`manifest.json.sig` is the 64-byte raw Ed25519 signature over the exact
|
||||
`manifest.json` bytes, and is the second member. The key is a 32-byte raw seed
|
||||
or 64 hex characters in a file named by the release environment; no key value
|
||||
is stored in this repository. Adding a signature changes only the member set,
|
||||
not the schema, so unsigned bundles remain readable.
|
||||
|
||||
Site use requires a signed bundle. The bench allows an unsigned bundle only
|
||||
with `--allow-unsigned`, which prints a warning and the payload SHA-256.
|
||||
|
||||
## Build and check
|
||||
|
||||
The producer stages the manifest and payload, pads the CV p1 FIT to exactly
|
||||
16 MiB, and packs the members. The checker is the release gate. Both are
|
||||
offline and use only the Python standard library, except that Ed25519 signing
|
||||
and verification use the `cryptography` package.
|
||||
|
||||
```sh
|
||||
alkane-os/ci/make-afw.sh \
|
||||
--board cv1835 --version 0.1.0 \
|
||||
--input alkane-sdk/build/out/cv1835 \
|
||||
--sdk-revision "$(git -C alkane-sdk rev-parse HEAD)" \
|
||||
--os-revision "$(git -C alkane-os rev-parse HEAD)" \
|
||||
--output alkane-os/dist --allow-unsigned
|
||||
|
||||
python3 alkane-os/ci/check-afw.py \
|
||||
alkane-os/dist/alkane-os-0.1.0-cv1835-arm64.afw \
|
||||
--allow-unsigned --expect-board cv1835
|
||||
```
|
||||
|
||||
The checker fails on a wrong board or arch, a missing image, an image larger
|
||||
than its partition, a bootloader member under `preserve`, a hash or size
|
||||
mismatch, a path-traversal member, a truncated tar, a signed bundle without a
|
||||
valid signature, or an unsigned bundle without the explicit flag.
|
||||
|
||||
## Install rule
|
||||
|
||||
The toolkit verifies the whole bundle before opening a transport. It then
|
||||
preflights the board, holds the current p1 over the network, writes only the
|
||||
declared install partition, reads the whole partition back, and compares the
|
||||
hash before it reboots. No install step needs a serial console, an SD card, a
|
||||
U-Boot prompt, JTAG or a button.
|
||||
|
||||
## AM335x (legacy-uImage, non-FIT)
|
||||
|
||||
`am335x` is the BeagleBone-class AM335x slice. The board already runs our
|
||||
non-RSA U-Boot, so the bundle preserves mtd0-5 (SPL, U-Boot, bootenv) and
|
||||
writes only:
|
||||
|
||||
| Region | Device | Size | Image | Order |
|
||||
|---|---|---|---|---|
|
||||
| `mtd8` | `/dev/mtd8` | 20 MiB | type-3 ramdisk uImage | 1 |
|
||||
| `mtd6` | `/dev/mtd6` | 128 KiB | dtb (FDT) | 2 |
|
||||
| `mtd7` | `/dev/mtd7` | 5 MiB | type-2 kernel uImage | 3 |
|
||||
|
||||
`mtd0-5` are declared secure, image-free and outside the write order. Every
|
||||
partition offset is taken from the 12-entry map, including the unmapped
|
||||
512 KiB hole at `0x780000-0x800000`; mtd7 ends at `0x780000` and mtd8 starts
|
||||
at `0x800000`, never `0x780000`. The producer and both checkers refuse an
|
||||
offset in the hole, a write to mtd0-5, an image over its mtd ceiling, a
|
||||
bundle carrying an spl/u-boot member, a wrong arch, an oversize image, a
|
||||
truncated tar, or a traversal member. The images are legacy ARM uImages
|
||||
(kernel type 2, ramdisk type 3); a FIT is rejected.
|
||||
|
||||
```sh
|
||||
alkane-os/ci/make-afw.sh \
|
||||
--board am335x --version 0.1.0 \
|
||||
--input alkane-sdk/build/out/am335x \
|
||||
--sdk-dir alkane-sdk --plan am335x-plan.json \
|
||||
--output alkane-os/dist --allow-unsigned
|
||||
|
||||
python3 alkane-os/ci/check-afw.py \
|
||||
alkane-os/dist/alkane-os-0.1.0-am335x-arm.afw \
|
||||
--allow-unsigned --expect-board am335x
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
# Vendored flare-ui pin. Re-vendor with scripts, never edit the tree by hand.
|
||||
repo = https://gitea.bluefla.re/blueflare/flare-ui
|
||||
branch = sprint
|
||||
commit = 0e1f5a259faa32798bbb9ff3fedaa0b5faf5302d
|
||||
vendored = 2026-11-10
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a zynq-7010 .afw carrying the current alkane-os console.
|
||||
#
|
||||
# The SDK builds the base OS (kernel, dtb, rootfs) for the board; this script
|
||||
# cross-compiles the current alkane-os binary for armv7 (static musl, matching
|
||||
# the SDK rootfs), drops it and the image overlay (image/overlay) into the SDK's
|
||||
# rootfs, repacks the ramdisk, and packages the three images into a .afw with
|
||||
# ci/make-afw.sh. The rootfs is repacked under fakeroot so device nodes and root
|
||||
# ownership survive. Unsigned is bench-only.
|
||||
#
|
||||
# usage:
|
||||
# image/make-zynq-afw.sh [--sdk-out DIR] [--version X.Y.Z] [--skip-build]
|
||||
# defaults: --sdk-out ../alkane-sdk/build/out/zynq-7010 --version 0.1.0
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
SDK_OUT="$ROOT/../alkane-sdk/build/out/zynq-7010"
|
||||
SDK_DIR="$ROOT/../alkane-sdk"
|
||||
VERSION=0.1.0
|
||||
TARGET=armv7-unknown-linux-musleabihf
|
||||
SKIP_BUILD=0
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--sdk-out) SDK_OUT=$2; shift 2 ;;
|
||||
--sdk-dir) SDK_DIR=$2; shift 2 ;;
|
||||
--version) VERSION=$2; shift 2 ;;
|
||||
--skip-build) SKIP_BUILD=1; shift ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
command -v fakeroot >/dev/null 2>&1 || { echo "fakeroot is required" >&2; exit 1; }
|
||||
SDK_OUT="$(cd "$SDK_OUT" && pwd)"
|
||||
for f in zImage zynq-alkane.dtb rootfs.cpio.gz; do
|
||||
[ -f "$SDK_OUT/$f" ] || { echo "missing SDK image: $SDK_OUT/$f (build it in alkane-sdk first)" >&2; exit 1; }
|
||||
done
|
||||
|
||||
TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}"
|
||||
BIN="$TARGET_DIR/$TARGET/release/alkane-os"
|
||||
if [ "$SKIP_BUILD" -eq 0 ]; then
|
||||
echo "cross-compiling alkane-os for $TARGET (static)"
|
||||
# rustc drives the final link through a C compiler; the host cc cannot link
|
||||
# ARM objects, so use the ARM cross-gcc as the linker (musl crt + libs come
|
||||
# from rustup's self-contained target, so only the ARM linker driver is used).
|
||||
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER="${ARMV7_LINKER:-arm-linux-gnueabihf-gcc}"
|
||||
( cd "$ROOT" && cargo build --release --offline --target "$TARGET" --bin alkane-os )
|
||||
fi
|
||||
[ -f "$BIN" ] || { echo "cross-compiled binary not found: $BIN" >&2; exit 1; }
|
||||
|
||||
WORK=$(mktemp -d "${TMPDIR:-/tmp}/zynq-afw.XXXXXX")
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
mkdir -p "$WORK/in"
|
||||
|
||||
echo "staging the console binary"
|
||||
cp "$BIN" "$WORK/alkane-os"
|
||||
command -v arm-linux-gnueabihf-strip >/dev/null 2>&1 && arm-linux-gnueabihf-strip "$WORK/alkane-os" || true
|
||||
|
||||
echo "repacking the SDK rootfs with the console + overlay (under fakeroot)"
|
||||
cat > "$WORK/pack.sh" <<'PACK'
|
||||
set -e
|
||||
RFS=$1; SDK_OUT=$2; WORK=$3; OVERLAY=$4
|
||||
mkdir -p "$RFS"
|
||||
( cd "$RFS" && zcat "$SDK_OUT/rootfs.cpio.gz" | cpio -idm --quiet )
|
||||
install -D -m 0755 "$WORK/alkane-os" "$RFS/usr/bin/alkane-os"
|
||||
if [ -d "$OVERLAY" ]; then
|
||||
( cd "$OVERLAY" && find . -type f ) | while IFS= read -r f; do
|
||||
install -D -m 0755 "$OVERLAY/${f#./}" "$RFS/${f#./}"
|
||||
done
|
||||
fi
|
||||
( cd "$RFS" && find . | cpio -o -H newc --owner=0:0 --quiet | gzip -9 > "$WORK/in/rootfs.cpio.gz" )
|
||||
PACK
|
||||
fakeroot -- bash "$WORK/pack.sh" "$WORK/rootfs" "$SDK_OUT" "$WORK" "$ROOT/image/overlay"
|
||||
|
||||
cp "$SDK_OUT/zImage" "$WORK/in/zImage"
|
||||
cp "$SDK_OUT/zynq-alkane.dtb" "$WORK/in/zynq-alkane.dtb"
|
||||
|
||||
echo "packaging the .afw"
|
||||
"$ROOT/ci/make-afw.sh" \
|
||||
--board zynq-7010 \
|
||||
--version "$VERSION" \
|
||||
--input "$WORK/in" \
|
||||
--sdk-dir "$SDK_DIR" \
|
||||
--os-revision "$(git -C "$ROOT" rev-parse HEAD)" \
|
||||
--output "$ROOT/dist" \
|
||||
--allow-unsigned
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# S60alkane-web: serve the Alkane console and HTTP API.
|
||||
#
|
||||
# Starts after the network (S40). `alkane-os --serve` brings up the web console
|
||||
# (gated on a login) and the read-only JSON API on port 80, falling back to 8080
|
||||
# without privilege. The board HAL/mining backend is started separately; this
|
||||
# only needs the box to be reachable and observable, so every page renders and
|
||||
# the console works before any hashboard is driven.
|
||||
#
|
||||
# This file is part of the alkane-os image overlay (image/overlay), dropped into
|
||||
# the SDK rootfs at build time. It is intentionally not in the SDK's own init,
|
||||
# which owns board-detect / network / ssh and leaves the console to alkane-os.
|
||||
|
||||
PIDFILE=/run/alkane-web.pid
|
||||
BIN=/usr/bin/alkane-os
|
||||
|
||||
start() {
|
||||
[ -x "$BIN" ] || { echo "alkane-web: $BIN missing"; exit 1; }
|
||||
echo "alkane-web: starting console on :80 (falls back to :8080)"
|
||||
start-stop-daemon -S -b -m -p "$PIDFILE" -x "$BIN" -- --serve
|
||||
}
|
||||
|
||||
stop() {
|
||||
echo "alkane-web: stopping console"
|
||||
start-stop-daemon -K -q -p "$PIDFILE" 2>/dev/null
|
||||
rm -f "$PIDFILE"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
restart) stop; start ;;
|
||||
*) echo "usage: $0 {start|stop|restart}"; exit 1 ;;
|
||||
esac
|
||||
@@ -111,6 +111,27 @@
|
||||
"order": 60,
|
||||
"page": "settings.logs"
|
||||
},
|
||||
{
|
||||
"id": "settings/drivers",
|
||||
"slug": "drivers",
|
||||
"title": "Drivers",
|
||||
"order": 50,
|
||||
"page": "settings.drivers"
|
||||
},
|
||||
{
|
||||
"id": "settings/services",
|
||||
"slug": "services",
|
||||
"title": "Services",
|
||||
"order": 70,
|
||||
"page": "settings.services"
|
||||
},
|
||||
{
|
||||
"id": "settings/monitor",
|
||||
"slug": "monitor",
|
||||
"title": "Monitor",
|
||||
"order": 80,
|
||||
"page": "settings.monitor"
|
||||
},
|
||||
{
|
||||
"id": "settings/files",
|
||||
"slug": "files",
|
||||
|
||||
+10
-3
@@ -5,6 +5,7 @@
|
||||
//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover
|
||||
//! ephemeral ports instead of guessing them.
|
||||
|
||||
use crate::bus::Bus;
|
||||
use crate::detect::{
|
||||
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
|
||||
SensorTopology,
|
||||
@@ -52,6 +53,7 @@ pub fn start(
|
||||
status: Arc<MiningStatus>,
|
||||
api: Option<SocketAddr>,
|
||||
web_bind: Option<SocketAddr>,
|
||||
bus: Arc<Bus>,
|
||||
) -> io::Result<Servers> {
|
||||
let api_listener = match api {
|
||||
Some(address) => Some(bind_local(address)?),
|
||||
@@ -80,9 +82,9 @@ pub fn start(
|
||||
}));
|
||||
}
|
||||
if let Some(listener) = web_listener {
|
||||
let snapshot = Arc::clone(&status);
|
||||
let ctx = web::WebContext::new(Arc::clone(&bus));
|
||||
handles.push(std::thread::spawn(move || {
|
||||
if let Err(error) = web::serve_listener(listener, snapshot) {
|
||||
if let Err(error) = web::serve_listener(listener, ctx) {
|
||||
eprintln!("web UI stopped: {error}");
|
||||
}
|
||||
}));
|
||||
@@ -291,10 +293,15 @@ mod tests {
|
||||
fn both_servers_serve_the_published_snapshot() {
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
status.set_hardware(snapshot(&runtime(), "power:2400"));
|
||||
let bus = crate::bus::Bus::new();
|
||||
let control = Arc::new(crate::control::Control::default());
|
||||
crate::service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
crate::service::publish(&bus, &status, &control);
|
||||
let servers = start(
|
||||
Arc::clone(&status),
|
||||
Some("127.0.0.1:0".parse().unwrap()),
|
||||
Some("127.0.0.1:0".parse().unwrap()),
|
||||
bus,
|
||||
)
|
||||
.expect("start");
|
||||
let (api, web) = servers.addresses();
|
||||
@@ -319,7 +326,7 @@ mod tests {
|
||||
#[test]
|
||||
fn servers_are_optional() {
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
let servers = start(status, None, None).expect("start");
|
||||
let servers = start(status, None, None, crate::bus::Bus::new()).expect("start");
|
||||
assert_eq!(servers.addresses(), (None, None));
|
||||
}
|
||||
|
||||
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Web console authentication: a local account and session cookies.
|
||||
//!
|
||||
//! Modeled on wardenOS's web auth (spec d05): a local account whose password is
|
||||
//! stored only as a salted KDF hash, and a `wsid` session cookie issued on
|
||||
//! login. wardenOS uses Argon2 from its `warden-verifier` crate; alkane-os is
|
||||
//! dependency-light, so this uses PBKDF2-HMAC-SHA256 built on the crate's own
|
||||
//! pure-Rust SHA-256 (`pow::sha256`) - a standard password KDF with no new
|
||||
//! dependency. OIDC and FLARE bundle users are out of scope (no portal here).
|
||||
//!
|
||||
//! The box is guarded by SSH; this login is defense-in-depth for the console on
|
||||
//! a shared network, and the factory account is `admin` / `admin`, which the
|
||||
//! operator is expected to change.
|
||||
|
||||
use crate::pow::sha256;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// PBKDF2 iterations. A compromise for the crate's pure-Rust SHA-256: strong
|
||||
/// enough as defense-in-depth behind SSH, while a single login stays well under
|
||||
/// a second even on a slow control board.
|
||||
const PBKDF2_ITERS: u32 = 50_000;
|
||||
/// How long a session cookie stays valid.
|
||||
const SESSION_TTL: Duration = Duration::from_secs(12 * 3600);
|
||||
const AUTH_FILE: &str = "/etc/alkane/auth.json";
|
||||
|
||||
fn now_unix() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 16 bytes (32 hex) from the OS CSPRNG. The single random-token source for the
|
||||
/// console (CSRF token and session ids). If `/dev/urandom` is unreadable it
|
||||
/// fails LOUD and still avoids a fixed/guessable value: a per-call mix (nanos,
|
||||
/// pid, a process counter, a stack address) hashed through SHA-256, distinct on
|
||||
/// every call. Not a CSPRNG, but never the published constant it replaced.
|
||||
pub(crate) fn rand_hex() -> String {
|
||||
if let Ok(mut f) = fs::File::open("/dev/urandom") {
|
||||
let mut b = [0_u8; 16];
|
||||
if f.read_exact(&mut b).is_ok() {
|
||||
return hex(&b);
|
||||
}
|
||||
}
|
||||
static CTR: AtomicU64 = AtomicU64::new(0);
|
||||
eprintln!("alkane auth: WARNING /dev/urandom unreadable; session/token entropy is degraded");
|
||||
let n = CTR.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let stack = &n as *const _ as u64;
|
||||
let mix = nanos
|
||||
^ (std::process::id() as u64).rotate_left(17)
|
||||
^ n.rotate_left(33)
|
||||
^ stack.rotate_left(49);
|
||||
hex(&sha256(&mix.to_le_bytes())[..16])
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.filter_map(|i| u8::from_str_radix(text.get(i * 2..i * 2 + 2)?, 16).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HMAC-SHA256 over the crate's SHA-256.
|
||||
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
|
||||
const BLOCK: usize = 64;
|
||||
let mut k = [0_u8; BLOCK];
|
||||
if key.len() > BLOCK {
|
||||
k[..32].copy_from_slice(&sha256(key));
|
||||
} else {
|
||||
k[..key.len()].copy_from_slice(key);
|
||||
}
|
||||
let mut ipad = [0x36_u8; BLOCK];
|
||||
let mut opad = [0x5c_u8; BLOCK];
|
||||
for i in 0..BLOCK {
|
||||
ipad[i] ^= k[i];
|
||||
opad[i] ^= k[i];
|
||||
}
|
||||
let mut inner = Vec::with_capacity(BLOCK + msg.len());
|
||||
inner.extend_from_slice(&ipad);
|
||||
inner.extend_from_slice(msg);
|
||||
let ih = sha256(&inner);
|
||||
let mut outer = Vec::with_capacity(BLOCK + 32);
|
||||
outer.extend_from_slice(&opad);
|
||||
outer.extend_from_slice(&ih);
|
||||
sha256(&outer)
|
||||
}
|
||||
|
||||
/// PBKDF2-HMAC-SHA256 producing one 32-byte block (dkLen == hLen).
|
||||
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iters: u32) -> [u8; 32] {
|
||||
let mut block1 = salt.to_vec();
|
||||
block1.extend_from_slice(&1_u32.to_be_bytes());
|
||||
let mut u = hmac_sha256(password, &block1);
|
||||
let mut t = u;
|
||||
for _ in 1..iters.max(1) {
|
||||
u = hmac_sha256(password, &u);
|
||||
for i in 0..32 {
|
||||
t[i] ^= u[i];
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Constant-time comparison of two byte slices.
|
||||
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0_u8;
|
||||
for i in 0..a.len() {
|
||||
diff |= a[i] ^ b[i];
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// The stored local account.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Account {
|
||||
user: String,
|
||||
salt: Vec<u8>,
|
||||
iters: u32,
|
||||
hash: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
fn factory() -> Self {
|
||||
Self::with_password("admin", "admin")
|
||||
}
|
||||
|
||||
fn with_password(user: &str, password: &str) -> Self {
|
||||
let salt = unhex(&rand_hex());
|
||||
let hash = pbkdf2_sha256(password.as_bytes(), &salt, PBKDF2_ITERS).to_vec();
|
||||
Self {
|
||||
user: user.to_string(),
|
||||
salt,
|
||||
iters: PBKDF2_ITERS,
|
||||
hash,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"user": self.user,
|
||||
"salt": hex(&self.salt),
|
||||
"iters": self.iters,
|
||||
"hash": hex(&self.hash),
|
||||
})
|
||||
}
|
||||
|
||||
fn from_json(v: &Value) -> Option<Self> {
|
||||
Some(Self {
|
||||
user: v.get("user")?.as_str()?.to_string(),
|
||||
salt: unhex(v.get("salt")?.as_str()?),
|
||||
iters: v.get("iters")?.as_u64()? as u32,
|
||||
hash: unhex(v.get("hash")?.as_str()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn verify(&self, user: &str, password: &str) -> bool {
|
||||
let candidate = pbkdf2_sha256(password.as_bytes(), &self.salt, self.iters);
|
||||
// Compare the user name too, but not in constant time (it is not secret).
|
||||
user == self.user && ct_eq(&candidate, &self.hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The console auth state: one local account and the live sessions.
|
||||
pub struct Auth {
|
||||
account: Account,
|
||||
sessions: Mutex<HashMap<String, u64>>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// Load the account from `AUTH_FILE`, creating the factory `admin`/`admin`
|
||||
/// account (persisted when the path is writable) on first run.
|
||||
pub fn load() -> Self {
|
||||
Self::load_from(Path::new(AUTH_FILE))
|
||||
}
|
||||
|
||||
pub fn load_from(path: &Path) -> Self {
|
||||
let account = fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| Account::from_json(&v))
|
||||
.unwrap_or_else(|| {
|
||||
let account = Account::factory();
|
||||
persist(path, &account);
|
||||
account
|
||||
});
|
||||
Self {
|
||||
account,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
path: path.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a login. On success return a fresh `wsid`.
|
||||
pub fn login(&self, user: &str, password: &str) -> Option<String> {
|
||||
if !self.account.verify(user, password) {
|
||||
return None;
|
||||
}
|
||||
let wsid = rand_hex() + &rand_hex();
|
||||
// Only hand back a cookie if the session was actually recorded; a
|
||||
// poisoned lock must not mint a token that `valid` will always reject.
|
||||
match self.sessions.lock() {
|
||||
Ok(mut s) => {
|
||||
s.insert(wsid.clone(), now_unix() + SESSION_TTL.as_secs());
|
||||
Some(wsid)
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `wsid` names a live, unexpired session.
|
||||
pub fn valid(&self, wsid: &str) -> bool {
|
||||
if wsid.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let now = now_unix();
|
||||
let mut sessions = match self.sessions.lock() {
|
||||
Ok(s) => s,
|
||||
Err(_) => return false,
|
||||
};
|
||||
sessions.retain(|_, &mut exp| exp > now);
|
||||
sessions.get(wsid).is_some_and(|&exp| exp > now)
|
||||
}
|
||||
|
||||
/// End a session.
|
||||
pub fn logout(&self, wsid: &str) {
|
||||
if let Ok(mut s) = self.sessions.lock() {
|
||||
s.remove(wsid);
|
||||
}
|
||||
}
|
||||
|
||||
/// The path the account is stored at (for diagnostics).
|
||||
pub fn store_path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(path: &Path, account: &Account) {
|
||||
if let Some(parent) = path.parent() {
|
||||
if fs::create_dir_all(parent).is_err() {
|
||||
eprintln!(
|
||||
"alkane auth: cannot create {}; account not persisted",
|
||||
parent.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
let _ = fs::set_permissions(parent, fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
// The file holds the password hash: create it 0600, not umask-default.
|
||||
let text = serde_json::to_string_pretty(&account.to_json()).unwrap_or_default();
|
||||
match OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
{
|
||||
Ok(mut file) => {
|
||||
let _ = file.write_all(text.as_bytes());
|
||||
}
|
||||
Err(error) => eprintln!("alkane auth: cannot write {}: {error}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hmac_matches_rfc4231_case_2() {
|
||||
// RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?".
|
||||
let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
|
||||
assert_eq!(
|
||||
hex(&mac),
|
||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbkdf2_matches_a_known_vector() {
|
||||
// RFC 7914 / standard PBKDF2-HMAC-SHA256: P="passwd", S="salt", c=1.
|
||||
let dk = pbkdf2_sha256(b"passwd", b"salt", 1);
|
||||
assert_eq!(&hex(&dk)[..16], "55ac046e56e3089f");
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("alkane-auth-{name}-{}.json", std::process::id()));
|
||||
let _ = fs::remove_file(&p);
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory_account_accepts_admin_admin_and_rejects_others() {
|
||||
let auth = Auth::load_from(&temp("factory"));
|
||||
assert!(auth.login("admin", "admin").is_some());
|
||||
assert!(auth.login("admin", "wrong").is_none());
|
||||
assert!(auth.login("root", "admin").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_is_valid_until_logout() {
|
||||
let auth = Auth::load_from(&temp("session"));
|
||||
let wsid = auth.login("admin", "admin").expect("login");
|
||||
assert!(auth.valid(&wsid));
|
||||
assert!(!auth.valid("not-a-session"));
|
||||
auth.logout(&wsid);
|
||||
assert!(!auth.valid(&wsid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_account_persists_and_reloads() {
|
||||
let path = temp("persist");
|
||||
let _ = Auth::load_from(&path);
|
||||
assert!(path.exists(), "the factory account should be written");
|
||||
let again = Auth::load_from(&path);
|
||||
assert!(again.login("admin", "admin").is_some());
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -4,7 +4,11 @@
|
||||
//! rather than the cost of a Rust binary at all.
|
||||
|
||||
fn main() {
|
||||
let sections = [("dashboard", "Dashboard"), ("mining", "Mining"), ("settings", "Settings")];
|
||||
let sections = [
|
||||
("dashboard", "Dashboard"),
|
||||
("mining", "Mining"),
|
||||
("settings", "Settings"),
|
||||
];
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
@@ -17,5 +21,9 @@ fn main() {
|
||||
}
|
||||
html.push_str(&body.into_string());
|
||||
html.push_str("</body></html>");
|
||||
println!("{} {}", html.len(), serde_json::json!({"sections": sections.len()}));
|
||||
println!(
|
||||
"{} {}",
|
||||
html.len(),
|
||||
serde_json::json!({"sections": sections.len()})
|
||||
);
|
||||
}
|
||||
|
||||
+13
-3
@@ -43,8 +43,13 @@ fn main() {
|
||||
};
|
||||
|
||||
let visible = nav::visible(&schema.menus, &ctx);
|
||||
let first = visible.first_tab().map(|(section, tab)| Active { section, tab });
|
||||
let active = first.unwrap_or(Active { section: "", tab: "" });
|
||||
let first = visible
|
||||
.first_tab()
|
||||
.map(|(section, tab)| Active { section, tab });
|
||||
let active = first.unwrap_or(Active {
|
||||
section: "",
|
||||
tab: "",
|
||||
});
|
||||
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
@@ -60,7 +65,12 @@ fn main() {
|
||||
println!("html_bytes {}", html.len());
|
||||
println!("sections {}", visible.sections.len());
|
||||
for section in &visible.sections {
|
||||
println!("section {} ({}) tabs={}", section.slug, section.title, section.tabs.len());
|
||||
println!(
|
||||
"section {} ({}) tabs={}",
|
||||
section.slug,
|
||||
section.title,
|
||||
section.tabs.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
println!("{html}");
|
||||
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! The command/state bus: the single point of command for the miner.
|
||||
//!
|
||||
//! Modeled on wardenOS's bus (flare-edge `sprint`): one hub that the HTTP API,
|
||||
//! the web UI, and any future remote/flare client all go through, so there is no
|
||||
//! second way to change the machine. State is *retained* - a reader subscribes
|
||||
//! to / reads a topic and gets the last published document - and commands are
|
||||
//! *request/reply* to the service that owns the verb.
|
||||
//!
|
||||
//! wardenOS runs this as an MQTT-5 broker over a Unix socket with per-user ACLs.
|
||||
//! Here the wire is in-process (std threads, no broker, no async): the facade
|
||||
//! below - `publish_state` / `read_state` / `request` / `emit` - matches the
|
||||
//! warden `Bus` surface, so callers never learn the transport and the broker can
|
||||
//! be swapped in later without touching them. The registry in `registry.rs` is
|
||||
//! the contract (topics and verbs), exactly as warden's `topics.json` is.
|
||||
//!
|
||||
//! Topic kinds, mirroring warden:
|
||||
//! - `state` (retained): telemetry and status. Read = `read_state`.
|
||||
//! - `evt` (not retained): events (log lines, faults). `emit` keeps a bounded
|
||||
//! ring the UI and API can tail.
|
||||
//! - `req`/`reply`: a command to an owning service. `register` + `request`.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// How many recent events the bus keeps for tailing.
|
||||
const EVENT_RING: usize = 256;
|
||||
|
||||
/// Why a request could not be served. Serializes to the warden-style
|
||||
/// `{ "error": CODE, "message": ... }` envelope.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum BusError {
|
||||
/// No service owns this verb.
|
||||
NoHandler(String),
|
||||
/// The request body was malformed for this verb.
|
||||
BadRequest(String),
|
||||
/// The owning service refused the request (out of range, wrong state).
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
impl BusError {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
BusError::NoHandler(_) => "E_NO_HANDLER",
|
||||
BusError::BadRequest(_) => "E_BAD_REQUEST",
|
||||
BusError::Rejected(_) => "E_REJECTED",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
match self {
|
||||
BusError::NoHandler(m) | BusError::BadRequest(m) | BusError::Rejected(m) => m,
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON error envelope a surface returns to its client.
|
||||
pub fn envelope(&self) -> Value {
|
||||
json!({ "error": self.code(), "message": self.message() })
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BusError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.code(), self.message())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for BusError {}
|
||||
|
||||
/// A command handler: owns one verb, validates and applies the request, and
|
||||
/// returns the result document (or a [`BusError`]).
|
||||
pub type Handler = Box<dyn Fn(&Value) -> Result<Value, BusError> + Send + Sync>;
|
||||
|
||||
/// One emitted event, kept in the ring for tailing.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Event {
|
||||
pub topic: String,
|
||||
pub body: Value,
|
||||
pub at_unix: u64,
|
||||
}
|
||||
|
||||
/// The in-process bus.
|
||||
pub struct Bus {
|
||||
state: RwLock<BTreeMap<String, Value>>,
|
||||
handlers: RwLock<BTreeMap<String, Handler>>,
|
||||
events: Mutex<VecDeque<Event>>,
|
||||
}
|
||||
|
||||
impl Default for Bus {
|
||||
fn default() -> Self {
|
||||
Self::new_inner()
|
||||
}
|
||||
}
|
||||
|
||||
impl Bus {
|
||||
fn new_inner() -> Self {
|
||||
Self {
|
||||
state: RwLock::new(BTreeMap::new()),
|
||||
handlers: RwLock::new(BTreeMap::new()),
|
||||
events: Mutex::new(VecDeque::with_capacity(EVENT_RING)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared bus handle. The hub is cheap to clone (`Arc`).
|
||||
pub fn new() -> Arc<Self> {
|
||||
Arc::new(Self::new_inner())
|
||||
}
|
||||
|
||||
// --- state (retained) ----------------------------------------------------
|
||||
|
||||
/// Publish a retained state document. A later reader gets this verbatim.
|
||||
pub fn publish_state(&self, topic: &str, doc: Value) {
|
||||
if let Ok(mut map) = self.state.write() {
|
||||
map.insert(topic.to_string(), doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the last retained document for a topic, if any.
|
||||
pub fn read_state(&self, topic: &str) -> Option<Value> {
|
||||
self.state
|
||||
.read()
|
||||
.ok()
|
||||
.and_then(|map| map.get(topic).cloned())
|
||||
}
|
||||
|
||||
/// Read a retained document, or a fallback when nothing is published yet.
|
||||
pub fn read_state_or(&self, topic: &str, fallback: Value) -> Value {
|
||||
self.read_state(topic).unwrap_or(fallback)
|
||||
}
|
||||
|
||||
/// Drop a retained document (the warden "clear via empty will" semantics).
|
||||
pub fn clear_state(&self, topic: &str) {
|
||||
if let Ok(mut map) = self.state.write() {
|
||||
map.remove(topic);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every state topic currently published, for introspection and parity tests.
|
||||
pub fn state_topics(&self) -> Vec<String> {
|
||||
self.state
|
||||
.read()
|
||||
.map(|map| map.keys().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// --- commands (request/reply) --------------------------------------------
|
||||
|
||||
/// Register the service that owns `verb`. Re-registering replaces it.
|
||||
pub fn register<F>(&self, verb: &str, handler: F)
|
||||
where
|
||||
F: Fn(&Value) -> Result<Value, BusError> + Send + Sync + 'static,
|
||||
{
|
||||
if let Ok(mut map) = self.handlers.write() {
|
||||
map.insert(verb.to_string(), Box::new(handler));
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch a command to its owning service. This is the single write path:
|
||||
/// the API and the UI both call this, so a verb cannot be driven two ways.
|
||||
pub fn request(&self, verb: &str, body: &Value) -> Result<Value, BusError> {
|
||||
let map = self
|
||||
.handlers
|
||||
.read()
|
||||
.map_err(|_| BusError::Rejected("bus handler lock poisoned".into()))?;
|
||||
let handler = map
|
||||
.get(verb)
|
||||
.ok_or_else(|| BusError::NoHandler(format!("no service owns {verb}")))?;
|
||||
handler(body)
|
||||
}
|
||||
|
||||
/// True when a service owns the verb.
|
||||
pub fn has_verb(&self, verb: &str) -> bool {
|
||||
self.handlers
|
||||
.read()
|
||||
.map(|m| m.contains_key(verb))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Every registered verb, sorted, for introspection and parity tests.
|
||||
pub fn verbs(&self) -> Vec<String> {
|
||||
self.handlers
|
||||
.read()
|
||||
.map(|map| map.keys().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// --- events (non-retained) -----------------------------------------------
|
||||
|
||||
/// Emit an event onto the ring (faults, log lines, notices).
|
||||
pub fn emit(&self, topic: &str, body: Value) {
|
||||
let at_unix = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
if let Ok(mut ring) = self.events.lock() {
|
||||
if ring.len() == EVENT_RING {
|
||||
ring.pop_front();
|
||||
}
|
||||
ring.push_back(Event {
|
||||
topic: topic.to_string(),
|
||||
body,
|
||||
at_unix,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The most recent `n` events, oldest first.
|
||||
pub fn recent_events(&self, n: usize) -> Vec<Event> {
|
||||
self.events
|
||||
.lock()
|
||||
.map(|ring| ring.iter().rev().take(n).rev().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retained_state_round_trips() {
|
||||
let bus = Bus::new();
|
||||
assert_eq!(bus.read_state("miner/state/x"), None);
|
||||
bus.publish_state("miner/state/x", json!({"v": 1}));
|
||||
assert_eq!(bus.read_state("miner/state/x"), Some(json!({"v": 1})));
|
||||
bus.publish_state("miner/state/x", json!({"v": 2}));
|
||||
assert_eq!(bus.read_state("miner/state/x").unwrap()["v"], 2);
|
||||
bus.clear_state("miner/state/x");
|
||||
assert_eq!(bus.read_state("miner/state/x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_reaches_its_owning_handler() {
|
||||
let bus = Bus::new();
|
||||
bus.register("control/echo", |body| Ok(body.clone()));
|
||||
let out = bus.request("control/echo", &json!({"hi": true})).unwrap();
|
||||
assert_eq!(out["hi"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unowned_verb_is_a_no_handler_error() {
|
||||
let bus = Bus::new();
|
||||
let err = bus.request("nope", &json!({})).unwrap_err();
|
||||
assert_eq!(err.code(), "E_NO_HANDLER");
|
||||
assert_eq!(err.envelope()["error"], "E_NO_HANDLER");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handler_can_reject_and_the_code_is_preserved() {
|
||||
let bus = Bus::new();
|
||||
bus.register("control/set", |_| {
|
||||
Err(BusError::Rejected("out of range".into()))
|
||||
});
|
||||
let err = bus.request("control/set", &json!({})).unwrap_err();
|
||||
assert_eq!(err.code(), "E_REJECTED");
|
||||
assert_eq!(err.message(), "out of range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registering_a_verb_replaces_the_prior_owner() {
|
||||
let bus = Bus::new();
|
||||
bus.register("v", |_| Ok(json!(1)));
|
||||
bus.register("v", |_| Ok(json!(2)));
|
||||
assert_eq!(bus.request("v", &json!({})).unwrap(), json!(2));
|
||||
assert!(bus.has_verb("v"));
|
||||
assert_eq!(bus.verbs(), vec!["v".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_event_ring_is_bounded_and_ordered() {
|
||||
let bus = Bus::new();
|
||||
for i in 0..(EVENT_RING + 10) {
|
||||
bus.emit("evt/log", json!({ "i": i }));
|
||||
}
|
||||
let recent = bus.recent_events(5);
|
||||
assert_eq!(recent.len(), 5);
|
||||
// oldest-first, and the very last is the newest emitted.
|
||||
assert_eq!(
|
||||
recent.last().unwrap().body["i"],
|
||||
(EVENT_RING + 10 - 1) as i64
|
||||
);
|
||||
assert!(recent[0].body["i"].as_i64().unwrap() < recent[1].body["i"].as_i64().unwrap());
|
||||
}
|
||||
}
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! The flare-ui console: every navigation tab rendered with live data and real
|
||||
//! controls, inside the shared `flare-ui` shell.
|
||||
//!
|
||||
//! Content comes from the bus: telemetry is read from `state` topics and every
|
||||
//! control is a form that POSTs to a bus verb through `web.rs`. Host facts (the
|
||||
//! system/security/logs/files/terminal pages) are read directly. The module is
|
||||
//! built entirely from `flare-ui` primitives so the on-box console is the
|
||||
//! parameterised FLARE UI rather than a second hand-written one.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use maud::{html, Markup, PreEscaped};
|
||||
use serde_json::Value;
|
||||
|
||||
use flare_ui::actions::{self, Tone};
|
||||
use flare_ui::components;
|
||||
use flare_ui::nav::VisibleNav;
|
||||
use flare_ui::readings::{self, Level, Reading};
|
||||
use flare_ui::render::{self, View};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use wschema::model::Surface;
|
||||
|
||||
use crate::bus::Bus;
|
||||
use crate::dashboard::Dashboard;
|
||||
use crate::registry::topics;
|
||||
use crate::{service, web};
|
||||
|
||||
/// Render one navigation tab. `section`/`tab` are already validated by the
|
||||
/// caller. `errors` carries messages from a rejected form (`""` = a general
|
||||
/// banner, a path key = a field error).
|
||||
pub fn page(
|
||||
bus: &Bus,
|
||||
csrf: &str,
|
||||
section: &str,
|
||||
tab: &str,
|
||||
errors: &BTreeMap<String, String>,
|
||||
) -> Markup {
|
||||
let dash = Dashboard::load(service::settings_path());
|
||||
let nav = dash.nav().unwrap_or_default();
|
||||
let title = tab_title(&nav, section, tab);
|
||||
let hw = bus.read_state_or(topics::HARDWARE, serde_json::json!({"available": false}));
|
||||
let ctl = bus.read_state_or(topics::CONTROL, serde_json::json!({"running": false}));
|
||||
let body = match (section, tab) {
|
||||
("dashboard", "overview") | ("", "") => editable_dashboard(),
|
||||
("dashboard", "alerts") => alerts_card(&hw),
|
||||
("mining", "overview") => control_card(&hw, &ctl, csrf),
|
||||
("mining", "hashboards") => hashboards_card(&hw),
|
||||
("mining", "power") => power_card(&hw),
|
||||
("mining", "fans") => fans_card(&hw),
|
||||
("settings", "system") => system_card(),
|
||||
("settings", "tuning") => tuning_card(&dash, &ctl, csrf, errors),
|
||||
("settings", "pools") => pools_card(),
|
||||
("settings", "network") => network_card(),
|
||||
("settings", "drivers") => drivers_card(&hw),
|
||||
("settings", "security") => security_card(),
|
||||
("settings", "services") => services_card(),
|
||||
("settings", "monitor") => monitor_card(&hw),
|
||||
("settings", "logs") => logs_card(),
|
||||
("settings", "files") => files_card(),
|
||||
("settings", "terminal") => terminal_card(),
|
||||
_ => components::card(&title, readings::note("This page has no content yet.")),
|
||||
};
|
||||
shell::page(
|
||||
"Alkane OS",
|
||||
&Dashboard::assets(),
|
||||
&nav,
|
||||
Active { section, tab },
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
/// The sign-in page: a standalone card (no nav) styled with the flare-ui tokens,
|
||||
/// modeled on wardenOS's local login.
|
||||
pub fn login_page(csrf: &str, error: Option<&str>) -> Markup {
|
||||
html! {
|
||||
(maud::DOCTYPE)
|
||||
html lang="en" {
|
||||
head {
|
||||
meta charset="utf-8";
|
||||
meta name="viewport" content="width=device-width, initial-scale=1";
|
||||
title { "Alkane OS - Sign in" }
|
||||
link rel="stylesheet" href="/assets/tokens.css";
|
||||
link rel="stylesheet" href="/assets/components.css";
|
||||
link rel="stylesheet" href="/assets/theme.css";
|
||||
}
|
||||
body class="bf-shell" {
|
||||
main class="bf-main" {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
@if let Some(message) = error {
|
||||
p class="bf-field-error bf-text-body" role="alert" { (message) }
|
||||
}
|
||||
form class="bf-form" method="post" action="/auth/local" {
|
||||
input type="hidden" name="csrf" value=(csrf);
|
||||
div class="bf-field" {
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { "User" }
|
||||
input class="bf-input" type="text" name="user" autocomplete="username";
|
||||
}
|
||||
}
|
||||
div class="bf-field" {
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { "Password" }
|
||||
input class="bf-input" type="password" name="password" autocomplete="current-password";
|
||||
}
|
||||
}
|
||||
div class="bf-actions" {
|
||||
button type="submit" class="bf-btn bf-btn-primary bf-text-button" { "Sign in" }
|
||||
}
|
||||
}
|
||||
p class="bf-text-body-sm" { "Factory login is admin / admin. Change it after first sign-in." }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_title(nav: &VisibleNav, section: &str, tab: &str) -> String {
|
||||
nav.sections
|
||||
.iter()
|
||||
.find(|s| s.slug == section)
|
||||
.and_then(|s| s.tabs.iter().find(|t| t.slug == tab))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_else(|| tab.to_string())
|
||||
}
|
||||
|
||||
// --- value helpers -----------------------------------------------------------
|
||||
|
||||
fn reading(key: &str, label: &str, value: Option<f64>, units: &str, digits: usize) -> Reading {
|
||||
Reading {
|
||||
key: key.to_string(),
|
||||
label: label.to_string(),
|
||||
value,
|
||||
units: units.to_string(),
|
||||
digits,
|
||||
}
|
||||
}
|
||||
|
||||
fn num(doc: &Value, pointer: &str) -> Option<f64> {
|
||||
doc.pointer(pointer).and_then(Value::as_f64)
|
||||
}
|
||||
|
||||
fn text(doc: &Value, pointer: &str, fallback: &str) -> String {
|
||||
doc.pointer(pointer)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(fallback)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn active_chain_count(hw: &Value) -> usize {
|
||||
hw.get("active_chains")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.len())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Run/stop badge: a fault stop wins over the operator switch.
|
||||
fn run_state(hw: &Value, ctl: &Value) -> (Level, String) {
|
||||
if let Some(reason) = hw.get("stopped").and_then(Value::as_str) {
|
||||
return (Level::Err, format!("stopped: {reason}"));
|
||||
}
|
||||
if ctl.get("running").and_then(Value::as_bool).unwrap_or(false) {
|
||||
(Level::Ok, "mining".to_string())
|
||||
} else {
|
||||
(Level::Warn, "idle (operator stopped)".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
// --- cards -------------------------------------------------------------------
|
||||
|
||||
/// The main dashboard: an editable deck, like wardenOS's dashboard. The layout
|
||||
/// is a `.wdash`-style document stored on the box (bus `dashboard/*` verbs behind
|
||||
/// `/api/dashboard`); blocks draw live values from the open miner-state API. In
|
||||
/// edit mode the operator can add, remove, reorder and save blocks.
|
||||
fn editable_dashboard() -> Markup {
|
||||
html! {
|
||||
(PreEscaped(DECK_CSS))
|
||||
div class="bf-card" {
|
||||
div class="akd-bar" {
|
||||
button id="akd-edit" class="bf-btn bf-text-button" type="button" { "Edit" }
|
||||
button id="akd-add" class="bf-btn bf-text-button" type="button" hidden { "Add block" }
|
||||
button id="akd-save" class="bf-btn bf-btn-primary bf-text-button" type="button" hidden { "Save" }
|
||||
button id="akd-reset" class="bf-btn bf-btn-danger bf-text-button" type="button" hidden { "Reset to template" }
|
||||
span id="akd-msg" class="bf-text-body-sm" {}
|
||||
}
|
||||
div id="akd-grid" class="akd-grid" {}
|
||||
}
|
||||
(PreEscaped(DECK_JS))
|
||||
}
|
||||
}
|
||||
|
||||
const DECK_CSS: &str = "<style>\
|
||||
.akd-bar{display:flex;gap:8px;align-items:center;margin-bottom:12px;flex-wrap:wrap}\
|
||||
.akd-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}\
|
||||
.akd-card{border:1px solid var(--border,#192858);border-radius:8px;padding:12px;background:rgba(255,255,255,.03);min-width:0}\
|
||||
.akd-card h3{margin:0 0 6px;font-size:13px;font-weight:600;opacity:.8}\
|
||||
.akd-big{font-size:28px;font-weight:700;line-height:1.1;word-break:break-word}\
|
||||
.akd-unit{opacity:.7;font-size:13px;margin-left:4px}\
|
||||
.akd-s1{grid-column:span 1}.akd-s2{grid-column:span 2}.akd-s3{grid-column:span 3}.akd-s4{grid-column:span 4}\
|
||||
.akd-card table{width:100%;border-collapse:collapse;font-size:12px}.akd-card td,.akd-card th{text-align:left;padding:2px 4px}\
|
||||
.akd-card.drag{opacity:.5}.akd-rm{float:right;cursor:pointer;opacity:.6}\
|
||||
.akd-dim{opacity:.5}\
|
||||
@media(max-width:720px){.akd-grid{grid-template-columns:1fr}.akd-s2,.akd-s3,.akd-s4{grid-column:span 1}}\
|
||||
</style>";
|
||||
|
||||
const DECK_JS: &str = "<script>(function(){\
|
||||
var DECK='dashboard',doc=null,edit=false,drag=null;\
|
||||
function $(i){return document.getElementById(i)}\
|
||||
function esc(s){return String(s).replace(/[&<>\"']/g,function(c){return{'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]})}\
|
||||
function msg(t){var e=$('akd-msg');if(e)e.textContent=t}\
|
||||
var grid=$('akd-grid');\
|
||||
function render(){grid.innerHTML='';(doc.blocks||[]).forEach(function(b){\
|
||||
var c=document.createElement('div');c.className='akd-card akd-s'+(b.span||1);c.draggable=edit;\
|
||||
c.addEventListener('dragstart',function(){drag=b.id;c.classList.add('drag')});\
|
||||
c.addEventListener('dragend',function(){c.classList.remove('drag')});\
|
||||
c.addEventListener('dragover',function(e){if(edit)e.preventDefault()});\
|
||||
c.addEventListener('drop',function(e){e.preventDefault();if(!drag||drag===b.id)return;\
|
||||
var f=doc.blocks.findIndex(function(x){return x.id===drag}),t=doc.blocks.findIndex(function(x){return x.id===b.id});\
|
||||
if(f<0||t<0)return;var m=doc.blocks.splice(f,1)[0];doc.blocks.splice(f<t?t-1:t,0,m);render();msg('unsaved changes')});\
|
||||
var h=document.createElement('h3');h.textContent=b.title||b.id;\
|
||||
if(edit){var x=document.createElement('span');x.className='akd-rm';x.textContent='x';x.title='remove';\
|
||||
x.onclick=function(){doc.blocks=doc.blocks.filter(function(y){return y.id!==b.id});render();msg('unsaved changes')};h.appendChild(x)}\
|
||||
c.appendChild(h);\
|
||||
if(b.kind==='metric'||b.kind==='status'){var big=document.createElement('div');big.className='akd-big';big.dataset.source=b.source||'';big.textContent='--';\
|
||||
if(b.unit){var u=document.createElement('span');u.className='akd-unit';u.textContent=b.unit;big.appendChild(u)}c.appendChild(big)}\
|
||||
else if(b.kind==='table'){var tb=document.createElement('table');tb.dataset[b.source==='fans'?'fans':'table']=b.source||'';tb.innerHTML='<tbody><tr><td class=akd-dim>loading</td></tr></tbody>';c.appendChild(tb)}\
|
||||
else{var p=document.createElement('div');p.className='akd-dim';p.dataset.kv=b.source||'';p.textContent='loading';c.appendChild(p)}\
|
||||
grid.appendChild(c)})}\
|
||||
function fill(){var hw=null,sm=null;function paint(){if(!hw||!sm)return;var s=(sm.SUMMARY||[{}])[0];\
|
||||
var src={status:s.Status||'unknown',accepted:s.Accepted||0,rejected:s.Rejected||0,elapsed:s.Elapsed||0,\
|
||||
active_chains:(hw.active_chains||[]).length,frequency:hw.frequency_mhz||0,voltage:(hw.operating_point||{}).voltage_mv||0,target:hw.target||'-'};\
|
||||
document.querySelectorAll('[data-source]').forEach(function(el){var v=src[el.dataset.source];var u=el.querySelector('.akd-unit');\
|
||||
el.childNodes[0]&&(el.childNodes[0].nodeValue=(v===undefined||v===null)?'n/a':String(v));if(u)el.appendChild(u)});\
|
||||
document.querySelectorAll('[data-table]').forEach(function(t){var rows=(hw.chains||[]).map(function(c){return[c.index,c.chip,c.chips_found,c.response_per_mille]});\
|
||||
t.innerHTML=rows.length?'<thead><tr><th>#</th><th>chip</th><th>chips</th><th>resp</th></tr></thead><tbody>'+rows.map(function(r){return '<tr>'+r.map(function(c){return '<td>'+esc(c)+'</td>'}).join('')+'</tr>'}).join('')+'</tbody>':'<tbody><tr><td class=akd-dim>no chains</td></tr></tbody>'});\
|
||||
document.querySelectorAll('[data-kv]').forEach(function(el){var rows=[['profile',hw.profile||'-'],['chip',hw.chip||'-'],['psu',hw.psu||'-'],['target',hw.target||'-'],['stopped',hw.stopped?hw.stopped:'no']];\
|
||||
el.innerHTML=rows.map(function(r){return '<div><span class=akd-dim>'+esc(r[0])+'</span> '+esc(r[1])+'</div>'}).join('')});\
|
||||
document.querySelectorAll('[data-fans]').forEach(function(t){var rows=(hw.fan_zones||[]).map(function(z){return[z.fan,(z.zones||[]).join(', ')]});\
|
||||
t.innerHTML=rows.length?'<thead><tr><th>fan</th><th>zones</th></tr></thead><tbody>'+rows.map(function(r){return '<tr><td>'+esc(r[0])+'</td><td>'+esc(r[1])+'</td></tr>'}).join('')+'</tbody>':'<tbody><tr><td class=akd-dim>not mapped</td></tr></tbody>'})}\
|
||||
fetch('/api/hardware').then(function(r){return r.json()}).then(function(h){hw=h;paint()}).catch(function(){});\
|
||||
fetch('/api/summary').then(function(r){return r.json()}).then(function(x){sm=x;paint()}).catch(function(){})}\
|
||||
function setEdit(on){edit=on;['akd-add','akd-save','akd-reset'].forEach(function(i){$(i).hidden=!on});$('akd-edit').textContent=on?'Done':'Edit';render()}\
|
||||
$('akd-edit').onclick=function(){setEdit(!edit)};\
|
||||
$('akd-add').onclick=function(){if(doc.blocks.length>=32){msg('32 block limit');return}var n=1;doc.blocks.forEach(function(b){var x=parseInt(String(b.id).replace(/[^0-9]/g,''),10)||0;if(x>=n)n=x+1});doc.blocks.push({id:'block'+n,kind:'metric',span:1,title:'New block',source:'frequency',unit:'MHz'});render();msg('unsaved changes')};\
|
||||
$('akd-save').onclick=function(){fetch('/api/dashboard?deck='+DECK,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(doc)}).then(function(r){return r.ok?r.json().then(function(d){doc=d;render();msg('saved')}):r.text().then(msg)})};\
|
||||
$('akd-reset').onclick=function(){fetch('/api/dashboard?deck='+DECK+'&reset=1',{method:'PUT',headers:{'Content-Type':'application/json'},body:'{}'}).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();msg('template restored')})};\
|
||||
fetch('/api/dashboard?deck='+DECK).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();setInterval(fill,5000)});\
|
||||
})();</script>";
|
||||
|
||||
fn alerts_card(hw: &Value) -> Markup {
|
||||
let stopped = hw.get("stopped").and_then(Value::as_str);
|
||||
let run = reading("alert", "Supervisor", None, "", 0);
|
||||
components::card(
|
||||
"Alerts",
|
||||
html! {
|
||||
@match stopped {
|
||||
Some(reason) => (readings::status(&run, Level::Err, &format!("machine stopped: {reason}"))),
|
||||
None => (readings::status(&run, Level::Ok, "no active faults")),
|
||||
}
|
||||
(readings::log(&web::recent_log_lines(40)))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn control_card(hw: &Value, ctl: &Value, csrf: &str) -> Markup {
|
||||
let (level, state) = run_state(hw, ctl);
|
||||
let run = reading("run", "State", None, "", 0);
|
||||
let freq = reading(
|
||||
"frequency_mhz",
|
||||
"Chain frequency",
|
||||
num(hw, "/frequency_mhz"),
|
||||
"MHz",
|
||||
0,
|
||||
);
|
||||
components::card(
|
||||
"Control",
|
||||
html! {
|
||||
(readings::status(&run, level, &state))
|
||||
(readings::hero(&freq))
|
||||
(readings::plate(&[
|
||||
("Mode".into(), text(ctl, "/mode_label", "-")),
|
||||
("Target".into(), text(hw, "/target", "-")),
|
||||
("Active chains".into(), active_chain_count(hw).to_string()),
|
||||
]))
|
||||
div class="bf-actions" {
|
||||
@if let Some(b) = actions::action_button("/control/start", "Start mining", Tone::Primary, csrf, None) { (b) }
|
||||
@if let Some(b) = actions::action_button("/control/stop", "Stop mining", Tone::Danger, csrf, Some("Stops hashing immediately.")) { (b) }
|
||||
}
|
||||
(readings::note("Change the mode and target on Settings -> Tuning. A thermal or chain fault always overrides the operator switch."))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn hashboards_card(hw: &Value) -> Markup {
|
||||
let rows: Vec<Vec<String>> = hw
|
||||
.get("chains")
|
||||
.and_then(Value::as_array)
|
||||
.map(|chains| {
|
||||
chains
|
||||
.iter()
|
||||
.map(|c| {
|
||||
vec![
|
||||
c.get("index").map(|v| v.to_string()).unwrap_or_default(),
|
||||
c.get("chip")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("-")
|
||||
.to_string(),
|
||||
c.get("chips_found")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default(),
|
||||
c.pointer("/eeprom/state")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("-")
|
||||
.to_string(),
|
||||
c.get("response_per_mille")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default(),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
components::card(
|
||||
"Hashboards",
|
||||
if rows.is_empty() {
|
||||
readings::note("No chains detected.")
|
||||
} else {
|
||||
readings::table(
|
||||
&["#", "chip", "chips", "eeprom", "response per mille"],
|
||||
&rows,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn power_card(hw: &Value) -> Markup {
|
||||
components::card(
|
||||
"Power supply",
|
||||
readings::plate(&[
|
||||
("Supply".into(), text(hw, "/psu", "not identified")),
|
||||
(
|
||||
"Voltage range".into(),
|
||||
format!(
|
||||
"{} - {} mV",
|
||||
hw.pointer("/envelope/v_min_mv")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default(),
|
||||
hw.pointer("/envelope/v_max_mv")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default()
|
||||
),
|
||||
),
|
||||
(
|
||||
"Frequency range".into(),
|
||||
format!(
|
||||
"{} - {} MHz",
|
||||
hw.pointer("/envelope/f_min_mhz")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default(),
|
||||
hw.pointer("/envelope/f_max_mhz")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default()
|
||||
),
|
||||
),
|
||||
(
|
||||
"Operating point".into(),
|
||||
format!(
|
||||
"{} mV / {} MHz",
|
||||
hw.pointer("/operating_point/voltage_mv")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default(),
|
||||
hw.pointer("/operating_point/frequency_mhz")
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default()
|
||||
),
|
||||
),
|
||||
("Target".into(), text(hw, "/target", "-")),
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
fn fans_card(hw: &Value) -> Markup {
|
||||
let rows: Vec<Vec<String>> = hw
|
||||
.get("fan_zones")
|
||||
.and_then(Value::as_array)
|
||||
.map(|zones| {
|
||||
zones
|
||||
.iter()
|
||||
.map(|z| {
|
||||
vec![
|
||||
z.get("fan").map(|v| v.to_string()).unwrap_or_default(),
|
||||
z.get("zones").map(|v| v.to_string()).unwrap_or_default(),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
components::card(
|
||||
"Fans",
|
||||
if rows.is_empty() {
|
||||
readings::note("No fan zones mapped.")
|
||||
} else {
|
||||
readings::table(&["fan", "zones it cools"], &rows)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn plate_from(rows: Vec<(&str, String)>) -> Markup {
|
||||
let items: Vec<(String, String)> = rows.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
|
||||
readings::plate(&items)
|
||||
}
|
||||
|
||||
fn system_card() -> Markup {
|
||||
html! {
|
||||
(components::card("Identity", plate_from(web::system_rows())))
|
||||
(components::card("Updates", plate_from(web::update_rows())))
|
||||
}
|
||||
}
|
||||
|
||||
fn network_card() -> Markup {
|
||||
components::card("Network", plate_from(web::network_rows()))
|
||||
}
|
||||
|
||||
fn drivers_card(hw: &Value) -> Markup {
|
||||
components::card("Drivers", plate_from(web::driver_rows(hw)))
|
||||
}
|
||||
|
||||
fn security_card() -> Markup {
|
||||
components::card("Security", plate_from(web::security_rows()))
|
||||
}
|
||||
|
||||
fn services_card() -> Markup {
|
||||
components::card(
|
||||
"Services",
|
||||
readings::table(&["service", "running"], &web::service_rows()),
|
||||
)
|
||||
}
|
||||
|
||||
fn monitor_card(hw: &Value) -> Markup {
|
||||
components::card("Monitor", plate_from(web::monitor_rows(hw)))
|
||||
}
|
||||
|
||||
fn logs_card() -> Markup {
|
||||
components::card("Logs", readings::log(&web::recent_log_lines(200)))
|
||||
}
|
||||
|
||||
fn files_card() -> Markup {
|
||||
let doc = web::files_document("/");
|
||||
let rows: Vec<Vec<String>> = doc
|
||||
.get("entries")
|
||||
.and_then(Value::as_array)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
vec![
|
||||
e.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("-")
|
||||
.to_string(),
|
||||
e.get("kind")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("-")
|
||||
.to_string(),
|
||||
e.get("size").map(|v| v.to_string()).unwrap_or_default(),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
components::card(
|
||||
"Files",
|
||||
html! {
|
||||
(readings::note("Read-only listing of /. Individual text files are at /api/file?path=."))
|
||||
(readings::table(&["name", "kind", "size"], &rows))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn pools_card() -> Markup {
|
||||
components::card(
|
||||
"Pools",
|
||||
readings::note("Pool configuration is set at mining start (worker and pool address). Live pool editing from the console is not wired yet."),
|
||||
)
|
||||
}
|
||||
|
||||
fn terminal_card() -> Markup {
|
||||
if web::ui_token().is_none() {
|
||||
return components::card(
|
||||
"Terminal",
|
||||
readings::note("Terminal is disabled until a token exists at /var/lib/alkane/ui-token. Create one, then reload."),
|
||||
);
|
||||
}
|
||||
components::card(
|
||||
"Terminal",
|
||||
html! {
|
||||
div class="bf-field" {
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { "Command (runs as root on this miner)" }
|
||||
input id="cmd" class="bf-input" type="text" placeholder="command";
|
||||
}
|
||||
}
|
||||
div class="bf-actions" {
|
||||
button id="run" class="bf-btn bf-btn-primary bf-text-button" type="button" { "Run" }
|
||||
}
|
||||
pre id="out" class="bf-log" { "ready" }
|
||||
(PreEscaped(TERMINAL_JS))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const TERMINAL_JS: &str = "<script>(function(){var b=document.getElementById('run');if(!b)return;\
|
||||
b.onclick=function(){var c=document.getElementById('cmd').value;\
|
||||
fetch('/api/terminal?cmd='+encodeURIComponent(c),{method:'POST'})\
|
||||
.then(function(r){return r.text()}).then(function(t){document.getElementById('out').textContent=t})}})();</script>";
|
||||
|
||||
/// The tuning control: the schema `tuning` settings in a working form that posts
|
||||
/// to `/settings` (persist + drive the live runtime), plus the mode legend.
|
||||
fn tuning_card(
|
||||
dash: &Dashboard,
|
||||
ctl: &Value,
|
||||
csrf: &str,
|
||||
errors: &BTreeMap<String, String>,
|
||||
) -> Markup {
|
||||
let Ok(eff) = dash.schema() else {
|
||||
return components::card("Tuning", readings::note("Schema did not load."));
|
||||
};
|
||||
let view = View {
|
||||
eff,
|
||||
rows: dash.rows(),
|
||||
errors,
|
||||
surface: Surface::Web,
|
||||
can_write: true,
|
||||
};
|
||||
let banner = errors.get("").cloned();
|
||||
html! {
|
||||
@if let Some(message) = banner {
|
||||
div class="bf-card" {
|
||||
p class="bf-field-error bf-text-body" role="alert" { "Could not apply: " (message) }
|
||||
}
|
||||
}
|
||||
form class="bf-form" method="post" action="/settings" {
|
||||
input type="hidden" name="csrf" value=(csrf);
|
||||
input type="hidden" name="__section" value="settings";
|
||||
input type="hidden" name="__tab" value="tuning";
|
||||
(render::card("Tuning target", "tuning", &view))
|
||||
div class="bf-actions" {
|
||||
button type="submit" class="bf-btn bf-btn-primary bf-text-button" { "Apply target" }
|
||||
}
|
||||
}
|
||||
(components::card("How it maps", html! {
|
||||
(readings::plate(&[
|
||||
("Current mode".into(), text(ctl, "/mode_label", "-")),
|
||||
("Power target".into(), "hold a DC draw; efficiency follows the power point".into()),
|
||||
("Ambient temperature target".into(), "hold the hottest sensor a margin above ambient".into()),
|
||||
("Hashrate ceiling".into(), "seek a hashrate".into()),
|
||||
("Max fan".into(), "pin the fan and ramp under it".into()),
|
||||
]))
|
||||
(readings::note("Apply writes the setting and switches the live target. Start and stop are on Mining -> Overview."))
|
||||
}))
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Operator control intent for the live runtime.
|
||||
//!
|
||||
//! The management status in `management.rs` is read-only by design. This is the
|
||||
//! one small mutable channel the other way: the web UI (and any local client)
|
||||
//! WRITES a desired mode/target and a run switch here, and the serve-path
|
||||
//! runtime loop READS it each control period and applies it with
|
||||
//! [`crate::runtime::MinerRuntime::set_target`]. It owns nothing the fault
|
||||
//! supervisor owns: a thermal or chain fault still stops the machine regardless
|
||||
//! of what the operator asked for.
|
||||
//!
|
||||
//! A generation counter lets the loop notice a change cheaply without diffing
|
||||
//! the target every period.
|
||||
|
||||
use crate::tuning::TuningTarget;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The operator-visible control modes. Each maps onto exactly one
|
||||
/// [`TuningTarget`] the runtime already implements, so the UI never claims a
|
||||
/// behaviour the controller does not have.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ControlMode {
|
||||
/// Hold a DC power draw; efficiency follows from the power point. The MPC
|
||||
/// "power target" mode.
|
||||
Power,
|
||||
/// Hold the hottest sensor a fixed margin above measured ambient. The MPC
|
||||
/// "ambient temperature target" mode.
|
||||
Ambient,
|
||||
/// Seek a hashrate ceiling.
|
||||
Hashrate,
|
||||
/// Pin the fan at a duty and ramp frequency under it.
|
||||
MaxFan,
|
||||
}
|
||||
|
||||
impl ControlMode {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ControlMode::Power => "power",
|
||||
ControlMode::Ambient => "ambient",
|
||||
ControlMode::Hashrate => "hashrate",
|
||||
ControlMode::MaxFan => "fan",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ControlMode::Power => "Power target",
|
||||
ControlMode::Ambient => "Ambient temperature target",
|
||||
ControlMode::Hashrate => "Hashrate ceiling",
|
||||
ControlMode::MaxFan => "Max fan",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> [ControlMode; 4] {
|
||||
[
|
||||
ControlMode::Power,
|
||||
ControlMode::Ambient,
|
||||
ControlMode::Hashrate,
|
||||
ControlMode::MaxFan,
|
||||
]
|
||||
}
|
||||
|
||||
pub fn of_target(target: TuningTarget) -> ControlMode {
|
||||
match target {
|
||||
TuningTarget::PowerW(_) => ControlMode::Power,
|
||||
TuningTarget::AmbientC { .. } => ControlMode::Ambient,
|
||||
TuningTarget::HashrateThs(_) => ControlMode::Hashrate,
|
||||
TuningTarget::MaxFan { .. } => ControlMode::MaxFan,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit and sensible value for a mode's input box, for the UI form.
|
||||
pub fn mode_input(mode: ControlMode) -> (&'static str, &'static str) {
|
||||
match mode {
|
||||
ControlMode::Power => ("W", "watts of DC draw to hold"),
|
||||
ControlMode::Ambient => ("C", "degrees above ambient to hold the hottest sensor"),
|
||||
ControlMode::Hashrate => ("TH/s", "hashrate ceiling"),
|
||||
ControlMode::MaxFan => ("% PWM", "fan duty to pin (0-100)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a [`TuningTarget`] from a mode name and its single value. The value is
|
||||
/// in the mode's natural unit (watts, degrees C, TH/s, percent).
|
||||
pub fn parse_target(mode: &str, value: f32) -> Result<TuningTarget, String> {
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("value {value} is not a non-negative number"));
|
||||
}
|
||||
Ok(match mode {
|
||||
"power" => TuningTarget::PowerW(value),
|
||||
"hashrate" => TuningTarget::HashrateThs(value),
|
||||
"ambient" => TuningTarget::AmbientC {
|
||||
// UI gives whole degrees C; the controller works in millidegrees.
|
||||
margin_mc: (value * 1000.0).round() as i32,
|
||||
},
|
||||
"fan" => {
|
||||
if value > 100.0 {
|
||||
return Err("fan duty must be 0-100".into());
|
||||
}
|
||||
TuningTarget::MaxFan {
|
||||
max_pwm: value.round() as u8,
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unknown mode {other:?}")),
|
||||
})
|
||||
}
|
||||
|
||||
/// The compact `kind:value` label, matching the management `target` field and
|
||||
/// `app::target_label`.
|
||||
pub fn target_label(target: TuningTarget) -> String {
|
||||
match target {
|
||||
TuningTarget::PowerW(w) => format!("power:{}", w.round() as i64),
|
||||
TuningTarget::HashrateThs(t) => format!("hashrate:{}", t.round() as i64),
|
||||
TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"),
|
||||
TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared operator intent. Cheap to read every control period.
|
||||
#[derive(Debug)]
|
||||
pub struct Control {
|
||||
running: AtomicBool,
|
||||
generation: AtomicU64,
|
||||
target: Mutex<TuningTarget>,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
pub fn new(initial: TuningTarget, running: bool) -> Self {
|
||||
Self {
|
||||
running: AtomicBool::new(running),
|
||||
generation: AtomicU64::new(1),
|
||||
target: Mutex::new(initial),
|
||||
}
|
||||
}
|
||||
|
||||
/// Monotonic counter, bumped on every mutation. The loop keeps the last
|
||||
/// value it applied and only re-applies when this moves.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn running(&self) -> bool {
|
||||
self.running.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_running(&self, running: bool) {
|
||||
self.running.store(running, Ordering::Release);
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
pub fn target(&self) -> TuningTarget {
|
||||
*self.target.lock().expect("control target lock")
|
||||
}
|
||||
|
||||
pub fn set_target(&self, target: TuningTarget) {
|
||||
*self.target.lock().expect("control target lock") = target;
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
pub fn set_mode_value(&self, mode: &str, value: f32) -> Result<(), String> {
|
||||
let target = parse_target(mode, value)?;
|
||||
self.set_target(target);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Control {
|
||||
fn default() -> Self {
|
||||
// Default to a conservative power target, stopped until the operator starts it.
|
||||
Self::new(TuningTarget::PowerW(2_400.0), false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn modes_round_trip_through_targets() {
|
||||
for mode in ControlMode::all() {
|
||||
let value = match mode {
|
||||
ControlMode::MaxFan => 80.0,
|
||||
ControlMode::Ambient => 20.0,
|
||||
_ => 2_400.0,
|
||||
};
|
||||
let target = parse_target(mode.as_str(), value).expect("parse");
|
||||
assert_eq!(ControlMode::of_target(target), mode);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambient_degrees_become_millidegrees() {
|
||||
let target = parse_target("ambient", 20.0).expect("parse");
|
||||
assert_eq!(target, TuningTarget::AmbientC { margin_mc: 20_000 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fan_duty_is_bounded() {
|
||||
assert!(parse_target("fan", 120.0).is_err());
|
||||
assert_eq!(
|
||||
parse_target("fan", 100.0).expect("parse"),
|
||||
TuningTarget::MaxFan { max_pwm: 100 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_and_unknown_are_rejected() {
|
||||
assert!(parse_target("power", -1.0).is_err());
|
||||
assert!(parse_target("bogus", 1.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_target_or_running_bumps_the_generation() {
|
||||
let control = Control::new(TuningTarget::PowerW(2_000.0), false);
|
||||
let g0 = control.generation();
|
||||
control.set_target(TuningTarget::HashrateThs(100.0));
|
||||
let g1 = control.generation();
|
||||
assert!(g1 > g0);
|
||||
assert_eq!(control.target(), TuningTarget::HashrateThs(100.0));
|
||||
control.set_running(true);
|
||||
assert!(control.generation() > g1);
|
||||
assert!(control.running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn label_matches_management_shape() {
|
||||
assert_eq!(target_label(TuningTarget::PowerW(3_000.0)), "power:3000");
|
||||
assert_eq!(
|
||||
target_label(TuningTarget::AmbientC { margin_mc: 20_000 }),
|
||||
"ambient:20000"
|
||||
);
|
||||
}
|
||||
}
|
||||
+86
-59
@@ -18,10 +18,10 @@ use serde_json::{Map, Value};
|
||||
|
||||
use flare_ui::assets::PageAssets;
|
||||
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
|
||||
use flare_ui::url::Routes;
|
||||
use flare_ui::render::{self, View};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use flare_ui::tokens;
|
||||
use flare_ui::url::Routes;
|
||||
use wschema::effective::{self, Effective};
|
||||
use wschema::model::{Document, Surface};
|
||||
use wschema::validate::{Op, Rows};
|
||||
@@ -158,7 +158,13 @@ impl Dashboard {
|
||||
(card)
|
||||
}
|
||||
};
|
||||
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
|
||||
shell::page(
|
||||
"Alkane OS",
|
||||
&Self::assets(),
|
||||
&nav,
|
||||
Active { section, tab },
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
|
||||
@@ -176,7 +182,13 @@ impl Dashboard {
|
||||
}
|
||||
};
|
||||
let ops = self.parse_ops(effective, body);
|
||||
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
|
||||
let failures = render::validate_form(
|
||||
effective,
|
||||
&ops,
|
||||
&self.rows,
|
||||
wschema::validate::Origin::Web,
|
||||
None,
|
||||
);
|
||||
if !failures.is_empty() {
|
||||
return Err(failures);
|
||||
}
|
||||
@@ -190,13 +202,22 @@ impl Dashboard {
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
|
||||
let text =
|
||||
serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
|
||||
// Persist only after validation passed, atomically (temp + rename), and
|
||||
// surface a write failure instead of reporting a false success.
|
||||
let fail = |message: String| -> BTreeMap<String, String> {
|
||||
let mut failures = BTreeMap::new();
|
||||
failures.insert(String::new(), message);
|
||||
failures
|
||||
};
|
||||
if let Some(parent) = self.path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| fail(format!("cannot create {}: {e}", parent.display())))?;
|
||||
}
|
||||
// Persist only after validation passed; a failed write leaves the rows
|
||||
// changed in memory but never on disk, which the API reports.
|
||||
let _ = fs::write(&self.path, text);
|
||||
let tmp = self.path.with_extension("json.tmp");
|
||||
fs::write(&tmp, &text).map_err(|e| fail(format!("cannot write settings: {e}")))?;
|
||||
fs::rename(&tmp, &self.path).map_err(|e| fail(format!("cannot save settings: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -208,8 +229,8 @@ impl Dashboard {
|
||||
continue;
|
||||
}
|
||||
let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let key = percent_decode(raw_key);
|
||||
let raw = percent_decode(raw_value);
|
||||
let key = crate::form::percent_decode(raw_key);
|
||||
let raw = crate::form::percent_decode(raw_value);
|
||||
let setting = match effective.setting(&key) {
|
||||
Some(setting) => setting,
|
||||
None => continue,
|
||||
@@ -224,39 +245,6 @@ impl Dashboard {
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
index += 1;
|
||||
}
|
||||
b'%' if index + 2 < bytes.len() => {
|
||||
let high = (bytes[index + 1] as char).to_digit(16);
|
||||
let low = (bytes[index + 2] as char).to_digit(16);
|
||||
match (high, low) {
|
||||
(Some(high), Some(low)) => {
|
||||
out.push((high * 16 + low) as u8);
|
||||
index += 3;
|
||||
}
|
||||
_ => {
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn coerce(kind: &str, raw: &str) -> Value {
|
||||
match kind {
|
||||
"int" | "int_set" => raw
|
||||
@@ -275,7 +263,10 @@ mod tests {
|
||||
|
||||
fn temp_path(name: &str) -> PathBuf {
|
||||
let mut path = std::env::temp_dir();
|
||||
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
|
||||
path.push(format!(
|
||||
"alkane-dashboard-{name}-{}.json",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_file(&path);
|
||||
path
|
||||
}
|
||||
@@ -284,11 +275,14 @@ mod tests {
|
||||
fn the_schema_loads_and_yields_the_three_sections() {
|
||||
let dash = Dashboard::load(temp_path("load"));
|
||||
let effective = dash.schema().expect("schema loads");
|
||||
assert_eq!(effective.doc.menus.len(), 17);
|
||||
assert_eq!(effective.doc.menus.len(), 20);
|
||||
let nav = dash.nav().expect("nav builds");
|
||||
assert_eq!(nav.sections.len(), 3);
|
||||
assert_eq!(nav.sections[1].slug, "mining");
|
||||
assert_eq!(nav.sections[1].tabs.len(), 4);
|
||||
// Settings now carries the full tab set including drivers/services/monitor.
|
||||
assert_eq!(nav.sections[2].slug, "settings");
|
||||
assert_eq!(nav.sections[2].tabs.len(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -308,7 +302,10 @@ mod tests {
|
||||
"profiles.db",
|
||||
"system.name",
|
||||
] {
|
||||
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
|
||||
assert!(
|
||||
effective.setting(path).is_some(),
|
||||
"{path} is missing from the schema"
|
||||
);
|
||||
}
|
||||
assert_eq!(effective.doc.settings.len(), 20);
|
||||
}
|
||||
@@ -316,24 +313,42 @@ mod tests {
|
||||
#[test]
|
||||
fn a_page_renders_its_settings_with_inputs() {
|
||||
let dash = Dashboard::load(temp_path("page"));
|
||||
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
|
||||
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
|
||||
let html = dash
|
||||
.page("settings", "tuning", &BTreeMap::new())
|
||||
.into_string();
|
||||
assert!(
|
||||
html.contains("bf-sidebar"),
|
||||
"the unified sidebar is missing"
|
||||
);
|
||||
assert!(html.contains("bf-tabs"), "the tab strip is missing");
|
||||
assert!(html.contains("Tuning target"), "a settings label is missing");
|
||||
assert!(
|
||||
html.contains("Tuning target"),
|
||||
"a settings label is missing"
|
||||
);
|
||||
assert!(html.contains("tuning.power_w"), "the field path is missing");
|
||||
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
|
||||
assert!(
|
||||
html.contains("name=\"tuning.mode\""),
|
||||
"the mode field is missing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_valid_submission_is_persisted_and_reloaded() {
|
||||
let path = temp_path("submit");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
|
||||
dash.submit("tuning.power_w=1500&system.name=s19jpro")
|
||||
.expect("valid form");
|
||||
assert_eq!(
|
||||
dash.rows().get("tuning.power_w"),
|
||||
Some(&serde_json::json!(1500))
|
||||
);
|
||||
let stored = fs::read_to_string(&path).expect("settings file written");
|
||||
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
|
||||
let reloaded = Dashboard::load(&path);
|
||||
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
|
||||
assert_eq!(
|
||||
reloaded.rows().get("system.name"),
|
||||
Some(&serde_json::json!("s19jpro"))
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
@@ -341,9 +356,17 @@ mod tests {
|
||||
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
|
||||
let path = temp_path("reject");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
|
||||
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
|
||||
assert!(!path.exists(), "a rejected submission must not be persisted");
|
||||
let failures = dash
|
||||
.submit("tuning.power_w=99999")
|
||||
.expect_err("must be rejected");
|
||||
assert!(
|
||||
failures.keys().any(|key| key.contains("tuning.power_w")),
|
||||
"{failures:?}"
|
||||
);
|
||||
assert!(
|
||||
!path.exists(),
|
||||
"a rejected submission must not be persisted"
|
||||
);
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), None);
|
||||
}
|
||||
|
||||
@@ -351,14 +374,18 @@ mod tests {
|
||||
fn unknown_form_keys_are_ignored() {
|
||||
let path = temp_path("unknown");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
|
||||
dash.submit("not.a.setting=1&tuning.ceiling_mc=650")
|
||||
.expect("known key applies");
|
||||
assert_eq!(dash.rows().get("not.a.setting"), None);
|
||||
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
|
||||
assert_eq!(
|
||||
dash.rows().get("tuning.ceiling_mc"),
|
||||
Some(&serde_json::json!(650))
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_values_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
|
||||
assert_eq!(crate::form::percent_decode("a+b%2Fc"), "a b/c");
|
||||
}
|
||||
}
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Shared `application/x-www-form-urlencoded` / query decoding for the HTTP edge.
|
||||
//!
|
||||
//! One implementation, used by the web server, the miner service and the
|
||||
//! dashboard, so a fix or a bug cannot diverge between copies.
|
||||
|
||||
/// Percent-decode a form or query token (`%XX` escapes and `+` as space).
|
||||
pub fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
|
||||
match u8::from_str_radix(hex, 16) {
|
||||
Ok(byte) => {
|
||||
out.push(byte);
|
||||
i += 3;
|
||||
}
|
||||
Err(_) => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// Read one field from a urlencoded body by key (first match), percent-decoded.
|
||||
pub fn field(body: &str, key: &str) -> Option<String> {
|
||||
body.split('&').find_map(|pair| {
|
||||
let (k, v) = pair.split_once('=')?;
|
||||
(percent_decode(k) == key).then(|| percent_decode(v))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decodes_escapes_and_plus() {
|
||||
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
|
||||
assert_eq!(percent_decode("%0d%0a"), "\r\n");
|
||||
// A truncated trailing escape is passed through, not dropped.
|
||||
assert_eq!(percent_decode("x%2"), "x%2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_reads_first_match() {
|
||||
assert_eq!(field("a=1&b=two&a=3", "b").as_deref(), Some("two"));
|
||||
assert_eq!(field("a=1", "missing"), None);
|
||||
assert_eq!(field("csrf=tok&user=admin", "csrf").as_deref(), Some("tok"));
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -4,16 +4,21 @@
|
||||
//! the pairing already mines. Hardware backends are supplied by SDK images.
|
||||
|
||||
pub mod app;
|
||||
pub mod auth;
|
||||
pub mod bm1362;
|
||||
pub mod bm1366;
|
||||
pub mod bm1370;
|
||||
pub mod bm13xx;
|
||||
pub mod detect;
|
||||
pub mod bus;
|
||||
pub mod console;
|
||||
pub mod control;
|
||||
pub mod dashboard;
|
||||
pub mod detect;
|
||||
pub mod difficulty;
|
||||
pub mod fanmap;
|
||||
pub mod fanmap_store;
|
||||
pub mod fault;
|
||||
pub mod form;
|
||||
pub mod hal_conformance;
|
||||
pub mod hal_sim;
|
||||
pub mod hal_wire;
|
||||
@@ -21,8 +26,10 @@ pub mod management;
|
||||
pub mod miner;
|
||||
pub mod pow;
|
||||
pub mod profiles;
|
||||
pub mod registry;
|
||||
pub mod runtime;
|
||||
pub mod scrypt_pow;
|
||||
pub mod service;
|
||||
pub mod split;
|
||||
pub mod stratum_client;
|
||||
pub mod stratum_link;
|
||||
|
||||
+151
-5
@@ -1,5 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
use alkane_os::app;
|
||||
use alkane_os::bus::Bus;
|
||||
use alkane_os::control::Control;
|
||||
use alkane_os::detect::{
|
||||
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
|
||||
PsuCapability, SensorTopology,
|
||||
@@ -8,6 +10,7 @@ use alkane_os::hal_wire::HalClient;
|
||||
use alkane_os::management::MiningStatus;
|
||||
use alkane_os::miner::{Bm1366Miner, ChipModel};
|
||||
use alkane_os::runtime::{Tick, TickOutcome};
|
||||
use alkane_os::service;
|
||||
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
|
||||
use alkane_os::target_matrix;
|
||||
use alkane_os::tuning::{PidConfig, TuningTarget};
|
||||
@@ -39,7 +42,11 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = web_listen()?;
|
||||
let servers = app::start(Arc::clone(&status), api, web)?;
|
||||
let control = Arc::new(Control::default());
|
||||
let bus = Bus::new();
|
||||
service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
service::publish(&bus, &status, &control);
|
||||
let servers = app::start(Arc::clone(&status), api, web, Arc::clone(&bus))?;
|
||||
let (api_address, web_address) = servers.addresses();
|
||||
if let Some(address) = api_address {
|
||||
println!("management API on {address}");
|
||||
@@ -210,7 +217,11 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = web_listen()?;
|
||||
let servers = app::start(Arc::clone(&status), api, web)?;
|
||||
let control = Arc::new(Control::default());
|
||||
let bus = Bus::new();
|
||||
service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
service::publish(&bus, &status, &control);
|
||||
let servers = app::start(Arc::clone(&status), api, web, Arc::clone(&bus))?;
|
||||
|
||||
let config = app::BootConfig {
|
||||
profile_db_json,
|
||||
@@ -282,6 +293,7 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
// Publish every period: a client watching the API must see the live operating point,
|
||||
// not the boot-time snapshot.
|
||||
status.set_hardware(app::snapshot(&runtime, &label));
|
||||
service::publish(&bus, &status, &control);
|
||||
if let Some(reason) = runtime.stop_reason() {
|
||||
println!("stopped: {reason:?}");
|
||||
break;
|
||||
@@ -312,6 +324,128 @@ fn web_listen() -> Result<Option<std::net::SocketAddr>, Box<dyn std::error::Erro
|
||||
Ok(Some(std::net::SocketAddr::from(([0, 0, 0, 0], port))))
|
||||
}
|
||||
|
||||
/// Serve the full UI and API driven by the reference simulator HAL, in-process.
|
||||
///
|
||||
/// This is the "fully functional on a workstation" path: no hashboard is needed.
|
||||
/// A reference HAL runs on a private unix socket, the runtime boots against it,
|
||||
/// and a control loop applies the operator intent (mode/target, start/stop) from
|
||||
/// the web UI every period, publishing a live snapshot. Open the printed URL and
|
||||
/// the console shows frequency moving toward the target and the controls working.
|
||||
fn serve_sim() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use alkane_os::hal_sim::{serve as sim_serve, SimConfig};
|
||||
|
||||
let socket = std::env::temp_dir().join(format!("alkane-serve-sim-{}.sock", std::process::id()));
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
{
|
||||
let socket = socket.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = sim_serve(&socket, SimConfig::default()) {
|
||||
eprintln!("reference HAL stopped: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
// Wait for the HAL to bind its socket before the first connection.
|
||||
for _ in 0..500 {
|
||||
if socket.exists() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
let initial = TuningTarget::PowerW(2_400.0);
|
||||
// Start hashing immediately so the page is live; the operator can stop it.
|
||||
let control = Arc::new(Control::new(initial, true));
|
||||
let bus = Bus::new();
|
||||
service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
|
||||
let config = app::BootConfig {
|
||||
profile_db_json: include_str!("../profiles.example.json").to_owned(),
|
||||
chain_ports: vec![0, 1, 2],
|
||||
sensor: SensorTopology::Pic,
|
||||
budget: ProbeBudget::default(),
|
||||
fan_zones: Vec::new(),
|
||||
target: initial,
|
||||
pid: PidConfig::default(),
|
||||
ceiling_mc: 95_000,
|
||||
fault_policy: Default::default(),
|
||||
};
|
||||
let map_path =
|
||||
std::env::temp_dir().join(format!("alkane-serve-sim-{}.map.json", std::process::id()));
|
||||
let settings = app::HalBoot {
|
||||
config: &config,
|
||||
sweep: alkane_os::fanmap::SweepConfig {
|
||||
fans: 0,
|
||||
zones: 0,
|
||||
low_pwm: 40,
|
||||
high_pwm: 100,
|
||||
repeats: 1,
|
||||
settle_ms: 0,
|
||||
},
|
||||
thresholds: Default::default(),
|
||||
map_path: &map_path,
|
||||
};
|
||||
let (mut runtime, _map) = app::boot_from_hal(&socket, &settings, &status)?;
|
||||
println!(
|
||||
"detected {} with {} active chains",
|
||||
runtime.plan().profile,
|
||||
runtime.active_chains().len()
|
||||
);
|
||||
|
||||
let api = std::env::var("ALKANE_API_LISTEN")
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?
|
||||
.or(Some("127.0.0.1:4028".parse()?));
|
||||
let servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&bus))?;
|
||||
let (api_address, web_address) = servers.addresses();
|
||||
if let Some(address) = api_address {
|
||||
println!("management API on {address}");
|
||||
}
|
||||
if let Some(address) = web_address {
|
||||
println!("web UI on http://{address}/");
|
||||
}
|
||||
|
||||
// The control loop: its own HAL connection, applying operator intent.
|
||||
let mut client = HalClient::connect(&socket)?;
|
||||
let mut last_generation = 0_u64;
|
||||
loop {
|
||||
let generation = control.generation();
|
||||
if generation != last_generation {
|
||||
runtime.set_target(control.target());
|
||||
last_generation = generation;
|
||||
}
|
||||
let label = app::target_label(&control.target());
|
||||
if control.running() && runtime.stop_reason().is_none() {
|
||||
status.set_running(true);
|
||||
let hottest = client.read_temperature_mc(0).ok();
|
||||
let power_w = client.read_power_w().ok().map(f32::from);
|
||||
let outcome = runtime.tick(&Tick {
|
||||
power_w,
|
||||
hashrate_ths: None,
|
||||
hottest_mc: hottest,
|
||||
// The bench enclosure has no ambient sensor; assume 25 C so the
|
||||
// ambient-target mode has something to track.
|
||||
ambient_mc: Some(25_000),
|
||||
dt_s: 1.0,
|
||||
});
|
||||
if let TickOutcome::Run(command) = outcome {
|
||||
for chain in runtime.active_chains() {
|
||||
let _ = client.set_chain_frequency(chain, command.frequency_mhz);
|
||||
}
|
||||
if let Some(pwm) = command.fan_pwm {
|
||||
let _ = client.set_fan_target(0, pwm);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status.set_running(false);
|
||||
}
|
||||
status.set_hardware(app::snapshot(&runtime, &label));
|
||||
service::publish(&bus, &status, &control);
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve the UI and the API without a mining backend. A board whose HAL
|
||||
/// backend is not written yet still has to be reachable and observable; every
|
||||
/// page says "not identified" rather than claiming hardware it cannot see.
|
||||
@@ -321,8 +455,14 @@ fn serve_only() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let api = api.or(Some("0.0.0.0:4028".parse()?));
|
||||
let servers = app::start(Arc::clone(&status), api, web_listen()?)?;
|
||||
// The cgminer-style API is loopback-only (reach it through SSH); default to
|
||||
// loopback so `--serve` starts even when ALKANE_API_LISTEN is unset.
|
||||
let api = api.or(Some("127.0.0.1:4028".parse()?));
|
||||
let control = Arc::new(Control::default());
|
||||
let bus = Bus::new();
|
||||
service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
service::publish(&bus, &status, &control);
|
||||
let servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&bus))?;
|
||||
let (api_address, web_address) = servers.addresses();
|
||||
if let Some(address) = api_address {
|
||||
println!("management API on {address}");
|
||||
@@ -354,6 +494,12 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Some("--serve-sim") => {
|
||||
if let Err(error) = serve_sim() {
|
||||
eprintln!("serve-sim failed: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Some("--boot") => {
|
||||
if let Err(error) = boot_hal(args) {
|
||||
eprintln!("boot failed: {error}");
|
||||
@@ -439,7 +585,7 @@ fn main() {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
|
||||
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --serve | --serve-sim | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
|
||||
eprintln!(
|
||||
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
|
||||
);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! The bus registry: the single source of truth for every topic and verb.
|
||||
//!
|
||||
//! wardenOS keeps this as `bus/registry/topics.json` and generates the broker
|
||||
//! ACL, the constants and the retain rules from it with `busgen`. alkane-os is
|
||||
//! std-only and in-process, so the registry lives here as typed constants plus a
|
||||
//! machine-readable description ([`contract`]). A test asserts that every verb a
|
||||
//! service registers and every state topic it publishes appears here, so the
|
||||
//! contract cannot drift from the code - the property `busgen` gives warden.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Retained state topics (read with `Bus::read_state`).
|
||||
pub mod topics {
|
||||
/// Full hardware/runtime snapshot (profile, chip, PSU, chains, operating point).
|
||||
pub const HARDWARE: &str = "miner/state/hardware";
|
||||
/// cgminer-style summary (elapsed, accepted, rejected, mining/stopped).
|
||||
pub const SUMMARY: &str = "miner/state/summary";
|
||||
/// Operator control state (running, mode, target, generation).
|
||||
pub const CONTROL: &str = "miner/state/control";
|
||||
}
|
||||
|
||||
/// Event topics (emitted with `Bus::emit`, tailed from the ring).
|
||||
pub mod events {
|
||||
/// A human-facing notice (fault, state change) for the alerts view.
|
||||
pub const NOTICE: &str = "miner/evt/notice";
|
||||
}
|
||||
|
||||
/// Command verbs (dispatched with `Bus::request`). Each is owned by one service.
|
||||
pub mod verbs {
|
||||
/// Start hashing (operator). Body: `{}`.
|
||||
pub const CONTROL_START: &str = "control/start";
|
||||
/// Stop hashing (operator). Body: `{}`.
|
||||
pub const CONTROL_STOP: &str = "control/stop";
|
||||
/// Switch the live MPC target. Body: `{ "mode": "power|ambient|hashrate|fan", "value": <f32> }`.
|
||||
pub const CONTROL_SET_TARGET: &str = "control/set_target";
|
||||
/// Apply a settings form (persist + drive the runtime). Body: `{ "form": "<urlencoded>" }`.
|
||||
pub const SETTINGS_APPLY: &str = "settings/apply";
|
||||
/// Load a dashboard deck. Body: `{ "deck": "<name>" }` -> the deck document.
|
||||
pub const DASHBOARD_LOAD: &str = "dashboard/load";
|
||||
/// Save a dashboard deck. Body: `{ "deck": "<name>", "doc": <deck> }`.
|
||||
pub const DASHBOARD_SAVE: &str = "dashboard/save";
|
||||
/// Reset a dashboard deck to the compiled default. Body: `{ "deck": "<name>" }`.
|
||||
pub const DASHBOARD_RESET: &str = "dashboard/reset";
|
||||
}
|
||||
|
||||
/// The declared contract: every verb and state topic the miner service owns.
|
||||
/// The parity test checks the live bus against this, so a new verb that is not
|
||||
/// listed here, or a listed verb no service registers, fails CI.
|
||||
pub fn contract() -> Value {
|
||||
json!({
|
||||
"state": [topics::HARDWARE, topics::SUMMARY, topics::CONTROL],
|
||||
"events": [events::NOTICE],
|
||||
"verbs": [
|
||||
verbs::CONTROL_START,
|
||||
verbs::CONTROL_STOP,
|
||||
verbs::CONTROL_SET_TARGET,
|
||||
verbs::SETTINGS_APPLY,
|
||||
verbs::DASHBOARD_LOAD,
|
||||
verbs::DASHBOARD_SAVE,
|
||||
verbs::DASHBOARD_RESET,
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// The verbs in the contract, as a sorted list.
|
||||
pub fn contract_verbs() -> Vec<String> {
|
||||
let mut v: Vec<String> = contract()["verbs"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(str::to_string))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_contract_lists_distinct_verbs_and_topics() {
|
||||
let verbs = contract_verbs();
|
||||
let mut unique = verbs.clone();
|
||||
unique.dedup();
|
||||
assert_eq!(verbs, unique, "duplicate verb in the contract");
|
||||
assert!(verbs.contains(&verbs::CONTROL_SET_TARGET.to_string()));
|
||||
assert_eq!(contract()["state"].as_array().unwrap().len(), 3);
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,18 @@ impl MinerRuntime {
|
||||
self.faults.active_chains()
|
||||
}
|
||||
|
||||
/// The operator target currently in force.
|
||||
pub fn target(&self) -> TuningTarget {
|
||||
self.tuning.target()
|
||||
}
|
||||
|
||||
/// Switch the operator target (one of the MPC modes) without a restart. The
|
||||
/// PID state carries over, so the operating point moves from where it is
|
||||
/// rather than snapping back to the envelope floor.
|
||||
pub fn set_target(&mut self, target: TuningTarget) {
|
||||
self.tuning.set_target(target);
|
||||
}
|
||||
|
||||
pub fn stop_reason(&self) -> Option<StopReason> {
|
||||
self.faults.stop_reason()
|
||||
}
|
||||
@@ -268,6 +280,36 @@ mod tests {
|
||||
assert!(runtime.active_chains().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_target_keeps_the_operating_point_and_takes_effect() {
|
||||
let mut runtime = runtime();
|
||||
// Climb under a power target so the frequency leaves the floor.
|
||||
for _ in 0..30 {
|
||||
let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz);
|
||||
runtime.tick(&tick(power));
|
||||
}
|
||||
let climbed = runtime.operating_point().frequency_mhz;
|
||||
assert!(climbed > 300, "frequency never left the floor: {climbed}");
|
||||
assert!(matches!(runtime.target(), TuningTarget::PowerW(_)));
|
||||
// Switch to an ambient target in place: the target changes and the
|
||||
// operating point carries over (no snap back to the floor).
|
||||
runtime.set_target(TuningTarget::AmbientC { margin_mc: 20_000 });
|
||||
assert!(matches!(
|
||||
runtime.target(),
|
||||
TuningTarget::AmbientC { margin_mc: 20_000 }
|
||||
));
|
||||
assert_eq!(runtime.operating_point().frequency_mhz, climbed);
|
||||
// The ambient target now drives: feed ambient + hottest and it still runs.
|
||||
let outcome = runtime.tick(&Tick {
|
||||
power_w: None,
|
||||
hashrate_ths: None,
|
||||
hottest_mc: Some(60_000),
|
||||
ambient_mc: Some(40_000),
|
||||
dt_s: 1.0,
|
||||
});
|
||||
assert!(matches!(outcome, TickOutcome::Run(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operating_point_reflects_the_last_command() {
|
||||
let mut runtime = runtime();
|
||||
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! The miner service: the one owner of the control verbs, the settings/dashboard
|
||||
//! verbs, and the published state topics.
|
||||
//!
|
||||
//! Every surface - the HTTP API, the web console, a future remote/flare client -
|
||||
//! reaches the machine only by a `Bus::request` to a verb registered here, or by
|
||||
//! reading a state topic published here. There is no second write path, which is
|
||||
//! the wardenOS property: one dispatch shared by all surfaces.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bus::{Bus, BusError};
|
||||
use crate::control::{self, Control, ControlMode};
|
||||
use crate::management::MiningStatus;
|
||||
use crate::registry::{topics, verbs};
|
||||
use crate::ui;
|
||||
|
||||
const DECK_DIR: &str = "/var/lib/alkane/decks";
|
||||
|
||||
/// Where the dashboard keeps operator settings (the schema rows).
|
||||
pub(crate) fn settings_path() -> PathBuf {
|
||||
let etc = Path::new("/etc/alkane/settings.json");
|
||||
if etc.exists() || Path::new("/etc/alkane").is_dir() {
|
||||
return etc.to_path_buf();
|
||||
}
|
||||
// A read-only root or a test run: keep the file beside the binary.
|
||||
std::env::temp_dir().join("alkane-settings.json")
|
||||
}
|
||||
|
||||
/// The deck directory: the on-box `/var/lib/alkane/decks` when it exists or can
|
||||
/// be created (root on the miner), else a writable fallback for a dev run.
|
||||
fn deck_dir() -> PathBuf {
|
||||
let dir = Path::new(DECK_DIR);
|
||||
if dir.is_dir() || fs::create_dir_all(dir).is_ok() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
std::env::temp_dir().join("alkane-decks")
|
||||
}
|
||||
|
||||
fn deck_path(deck: &str) -> PathBuf {
|
||||
let safe: String = deck
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
||||
.collect();
|
||||
deck_dir().join(format!("{safe}.json"))
|
||||
}
|
||||
|
||||
pub(crate) fn load_deck(deck: &str) -> Value {
|
||||
fs::read_to_string(deck_path(deck))
|
||||
.ok()
|
||||
.and_then(|text| ui::validate_deck(&text).ok())
|
||||
.unwrap_or_else(|| ui::default_deck(deck))
|
||||
}
|
||||
|
||||
fn save_deck(deck: &str, doc: &Value) -> Result<(), String> {
|
||||
let path = deck_path(deck);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
|
||||
}
|
||||
let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?;
|
||||
// Atomic replace: a concurrent read never sees a half-written deck.
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
fs::write(&tmp, text).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
|
||||
fs::rename(&tmp, &path).map_err(|e| format!("cannot replace {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Translate a settings form's tuning fields into the live control target.
|
||||
fn apply_tuning(body: &str, control: &Control) {
|
||||
let Some(mode) = crate::form::field(body, "tuning.mode") else {
|
||||
return;
|
||||
};
|
||||
let (mode, value_field) = match mode.as_str() {
|
||||
"power" => ("power", "tuning.power_w"),
|
||||
"hashrate" => ("hashrate", "tuning.hashrate_ths"),
|
||||
"ambient" => ("ambient", "tuning.ambient_margin_c"),
|
||||
"max-fan" => ("fan", "tuning.max_fan_pwm"),
|
||||
_ => return,
|
||||
};
|
||||
if let Some(value) =
|
||||
crate::form::field(body, value_field).and_then(|v| v.trim().parse::<f32>().ok())
|
||||
{
|
||||
let _ = control.set_mode_value(mode, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner of the control state: it mutates [`Control`] and, like a wardenOS
|
||||
/// service, republishes the affected state the instant a command applies, so a
|
||||
/// reader never sees a command lag behind the periodic telemetry publish. The
|
||||
/// bus is held `Weak` to avoid an `Arc` cycle (the bus owns the handlers).
|
||||
struct MinerService {
|
||||
status: Arc<MiningStatus>,
|
||||
control: Arc<Control>,
|
||||
bus: std::sync::Weak<Bus>,
|
||||
}
|
||||
|
||||
impl MinerService {
|
||||
fn republish_control(&self) {
|
||||
if let Some(bus) = self.bus.upgrade() {
|
||||
bus.publish_state(
|
||||
topics::CONTROL,
|
||||
control_document(&self.status, &self.control),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Register every miner verb on the bus. Called once at start-up.
|
||||
pub fn register(bus: &Arc<Bus>, status: Arc<MiningStatus>, control: Arc<Control>) {
|
||||
let svc = Arc::new(MinerService {
|
||||
status,
|
||||
control,
|
||||
bus: Arc::downgrade(bus),
|
||||
});
|
||||
{
|
||||
let s = Arc::clone(&svc);
|
||||
bus.register(verbs::CONTROL_START, move |_| {
|
||||
s.control.set_running(true);
|
||||
s.republish_control();
|
||||
Ok(json!({ "running": true }))
|
||||
});
|
||||
}
|
||||
{
|
||||
let s = Arc::clone(&svc);
|
||||
bus.register(verbs::CONTROL_STOP, move |_| {
|
||||
s.control.set_running(false);
|
||||
s.republish_control();
|
||||
Ok(json!({ "running": false }))
|
||||
});
|
||||
}
|
||||
{
|
||||
let s = Arc::clone(&svc);
|
||||
bus.register(verbs::CONTROL_SET_TARGET, move |body| {
|
||||
let mode = body
|
||||
.get("mode")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| BusError::BadRequest("mode is required".into()))?;
|
||||
let value = body
|
||||
.get("value")
|
||||
.and_then(Value::as_f64)
|
||||
.ok_or_else(|| BusError::BadRequest("value is required".into()))?
|
||||
as f32;
|
||||
s.control
|
||||
.set_mode_value(mode, value)
|
||||
.map_err(BusError::Rejected)?;
|
||||
s.republish_control();
|
||||
Ok(json!({
|
||||
"target": control::target_label(s.control.target()),
|
||||
"mode": ControlMode::of_target(s.control.target()).as_str(),
|
||||
}))
|
||||
});
|
||||
}
|
||||
{
|
||||
// A settings form: persist the validated rows, then drive the runtime
|
||||
// from the tuning fields. Body carries the raw urlencoded form.
|
||||
let s = Arc::clone(&svc);
|
||||
bus.register(verbs::SETTINGS_APPLY, move |body| {
|
||||
let form = body
|
||||
.get("form")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| BusError::BadRequest("form is required".into()))?;
|
||||
let mut dash = crate::dashboard::Dashboard::load(settings_path());
|
||||
dash.submit(form).map_err(|failures| {
|
||||
let mut msg = String::new();
|
||||
for (k, why) in failures {
|
||||
msg.push_str(&format!("{k}: {why}; "));
|
||||
}
|
||||
BusError::Rejected(msg.trim_end().to_string())
|
||||
})?;
|
||||
apply_tuning(form, &s.control);
|
||||
s.republish_control();
|
||||
Ok(json!({ "applied": true }))
|
||||
});
|
||||
}
|
||||
bus.register(verbs::DASHBOARD_LOAD, |body| {
|
||||
let deck = body
|
||||
.get("deck")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("dashboard");
|
||||
Ok(load_deck(deck))
|
||||
});
|
||||
bus.register(verbs::DASHBOARD_SAVE, |body| {
|
||||
let deck = body
|
||||
.get("deck")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("dashboard");
|
||||
let doc = body
|
||||
.get("doc")
|
||||
.ok_or_else(|| BusError::BadRequest("doc is required".into()))?;
|
||||
let validated = ui::validate_deck(&doc.to_string()).map_err(BusError::Rejected)?;
|
||||
save_deck(deck, &validated).map_err(BusError::Rejected)?;
|
||||
Ok(validated)
|
||||
});
|
||||
bus.register(verbs::DASHBOARD_RESET, |body| {
|
||||
let deck = body
|
||||
.get("deck")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("dashboard");
|
||||
let doc = ui::default_deck(deck);
|
||||
save_deck(deck, &doc).map_err(BusError::Rejected)?;
|
||||
Ok(doc)
|
||||
});
|
||||
}
|
||||
|
||||
/// Publish the current miner state onto the bus. Called each control period and
|
||||
/// once at start-up. These documents are exactly what the API and UI read back.
|
||||
pub fn publish(bus: &Bus, status: &MiningStatus, control: &Control) {
|
||||
bus.publish_state(topics::HARDWARE, status.hardware_document());
|
||||
bus.publish_state(topics::SUMMARY, status.summary_document());
|
||||
bus.publish_state(topics::CONTROL, control_document(status, control));
|
||||
}
|
||||
|
||||
/// The operator control document (also the `/api/control` body).
|
||||
pub fn control_document(status: &MiningStatus, control: &Control) -> Value {
|
||||
let hw = status.hardware_document();
|
||||
let mode = ControlMode::of_target(control.target());
|
||||
json!({
|
||||
"running": control.running(),
|
||||
"mode": mode.as_str(),
|
||||
"mode_label": mode.label(),
|
||||
"target": control::target_label(control.target()),
|
||||
"generation": control.generation(),
|
||||
"stopped": hw.get("stopped").cloned().unwrap_or(Value::Null),
|
||||
"frequency_mhz": hw.get("frequency_mhz").cloned().unwrap_or(Value::Null),
|
||||
"available": hw.get("available").cloned().unwrap_or(Value::Bool(false)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::registry;
|
||||
|
||||
#[test]
|
||||
fn registered_verbs_match_the_contract() {
|
||||
let bus = Bus::new();
|
||||
register(
|
||||
&bus,
|
||||
Arc::new(MiningStatus::new()),
|
||||
Arc::new(Control::default()),
|
||||
);
|
||||
let mut registered = bus.verbs();
|
||||
registered.sort();
|
||||
// Every registered verb is declared in the contract (nothing undocumented),
|
||||
// and every contract verb is actually registered (nothing missing).
|
||||
assert_eq!(registered, registry::contract_verbs());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_state_topics_match_the_contract() {
|
||||
let bus = Bus::new();
|
||||
publish(&bus, &MiningStatus::new(), &Control::default());
|
||||
let mut published = bus.state_topics();
|
||||
published.sort();
|
||||
let mut declared: Vec<String> = registry::contract()["state"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap().to_string())
|
||||
.collect();
|
||||
declared.sort();
|
||||
assert_eq!(
|
||||
published, declared,
|
||||
"published state topics must match the contract"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_verbs_drive_the_shared_control() {
|
||||
let bus = Bus::new();
|
||||
let control = Arc::new(Control::default());
|
||||
register(&bus, Arc::new(MiningStatus::new()), Arc::clone(&control));
|
||||
bus.request(verbs::CONTROL_START, &json!({})).unwrap();
|
||||
assert!(control.running());
|
||||
bus.request(verbs::CONTROL_STOP, &json!({})).unwrap();
|
||||
assert!(!control.running());
|
||||
bus.request(
|
||||
verbs::CONTROL_SET_TARGET,
|
||||
&json!({"mode": "ambient", "value": 18.0}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
control.target(),
|
||||
crate::tuning::TuningTarget::AmbientC { margin_mc: 18_000 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_target_rejects_a_bad_mode() {
|
||||
let bus = Bus::new();
|
||||
register(
|
||||
&bus,
|
||||
Arc::new(MiningStatus::new()),
|
||||
Arc::new(Control::default()),
|
||||
);
|
||||
let err = bus
|
||||
.request(
|
||||
verbs::CONTROL_SET_TARGET,
|
||||
&json!({"mode": "bogus", "value": 1.0}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "E_REJECTED");
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,14 @@ impl Pid {
|
||||
self.output = value.clamp(self.config.out_min, self.config.out_max);
|
||||
}
|
||||
|
||||
/// Clear the integral and derivative history, keeping the current output.
|
||||
/// Used on a target switch so error accumulated in one unit (watts) is not
|
||||
/// injected into the next target's loop (millidegrees, TH/s).
|
||||
pub fn reset_accumulator(&mut self) {
|
||||
self.integral = 0.0;
|
||||
self.last_measurement = None;
|
||||
}
|
||||
|
||||
/// Advance one control period and return the new output.
|
||||
pub fn update(&mut self, setpoint: f32, measurement: f32, dt_s: f32) -> f32 {
|
||||
if !dt_s.is_finite() || dt_s <= 0.0 {
|
||||
@@ -168,6 +176,23 @@ impl TuningLoop {
|
||||
self.pid.output().round() as u16
|
||||
}
|
||||
|
||||
/// The target the loop is currently chasing.
|
||||
pub fn target(&self) -> TuningTarget {
|
||||
self.target
|
||||
}
|
||||
|
||||
/// Switch the operator target in place, keeping the operating point (the PID
|
||||
/// output) so it carries over instead of jumping back to the floor, but
|
||||
/// clearing the error accumulator: the old target's integral is in the old
|
||||
/// target's units and must not drive the new loop. The thermal guard and
|
||||
/// envelope bounds are unchanged.
|
||||
pub fn set_target(&mut self, target: TuningTarget) {
|
||||
if target != self.target {
|
||||
self.pid.reset_accumulator();
|
||||
}
|
||||
self.target = target;
|
||||
}
|
||||
|
||||
/// Fan duty implied by the target, if the target owns the fan.
|
||||
fn target_fan(&self) -> Option<u8> {
|
||||
match self.target {
|
||||
|
||||
+562
-360
File diff suppressed because it is too large
Load Diff
+557
@@ -64,18 +64,79 @@ version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||
dependencies = [
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde_core",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-core"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -85,6 +146,18 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
@@ -310,6 +383,12 @@ version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
@@ -319,6 +398,21 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
[[package]]
|
||||
name = "flare-plugin-abi"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"wapp-core",
|
||||
"wasmparser 0.228.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flare-plugin-host"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"flare-plugin-abi",
|
||||
"sha2",
|
||||
"wasmi",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flare-ui"
|
||||
@@ -330,6 +424,24 @@ dependencies = [
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flare-ui-axum"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"criterion",
|
||||
"flare-ui",
|
||||
"form_urlencoded",
|
||||
"futures-core",
|
||||
"http-body-util",
|
||||
"maud",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tower",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
@@ -340,6 +452,45 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -382,6 +533,21 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
@@ -426,6 +592,95 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body-util"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
@@ -461,12 +716,30 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.190"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "maud"
|
||||
version = "0.27.0"
|
||||
@@ -495,6 +768,12 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
@@ -505,6 +784,17 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -532,6 +822,18 @@ version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.8.0"
|
||||
@@ -555,6 +857,15 @@ dependencies = [
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -585,6 +896,27 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
@@ -638,6 +970,12 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -696,6 +1034,29 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -713,6 +1074,44 @@ version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "string-interner"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
@@ -741,6 +1140,12 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sync_wrapper"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
||||
|
||||
[[package]]
|
||||
name = "tinytemplate"
|
||||
version = "1.2.1"
|
||||
@@ -751,6 +1156,59 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
||||
|
||||
[[package]]
|
||||
name = "tower-service"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@@ -763,6 +1221,12 @@ version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
|
||||
|
||||
[[package]]
|
||||
name = "universal-hash"
|
||||
version = "0.5.1"
|
||||
@@ -834,6 +1298,99 @@ version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
|
||||
dependencies = [
|
||||
"spin",
|
||||
"wasmi_collections",
|
||||
"wasmi_core",
|
||||
"wasmi_ir",
|
||||
"wasmparser 0.228.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_collections"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
|
||||
dependencies = [
|
||||
"string-interner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_core"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_ir"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
|
||||
dependencies = [
|
||||
"wasmi_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.228.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wast"
|
||||
version = "263.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wat"
|
||||
version = "1.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7"
|
||||
dependencies = [
|
||||
"wast",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
|
||||
Vendored
+2
@@ -2,6 +2,7 @@
|
||||
# other lanes ask it through a note. Only lane LD tags (see docs/vendoring.md).
|
||||
# scripts/check-owners.sh keeps this file and crates/ in step.
|
||||
crates/flare-ui LD
|
||||
crates/flare-ui-axum LD
|
||||
crates/flare-plugin-abi LD
|
||||
crates/wschema LB
|
||||
crates/wschema-gen LB
|
||||
@@ -10,3 +11,4 @@ crates/warden-sync LI
|
||||
crates/warden-seal LI
|
||||
crates/wapp-core LM
|
||||
crates/wapp-pack LM
|
||||
crates/flare-plugin-host LD
|
||||
|
||||
Vendored
+12
-1
@@ -22,7 +22,8 @@ schema forms, navigation, charts, page assets, editors and package validation.
|
||||
|
||||
| Crate | Role |
|
||||
|---|---|
|
||||
| `flare-ui` | Schema forms, navigation, chart islands, page assets and editor assets |
|
||||
| `flare-ui` | Schema forms, read-only pages, navigation, chart islands, page assets and editor assets |
|
||||
| `flare-ui-axum` | Authenticated-page SSE transport, replay, stream limits, poll responses and the d04 7.4 action routes; [host contract](crates/flare-ui-axum/README.md) |
|
||||
| `wschema` | Schema document model, builder DSL, canonical JSON, hashes, lint L01 to L23 |
|
||||
| `wschema-cli` | `canon`, `hash`, `lint` and corpus `validate` for fragment authors and CI; `verify-lock` and `gen-lock` for consumer locks (`flare-ui.lock`, `gen.lock`) |
|
||||
| `wschema-gen` | Generators: the OpenAPI `components.schemas` of an effective schema and their splice into a template |
|
||||
@@ -45,10 +46,20 @@ scripts/check-owners.sh
|
||||
scripts/vendor-selftest.sh
|
||||
```
|
||||
|
||||
`cargo test` runs the JavaScript unit tests of the browser assets with `node`
|
||||
(flare-ui#148): `node --test tests/js/<file>.test.js` in `crates/flare-ui`, for
|
||||
actions, boot, chart, islands, live and page-live. A machine without `node`
|
||||
fails those tests. A host that cannot run node sets `FLARE_UI_SKIP_NODE_TESTS=1`
|
||||
to skip them. The skip is written to the test's stderr, which cargo shows only
|
||||
for a failing test or with `--nocapture`, so a host that skips them runs those
|
||||
six files with `node` elsewhere and records that run in its commit.
|
||||
|
||||
The [chart browser checks](crates/flare-ui/tests/browser/README.md) run on
|
||||
Chromium and Firefox over plain HTTP, with CSP and real SSE samples.
|
||||
The [live client](docs/live.md) documents typed chart props, server tier
|
||||
links, accessible latest values and named series events.
|
||||
The [schema page contract](docs/schema-pages.md) covers authorized read-only
|
||||
snapshots, shared full/HX bodies and stable OOB fragments.
|
||||
|
||||
The shared crates also build for the panel:
|
||||
|
||||
|
||||
@@ -7,4 +7,14 @@ license.workspace = true
|
||||
description = "Plugin ABI shared by FLARE and the Warden console"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = ["wasm"]
|
||||
# FLARE plugin (Wasm) admission. A panel build turns it off.
|
||||
wasm = ["dep:wasmparser"]
|
||||
# Admits dev-class signatures. Release images leave it off (d04 13.4.8, W-D4).
|
||||
plugin-dev = ["wapp-core/dev-signing-key"]
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
wapp-core = { path = "../wapp-core" }
|
||||
wasmparser = { version = "0.228", default-features = false, features = ["std", "validate", "features"], optional = true }
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# flare-plugin-abi
|
||||
|
||||
Plugin and module admission shared by FLARE and the Warden console
|
||||
(d04 13.3.5 and 13.4; B-13, W-D4).
|
||||
|
||||
| Module | Admits | Spec |
|
||||
|---|---|---|
|
||||
| `package` | the code inside one signed `.wapp`: `validate_full` first, then the signer class and the code checks | s12 V16, V19, V20 |
|
||||
| `wmod` | panel modules (`ui/modules/*.so`, ABI `wmod/1`) before `dlopen` | d04 13.3.5 |
|
||||
| `wasm` | FLARE plugin modules (`fp/1`, feature `wasm`) before compile | d04 13.4.4 |
|
||||
| `fp1` | `fp/1` names, handler kinds, negative codes, op registry | d04 13.4.2 |
|
||||
| `code` | reason codes shared by all of the above | s12 4.6 |
|
||||
|
||||
`wmod` checks the image the loader maps. The dynamic section and every table it
|
||||
names (symbols, strings, relocations, hash tables, the info block) are read at
|
||||
their load addresses through the PT_LOAD segments, and a section header that
|
||||
names one of them must name the same file bytes. Every symbol index the loader
|
||||
can reach, through a relocation or a hash chain, must be a checked symbol
|
||||
(#187).
|
||||
|
||||
Only `platform`-signed code is admitted. The `dev` class needs the
|
||||
`plugin-dev` feature and is compiled out of release images. The `partner`
|
||||
class is refused until an out-of-process runtime exists (B-13).
|
||||
|
||||
## Amendments
|
||||
|
||||
Each row records a reading of frozen spec text that the code follows. The
|
||||
frozen copy in `flare-edge-construction/raw/2026-10-09-rebuild-design-specs/`
|
||||
is not edited.
|
||||
|
||||
| Id | Spec text | Reading in this crate | Why |
|
||||
|---|---|---|---|
|
||||
| AM-PL2-1 | d04 13.3.5 leaves the info block locator open | the block is the `.wmod_info` section, found by name (`wmod::INFO_SECTION`) | the module SDK must link it somewhere the verifier can read without running the module; `wmod_entry` is the only exported symbol |
|
||||
| AM-PL2-2 | d04 13.3.5 "Info block" row gives `E_PLATFORM` for an LVGL or SDK hash mismatch; 13.3.6 and 13.3.10 give `needs_platform` | an LVGL or SDK mismatch under `LVGL_DIRECT` is `Compat::NeedsPlatform`; app_id, app_build and ABI major stay `E_PLATFORM` | 13.3.6 and 13.3.10 are the later, specific rows; s12 4.2 makes the module mismatch soft (T-WA-06) |
|
||||
| AM-PL2-3 | d04 13.3.5 "Dynamic section" refuses `DT_TEXTREL` | the verifier refuses the `DT_TEXTREL` tag and `DF_TEXTREL` in `DT_FLAGS`, and a second `DT_FLAGS` entry | current linkers record text relocations as `DF_TEXTREL` in `DT_FLAGS`; a second entry could give the verifier and the loader different flag words |
|
||||
| AM-PL2-4 | d04 13.4.4 "imports must be exactly `fp1.call` and `fp1.log`" | the import list may hold only those two names, each at most once with its fixed signature; a module may import one of them | a guest that never logs does not import `fp1.log`; the rule that matters is that no other import exists |
|
||||
| AM-PL2-5 | d04 13.4.8 names no code for the `off` refusal of a Wasm plugin. s12 1282 gives `E_KEY` with detail `plugins_off` | `E_KEY` with detail `plugins_off`, in both `package::admit_plugin` and the host `load` gate. The host once returned `E_STATE` for this refusal, an implementation defect fixed in 42b9646 | s12 1282 is the governing text (the install pipeline the audit records use). The host test `off_mode_loads_nothing` pins the code |
|
||||
| AM-PL2-6 | d04 13.3.5 "ELF header" row requires hard-float by `Tag_ABI_VFP_args` | hard-float is the `EF_ARM_ABI_FLOAT_HARD` bit of `e_flags`; the attribute section is not parsed (see `abi/fp1.md`) | the bit sits in the header the verifier already reads, so no attribute parser is needed; `d04_pl2_refuses_soft_float` pins the refusal |
|
||||
|
||||
## Reason codes
|
||||
|
||||
`code::Code` carries every wire code of the `.wapp` set and the plugin-only
|
||||
codes `E_WASM`, `E_IMPORT` and `E_LIMIT`. A refusal from `wapp-core` keeps its
|
||||
wire code; `t_wa_01_wire_codes_match_wapp_core` checks the mapping.
|
||||
`t_wa_01_every_reason_code_has_a_refusing_module_vector` refuses a panel module
|
||||
with each of the ten T-WA-01 codes (s12 4.5).
|
||||
@@ -0,0 +1,71 @@
|
||||
# fp/1 plugin ABI
|
||||
|
||||
Defined by d04 13.4.2 to 13.4.5. This file is the contract the crate tests
|
||||
pin; the sources are `src/fp1.rs`, `src/wasm.rs` and `src/wmod.rs`.
|
||||
|
||||
## Guest module
|
||||
|
||||
Core Wasm, one import namespace, JSON messages.
|
||||
|
||||
| Direction | Name | Type |
|
||||
|---|---|---|
|
||||
| import | `fp1.call` | `(i32 i32 i32 i32) -> i32` |
|
||||
| import | `fp1.log` | `(i32 i32 i32) -> ()` |
|
||||
| export | `memory` | the one linear memory |
|
||||
| export | `fp_alloc` | `(i32) -> i32` |
|
||||
| export | `fp_free` | `(i32 i32) -> ()` |
|
||||
| export | `fp_init` | `(i32 i32) -> i32` |
|
||||
| export | `fp_handle` | `(i32 i32 i32) -> i64` |
|
||||
|
||||
## Admission (`wasm::admit`)
|
||||
|
||||
Refused with `E_WASM`, `E_IMPORT` or `E_LIMIT`:
|
||||
|
||||
- module over 2 MiB (`E_LIMIT`);
|
||||
- any import other than `fp1.call` and `fp1.log`, each at most once and with
|
||||
the exact type above (`E_IMPORT`); memory, table and global imports count;
|
||||
- a start function, a second memory, more than one table, shared or 64-bit
|
||||
memory, a memory with no declared maximum, or a maximum above
|
||||
`limits.memory_mb` (`E_WASM`, the last two `E_LIMIT`);
|
||||
- a missing export, an export of the wrong kind or type, or a duplicate name;
|
||||
- threads, SIMD, GC, exceptions and other post-MVP features outside the
|
||||
accepted set: mutable globals, sign extension, saturating conversion,
|
||||
multi-value, bulk memory, reference types.
|
||||
|
||||
## Host ops
|
||||
|
||||
The registry is `fp1::OPS`. A manifest names an op or a family (`kv@1`).
|
||||
Negative codes of `fp1.call` are `-1 E_OP_UNKNOWN` through `-9 E_STATE`.
|
||||
`parse_call` maps a malformed request to `E_ARG`, an oversize one to
|
||||
`E_LIMIT` and an unknown op to `E_OP_UNKNOWN`.
|
||||
|
||||
## Handler output
|
||||
|
||||
- Response headers pass `filter_response_header`: `content-type`,
|
||||
`x-request-id`, `cache-control: no-store` and same-origin `location` only.
|
||||
`set-cookie` is never allowed.
|
||||
- Routes pass `route_allowed`: only `/apps/{id}/...` and
|
||||
`/api/v1/apps/{id}/...`.
|
||||
- Page output (UiTree, handler kind 4) is not checked in this crate yet;
|
||||
the UiTree checks belong to the PL-4 page work (d04 13.4.5).
|
||||
|
||||
## Native modules (`wmod/1`)
|
||||
|
||||
`wmod::check_module` runs the ELF checks of d04 13.3.5 on a Warden module:
|
||||
`ET_DYN`, ARM EABI5 hard-float, `DT_NEEDED` within the shipped libraries, no
|
||||
`RPATH`, `RUNPATH` or `TEXTREL`, `BIND_NOW`, non-executable stack, exports
|
||||
exactly `wmod_entry`, imports within `wmod-libc.allow` plus
|
||||
`wmod_exports.list`, with the denied families (allocator, files, sockets,
|
||||
`exec*`, `pthread_*`, signals, `setjmp`) refused whatever the lists say.
|
||||
`Info`, `check_info` and `check_grants` cover the info block and permission
|
||||
rows.
|
||||
|
||||
Hard-float is read from `e_flags` (`EF_ARM_ABI_FLOAT_HARD`), which the linker
|
||||
derives from `Tag_ABI_VFP_args`; the attribute section is not parsed.
|
||||
|
||||
## Not here
|
||||
|
||||
Signature, key class, revocation, floor and per-file hash checks are
|
||||
`wapp-core`. The wasmi runtime, fuel, store limits and the circuit breaker
|
||||
are `flare-plugin-host` (built into flare); the op implementations belong to
|
||||
the consumer behind its `HostOps` seam.
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Reason codes for refusals (s12 4.6, d04 13.3.5, 13.4.7).
|
||||
//!
|
||||
//! One enum carries a refusal from either verifier. The variants named by
|
||||
//! the `.wapp` set use the same spellings as `wapp_core::Code`, so a package
|
||||
//! refusal from `wapp_core::validate_full` keeps its code (`E_SIG`, `E_KEY`,
|
||||
//! ...). The plugin-only codes are `E_WASM`, `E_IMPORT` and `E_LIMIT`.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A refusal reason code, as shown in the UIs, the audit record and tests.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Code {
|
||||
Reserved,
|
||||
Source,
|
||||
Hash,
|
||||
Sig,
|
||||
Key,
|
||||
Revoked,
|
||||
Floor,
|
||||
Platform,
|
||||
Deps,
|
||||
Conflict,
|
||||
Budget,
|
||||
Grant,
|
||||
Precond,
|
||||
Policy,
|
||||
Dependents,
|
||||
Core,
|
||||
Veto,
|
||||
Compat,
|
||||
Manifest,
|
||||
Elf,
|
||||
Symbols,
|
||||
Snapshot,
|
||||
Wasm,
|
||||
Import,
|
||||
Limit,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
/// Every code, in declaration order.
|
||||
pub const ALL: &'static [Code] = &[
|
||||
Code::Reserved,
|
||||
Code::Source,
|
||||
Code::Hash,
|
||||
Code::Sig,
|
||||
Code::Key,
|
||||
Code::Revoked,
|
||||
Code::Floor,
|
||||
Code::Platform,
|
||||
Code::Deps,
|
||||
Code::Conflict,
|
||||
Code::Budget,
|
||||
Code::Grant,
|
||||
Code::Precond,
|
||||
Code::Policy,
|
||||
Code::Dependents,
|
||||
Code::Core,
|
||||
Code::Veto,
|
||||
Code::Compat,
|
||||
Code::Manifest,
|
||||
Code::Elf,
|
||||
Code::Symbols,
|
||||
Code::Snapshot,
|
||||
Code::Wasm,
|
||||
Code::Import,
|
||||
Code::Limit,
|
||||
];
|
||||
|
||||
/// The wire spelling, for example `E_MANIFEST`.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Code::Reserved => "E_RESERVED",
|
||||
Code::Source => "E_SOURCE",
|
||||
Code::Hash => "E_HASH",
|
||||
Code::Sig => "E_SIG",
|
||||
Code::Key => "E_KEY",
|
||||
Code::Revoked => "E_REVOKED",
|
||||
Code::Floor => "E_FLOOR",
|
||||
Code::Platform => "E_PLATFORM",
|
||||
Code::Deps => "E_DEPS",
|
||||
Code::Conflict => "E_CONFLICT",
|
||||
Code::Budget => "E_BUDGET",
|
||||
Code::Grant => "E_GRANT",
|
||||
Code::Precond => "E_PRECOND",
|
||||
Code::Policy => "E_POLICY",
|
||||
Code::Dependents => "E_DEPENDENTS",
|
||||
Code::Core => "E_CORE",
|
||||
Code::Veto => "E_VETO",
|
||||
Code::Compat => "E_COMPAT",
|
||||
Code::Manifest => "E_MANIFEST",
|
||||
Code::Elf => "E_ELF",
|
||||
Code::Symbols => "E_SYMBOLS",
|
||||
Code::Snapshot => "E_SNAPSHOT",
|
||||
Code::Wasm => "E_WASM",
|
||||
Code::Import => "E_IMPORT",
|
||||
Code::Limit => "E_LIMIT",
|
||||
}
|
||||
}
|
||||
|
||||
/// The code with this wire spelling, if any.
|
||||
pub fn from_wire(s: &str) -> Option<Code> {
|
||||
Code::ALL.iter().copied().find(|c| c.as_str() == s)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Code {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// A coded refusal with a plain detail line.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Error {
|
||||
pub code: Code,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn new(code: Code, detail: impl Into<String>) -> Self {
|
||||
Error {
|
||||
code,
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}: {}", self.code, self.detail)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// A package refusal from wapp-core keeps its wire code and detail.
|
||||
impl From<wapp_core::Error> for Error {
|
||||
fn from(e: wapp_core::Error) -> Self {
|
||||
let code = Code::from_wire(e.code.as_str()).unwrap_or(Code::Manifest);
|
||||
Error::new(code, e.detail)
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The `fp/1` plugin ABI surface (d04 13.4.2): names, handler kinds,
|
||||
//! negative codes, limits and the op registry. Pure data and validators;
|
||||
//! the wasmi runtime lives in `flare-plugin-host`.
|
||||
|
||||
use crate::code::{Code, Error, Result};
|
||||
use serde_json::Value;
|
||||
|
||||
pub const IMPORT_MODULE: &str = "fp1";
|
||||
pub const IMPORT_CALL: &str = "call";
|
||||
pub const IMPORT_LOG: &str = "log";
|
||||
|
||||
pub const EXPORT_MEMORY: &str = "memory";
|
||||
pub const EXPORT_ALLOC: &str = "fp_alloc";
|
||||
pub const EXPORT_FREE: &str = "fp_free";
|
||||
pub const EXPORT_INIT: &str = "fp_init";
|
||||
pub const EXPORT_HANDLE: &str = "fp_handle";
|
||||
|
||||
/// Largest module file (13.4.4 module admission).
|
||||
pub const MAX_MODULE_BYTES: usize = 2 * 1024 * 1024;
|
||||
/// Largest request or response body.
|
||||
pub const MAX_MESSAGE_BYTES: usize = 1024 * 1024;
|
||||
/// Host op calls per handler invocation.
|
||||
pub const MAX_CALLS_PER_HANDLER: u32 = 64;
|
||||
/// Longest log line.
|
||||
pub const MAX_LOG_BYTES: usize = 512;
|
||||
/// Wasm page size.
|
||||
pub const PAGE_BYTES: u64 = 65_536;
|
||||
|
||||
/// Default per-call fuel budget.
|
||||
pub const DEFAULT_FUEL: u64 = 50_000_000;
|
||||
/// Wall-clock deadline in milliseconds for `http`, `page` and `action`.
|
||||
pub const DEADLINE_FAST_MS: u64 = 250;
|
||||
/// Wall-clock deadline in milliseconds for `job` and `event`.
|
||||
pub const DEADLINE_SLOW_MS: u64 = 5_000;
|
||||
pub const MAX_INFLIGHT_PER_PLUGIN: u32 = 4;
|
||||
pub const MAX_INFLIGHT_PER_PORTAL: u32 = 32;
|
||||
|
||||
/// Circuit breaker: this many traps or timeouts inside the window trip it.
|
||||
pub const BREAKER_TRIPS: u32 = 5;
|
||||
pub const BREAKER_WINDOW_S: u64 = 60;
|
||||
pub const BREAKER_FIRST_HOLD_S: u64 = 600;
|
||||
pub const BREAKER_MAX_HOLD_S: u64 = 3_600;
|
||||
|
||||
/// Handler kinds passed as the first argument of `fp_handle`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Http = 1,
|
||||
Job = 2,
|
||||
Event = 3,
|
||||
Page = 4,
|
||||
Action = 5,
|
||||
Validate = 6,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn from_i32(n: i32) -> Option<Kind> {
|
||||
Some(match n {
|
||||
1 => Kind::Http,
|
||||
2 => Kind::Job,
|
||||
3 => Kind::Event,
|
||||
4 => Kind::Page,
|
||||
5 => Kind::Action,
|
||||
6 => Kind::Validate,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Wall-clock deadline for this kind.
|
||||
pub fn deadline_ms(self) -> u64 {
|
||||
match self {
|
||||
Kind::Job | Kind::Event => DEADLINE_SLOW_MS,
|
||||
_ => DEADLINE_FAST_MS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Negative return codes of `fp1.call`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Neg {
|
||||
OpUnknown = -1,
|
||||
OpDenied = -2,
|
||||
Arg = -3,
|
||||
Limit = -4,
|
||||
Timeout = -5,
|
||||
Upstream = -6,
|
||||
NotFound = -7,
|
||||
Conflict = -8,
|
||||
State = -9,
|
||||
}
|
||||
|
||||
impl Neg {
|
||||
pub fn code(self) -> i32 {
|
||||
self as i32
|
||||
}
|
||||
|
||||
pub fn from_i32(n: i32) -> Option<Neg> {
|
||||
Some(match n {
|
||||
-1 => Neg::OpUnknown,
|
||||
-2 => Neg::OpDenied,
|
||||
-3 => Neg::Arg,
|
||||
-4 => Neg::Limit,
|
||||
-5 => Neg::Timeout,
|
||||
-6 => Neg::Upstream,
|
||||
-7 => Neg::NotFound,
|
||||
-8 => Neg::Conflict,
|
||||
-9 => Neg::State,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Neg::OpUnknown => "E_OP_UNKNOWN",
|
||||
Neg::OpDenied => "E_OP_DENIED",
|
||||
Neg::Arg => "E_ARG",
|
||||
Neg::Limit => "E_LIMIT",
|
||||
Neg::Timeout => "E_TIMEOUT",
|
||||
Neg::Upstream => "E_UPSTREAM",
|
||||
Neg::NotFound => "E_NOT_FOUND",
|
||||
Neg::Conflict => "E_CONFLICT",
|
||||
Neg::State => "E_STATE",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a plugin needs before the host runs an op (13.4.3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Grant {
|
||||
/// No grant: the op works on the plugin's own namespace or is pure.
|
||||
None,
|
||||
/// The manifest sets `data.schema: true`.
|
||||
Schema,
|
||||
/// An admin-approved host list.
|
||||
Hosts,
|
||||
/// A per-site grant row.
|
||||
Site,
|
||||
/// A per-site grant that lists path patterns.
|
||||
SitePaths,
|
||||
/// A per-site grant that lists verbs; `platform` key class only.
|
||||
SiteVerbs,
|
||||
/// An admin-set plugin secret.
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// One host op of the v1 registry.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OpDef {
|
||||
pub name: &'static str,
|
||||
/// The family a manifest may name to cover this op, for example `kv@1`.
|
||||
pub family: &'static str,
|
||||
pub grant: Grant,
|
||||
}
|
||||
|
||||
const fn op(name: &'static str, family: &'static str, grant: Grant) -> OpDef {
|
||||
OpDef {
|
||||
name,
|
||||
family,
|
||||
grant,
|
||||
}
|
||||
}
|
||||
|
||||
/// The v1 op registry. A manifest may name only these.
|
||||
pub const OPS: &[OpDef] = &[
|
||||
op("kv.get@1", "kv@1", Grant::None),
|
||||
op("kv.put@1", "kv@1", Grant::None),
|
||||
op("kv.delete@1", "kv@1", Grant::None),
|
||||
op("kv.list@1", "kv@1", Grant::None),
|
||||
op("sql.query@1", "sql@1", Grant::Schema),
|
||||
op("sql.exec@1", "sql@1", Grant::Schema),
|
||||
op("http.fetch@1", "http.fetch@1", Grant::Hosts),
|
||||
op("telemetry.read@1", "telemetry.read@1", Grant::Site),
|
||||
op("cfg.read@1", "cfg.read@1", Grant::Site),
|
||||
op("cfg.write@1", "cfg.write@1", Grant::SitePaths),
|
||||
op("command.send@1", "command.send@1", Grant::SiteVerbs),
|
||||
op("audit@1", "audit@1", Grant::None),
|
||||
op("perm.check@1", "perm.check@1", Grant::None),
|
||||
op("appcred.verify@1", "appcred.verify@1", Grant::None),
|
||||
op("app.request@1", "app.request@1", Grant::Site),
|
||||
op("secret.get@1", "secret.get@1", Grant::Secret),
|
||||
op("time.now@1", "time.now@1", Grant::None),
|
||||
op("rand.bytes@1", "rand.bytes@1", Grant::None),
|
||||
];
|
||||
|
||||
/// Look an op up by its exact name.
|
||||
pub fn op_def(name: &str) -> Option<&'static OpDef> {
|
||||
OPS.iter().find(|o| o.name == name)
|
||||
}
|
||||
|
||||
/// True when `entry` (an op name or a family name) covers `op`.
|
||||
pub fn covers(entry: &str, op: &str) -> bool {
|
||||
op_def(op).is_some_and(|d| d.name == entry || d.family == entry)
|
||||
}
|
||||
|
||||
/// Check a manifest op list: every entry must be a known op or family.
|
||||
pub fn check_manifest_ops(entries: &[&str]) -> Result<()> {
|
||||
for e in entries {
|
||||
let known = OPS.iter().any(|o| o.name == *e || o.family == *e);
|
||||
if !known {
|
||||
return Err(Error::new(Code::Manifest, format!("unknown op {e}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A parsed `fp1.call` request.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CallRequest {
|
||||
pub op: &'static OpDef,
|
||||
pub args: Value,
|
||||
}
|
||||
|
||||
/// Parse the JSON request of `fp1.call`. Errors map to the negative code the
|
||||
/// host returns to the guest.
|
||||
pub fn parse_call(bytes: &[u8]) -> std::result::Result<CallRequest, Neg> {
|
||||
if bytes.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(Neg::Limit);
|
||||
}
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|_| Neg::Arg)?;
|
||||
let o = v.as_object().ok_or(Neg::Arg)?;
|
||||
if o.keys().any(|k| k != "op" && k != "args") {
|
||||
return Err(Neg::Arg);
|
||||
}
|
||||
let name = o.get("op").and_then(Value::as_str).ok_or(Neg::Arg)?;
|
||||
let def = op_def(name).ok_or(Neg::OpUnknown)?;
|
||||
let args = match o.get("args") {
|
||||
None => Value::Object(Default::default()),
|
||||
Some(a) if a.is_object() => a.clone(),
|
||||
Some(_) => return Err(Neg::Arg),
|
||||
};
|
||||
Ok(CallRequest { op: def, args })
|
||||
}
|
||||
|
||||
/// Response headers a plugin may set (13.4.2). `set-cookie` is never allowed.
|
||||
/// Returns the value to emit, or `None` to drop the header.
|
||||
pub fn filter_response_header(name: &str, value: &str) -> Option<String> {
|
||||
let n = name.to_ascii_lowercase();
|
||||
if value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) {
|
||||
return None;
|
||||
}
|
||||
match n.as_str() {
|
||||
"content-type" | "x-request-id" => Some(value.to_string()),
|
||||
"cache-control" => {
|
||||
(value.trim().eq_ignore_ascii_case("no-store")).then(|| "no-store".to_string())
|
||||
}
|
||||
// Same origin only: a path, never a scheme, authority or `//`.
|
||||
"location" => (value.starts_with('/') && !value.starts_with("//") && !value.contains('\\'))
|
||||
.then(|| value.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `path` is a route a plugin with id `id` may mount (13.4.2).
|
||||
pub fn route_allowed(id: &str, path: &str) -> bool {
|
||||
let ok_id = !id.is_empty()
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
|
||||
if !ok_id || path.contains("..") || path.contains("//") || path.contains('?') {
|
||||
return false;
|
||||
}
|
||||
let pages = format!("/apps/{id}/");
|
||||
let api = format!("/api/v1/apps/{id}/");
|
||||
(path.starts_with(&pages) && path.len() > pages.len())
|
||||
|| (path.starts_with(&api) && path.len() > api.len())
|
||||
|| path == format!("/apps/{id}")
|
||||
|| path == format!("/api/v1/apps/{id}")
|
||||
}
|
||||
+26
-2
@@ -1,6 +1,30 @@
|
||||
//! Plugin ABI shared by FLARE and the Warden console.
|
||||
//! Plugin and module admission shared by FLARE and the Warden console
|
||||
//! (d04 13.3.5, 13.4; B-13, W-D4).
|
||||
//!
|
||||
//! Placeholder until its owning lane lands the real crate (see OWNERS).
|
||||
//! - `package`: the admission entry points. Each one runs the `.wapp` package
|
||||
//! checks of `wapp_core::validate_full` first, so a signature, key class,
|
||||
//! hash or payload failure refuses the package before any code check runs.
|
||||
//! Only `platform`-signed code is admitted (`dev` only in a `plugin-dev`
|
||||
//! build, `partner` never). FLARE verifies signatures itself and refuses on
|
||||
//! failure (B-13).
|
||||
//! - `wmod`: the ELF verifier for panel modules (`ui/modules/*.so`, ABI
|
||||
//! `wmod/1`): header, dynamic section, symbol lists, info block, grants.
|
||||
//! - `wasm`: the Wasm verifier for FLARE plugins (ABI `fp/1`, feature `wasm`):
|
||||
//! core Wasm validated with `wasmparser`, imports, exports and limits.
|
||||
//! - `fp1`: the `fp/1` surface data: names, handler kinds, negative codes, the
|
||||
//! op registry and the request and header validators.
|
||||
//! - `code`: the reason codes shared by all of the above.
|
||||
//!
|
||||
//! The verifiers never run module code. Every check reads the bytes only.
|
||||
|
||||
pub mod code;
|
||||
pub mod fp1;
|
||||
pub mod package;
|
||||
#[cfg(feature = "wasm")]
|
||||
pub mod wasm;
|
||||
pub mod wmod;
|
||||
|
||||
pub use code::{Code, Error, Result};
|
||||
|
||||
/// Crate name, used by consumers to check which pin they vendored.
|
||||
pub const NAME: &str = "flare-plugin-abi";
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Admission of the code inside one signed `.wapp` (d04 13.3.5, 13.4.8; B-13).
|
||||
//!
|
||||
//! Each entry point runs `wapp_core::validate::validate_full` first (V01 to
|
||||
//! V09, V15 and V16), so a signature, key class, hash or payload failure
|
||||
//! refuses the package here, whatever the caller checked before. The signer
|
||||
//! must be `platform`. A `dev` signer is admitted only by a build with the
|
||||
//! `plugin-dev` feature, and a `partner` signer is never admitted: no
|
||||
//! third-party code runs before an out-of-process runtime exists (B-13).
|
||||
|
||||
use crate::code::{Code, Error, Result};
|
||||
use crate::wmod::{self, Compat, Expect, Info, NameList, Policy};
|
||||
use wapp_core::appkeys::KeyClass;
|
||||
use wapp_core::json::Value;
|
||||
use wapp_core::payload::Checked;
|
||||
use wapp_core::validate::{validate_full, Ctx, Validated};
|
||||
|
||||
/// True when this build admits `dev`-class signatures (feature `plugin-dev`).
|
||||
pub const DEV_COMPILED: bool = cfg!(feature = "plugin-dev");
|
||||
|
||||
/// The `FLARE_PLUGINS` modes (d04 13.4.8). `off` is the default.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PluginMode {
|
||||
/// Wasm plugins are refused with `E_KEY plugins_off`; descriptors install.
|
||||
Off,
|
||||
/// Only `platform`-signed plugins load.
|
||||
Signed,
|
||||
/// `dev`-signed plugins load too, and only in a `plugin-dev` build.
|
||||
Dev,
|
||||
}
|
||||
|
||||
impl PluginMode {
|
||||
/// The value of `FLARE_PLUGINS`, or `None` for any other text.
|
||||
pub fn parse(s: &str) -> Option<PluginMode> {
|
||||
match s {
|
||||
"off" => Some(PluginMode::Off),
|
||||
"signed" => Some(PluginMode::Signed),
|
||||
"dev" => Some(PluginMode::Dev),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Startup check: a release build refuses `FLARE_PLUGINS=dev` (13.4.8).
|
||||
pub fn check_startup(self) -> Result<()> {
|
||||
match self {
|
||||
PluginMode::Dev if !DEV_COMPILED => Err(Error::new(
|
||||
Code::Key,
|
||||
"FLARE_PLUGINS=dev needs a plugin-dev build",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse every signer class this build does not admit. `dev_wanted` says
|
||||
/// whether the caller accepts `dev` at all.
|
||||
fn check_signer(v: &Validated, dev_wanted: bool) -> Result<()> {
|
||||
match v.signer.class {
|
||||
KeyClass::Platform => Ok(()),
|
||||
KeyClass::Dev if dev_wanted && DEV_COMPILED => Ok(()),
|
||||
KeyClass::Dev => Err(Error::new(
|
||||
Code::Key,
|
||||
"dev key class is not admitted in this build",
|
||||
)),
|
||||
KeyClass::Partner => Err(Error::new(
|
||||
Code::Key,
|
||||
"partner key class is refused until an out-of-process runtime exists",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn missing(what: &str) -> Error {
|
||||
Error::new(Code::Manifest, format!("{what} is missing"))
|
||||
}
|
||||
|
||||
fn not_in_package(path: &str) -> Error {
|
||||
Error::new(Code::Manifest, format!("{path} is not in the package"))
|
||||
}
|
||||
|
||||
/// A FLARE plugin package admitted for install (13.4.7, `verified`).
|
||||
#[cfg(feature = "wasm")]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginAdmission {
|
||||
pub app_id: String,
|
||||
pub app_build: i64,
|
||||
pub kid: String,
|
||||
pub class: KeyClass,
|
||||
/// The module inside the package, for example `flare/plugin.wasm`.
|
||||
pub module: String,
|
||||
pub admitted: crate::wasm::Admitted,
|
||||
}
|
||||
|
||||
/// Admit the FLARE plugin in `archive`: the package checks, the platform
|
||||
/// signer, the `fp/1` block of the manifest and the Wasm module (13.4.4).
|
||||
#[cfg(feature = "wasm")]
|
||||
pub fn admit_plugin(mode: PluginMode, archive: &[u8], ctx: &Ctx<'_>) -> Result<PluginAdmission> {
|
||||
match mode {
|
||||
PluginMode::Off => return Err(Error::new(Code::Key, "plugins_off")),
|
||||
PluginMode::Dev => mode.check_startup()?,
|
||||
PluginMode::Signed => {}
|
||||
}
|
||||
let (v, checked) = validate_full(archive, ctx)?;
|
||||
check_signer(&v, mode == PluginMode::Dev)?;
|
||||
let flare = v
|
||||
.manifest
|
||||
.flare
|
||||
.as_ref()
|
||||
.ok_or_else(|| missing("manifest flare half"))?;
|
||||
let plugin = flare
|
||||
.plugin
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::new(Code::Manifest, "flare half is not a plugin"))?;
|
||||
if plugin.get("abi").and_then(Value::as_int) != Some(1) {
|
||||
return Err(Error::new(
|
||||
Code::Manifest,
|
||||
"flare.plugin.abi must be 1 (fp/1)",
|
||||
));
|
||||
}
|
||||
let module = plugin
|
||||
.get("module")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| missing("flare.plugin.module"))?;
|
||||
if !module.starts_with("flare/") {
|
||||
return Err(Error::new(
|
||||
Code::Manifest,
|
||||
"flare.plugin.module must be under flare/",
|
||||
));
|
||||
}
|
||||
let memory_mb = plugin
|
||||
.get("limits")
|
||||
.and_then(|l| l.get("memory_mb"))
|
||||
.and_then(Value::as_int)
|
||||
.and_then(|m| u32::try_from(m).ok())
|
||||
.ok_or_else(|| missing("flare.plugin.limits.memory_mb"))?;
|
||||
let bytes = checked.file(module).ok_or_else(|| not_in_package(module))?;
|
||||
let admitted = crate::wasm::admit(bytes, memory_mb)?;
|
||||
Ok(PluginAdmission {
|
||||
app_id: v.manifest.id.clone(),
|
||||
app_build: v.manifest.build,
|
||||
kid: v.signer.kid.clone(),
|
||||
class: v.signer.class,
|
||||
module: module.to_string(),
|
||||
admitted,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the firmware offers a panel module: the import lists, the ABI and
|
||||
/// LVGL build it runs, and the permission names the install granted.
|
||||
pub struct Host<'a> {
|
||||
/// `wmod-libc.allow`.
|
||||
pub libc_allow: &'a NameList,
|
||||
/// `wmod_exports.list`: the host symbols a Layer 2 module may call.
|
||||
pub host_exports: &'a NameList,
|
||||
/// The manifest declares C++, so `libstdc++.so.6` may be needed.
|
||||
pub cxx: bool,
|
||||
pub abi_major: u16,
|
||||
pub abi_minor: u16,
|
||||
pub lvgl_version: &'a str,
|
||||
pub sdk_hash: [u8; 32],
|
||||
/// Permission names the install granted, for example `ui.native`.
|
||||
pub granted: &'a [&'a str],
|
||||
}
|
||||
|
||||
/// A panel module admitted for install (13.3.5, `verified` in 13.3.6).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleAdmission {
|
||||
pub app_id: String,
|
||||
pub app_build: i64,
|
||||
pub kid: String,
|
||||
pub class: KeyClass,
|
||||
/// The module inside the package, for example `ui/modules/mining.so`.
|
||||
pub module: String,
|
||||
/// The libraries the module needs (DT_NEEDED).
|
||||
pub needed: Vec<String>,
|
||||
pub info: Info,
|
||||
/// `NeedsPlatform` when a matching firmware update must come first. That
|
||||
/// is still an admission: the install goes through (13.3.6).
|
||||
pub compat: Compat,
|
||||
}
|
||||
|
||||
/// Admit the panel module in `archive` (13.3.5). The package must be signed
|
||||
/// by `platform` (or `dev` in a `plugin-dev` build).
|
||||
pub fn admit_module(archive: &[u8], ctx: &Ctx<'_>, host: &Host<'_>) -> Result<ModuleAdmission> {
|
||||
let (v, checked) = validate_full(archive, ctx)?;
|
||||
admit_validated_module(&v, &checked, host)
|
||||
}
|
||||
|
||||
/// [`admit_module`] for a package that `validate_full` has already accepted.
|
||||
/// An installer holds that result by the time it checks the modules, so the
|
||||
/// package is verified once, not twice.
|
||||
pub fn admit_validated_module(
|
||||
v: &Validated,
|
||||
checked: &Checked,
|
||||
host: &Host<'_>,
|
||||
) -> Result<ModuleAdmission> {
|
||||
check_signer(v, true)?;
|
||||
let native = v
|
||||
.manifest
|
||||
.ui_native
|
||||
.as_ref()
|
||||
.ok_or_else(|| missing("ui.native block"))?;
|
||||
let module = native
|
||||
.get("module")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| missing("ui.native.module"))?;
|
||||
if !module.starts_with("ui/modules/") {
|
||||
return Err(Error::new(
|
||||
Code::Manifest,
|
||||
"ui.native.module must be under ui/modules/",
|
||||
));
|
||||
}
|
||||
let bytes = checked.file(module).ok_or_else(|| not_in_package(module))?;
|
||||
let policy = Policy {
|
||||
libc_allow: host.libc_allow,
|
||||
host_exports: host.host_exports,
|
||||
cxx: host.cxx,
|
||||
};
|
||||
let needed = wmod::check_module(bytes, &policy)?;
|
||||
let info = Info::parse(wmod::info_block(bytes)?)?;
|
||||
let app_build = u32::try_from(v.manifest.build)
|
||||
.map_err(|_| Error::new(Code::Manifest, "manifest build out of range"))?;
|
||||
let compat = wmod::check_info(
|
||||
&info,
|
||||
&Expect {
|
||||
abi_major: host.abi_major,
|
||||
abi_minor: host.abi_minor,
|
||||
app_id: &v.manifest.id,
|
||||
app_build,
|
||||
lvgl_version: host.lvgl_version,
|
||||
sdk_hash: host.sdk_hash,
|
||||
},
|
||||
)?;
|
||||
// Every platform verb the manifest declares must be granted (13.3.5).
|
||||
let verbs: Vec<&str> = v
|
||||
.manifest
|
||||
.permissions
|
||||
.iter()
|
||||
.filter_map(|p| p.name.strip_prefix("platform."))
|
||||
.collect();
|
||||
wmod::check_grants(&info, host.granted, &verbs)?;
|
||||
Ok(ModuleAdmission {
|
||||
app_id: v.manifest.id.clone(),
|
||||
app_build: v.manifest.build,
|
||||
kid: v.signer.kid.clone(),
|
||||
class: v.signer.class,
|
||||
module: module.to_string(),
|
||||
needed,
|
||||
info,
|
||||
compat,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Wasm module admission (d04 13.4.4): the checks that run before a plugin
|
||||
//! module is compiled, at install and again on every load from disk.
|
||||
//!
|
||||
//! Admitted modules import nothing but `fp1.call` and `fp1.log` (each at most
|
||||
//! once, with its fixed signature), have no start function, export the five
|
||||
//! required names with the right types, declare a single memory with a
|
||||
//! maximum at or below the manifest limit, use no threads or SIMD, and are at
|
||||
//! most 2 MiB. A module that imports only one of the two is admitted; the
|
||||
//! amendments in the crate README record that reading of 13.4.4.
|
||||
|
||||
use crate::code::{Code, Error, Result};
|
||||
use crate::fp1::*;
|
||||
use wasmparser::{
|
||||
CompositeInnerType, ExternalKind, FuncType, Parser, Payload, TypeRef, ValType, Validator,
|
||||
WasmFeatures,
|
||||
};
|
||||
|
||||
/// What admission learned about a module.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Admitted {
|
||||
pub memory_min_pages: u64,
|
||||
pub memory_max_pages: u64,
|
||||
pub imports_log: bool,
|
||||
pub imports_call: bool,
|
||||
}
|
||||
|
||||
fn wasm(m: impl Into<String>) -> Error {
|
||||
Error::new(Code::Wasm, m)
|
||||
}
|
||||
|
||||
/// Core Wasm 1.0 plus the post-MVP features rustc and clang emit by default
|
||||
/// that wasmi runs (sign extension, saturating conversion, multi-value, bulk
|
||||
/// memory, reference types). No threads, SIMD, GC, exceptions, memory64 or
|
||||
/// relaxed SIMD.
|
||||
fn features() -> WasmFeatures {
|
||||
WasmFeatures::MUTABLE_GLOBAL
|
||||
| WasmFeatures::SATURATING_FLOAT_TO_INT
|
||||
| WasmFeatures::SIGN_EXTENSION
|
||||
| WasmFeatures::MULTI_VALUE
|
||||
| WasmFeatures::BULK_MEMORY
|
||||
| WasmFeatures::REFERENCE_TYPES
|
||||
| WasmFeatures::FLOATS
|
||||
}
|
||||
|
||||
fn sig_is(t: &FuncType, params: &[ValType], results: &[ValType]) -> bool {
|
||||
t.params() == params && t.results() == results
|
||||
}
|
||||
|
||||
/// Admit `bytes` for a plugin whose manifest allows `memory_mb` MiB.
|
||||
pub fn admit(bytes: &[u8], memory_mb: u32) -> Result<Admitted> {
|
||||
if bytes.len() > MAX_MODULE_BYTES {
|
||||
return Err(Error::new(Code::Limit, "module larger than 2 MiB"));
|
||||
}
|
||||
if memory_mb == 0 {
|
||||
return Err(Error::new(
|
||||
Code::Manifest,
|
||||
"limits.memory_mb must be positive",
|
||||
));
|
||||
}
|
||||
let limit_pages = u64::from(memory_mb) * 16;
|
||||
let mut v = Validator::new_with_features(features());
|
||||
let mut types: Vec<Option<FuncType>> = Vec::new();
|
||||
// Type index of every function: imports first, then defined functions.
|
||||
let mut funcs: Vec<u32> = Vec::new();
|
||||
let (mut call_seen, mut log_seen) = (false, false);
|
||||
let mut memory: Option<(u64, u64)> = None;
|
||||
let mut tables = 0usize;
|
||||
let mut exports: Vec<(String, ExternalKind, u32)> = Vec::new();
|
||||
|
||||
for payload in Parser::new(0).parse_all(bytes) {
|
||||
let payload = payload.map_err(|e| wasm(format!("malformed module: {e}")))?;
|
||||
v.payload(&payload)
|
||||
.map_err(|e| wasm(format!("invalid module: {e}")))?;
|
||||
match payload {
|
||||
Payload::Version { encoding, .. } => {
|
||||
if encoding != wasmparser::Encoding::Module {
|
||||
return Err(wasm("not a core module"));
|
||||
}
|
||||
}
|
||||
Payload::TypeSection(r) => {
|
||||
for rg in r {
|
||||
let rg = rg.map_err(|e| wasm(e.to_string()))?;
|
||||
for st in rg.into_types() {
|
||||
types.push(match st.composite_type.inner {
|
||||
CompositeInnerType::Func(f) => Some(f),
|
||||
_ => return Err(wasm("only function types are allowed")),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Payload::ImportSection(r) => {
|
||||
for imp in r {
|
||||
let imp = imp.map_err(|e| wasm(e.to_string()))?;
|
||||
let TypeRef::Func(ti) = imp.ty else {
|
||||
return Err(Error::new(
|
||||
Code::Import,
|
||||
format!("import {}.{} is not a function", imp.module, imp.name),
|
||||
));
|
||||
};
|
||||
let t = types
|
||||
.get(ti as usize)
|
||||
.and_then(|t| t.as_ref())
|
||||
.ok_or_else(|| wasm("import type out of range"))?;
|
||||
use ValType::I32;
|
||||
match (imp.module, imp.name) {
|
||||
(IMPORT_MODULE, IMPORT_CALL) => {
|
||||
if call_seen || !sig_is(t, &[I32, I32, I32, I32], &[I32]) {
|
||||
return Err(Error::new(
|
||||
Code::Import,
|
||||
"fp1.call has the wrong type",
|
||||
));
|
||||
}
|
||||
call_seen = true;
|
||||
}
|
||||
(IMPORT_MODULE, IMPORT_LOG) => {
|
||||
if log_seen || !sig_is(t, &[I32, I32, I32], &[]) {
|
||||
return Err(Error::new(Code::Import, "fp1.log has the wrong type"));
|
||||
}
|
||||
log_seen = true;
|
||||
}
|
||||
(m, n) => {
|
||||
return Err(Error::new(Code::Import, format!("unknown import {m}.{n}")))
|
||||
}
|
||||
}
|
||||
funcs.push(ti);
|
||||
}
|
||||
}
|
||||
Payload::FunctionSection(r) => {
|
||||
for ti in r {
|
||||
funcs.push(ti.map_err(|e| wasm(e.to_string()))?);
|
||||
}
|
||||
}
|
||||
Payload::TableSection(r) => {
|
||||
tables += r.count() as usize;
|
||||
}
|
||||
Payload::MemorySection(r) => {
|
||||
for m in r {
|
||||
let m = m.map_err(|e| wasm(e.to_string()))?;
|
||||
if memory.is_some() {
|
||||
return Err(wasm("more than one memory"));
|
||||
}
|
||||
if m.memory64 || m.shared {
|
||||
return Err(wasm("memory64 and shared memory are not allowed"));
|
||||
}
|
||||
let Some(max) = m.maximum else {
|
||||
return Err(Error::new(Code::Limit, "memory has no declared maximum"));
|
||||
};
|
||||
if max > limit_pages {
|
||||
return Err(Error::new(
|
||||
Code::Limit,
|
||||
format!("memory maximum {max} pages exceeds {limit_pages}"),
|
||||
));
|
||||
}
|
||||
memory = Some((m.initial, max));
|
||||
}
|
||||
}
|
||||
Payload::StartSection { .. } => return Err(wasm("start function is not allowed")),
|
||||
Payload::ExportSection(r) => {
|
||||
for e in r {
|
||||
let e = e.map_err(|e| wasm(e.to_string()))?;
|
||||
exports.push((e.name.to_string(), e.kind, e.index));
|
||||
}
|
||||
}
|
||||
Payload::UnknownSection { .. } => return Err(wasm("unknown section")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if tables > 1 {
|
||||
return Err(wasm("more than one table"));
|
||||
}
|
||||
let Some((min, max)) = memory else {
|
||||
return Err(wasm("no memory defined"));
|
||||
};
|
||||
if min > max {
|
||||
return Err(wasm("memory minimum above maximum"));
|
||||
}
|
||||
|
||||
let find = |name: &str| exports.iter().find(|(n, _, _)| n == name);
|
||||
let func_sig = |name: &str, params: &[ValType], results: &[ValType]| -> Result<()> {
|
||||
let Some((_, kind, idx)) = find(name) else {
|
||||
return Err(wasm(format!("missing export {name}")));
|
||||
};
|
||||
if *kind != ExternalKind::Func {
|
||||
return Err(wasm(format!("export {name} is not a function")));
|
||||
}
|
||||
let ti = funcs
|
||||
.get(*idx as usize)
|
||||
.ok_or_else(|| wasm("export index out of range"))?;
|
||||
let t = types
|
||||
.get(*ti as usize)
|
||||
.and_then(|t| t.as_ref())
|
||||
.ok_or_else(|| wasm("function type out of range"))?;
|
||||
if sig_is(t, params, results) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(wasm(format!("export {name} has the wrong type")))
|
||||
}
|
||||
};
|
||||
use ValType::{I32, I64};
|
||||
match find(EXPORT_MEMORY) {
|
||||
Some((_, ExternalKind::Memory, 0)) => {}
|
||||
_ => return Err(wasm("missing export memory")),
|
||||
}
|
||||
func_sig(EXPORT_ALLOC, &[I32], &[I32])?;
|
||||
func_sig(EXPORT_FREE, &[I32, I32], &[])?;
|
||||
func_sig(EXPORT_INIT, &[I32, I32], &[I32])?;
|
||||
func_sig(EXPORT_HANDLE, &[I32, I32, I32], &[I64])?;
|
||||
for (i, (n, _, _)) in exports.iter().enumerate() {
|
||||
if exports[..i].iter().any(|(m, _, _)| m == n) {
|
||||
return Err(wasm("duplicate export name"));
|
||||
}
|
||||
}
|
||||
Ok(Admitted {
|
||||
memory_min_pages: min,
|
||||
memory_max_pages: max,
|
||||
imports_call: call_seen,
|
||||
imports_log: log_seen,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,923 @@
|
||||
//! Warden native module admission (d04 13.3.5): the static checks on a
|
||||
//! `wmod/1` shared object before `dlopen`.
|
||||
//!
|
||||
//! The input is attacker-shaped bytes, so every read is bounds checked and
|
||||
//! every count is capped. The verifier checks the image the loader maps: the
|
||||
//! dynamic section and every table it names are read at their load addresses
|
||||
//! through the PT_LOAD segments. A section header that names one of those
|
||||
//! tables must name the same file bytes (#187).
|
||||
|
||||
use crate::code::{Code, Error, Result};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub const ENTRY_SYMBOL: &str = "wmod_entry";
|
||||
|
||||
const ET_DYN: u16 = 3;
|
||||
const EM_ARM: u16 = 40;
|
||||
const EF_ARM_ABI_FLOAT_HARD: u32 = 0x400;
|
||||
const PT_LOAD: u32 = 1;
|
||||
const PT_DYNAMIC: u32 = 2;
|
||||
const PT_GNU_STACK: u32 = 0x6474_e551;
|
||||
const PF_X: u32 = 1;
|
||||
const STB_LOCAL: u8 = 0;
|
||||
const SHT_DYNSYM: u32 = 11;
|
||||
const SHT_NOBITS: u32 = 8;
|
||||
|
||||
const DT_NULL: u32 = 0;
|
||||
const DT_NEEDED: u32 = 1;
|
||||
const DT_STRTAB: u32 = 5;
|
||||
const DT_SYMTAB: u32 = 6;
|
||||
const DT_STRSZ: u32 = 10;
|
||||
const DT_RPATH: u32 = 15;
|
||||
const DT_TEXTREL: u32 = 22;
|
||||
const DT_RUNPATH: u32 = 29;
|
||||
const DT_FLAGS: u32 = 30;
|
||||
const DT_FLAGS_1: u32 = 0x6fff_fffb;
|
||||
const DF_TEXTREL: u32 = 4;
|
||||
const DF_BIND_NOW: u32 = 8;
|
||||
const DF_1_NOW: u32 = 1;
|
||||
|
||||
const MAX_PHNUM: usize = 64;
|
||||
const MAX_SHNUM: usize = 512;
|
||||
const MAX_DYN: usize = 512;
|
||||
const MAX_SYMS: usize = 65_536;
|
||||
|
||||
/// Libraries a module may need. `libstdc++.so.6` only when C++ is declared.
|
||||
pub const NEEDED_BASE: &[&str] = &["libc.so.0", "libm.so.0", "libgcc_s.so.1"];
|
||||
pub const NEEDED_CXX: &str = "libstdc++.so.6";
|
||||
|
||||
/// Imports refused whatever the allow list says (13.3.5): the allocator
|
||||
/// family, files and sockets, process control, signals, and bus handles.
|
||||
pub const DENIED_IMPORTS: &[&str] = &[
|
||||
"malloc",
|
||||
"calloc",
|
||||
"realloc",
|
||||
"free",
|
||||
"posix_memalign",
|
||||
"memalign",
|
||||
"aligned_alloc",
|
||||
"valloc",
|
||||
"open",
|
||||
"openat",
|
||||
"creat",
|
||||
"fopen",
|
||||
"fdopen",
|
||||
"freopen",
|
||||
"read",
|
||||
"write",
|
||||
"socket",
|
||||
"connect",
|
||||
"bind",
|
||||
"listen",
|
||||
"accept",
|
||||
"send",
|
||||
"recv",
|
||||
"sendto",
|
||||
"recvfrom",
|
||||
"mmap",
|
||||
"mmap2",
|
||||
"mprotect",
|
||||
"munmap",
|
||||
"dlopen",
|
||||
"dlsym",
|
||||
"dlclose",
|
||||
"fork",
|
||||
"vfork",
|
||||
"clone",
|
||||
"system",
|
||||
"popen",
|
||||
"signal",
|
||||
"sigaction",
|
||||
"setjmp",
|
||||
"longjmp",
|
||||
"_setjmp",
|
||||
"siglongjmp",
|
||||
"sigsetjmp",
|
||||
"abort",
|
||||
"exit",
|
||||
"_exit",
|
||||
"getenv",
|
||||
"setenv",
|
||||
"putenv",
|
||||
"kill",
|
||||
"raise",
|
||||
"syscall",
|
||||
"prctl",
|
||||
"ptrace",
|
||||
"ioctl",
|
||||
];
|
||||
|
||||
/// True for an import the verifier refuses whatever the allow list says:
|
||||
/// the exact names above plus the `pthread_*` and `exec*` families.
|
||||
pub fn is_denied(name: &str) -> bool {
|
||||
DENIED_IMPORTS.contains(&name) || name.starts_with("pthread_") || name.starts_with("exec")
|
||||
}
|
||||
|
||||
/// A parsed `wmod-libc.allow` or `wmod_exports.list`: names, with a trailing
|
||||
/// `*` as a prefix wildcard. Lines starting with `#` and blank lines are
|
||||
/// ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NameList {
|
||||
exact: BTreeSet<String>,
|
||||
prefix: Vec<String>,
|
||||
}
|
||||
|
||||
impl NameList {
|
||||
pub fn parse(text: &str) -> NameList {
|
||||
let mut l = NameList::default();
|
||||
for line in text.lines() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
match t.strip_suffix('*') {
|
||||
Some(p) => l.prefix.push(p.to_string()),
|
||||
None => {
|
||||
l.exact.insert(t.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
self.exact.contains(name) || self.prefix.iter().any(|p| name.starts_with(p.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the firmware tells the verifier about the module.
|
||||
pub struct Policy<'a> {
|
||||
/// `wmod-libc.allow`.
|
||||
pub libc_allow: &'a NameList,
|
||||
/// `wmod_exports.list`: host symbols a Layer 2 module may call.
|
||||
pub host_exports: &'a NameList,
|
||||
/// The manifest declares C++, so `libstdc++.so.6` may be needed.
|
||||
pub cxx: bool,
|
||||
}
|
||||
|
||||
fn elf<T>(m: impl Into<String>) -> Result<T> {
|
||||
Err(Error::new(Code::Elf, m))
|
||||
}
|
||||
|
||||
fn sym<T>(m: impl Into<String>) -> Result<T> {
|
||||
Err(Error::new(Code::Symbols, m))
|
||||
}
|
||||
|
||||
fn u16le(b: &[u8], o: usize) -> Option<u16> {
|
||||
Some(u16::from_le_bytes(
|
||||
b.get(o..o.checked_add(2)?)?.try_into().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
fn u32le(b: &[u8], o: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(
|
||||
b.get(o..o.checked_add(4)?)?.try_into().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
fn slice(b: &[u8], off: usize, len: usize) -> Option<&[u8]> {
|
||||
b.get(off..off.checked_add(len)?)
|
||||
}
|
||||
|
||||
fn cstr(table: &[u8], off: usize) -> Option<&str> {
|
||||
let rest = table.get(off..)?;
|
||||
let end = rest.iter().position(|&c| c == 0)?;
|
||||
std::str::from_utf8(&rest[..end]).ok()
|
||||
}
|
||||
|
||||
// Tags and flags the verifier reads beyond the constants above.
|
||||
const DT_PLTRELSZ: u32 = 2;
|
||||
const DT_HASH: u32 = 4;
|
||||
const DT_RELA: u32 = 7;
|
||||
const DT_RELASZ: u32 = 8;
|
||||
const DT_RELAENT: u32 = 9;
|
||||
const DT_REL: u32 = 17;
|
||||
const DT_RELSZ: u32 = 18;
|
||||
const DT_RELENT: u32 = 19;
|
||||
const DT_PLTREL: u32 = 20;
|
||||
const DT_JMPREL: u32 = 23;
|
||||
const DT_GNU_HASH: u32 = 0x6fff_fef5;
|
||||
const SHF_ALLOC: u32 = 2;
|
||||
|
||||
/// One PT_LOAD segment: the loader maps `filesz` bytes from file offset `off`
|
||||
/// at `vaddr` and zero-fills up to `memsz`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Load {
|
||||
vaddr: u32,
|
||||
memsz: u32,
|
||||
off: u32,
|
||||
filesz: u32,
|
||||
}
|
||||
|
||||
/// The file offset of the `len` bytes at virtual address `va`, when they all
|
||||
/// lie in the file contents of one PT_LOAD segment.
|
||||
///
|
||||
/// The dynamic linker reads the dynamic section, the string and symbol tables,
|
||||
/// the hash tables, the relocations and the info block at their load addresses.
|
||||
/// A table read at any other file offset can be a different table from the one
|
||||
/// that loads, so every such read goes through this mapping (13.3.5).
|
||||
fn va_off(loads: &[Load], va: u32, len: usize) -> Option<usize> {
|
||||
let end = u64::from(va).checked_add(len as u64)?;
|
||||
loads.iter().find_map(|l| {
|
||||
let seg_end = u64::from(l.vaddr) + u64::from(l.filesz);
|
||||
if u64::from(va) < u64::from(l.vaddr) || end > seg_end {
|
||||
return None;
|
||||
}
|
||||
(l.off as usize).checked_add((va - l.vaddr) as usize)
|
||||
})
|
||||
}
|
||||
|
||||
/// The u32 at `base + add`, with both the sum and the read checked.
|
||||
fn u32_at(b: &[u8], base: usize, add: usize) -> Option<u32> {
|
||||
u32le(b, base.checked_add(add)?)
|
||||
}
|
||||
|
||||
/// The u32 the loader reads at address `va`.
|
||||
fn va_u32(b: &[u8], loads: &[Load], va: u64) -> Result<u32> {
|
||||
let Ok(va) = u32::try_from(va) else {
|
||||
return elf("table address outside the 32-bit address space");
|
||||
};
|
||||
match va_off(loads, va, 4).and_then(|o| u32le(b, o)) {
|
||||
Some(v) => Ok(v),
|
||||
None => elf("table entry outside the load segments"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the loader sees of the image: its PT_LOAD segments and PT_DYNAMIC.
|
||||
struct Image {
|
||||
loads: Vec<Load>,
|
||||
/// (p_vaddr, p_offset, p_filesz) of PT_DYNAMIC.
|
||||
dynamic: Option<(u32, u32, u32)>,
|
||||
}
|
||||
|
||||
/// The ELF header and the program headers. `check_module` and `info_block`
|
||||
/// both start here, so the info block is found through the same segments as
|
||||
/// the rest of the image.
|
||||
fn parse_image(b: &[u8]) -> Result<Image> {
|
||||
if b.len() < 52 || &b[..4] != b"\x7fELF" {
|
||||
return elf("not an ELF file");
|
||||
}
|
||||
if b[4] != 1 || b[5] != 1 {
|
||||
return elf("not 32-bit little-endian");
|
||||
}
|
||||
if u16le(b, 16) != Some(ET_DYN) {
|
||||
return elf("not a shared object (ET_DYN)");
|
||||
}
|
||||
if u16le(b, 18) != Some(EM_ARM) {
|
||||
return elf("not EM_ARM");
|
||||
}
|
||||
let flags = u32le(b, 36).unwrap_or(0);
|
||||
if flags >> 24 != 5 {
|
||||
return elf("not EABI5");
|
||||
}
|
||||
if flags & EF_ARM_ABI_FLOAT_HARD == 0 {
|
||||
return elf("not hard-float (a soft-float build is refused)");
|
||||
}
|
||||
|
||||
// Program headers.
|
||||
let phoff = u32le(b, 28).unwrap_or(0) as usize;
|
||||
let phentsize = u16le(b, 42).unwrap_or(0) as usize;
|
||||
let phnum = u16le(b, 44).unwrap_or(0) as usize;
|
||||
if phentsize != 32 || phnum == 0 || phnum > MAX_PHNUM {
|
||||
return elf("bad program header table");
|
||||
}
|
||||
let mut loads: Vec<Load> = Vec::new();
|
||||
let mut dynamic = None;
|
||||
let mut stack_seen = false;
|
||||
for i in 0..phnum {
|
||||
// Checked: on the 32-bit panel build a hostile e_phoff must not wrap.
|
||||
let Some(o) = phoff.checked_add(i * 32) else {
|
||||
return elf("program header outside the file");
|
||||
};
|
||||
let (Some(ty), Some(off), Some(va), Some(fsz), Some(msz), Some(pf)) = (
|
||||
u32_at(b, o, 0),
|
||||
u32_at(b, o, 4),
|
||||
u32_at(b, o, 8),
|
||||
u32_at(b, o, 16),
|
||||
u32_at(b, o, 20),
|
||||
u32_at(b, o, 24),
|
||||
) else {
|
||||
return elf("program header outside the file");
|
||||
};
|
||||
match ty {
|
||||
PT_LOAD => {
|
||||
if msz < fsz {
|
||||
return elf("load segment is smaller in memory than in the file");
|
||||
}
|
||||
if slice(b, off as usize, fsz as usize).is_none() {
|
||||
return elf("load segment outside the file");
|
||||
}
|
||||
loads.push(Load {
|
||||
vaddr: va,
|
||||
memsz: msz,
|
||||
off,
|
||||
filesz: fsz,
|
||||
});
|
||||
}
|
||||
PT_DYNAMIC => {
|
||||
if dynamic.is_some() {
|
||||
return elf("more than one dynamic segment");
|
||||
}
|
||||
dynamic = Some((va, off, fsz));
|
||||
}
|
||||
PT_GNU_STACK => {
|
||||
stack_seen = true;
|
||||
if pf & PF_X != 0 {
|
||||
return elf("executable stack");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Two segments that map the same addresses have no single loaded image.
|
||||
for (i, a) in loads.iter().enumerate() {
|
||||
for c in &loads[i + 1..] {
|
||||
let a0 = u64::from(a.vaddr);
|
||||
let a1 = a0 + u64::from(a.memsz);
|
||||
let c0 = u64::from(c.vaddr);
|
||||
let c1 = c0 + u64::from(c.memsz);
|
||||
if a0 < c1 && c0 < a1 {
|
||||
return elf("load segments overlap");
|
||||
}
|
||||
}
|
||||
}
|
||||
if !stack_seen {
|
||||
return elf("no PT_GNU_STACK (stack permissions unknown)");
|
||||
}
|
||||
Ok(Image { loads, dynamic })
|
||||
}
|
||||
|
||||
/// One section header.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Shdr {
|
||||
ty: u32,
|
||||
flags: u32,
|
||||
addr: u32,
|
||||
off: u32,
|
||||
size: u32,
|
||||
}
|
||||
|
||||
/// Every section header with its name. The loader does not read section
|
||||
/// headers. The verifier reads them to find each table's file bytes and to
|
||||
/// check those bytes against the loaded addresses.
|
||||
fn sections(b: &[u8]) -> Result<Vec<(Shdr, &str)>> {
|
||||
let shoff = u32le(b, 32).unwrap_or(0) as usize;
|
||||
let shentsize = u16le(b, 46).unwrap_or(0) as usize;
|
||||
let shnum = u16le(b, 48).unwrap_or(0) as usize;
|
||||
let shstrndx = u16le(b, 50).unwrap_or(0) as usize;
|
||||
if shentsize != 40 || shnum == 0 || shnum > MAX_SHNUM {
|
||||
return elf("no usable section headers");
|
||||
}
|
||||
let mut raw: Vec<(usize, Shdr)> = Vec::with_capacity(shnum);
|
||||
for i in 0..shnum {
|
||||
let Some(o) = shoff.checked_add(i * 40) else {
|
||||
return elf("section header outside the file");
|
||||
};
|
||||
let (Some(name), Some(ty), Some(flags), Some(addr), Some(off), Some(size)) = (
|
||||
u32_at(b, o, 0),
|
||||
u32_at(b, o, 4),
|
||||
u32_at(b, o, 8),
|
||||
u32_at(b, o, 12),
|
||||
u32_at(b, o, 16),
|
||||
u32_at(b, o, 20),
|
||||
) else {
|
||||
return elf("section header outside the file");
|
||||
};
|
||||
raw.push((
|
||||
name as usize,
|
||||
Shdr {
|
||||
ty,
|
||||
flags,
|
||||
addr,
|
||||
off,
|
||||
size,
|
||||
},
|
||||
));
|
||||
}
|
||||
let names: &[u8] = match raw.get(shstrndx) {
|
||||
Some((_, s)) => slice(b, s.off as usize, s.size as usize).unwrap_or(&[]),
|
||||
None => &[],
|
||||
};
|
||||
Ok(raw
|
||||
.into_iter()
|
||||
.map(|(name, s)| (s, cstr(names, name).unwrap_or("")))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The dynamic entries the verifier uses, read from the loaded dynamic section.
|
||||
#[derive(Default)]
|
||||
struct Dynamic {
|
||||
needed: Vec<usize>,
|
||||
strtab: Option<u32>,
|
||||
strsz: Option<u32>,
|
||||
symtab: Option<u32>,
|
||||
hash: Option<u32>,
|
||||
gnu_hash: Option<u32>,
|
||||
rel: Option<u32>,
|
||||
relsz: Option<u32>,
|
||||
relent: Option<u32>,
|
||||
rela: Option<u32>,
|
||||
relasz: Option<u32>,
|
||||
relaent: Option<u32>,
|
||||
jmprel: Option<u32>,
|
||||
pltrelsz: Option<u32>,
|
||||
pltrel: Option<u32>,
|
||||
flags: u32,
|
||||
flags_1: u32,
|
||||
}
|
||||
|
||||
/// Read the dynamic section. A tag the verifier relies on may appear once: a
|
||||
/// second entry is refused rather than guessed at, because the verifier and
|
||||
/// the loader could otherwise read different copies.
|
||||
fn read_dynamic(dyn_bytes: &[u8]) -> Result<Dynamic> {
|
||||
let mut d = Dynamic::default();
|
||||
let mut seen: BTreeSet<u32> = BTreeSet::new();
|
||||
for (n, ent) in dyn_bytes.chunks_exact(8).enumerate() {
|
||||
if n >= MAX_DYN {
|
||||
return elf("dynamic section too long");
|
||||
}
|
||||
let tag = u32::from_le_bytes([ent[0], ent[1], ent[2], ent[3]]);
|
||||
let val = u32::from_le_bytes([ent[4], ent[5], ent[6], ent[7]]);
|
||||
if tag == DT_NULL {
|
||||
break;
|
||||
}
|
||||
let once = matches!(
|
||||
tag,
|
||||
DT_STRTAB
|
||||
| DT_STRSZ
|
||||
| DT_SYMTAB
|
||||
| DT_HASH
|
||||
| DT_GNU_HASH
|
||||
| DT_REL
|
||||
| DT_RELSZ
|
||||
| DT_RELENT
|
||||
| DT_RELA
|
||||
| DT_RELASZ
|
||||
| DT_RELAENT
|
||||
| DT_JMPREL
|
||||
| DT_PLTRELSZ
|
||||
| DT_PLTREL
|
||||
| DT_FLAGS
|
||||
| DT_FLAGS_1
|
||||
);
|
||||
if once && !seen.insert(tag) {
|
||||
return elf("more than one dynamic entry for a table the verifier reads");
|
||||
}
|
||||
match tag {
|
||||
DT_NEEDED => d.needed.push(val as usize),
|
||||
DT_STRTAB => d.strtab = Some(val),
|
||||
DT_STRSZ => d.strsz = Some(val),
|
||||
DT_SYMTAB => d.symtab = Some(val),
|
||||
DT_HASH => d.hash = Some(val),
|
||||
DT_GNU_HASH => d.gnu_hash = Some(val),
|
||||
DT_REL => d.rel = Some(val),
|
||||
DT_RELSZ => d.relsz = Some(val),
|
||||
DT_RELENT => d.relent = Some(val),
|
||||
DT_RELA => d.rela = Some(val),
|
||||
DT_RELASZ => d.relasz = Some(val),
|
||||
DT_RELAENT => d.relaent = Some(val),
|
||||
DT_JMPREL => d.jmprel = Some(val),
|
||||
DT_PLTRELSZ => d.pltrelsz = Some(val),
|
||||
DT_PLTREL => d.pltrel = Some(val),
|
||||
DT_RPATH | DT_RUNPATH => return elf("DT_RPATH or DT_RUNPATH present"),
|
||||
DT_TEXTREL => return elf("DT_TEXTREL present"),
|
||||
DT_FLAGS => d.flags = val,
|
||||
DT_FLAGS_1 => d.flags_1 = val,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// One relocation table, REL or RELA. The loader resolves each entry's symbol
|
||||
/// index without a bounds check, so every index must name a checked symbol.
|
||||
/// `nsyms` counts the checked entries, index 0 included.
|
||||
fn check_relocs(
|
||||
b: &[u8],
|
||||
loads: &[Load],
|
||||
table: Option<u32>,
|
||||
size: Option<u32>,
|
||||
declared_entsize: Option<u32>,
|
||||
entsize: u32,
|
||||
nsyms: usize,
|
||||
) -> Result<()> {
|
||||
if declared_entsize.is_some_and(|e| e != entsize) {
|
||||
return elf("relocation entry size is not the ELF size");
|
||||
}
|
||||
let size = size.unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(va) = table else {
|
||||
return elf("relocation size without a relocation table");
|
||||
};
|
||||
if size % entsize != 0 {
|
||||
return elf("relocation table is not a whole number of entries");
|
||||
}
|
||||
let Some(base) = va_off(loads, va, size as usize) else {
|
||||
return elf("relocation table is not in a load segment");
|
||||
};
|
||||
for k in 0..size / entsize {
|
||||
// r_info is the second word of both the REL and the RELA entry.
|
||||
let Some(info) = u32le(b, base + (k * entsize) as usize + 4) else {
|
||||
return elf("relocation table outside the file");
|
||||
};
|
||||
let index = (info >> 8) as usize;
|
||||
if index != 0 && index >= nsyms {
|
||||
return elf("relocation names a symbol outside the checked table");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// DT_HASH. A lookup walks these chains to find a symbol by name, so the table
|
||||
/// may count no more symbols than were checked, and every bucket and chain
|
||||
/// value must name a checked symbol.
|
||||
fn check_sysv_hash(b: &[u8], loads: &[Load], va: u32, nsyms: usize) -> Result<()> {
|
||||
let nbucket = va_u32(b, loads, u64::from(va))?;
|
||||
let nchain = va_u32(b, loads, u64::from(va) + 4)?;
|
||||
if nchain as usize > nsyms {
|
||||
return elf("hash table counts more symbols than the checked table");
|
||||
}
|
||||
let words = u64::from(nbucket) + u64::from(nchain);
|
||||
let Some(len) = words.checked_mul(4).and_then(|w| w.checked_add(8)) else {
|
||||
return elf("hash table too large");
|
||||
};
|
||||
let Some(base) = usize::try_from(len).ok().and_then(|n| va_off(loads, va, n)) else {
|
||||
return elf("hash table is not in one load segment");
|
||||
};
|
||||
let Some(body) = slice(b, base + 8, (len - 8) as usize) else {
|
||||
return elf("hash table outside the file");
|
||||
};
|
||||
for c in body.chunks_exact(4) {
|
||||
if u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as usize >= nsyms {
|
||||
return elf("hash table names a symbol outside the checked table");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// DT_GNU_HASH. A lookup walks each bucket's chain from `symoffset` until a
|
||||
/// chain word with its low bit set. Every index a walk reaches must name a
|
||||
/// checked symbol.
|
||||
fn check_gnu_hash(b: &[u8], loads: &[Load], va: u32, nsyms: usize) -> Result<()> {
|
||||
let va = u64::from(va);
|
||||
let nbuckets = u64::from(va_u32(b, loads, va)?);
|
||||
let symoffset = va_u32(b, loads, va + 4)?;
|
||||
let bloom_words = u64::from(va_u32(b, loads, va + 8)?);
|
||||
let buckets = va + 16 + 4 * bloom_words;
|
||||
let chains = buckets + 4 * nbuckets;
|
||||
let mut seen = vec![false; nsyms];
|
||||
for k in 0..nbuckets {
|
||||
let mut i = va_u32(b, loads, buckets + 4 * k)?;
|
||||
while i != 0 {
|
||||
if i < symoffset || i as usize >= nsyms {
|
||||
return elf("GNU hash chain names a symbol outside the checked table");
|
||||
}
|
||||
if seen[i as usize] {
|
||||
// Another bucket already walked the rest of this chain.
|
||||
break;
|
||||
}
|
||||
seen[i as usize] = true;
|
||||
let link = va_u32(b, loads, chains + 4 * u64::from(i - symoffset))?;
|
||||
if link & 1 != 0 {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Admit a module, returning the `DT_NEEDED` list on success.
|
||||
///
|
||||
/// The loader's view is the one checked. The dynamic section and every table
|
||||
/// it names are read at their load addresses through the PT_LOAD segments. A
|
||||
/// section header that names one of them must name the same file bytes, and
|
||||
/// the symbol checks cover every index the loader can reach.
|
||||
pub fn check_module(b: &[u8], policy: &Policy<'_>) -> Result<Vec<String>> {
|
||||
let image = parse_image(b)?;
|
||||
let loads = &image.loads;
|
||||
|
||||
// The dynamic section, read where the loader maps it (p_vaddr). Its file
|
||||
// offset must name the same bytes.
|
||||
let Some((dva, doff, dsz)) = image.dynamic else {
|
||||
return elf("no dynamic segment");
|
||||
};
|
||||
let Some(dyn_at) = va_off(loads, dva, dsz as usize) else {
|
||||
return elf("dynamic segment is not in a load segment");
|
||||
};
|
||||
if dyn_at != doff as usize {
|
||||
return elf("dynamic segment file offset differs from its load address");
|
||||
}
|
||||
let Some(dyn_bytes) = slice(b, dyn_at, dsz as usize) else {
|
||||
return elf("dynamic segment outside the file");
|
||||
};
|
||||
let d = read_dynamic(dyn_bytes)?;
|
||||
// Modern linkers record text relocations as DF_TEXTREL in DT_FLAGS rather
|
||||
// than with the DT_TEXTREL tag, so both spellings are refused (13.3.5).
|
||||
if d.flags & DF_TEXTREL != 0 {
|
||||
return elf("DF_TEXTREL in DT_FLAGS (text relocations)");
|
||||
}
|
||||
if d.flags & DF_BIND_NOW == 0 && d.flags_1 & DF_1_NOW == 0 {
|
||||
return elf("not linked with BIND_NOW");
|
||||
}
|
||||
let (Some(strtab), Some(strsz), Some(symtab)) = (d.strtab, d.strsz, d.symtab) else {
|
||||
return elf("missing DT_STRTAB, DT_STRSZ or DT_SYMTAB");
|
||||
};
|
||||
let Some(str_at) = va_off(loads, strtab, strsz as usize) else {
|
||||
return elf("string table not in a load segment");
|
||||
};
|
||||
let Some(strs) = slice(b, str_at, strsz as usize) else {
|
||||
return elf("string table outside the file");
|
||||
};
|
||||
|
||||
let mut needed = Vec::new();
|
||||
for &o in &d.needed {
|
||||
let Some(name) = cstr(strs, o) else {
|
||||
return elf("bad DT_NEEDED string");
|
||||
};
|
||||
let ok = NEEDED_BASE.contains(&name) || (policy.cxx && name == NEEDED_CXX);
|
||||
if !ok {
|
||||
return elf(format!(
|
||||
"needs {name}, which the firmware does not ship for modules"
|
||||
));
|
||||
}
|
||||
needed.push(name.to_string());
|
||||
}
|
||||
|
||||
// The dynamic symbol table is the one at DT_SYMTAB. Its section header must
|
||||
// name the same file bytes, and the table is read from there.
|
||||
let secs = sections(b)?;
|
||||
let mut dynsym: Option<Shdr> = None;
|
||||
for (s, _) in &secs {
|
||||
if s.addr != symtab {
|
||||
continue;
|
||||
}
|
||||
if s.ty == SHT_NOBITS {
|
||||
return elf("dynamic symbol table has no file contents");
|
||||
}
|
||||
if s.ty == SHT_DYNSYM {
|
||||
if dynsym.is_some() {
|
||||
return elf("more than one section matches DT_SYMTAB");
|
||||
}
|
||||
dynsym = Some(*s);
|
||||
}
|
||||
}
|
||||
let Some(sym_sec) = dynsym else {
|
||||
return elf("no section matches DT_SYMTAB");
|
||||
};
|
||||
if sym_sec.size % 16 != 0 {
|
||||
return elf("dynamic symbol table is not a whole number of entries");
|
||||
}
|
||||
let Some(sym_at) = va_off(loads, symtab, sym_sec.size as usize) else {
|
||||
return elf("dynamic symbol table is not in one load segment");
|
||||
};
|
||||
if sym_at != sym_sec.off as usize {
|
||||
return elf("dynamic symbol table section offset differs from DT_SYMTAB's load address");
|
||||
}
|
||||
let Some(syms) = slice(b, sym_at, sym_sec.size as usize) else {
|
||||
return elf("symbol table outside the file");
|
||||
};
|
||||
let nsyms = syms.len() / 16;
|
||||
if nsyms > MAX_SYMS {
|
||||
return elf("too many symbols");
|
||||
}
|
||||
let mut defined = Vec::new();
|
||||
let mut undefined = Vec::new();
|
||||
for s in syms.chunks_exact(16).skip(1) {
|
||||
let name_off = u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as usize;
|
||||
let bind = s[12] >> 4;
|
||||
let shndx = u16::from_le_bytes([s[14], s[15]]);
|
||||
// Only LOCAL symbols stay out of the checks. GNU_UNIQUE (10) and the
|
||||
// OS and processor ranges (11-15) bind by name like GLOBAL and WEAK,
|
||||
// so they count as global: an extra one is an extra export, and an
|
||||
// unlisted one is an unlisted import. Counting only 1 and 2 let them
|
||||
// skip both checks.
|
||||
if bind == STB_LOCAL {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = cstr(strs, name_off) else {
|
||||
return elf("bad symbol name");
|
||||
};
|
||||
// An empty name is still a binding the loader can use, so it is
|
||||
// checked like any other name instead of being skipped.
|
||||
if shndx == 0 {
|
||||
undefined.push(name.to_string());
|
||||
} else {
|
||||
defined.push(name.to_string());
|
||||
}
|
||||
}
|
||||
if defined.len() != 1 || defined[0] != ENTRY_SYMBOL {
|
||||
return sym(format!(
|
||||
"exports must be exactly {ENTRY_SYMBOL}, found {} defined global symbols",
|
||||
defined.len()
|
||||
));
|
||||
}
|
||||
for name in &undefined {
|
||||
if name.is_empty() {
|
||||
return sym("import with an empty name is not allowed");
|
||||
}
|
||||
if is_denied(name) {
|
||||
return sym(format!("import {name} is forbidden"));
|
||||
}
|
||||
if !(policy.libc_allow.contains(name) || policy.host_exports.contains(name)) {
|
||||
return sym(format!("import {name} is not allowed"));
|
||||
}
|
||||
}
|
||||
|
||||
// The loader reaches a symbol by index through relocations and by chain
|
||||
// through the hash tables. Each such index must be a checked symbol.
|
||||
check_relocs(b, loads, d.rel, d.relsz, d.relent, 8, nsyms)?;
|
||||
check_relocs(b, loads, d.rela, d.relasz, d.relaent, 12, nsyms)?;
|
||||
let plt_entsize = match d.pltrel {
|
||||
Some(DT_REL) => 8,
|
||||
Some(DT_RELA) => 12,
|
||||
Some(_) => return elf("DT_PLTREL names neither REL nor RELA"),
|
||||
None if d.jmprel.is_none() => 8,
|
||||
None => return elf("DT_JMPREL without DT_PLTREL"),
|
||||
};
|
||||
check_relocs(b, loads, d.jmprel, d.pltrelsz, None, plt_entsize, nsyms)?;
|
||||
if let Some(h) = d.hash {
|
||||
check_sysv_hash(b, loads, h, nsyms)?;
|
||||
}
|
||||
if let Some(g) = d.gnu_hash {
|
||||
check_gnu_hash(b, loads, g, nsyms)?;
|
||||
}
|
||||
Ok(needed)
|
||||
}
|
||||
|
||||
/// The fixed prefix of `wmod_info_t` (d04 13.3.3), 32-bit little endian.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Info {
|
||||
pub size: u32,
|
||||
pub abi_major: u16,
|
||||
pub abi_minor: u16,
|
||||
pub app_id: String,
|
||||
pub app_build: u32,
|
||||
pub flags: u32,
|
||||
pub lvgl_version: String,
|
||||
pub sdk_hash: [u8; 32],
|
||||
}
|
||||
|
||||
pub const INFO_SIZE_MIN: usize = 4 + 2 + 2 + 32 + 4 + 4 + 16 + 32;
|
||||
pub const F_LVGL_DIRECT: u32 = 1;
|
||||
|
||||
fn fixed_str(b: &[u8]) -> Option<String> {
|
||||
let end = b.iter().position(|&c| c == 0)?;
|
||||
if !b[..end].is_ascii() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8_lossy(&b[..end]).into_owned())
|
||||
}
|
||||
|
||||
impl Info {
|
||||
/// Parse the fixed prefix. The pointer members that follow are read by
|
||||
/// the host from the loaded image, not here.
|
||||
pub fn parse(b: &[u8]) -> Result<Info> {
|
||||
if b.len() < INFO_SIZE_MIN {
|
||||
return Err(Error::new(Code::Platform, "info block too short"));
|
||||
}
|
||||
let size = u32le(b, 0).unwrap_or(0);
|
||||
if (size as usize) < INFO_SIZE_MIN {
|
||||
return Err(Error::new(
|
||||
Code::Platform,
|
||||
"info block size field too small",
|
||||
));
|
||||
}
|
||||
let bad = || Error::new(Code::Platform, "info block string not terminated ASCII");
|
||||
let mut hash = [0u8; 32];
|
||||
hash.copy_from_slice(&b[64..96]);
|
||||
Ok(Info {
|
||||
size,
|
||||
abi_major: u16le(b, 4).unwrap_or(0),
|
||||
abi_minor: u16le(b, 6).unwrap_or(0),
|
||||
app_id: fixed_str(&b[8..40]).ok_or_else(bad)?,
|
||||
app_build: u32le(b, 40).unwrap_or(0),
|
||||
flags: u32le(b, 44).unwrap_or(0),
|
||||
lvgl_version: fixed_str(&b[48..64]).ok_or_else(bad)?,
|
||||
sdk_hash: hash,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Section that holds the `wmod_info_t` block. The module SDK links the block
|
||||
/// here so the verifier can read it without running the module: `wmod_entry`
|
||||
/// is the only exported symbol, so no symbol can name the block (13.3.2,
|
||||
/// 13.3.5). The name is an amendment to 13.3.5, which leaves the locator open.
|
||||
pub const INFO_SECTION: &str = ".wmod_info";
|
||||
|
||||
/// The bytes of the info block, found by section name. The host reads the
|
||||
/// block at its load address, so the section must be allocated, must map
|
||||
/// through the PT_LOAD segments to the file bytes its header names, and must be
|
||||
/// the only section of that name. The caller parses the result with
|
||||
/// [`Info::parse`].
|
||||
pub fn info_block(b: &[u8]) -> Result<&[u8]> {
|
||||
let image = parse_image(b)?;
|
||||
let secs = sections(b)?;
|
||||
let mut found: Option<Shdr> = None;
|
||||
for (s, name) in &secs {
|
||||
if *name == INFO_SECTION {
|
||||
if found.is_some() {
|
||||
return elf("more than one .wmod_info section");
|
||||
}
|
||||
found = Some(*s);
|
||||
}
|
||||
}
|
||||
let Some(s) = found else {
|
||||
return elf("no .wmod_info section (the info block cannot be found)");
|
||||
};
|
||||
if s.flags & SHF_ALLOC == 0 {
|
||||
return elf(".wmod_info is not allocated, so the loader does not map it");
|
||||
}
|
||||
let Some(at) = va_off(&image.loads, s.addr, s.size as usize) else {
|
||||
return elf(".wmod_info is not in a load segment");
|
||||
};
|
||||
if at != s.off as usize {
|
||||
return elf(".wmod_info file offset differs from its load address");
|
||||
}
|
||||
match slice(b, at, s.size as usize) {
|
||||
Some(bytes) if bytes.len() >= INFO_SIZE_MIN => Ok(bytes),
|
||||
_ => elf("info block section outside the file or too short"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the firmware and manifest expect of the info block.
|
||||
pub struct Expect<'a> {
|
||||
pub abi_major: u16,
|
||||
pub abi_minor: u16,
|
||||
pub app_id: &'a str,
|
||||
pub app_build: u32,
|
||||
pub lvgl_version: &'a str,
|
||||
pub sdk_hash: [u8; 32],
|
||||
}
|
||||
|
||||
/// Outcome of the info-block check: a mismatch the device can recover from by
|
||||
/// a firmware update is `NeedsPlatform` (module state `needs_platform`), not
|
||||
/// a refusal.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Compat {
|
||||
Ok,
|
||||
NeedsPlatform(String),
|
||||
}
|
||||
|
||||
/// Check the info block (13.3.5, 13.3.6). A wrong id or build, or an ABI
|
||||
/// major other than the host's, is refused with `E_PLATFORM`: the file is not
|
||||
/// a module this firmware can load (13.3.10, "major mismatch refused"). A
|
||||
/// newer ABI minor, or an LVGL or SDK mismatch, is `NeedsPlatform`: a firmware
|
||||
/// update that matches makes the module loadable (13.3.6).
|
||||
pub fn check_info(i: &Info, e: &Expect<'_>) -> Result<Compat> {
|
||||
if i.app_id != e.app_id {
|
||||
return Err(Error::new(
|
||||
Code::Platform,
|
||||
"app_id differs from the manifest",
|
||||
));
|
||||
}
|
||||
if i.app_build != e.app_build {
|
||||
return Err(Error::new(
|
||||
Code::Platform,
|
||||
"app_build differs from the manifest",
|
||||
));
|
||||
}
|
||||
if i.abi_major != e.abi_major {
|
||||
return Err(Error::new(
|
||||
Code::Platform,
|
||||
format!(
|
||||
"module ABI major {} differs from the host major {}",
|
||||
i.abi_major, e.abi_major
|
||||
),
|
||||
));
|
||||
}
|
||||
if i.abi_minor > e.abi_minor {
|
||||
return Ok(Compat::NeedsPlatform(format!(
|
||||
"module ABI minor {} is above the host minor {}",
|
||||
i.abi_minor, e.abi_minor
|
||||
)));
|
||||
}
|
||||
if i.flags & F_LVGL_DIRECT != 0
|
||||
&& (i.lvgl_version != e.lvgl_version || i.sdk_hash != e.sdk_hash)
|
||||
{
|
||||
return Ok(Compat::NeedsPlatform(
|
||||
"LVGL version or SDK hash differs".into(),
|
||||
));
|
||||
}
|
||||
Ok(Compat::Ok)
|
||||
}
|
||||
|
||||
/// Permission check (13.3.5): `ui.native` granted, `ui.lvgl_direct` when the
|
||||
/// flag is set, and each `platform.<verb>` the module uses is granted.
|
||||
pub fn check_grants(info: &Info, granted: &[&str], verbs_used: &[&str]) -> Result<()> {
|
||||
let has = |p: &str| granted.contains(&p);
|
||||
if !has("ui.native") {
|
||||
return Err(Error::new(Code::Grant, "ui.native not granted"));
|
||||
}
|
||||
if info.flags & F_LVGL_DIRECT != 0 && !has("ui.lvgl_direct") {
|
||||
return Err(Error::new(Code::Grant, "ui.lvgl_direct not granted"));
|
||||
}
|
||||
for v in verbs_used {
|
||||
if !has(&format!("platform.{v}")) {
|
||||
return Err(Error::new(Code::Grant, format!("platform.{v} not granted")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,817 @@
|
||||
//! Builders for hostile and valid inputs. Everything is generated, so the
|
||||
//! vectors are reviewable as code and no binary blobs are checked in.
|
||||
#![allow(dead_code)]
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use flare_plugin_abi::wmod::INFO_SIZE_MIN;
|
||||
use std::collections::BTreeMap;
|
||||
use wapp_core::appkeys::{AllowedIds, AppKey, KeyClass};
|
||||
use wapp_core::build::{pack, public_of};
|
||||
use wapp_core::json::{self, Value};
|
||||
use wapp_core::platform::Platform;
|
||||
use wapp_core::validate::{Ctx, Revocations};
|
||||
|
||||
pub fn leb(mut n: u32) -> Vec<u8> {
|
||||
let mut o = Vec::new();
|
||||
loop {
|
||||
let b = (n & 0x7f) as u8;
|
||||
n >>= 7;
|
||||
if n == 0 {
|
||||
o.push(b);
|
||||
return o;
|
||||
}
|
||||
o.push(b | 0x80);
|
||||
}
|
||||
}
|
||||
|
||||
fn name(s: &str) -> Vec<u8> {
|
||||
let mut o = leb(s.len() as u32);
|
||||
o.extend_from_slice(s.as_bytes());
|
||||
o
|
||||
}
|
||||
|
||||
fn section(id: u8, body: Vec<u8>) -> Vec<u8> {
|
||||
let mut o = vec![id];
|
||||
o.extend(leb(body.len() as u32));
|
||||
o.extend(body);
|
||||
o
|
||||
}
|
||||
|
||||
fn vec_of(items: Vec<Vec<u8>>) -> Vec<u8> {
|
||||
let mut o = leb(items.len() as u32);
|
||||
for i in items {
|
||||
o.extend(i);
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
const I32: u8 = 0x7f;
|
||||
const I64: u8 = 0x7e;
|
||||
|
||||
fn functype(p: &[u8], r: &[u8]) -> Vec<u8> {
|
||||
let mut o = vec![0x60];
|
||||
o.extend(leb(p.len() as u32));
|
||||
o.extend_from_slice(p);
|
||||
o.extend(leb(r.len() as u32));
|
||||
o.extend_from_slice(r);
|
||||
o
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct W {
|
||||
pub extra_import: Option<(&'static str, &'static str)>,
|
||||
pub memory_import: bool,
|
||||
pub start: bool,
|
||||
/// (min, max, shared)
|
||||
pub memory: Option<(u32, Option<u32>, bool)>,
|
||||
pub second_memory: bool,
|
||||
pub tables: usize,
|
||||
pub drop_export: Option<&'static str>,
|
||||
pub handle_returns_i32: bool,
|
||||
pub call_sig_wrong: bool,
|
||||
pub simd: bool,
|
||||
pub pad: usize,
|
||||
pub duplicate_log: bool,
|
||||
}
|
||||
|
||||
impl Default for W {
|
||||
fn default() -> Self {
|
||||
W {
|
||||
extra_import: None,
|
||||
memory_import: false,
|
||||
start: false,
|
||||
memory: Some((1, Some(4), false)),
|
||||
second_memory: false,
|
||||
tables: 0,
|
||||
drop_export: None,
|
||||
handle_returns_i32: false,
|
||||
call_sig_wrong: false,
|
||||
simd: false,
|
||||
pad: 0,
|
||||
duplicate_log: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl W {
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
let mut m = b"\0asm\x01\0\0\0".to_vec();
|
||||
let t_call: Vec<u8> = if self.call_sig_wrong {
|
||||
functype(&[I32, I32], &[I32])
|
||||
} else {
|
||||
functype(&[I32, I32, I32, I32], &[I32])
|
||||
};
|
||||
let mut types = vec![
|
||||
t_call, // 0
|
||||
functype(&[I32, I32, I32], &[]), // 1 log
|
||||
functype(&[I32], &[I32]), // 2 alloc
|
||||
functype(&[I32, I32], &[]), // 3 free
|
||||
functype(&[I32, I32], &[I32]), // 4 init
|
||||
functype(&[I32, I32, I32], &[I64]), // 5 handle
|
||||
functype(&[I32, I32, I32], &[I32]), // 6 handle (wrong)
|
||||
functype(&[], &[]), // 7 start
|
||||
];
|
||||
if self.simd {
|
||||
types.push(functype(&[], &[0x7b])); // v128 result
|
||||
}
|
||||
m.extend(section(1, vec_of(types)));
|
||||
|
||||
let mut imports = vec![
|
||||
[name("fp1"), name("call"), vec![0x00, 0]].concat(),
|
||||
[name("fp1"), name("log"), vec![0x00, 1]].concat(),
|
||||
];
|
||||
if self.duplicate_log {
|
||||
imports.push([name("fp1"), name("log"), vec![0x00, 1]].concat());
|
||||
}
|
||||
if let Some((a, b)) = self.extra_import {
|
||||
imports.push([name(a), name(b), vec![0x00, 1]].concat());
|
||||
}
|
||||
if self.memory_import {
|
||||
imports.push([name("env"), name("memory"), vec![0x02, 0x01, 1, 4]].concat());
|
||||
}
|
||||
let n_imp_funcs = imports.len() as u32 - u32::from(self.memory_import);
|
||||
m.extend(section(2, vec_of(imports)));
|
||||
|
||||
let mut funcs = vec![
|
||||
vec![2u8],
|
||||
vec![3],
|
||||
vec![4],
|
||||
vec![if self.handle_returns_i32 { 6 } else { 5 }],
|
||||
];
|
||||
if self.start {
|
||||
funcs.push(vec![7]);
|
||||
}
|
||||
if self.simd {
|
||||
funcs.push(vec![8]);
|
||||
}
|
||||
let n_funcs = funcs.len();
|
||||
m.extend(section(3, vec_of(funcs)));
|
||||
|
||||
if self.tables > 0 {
|
||||
let t = (0..self.tables).map(|_| vec![0x70, 0x00, 1]).collect();
|
||||
m.extend(section(4, vec_of(t)));
|
||||
}
|
||||
let mut mems = Vec::new();
|
||||
if let Some((min, max, shared)) = self.memory {
|
||||
let mut e = Vec::new();
|
||||
let flag = u8::from(max.is_some()) | if shared { 2 } else { 0 };
|
||||
e.push(flag);
|
||||
e.extend(leb(min));
|
||||
if let Some(x) = max {
|
||||
e.extend(leb(x));
|
||||
}
|
||||
mems.push(e.clone());
|
||||
if self.second_memory {
|
||||
mems.push(e);
|
||||
}
|
||||
}
|
||||
if !mems.is_empty() {
|
||||
m.extend(section(5, vec_of(mems)));
|
||||
}
|
||||
|
||||
let f0 = n_imp_funcs; // first defined function index
|
||||
let mut exports = Vec::new();
|
||||
let mut add = |n: &'static str, kind: u8, idx: u32| {
|
||||
if self.drop_export != Some(n) {
|
||||
exports.push([name(n), vec![kind], leb(idx)].concat());
|
||||
}
|
||||
};
|
||||
add("memory", 2, 0);
|
||||
add("fp_alloc", 0, f0);
|
||||
add("fp_free", 0, f0 + 1);
|
||||
add("fp_init", 0, f0 + 2);
|
||||
add("fp_handle", 0, f0 + 3);
|
||||
m.extend(section(7, vec_of(exports)));
|
||||
|
||||
if self.start {
|
||||
m.extend(section(8, leb(f0 + 4)));
|
||||
}
|
||||
let mut bodies = vec![
|
||||
vec![0x04, 0x00, 0x41, 0x00, 0x0b],
|
||||
vec![0x02, 0x00, 0x0b],
|
||||
vec![0x04, 0x00, 0x41, 0x00, 0x0b],
|
||||
if self.handle_returns_i32 {
|
||||
vec![0x04, 0x00, 0x41, 0x00, 0x0b]
|
||||
} else {
|
||||
vec![0x04, 0x00, 0x42, 0x00, 0x0b]
|
||||
},
|
||||
];
|
||||
if self.start {
|
||||
bodies.push(vec![0x02, 0x00, 0x0b]);
|
||||
}
|
||||
if self.simd {
|
||||
// v128.const 0 (16 zero bytes)
|
||||
let mut b = vec![0x00, 0xfd, 0x0c];
|
||||
b.extend([0u8; 16]);
|
||||
b.push(0x0b);
|
||||
let mut body = leb(b.len() as u32);
|
||||
body.extend(b);
|
||||
bodies.push(body);
|
||||
}
|
||||
assert_eq!(bodies.len(), n_funcs);
|
||||
m.extend(section(10, vec_of(bodies)));
|
||||
if self.pad > 0 {
|
||||
let mut body = name("pad");
|
||||
body.extend(vec![0u8; self.pad]);
|
||||
m.extend(section(0, body));
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ELF ----
|
||||
|
||||
/// A GNU hash table for `E::gnu_hash`: `symoffset`, the bucket heads and one
|
||||
/// chain word per symbol from `symoffset` (bit 0 set on the last word of each
|
||||
/// chain). The bloom filter is one zero word.
|
||||
#[derive(Clone)]
|
||||
pub struct GnuHash {
|
||||
pub symoffset: u32,
|
||||
pub bucket: Vec<u32>,
|
||||
pub chain: Vec<u32>,
|
||||
}
|
||||
|
||||
pub struct E {
|
||||
pub class: u8,
|
||||
pub data: u8,
|
||||
pub etype: u16,
|
||||
pub machine: u16,
|
||||
pub flags: u32,
|
||||
pub needed: Vec<&'static str>,
|
||||
pub rpath: bool,
|
||||
pub runpath: bool,
|
||||
pub textrel: bool,
|
||||
/// DF_TEXTREL set in DT_FLAGS (the spelling modern linkers emit).
|
||||
pub textrel_flag: bool,
|
||||
/// A second DT_FLAGS entry after the first.
|
||||
pub dup_dt_flags: bool,
|
||||
pub bind_now: bool,
|
||||
pub flags1_now: bool,
|
||||
pub exec_stack: bool,
|
||||
pub gnu_stack: bool,
|
||||
pub defined: Vec<&'static str>,
|
||||
pub undefined: Vec<&'static str>,
|
||||
/// Extra defined symbols with an explicit binding nibble (10 is
|
||||
/// GNU_UNIQUE, 11 to 15 the OS and processor ranges). Emitted after
|
||||
/// `defined`.
|
||||
pub defined_bind: Vec<(&'static str, u8)>,
|
||||
/// Extra undefined symbols with an explicit binding nibble. Emitted
|
||||
/// after `undefined`.
|
||||
pub undefined_bind: Vec<(&'static str, u8)>,
|
||||
pub no_sections: bool,
|
||||
/// Contents of a `.wmod_info` section, when present.
|
||||
pub info: Option<Vec<u8>>,
|
||||
/// A second `.wmod_info` section with these contents, after the first.
|
||||
pub info_twin: Option<Vec<u8>>,
|
||||
/// A second PT_LOAD program header that maps addresses 0 to 3 again.
|
||||
pub extra_load: bool,
|
||||
/// A DT_REL table with one R_ARM_ABS32 relocation per symbol index here.
|
||||
pub rel_syms: Vec<u32>,
|
||||
/// A DT_HASH table: (nchain, bucket[0]), with a chain of zeros.
|
||||
pub sysv_hash: Option<(u32, u32)>,
|
||||
/// A DT_GNU_HASH table.
|
||||
pub gnu_hash: Option<GnuHash>,
|
||||
}
|
||||
|
||||
impl Default for E {
|
||||
fn default() -> Self {
|
||||
E {
|
||||
class: 1,
|
||||
data: 1,
|
||||
etype: 3,
|
||||
machine: 40,
|
||||
flags: 0x0500_0400,
|
||||
needed: vec!["libc.so.0"],
|
||||
rpath: false,
|
||||
runpath: false,
|
||||
textrel: false,
|
||||
textrel_flag: false,
|
||||
dup_dt_flags: false,
|
||||
bind_now: true,
|
||||
flags1_now: false,
|
||||
exec_stack: false,
|
||||
gnu_stack: true,
|
||||
defined: vec!["wmod_entry"],
|
||||
undefined: vec!["memcpy", "snprintf"],
|
||||
defined_bind: vec![],
|
||||
undefined_bind: vec![],
|
||||
no_sections: false,
|
||||
info: None,
|
||||
info_twin: None,
|
||||
extra_load: false,
|
||||
rel_syms: vec![],
|
||||
sysv_hash: None,
|
||||
gnu_hash: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn p32(o: &mut Vec<u8>, v: u32) {
|
||||
o.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn p16(o: &mut Vec<u8>, v: u16) {
|
||||
o.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
impl E {
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
// string table: "\0" then names
|
||||
let mut strs = vec![0u8];
|
||||
let mut add = |s: &str| {
|
||||
let o = strs.len() as u32;
|
||||
strs.extend_from_slice(s.as_bytes());
|
||||
strs.push(0);
|
||||
o
|
||||
};
|
||||
let needed: Vec<u32> = self.needed.iter().map(|n| add(n)).collect();
|
||||
let defs: Vec<u32> = self.defined.iter().map(|n| add(n)).collect();
|
||||
let undefs: Vec<u32> = self.undefined.iter().map(|n| add(n)).collect();
|
||||
let dbind: Vec<(u32, u8)> = self
|
||||
.defined_bind
|
||||
.iter()
|
||||
.map(|(n, b)| (add(n), *b))
|
||||
.collect();
|
||||
let ubind: Vec<(u32, u8)> = self
|
||||
.undefined_bind
|
||||
.iter()
|
||||
.map(|(n, b)| (add(n), *b))
|
||||
.collect();
|
||||
|
||||
let nph = (if self.gnu_stack { 3 } else { 2 }) + usize::from(self.extra_load);
|
||||
let dyn_off = 52 + 32 * nph;
|
||||
let flags_word =
|
||||
(if self.bind_now { 8 } else { 0 }) | (if self.textrel_flag { 4 } else { 0 });
|
||||
let flag_entries =
|
||||
usize::from(flags_word != 0 || self.dup_dt_flags) + usize::from(self.dup_dt_flags);
|
||||
let rel_entries = if self.rel_syms.is_empty() { 0 } else { 3 };
|
||||
let hash_entries =
|
||||
usize::from(self.sysv_hash.is_some()) + usize::from(self.gnu_hash.is_some());
|
||||
let ndyn = needed.len()
|
||||
+ usize::from(self.rpath)
|
||||
+ usize::from(self.runpath)
|
||||
+ usize::from(self.textrel)
|
||||
+ flag_entries
|
||||
+ usize::from(self.flags1_now)
|
||||
+ 4
|
||||
+ rel_entries
|
||||
+ hash_entries
|
||||
+ 1;
|
||||
let str_off = dyn_off + ndyn * 8;
|
||||
let sym_off = (str_off + strs.len() + 3) & !3;
|
||||
let nsym = 1 + defs.len() + undefs.len() + dbind.len() + ubind.len();
|
||||
let sym_end = sym_off + nsym * 16;
|
||||
// Optional tables after the symbols: REL entries, DT_HASH, DT_GNU_HASH.
|
||||
let rel_off = (sym_end + 3) & !3;
|
||||
let rel_len = 8 * self.rel_syms.len();
|
||||
let hash_off = (rel_off + rel_len + 3) & !3;
|
||||
let hash_len = self
|
||||
.sysv_hash
|
||||
.map_or(0, |(nchain, _)| 12 + 4 * nchain as usize);
|
||||
let gnu_off = (hash_off + hash_len + 3) & !3;
|
||||
let gnu_len = self
|
||||
.gnu_hash
|
||||
.as_ref()
|
||||
.map_or(0, |g| 20 + 4 * g.bucket.len() + 4 * g.chain.len());
|
||||
let tables_end = gnu_off + gnu_len;
|
||||
|
||||
let mut dynents: Vec<(u32, u32)> = needed.iter().map(|&o| (1, o)).collect();
|
||||
dynents.push((5, str_off as u32));
|
||||
dynents.push((10, strs.len() as u32));
|
||||
dynents.push((6, sym_off as u32));
|
||||
dynents.push((11, 16));
|
||||
if !self.rel_syms.is_empty() {
|
||||
dynents.push((17, rel_off as u32));
|
||||
dynents.push((18, rel_len as u32));
|
||||
dynents.push((19, 8));
|
||||
}
|
||||
if self.sysv_hash.is_some() {
|
||||
dynents.push((4, hash_off as u32));
|
||||
}
|
||||
if self.gnu_hash.is_some() {
|
||||
dynents.push((0x6fff_fef5, gnu_off as u32));
|
||||
}
|
||||
if self.rpath {
|
||||
dynents.push((15, 1));
|
||||
}
|
||||
if self.runpath {
|
||||
dynents.push((29, 1));
|
||||
}
|
||||
if self.textrel {
|
||||
dynents.push((22, 0));
|
||||
}
|
||||
if flags_word != 0 || self.dup_dt_flags {
|
||||
dynents.push((30, flags_word));
|
||||
}
|
||||
if self.dup_dt_flags {
|
||||
dynents.push((30, flags_word));
|
||||
}
|
||||
if self.flags1_now {
|
||||
dynents.push((0x6fff_fffb, 1));
|
||||
}
|
||||
dynents.push((0, 0));
|
||||
assert_eq!(dynents.len(), ndyn);
|
||||
|
||||
// Names of the optional sections: ".shstrtab" at 9, ".wmod_info" at 19.
|
||||
const SHSTR: &[u8] = b"\0.dynsym\0.shstrtab\0.wmod_info\0";
|
||||
let (shstr_off, info_off, info2_off, sh_off, shnum): (usize, usize, usize, usize, usize) =
|
||||
match &self.info {
|
||||
Some(info) => {
|
||||
let shstr_off = (tables_end + 3) & !3;
|
||||
let info_off = (shstr_off + SHSTR.len() + 3) & !3;
|
||||
let mut end = info_off + info.len();
|
||||
let info2_off = match &self.info_twin {
|
||||
Some(twin) => {
|
||||
let at = (end + 3) & !3;
|
||||
end = at + twin.len();
|
||||
at
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
let sh_off = (end + 3) & !3;
|
||||
let shnum = if self.info_twin.is_some() { 5 } else { 4 };
|
||||
(shstr_off, info_off, info2_off, sh_off, shnum)
|
||||
}
|
||||
None => {
|
||||
let sh_off = (tables_end + 3) & !3;
|
||||
(0, 0, 0, sh_off, 2)
|
||||
}
|
||||
};
|
||||
let total = sh_off + 40 * shnum;
|
||||
|
||||
let mut o = Vec::new();
|
||||
o.extend_from_slice(b"\x7fELF");
|
||||
o.extend_from_slice(&[self.class, self.data, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
p16(&mut o, self.etype);
|
||||
p16(&mut o, self.machine);
|
||||
p32(&mut o, 1);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 52);
|
||||
p32(&mut o, if self.no_sections { 0 } else { sh_off as u32 });
|
||||
p32(&mut o, self.flags);
|
||||
p16(&mut o, 52);
|
||||
p16(&mut o, 32);
|
||||
p16(&mut o, nph as u16);
|
||||
p16(&mut o, 40);
|
||||
p16(&mut o, if self.no_sections { 0 } else { shnum as u16 });
|
||||
p16(&mut o, if self.info.is_some() { 2 } else { 0 });
|
||||
let ph = |o: &mut Vec<u8>, ty: u32, off: u32, sz: u32, flags: u32| {
|
||||
p32(o, ty);
|
||||
p32(o, off);
|
||||
p32(o, off); // vaddr == offset
|
||||
p32(o, off);
|
||||
p32(o, sz);
|
||||
p32(o, sz);
|
||||
p32(o, flags);
|
||||
p32(o, 4);
|
||||
};
|
||||
ph(&mut o, 1, 0, total as u32, 5);
|
||||
ph(&mut o, 2, dyn_off as u32, (ndyn * 8) as u32, 6);
|
||||
if self.gnu_stack {
|
||||
let f = if self.exec_stack { 7 } else { 6 };
|
||||
ph(&mut o, 0x6474_e551, 0, 0, f);
|
||||
}
|
||||
if self.extra_load {
|
||||
ph(&mut o, 1, 0, 4, 4);
|
||||
}
|
||||
assert_eq!(o.len(), dyn_off);
|
||||
for (t, v) in &dynents {
|
||||
p32(&mut o, *t);
|
||||
p32(&mut o, *v);
|
||||
}
|
||||
o.extend_from_slice(&strs);
|
||||
o.resize(sym_off, 0);
|
||||
o.extend_from_slice(&[0u8; 16]);
|
||||
for &n in &defs {
|
||||
p32(&mut o, n);
|
||||
p32(&mut o, 0x1000);
|
||||
p32(&mut o, 4);
|
||||
o.push(0x12); // GLOBAL FUNC
|
||||
o.push(0);
|
||||
p16(&mut o, 1);
|
||||
}
|
||||
for &(n, bind) in &dbind {
|
||||
p32(&mut o, n);
|
||||
p32(&mut o, 0x1000);
|
||||
p32(&mut o, 4);
|
||||
o.push((bind << 4) | 2); // explicit binding, FUNC type
|
||||
o.push(0);
|
||||
p16(&mut o, 1);
|
||||
}
|
||||
for &n in &undefs {
|
||||
p32(&mut o, n);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
o.push(0x12);
|
||||
o.push(0);
|
||||
p16(&mut o, 0);
|
||||
}
|
||||
for &(n, bind) in &ubind {
|
||||
p32(&mut o, n);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
o.push((bind << 4) | 2); // explicit binding, FUNC type
|
||||
o.push(0);
|
||||
p16(&mut o, 0);
|
||||
}
|
||||
o.resize(rel_off, 0);
|
||||
for &sym in &self.rel_syms {
|
||||
p32(&mut o, 0x1000); // r_offset
|
||||
p32(&mut o, (sym << 8) | 2); // R_ARM_ABS32 against `sym`
|
||||
}
|
||||
o.resize(hash_off, 0);
|
||||
if let Some((nchain, bucket0)) = self.sysv_hash {
|
||||
p32(&mut o, 1); // nbucket
|
||||
p32(&mut o, nchain);
|
||||
p32(&mut o, bucket0);
|
||||
for _ in 0..nchain {
|
||||
p32(&mut o, 0);
|
||||
}
|
||||
}
|
||||
o.resize(gnu_off, 0);
|
||||
if let Some(g) = &self.gnu_hash {
|
||||
p32(&mut o, g.bucket.len() as u32);
|
||||
p32(&mut o, g.symoffset);
|
||||
p32(&mut o, 1); // bloom size
|
||||
p32(&mut o, 6); // bloom shift
|
||||
p32(&mut o, 0); // bloom word
|
||||
for &v in &g.bucket {
|
||||
p32(&mut o, v);
|
||||
}
|
||||
for &v in &g.chain {
|
||||
p32(&mut o, v);
|
||||
}
|
||||
}
|
||||
if let Some(info) = &self.info {
|
||||
o.resize(shstr_off, 0);
|
||||
o.extend_from_slice(SHSTR);
|
||||
o.resize(info_off, 0);
|
||||
o.extend_from_slice(info);
|
||||
if let Some(twin) = &self.info_twin {
|
||||
o.resize(info2_off, 0);
|
||||
o.extend_from_slice(twin);
|
||||
}
|
||||
}
|
||||
o.resize(sh_off, 0);
|
||||
o.extend_from_slice(&[0u8; 40]);
|
||||
// section 1: SHT_DYNSYM
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 11);
|
||||
p32(&mut o, 2);
|
||||
p32(&mut o, sym_off as u32);
|
||||
p32(&mut o, sym_off as u32);
|
||||
p32(&mut o, (nsym * 16) as u32);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 1);
|
||||
p32(&mut o, 4);
|
||||
p32(&mut o, 16);
|
||||
if let Some(info) = &self.info {
|
||||
// section 2: .shstrtab
|
||||
p32(&mut o, 9);
|
||||
p32(&mut o, 3); // SHT_STRTAB
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, shstr_off as u32);
|
||||
p32(&mut o, SHSTR.len() as u32);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 1);
|
||||
p32(&mut o, 0);
|
||||
// section 3: .wmod_info, allocated and loaded at sh_addr
|
||||
p32(&mut o, 19);
|
||||
p32(&mut o, 1); // SHT_PROGBITS
|
||||
p32(&mut o, 2); // SHF_ALLOC
|
||||
p32(&mut o, info_off as u32); // sh_addr
|
||||
p32(&mut o, info_off as u32);
|
||||
p32(&mut o, info.len() as u32);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 4);
|
||||
p32(&mut o, 0);
|
||||
if let Some(twin) = &self.info_twin {
|
||||
// section 4: a second .wmod_info
|
||||
p32(&mut o, 19);
|
||||
p32(&mut o, 1);
|
||||
p32(&mut o, 2);
|
||||
p32(&mut o, info2_off as u32);
|
||||
p32(&mut o, info2_off as u32);
|
||||
p32(&mut o, twin.len() as u32);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 0);
|
||||
p32(&mut o, 4);
|
||||
p32(&mut o, 0);
|
||||
}
|
||||
}
|
||||
assert_eq!(o.len(), total);
|
||||
o
|
||||
}
|
||||
}
|
||||
|
||||
/// A `wmod_info_t` prefix (d04 13.3.3), 32-bit little endian, as the module SDK
|
||||
/// links it into the `.wmod_info` section.
|
||||
pub fn info_bytes(
|
||||
id: &str,
|
||||
build: u32,
|
||||
flags: u32,
|
||||
lvgl: &str,
|
||||
hash: u8,
|
||||
major: u16,
|
||||
minor: u16,
|
||||
) -> Vec<u8> {
|
||||
let mut b = vec![0u8; INFO_SIZE_MIN];
|
||||
b[0..4].copy_from_slice(&(INFO_SIZE_MIN as u32).to_le_bytes());
|
||||
b[4..6].copy_from_slice(&major.to_le_bytes());
|
||||
b[6..8].copy_from_slice(&minor.to_le_bytes());
|
||||
b[8..8 + id.len()].copy_from_slice(id.as_bytes());
|
||||
b[40..44].copy_from_slice(&build.to_le_bytes());
|
||||
b[44..48].copy_from_slice(&flags.to_le_bytes());
|
||||
b[48..48 + lvgl.len()].copy_from_slice(lvgl.as_bytes());
|
||||
b[64..96].fill(hash);
|
||||
b
|
||||
}
|
||||
|
||||
// ---- signed packages (package-level tests) ----
|
||||
|
||||
pub const SEED: [u8; 32] = [7; 32];
|
||||
pub const OTHER_SEED: [u8; 32] = [9; 32];
|
||||
|
||||
/// Test keys live only in test code (wapp-core contract K10).
|
||||
pub fn key(seed: &[u8; 32], class: KeyClass, ids: AllowedIds) -> AppKey {
|
||||
AppKey {
|
||||
public: public_of(seed),
|
||||
class,
|
||||
allowed: ids,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn platform() -> Platform {
|
||||
Platform::parse(
|
||||
br#"{"v":1,"platform_api":3,"bus_contract":[1],"display_api":1,"checks_api":1,
|
||||
"capabilities":["rs485-bus","relay-io"],"reserved_ports":[22,53,67,80,443],
|
||||
"app_ram_cap_mb":96,"uid_base":10000,"uid_max":10999}"#,
|
||||
br#"{"v":1,"features":["cgroup-memory","cgroup-pids","cgroup-cpu"]}"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The verifier context of one test: the key set, the platform and no
|
||||
/// revocations.
|
||||
pub struct Fx {
|
||||
pub keys: Vec<AppKey>,
|
||||
pub platform: Platform,
|
||||
pub revoked: Revocations,
|
||||
}
|
||||
|
||||
impl Fx {
|
||||
/// A release-like key set: one `platform` key that signs any id.
|
||||
pub fn new() -> Fx {
|
||||
Fx {
|
||||
keys: vec![key(&SEED, KeyClass::Platform, AllowedIds::Any)],
|
||||
platform: platform(),
|
||||
revoked: Revocations::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ctx(&self) -> Ctx<'_> {
|
||||
Ctx {
|
||||
keys: &self.keys,
|
||||
platform: &self.platform,
|
||||
revoked: &self.revoked,
|
||||
floor_build: None,
|
||||
pin: None,
|
||||
explicit_rollback: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Fx {
|
||||
fn default() -> Self {
|
||||
Fx::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn j(s: &str) -> Value {
|
||||
json::parse(s.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
const SOURCE: &str = r#""source":{"repo":"blueflare/flare-edge","commit":"0123456789abcdef0123456789abcdef01234567","build_date":"2026-11-07","builder":"ci","sbom_sha256":"0000000000000000000000000000000000000000000000000000000000000000"}"#;
|
||||
|
||||
/// A FLARE plugin package: one descriptor part whose `flare/plugin.wasm`
|
||||
/// is the module under test.
|
||||
pub fn plugin_template() -> Value {
|
||||
j(&format!(
|
||||
r#"{{"format":1,"id":"ai-test","name":"Test plugin","summary":"Plugin admission test",
|
||||
"publisher":"BlueFlare Energy","version":"1.0.0","build":1,"kind":"descriptor","parts":["flare"],
|
||||
"platform":{{"arch":"armv7-musl-static","min_api":1,"bus_contract":[1],"display_api":1,"checks_api":1}},
|
||||
{SOURCE},
|
||||
"requires":{{}},"permissions":[],
|
||||
"flare":{{"plugin":{{"module":"flare/plugin.wasm","abi":1,"ops":["kv@1"],
|
||||
"limits":{{"memory_mb":32,"fuel":50000000,"call_ms":250,"kv_mb":16}}}}}},
|
||||
"data":{{"disk":{{"data_quota_mb":8,"cache_quota_mb":0}}}}}}"#
|
||||
))
|
||||
}
|
||||
|
||||
pub fn plugin_files(module: Vec<u8>) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut f = BTreeMap::new();
|
||||
f.insert("flare/plugin.wasm".into(), module);
|
||||
f
|
||||
}
|
||||
|
||||
/// A panel module package: one content part with a `ui.native` block whose
|
||||
/// module is `ui/modules/mining.so`.
|
||||
pub fn module_template() -> Value {
|
||||
j(&format!(
|
||||
r#"{{"format":1,"id":"solar","name":"Solar","summary":"Solar inverter overview",
|
||||
"publisher":"BlueFlare Energy","version":"1.0.0","build":1,"kind":"content",
|
||||
"parts":["warden"],"default_enabled":true,
|
||||
"platform":{{"arch":"armv7-musl-static","min_api":1,"bus_contract":[1],"display_api":1,"checks_api":1}},
|
||||
{SOURCE},
|
||||
"requires":{{"any":[["rs485-bus","relay-io"]]}},
|
||||
"permissions":[{{"name":"storage.data","class":"normal","reason":"Keeps its settings"}},
|
||||
{{"name":"ui.native","class":"privileged","reason":"Draws the radar"}}],
|
||||
"ui":{{"native":{{"module":"ui/modules/mining.so","host":"inproc","wmod_api":[1,0],"lvgl_direct":false,"memory_max_mb":4}}}},
|
||||
"schema":{{"fragment":"schema/fragment.json","data_version":1}},
|
||||
"data":{{"disk":{{"data_quota_mb":8,"cache_quota_mb":0}}}}}}"#
|
||||
))
|
||||
}
|
||||
|
||||
pub fn module_files(module: Vec<u8>) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut f = BTreeMap::new();
|
||||
f.insert("schema/fragment.json".into(), b"{\"v\":1}".to_vec());
|
||||
f.insert("ui/modules/mining.so".into(), module);
|
||||
f
|
||||
}
|
||||
|
||||
/// Set a dotted path inside a template; numeric segments index arrays.
|
||||
pub fn set(t: &mut Value, path: &str, v: Value) {
|
||||
let parts: Vec<&str> = path.split('.').collect();
|
||||
let mut cur = t;
|
||||
for p in &parts[..parts.len() - 1] {
|
||||
cur = step(cur, p);
|
||||
}
|
||||
let last = parts[parts.len() - 1];
|
||||
match cur {
|
||||
Value::Obj(m) => {
|
||||
m.insert(last.to_string(), v);
|
||||
}
|
||||
Value::Arr(a) => a[last.parse::<usize>().unwrap()] = v,
|
||||
_ => panic!("cannot set into a scalar"),
|
||||
}
|
||||
}
|
||||
|
||||
fn step<'a>(cur: &'a mut Value, p: &str) -> &'a mut Value {
|
||||
match cur {
|
||||
Value::Obj(m) => m.get_mut(p).unwrap_or_else(|| panic!("missing {p}")),
|
||||
Value::Arr(a) => &mut a[p.parse::<usize>().expect("array index")],
|
||||
_ => panic!("cannot step into {p}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sign `t` and its files with `seed`.
|
||||
pub fn pack_signed(t: &Value, files: &BTreeMap<String, Vec<u8>>, seed: &[u8; 32]) -> Vec<u8> {
|
||||
pack(t, files, false, seed).unwrap()
|
||||
}
|
||||
|
||||
/// A service package with two `bin/` executables, the shape of wapp-core's
|
||||
/// fixtures. `bin/warden-asic` is the first service's executable.
|
||||
pub fn service_template() -> Value {
|
||||
j(&format!(
|
||||
r#"{{"format":1,"id":"mining","name":"Mining Devices","summary":"Miner scan and Stratum proxy",
|
||||
"publisher":"BlueFlare Energy","version":"1.4.0","build":140,"kind":"service",
|
||||
"parts":["warden","flare"],
|
||||
"platform":{{"arch":"armv7-musl-static","min_api":3,"bus_contract":[1],
|
||||
"features":["cgroup-memory","cgroup-pids","cgroup-cpu"],"display_api":1,"checks_api":1}},
|
||||
{SOURCE},
|
||||
"requires":{{"capabilities":["network-scan","flare-link"]}},"provides":["mining-scan"],
|
||||
"permissions":[
|
||||
{{"name":"net.scan","class":"sensitive","reason":"Find miners on the LAN","services":["asic"]}},
|
||||
{{"name":"net.listen","class":"sensitive","reason":"Miners connect to the proxy","services":["stratum"]}},
|
||||
{{"name":"net.connect","class":"sensitive","reason":"Pool connections","services":["stratum"]}},
|
||||
{{"name":"flare.up","class":"sensitive","reason":"Send summaries to FLARE"}},
|
||||
{{"name":"secret.read:apps.mining.stratum.pass","class":"sensitive","reason":"Pool password","services":["stratum"]}}],
|
||||
"bus":{{"docs":[{{"name":"devices","refresh_s":30,"public":false}},{{"name":"summary","refresh_s":30,"public":true}}],
|
||||
"verbs":[{{"verb":"scan","service":"asic","idem":false,"timeout_s":10}}],"events":[],"up":[{{"name":"sessions"}}]}},
|
||||
"schema":{{"fragment":"schema/fragment.json","data_version":3}},
|
||||
"services":[
|
||||
{{"name":"asic","exe":"bin/warden-asic","phase":"normal","restart":{{"policy":"always"}},
|
||||
"resources":{{"memory_max_mb":48,"memory_typical_mb":20,"pids_max":64,"cpu_weight":100}}}},
|
||||
{{"name":"stratum","exe":"bin/warden-stratum","phase":"normal","after":["asic"],"restart":{{"policy":"always"}},
|
||||
"resources":{{"memory_max_mb":64,"memory_typical_mb":24,"pids_max":256,"cpu_weight":100}}}}],
|
||||
"net":{{"listen":[{{"service":"stratum","proto":"tcp","port_setting":"apps.mining.proxy.port","zones":["lan"],"purpose":"Stratum proxy for miners"}}],
|
||||
"connect":[{{"service":"stratum","proto":"tcp","range":[1,65535],"scope":"wan","host_hint":"pool","purpose":"Pool connection"}},
|
||||
{{"service":"asic","proto":"tcp","ports":[80,443,4028,6060],"scope":"lan","purpose":"Miner scan"}}]}},
|
||||
"data":{{"disk":{{"data_quota_mb":16,"cache_quota_mb":8}},"secrets":["apps.mining.stratum.pass"],
|
||||
"flare":[{{"class":"pools","default":"purge"}}]}}}}"#
|
||||
))
|
||||
}
|
||||
|
||||
/// The files of `service_template`: the schema fragment and both executables.
|
||||
pub fn service_files() -> BTreeMap<String, Vec<u8>> {
|
||||
let mut f = BTreeMap::new();
|
||||
f.insert("schema/fragment.json".into(), b"{\"v\":1}".to_vec());
|
||||
let asic = wapp_core::elf::sample_arm_static();
|
||||
f.insert("bin/warden-asic".into(), asic);
|
||||
let mut stratum = wapp_core::elf::sample_arm_static();
|
||||
stratum.extend_from_slice(b"stratum");
|
||||
f.insert("bin/warden-stratum".into(), stratum);
|
||||
f
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
//! d04 13.3.10 "ELF verifier vectors" for panel modules (AT-M6-13, PL-2).
|
||||
//!
|
||||
//! The reference module is admitted, and each hostile module is refused with
|
||||
//! its reason code. Every vector is a named test, so the acceptance row can
|
||||
//! cite it. The modules come from `common::E`, which writes the ELF facts that
|
||||
//! 13.3.5 checks; no toolchain links them, because the module SDK (13.3.3) is
|
||||
//! not built yet.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{info_bytes, GnuHash, E};
|
||||
use flare_plugin_abi::wmod::*;
|
||||
use flare_plugin_abi::Code;
|
||||
|
||||
const ALLOW: &str = "# libc\nstr*\nmem*\nsnprintf\nstrto*\nqsort\n__aeabi_*\nsin\n";
|
||||
const EXPORTS: &str = "lv_*\nwarden_page_*\n";
|
||||
|
||||
/// The reference module: ET_DYN, EM_ARM, EABI5 hard-float, libc only, BIND_NOW,
|
||||
/// a non-executable stack, one export, two imports from the allow list and the
|
||||
/// info block of app `solar`, build 1, ABI 1.0.
|
||||
fn reference() -> E {
|
||||
E {
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Every admission check of 13.3.5 on `bytes`, in the order flared runs them,
|
||||
/// returning the first refusal code. `Ok` carries the compat outcome.
|
||||
fn admit(bytes: &[u8]) -> Result<Compat, Code> {
|
||||
let allow = NameList::parse(ALLOW);
|
||||
let host = NameList::parse(EXPORTS);
|
||||
let policy = Policy {
|
||||
libc_allow: &allow,
|
||||
host_exports: &host,
|
||||
cxx: false,
|
||||
};
|
||||
check_module(bytes, &policy).map_err(|e| e.code)?;
|
||||
let info = Info::parse(info_block(bytes).map_err(|e| e.code)?).map_err(|e| e.code)?;
|
||||
let expect = Expect {
|
||||
abi_major: 1,
|
||||
abi_minor: 0,
|
||||
app_id: "solar",
|
||||
app_build: 1,
|
||||
lvgl_version: "9.6.0",
|
||||
sdk_hash: [9; 32],
|
||||
};
|
||||
check_info(&info, &expect).map_err(|e| e.code)
|
||||
}
|
||||
|
||||
fn refused(e: E, want: Code) {
|
||||
assert_eq!(admit(&e.build()), Err(want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_reference_module_is_admitted() {
|
||||
assert_eq!(admit(&reference().build()), Ok(Compat::Ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_musl_linked_module() {
|
||||
// musl names its C library `libc.so` in DT_NEEDED.
|
||||
refused(
|
||||
E {
|
||||
needed: vec!["libc.so"],
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_glibc_linked_module() {
|
||||
refused(
|
||||
E {
|
||||
needed: vec!["libc.so.6"],
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_rpath_and_runpath() {
|
||||
refused(
|
||||
E {
|
||||
rpath: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
refused(
|
||||
E {
|
||||
runpath: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_textrel() {
|
||||
refused(
|
||||
E {
|
||||
textrel: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
/// DF_TEXTREL in DT_FLAGS is how current linkers record text relocations; the
|
||||
/// DT_TEXTREL tag alone would let such a module through.
|
||||
#[test]
|
||||
fn d04_pl2_refuses_textrel_flag_in_dt_flags() {
|
||||
refused(
|
||||
E {
|
||||
textrel_flag: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_a_second_dt_flags_entry() {
|
||||
refused(
|
||||
E {
|
||||
dup_dt_flags: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
/// Hostile e_phoff and e_shoff near 2^32 must be refused, never wrapped into
|
||||
/// a valid-looking offset (the panel builds this crate for 32-bit usize).
|
||||
#[test]
|
||||
fn d04_pl2_hostile_header_offsets_are_refused() {
|
||||
let mut phoff = reference().build();
|
||||
phoff[28..32].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());
|
||||
assert_eq!(admit(&phoff), Err(Code::Elf));
|
||||
let mut shoff = reference().build();
|
||||
shoff[32..36].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());
|
||||
assert_eq!(admit(&shoff), Err(Code::Elf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_extra_export() {
|
||||
refused(
|
||||
E {
|
||||
defined: vec!["wmod_entry", "extra_export"],
|
||||
..reference()
|
||||
},
|
||||
Code::Symbols,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_import_outside_the_allow_list() {
|
||||
refused(
|
||||
E {
|
||||
undefined: vec!["memcpy", "unlisted_call"],
|
||||
..reference()
|
||||
},
|
||||
Code::Symbols,
|
||||
);
|
||||
// A forbidden import is refused even when a list would admit it.
|
||||
refused(
|
||||
E {
|
||||
undefined: vec!["memcpy", "malloc"],
|
||||
..reference()
|
||||
},
|
||||
Code::Symbols,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_wrong_architecture() {
|
||||
refused(
|
||||
E {
|
||||
machine: 3, // EM_386
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_soft_float() {
|
||||
refused(
|
||||
E {
|
||||
flags: 0x0500_0000,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_executable_stack() {
|
||||
refused(
|
||||
E {
|
||||
exec_stack: true,
|
||||
..reference()
|
||||
},
|
||||
Code::Elf,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_refuses_abi_major_mismatch() {
|
||||
refused(
|
||||
E {
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 2, 0)),
|
||||
..reference()
|
||||
},
|
||||
Code::Platform,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_newer_minor_needs_platform_not_refusal() {
|
||||
let e = E {
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 1)),
|
||||
..reference()
|
||||
};
|
||||
assert!(matches!(admit(&e.build()), Ok(Compat::NeedsPlatform(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_info_block_is_found_by_section_name() {
|
||||
let bytes = reference().build();
|
||||
assert_eq!(
|
||||
info_block(&bytes).unwrap(),
|
||||
info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0).as_slice()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_missing_or_short_info_block_is_refused() {
|
||||
assert_eq!(
|
||||
info_block(&E::default().build()).unwrap_err().code,
|
||||
Code::Elf
|
||||
);
|
||||
let short = E {
|
||||
info: Some(vec![0u8; 40]),
|
||||
..E::default()
|
||||
};
|
||||
assert_eq!(info_block(&short.build()).unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_info_section_outside_the_file_is_refused() {
|
||||
let mut b = reference().build();
|
||||
// Section 3 is `.wmod_info`: its header sits at e_shoff + 3 * 40 and its
|
||||
// sh_size field at +20.
|
||||
let shoff = u32::from_le_bytes([b[32], b[33], b[34], b[35]]) as usize;
|
||||
let at = shoff + 3 * 40 + 20;
|
||||
b[at..at + 4].copy_from_slice(&0xFFFF_0000u32.to_le_bytes());
|
||||
assert_eq!(info_block(&b).unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
// ---- the loader's view (#187, and the holes of the same class) ----
|
||||
//
|
||||
// Each decoy copies a table to a second place in the file and points a header
|
||||
// at it. The loader reads the table at its load address, so the verifier must
|
||||
// refuse the header rather than check the copy.
|
||||
|
||||
/// The word at byte offset `at` of a built module.
|
||||
fn word(b: &[u8], at: usize) -> u32 {
|
||||
u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
|
||||
}
|
||||
|
||||
fn put_word(b: &mut [u8], at: usize, v: u32) {
|
||||
b[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Section header `i` of a built module: (sh_type, sh_addr, sh_offset, sh_size).
|
||||
fn shdr(b: &[u8], i: usize) -> (u32, u32, u32, u32) {
|
||||
let at = word(b, 32) as usize + i * 40;
|
||||
(
|
||||
word(b, at + 4),
|
||||
word(b, at + 12),
|
||||
word(b, at + 16),
|
||||
word(b, at + 20),
|
||||
)
|
||||
}
|
||||
|
||||
/// Set one field of section header `i`: 8 sh_flags, 12 sh_addr, 16 sh_offset,
|
||||
/// 20 sh_size.
|
||||
fn set_shdr(b: &mut [u8], i: usize, field: usize, v: u32) {
|
||||
let at = word(b, 32) as usize + i * 40 + field;
|
||||
put_word(b, at, v);
|
||||
}
|
||||
|
||||
/// (p_offset, p_filesz) of program header `i`.
|
||||
fn phdr_range(b: &[u8], i: usize) -> (usize, usize) {
|
||||
let at = word(b, 28) as usize + i * 32;
|
||||
(word(b, at + 4) as usize, word(b, at + 16) as usize)
|
||||
}
|
||||
|
||||
/// Set one field of program header `i`: 4 p_offset, 8 p_vaddr, 16 p_filesz,
|
||||
/// 20 p_memsz.
|
||||
fn set_phdr(b: &mut [u8], i: usize, field: usize, v: u32) {
|
||||
let at = word(b, 28) as usize + i * 32 + field;
|
||||
put_word(b, at, v);
|
||||
}
|
||||
|
||||
/// Append `bytes` at a 4-byte boundary and return their file offset.
|
||||
fn append(b: &mut Vec<u8>, bytes: &[u8]) -> u32 {
|
||||
while b.len() % 4 != 0 {
|
||||
b.push(0);
|
||||
}
|
||||
let at = b.len();
|
||||
b.extend_from_slice(bytes);
|
||||
at as u32
|
||||
}
|
||||
|
||||
/// The 16-byte entries of the built module's `.dynsym` at the indices `keep`.
|
||||
fn dynsym_entries(b: &[u8], keep: &[usize]) -> Vec<u8> {
|
||||
let (_, _, off, size) = shdr(b, 1);
|
||||
let table = &b[off as usize..(off + size) as usize];
|
||||
keep.iter()
|
||||
.flat_map(|&i| table[i * 16..i * 16 + 16].to_vec())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The loaded `.dynsym` (at DT_SYMTAB) exports an extra symbol. The section
|
||||
/// header names a benign copy of the table, which the old reader checked.
|
||||
#[test]
|
||||
fn d04_pl2_dynsym_header_at_a_benign_copy_is_refused() {
|
||||
let mut b = E {
|
||||
defined: vec!["wmod_entry", "extra_export"],
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
// Entries 0, 1, 3 and 4: null, wmod_entry, memcpy and snprintf.
|
||||
let benign = dynsym_entries(&b, &[0, 1, 3, 4]);
|
||||
let at = append(&mut b, &benign);
|
||||
set_shdr(&mut b, 1, 16, at);
|
||||
set_shdr(&mut b, 1, 20, benign.len() as u32);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// The loaded table imports `unlisted_call`. The header names a benign copy
|
||||
/// without it, so the import check would pass on the copy.
|
||||
#[test]
|
||||
fn d04_pl2_dynsym_header_at_a_benign_copy_hides_an_import_is_refused() {
|
||||
let mut b = E {
|
||||
undefined: vec!["memcpy", "snprintf", "unlisted_call"],
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
// Entries 0 to 3: null, wmod_entry, memcpy and snprintf.
|
||||
let benign = dynsym_entries(&b, &[0, 1, 2, 3]);
|
||||
let at = append(&mut b, &benign);
|
||||
set_shdr(&mut b, 1, 16, at);
|
||||
set_shdr(&mut b, 1, 20, benign.len() as u32);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// The info block at the section's load address names app `other`. The header
|
||||
/// names a benign copy that names `solar`.
|
||||
#[test]
|
||||
fn d04_pl2_info_header_at_a_benign_copy_is_refused() {
|
||||
let mut b = E {
|
||||
info: Some(info_bytes("other", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
let benign = info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0);
|
||||
let at = append(&mut b, &benign);
|
||||
set_shdr(&mut b, 3, 16, at); // .wmod_info sh_offset
|
||||
assert_eq!(info_block(&b).unwrap_err().code, Code::Elf);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// A loaded dynamic section that sets DF_TEXTREL. The PT_DYNAMIC program
|
||||
/// header names a benign copy of the same table without it.
|
||||
#[test]
|
||||
fn d04_pl2_pt_dynamic_at_a_benign_copy_is_refused() {
|
||||
let genuine = reference().build();
|
||||
let (off, size) = phdr_range(&genuine, 1);
|
||||
let benign = genuine[off..off + size].to_vec();
|
||||
let mut b = E {
|
||||
textrel_flag: true,
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
let at = append(&mut b, &benign);
|
||||
set_phdr(&mut b, 1, 4, at); // PT_DYNAMIC p_offset
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// A second DT_SYMENT tag turned into DT_SYMTAB: the verifier would read the
|
||||
/// first table, and the loader may read the other.
|
||||
#[test]
|
||||
fn d04_pl2_duplicate_dt_symtab_is_refused() {
|
||||
let mut b = reference().build();
|
||||
let (off, size) = phdr_range(&b, 1);
|
||||
for at in (off..off + size).step_by(8) {
|
||||
if word(&b, at) == 11 {
|
||||
put_word(&mut b, at, 6);
|
||||
}
|
||||
}
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// Two `.wmod_info` sections: the verifier would check the first, and the
|
||||
/// block the module hands the host may be the second.
|
||||
#[test]
|
||||
fn d04_pl2_two_info_sections_are_refused() {
|
||||
let b = E {
|
||||
info_twin: Some(info_bytes("solar", 1, F_LVGL_DIRECT, "9.6.0", 9, 1, 0)),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(info_block(&b).unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
/// The host reads the info block at its load address, so an unallocated
|
||||
/// `.wmod_info` section is refused.
|
||||
#[test]
|
||||
fn d04_pl2_unallocated_info_section_is_refused() {
|
||||
let mut b = reference().build();
|
||||
set_shdr(&mut b, 3, 8, 0); // sh_flags without SHF_ALLOC
|
||||
assert_eq!(info_block(&b).unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
/// The header names 4 entries, so the checked table stops at `memcpy`. A
|
||||
/// relocation names the fifth entry, `unlisted_call`, which the import check
|
||||
/// never saw.
|
||||
#[test]
|
||||
fn d04_pl2_relocation_past_the_checked_table_is_refused() {
|
||||
let mut b = E {
|
||||
undefined: vec!["memcpy", "snprintf", "unlisted_call"],
|
||||
rel_syms: vec![4],
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
set_shdr(&mut b, 1, 20, 4 * 16);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_relocations_of_checked_symbols_are_admitted() {
|
||||
let b = E {
|
||||
rel_syms: vec![2, 3],
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(admit(&b), Ok(Compat::Ok));
|
||||
}
|
||||
|
||||
/// DT_HASH counts five symbols; the section header lets the verifier check four.
|
||||
#[test]
|
||||
fn d04_pl2_sysv_hash_counting_more_symbols_is_refused() {
|
||||
let mut b = E {
|
||||
undefined: vec!["memcpy", "snprintf", "unlisted_call"],
|
||||
sysv_hash: Some((5, 0)),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
set_shdr(&mut b, 1, 20, 4 * 16);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_sysv_hash_bucket_past_the_table_is_refused() {
|
||||
let b = E {
|
||||
sysv_hash: Some((4, 4)),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_sysv_hash_within_the_table_is_admitted() {
|
||||
let b = E {
|
||||
sysv_hash: Some((4, 0)),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(admit(&b), Ok(Compat::Ok));
|
||||
}
|
||||
|
||||
/// A GNU hash chain runs from symbol 1 to symbol 4. The checked table stops at
|
||||
/// symbol 3.
|
||||
#[test]
|
||||
fn d04_pl2_gnu_hash_chain_past_the_table_is_refused() {
|
||||
let mut b = E {
|
||||
undefined: vec!["memcpy", "snprintf", "unlisted_call"],
|
||||
gnu_hash: Some(GnuHash {
|
||||
symoffset: 1,
|
||||
bucket: vec![1],
|
||||
chain: vec![0, 0, 0, 1],
|
||||
}),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
set_shdr(&mut b, 1, 20, 4 * 16);
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d04_pl2_gnu_hash_within_the_table_is_admitted() {
|
||||
let b = E {
|
||||
gnu_hash: Some(GnuHash {
|
||||
symoffset: 1,
|
||||
bucket: vec![1],
|
||||
chain: vec![0, 0, 1],
|
||||
}),
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(admit(&b), Ok(Compat::Ok));
|
||||
}
|
||||
|
||||
/// A load segment whose memory size is below its file size.
|
||||
#[test]
|
||||
fn d04_pl2_load_smaller_in_memory_than_in_file_is_refused() {
|
||||
let mut b = reference().build();
|
||||
set_phdr(&mut b, 0, 20, 0); // PT_LOAD p_memsz
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// A second load segment that maps addresses the first one already maps.
|
||||
#[test]
|
||||
fn d04_pl2_overlapping_load_segments_are_refused() {
|
||||
let b = E {
|
||||
extra_load: true,
|
||||
..reference()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
|
||||
/// The first load segment ends inside the symbol table, so the table is not in
|
||||
/// one segment and cannot be read at the header's offset.
|
||||
#[test]
|
||||
fn d04_pl2_symbol_table_crossing_its_load_segment_is_refused() {
|
||||
let mut b = reference().build();
|
||||
let (_, _, sym_off, _) = shdr(&b, 1);
|
||||
set_phdr(&mut b, 0, 16, sym_off + 8); // PT_LOAD p_filesz
|
||||
assert_eq!(admit(&b), Err(Code::Elf));
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use flare_plugin_abi::fp1::*;
|
||||
|
||||
#[test]
|
||||
fn kinds_and_deadlines() {
|
||||
for n in 1..=6 {
|
||||
assert!(Kind::from_i32(n).is_some());
|
||||
}
|
||||
assert!(Kind::from_i32(0).is_none() && Kind::from_i32(7).is_none());
|
||||
assert_eq!(Kind::Http.deadline_ms(), 250);
|
||||
assert_eq!(Kind::Page.deadline_ms(), 250);
|
||||
assert_eq!(Kind::Action.deadline_ms(), 250);
|
||||
assert_eq!(Kind::Job.deadline_ms(), 5000);
|
||||
assert_eq!(Kind::Event.deadline_ms(), 5000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_codes_round_trip() {
|
||||
for n in -9..=-1 {
|
||||
let c = Neg::from_i32(n).unwrap();
|
||||
assert_eq!(c.code(), n);
|
||||
assert!(c.name().starts_with("E_"));
|
||||
}
|
||||
assert!(Neg::from_i32(0).is_none() && Neg::from_i32(-10).is_none());
|
||||
assert_eq!(Neg::OpDenied.name(), "E_OP_DENIED");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_has_unique_names_and_known_families() {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for o in OPS {
|
||||
assert!(seen.insert(o.name), "duplicate {}", o.name);
|
||||
assert!(o.name.ends_with("@1"));
|
||||
}
|
||||
assert_eq!(OPS.len(), 18);
|
||||
assert!(covers("kv@1", "kv.get@1") && covers("kv@1", "kv.list@1"));
|
||||
assert!(covers("audit@1", "audit@1"));
|
||||
assert!(!covers("kv@1", "sql.query@1"));
|
||||
assert!(!covers("kv@1", "kv.nope@1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grants_follow_the_op_table() {
|
||||
assert_eq!(op_def("kv.put@1").unwrap().grant, Grant::None);
|
||||
assert_eq!(op_def("sql.exec@1").unwrap().grant, Grant::Schema);
|
||||
assert_eq!(op_def("http.fetch@1").unwrap().grant, Grant::Hosts);
|
||||
assert_eq!(op_def("cfg.write@1").unwrap().grant, Grant::SitePaths);
|
||||
assert_eq!(op_def("command.send@1").unwrap().grant, Grant::SiteVerbs);
|
||||
assert_eq!(op_def("secret.get@1").unwrap().grant, Grant::Secret);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_op_lists() {
|
||||
assert!(check_manifest_ops(&["kv@1", "audit@1", "cfg.write@1"]).is_ok());
|
||||
assert!(check_manifest_ops(&["kv@2"]).is_err());
|
||||
assert!(check_manifest_ops(&["fs.read@1"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_requests() {
|
||||
let r = parse_call(br#"{"op":"kv.get@1","args":{"scope":"global","key":"a"}}"#).unwrap();
|
||||
assert_eq!(r.op.name, "kv.get@1");
|
||||
assert_eq!(r.args["key"], "a");
|
||||
// args default to an empty object
|
||||
assert!(parse_call(br#"{"op":"time.now@1"}"#)
|
||||
.unwrap()
|
||||
.args
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
let cases: &[(&[u8], Neg)] = &[
|
||||
(b"", Neg::Arg),
|
||||
(b"[]", Neg::Arg),
|
||||
(b"not json", Neg::Arg),
|
||||
(br#"{"args":{}}"#, Neg::Arg),
|
||||
(br#"{"op":5}"#, Neg::Arg),
|
||||
(br#"{"op":"time.now@1","args":[]}"#, Neg::Arg),
|
||||
(br#"{"op":"time.now@1","extra":1}"#, Neg::Arg),
|
||||
(br#"{"op":"fs.read@1"}"#, Neg::OpUnknown),
|
||||
(br#"{"op":"kv.get"}"#, Neg::OpUnknown),
|
||||
];
|
||||
for (b, want) in cases {
|
||||
assert_eq!(
|
||||
parse_call(b).unwrap_err(),
|
||||
*want,
|
||||
"{}",
|
||||
String::from_utf8_lossy(b)
|
||||
);
|
||||
}
|
||||
let big = vec![b' '; MAX_MESSAGE_BYTES + 1];
|
||||
assert_eq!(parse_call(&big).unwrap_err(), Neg::Limit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_headers_are_filtered() {
|
||||
let f = filter_response_header;
|
||||
assert_eq!(
|
||||
f("Content-Type", "text/plain").as_deref(),
|
||||
Some("text/plain")
|
||||
);
|
||||
assert_eq!(f("x-request-id", "abc").as_deref(), Some("abc"));
|
||||
assert_eq!(f("Cache-Control", "no-store").as_deref(), Some("no-store"));
|
||||
assert_eq!(f("cache-control", "public, max-age=99"), None);
|
||||
assert_eq!(f("Set-Cookie", "a=b"), None);
|
||||
assert_eq!(f("set-cookie", "a=b"), None);
|
||||
assert_eq!(f("x-custom", "1"), None);
|
||||
assert_eq!(
|
||||
f("location", "/apps/x/done").as_deref(),
|
||||
Some("/apps/x/done")
|
||||
);
|
||||
for bad in [
|
||||
"https://evil.example/",
|
||||
"//evil.example/",
|
||||
"javascript:alert(1)",
|
||||
"/\\evil",
|
||||
"foo",
|
||||
] {
|
||||
assert_eq!(f("location", bad), None, "{bad}");
|
||||
}
|
||||
assert_eq!(f("content-type", "text/plain\r\nSet-Cookie: a=b"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes_mount_only_under_the_plugin_prefix() {
|
||||
assert!(route_allowed("acme", "/apps/acme/settings"));
|
||||
assert!(route_allowed("acme", "/api/v1/apps/acme/hook"));
|
||||
assert!(route_allowed("acme", "/apps/acme"));
|
||||
for bad in [
|
||||
"/apps/other/x",
|
||||
"/apps/acme/../admin",
|
||||
"/apps/acmex/y",
|
||||
"/admin",
|
||||
"/",
|
||||
"/api/v1/sites",
|
||||
"/apps/acme//x",
|
||||
"/apps/acme/x?y=1",
|
||||
"/api/v1/apps/other/x",
|
||||
] {
|
||||
assert!(!route_allowed("acme", bad), "{bad}");
|
||||
}
|
||||
assert!(!route_allowed("", "/apps//x"));
|
||||
assert!(!route_allowed("A/b", "/apps/A/b/x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_match_the_spec() {
|
||||
assert_eq!(MAX_MODULE_BYTES, 2 << 20);
|
||||
assert_eq!(MAX_MESSAGE_BYTES, 1 << 20);
|
||||
assert_eq!(MAX_CALLS_PER_HANDLER, 64);
|
||||
assert_eq!(DEFAULT_FUEL, 50_000_000);
|
||||
assert_eq!((BREAKER_TRIPS, BREAKER_WINDOW_S), (5, 60));
|
||||
assert_eq!((BREAKER_FIRST_HOLD_S, BREAKER_MAX_HOLD_S), (600, 3600));
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! Package admission (B-13, W-D4, AT-M6-13, AT-M8-08 admission errors, T-WA-01).
|
||||
//!
|
||||
//! The code inside a signed `.wapp` is admitted only from a `platform` key,
|
||||
//! every refusal carries its reason code, and the signature is checked by the
|
||||
//! verifier itself, not by the caller.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use flare_plugin_abi::package::{admit_module, admit_validated_module, Host};
|
||||
#[cfg(feature = "wasm")]
|
||||
use flare_plugin_abi::package::{admit_plugin, PluginMode};
|
||||
use flare_plugin_abi::wmod::{Compat, NameList, F_LVGL_DIRECT};
|
||||
use flare_plugin_abi::{Code, Error};
|
||||
use wapp_core::appkeys::{AllowedIds, KeyClass};
|
||||
use wapp_core::json::Value;
|
||||
#[cfg(feature = "wasm")]
|
||||
use wapp_core::ustar::read_members;
|
||||
|
||||
/// Firmware import lists for module admission: the libc allow list and the
|
||||
/// host exports a Layer 2 module may call.
|
||||
fn firmware() -> (NameList, NameList) {
|
||||
(
|
||||
NameList::parse("# libc\nmem*\nsnprintf\n"),
|
||||
NameList::parse("lv_*\n"),
|
||||
)
|
||||
}
|
||||
|
||||
fn host<'a>(libc: &'a NameList, exports: &'a NameList, granted: &'a [&'a str]) -> Host<'a> {
|
||||
Host {
|
||||
libc_allow: libc,
|
||||
host_exports: exports,
|
||||
cxx: false,
|
||||
abi_major: 1,
|
||||
abi_minor: 0,
|
||||
lvgl_version: "9.6.0",
|
||||
sdk_hash: [9; 32],
|
||||
granted,
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel module built with the info block of `solar`, build 1, ABI 1.0.
|
||||
fn module_bytes(major: u16, minor: u16) -> Vec<u8> {
|
||||
E {
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, major, minor)),
|
||||
..E::default()
|
||||
}
|
||||
.build()
|
||||
}
|
||||
|
||||
fn module_archive(t: &Value, module: Vec<u8>) -> Vec<u8> {
|
||||
pack_signed(t, &module_files(module), &SEED)
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
fn plugin_archive(module: Vec<u8>) -> Vec<u8> {
|
||||
pack_signed(&plugin_template(), &plugin_files(module), &SEED)
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
fn wasm_ok() -> Vec<u8> {
|
||||
W::default().build()
|
||||
}
|
||||
|
||||
// ---- FLARE plugins (fp/1) ----
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_signed_by_platform_is_admitted() {
|
||||
let fx = Fx::new();
|
||||
let a = plugin_archive(wasm_ok());
|
||||
let p = admit_plugin(PluginMode::Signed, &a, &fx.ctx()).unwrap();
|
||||
assert_eq!(p.app_id, "ai-test");
|
||||
assert_eq!(p.app_build, 1);
|
||||
assert_eq!(p.class, KeyClass::Platform);
|
||||
assert_eq!(p.module, "flare/plugin.wasm");
|
||||
assert_eq!(p.admitted.memory_max_pages, 4);
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_with_a_flipped_signature_bit_is_refused() {
|
||||
let fx = Fx::new();
|
||||
let mut a = plugin_archive(wasm_ok());
|
||||
let m = read_members(&a).unwrap();
|
||||
a[m.sig.start] ^= 1;
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Sig
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_signed_by_an_unknown_key_is_refused() {
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&OTHER_SEED, KeyClass::Platform, AllowedIds::Any)];
|
||||
let a = plugin_archive(wasm_ok());
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Sig
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_signed_by_a_partner_key_is_refused() {
|
||||
// B-13: no third-party code runs before an out-of-process runtime exists.
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Partner, AllowedIds::Any)];
|
||||
let a = plugin_archive(wasm_ok());
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "plugin-dev"))]
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn dev_class_is_compiled_out_of_a_release_build() {
|
||||
// W-D4: the dev key class is absent from a release build, so no mode admits it.
|
||||
assert!(PluginMode::Dev.check_startup().is_err());
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Dev, AllowedIds::Any)];
|
||||
let a = plugin_archive(wasm_ok());
|
||||
assert_eq!(PluginMode::Dev.check_startup().unwrap_err().code, Code::Key);
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Dev, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "plugin-dev")]
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn dev_signed_plugin_is_admitted_only_in_dev_mode() {
|
||||
assert!(PluginMode::Dev.check_startup().is_ok());
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Dev, AllowedIds::Any)];
|
||||
let a = plugin_archive(wasm_ok());
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
let p = admit_plugin(PluginMode::Dev, &a, &fx.ctx()).unwrap();
|
||||
assert_eq!(p.class, KeyClass::Dev);
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugins_off_refuses_wasm_before_any_check() {
|
||||
let fx = Fx::new();
|
||||
let a = plugin_archive(wasm_ok());
|
||||
let e: Error = admit_plugin(PluginMode::Off, &a, &fx.ctx()).unwrap_err();
|
||||
assert_eq!((e.code, e.detail.as_str()), (Code::Key, "plugins_off"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_mode_values_parse_exactly() {
|
||||
assert_eq!(PluginMode::parse("off"), Some(PluginMode::Off));
|
||||
assert_eq!(PluginMode::parse("signed"), Some(PluginMode::Signed));
|
||||
assert_eq!(PluginMode::parse("dev"), Some(PluginMode::Dev));
|
||||
assert_eq!(PluginMode::parse("DEV"), None);
|
||||
assert_eq!(PluginMode::parse(""), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_admission_errors_carry_their_codes() {
|
||||
// AT-M8-08: admission errors E_IMPORT, E_WASM and E_LIMIT.
|
||||
let fx = Fx::new();
|
||||
let cases = [
|
||||
(
|
||||
W {
|
||||
extra_import: Some(("env", "puts")),
|
||||
..W::default()
|
||||
},
|
||||
Code::Import,
|
||||
),
|
||||
(
|
||||
W {
|
||||
start: true,
|
||||
..W::default()
|
||||
},
|
||||
Code::Wasm,
|
||||
),
|
||||
(
|
||||
W {
|
||||
memory: Some((1, Some(1024), false)),
|
||||
..W::default()
|
||||
},
|
||||
Code::Limit,
|
||||
),
|
||||
(
|
||||
W {
|
||||
drop_export: Some("fp_handle"),
|
||||
..W::default()
|
||||
},
|
||||
Code::Wasm,
|
||||
),
|
||||
];
|
||||
for (w, want) in cases {
|
||||
let a = plugin_archive(w.build());
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
want
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
#[test]
|
||||
fn plugin_manifest_refusals_are_manifest_codes() {
|
||||
let fx = Fx::new();
|
||||
// An ABI other than fp/1.
|
||||
let mut t = plugin_template();
|
||||
set(&mut t, "flare.plugin.abi", Value::Int(2));
|
||||
let a = pack_signed(&t, &plugin_files(wasm_ok()), &SEED);
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Manifest
|
||||
);
|
||||
// A flare half that names a compiled-in module, not a plugin.
|
||||
let mut t = plugin_template();
|
||||
set(&mut t, "flare", j(r#"{"module":"flare/plugin.wasm"}"#));
|
||||
let a = pack_signed(&t, &plugin_files(wasm_ok()), &SEED);
|
||||
assert_eq!(
|
||||
admit_plugin(PluginMode::Signed, &a, &fx.ctx())
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Manifest
|
||||
);
|
||||
}
|
||||
|
||||
// ---- panel modules (wmod/1) ----
|
||||
|
||||
#[test]
|
||||
fn module_signed_by_platform_is_admitted() {
|
||||
let fx = Fx::new();
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
let m = admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted)).unwrap();
|
||||
assert_eq!(m.compat, Compat::Ok);
|
||||
assert_eq!(m.needed, vec!["libc.so.0".to_string()]);
|
||||
assert_eq!(m.module, "ui/modules/mining.so");
|
||||
assert_eq!(m.info.app_id, "solar");
|
||||
assert_eq!(m.class, KeyClass::Platform);
|
||||
}
|
||||
|
||||
/// The installer path verifies once and then runs the module check on the
|
||||
/// result; it must admit exactly what `admit_module` admits.
|
||||
#[test]
|
||||
fn validated_module_path_matches_admit_module() {
|
||||
let fx = Fx::new();
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
let h = host(&libc, &exports, &granted);
|
||||
let direct = admit_module(&a, &fx.ctx(), &h).unwrap();
|
||||
let (v, c) = wapp_core::validate::validate_full(&a, &fx.ctx()).unwrap();
|
||||
assert_eq!(admit_validated_module(&v, &c, &h).unwrap(), direct);
|
||||
// Without the grant the validated path refuses too.
|
||||
let no_grant: [&str; 0] = [];
|
||||
let h2 = host(&libc, &exports, &no_grant);
|
||||
assert_eq!(
|
||||
admit_validated_module(&v, &c, &h2).unwrap_err().code,
|
||||
Code::Grant
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_signed_by_a_partner_key_is_refused() {
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Partner, AllowedIds::Any)];
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "plugin-dev"))]
|
||||
#[test]
|
||||
fn module_dev_key_is_compiled_out_of_a_release_build() {
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Dev, AllowedIds::Any)];
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Key
|
||||
);
|
||||
}
|
||||
|
||||
/// The positive side of the refusal above: in a plugin-dev build a module
|
||||
/// signed by the dev key class is admitted (13.3.5).
|
||||
#[cfg(feature = "plugin-dev")]
|
||||
#[test]
|
||||
fn module_signed_by_a_dev_key_is_admitted_in_a_plugin_dev_build() {
|
||||
let mut fx = Fx::new();
|
||||
fx.keys = vec![key(&SEED, KeyClass::Dev, AllowedIds::Any)];
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
let adm = admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted)).unwrap();
|
||||
assert_eq!(adm.app_id, "solar");
|
||||
assert_eq!(adm.class, KeyClass::Dev);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_abi_major_mismatch_is_refused_at_install() {
|
||||
let fx = Fx::new();
|
||||
let a = module_archive(&module_template(), module_bytes(2, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Platform
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_newer_minor_is_admitted_as_needs_platform() {
|
||||
// 13.3.6: the install goes through; the module waits for firmware.
|
||||
let fx = Fx::new();
|
||||
let a = module_archive(&module_template(), module_bytes(1, 1));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
let m = admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted)).unwrap();
|
||||
assert!(matches!(m.compat, Compat::NeedsPlatform(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_lvgl_mismatch_is_admitted_as_needs_platform() {
|
||||
let fx = Fx::new();
|
||||
let bytes = E {
|
||||
info: Some(info_bytes("solar", 1, F_LVGL_DIRECT, "9.5.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let a = module_archive(&module_template(), bytes);
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native", "ui.lvgl_direct"];
|
||||
let m = admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted)).unwrap();
|
||||
assert!(matches!(m.compat, Compat::NeedsPlatform(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_without_the_ui_native_grant_is_refused() {
|
||||
let fx = Fx::new();
|
||||
let a = module_archive(&module_template(), module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted: [&str; 0] = [];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Grant
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_platform_verbs_need_their_grant() {
|
||||
let fx = Fx::new();
|
||||
let mut t = module_template();
|
||||
set(
|
||||
&mut t,
|
||||
"permissions",
|
||||
j(
|
||||
r#"[{"name":"storage.data","class":"normal","reason":"Keeps its settings"},
|
||||
{"name":"ui.native","class":"privileged","reason":"Draws the radar"},
|
||||
{"name":"platform.reboot","class":"privileged","reason":"Restarts after an update"}]"#,
|
||||
),
|
||||
);
|
||||
let a = module_archive(&t, module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let without = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &without))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Grant
|
||||
);
|
||||
let with = ["ui.native", "platform.reboot"];
|
||||
assert!(admit_module(&a, &fx.ctx(), &host(&libc, &exports, &with)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_info_for_another_app_is_refused() {
|
||||
let fx = Fx::new();
|
||||
let bytes = E {
|
||||
info: Some(info_bytes("other", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let a = module_archive(&module_template(), bytes);
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Platform
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_outside_ui_modules_is_refused() {
|
||||
let fx = Fx::new();
|
||||
let mut t = module_template();
|
||||
set(
|
||||
&mut t,
|
||||
"ui.native.module",
|
||||
Value::Str("bin/mining.so".into()),
|
||||
);
|
||||
let a = module_archive(&t, module_bytes(1, 0));
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Manifest
|
||||
);
|
||||
}
|
||||
|
||||
// ---- T-WA-01: reason codes bound to refusing vectors ----
|
||||
|
||||
#[test]
|
||||
fn t_wa_01_panel_module_elf_code_has_a_refusing_vector() {
|
||||
let fx = Fx::new();
|
||||
let musl = E {
|
||||
needed: vec!["libc.so"],
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let a = module_archive(&module_template(), musl);
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Elf
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_wa_01_panel_module_symbols_code_has_a_refusing_vector() {
|
||||
let fx = Fx::new();
|
||||
let extra = E {
|
||||
defined: vec!["wmod_entry", "extra_export"],
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let a = module_archive(&module_template(), extra);
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
assert_eq!(
|
||||
admit_module(&a, &fx.ctx(), &host(&libc, &exports, &granted))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Symbols
|
||||
);
|
||||
}
|
||||
|
||||
/// The code a panel-module archive is refused with. A module that is admitted
|
||||
/// panics here, so each test names the one code it expects.
|
||||
fn module_refusal(archive: &[u8], ctx: &wapp_core::validate::Ctx<'_>, host: &Host<'_>) -> Code {
|
||||
admit_module(archive, ctx, host).unwrap_err().code
|
||||
}
|
||||
|
||||
/// T-WA-01 (s12 4.5): every reason code of the row has a refusing vector on the
|
||||
/// panel-module admission path. The list at the end names all ten codes.
|
||||
#[test]
|
||||
fn t_wa_01_every_reason_code_has_a_refusing_module_vector() {
|
||||
let (libc, exports) = firmware();
|
||||
let granted = ["ui.native"];
|
||||
let h = host(&libc, &exports, &granted);
|
||||
let fx = Fx::new();
|
||||
let ok = module_bytes(1, 0);
|
||||
let mut seen: Vec<&'static str> = Vec::new();
|
||||
|
||||
// E_MANIFEST: a manifest format this verifier does not read.
|
||||
let mut t = module_template();
|
||||
set(&mut t, "format", j("2"));
|
||||
let got = module_refusal(&module_archive(&t, ok.clone()), &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Manifest);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_RESERVED: an id that is not a valid app id.
|
||||
let mut t = module_template();
|
||||
set(&mut t, "id", j("\"Solar\""));
|
||||
let got = module_refusal(&module_archive(&t, ok.clone()), &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Reserved);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_SIG: one bit of the signature flipped.
|
||||
let mut a = module_archive(&module_template(), ok.clone());
|
||||
let m = wapp_core::ustar::read_members(&a).unwrap();
|
||||
a[m.sig.start] ^= 1;
|
||||
let got = module_refusal(&a, &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Sig);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_KEY: signed by a partner key, which panel modules never admit.
|
||||
let mut partner = Fx::new();
|
||||
partner.keys = vec![key(&SEED, KeyClass::Partner, AllowedIds::Any)];
|
||||
let a = module_archive(&module_template(), ok.clone());
|
||||
let got = module_refusal(&a, &partner.ctx(), &h);
|
||||
assert_eq!(got, Code::Key);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_REVOKED: build 1 of the app is in the revocation list.
|
||||
let mut revoked = Fx::new();
|
||||
revoked.revoked.builds.push(("solar".into(), 1));
|
||||
let a = module_archive(&module_template(), ok.clone());
|
||||
let got = module_refusal(&a, &revoked.ctx(), &h);
|
||||
assert_eq!(got, Code::Revoked);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_FLOOR: build 1 is at or below the anti-rollback floor.
|
||||
let mut floor = fx.ctx();
|
||||
floor.floor_build = Some(1);
|
||||
let a = module_archive(&module_template(), ok.clone());
|
||||
let got = module_refusal(&a, &floor, &h);
|
||||
assert_eq!(got, Code::Floor);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_PLATFORM: the info block names another app.
|
||||
let other = E {
|
||||
info: Some(info_bytes("other", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let got = module_refusal(&module_archive(&module_template(), other), &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Platform);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_HASH: one byte of the stored module changed after signing.
|
||||
let mut a = module_archive(&module_template(), ok.clone());
|
||||
let at = a.windows(4).position(|w| w == b"\x7fELF").unwrap();
|
||||
a[at + ok.len() - 1] ^= 1;
|
||||
let got = module_refusal(&a, &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Hash);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_ELF: linked against musl.
|
||||
let musl = E {
|
||||
needed: vec!["libc.so"],
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let got = module_refusal(&module_archive(&module_template(), musl), &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Elf);
|
||||
seen.push(got.as_str());
|
||||
|
||||
// E_SYMBOLS: one export beyond wmod_entry.
|
||||
let extra = E {
|
||||
defined: vec!["wmod_entry", "extra_export"],
|
||||
info: Some(info_bytes("solar", 1, 0, "9.6.0", 9, 1, 0)),
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
let got = module_refusal(&module_archive(&module_template(), extra), &fx.ctx(), &h);
|
||||
assert_eq!(got, Code::Symbols);
|
||||
seen.push(got.as_str());
|
||||
|
||||
let mut want = vec![
|
||||
"E_MANIFEST",
|
||||
"E_RESERVED",
|
||||
"E_SIG",
|
||||
"E_KEY",
|
||||
"E_REVOKED",
|
||||
"E_FLOOR",
|
||||
"E_PLATFORM",
|
||||
"E_HASH",
|
||||
"E_ELF",
|
||||
"E_SYMBOLS",
|
||||
];
|
||||
seen.sort_unstable();
|
||||
want.sort_unstable();
|
||||
assert_eq!(seen, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_wa_01_wire_codes_match_wapp_core() {
|
||||
// Every .wapp code keeps its spelling, so a package refusal reaches the UI
|
||||
// with the code wapp-core chose (s12 4.6).
|
||||
use wapp_core::Code as WappCode;
|
||||
let wapp = [
|
||||
WappCode::Reserved,
|
||||
WappCode::Source,
|
||||
WappCode::Hash,
|
||||
WappCode::Sig,
|
||||
WappCode::Key,
|
||||
WappCode::Revoked,
|
||||
WappCode::Floor,
|
||||
WappCode::Platform,
|
||||
WappCode::Deps,
|
||||
WappCode::Conflict,
|
||||
WappCode::Budget,
|
||||
WappCode::Grant,
|
||||
WappCode::Precond,
|
||||
WappCode::Policy,
|
||||
WappCode::Dependents,
|
||||
WappCode::Core,
|
||||
WappCode::Veto,
|
||||
WappCode::Compat,
|
||||
WappCode::Manifest,
|
||||
WappCode::Elf,
|
||||
WappCode::Symbols,
|
||||
WappCode::Snapshot,
|
||||
];
|
||||
for c in wapp {
|
||||
let mapped: Error = wapp_core::Error::new(c, "detail").into();
|
||||
assert_eq!(mapped.code.as_str(), c.as_str());
|
||||
assert_eq!(mapped.detail, "detail");
|
||||
}
|
||||
assert_eq!(Code::ALL.len(), 25);
|
||||
assert_eq!(Code::from_wire("E_NOPE"), None);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! T-WA-07 (s12 4.5 V16): ELF vectors for `bin/` and `hooks/`.
|
||||
//!
|
||||
//! The ELF checks are wapp-core's (`wapp_core::elf`). This file replays the
|
||||
//! vector table against them, so the T-WA-07 row names a test in this crate.
|
||||
//! The setuid vectors are payload-mode cases: under a valid signature, a
|
||||
//! `bin/` or `hooks/` member whose tar mode carries the setuid bit is refused
|
||||
//! with `Code::Manifest` ("wrong mode"), and the same archive with the expected
|
||||
//! modes is admitted.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use common::{j, service_files, service_template, set, Fx, E, SEED};
|
||||
use wapp_core::build::seal;
|
||||
use wapp_core::elf::{check_arm_static, check_script, sample_arm_static};
|
||||
use wapp_core::manifest::expected_mode;
|
||||
use wapp_core::ustar::{write_end, write_member};
|
||||
use wapp_core::validate::validate_full;
|
||||
use wapp_core::Code;
|
||||
|
||||
#[test]
|
||||
fn t_wa_07_bin_and_hook_vectors() {
|
||||
// Static ARM hard-float ELF without interpreter or needed libraries: passes.
|
||||
assert!(check_arm_static(&sample_arm_static()).is_ok());
|
||||
|
||||
// Dynamic: DT_NEEDED names a shared library.
|
||||
let dynamic = E::default().build();
|
||||
assert_eq!(check_arm_static(&dynamic).unwrap_err().code, Code::Elf);
|
||||
|
||||
// Wrong architecture (EM_386).
|
||||
let wrong_arch = E {
|
||||
machine: 3,
|
||||
needed: vec![],
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(check_arm_static(&wrong_arch).unwrap_err().code, Code::Elf);
|
||||
|
||||
// Soft-float: EF_ARM_ABI_FLOAT_HARD is clear.
|
||||
let soft = E {
|
||||
flags: 0x0500_0000,
|
||||
needed: vec![],
|
||||
..E::default()
|
||||
}
|
||||
.build();
|
||||
assert_eq!(check_arm_static(&soft).unwrap_err().code, Code::Elf);
|
||||
|
||||
// PT_INTERP: the first program header is changed to type 3.
|
||||
let mut interp = sample_arm_static();
|
||||
interp[52] = 3;
|
||||
assert_eq!(check_arm_static(&interp).unwrap_err().code, Code::Elf);
|
||||
|
||||
// Shell hooks must start with #!/bin/sh.
|
||||
assert!(check_script(b"#!/bin/sh\nexit 0\n").is_ok());
|
||||
assert_eq!(check_script(b"#!/bin/bash\n").unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
/// The members of `files` in payload order, each with its expected mode.
|
||||
/// `setuid` names one member that also gets the setuid bit.
|
||||
fn payload_with_setuid(files: &BTreeMap<String, Vec<u8>>, setuid: Option<&str>) -> Vec<u8> {
|
||||
let mut tar = Vec::new();
|
||||
for (path, data) in files {
|
||||
let mut mode = expected_mode(path);
|
||||
if setuid == Some(path.as_str()) {
|
||||
mode |= 0o4000;
|
||||
}
|
||||
write_member(&mut tar, path, mode, data);
|
||||
}
|
||||
write_end(&mut tar);
|
||||
tar
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_wa_07_setuid_bin_and_hook_members_are_refused() {
|
||||
let fx = Fx::new();
|
||||
let mut template = service_template();
|
||||
set(
|
||||
&mut template,
|
||||
"hooks",
|
||||
j(r#"{"pre_stop":{"path":"hooks/pre-stop"}}"#),
|
||||
);
|
||||
let mut files = service_files();
|
||||
files.insert("hooks/pre-stop".into(), b"#!/bin/sh\nexit 0\n".to_vec());
|
||||
|
||||
// Control: the expected modes. Each refusal below differs from this
|
||||
// archive in the setuid bit alone.
|
||||
let payload = payload_with_setuid(&files, None);
|
||||
let ok = seal(&template, &files, &payload, false, &SEED).unwrap();
|
||||
if let Err(e) = validate_full(&ok, &fx.ctx()) {
|
||||
panic!("control archive refused: {:?} {}", e.code, e.detail);
|
||||
}
|
||||
|
||||
for member in ["bin/warden-asic", "hooks/pre-stop"] {
|
||||
let payload = payload_with_setuid(&files, Some(member));
|
||||
let forged = seal(&template, &files, &payload, false, &SEED).unwrap();
|
||||
let Err(e) = validate_full(&forged, &fx.ctx()) else {
|
||||
panic!("{member}: a setuid member was admitted");
|
||||
};
|
||||
assert_eq!(e.code, Code::Manifest, "{member}: {}", e.detail);
|
||||
assert!(e.detail.contains("wrong mode"), "{member}: {}", e.detail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
#![cfg(feature = "wasm")]
|
||||
mod common;
|
||||
use common::W;
|
||||
use flare_plugin_abi::wasm::admit;
|
||||
use flare_plugin_abi::Code;
|
||||
|
||||
fn code(w: &W, mb: u32) -> Code {
|
||||
admit(&w.build(), mb).unwrap_err().code
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_module_is_admitted() {
|
||||
let a = admit(&W::default().build(), 4).unwrap();
|
||||
assert_eq!((a.memory_min_pages, a.memory_max_pages), (1, 4));
|
||||
assert!(a.imports_call && a.imports_log);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_at_the_limit_is_admitted() {
|
||||
// 1 MiB is 16 pages.
|
||||
let w = W {
|
||||
memory: Some((1, Some(16), false)),
|
||||
..W::default()
|
||||
};
|
||||
assert!(admit(&w.build(), 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_above_the_limit_is_refused() {
|
||||
let w = W {
|
||||
memory: Some((1, Some(17), false)),
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 1), Code::Limit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_without_maximum_is_refused() {
|
||||
let w = W {
|
||||
memory: Some((1, None, false)),
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 64), Code::Limit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_memory_is_refused() {
|
||||
let w = W {
|
||||
memory: Some((1, Some(2), true)),
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_memory_is_refused() {
|
||||
let w = W {
|
||||
memory: None,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_memories_are_refused() {
|
||||
let w = W {
|
||||
second_memory: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_import_is_refused() {
|
||||
for (m, n) in [
|
||||
("env", "abort"),
|
||||
("wasi_snapshot_preview1", "fd_write"),
|
||||
("fp1", "exec"),
|
||||
] {
|
||||
let w = W {
|
||||
extra_import: Some((m, n)),
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Import, "{m}.{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_import_is_refused() {
|
||||
let w = W {
|
||||
memory_import: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Import);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_import_type_is_refused() {
|
||||
let w = W {
|
||||
call_sig_wrong: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Import);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_import_is_refused() {
|
||||
let w = W {
|
||||
duplicate_log: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Import);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_function_is_refused() {
|
||||
let w = W {
|
||||
start: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_missing_export_is_refused() {
|
||||
for n in ["memory", "fp_alloc", "fp_free", "fp_init", "fp_handle"] {
|
||||
let w = W {
|
||||
drop_export: Some(n),
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm, "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_export_type_is_refused() {
|
||||
let w = W {
|
||||
handle_returns_i32: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_tables_are_refused() {
|
||||
let w = W {
|
||||
tables: 2,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
let one = W {
|
||||
tables: 1,
|
||||
..W::default()
|
||||
};
|
||||
assert!(admit(&one.build(), 4).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simd_is_refused() {
|
||||
let w = W {
|
||||
simd: true,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Wasm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversize_module_is_refused() {
|
||||
let w = W {
|
||||
pad: 2 * 1024 * 1024,
|
||||
..W::default()
|
||||
};
|
||||
assert_eq!(code(&w, 4), Code::Limit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_at_the_size_limit_is_admitted() {
|
||||
let base = W::default().build().len();
|
||||
// The custom section header costs a few bytes; fill to exactly 2 MiB.
|
||||
let mut pad = 2 * 1024 * 1024 - base - 12;
|
||||
let w = loop {
|
||||
let w = W {
|
||||
pad,
|
||||
..W::default()
|
||||
};
|
||||
let n = w.build().len();
|
||||
if n == 2 * 1024 * 1024 {
|
||||
break w;
|
||||
}
|
||||
pad = (pad as i64 + (2 * 1024 * 1024) - n as i64) as usize;
|
||||
};
|
||||
assert!(admit(&w.build(), 4).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_refused_not_panicked() {
|
||||
for b in [
|
||||
&b""[..],
|
||||
b"\0asm",
|
||||
b"\0asm\x01\0\0\0\x01",
|
||||
b"not wasm at all",
|
||||
&[0xff; 64],
|
||||
] {
|
||||
assert_eq!(admit(b, 4).unwrap_err().code, Code::Wasm);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_memory_limit_is_a_manifest_error() {
|
||||
assert_eq!(
|
||||
admit(&W::default().build(), 0).unwrap_err().code,
|
||||
Code::Manifest
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_never_panics() {
|
||||
let full = W::default().build();
|
||||
for n in 0..full.len() {
|
||||
let _ = admit(&full[..n], 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
mod common;
|
||||
use common::{info_bytes, E};
|
||||
use flare_plugin_abi::wmod::*;
|
||||
use flare_plugin_abi::Code;
|
||||
|
||||
const ALLOW: &str = "# libc\nstr*\nmem*\nsnprintf\nstrto*\nqsort\n__aeabi_*\nsin\n";
|
||||
const EXPORTS: &str = "lv_*\nwarden_page_*\n";
|
||||
|
||||
fn run(e: &E, cxx: bool) -> Result<Vec<String>, flare_plugin_abi::Error> {
|
||||
let allow = NameList::parse(ALLOW);
|
||||
let host = NameList::parse(EXPORTS);
|
||||
check_module(
|
||||
&e.build(),
|
||||
&Policy {
|
||||
libc_allow: &allow,
|
||||
host_exports: &host,
|
||||
cxx,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn code(e: &E) -> Code {
|
||||
run(e, false).unwrap_err().code
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_module_is_admitted() {
|
||||
assert_eq!(run(&E::default(), false).unwrap(), vec!["libc.so.0"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_1_now_also_counts_as_bind_now() {
|
||||
let e = E {
|
||||
bind_now: false,
|
||||
flags1_now: true,
|
||||
..E::default()
|
||||
};
|
||||
assert!(run(&e, false).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_refusals() {
|
||||
let cases = [
|
||||
E {
|
||||
class: 2,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
data: 2,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
etype: 2,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
machine: 3,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
flags: 0x0400_0400,
|
||||
..E::default()
|
||||
}, // EABI4
|
||||
E {
|
||||
flags: 0x0500_0200,
|
||||
..E::default()
|
||||
}, // soft float
|
||||
];
|
||||
for (i, e) in cases.iter().enumerate() {
|
||||
assert_eq!(code(e), Code::Elf, "case {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_section_refusals() {
|
||||
let cases = [
|
||||
E {
|
||||
needed: vec!["libc.so.6"],
|
||||
..E::default()
|
||||
}, // glibc build
|
||||
E {
|
||||
needed: vec!["libpthread.so.0"],
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
needed: vec!["libstdc++.so.6"],
|
||||
..E::default()
|
||||
}, // C++ not declared
|
||||
E {
|
||||
rpath: true,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
runpath: true,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
textrel: true,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
bind_now: false,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
exec_stack: true,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
gnu_stack: false,
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
no_sections: true,
|
||||
..E::default()
|
||||
},
|
||||
];
|
||||
for (i, e) in cases.iter().enumerate() {
|
||||
assert_eq!(code(e), Code::Elf, "case {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cxx_allows_libstdcxx_only_when_declared() {
|
||||
let e = E {
|
||||
needed: vec!["libc.so.0", "libm.so.0", "libgcc_s.so.1", "libstdc++.so.6"],
|
||||
..E::default()
|
||||
};
|
||||
assert!(run(&e, true).is_ok());
|
||||
assert_eq!(run(&e, false).unwrap_err().code, Code::Elf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_must_be_exactly_the_entry() {
|
||||
let cases = [
|
||||
E {
|
||||
defined: vec![],
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
defined: vec!["wmod_entry", "helper"],
|
||||
..E::default()
|
||||
},
|
||||
E {
|
||||
defined: vec!["wmod_main"],
|
||||
..E::default()
|
||||
},
|
||||
];
|
||||
for (i, e) in cases.iter().enumerate() {
|
||||
assert_eq!(code(e), Code::Symbols, "case {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_are_checked_against_the_lists() {
|
||||
// Allowed by prefix and by the host export list.
|
||||
let ok = E {
|
||||
undefined: vec![
|
||||
"strlen",
|
||||
"memset",
|
||||
"__aeabi_idiv",
|
||||
"lv_obj_create",
|
||||
"warden_page_add",
|
||||
"sin",
|
||||
],
|
||||
..E::default()
|
||||
};
|
||||
assert!(run(&ok, false).is_ok());
|
||||
for bad in ["cos", "mosquitto_publish", "lvx_unknown", "unknown_fn"] {
|
||||
let e = E {
|
||||
undefined: vec![bad],
|
||||
..E::default()
|
||||
};
|
||||
assert_eq!(code(&e), Code::Symbols, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_imports_beat_the_allow_list() {
|
||||
// Even when a list is careless enough to allow them.
|
||||
let allow = NameList::parse(&format!(
|
||||
"{}malloc\nsystem\nexecve\npthread_create\n",
|
||||
"str*\n"
|
||||
));
|
||||
let host = NameList::parse("");
|
||||
for bad in [
|
||||
"malloc",
|
||||
"calloc",
|
||||
"free",
|
||||
"open",
|
||||
"socket",
|
||||
"mmap",
|
||||
"dlopen",
|
||||
"fork",
|
||||
"execve",
|
||||
"execvp",
|
||||
"system",
|
||||
"pthread_create",
|
||||
"pthread_mutex_lock",
|
||||
"signal",
|
||||
"setjmp",
|
||||
"longjmp",
|
||||
"abort",
|
||||
"exit",
|
||||
"getenv",
|
||||
"kill",
|
||||
"syscall",
|
||||
"prctl",
|
||||
] {
|
||||
let e = E {
|
||||
undefined: vec![bad],
|
||||
..E::default()
|
||||
};
|
||||
let r = check_module(
|
||||
&e.build(),
|
||||
&Policy {
|
||||
libc_allow: &allow,
|
||||
host_exports: &host,
|
||||
cxx: false,
|
||||
},
|
||||
);
|
||||
assert_eq!(r.unwrap_err().code, Code::Symbols, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// GNU_UNIQUE (10), the OS range (11-15) and an empty name all take part in
|
||||
/// binding: each extra export below must be refused (E_SYMBOLS).
|
||||
#[test]
|
||||
fn exports_count_every_non_local_binding() {
|
||||
for (name, bind) in [("helper", 10), ("helper", 11), ("helper", 13), ("", 1)] {
|
||||
let e = E {
|
||||
defined_bind: vec![(name, bind)],
|
||||
..E::default()
|
||||
};
|
||||
assert_eq!(code(&e), Code::Symbols, "{name:?} bind {bind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The import check covers every non-local binding as well. A unique import
|
||||
/// is still judged by the lists, so an allowed one is admitted (E_SYMBOLS for
|
||||
/// the rest).
|
||||
#[test]
|
||||
fn imports_count_every_non_local_binding() {
|
||||
let ok = E {
|
||||
undefined_bind: vec![("strlen", 10)],
|
||||
..E::default()
|
||||
};
|
||||
assert!(run(&ok, false).is_ok());
|
||||
for (name, bind) in [("cos", 10), ("unknown_fn", 11), ("dlopen", 10), ("", 1)] {
|
||||
let e = E {
|
||||
undefined_bind: vec![(name, bind)],
|
||||
..E::default()
|
||||
};
|
||||
assert_eq!(code(&e), Code::Symbols, "{name:?} bind {bind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_list_parsing() {
|
||||
let l = NameList::parse("# c\n\n str* \nqsort\n");
|
||||
assert!(l.contains("strlen") && l.contains("qsort"));
|
||||
assert!(!l.contains("qsor") && !l.contains("mem"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_and_corruption_never_panic() {
|
||||
let full = E::default().build();
|
||||
let allow = NameList::parse(ALLOW);
|
||||
let host = NameList::parse(EXPORTS);
|
||||
let p = Policy {
|
||||
libc_allow: &allow,
|
||||
host_exports: &host,
|
||||
cxx: false,
|
||||
};
|
||||
for n in 0..full.len() {
|
||||
let _ = check_module(&full[..n], &p);
|
||||
}
|
||||
// Flip every byte to a few hostile values.
|
||||
for i in 0..full.len() {
|
||||
for v in [0u8, 0xff, 0x7f] {
|
||||
let mut b = full.clone();
|
||||
b[i] = v;
|
||||
let _ = check_module(&b, &p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- info block ----
|
||||
|
||||
fn expect() -> Expect<'static> {
|
||||
Expect {
|
||||
abi_major: 1,
|
||||
abi_minor: 1,
|
||||
app_id: "mining",
|
||||
app_build: 7,
|
||||
lvgl_version: "9.6.0",
|
||||
sdk_hash: [9; 32],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_matching_is_ok() {
|
||||
let i = Info::parse(&info_bytes("mining", 7, 0, "9.6.0", 9, 1, 0)).unwrap();
|
||||
assert_eq!(check_info(&i, &expect()).unwrap(), Compat::Ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_id_or_build_mismatch_is_refused() {
|
||||
let i = Info::parse(&info_bytes("other", 7, 0, "9.6.0", 9, 1, 0)).unwrap();
|
||||
assert_eq!(check_info(&i, &expect()).unwrap_err().code, Code::Platform);
|
||||
let i = Info::parse(&info_bytes("mining", 8, 0, "9.6.0", 9, 1, 0)).unwrap();
|
||||
assert_eq!(check_info(&i, &expect()).unwrap_err().code, Code::Platform);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abi_matrix() {
|
||||
// Modules built for minor 0 load on hosts at minor 0 and 1 (13.3.2). A
|
||||
// newer minor needs a firmware update (NeedsPlatform, 13.3.6).
|
||||
for (major, minor, ok) in [(1, 0, true), (1, 1, true), (1, 2, false)] {
|
||||
let i = Info::parse(&info_bytes("mining", 7, 0, "9.6.0", 9, major, minor)).unwrap();
|
||||
let r = check_info(&i, &expect()).unwrap();
|
||||
assert_eq!(r == Compat::Ok, ok, "{major}.{minor}");
|
||||
}
|
||||
// Another major is refused at install (13.3.5, 13.3.10).
|
||||
for major in [0u16, 2] {
|
||||
let i = Info::parse(&info_bytes("mining", 7, 0, "9.6.0", 9, major, 0)).unwrap();
|
||||
assert_eq!(check_info(&i, &expect()).unwrap_err().code, Code::Platform);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lvgl_direct_needs_exact_lvgl_and_hash() {
|
||||
let direct = Info::parse(&info_bytes("mining", 7, F_LVGL_DIRECT, "9.6.0", 9, 1, 0)).unwrap();
|
||||
assert_eq!(check_info(&direct, &expect()).unwrap(), Compat::Ok);
|
||||
let wrong_hash =
|
||||
Info::parse(&info_bytes("mining", 7, F_LVGL_DIRECT, "9.6.0", 3, 1, 0)).unwrap();
|
||||
assert!(matches!(
|
||||
check_info(&wrong_hash, &expect()).unwrap(),
|
||||
Compat::NeedsPlatform(_)
|
||||
));
|
||||
let wrong_ver = Info::parse(&info_bytes("mining", 7, F_LVGL_DIRECT, "9.5.0", 9, 1, 0)).unwrap();
|
||||
assert!(matches!(
|
||||
check_info(&wrong_ver, &expect()).unwrap(),
|
||||
Compat::NeedsPlatform(_)
|
||||
));
|
||||
// Layer 1 modules ignore the LVGL fields.
|
||||
let layer1 = Info::parse(&info_bytes("mining", 7, 0, "1.0.0", 3, 1, 0)).unwrap();
|
||||
assert_eq!(check_info(&layer1, &expect()).unwrap(), Compat::Ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_parse_refusals() {
|
||||
assert!(Info::parse(&[0; 10]).is_err());
|
||||
let mut b = info_bytes("mining", 7, 0, "9.6.0", 9, 1, 0);
|
||||
b[8..40].fill(b'a'); // no terminator
|
||||
assert!(Info::parse(&b).is_err());
|
||||
let mut b = info_bytes("mining", 7, 0, "9.6.0", 9, 1, 0);
|
||||
b[0..4].copy_from_slice(&4u32.to_le_bytes());
|
||||
assert!(Info::parse(&b).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grants() {
|
||||
let plain = Info::parse(&info_bytes("mining", 7, 0, "9.6.0", 9, 1, 0)).unwrap();
|
||||
let direct = Info::parse(&info_bytes("mining", 7, F_LVGL_DIRECT, "9.6.0", 9, 1, 0)).unwrap();
|
||||
assert!(check_grants(&plain, &["ui.native"], &[]).is_ok());
|
||||
assert_eq!(
|
||||
check_grants(&plain, &[], &[]).unwrap_err().code,
|
||||
Code::Grant
|
||||
);
|
||||
assert_eq!(
|
||||
check_grants(&direct, &["ui.native"], &[]).unwrap_err().code,
|
||||
Code::Grant
|
||||
);
|
||||
assert!(check_grants(&direct, &["ui.native", "ui.lvgl_direct"], &[]).is_ok());
|
||||
assert_eq!(
|
||||
check_grants(&plain, &["ui.native"], &["reboot"])
|
||||
.unwrap_err()
|
||||
.code,
|
||||
Code::Grant
|
||||
);
|
||||
assert!(check_grants(&plain, &["ui.native", "platform.reboot"], &["reboot"]).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "flare-plugin-host"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "wasmi host for FLARE-side plugins (built by the flare repo only)"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
flare-plugin-abi = { path = "../flare-plugin-abi" }
|
||||
sha2 = "0.10"
|
||||
# portable-dispatch is required: the tail-call dispatch relies on the optimizer
|
||||
# for guaranteed tail calls and recurses natively without it (debug builds
|
||||
# overflow the stack on a plain loop).
|
||||
wasmi = { version = "=2.0.0", default-features = false, features = ["std", "validate", "portable-dispatch"] }
|
||||
|
||||
[dev-dependencies]
|
||||
wat = "1"
|
||||
|
||||
[features]
|
||||
# Accepts FLARE_PLUGINS=dev. Release images omit it and refuse to start in dev mode.
|
||||
plugin-dev = ["flare-plugin-abi/plugin-dev"]
|
||||
@@ -0,0 +1,34 @@
|
||||
# flare-plugin-host
|
||||
|
||||
wasmi host for FLARE plugins (d04 13.4). Built by the flare repo only; the
|
||||
panel never links it.
|
||||
|
||||
| Module | Role |
|
||||
|---|---|
|
||||
| `runtime` | `Runtime` trait, `WasmiRuntime`, limits, faults, `HostOps` |
|
||||
| `load` | fail-closed load gate: mode, key class, hash, admission |
|
||||
| `breaker` | 5 faults in 60 s open for 10 min, doubling to 1 h |
|
||||
| `gate` | in-flight caps: 4 per plugin, 32 per portal |
|
||||
|
||||
## Limits per call
|
||||
|
||||
- Fresh store and instance each call; fuel from the manifest (default 50 M).
|
||||
- Memory, one instance, one table, one memory; growth past the limit returns -1.
|
||||
- Guest call depth 250.
|
||||
- At most 64 `fp1.call` and 32 log lines (512 bytes each) per call.
|
||||
- Messages and replies at most 1 MiB.
|
||||
- Deadline checked on each host call and on return; the async caller adds its
|
||||
own timeout for time blocked inside a host op.
|
||||
|
||||
## Build notes
|
||||
|
||||
- wasmi is built with `portable-dispatch`. Its default tail-call dispatch
|
||||
recurses on the native stack when the optimizer does not guarantee tail
|
||||
calls, so a debug build overflows on any long loop.
|
||||
- `plugin-dev` accepts `FLARE_PLUGINS=dev`. Release images omit it.
|
||||
|
||||
## Not here
|
||||
|
||||
Signature, key pin, floor and revocation checks are `wapp-core`'s; the caller
|
||||
passes the result as an `Attestation`. The op implementations (kv, sql, http,
|
||||
cfg, command, audit) belong to the consumer behind `HostOps`.
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Circuit breaker (d04 13.4.4): five traps or timeouts within 60 s set the
|
||||
//! plugin to `failed` for 10 minutes, doubling to 1 hour. Time is passed in
|
||||
//! as seconds so the state machine is deterministic.
|
||||
|
||||
use flare_plugin_abi::fp1::{
|
||||
BREAKER_FIRST_HOLD_S, BREAKER_MAX_HOLD_S, BREAKER_TRIPS, BREAKER_WINDOW_S,
|
||||
};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// A state change the caller audits (13.4.4: every transition is audited).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Transition {
|
||||
/// The breaker opened; calls are refused until `until`.
|
||||
Tripped { until: u64, hold_s: u64 },
|
||||
/// The hold elapsed and calls are allowed again.
|
||||
Recovered,
|
||||
/// An administrator reopened the plugin early; the hold restarts at 10 min.
|
||||
AdminRetry,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Breaker {
|
||||
faults: VecDeque<u64>,
|
||||
until: Option<u64>,
|
||||
next_hold_s: u64,
|
||||
}
|
||||
|
||||
impl Breaker {
|
||||
pub fn new() -> Self {
|
||||
Breaker {
|
||||
faults: VecDeque::new(),
|
||||
until: None,
|
||||
next_hold_s: BREAKER_FIRST_HOLD_S,
|
||||
}
|
||||
}
|
||||
|
||||
/// True while the breaker is open at `now`.
|
||||
pub fn is_failed(&self, now: u64) -> bool {
|
||||
self.until.is_some_and(|u| now < u)
|
||||
}
|
||||
|
||||
/// Ask whether a call may start at `now`. An elapsed hold closes the
|
||||
/// breaker and reports [`Transition::Recovered`].
|
||||
pub fn allow(&mut self, now: u64) -> (bool, Option<Transition>) {
|
||||
match self.until {
|
||||
Some(u) if now < u => (false, None),
|
||||
Some(_) => {
|
||||
self.until = None;
|
||||
self.faults.clear();
|
||||
(true, Some(Transition::Recovered))
|
||||
}
|
||||
None => (true, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a trap, fuel exhaustion, timeout or memory-limit fault.
|
||||
pub fn record_fault(&mut self, now: u64) -> Option<Transition> {
|
||||
if self.is_failed(now) {
|
||||
return None;
|
||||
}
|
||||
self.faults.push_back(now);
|
||||
while self
|
||||
.faults
|
||||
.front()
|
||||
.is_some_and(|t| now.saturating_sub(*t) >= BREAKER_WINDOW_S)
|
||||
{
|
||||
self.faults.pop_front();
|
||||
}
|
||||
if (self.faults.len() as u32) < BREAKER_TRIPS {
|
||||
return None;
|
||||
}
|
||||
let hold_s = self.next_hold_s;
|
||||
let until = now + hold_s;
|
||||
self.until = Some(until);
|
||||
self.faults.clear();
|
||||
self.next_hold_s = (hold_s * 2).min(BREAKER_MAX_HOLD_S);
|
||||
Some(Transition::Tripped { until, hold_s })
|
||||
}
|
||||
|
||||
/// The administrator retries a failed plugin before the hold ends.
|
||||
pub fn admin_retry(&mut self) -> Option<Transition> {
|
||||
self.until?;
|
||||
self.until = None;
|
||||
self.faults.clear();
|
||||
self.next_hold_s = BREAKER_FIRST_HOLD_S;
|
||||
Some(Transition::AdminRetry)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn trip(b: &mut Breaker, at: u64) -> Option<Transition> {
|
||||
let mut last = None;
|
||||
for i in 0..BREAKER_TRIPS as u64 {
|
||||
last = b.record_fault(at + i);
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_faults_do_not_trip() {
|
||||
let mut b = Breaker::new();
|
||||
for t in 0..4 {
|
||||
assert_eq!(b.record_fault(t), None);
|
||||
}
|
||||
assert!(!b.is_failed(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_faults_in_window_trip_for_ten_minutes() {
|
||||
let mut b = Breaker::new();
|
||||
let t = trip(&mut b, 100);
|
||||
assert_eq!(
|
||||
t,
|
||||
Some(Transition::Tripped {
|
||||
until: 104 + 600,
|
||||
hold_s: 600
|
||||
})
|
||||
);
|
||||
assert!(b.is_failed(500));
|
||||
assert_eq!(b.allow(500), (false, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faults_outside_the_window_do_not_add_up() {
|
||||
let mut b = Breaker::new();
|
||||
for k in 0..10u64 {
|
||||
assert_eq!(b.record_fault(k * 61), None, "fault {k}");
|
||||
}
|
||||
assert!(!b.is_failed(700));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hold_doubles_to_the_cap() {
|
||||
let mut b = Breaker::new();
|
||||
let mut now = 0;
|
||||
let mut holds = Vec::new();
|
||||
for _ in 0..5 {
|
||||
if let Some(Transition::Tripped { until, hold_s }) = trip(&mut b, now) {
|
||||
holds.push(hold_s);
|
||||
now = until;
|
||||
assert_eq!(b.allow(now), (true, Some(Transition::Recovered)));
|
||||
}
|
||||
}
|
||||
assert_eq!(holds, vec![600, 1200, 2400, 3600, 3600]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_clears_the_fault_count() {
|
||||
let mut b = Breaker::new();
|
||||
let Some(Transition::Tripped { until, .. }) = trip(&mut b, 0) else {
|
||||
panic!("no trip")
|
||||
};
|
||||
assert_eq!(b.allow(until), (true, Some(Transition::Recovered)));
|
||||
for t in 0..4 {
|
||||
assert_eq!(b.record_fault(until + t), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_retry_reopens_and_resets_the_hold() {
|
||||
let mut b = Breaker::new();
|
||||
trip(&mut b, 0);
|
||||
assert!(b.is_failed(10));
|
||||
assert_eq!(b.admin_retry(), Some(Transition::AdminRetry));
|
||||
assert!(!b.is_failed(10));
|
||||
assert_eq!(b.admin_retry(), None);
|
||||
let t = trip(&mut b, 20);
|
||||
assert!(matches!(t, Some(Transition::Tripped { hold_s: 600, .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faults_while_failed_are_not_counted() {
|
||||
let mut b = Breaker::new();
|
||||
trip(&mut b, 0);
|
||||
assert_eq!(b.record_fault(10), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! In-flight call limits (d04 13.4.4): at most 4 per plugin and 32 per
|
||||
//! portal. The caller answers 429, or skips the job, on [`Busy`].
|
||||
|
||||
use flare_plugin_abi::fp1::{MAX_INFLIGHT_PER_PLUGIN, MAX_INFLIGHT_PER_PORTAL};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Busy {
|
||||
Plugin,
|
||||
Portal,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
total: u32,
|
||||
per_plugin: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Gate {
|
||||
state: Arc<Mutex<State>>,
|
||||
per_plugin: u32,
|
||||
per_portal: u32,
|
||||
}
|
||||
|
||||
impl Default for Gate {
|
||||
fn default() -> Self {
|
||||
Gate::new(MAX_INFLIGHT_PER_PLUGIN, MAX_INFLIGHT_PER_PORTAL)
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases its slot on drop.
|
||||
pub struct Permit {
|
||||
state: Arc<Mutex<State>>,
|
||||
plugin: String,
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
pub fn new(per_plugin: u32, per_portal: u32) -> Self {
|
||||
Gate {
|
||||
state: Arc::default(),
|
||||
per_plugin,
|
||||
per_portal,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_acquire(&self, plugin: &str) -> Result<Permit, Busy> {
|
||||
let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if s.total >= self.per_portal {
|
||||
return Err(Busy::Portal);
|
||||
}
|
||||
let n = s.per_plugin.entry(plugin.to_string()).or_insert(0);
|
||||
if *n >= self.per_plugin {
|
||||
return Err(Busy::Plugin);
|
||||
}
|
||||
*n += 1;
|
||||
s.total += 1;
|
||||
Ok(Permit {
|
||||
state: self.state.clone(),
|
||||
plugin: plugin.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls in flight across the portal.
|
||||
pub fn in_flight(&self) -> u32 {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner()).total
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Permit {
|
||||
fn drop(&mut self) {
|
||||
let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
|
||||
s.total = s.total.saturating_sub(1);
|
||||
if let Some(n) = s.per_plugin.get_mut(&self.plugin) {
|
||||
*n = n.saturating_sub(1);
|
||||
if *n == 0 {
|
||||
s.per_plugin.remove(&self.plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fifth_call_of_one_plugin_is_busy() {
|
||||
let g = Gate::default();
|
||||
let held: Vec<_> = (0..4).map(|_| g.try_acquire("a").unwrap()).collect();
|
||||
assert_eq!(g.try_acquire("a").err(), Some(Busy::Plugin));
|
||||
assert!(g.try_acquire("b").is_ok());
|
||||
drop(held);
|
||||
assert!(g.try_acquire("a").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portal_cap_applies_across_plugins() {
|
||||
let g = Gate::default();
|
||||
let mut held = Vec::new();
|
||||
for i in 0..8 {
|
||||
for _ in 0..4 {
|
||||
held.push(g.try_acquire(&format!("p{i}")).unwrap());
|
||||
}
|
||||
}
|
||||
assert_eq!(g.in_flight(), 32);
|
||||
assert_eq!(g.try_acquire("p9").err(), Some(Busy::Portal));
|
||||
held.pop();
|
||||
assert!(g.try_acquire("p9").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_releases_everything() {
|
||||
let g = Gate::default();
|
||||
{
|
||||
let _p = g.try_acquire("a").unwrap();
|
||||
assert_eq!(g.in_flight(), 1);
|
||||
}
|
||||
assert_eq!(g.in_flight(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! wasmi host for FLARE plugins (d04 13.4).
|
||||
//!
|
||||
//! flare-server links this crate; the panel never does. It runs `fp/1`
|
||||
//! modules that `flare-plugin-abi` admitted, with fuel, memory and call
|
||||
//! limits, and hands every `fp1.call` to a [`HostOps`] implementation the
|
||||
//! caller supplies. The op implementations (kv, sql, http, ...) live in the
|
||||
//! consumer; this crate is the sandbox and the policy around it.
|
||||
//!
|
||||
//! - `runtime`: the [`Runtime`] trait, [`WasmiRuntime`], [`Limits`], [`Fault`];
|
||||
//! - `load`: the fail-closed load gate ([`Policy`], [`Attestation`], [`load`]);
|
||||
//! - `breaker`: the circuit breaker (5 faults in 60 s, 10 min doubling to 1 h);
|
||||
//! - `gate`: in-flight call limits (4 per plugin, 32 per portal).
|
||||
//!
|
||||
//! Signature, key pin, floor and revocation checks are `wapp-core`'s; the
|
||||
//! caller runs them and passes the outcome as an [`Attestation`].
|
||||
|
||||
pub mod breaker;
|
||||
pub mod gate;
|
||||
pub mod load;
|
||||
pub mod runtime;
|
||||
|
||||
pub use breaker::{Breaker, Transition};
|
||||
pub use gate::{Busy, Gate, Permit};
|
||||
pub use load::{load, Attestation, KeyClass, LoadError, Loaded, Mode, Policy};
|
||||
pub use runtime::{Fault, HostOps, Limits, Runtime, WasmiRuntime};
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The load gate (d04 13.4.8): FLARE's verification of the `flare` half of a
|
||||
//! package is authoritative and fails closed.
|
||||
//!
|
||||
//! The consumer runs the `wapp-core` chain (signature over the manifest
|
||||
//! bytes, key pin, floor, revocation, per-file hashes) and reports the result
|
||||
//! as an [`Attestation`]. [`load`] then re-checks what the host itself must
|
||||
//! not take on trust: the mode, the key class, the module hash against the
|
||||
//! attested one, and `wasm::admit`. Nothing here ever falls back to running
|
||||
//! an unverified module.
|
||||
|
||||
use crate::runtime::{Fault, Limits, Runtime};
|
||||
use flare_plugin_abi::{self as abi, Code};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fmt;
|
||||
|
||||
/// `FLARE_PLUGINS`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Off,
|
||||
Signed,
|
||||
Dev,
|
||||
}
|
||||
|
||||
/// Key class of the signing key (wapp-core `keys`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum KeyClass {
|
||||
Platform,
|
||||
Partner,
|
||||
Dev,
|
||||
}
|
||||
|
||||
/// The startup policy.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Policy {
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// Parse `FLARE_PLUGINS`. `dev` needs a build with the `plugin-dev`
|
||||
/// feature; a release build refuses to start with it.
|
||||
pub fn from_env_value(v: Option<&str>) -> Result<Policy, String> {
|
||||
let mode = match v.map(str::trim) {
|
||||
None | Some("") | Some("off") => Mode::Off,
|
||||
Some("signed") => Mode::Signed,
|
||||
Some("dev") => Mode::Dev,
|
||||
Some(o) => return Err(format!("FLARE_PLUGINS={o:?} is not off, signed or dev")),
|
||||
};
|
||||
Policy::new(mode)
|
||||
}
|
||||
|
||||
pub fn new(mode: Mode) -> Result<Policy, String> {
|
||||
if mode == Mode::Dev && !cfg!(feature = "plugin-dev") {
|
||||
return Err("FLARE_PLUGINS=dev needs a build with the plugin-dev feature".into());
|
||||
}
|
||||
Ok(Policy { mode })
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> Mode {
|
||||
self.mode
|
||||
}
|
||||
}
|
||||
|
||||
/// What the `wapp-core` verification established about one plugin module.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Attestation {
|
||||
pub id: String,
|
||||
pub key_class: KeyClass,
|
||||
/// The signed per-file SHA-256 of the module.
|
||||
pub module_sha256: [u8; 32],
|
||||
}
|
||||
|
||||
/// Why a module did not load.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LoadError {
|
||||
/// `FLARE_PLUGINS=off`.
|
||||
Off,
|
||||
/// A key class that may not load here (`E_KEY`).
|
||||
Key(KeyClass),
|
||||
/// The bytes differ from the attested hash (`E_HASH`).
|
||||
Hash,
|
||||
/// Admission refused the module (`E_WASM`, `E_IMPORT`, `E_LIMIT`).
|
||||
Admission(abi::Error),
|
||||
/// The runtime could not compile it.
|
||||
Compile(Fault),
|
||||
}
|
||||
|
||||
impl LoadError {
|
||||
/// The reason code shown to the administrator and written to the audit.
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
// s12 4.7 and s12 1282: the Wasm kind under `off` is `E_KEY plugins_off`.
|
||||
LoadError::Off => "E_KEY",
|
||||
LoadError::Key(_) => "E_KEY",
|
||||
LoadError::Hash => "E_HASH",
|
||||
LoadError::Admission(e) => e.code.as_str(),
|
||||
LoadError::Compile(_) => Code::Wasm.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for LoadError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
LoadError::Off => f.write_str("E_KEY: plugins_off"),
|
||||
LoadError::Key(c) => write!(f, "E_KEY: key class {c:?} may not load plugins"),
|
||||
LoadError::Hash => f.write_str("E_HASH: module differs from the signed hash"),
|
||||
LoadError::Admission(e) => e.fmt(f),
|
||||
LoadError::Compile(e) => write!(f, "E_WASM: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LoadError {}
|
||||
|
||||
/// A module that passed every gate.
|
||||
pub struct Loaded<M> {
|
||||
pub id: String,
|
||||
pub sha256: [u8; 32],
|
||||
pub module: M,
|
||||
pub limits: Limits,
|
||||
}
|
||||
|
||||
/// Run the gate and compile. Call it at install and again on every load of
|
||||
/// the module from disk.
|
||||
pub fn load<R: Runtime>(
|
||||
rt: &R,
|
||||
policy: &Policy,
|
||||
att: &Attestation,
|
||||
bytes: &[u8],
|
||||
limits: Limits,
|
||||
) -> Result<Loaded<R::Module>, LoadError> {
|
||||
match (policy.mode, att.key_class) {
|
||||
(Mode::Off, _) => return Err(LoadError::Off),
|
||||
(_, KeyClass::Platform) => {}
|
||||
(Mode::Dev, KeyClass::Dev) => {}
|
||||
(_, c) => return Err(LoadError::Key(c)),
|
||||
}
|
||||
let sha: [u8; 32] = Sha256::digest(bytes).into();
|
||||
if sha != att.module_sha256 {
|
||||
return Err(LoadError::Hash);
|
||||
}
|
||||
abi::wasm::admit(bytes, limits.memory_mb).map_err(LoadError::Admission)?;
|
||||
let (module, _) = rt.compile(bytes).map_err(LoadError::Compile)?;
|
||||
Ok(Loaded {
|
||||
id: att.id.clone(),
|
||||
sha256: sha,
|
||||
module,
|
||||
limits,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
//! The `fp/1` runtime: a fresh wasmi store and instance for every call
|
||||
//! (d04 13.4.4), so no state leaks between calls or users; state lives only
|
||||
//! in the `kv` op of the consumer.
|
||||
//!
|
||||
//! Limits enforced here: fuel, linear memory, one instance/table/memory,
|
||||
//! 64 `fp1.call` per invocation, 1 MiB messages, 512-byte log lines and a
|
||||
//! wall-clock deadline that is checked on every host call and again when the
|
||||
//! guest returns. A guest that never calls the host is bounded by fuel; the
|
||||
//! async caller still wraps the call in its own timeout, because fuel does
|
||||
//! not cover time a host op spends blocked.
|
||||
|
||||
use flare_plugin_abi::fp1::{
|
||||
self, Kind, Neg, MAX_CALLS_PER_HANDLER, MAX_LOG_BYTES, MAX_MESSAGE_BYTES,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use wasmi::{
|
||||
Caller, Config, Engine, Extern, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder,
|
||||
TrapCode,
|
||||
};
|
||||
|
||||
/// Per-plugin limits from the manifest `limits` block (13.4.1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
pub memory_mb: u32,
|
||||
pub fuel: u64,
|
||||
/// Wall-clock deadline in ms; `None` takes the handler kind's default.
|
||||
pub call_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
memory_mb: 32,
|
||||
fuel: fp1::DEFAULT_FUEL,
|
||||
call_ms: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a call failed. The consumer maps every fault to a 500 (or a skipped
|
||||
/// job) and counts it for the breaker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Fault {
|
||||
/// Fuel budget used up.
|
||||
Fuel,
|
||||
/// A trap: out of bounds, unreachable, stack overflow, bad conversion.
|
||||
Trap(String),
|
||||
/// Deadline passed.
|
||||
Timeout,
|
||||
/// The module needs more memory than its limit.
|
||||
Limit(String),
|
||||
/// `fp_init` returned a non-zero code.
|
||||
Init(i32),
|
||||
/// The guest broke the `fp/1` contract (bad pointer, oversize reply).
|
||||
Protocol(String),
|
||||
/// Instantiation failed.
|
||||
Instantiate(String),
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
/// True when the fault counts toward the circuit breaker.
|
||||
pub fn counts_for_breaker(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Fault::Fuel => "fuel",
|
||||
Fault::Trap(_) => "trap",
|
||||
Fault::Timeout => "timeout",
|
||||
Fault::Limit(_) => "limit",
|
||||
Fault::Init(_) => "init",
|
||||
Fault::Protocol(_) => "protocol",
|
||||
Fault::Instantiate(_) => "instantiate",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Fault {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Fault::Fuel => f.write_str("fuel exhausted"),
|
||||
Fault::Trap(m) => write!(f, "trap: {m}"),
|
||||
Fault::Timeout => f.write_str("deadline exceeded"),
|
||||
Fault::Limit(m) => write!(f, "limit: {m}"),
|
||||
Fault::Init(c) => write!(f, "fp_init returned {c}"),
|
||||
Fault::Protocol(m) => write!(f, "protocol: {m}"),
|
||||
Fault::Instantiate(m) => write!(f, "instantiate: {m}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Fault {}
|
||||
|
||||
/// What the consumer provides to answer `fp1.call` and `fp1.log`.
|
||||
pub trait HostOps {
|
||||
/// Run one op. The request was parsed and the op is a known one; grants,
|
||||
/// rate limits and argument checks are the implementation's. A response
|
||||
/// over the guest's buffer becomes `E_LIMIT` in the guest.
|
||||
fn call(&mut self, req: &fp1::CallRequest) -> Result<Vec<u8>, Neg>;
|
||||
/// A log line, truncated to 512 bytes. Called at most 32 times a call.
|
||||
fn log(&mut self, level: i32, msg: &str);
|
||||
}
|
||||
|
||||
/// Result of a successful handler call.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Output {
|
||||
pub body: Vec<u8>,
|
||||
pub fuel_used: u64,
|
||||
pub host_calls: u32,
|
||||
}
|
||||
|
||||
/// Lines a guest may log in one call.
|
||||
pub const MAX_LOG_LINES: u32 = 32;
|
||||
|
||||
/// A thin seam so `wasmtime` can replace wasmi without an ABI change.
|
||||
pub trait Runtime {
|
||||
type Module: Clone;
|
||||
|
||||
/// Compile `bytes` (already admitted) once per SHA-256.
|
||||
fn compile(&self, bytes: &[u8]) -> Result<(Self::Module, [u8; 32]), Fault>;
|
||||
|
||||
/// Run `fp_init(cfg)` then `fp_handle(kind, request)` in a fresh instance.
|
||||
fn call(
|
||||
&self,
|
||||
module: &Self::Module,
|
||||
limits: &Limits,
|
||||
kind: Kind,
|
||||
cfg: &[u8],
|
||||
request: &[u8],
|
||||
ops: &mut dyn HostOps,
|
||||
) -> Result<Output, Fault>;
|
||||
}
|
||||
|
||||
const CACHE_MAX: usize = 64;
|
||||
|
||||
/// Guest call depth. wasmi's default of 1000 needs more native stack than a
|
||||
/// 2 MiB worker thread has in a debug build; 250 leaves room for a JSON
|
||||
/// parser's recursion and keeps the trap well inside any thread's stack.
|
||||
const MAX_GUEST_DEPTH: usize = 250;
|
||||
|
||||
pub struct WasmiRuntime {
|
||||
engine: Engine,
|
||||
cache: Mutex<HashMap<[u8; 32], Module>>,
|
||||
}
|
||||
|
||||
impl Default for WasmiRuntime {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
limits: StoreLimits,
|
||||
ops: &'a mut dyn HostOps,
|
||||
calls: u32,
|
||||
logs: u32,
|
||||
started: Instant,
|
||||
deadline: Duration,
|
||||
}
|
||||
|
||||
impl WasmiRuntime {
|
||||
pub fn new() -> Self {
|
||||
let mut cfg = Config::default();
|
||||
cfg.consume_fuel(true)
|
||||
.allow_start_fn(false)
|
||||
.set_max_recursion_depth(MAX_GUEST_DEPTH);
|
||||
WasmiRuntime {
|
||||
engine: Engine::new(&cfg),
|
||||
cache: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules compiled and cached.
|
||||
pub fn cached(&self) -> usize {
|
||||
self.cache.lock().unwrap_or_else(|e| e.into_inner()).len()
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(e: wasmi::Error) -> Fault {
|
||||
match e.as_trap_code() {
|
||||
Some(TrapCode::OutOfFuel) => Fault::Fuel,
|
||||
Some(c) => Fault::Trap(c.to_string()),
|
||||
None => Fault::Trap(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_of(caller: &Caller<'_, Ctx<'_>>) -> Option<Memory> {
|
||||
caller.get_export("memory").and_then(Extern::into_memory)
|
||||
}
|
||||
|
||||
fn host_call(
|
||||
mut caller: Caller<'_, Ctx<'_>>,
|
||||
req_ptr: i32,
|
||||
req_len: i32,
|
||||
out_ptr: i32,
|
||||
out_cap: i32,
|
||||
) -> i32 {
|
||||
let ctx = caller.data_mut();
|
||||
ctx.calls += 1;
|
||||
if ctx.calls > MAX_CALLS_PER_HANDLER {
|
||||
return Neg::Limit.code();
|
||||
}
|
||||
if ctx.started.elapsed() > ctx.deadline {
|
||||
return Neg::Timeout.code();
|
||||
}
|
||||
let (Ok(req_ptr), Ok(req_len), Ok(out_ptr), Ok(out_cap)) = (
|
||||
usize::try_from(req_ptr),
|
||||
usize::try_from(req_len),
|
||||
usize::try_from(out_ptr),
|
||||
usize::try_from(out_cap),
|
||||
) else {
|
||||
return Neg::Arg.code();
|
||||
};
|
||||
if req_len > MAX_MESSAGE_BYTES {
|
||||
return Neg::Limit.code();
|
||||
}
|
||||
let Some(mem) = memory_of(&caller) else {
|
||||
return Neg::Arg.code();
|
||||
};
|
||||
let mut buf = vec![0u8; req_len];
|
||||
if mem.read(&caller, req_ptr, &mut buf).is_err() {
|
||||
return Neg::Arg.code();
|
||||
}
|
||||
// The output window must lie inside memory before the op runs, so a bad
|
||||
// pointer cannot turn a write op into a half-done call.
|
||||
if out_ptr
|
||||
.checked_add(out_cap)
|
||||
.is_none_or(|end| end > mem.data_size(&caller))
|
||||
{
|
||||
return Neg::Arg.code();
|
||||
}
|
||||
let req = match fp1::parse_call(&buf) {
|
||||
Ok(r) => r,
|
||||
Err(n) => return n.code(),
|
||||
};
|
||||
let reply = match caller.data_mut().ops.call(&req) {
|
||||
Ok(r) => r,
|
||||
Err(n) => return n.code(),
|
||||
};
|
||||
if reply.len() > out_cap || reply.len() > MAX_MESSAGE_BYTES {
|
||||
return Neg::Limit.code();
|
||||
}
|
||||
if mem.write(&mut caller, out_ptr, &reply).is_err() {
|
||||
return Neg::Arg.code();
|
||||
}
|
||||
reply.len() as i32
|
||||
}
|
||||
|
||||
fn host_log(mut caller: Caller<'_, Ctx<'_>>, level: i32, ptr: i32, len: i32) {
|
||||
let ctx = caller.data_mut();
|
||||
ctx.logs += 1;
|
||||
if ctx.logs > MAX_LOG_LINES {
|
||||
return;
|
||||
}
|
||||
let (Ok(ptr), Ok(len)) = (usize::try_from(ptr), usize::try_from(len)) else {
|
||||
return;
|
||||
};
|
||||
let Some(mem) = memory_of(&caller) else {
|
||||
return;
|
||||
};
|
||||
let mut buf = vec![0u8; len.min(MAX_LOG_BYTES)];
|
||||
if mem.read(&caller, ptr, &mut buf).is_err() {
|
||||
return;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&buf).into_owned();
|
||||
caller.data_mut().ops.log(level, &text);
|
||||
}
|
||||
|
||||
impl Runtime for WasmiRuntime {
|
||||
type Module = Module;
|
||||
|
||||
fn compile(&self, bytes: &[u8]) -> Result<(Module, [u8; 32]), Fault> {
|
||||
let sha: [u8; 32] = Sha256::digest(bytes).into();
|
||||
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(m) = cache.get(&sha) {
|
||||
return Ok((m.clone(), sha));
|
||||
}
|
||||
let m = Module::new(&self.engine, bytes).map_err(|e| Fault::Instantiate(e.to_string()))?;
|
||||
if cache.len() >= CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(sha, m.clone());
|
||||
Ok((m, sha))
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
module: &Module,
|
||||
limits: &Limits,
|
||||
kind: Kind,
|
||||
cfg: &[u8],
|
||||
request: &[u8],
|
||||
ops: &mut dyn HostOps,
|
||||
) -> Result<Output, Fault> {
|
||||
if request.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(Fault::Protocol("request over 1 MiB".into()));
|
||||
}
|
||||
let deadline = Duration::from_millis(limits.call_ms.unwrap_or_else(|| kind.deadline_ms()));
|
||||
let started = Instant::now();
|
||||
let mem_bytes = (limits.memory_mb as usize).saturating_mul(1024 * 1024);
|
||||
let mut store = Store::new(
|
||||
&self.engine,
|
||||
Ctx {
|
||||
limits: StoreLimitsBuilder::new()
|
||||
.memory_size(mem_bytes)
|
||||
.instances(1)
|
||||
.tables(1)
|
||||
.memories(1)
|
||||
.build(),
|
||||
ops,
|
||||
calls: 0,
|
||||
logs: 0,
|
||||
started,
|
||||
deadline,
|
||||
},
|
||||
);
|
||||
store.limiter(|c| &mut c.limits);
|
||||
store
|
||||
.set_fuel(limits.fuel)
|
||||
.map_err(|e| Fault::Trap(e.to_string()))?;
|
||||
|
||||
let mut linker: Linker<Ctx<'_>> = Linker::new(&self.engine);
|
||||
linker
|
||||
.func_wrap(fp1::IMPORT_MODULE, fp1::IMPORT_CALL, host_call)
|
||||
.and_then(|l| l.func_wrap(fp1::IMPORT_MODULE, fp1::IMPORT_LOG, host_log))
|
||||
.map_err(|e| Fault::Instantiate(e.to_string()))?;
|
||||
let instance = linker
|
||||
.instantiate_and_start(&mut store, module)
|
||||
.map_err(|e| match e.as_trap_code() {
|
||||
Some(_) => classify(e),
|
||||
None => Fault::Limit(e.to_string()),
|
||||
})?;
|
||||
|
||||
let missing = |n: &str| Fault::Protocol(format!("missing export {n}"));
|
||||
let memory = instance
|
||||
.get_memory(&store, fp1::EXPORT_MEMORY)
|
||||
.ok_or_else(|| missing(fp1::EXPORT_MEMORY))?;
|
||||
let alloc = instance
|
||||
.get_typed_func::<i32, i32>(&store, fp1::EXPORT_ALLOC)
|
||||
.map_err(|_| missing(fp1::EXPORT_ALLOC))?;
|
||||
let free = instance
|
||||
.get_typed_func::<(i32, i32), ()>(&store, fp1::EXPORT_FREE)
|
||||
.map_err(|_| missing(fp1::EXPORT_FREE))?;
|
||||
let init = instance
|
||||
.get_typed_func::<(i32, i32), i32>(&store, fp1::EXPORT_INIT)
|
||||
.map_err(|_| missing(fp1::EXPORT_INIT))?;
|
||||
let handle = instance
|
||||
.get_typed_func::<(i32, i32, i32), i64>(&store, fp1::EXPORT_HANDLE)
|
||||
.map_err(|_| missing(fp1::EXPORT_HANDLE))?;
|
||||
|
||||
// Copy `data` into guest memory through `fp_alloc`.
|
||||
let put = |store: &mut Store<Ctx<'_>>, data: &[u8]| -> Result<(i32, i32), Fault> {
|
||||
let len = i32::try_from(data.len()).map_err(|_| Fault::Protocol("too long".into()))?;
|
||||
let ptr = alloc.call(&mut *store, len).map_err(classify)?;
|
||||
if ptr <= 0 {
|
||||
return Err(Fault::Protocol("fp_alloc refused".into()));
|
||||
}
|
||||
memory
|
||||
.write(&mut *store, ptr as usize, data)
|
||||
.map_err(|_| Fault::Protocol("fp_alloc returned a bad pointer".into()))?;
|
||||
Ok((ptr, len))
|
||||
};
|
||||
|
||||
let (cp, cl) = put(&mut store, cfg)?;
|
||||
let rc = init.call(&mut store, (cp, cl)).map_err(classify)?;
|
||||
if rc != 0 {
|
||||
return Err(Fault::Init(rc));
|
||||
}
|
||||
let _ = free.call(&mut store, (cp, cl));
|
||||
|
||||
let (rp, rl) = put(&mut store, request)?;
|
||||
let packed = handle
|
||||
.call(&mut store, (kind as i32, rp, rl))
|
||||
.map_err(classify)?;
|
||||
let _ = free.call(&mut store, (rp, rl));
|
||||
|
||||
let out_ptr = ((packed as u64) >> 32) as usize;
|
||||
let out_len = (packed as u64 & 0xffff_ffff) as usize;
|
||||
if out_len > MAX_MESSAGE_BYTES {
|
||||
return Err(Fault::Protocol("response over 1 MiB".into()));
|
||||
}
|
||||
let mut body = vec![0u8; out_len];
|
||||
memory
|
||||
.read(&store, out_ptr, &mut body)
|
||||
.map_err(|_| Fault::Protocol("response outside memory".into()))?;
|
||||
if started.elapsed() > deadline {
|
||||
return Err(Fault::Timeout);
|
||||
}
|
||||
let left = store.get_fuel().unwrap_or(0);
|
||||
Ok(Output {
|
||||
body,
|
||||
fuel_used: limits.fuel.saturating_sub(left),
|
||||
host_calls: store.data().calls,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,687 @@
|
||||
//! Sandbox abuse suite (d04 13.4.11): each hostile guest fails its own call
|
||||
//! and never the host. Guests are written in WAT and assembled in the test.
|
||||
|
||||
use flare_plugin_abi::fp1::{CallRequest, Kind, Neg};
|
||||
use flare_plugin_host::runtime::Output;
|
||||
use flare_plugin_host::{
|
||||
load, Attestation, Fault, HostOps, KeyClass, Limits, LoadError, Mode, Policy, Runtime,
|
||||
WasmiRuntime,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Stub {
|
||||
calls: Vec<String>,
|
||||
logs: Vec<(i32, String)>,
|
||||
sleep_ms: u64,
|
||||
}
|
||||
|
||||
impl HostOps for Stub {
|
||||
fn call(&mut self, req: &CallRequest) -> Result<Vec<u8>, Neg> {
|
||||
self.calls.push(req.op.name.to_string());
|
||||
if self.sleep_ms > 0 {
|
||||
std::thread::sleep(Duration::from_millis(self.sleep_ms));
|
||||
}
|
||||
match req.op.name {
|
||||
"time.now@1" => Ok(br#"{"now":1}"#.to_vec()),
|
||||
"kv.get@1" => Err(Neg::NotFound),
|
||||
"http.fetch@1" => Ok(vec![b'x'; 5000]),
|
||||
_ => Err(Neg::OpDenied),
|
||||
}
|
||||
}
|
||||
fn log(&mut self, level: i32, msg: &str) {
|
||||
self.logs.push((level, msg.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(s: &[u8]) -> String {
|
||||
s.iter().map(|b| format!("\\{b:02x}")).collect()
|
||||
}
|
||||
|
||||
struct G {
|
||||
req: Vec<u8>,
|
||||
alloc: &'static str,
|
||||
init: &'static str,
|
||||
handle: String,
|
||||
extra: &'static str,
|
||||
imports: &'static str,
|
||||
}
|
||||
|
||||
impl G {
|
||||
fn new(handle: &str) -> G {
|
||||
G {
|
||||
req: Vec::new(),
|
||||
alloc: "(local.set $r (global.get $bump)) (global.set $bump (i32.add (global.get $bump) (local.get $n))) (local.get $r)",
|
||||
init: "(i32.const 0)",
|
||||
handle: handle.to_string(),
|
||||
extra: "",
|
||||
imports: "",
|
||||
}
|
||||
}
|
||||
|
||||
fn wasm(&self) -> Vec<u8> {
|
||||
let src = format!(
|
||||
r#"(module
|
||||
(import "fp1" "call" (func $call (param i32 i32 i32 i32) (result i32)))
|
||||
(import "fp1" "log" (func $log (param i32 i32 i32)))
|
||||
{imports}
|
||||
(memory (export "memory") 1 16)
|
||||
(global $bump (mut i32) (i32.const 4096))
|
||||
(global $ctr (mut i32) (i32.const 0))
|
||||
(data (i32.const 16) "{req}")
|
||||
(func (export "fp_alloc") (param $n i32) (result i32) (local $r i32) {alloc})
|
||||
(func (export "fp_free") (param i32 i32))
|
||||
(func (export "fp_init") (param i32 i32) (result i32) {init})
|
||||
(func $pack (param $p i32) (param $l i32) (result i64)
|
||||
(i64.or (i64.shl (i64.extend_i32_u (local.get $p)) (i64.const 32)) (i64.extend_i32_u (local.get $l))))
|
||||
(func $int4 (param $v i32) (result i64)
|
||||
(i32.store (i32.const 600) (local.get $v)) (call $pack (i32.const 600) (i32.const 4)))
|
||||
(func $spin (param $n i32) (result i32) (call $spin (i32.add (local.get $n) (i32.const 1))))
|
||||
(func (export "fp_handle") (param $kind i32) (param $p i32) (param $l i32) (result i64)
|
||||
(local $i i32) (local $r i32) {handle})
|
||||
{extra})"#,
|
||||
req = hex(&self.req),
|
||||
alloc = self.alloc,
|
||||
init = self.init,
|
||||
handle = self.handle,
|
||||
extra = self.extra,
|
||||
imports = self.imports,
|
||||
);
|
||||
wat::parse_str(src).expect("guest assembles")
|
||||
}
|
||||
}
|
||||
|
||||
const ECHO: &str = "(call $pack (local.get $p) (local.get $l))";
|
||||
|
||||
/// Calls `fp1.call` `n` times with `req` and returns the last result (or the
|
||||
/// reply bytes when `reply`).
|
||||
fn caller(req: &str, n: u32, reply: bool) -> G {
|
||||
let tail = if reply {
|
||||
"(if (i32.lt_s (local.get $r) (i32.const 0)) (then (return (call $int4 (local.get $r))))) (call $pack (i32.const 512) (local.get $r))"
|
||||
} else {
|
||||
"(call $int4 (local.get $r))"
|
||||
};
|
||||
let mut g = G::new(&format!(
|
||||
"(block $done (loop $lp (br_if $done (i32.ge_u (local.get $i) (i32.const {n}))) \
|
||||
(local.set $r (call $call (i32.const 16) (i32.const {len}) (i32.const 512) (i32.const 64))) \
|
||||
(local.set $i (i32.add (local.get $i) (i32.const 1))) (br $lp))) {tail}",
|
||||
len = req.len()
|
||||
));
|
||||
g.req = req.as_bytes().to_vec();
|
||||
g
|
||||
}
|
||||
|
||||
fn run(
|
||||
rt: &WasmiRuntime,
|
||||
g: &G,
|
||||
limits: Limits,
|
||||
ops: &mut Stub,
|
||||
request: &[u8],
|
||||
) -> Result<Output, Fault> {
|
||||
let bytes = g.wasm();
|
||||
let (m, _) = rt.compile(&bytes).expect("compile");
|
||||
rt.call(&m, &limits, Kind::Http, b"{}", request, ops)
|
||||
}
|
||||
|
||||
fn lim() -> Limits {
|
||||
Limits {
|
||||
memory_mb: 1,
|
||||
fuel: 10_000_000,
|
||||
call_ms: Some(2_000),
|
||||
}
|
||||
}
|
||||
|
||||
fn int4(o: &Output) -> i32 {
|
||||
i32::from_le_bytes(o.body[..4].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo_round_trip() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let out = run(
|
||||
&rt,
|
||||
&G::new(ECHO),
|
||||
lim(),
|
||||
&mut Stub::default(),
|
||||
br#"{"route":"/x"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out.body, br#"{"route":"/x"}"#);
|
||||
assert!(out.fuel_used > 0 && out.fuel_used < 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_kind_reaches_the_guest() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $int4 (local.get $kind))");
|
||||
let (m, _) = rt.compile(&g.wasm()).unwrap();
|
||||
let out = rt
|
||||
.call(&m, &lim(), Kind::Page, b"{}", b"{}", &mut Stub::default())
|
||||
.unwrap();
|
||||
assert_eq!(int4(&out), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_state_survives_between_calls() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new(
|
||||
"(global.set $ctr (i32.add (global.get $ctr) (i32.const 1))) (call $int4 (global.get $ctr))",
|
||||
);
|
||||
let (m, _) = rt.compile(&g.wasm()).unwrap();
|
||||
let mut o = Stub::default();
|
||||
for _ in 0..3 {
|
||||
let out = rt
|
||||
.call(&m, &lim(), Kind::Http, b"{}", b"{}", &mut o)
|
||||
.unwrap();
|
||||
assert_eq!(int4(&out), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infinite_loop_runs_out_of_fuel() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(loop $l (br $l)) (i64.const 0)");
|
||||
let l = Limits {
|
||||
fuel: 100_000,
|
||||
..lim()
|
||||
};
|
||||
assert_eq!(
|
||||
run(&rt, &g, l, &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Fuel)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_recursion_traps_and_the_host_survives() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(drop (call $spin (i32.const 0))) (i64.const 0)");
|
||||
let l = Limits {
|
||||
fuel: u64::MAX / 2,
|
||||
..lim()
|
||||
};
|
||||
assert!(matches!(
|
||||
run(&rt, &g, l, &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Trap(_))
|
||||
));
|
||||
// The same runtime still serves a good guest.
|
||||
assert!(run(&rt, &G::new(ECHO), lim(), &mut Stub::default(), b"{}").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_bounds_access_traps() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $int4 (i32.load (i32.const 0x7ffffff0)))");
|
||||
assert!(matches!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Trap(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_traps() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("unreachable");
|
||||
assert!(matches!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Trap(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_grow_past_the_limit_is_refused() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// 1 MiB limit is 16 pages; the guest starts with 1 and asks for 100 more.
|
||||
let g = G::new("(call $int4 (memory.grow (i32.const 100)))");
|
||||
assert_eq!(
|
||||
int4(&run(&rt, &g, lim(), &mut Stub::default(), b"{}").unwrap()),
|
||||
-1
|
||||
);
|
||||
// Growing inside the limit works.
|
||||
let g = G::new("(call $int4 (memory.grow (i32.const 2)))");
|
||||
assert_eq!(
|
||||
int4(&run(&rt, &g, lim(), &mut Stub::default(), b"{}").unwrap()),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_needing_more_than_its_limit_fails_to_instantiate() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// Minimum 17 pages against a 1 MiB (16 page) limit; load() would refuse
|
||||
// it earlier, this checks the runtime alone.
|
||||
let src = r#"(module
|
||||
(import "fp1" "call" (func (param i32 i32 i32 i32) (result i32)))
|
||||
(import "fp1" "log" (func (param i32 i32 i32)))
|
||||
(memory (export "memory") 17 32)
|
||||
(func (export "fp_alloc") (param i32) (result i32) (i32.const 4096))
|
||||
(func (export "fp_free") (param i32 i32))
|
||||
(func (export "fp_init") (param i32 i32) (result i32) (i32.const 0))
|
||||
(func (export "fp_handle") (param i32 i32 i32) (result i64) (i64.const 0)))"#;
|
||||
let (m, _) = rt.compile(&wat::parse_str(src).unwrap()).unwrap();
|
||||
let r = rt.call(&m, &lim(), Kind::Http, b"{}", b"{}", &mut Stub::default());
|
||||
assert!(matches!(r, Err(Fault::Limit(_))), "{r:?}");
|
||||
}
|
||||
|
||||
/// Regression: wasmi's default depth of 1000 overflowed a 2 MiB native stack
|
||||
/// in a debug build, which aborts the whole process. Worker threads of the
|
||||
/// portal are small, so the depth is capped.
|
||||
#[test]
|
||||
fn runaway_recursion_traps_on_a_small_thread() {
|
||||
let h = std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(drop (call $spin (i32.const 0))) (i64.const 0)");
|
||||
let l = Limits {
|
||||
fuel: u64::MAX / 2,
|
||||
..lim()
|
||||
};
|
||||
run(&rt, &g, l, &mut Stub::default(), b"{}")
|
||||
})
|
||||
.unwrap();
|
||||
assert!(matches!(h.join().unwrap(), Err(Fault::Trap(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixty_five_host_calls_in_one_invocation_hit_the_cap() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = caller(r#"{"op":"time.now@1"}"#, 70, false);
|
||||
let mut ops = Stub::default();
|
||||
let out = run(&rt, &g, lim(), &mut ops, b"{}").unwrap();
|
||||
assert_eq!(int4(&out), Neg::Limit.code());
|
||||
assert_eq!(ops.calls.len(), 64);
|
||||
assert_eq!(out.host_calls, 70);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixty_four_calls_all_succeed() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = caller(r#"{"op":"time.now@1"}"#, 64, false);
|
||||
let mut ops = Stub::default();
|
||||
let out = run(&rt, &g, lim(), &mut ops, b"{}").unwrap();
|
||||
assert_eq!(int4(&out), 9);
|
||||
assert_eq!(ops.calls.len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn op_reply_reaches_the_guest() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = caller(r#"{"op":"time.now@1"}"#, 1, true);
|
||||
let out = run(&rt, &g, lim(), &mut Stub::default(), b"{}").unwrap();
|
||||
assert_eq!(out.body, br#"{"now":1}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn op_errors_become_negative_codes() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let cases = [
|
||||
(r#"{"op":"kv.get@1","args":{}}"#, Neg::NotFound),
|
||||
(r#"{"op":"sql.query@1"}"#, Neg::OpDenied),
|
||||
(r#"{"op":"nope@9"}"#, Neg::OpUnknown),
|
||||
(r#"not json"#, Neg::Arg),
|
||||
(r#"{"op":"time.now@1","extra":1}"#, Neg::Arg),
|
||||
(r#"{"op":"time.now@1","args":[]}"#, Neg::Arg),
|
||||
];
|
||||
for (req, want) in cases {
|
||||
let out = run(
|
||||
&rt,
|
||||
&caller(req, 1, false),
|
||||
lim(),
|
||||
&mut Stub::default(),
|
||||
b"{}",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(int4(&out), want.code(), "{req}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_larger_than_the_guest_buffer_is_e_limit() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// http.fetch@1 answers 5000 bytes into a 64-byte window.
|
||||
let g = caller(r#"{"op":"http.fetch@1"}"#, 1, false);
|
||||
let out = run(&rt, &g, lim(), &mut Stub::default(), b"{}").unwrap();
|
||||
assert_eq!(int4(&out), Neg::Limit.code());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_pointers_to_fp1_call_are_e_arg() {
|
||||
let rt = WasmiRuntime::new();
|
||||
for h in [
|
||||
// request outside memory
|
||||
"(call $int4 (call $call (i32.const 0x7fffff00) (i32.const 64) (i32.const 512) (i32.const 64)))",
|
||||
// output window outside memory
|
||||
"(call $int4 (call $call (i32.const 16) (i32.const 4) (i32.const 0x7fffff00) (i32.const 64)))",
|
||||
// negative length
|
||||
"(call $int4 (call $call (i32.const 16) (i32.const -1) (i32.const 512) (i32.const 64)))",
|
||||
// pointer plus capacity wraps
|
||||
"(call $int4 (call $call (i32.const 16) (i32.const 4) (i32.const 0xfffffff0) (i32.const 0x7fffffff)))",
|
||||
] {
|
||||
let out = run(&rt, &G::new(h), lim(), &mut Stub::default(), b"{}").unwrap();
|
||||
assert_eq!(int4(&out), Neg::Arg.code(), "{h}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversize_request_to_fp1_call_is_e_limit() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $int4 (call $call (i32.const 16) (i32.const 0x7ffffff0) (i32.const 512) (i32.const 64)))");
|
||||
let out = run(&rt, &g, lim(), &mut Stub::default(), b"{}").unwrap();
|
||||
assert_eq!(int4(&out), Neg::Limit.code());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversize_response_is_a_protocol_fault() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $pack (i32.const 0) (i32.const 0x7ffffff0))");
|
||||
assert!(matches!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Protocol(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_outside_memory_is_a_protocol_fault() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $pack (i32.const 0x00ff0000) (i32.const 64))");
|
||||
assert!(matches!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Protocol(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failing_init_discards_the_instance() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let mut g = G::new(ECHO);
|
||||
g.init = "(i32.const 7)";
|
||||
assert_eq!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Init(7))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocator_refusal_is_a_protocol_fault() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let mut g = G::new(ECHO);
|
||||
g.alloc = "(i32.const 0)";
|
||||
assert!(matches!(
|
||||
run(&rt, &g, lim(), &mut Stub::default(), b"{}"),
|
||||
Err(Fault::Protocol(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_over_one_mib_is_refused_before_running() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let big = vec![b'a'; 1024 * 1024 + 1];
|
||||
assert!(matches!(
|
||||
run(&rt, &G::new(ECHO), lim(), &mut Stub::default(), &big),
|
||||
Err(Fault::Protocol(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_host_op_past_the_deadline_is_a_timeout() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = caller(r#"{"op":"time.now@1"}"#, 1, false);
|
||||
let l = Limits {
|
||||
call_ms: Some(10),
|
||||
..lim()
|
||||
};
|
||||
let mut ops = Stub {
|
||||
sleep_ms: 40,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(run(&rt, &g, l, &mut ops, b"{}"), Err(Fault::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_call_after_the_deadline_is_e_timeout() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// Two calls; the first sleeps past the deadline, the second must refuse.
|
||||
let g = caller(r#"{"op":"time.now@1"}"#, 2, false);
|
||||
let l = Limits {
|
||||
call_ms: Some(10),
|
||||
..lim()
|
||||
};
|
||||
let mut ops = Stub {
|
||||
sleep_ms: 40,
|
||||
..Default::default()
|
||||
};
|
||||
let _ = run(&rt, &g, l, &mut ops, b"{}");
|
||||
assert_eq!(ops.calls.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_lines_are_truncated_and_capped() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// 600 bytes of 'a' at offset 2048, logged 40 times.
|
||||
let g = G::new(
|
||||
"(memory.fill (i32.const 2048) (i32.const 97) (i32.const 600)) \
|
||||
(block $d (loop $l (br_if $d (i32.ge_u (local.get $i) (i32.const 40))) \
|
||||
(call $log (i32.const 2) (i32.const 2048) (i32.const 600)) \
|
||||
(local.set $i (i32.add (local.get $i) (i32.const 1))) (br $l))) \
|
||||
(call $int4 (i32.const 0))",
|
||||
);
|
||||
let mut ops = Stub::default();
|
||||
run(&rt, &g, lim(), &mut ops, b"{}").unwrap();
|
||||
assert_eq!(ops.logs.len(), 32);
|
||||
assert!(ops.logs.iter().all(|(lv, m)| *lv == 2 && m.len() == 512));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_with_a_bad_pointer_is_dropped() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let g = G::new("(call $log (i32.const 1) (i32.const 0x7ffffff0) (i32.const 64)) (call $int4 (i32.const 0))");
|
||||
let mut ops = Stub::default();
|
||||
run(&rt, &g, lim(), &mut ops, b"{}").unwrap();
|
||||
assert!(ops.logs.is_empty());
|
||||
}
|
||||
|
||||
// Load gate.
|
||||
|
||||
fn att(bytes: &[u8], class: KeyClass) -> Attestation {
|
||||
Attestation {
|
||||
id: "hostile".into(),
|
||||
key_class: class,
|
||||
module_sha256: Sha256::digest(bytes).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn signed() -> Policy {
|
||||
Policy::new(Mode::Signed).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_module_loads_and_runs() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let l = load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Platform),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.unwrap();
|
||||
let out = rt
|
||||
.call(
|
||||
&l.module,
|
||||
&l.limits,
|
||||
Kind::Http,
|
||||
b"{}",
|
||||
b"[1]",
|
||||
&mut Stub::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out.body, b"[1]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_mode_loads_nothing() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let p = Policy::from_env_value(None).unwrap();
|
||||
let e = load(&rt, &p, &att(&bytes, KeyClass::Platform), &bytes, lim()).err();
|
||||
assert_eq!(e, Some(LoadError::Off));
|
||||
// The code and detail a Warden or an admin sees (s12 1282).
|
||||
assert_eq!(LoadError::Off.code(), "E_KEY");
|
||||
assert_eq!(LoadError::Off.to_string(), "E_KEY: plugins_off");
|
||||
assert_eq!(rt.cached(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partner_key_is_refused_with_e_key() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let e = load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Partner),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.err();
|
||||
assert_eq!(e, Some(LoadError::Key(KeyClass::Partner)));
|
||||
assert_eq!(e.unwrap().code(), "E_KEY");
|
||||
assert_eq!(rt.cached(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_key_is_refused_in_signed_mode() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let e = load(&rt, &signed(), &att(&bytes, KeyClass::Dev), &bytes, lim()).err();
|
||||
assert_eq!(e, Some(LoadError::Key(KeyClass::Dev)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_module_is_refused_with_e_hash() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let mut bytes = G::new(ECHO).wasm();
|
||||
let a = att(&bytes, KeyClass::Platform);
|
||||
let last = bytes.len() - 1;
|
||||
bytes[last] ^= 1;
|
||||
let e = load(&rt, &signed(), &a, &bytes, lim()).err().unwrap();
|
||||
assert_eq!(e, LoadError::Hash);
|
||||
assert_eq!(e.code(), "E_HASH");
|
||||
assert_eq!(rt.cached(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_module_is_refused() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let cut = &bytes[..bytes.len() / 2];
|
||||
// Even with a matching attestation the admission check refuses it.
|
||||
let e = load(&rt, &signed(), &att(cut, KeyClass::Platform), cut, lim())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(matches!(e, LoadError::Admission(_)), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_codes_surface_through_the_gate() {
|
||||
let rt = WasmiRuntime::new();
|
||||
// Unknown import.
|
||||
let mut g = G::new(ECHO);
|
||||
g.imports = r#"(import "env" "now" (func (result i32)))"#;
|
||||
let bytes = g.wasm();
|
||||
let e = load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Platform),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(e.code(), "E_IMPORT");
|
||||
// Start function.
|
||||
let mut g = G::new(ECHO);
|
||||
g.extra = "(func $st) (start $st)";
|
||||
let bytes = g.wasm();
|
||||
let e = load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Platform),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(e.code(), "E_WASM");
|
||||
// Memory maximum above the manifest limit (guest declares 16 pages, limit 0.5 MiB is
|
||||
// not expressible, so use a 1 MiB limit with a 32-page guest).
|
||||
let src = r#"(module
|
||||
(import "fp1" "call" (func (param i32 i32 i32 i32) (result i32)))
|
||||
(import "fp1" "log" (func (param i32 i32 i32)))
|
||||
(memory (export "memory") 1 32)
|
||||
(func (export "fp_alloc") (param i32) (result i32) (i32.const 4096))
|
||||
(func (export "fp_free") (param i32 i32))
|
||||
(func (export "fp_init") (param i32 i32) (result i32) (i32.const 0))
|
||||
(func (export "fp_handle") (param i32 i32 i32) (result i64) (i64.const 0)))"#;
|
||||
let bytes = wat::parse_str(src).unwrap();
|
||||
let e = load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Platform),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(e.code(), "E_LIMIT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_is_compiled_once_per_hash() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
for _ in 0..3 {
|
||||
load(
|
||||
&rt,
|
||||
&signed(),
|
||||
&att(&bytes, KeyClass::Platform),
|
||||
&bytes,
|
||||
lim(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(rt.cached(), 1);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "plugin-dev"))]
|
||||
#[test]
|
||||
fn dev_mode_is_refused_in_a_release_build() {
|
||||
assert!(Policy::from_env_value(Some("dev")).is_err());
|
||||
assert!(Policy::new(Mode::Dev).is_err());
|
||||
}
|
||||
|
||||
#[cfg(feature = "plugin-dev")]
|
||||
#[test]
|
||||
fn dev_mode_loads_dev_keys_with_the_feature() {
|
||||
let rt = WasmiRuntime::new();
|
||||
let bytes = G::new(ECHO).wasm();
|
||||
let p = Policy::from_env_value(Some("dev")).unwrap();
|
||||
assert!(load(&rt, &p, &att(&bytes, KeyClass::Dev), &bytes, lim()).is_ok());
|
||||
assert!(load(&rt, &p, &att(&bytes, KeyClass::Partner), &bytes, lim()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_values_parse() {
|
||||
assert_eq!(Policy::from_env_value(None).unwrap().mode(), Mode::Off);
|
||||
assert_eq!(Policy::from_env_value(Some("")).unwrap().mode(), Mode::Off);
|
||||
assert_eq!(
|
||||
Policy::from_env_value(Some("off")).unwrap().mode(),
|
||||
Mode::Off
|
||||
);
|
||||
assert_eq!(
|
||||
Policy::from_env_value(Some("signed")).unwrap().mode(),
|
||||
Mode::Signed
|
||||
);
|
||||
assert!(Policy::from_env_value(Some("yes")).is_err());
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "flare-ui-axum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "Bounded live-event transport for authenticated schema pages"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8", default-features = false, features = ["form", "query", "tokio", "http1", "original-uri"] }
|
||||
flare-ui = { path = "../flare-ui" }
|
||||
form_urlencoded = "1"
|
||||
futures-core = "0.3"
|
||||
maud = "0.27"
|
||||
rand = "0.8"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt", "sync", "time"] }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
http-body-util = "0.1"
|
||||
tokio = { version = "1", features = ["macros", "test-util", "net", "io-util"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
[[bench]]
|
||||
name = "live"
|
||||
harness = false
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# Live page transport
|
||||
|
||||
`Transport::events()` mounts an Axum 0.8 GET handler on a page's `/events`
|
||||
route. Share one `Transport` across routes so its limits cover the whole
|
||||
service. `Limits::default()` permits four streams per session and 32 total;
|
||||
FLARE can configure a larger global limit.
|
||||
|
||||
## Host contract
|
||||
|
||||
The consumer implements two interfaces:
|
||||
|
||||
- `Source::open` authenticates the request, resolves the requested page
|
||||
from its schema and binds that page to the principal. Sorting and tier
|
||||
query fields may affect rendering; they cannot grant access to readings.
|
||||
- `Page::snapshot` asynchronously rechecks session validity and permissions,
|
||||
then reads the journal and renders current values from one immutable cache
|
||||
snapshot. A host may await its authorization store before copying values.
|
||||
No synchronous lock may remain held across that await.
|
||||
It filters every key through the page schema and principal. It performs
|
||||
no blocking file or network I/O on the reactor.
|
||||
- `Page::subscribe` wakes the stream on value, schema or access changes.
|
||||
Call `Journal::invalidate` under the cache lock when schema or readable
|
||||
key membership changes, including permission expansion. It advances the
|
||||
replay floor so existing streams and new requests reload the page body.
|
||||
Revoked sessions or page permissions must fail the next snapshot.
|
||||
Closing the source ends the stream. Idle streams also recheck on ping.
|
||||
|
||||
The authenticated session identity is opaque and bounded to 256 bytes.
|
||||
Use one identity across that session's pages and devices. Never use a
|
||||
client-supplied query identity or a password as the session key.
|
||||
|
||||
`Journal` retains 256 change identities per Warden, without historical
|
||||
values. Allocate the initial sequence above the previous source
|
||||
incarnation's last sequence. The host owns this persistence or epoch
|
||||
allocation. Page HTML and the initial cursor must come from the same
|
||||
snapshot. A cursor before the journal boundary or ahead of the source
|
||||
requires a new page body.
|
||||
|
||||
Each journal key renders one event, which may contain several OOB elements.
|
||||
Different event kinds use different keys. A snapshot returns events in
|
||||
strict sequence order. Adjacent HTML events of the same kind share one
|
||||
frame, whose ID is the last included sequence. This lets a reconnect resume
|
||||
without skipping an unsent event. Snapshots may omit unauthorized keys;
|
||||
the transport never requests or accepts key lists from the client.
|
||||
|
||||
## Wire behavior
|
||||
|
||||
| Item | Contract |
|
||||
|---|---|
|
||||
| Initial cursor | `seq=N`; browser `Last-Event-ID` takes precedence for streams |
|
||||
| HTML events | `r`, `st`, `ap`; host-rendered OOB markup |
|
||||
| JSON events | `act`, `series`; host supplies their declared data shapes |
|
||||
| Replay | Current values for keys changed since the cursor |
|
||||
| Resync | Empty `rs` event, then stream close |
|
||||
| Event pacing | At most two data events per second; fresh snapshot before each |
|
||||
| Size | 64 KiB encoded event or aggregate change set; overflow becomes resync |
|
||||
| Retry | Uniform 2000-5000 ms initial retry field |
|
||||
| Keepalive | `: ping` after 15 seconds without a data event |
|
||||
| Poll | `mode=poll&seq=N`: HTML `r`, `st`, `ap` bodies and `X-Seq` |
|
||||
| Old poll cursor | HTTP 205, `X-Resync: 1`, empty body |
|
||||
| Poll limit | One per two seconds per session; separate bounded rate table |
|
||||
|
||||
Responses disable caching. Polls do not consume stream slots. Poll clients
|
||||
advance their cursor from `X-Seq`; chart and action polling need their own
|
||||
consumer endpoints, as the poll body contains HTML only.
|
||||
|
||||
## Backpressure boundary
|
||||
|
||||
Each response has one bounded frame slot. A producer waits at most ten
|
||||
seconds for the HTTP body to consume a frame, then stops and discards queued
|
||||
bytes. The response retains its stream slot until its body ends or drops,
|
||||
so stalled responses cannot bypass the global cap by timing out repeatedly.
|
||||
|
||||
Body consumption is not a TCP write acknowledgement. The consumer's HTTP
|
||||
server must also bound socket writes and connection lifetime. The on-target
|
||||
stalled-client disconnect and RSS acceptance tests remain consumer gates.
|
||||
The adapter does not own or close the server's TCP sockets.
|
||||
|
||||
Each snapshot also has a ten-second deadline. A pending authorization read
|
||||
cannot retain a stream producer indefinitely; dropping the body cancels the
|
||||
pending snapshot. Initial snapshot failures return an ordinary HTTP error
|
||||
and release the acquired stream slot before sending response headers.
|
||||
|
||||
## Action routes
|
||||
|
||||
`actions::router(host)` serves the d04 7.4 routes of one surface. Nest it under
|
||||
the prefix that the page URLs use (`/` on the Warden console, the Warden path in
|
||||
FLARE):
|
||||
|
||||
| Route | Reply |
|
||||
|---|---|
|
||||
| `POST {section}/{tab}/actions/{name}` | A refusal, a sync result or a pending status line |
|
||||
| `GET {section}/{tab}/actions/{name}/confirm` | The confirm page of the no-script path |
|
||||
| `GET {section}/{tab}/actions/{name}/status?id=` | `{id, state, detail}` JSON, `state` one of `running`, `ok`, `failed` |
|
||||
|
||||
The host implements `ActionHost`:
|
||||
|
||||
- `resolve` authenticates the request, compiles the page for this viewer with
|
||||
`compile_page_with_actions` and returns the control from
|
||||
`PageSnapshot::live_action`. It returns `Error::ActionDenied` (403 with the
|
||||
plate and no data, or problem+json `forbidden` for a JSON client) when
|
||||
`PageSnapshot::action_denied` names the action, and
|
||||
`Error::NotFound` for an unknown, hidden, local or unsupported action. The
|
||||
router calls it first on every route, status included.
|
||||
- `send` dispatches one command with the params that `decide` checked. The
|
||||
router calls it only after `flare_ui::actions::decide` has allowed the POST, so
|
||||
a refused request never reaches the device.
|
||||
- `status` answers an async action's state. It must check that the id belongs
|
||||
to this viewer and page.
|
||||
|
||||
The router compares the posted `csrf` with the token in the resolved control,
|
||||
reads `confirm_word` and the declared `param.<name>` fields, and bounds the form
|
||||
at 16 KiB (Q9: a profile-install `content_b64` of 10924 characters fits). A
|
||||
missing or repeated param, an undeclared `param.` field or a value
|
||||
outside its declared kind is refused with 422 before `send`. The confirm page
|
||||
takes its fields from the query of an arm form. A refusal answers its status
|
||||
with the refusal plate. For htmx requests (`HX-Request: true`) a success answers
|
||||
200 with the result or 202 with the pending status line. Without script a
|
||||
success answers 303 to the page. An API client that accepts `application/json`
|
||||
gets an async start as 202 with `{"id"}`. A refusal without script is the plate with its
|
||||
status, and the host wraps it in its shell. A client that accepts
|
||||
`application/json` and sends no htmx header gets a refusal, and a denied action,
|
||||
as `application/problem+json` with `type` and `status` (pending amendment row).
|
||||
|
||||
Host duties: the proof route must accept a posted `next` only when
|
||||
`flare_ui::actions::confirm_next_ok` holds for this surface's route prefix and
|
||||
its actions, because the proof prompt posts it. A host mounts these
|
||||
routes under its own authentication; this crate does not authenticate.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
cargo test -p flare-ui-axum --locked
|
||||
cargo clippy -p flare-ui-axum --all-targets --locked -- -D warnings
|
||||
cargo bench -p flare-ui-axum --bench live --locked
|
||||
```
|
||||
|
||||
Tests exercise the actual router, framed response bodies and a real HTTP
|
||||
connection with a host fixture that authenticates sessions and filters
|
||||
pages. They cover current-value replay, reconnect boundaries, event pacing,
|
||||
caps, expiry, poll limits, revocation and oversized resync. Benchmarks cover
|
||||
both replay sizes and encoding 50 readings; host timings do not establish
|
||||
the QEMU or panel load budget.
|
||||
|
||||
Edge session/cache wiring, schema-page SSR, HTTP/1.1 tab coordination and
|
||||
actual guest session continuity remain consumer work. This crate alone
|
||||
does not replace the legacy polling console or satisfy full M9 acceptance.
|
||||
@@ -0,0 +1,31 @@
|
||||
use criterion::{black_box, criterion_group, criterion_main, Criterion};
|
||||
use flare_ui_axum::journal::Journal;
|
||||
use flare_ui_axum::{Event, HtmlKind};
|
||||
use maud::html;
|
||||
|
||||
fn bench(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("live_transport");
|
||||
for count in [16, 256] {
|
||||
let mut journal = Journal::new(0).unwrap();
|
||||
for i in 0..count {
|
||||
journal.record(&format!("reading-{i}")).unwrap();
|
||||
}
|
||||
group.bench_function(format!("replay_{count}_keys"), |b| {
|
||||
b.iter(|| black_box(journal.since(black_box(0))))
|
||||
});
|
||||
}
|
||||
let event = Event::html(
|
||||
100,
|
||||
HtmlKind::Reading,
|
||||
html! {
|
||||
@for row in 0..50 { span id=(format!("r-{row}")) hx-swap-oob="outerHTML" { "23.5" } }
|
||||
},
|
||||
);
|
||||
group.bench_function("encode_50_readings", |b| {
|
||||
b.iter(|| black_box(event.encode().unwrap()))
|
||||
});
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,327 @@
|
||||
//! The action routes of d04 7.4: the POST that runs an action, its no-script
|
||||
//! confirm page and the status route of an async action.
|
||||
//!
|
||||
//! The host owns authentication, the page and the device. It implements
|
||||
//! [`ActionHost`]: `resolve` finds the live action for this viewer, `send`
|
||||
//! dispatches a command and `status` answers the poll. The router runs
|
||||
//! [`flare_ui::actions::decide`] on every POST before `send`, so a refused
|
||||
//! request never reaches the device, and `send` gets the params it checked.
|
||||
//! Nest [`router`] under the surface prefix that the page URLs use.
|
||||
//!
|
||||
//! Replies to the POST:
|
||||
//!
|
||||
//! | Outcome | htmx (`HX-Request: true`) | No script |
|
||||
//! |---|---|---|
|
||||
//! | Refused | the status of the refusal, with its plate | the same plate; the host wraps it in its shell |
|
||||
//! | Sync result | 200 with the host's fragment | 303 to the page |
|
||||
//! | Async started | 202 with the pending status line | 303 to the page |
|
||||
//! | Async started, `Accept: application/json` | 202 with the pending status line; the htmx header wins | 202 with `{"id"}` |
|
||||
//!
|
||||
//! A client that accepts JSON and sends no htmx header gets a refusal, and a denied
|
||||
//! action, as `application/problem+json` (`{"type", "status"}`) instead of the
|
||||
//! plate. The types are the d05 names where d05 has one (pending amendment row).
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{DefaultBodyLimit, Path, Query, RawForm, RawQuery, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
use flare_ui::actions::{self as contract, LiveAction, Params, Refusal, Submit};
|
||||
use maud::Markup;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// Largest action form the routes read, in bytes (Q9, 2026-11-06). A profile-install
|
||||
/// `content_b64` of 10924 base64 characters (an 8192-byte profile) fits with the
|
||||
/// token and the other fields, unless most of its characters are percent-encoded
|
||||
/// (`+`, `/`, `=`). A denser form answers 413 before any check runs.
|
||||
pub const MAX_FORM_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// The action a route names: its section and tab slugs, then the action id.
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct ActionRoute {
|
||||
pub section: String,
|
||||
pub tab: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// The live action of one viewer, as the host resolved it.
|
||||
#[derive(Debug)]
|
||||
pub struct Resolved {
|
||||
/// The control the page draws for this action: its rules, route and token.
|
||||
pub live: LiveAction,
|
||||
/// The request carried the cookie session, not a bearer token.
|
||||
pub cookie_session: bool,
|
||||
}
|
||||
|
||||
/// A device answer to an action that the rules allowed.
|
||||
#[derive(Debug)]
|
||||
pub enum Sent {
|
||||
/// A sync action's result, drawn in place.
|
||||
Done(Markup),
|
||||
/// An async action's id. Its result follows on the status route.
|
||||
Accepted(String),
|
||||
}
|
||||
|
||||
/// The state of one async action. `state` is `running`, `ok` or `failed`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Status {
|
||||
pub id: String,
|
||||
pub state: &'static str,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// The host side of the action routes. Implementations must not block the reactor.
|
||||
pub trait ActionHost: Send + Sync + 'static {
|
||||
/// Authenticates the request and returns the named action of its page as this
|
||||
/// viewer may run it. Unknown, hidden, disabled, local and unsupported actions
|
||||
/// are `Error::NotFound`. An action the viewer lacks the permission for is
|
||||
/// `Error::ActionDenied` (403 with the plate, d04 7.5); the host reads it from
|
||||
/// [`flare_ui::page::PageSnapshot::action_denied`]. The router calls this first
|
||||
/// on every route.
|
||||
fn resolve(
|
||||
&self,
|
||||
headers: &HeaderMap,
|
||||
route: &ActionRoute,
|
||||
) -> impl Future<Output = Result<Resolved, Error>> + Send;
|
||||
|
||||
/// Sends one action that [`contract::decide`] allowed. `params` are the values
|
||||
/// it checked against the declared kinds.
|
||||
fn send(
|
||||
&self,
|
||||
headers: &HeaderMap,
|
||||
live: &LiveAction,
|
||||
params: &Params,
|
||||
) -> impl Future<Output = Result<Sent, Refusal>> + Send;
|
||||
|
||||
/// The state of an async action this viewer started. The router resolves the
|
||||
/// viewer before it calls this. The host also checks that the id belongs to
|
||||
/// this viewer and page.
|
||||
fn status(
|
||||
&self,
|
||||
headers: &HeaderMap,
|
||||
route: &ActionRoute,
|
||||
id: &str,
|
||||
) -> impl Future<Output = Result<Status, Error>> + Send;
|
||||
}
|
||||
|
||||
/// The routes for one surface, with the host behind them.
|
||||
pub fn router<H: ActionHost>(host: H) -> Router {
|
||||
Router::new()
|
||||
.route("/{section}/{tab}/actions/{name}", post(run::<H>))
|
||||
.route("/{section}/{tab}/actions/{name}/confirm", get(confirm::<H>))
|
||||
.route("/{section}/{tab}/actions/{name}/status", get(status::<H>))
|
||||
.layer(DefaultBodyLimit::max(MAX_FORM_BYTES))
|
||||
.with_state(Arc::new(host))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct StatusQuery {
|
||||
id: Option<String>,
|
||||
}
|
||||
|
||||
async fn run<H: ActionHost>(
|
||||
State(host): State<Arc<H>>,
|
||||
Path(route): Path<ActionRoute>,
|
||||
headers: HeaderMap,
|
||||
RawForm(body): RawForm,
|
||||
) -> Response {
|
||||
let resolved = match host.resolve(&headers, &route).await {
|
||||
Ok(resolved) => resolved,
|
||||
Err(error) => return host_error(error, &headers),
|
||||
};
|
||||
let live = &resolved.live;
|
||||
let fields = form_fields(&body);
|
||||
let submit = Submit {
|
||||
csrf_ok: field(&fields, "csrf")
|
||||
.is_some_and(|posted| contract::token_matches(posted, &live.csrf)),
|
||||
cookie_session: resolved.cookie_session,
|
||||
fresh_proof: live.fresh_proof,
|
||||
confirm_word: field(&fields, "confirm_word"),
|
||||
fields: fields.as_slice(),
|
||||
};
|
||||
let params = match contract::decide(&live.spec, &submit) {
|
||||
Ok(params) => params,
|
||||
Err(refusal) => return refused(refusal, live, &headers),
|
||||
};
|
||||
let htmx = is_htmx(&headers);
|
||||
match host.send(&headers, live, ¶ms).await {
|
||||
Ok(Sent::Done(markup)) if htmx => fragment(StatusCode::OK, markup.into_string()),
|
||||
Ok(Sent::Done(_)) => back(live),
|
||||
Ok(Sent::Accepted(id)) if wants_json(&headers) => accepted_json(&id),
|
||||
Ok(Sent::Accepted(id)) => match contract::pending_plate(&id, &live.status_url) {
|
||||
Some(markup) if htmx => fragment(StatusCode::ACCEPTED, markup.into_string()),
|
||||
Some(_) => back(live),
|
||||
None => Error::InvalidSource.into_response(),
|
||||
},
|
||||
Err(refusal) => refused(refusal, live, &headers),
|
||||
}
|
||||
}
|
||||
|
||||
/// The confirm page. Its query carries the params of an arm form, which prefill
|
||||
/// the page's fields; the POST still checks every value.
|
||||
async fn confirm<H: ActionHost>(
|
||||
State(host): State<Arc<H>>,
|
||||
Path(route): Path<ActionRoute>,
|
||||
headers: HeaderMap,
|
||||
RawQuery(query): RawQuery,
|
||||
) -> Response {
|
||||
match host.resolve(&headers, &route).await {
|
||||
Ok(resolved) => {
|
||||
let given = query
|
||||
.map(|query| form_fields(query.as_bytes()))
|
||||
.unwrap_or_default();
|
||||
fragment(
|
||||
StatusCode::OK,
|
||||
contract::confirm_page_with(&resolved.live, &given).into_string(),
|
||||
)
|
||||
}
|
||||
Err(error) => host_error(error, &headers),
|
||||
}
|
||||
}
|
||||
|
||||
async fn status<H: ActionHost>(
|
||||
State(host): State<Arc<H>>,
|
||||
Path(route): Path<ActionRoute>,
|
||||
Query(query): Query<StatusQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
// The viewer is resolved first, so a request that is not for a live action of
|
||||
// this surface never reaches the host's action state.
|
||||
if let Err(error) = host.resolve(&headers, &route).await {
|
||||
return host_error(error, &headers);
|
||||
}
|
||||
let Some(id) = query.id.filter(|id| contract::id_ok(id)) else {
|
||||
return (StatusCode::BAD_REQUEST, "invalid action id").into_response();
|
||||
};
|
||||
match host.status(&headers, &route, &id).await {
|
||||
Ok(answer) if answer.id == id && matches!(answer.state, "running" | "ok" | "failed") => {
|
||||
let body = json!({
|
||||
"id": answer.id,
|
||||
"state": answer.state,
|
||||
"detail": answer.detail
|
||||
});
|
||||
(
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/json"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
body.to_string(),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Ok(_) => Error::InvalidSource.into_response(),
|
||||
Err(error) => host_error(error, &headers),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of a form body or query, as posted and in order.
|
||||
fn form_fields(bytes: &[u8]) -> Vec<(String, String)> {
|
||||
form_urlencoded::parse(bytes).into_owned().collect()
|
||||
}
|
||||
|
||||
/// The first posted value of `name`.
|
||||
fn field<'a>(fields: &'a [(String, String)], name: &str) -> Option<&'a str> {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(key, _)| key == name)
|
||||
.map(|(_, value)| value.as_str())
|
||||
}
|
||||
|
||||
/// The refusal's status with its plate. A missing proof adds the prompt, and a
|
||||
/// wrong typed word or a bad param draws the control again, so the viewer can
|
||||
/// retry on the page.
|
||||
fn refused(refusal: Refusal, live: &LiveAction, headers: &HeaderMap) -> Response {
|
||||
let status =
|
||||
StatusCode::from_u16(refusal.status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
if wants_json(headers) {
|
||||
return problem(status, refusal.problem());
|
||||
}
|
||||
fragment(
|
||||
status,
|
||||
contract::refusal_plate(refusal, Some(live)).into_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The answer to an error from the host's resolve or status. A denied action is
|
||||
/// 403 for every client (d04 7.5). A JSON API client gets it as problem+json,
|
||||
/// and any other client keeps the plate.
|
||||
fn host_error(error: Error, headers: &HeaderMap) -> Response {
|
||||
if error == Error::ActionDenied && wants_json(headers) {
|
||||
return problem(StatusCode::FORBIDDEN, contract::Refusal::Denied.problem());
|
||||
}
|
||||
error.into_response()
|
||||
}
|
||||
|
||||
/// A refusal for a JSON API client: `application/problem+json` with the d05
|
||||
/// problem type and the status (d05 11.4, amendment row for action refusals).
|
||||
fn problem(status: StatusCode, kind: &str) -> Response {
|
||||
(
|
||||
status,
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/problem+json"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
json!({ "type": kind, "status": status.as_u16() }).to_string(),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// The page the viewer came from, for a no-script success. The target is checked
|
||||
/// as a same-origin path before the redirect.
|
||||
fn back(live: &LiveAction) -> Response {
|
||||
if contract::safe_target(&live.back) {
|
||||
Redirect::to(&live.back).into_response()
|
||||
} else {
|
||||
Error::InvalidSource.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
fn fragment(status: StatusCode, body: String) -> Response {
|
||||
(
|
||||
status,
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// True for an API client: it accepts JSON and did not send the htmx header.
|
||||
fn wants_json(headers: &HeaderMap) -> bool {
|
||||
!is_htmx(headers)
|
||||
&& headers
|
||||
.get(header::ACCEPT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|accept| accept.contains("application/json"))
|
||||
}
|
||||
|
||||
/// The async start of an API client: 202 with the id, as d04 7.4 names it.
|
||||
fn accepted_json(id: &str) -> Response {
|
||||
if !contract::id_ok(id) {
|
||||
return Error::InvalidSource.into_response();
|
||||
}
|
||||
(
|
||||
StatusCode::ACCEPTED,
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/json"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
json!({ "id": id }).to_string(),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn is_htmx(headers: &HeaderMap) -> bool {
|
||||
headers
|
||||
.get("hx-request")
|
||||
.is_some_and(|value| value.as_bytes() == b"true")
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Change identities only; the page renders their current values on replay.
|
||||
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
|
||||
/// Change records retained per source, regardless of the number of viewers.
|
||||
pub const REPLAY_CAPACITY: usize = 256;
|
||||
/// Integers carried through the browser without losing precision.
|
||||
pub const MAX_SEQUENCE: u64 = (1_u64 << 53) - 1;
|
||||
|
||||
/// The most recent change of one server-owned rendering key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Change {
|
||||
pub seq: u64,
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
/// A replay either identifies changed keys or requires a new page body.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Replay {
|
||||
Changes { seq: u64, keys: Vec<Change> },
|
||||
Resync { seq: u64 },
|
||||
}
|
||||
|
||||
/// Bounded journal for one Warden's value cache.
|
||||
///
|
||||
/// Update values and this journal under the same host-owned lock. Render
|
||||
/// replayed keys under that lock too, after applying schema and permissions.
|
||||
/// The initial sequence must exceed the previous source incarnation's last
|
||||
/// sequence; the host owns that persistence or epoch allocation.
|
||||
#[derive(Debug)]
|
||||
pub struct Journal {
|
||||
seq: u64,
|
||||
floor: u64,
|
||||
records: VecDeque<Change>,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
pub fn new(initial: u64) -> Result<Self, &'static str> {
|
||||
if initial > MAX_SEQUENCE {
|
||||
return Err("sequence exceeds browser precision");
|
||||
}
|
||||
Ok(Self {
|
||||
seq: initial,
|
||||
floor: initial,
|
||||
records: VecDeque::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn seq(&self) -> u64 {
|
||||
self.seq
|
||||
}
|
||||
|
||||
/// Call under the value-cache lock before changing schema or readable
|
||||
/// key membership, including permission expansion. Older page cursors
|
||||
/// must reload even when no reading value changed.
|
||||
pub fn invalidate(&mut self) -> Result<u64, &'static str> {
|
||||
if self.seq == MAX_SEQUENCE {
|
||||
return Err("sequence exhausted");
|
||||
}
|
||||
self.seq += 1;
|
||||
self.floor = self.seq;
|
||||
self.records.clear();
|
||||
Ok(self.seq)
|
||||
}
|
||||
|
||||
/// Record one rendering key. A key may render several OOB elements in
|
||||
/// one event; different event kinds use distinct keys and sequences.
|
||||
pub fn record(&mut self, key: &str) -> Result<u64, &'static str> {
|
||||
if key.is_empty() || key.len() > 256 {
|
||||
return Err("rendering key must contain 1 to 256 bytes");
|
||||
}
|
||||
if self.seq == MAX_SEQUENCE {
|
||||
return Err("sequence exhausted");
|
||||
}
|
||||
self.seq += 1;
|
||||
self.records.push_back(Change {
|
||||
seq: self.seq,
|
||||
key: key.into(),
|
||||
});
|
||||
if self.records.len() > REPLAY_CAPACITY {
|
||||
self.floor = self.records.pop_front().expect("full journal").seq;
|
||||
}
|
||||
Ok(self.seq)
|
||||
}
|
||||
|
||||
pub fn since(&self, cursor: u64) -> Replay {
|
||||
if cursor < self.floor || cursor > self.seq {
|
||||
return Replay::Resync { seq: self.seq };
|
||||
}
|
||||
let mut latest = BTreeMap::new();
|
||||
for change in self.records.iter().filter(|change| change.seq > cursor) {
|
||||
latest.insert(&change.key, change.seq);
|
||||
}
|
||||
let mut keys: Vec<_> = latest
|
||||
.into_iter()
|
||||
.map(|(key, seq)| Change {
|
||||
seq,
|
||||
key: key.clone(),
|
||||
})
|
||||
.collect();
|
||||
keys.sort_by_key(|change| change.seq);
|
||||
Replay::Changes {
|
||||
seq: self.seq,
|
||||
keys,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
//! SSE and poll responses for host-authenticated schema pages, and the d04 7.4
|
||||
//! action routes ([`actions`]).
|
||||
//!
|
||||
//! The host supplies a [`Source`] and a [`Page`] bound to its principal,
|
||||
//! schema and value cache. This crate never accepts reading keys from the
|
||||
//! request. See the crate README for the host and socket-write contracts.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod actions;
|
||||
pub mod journal;
|
||||
mod limits;
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::extract::{OriginalUri, Query, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode, Uri};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, MethodRouter};
|
||||
use futures_core::Stream;
|
||||
use maud::Markup;
|
||||
use rand::Rng;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio::time::{Duration, Instant};
|
||||
|
||||
pub use limits::Limits;
|
||||
|
||||
/// Maximum encoded event or aggregate poll body.
|
||||
pub const MAX_BYTES: usize = 64 * 1024;
|
||||
const COALESCE: Duration = Duration::from_millis(500);
|
||||
const KEEPALIVE: Duration = Duration::from_secs(15);
|
||||
const STALL: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Unauthenticated,
|
||||
Forbidden,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
InvalidSource,
|
||||
Limited,
|
||||
BadRequest,
|
||||
/// The viewer lacks the action's permission: 403 with the plate and no data
|
||||
/// (d04 7.5). Unknown and hidden actions stay [`Error::NotFound`].
|
||||
ActionDenied,
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> Response {
|
||||
if self == Self::ActionDenied {
|
||||
// The refusal plate, so the viewer sees why; it carries no data.
|
||||
return (
|
||||
StatusCode::FORBIDDEN,
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
flare_ui::actions::refusal_plate(flare_ui::actions::Refusal::Denied, None)
|
||||
.into_string(),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let (status, message) = match self {
|
||||
Self::Unauthenticated => (StatusCode::UNAUTHORIZED, "authentication required"),
|
||||
Self::Forbidden => (StatusCode::FORBIDDEN, "page access denied"),
|
||||
Self::NotFound => (StatusCode::NOT_FOUND, "no such page"),
|
||||
Self::Unavailable => (StatusCode::SERVICE_UNAVAILABLE, "live source unavailable"),
|
||||
Self::InvalidSource => (StatusCode::INTERNAL_SERVER_ERROR, "invalid live source"),
|
||||
Self::Limited => (StatusCode::TOO_MANY_REQUESTS, "live request limit reached"),
|
||||
Self::BadRequest => (StatusCode::BAD_REQUEST, "invalid live cursor or mode"),
|
||||
Self::ActionDenied => (StatusCode::FORBIDDEN, "action access denied"),
|
||||
};
|
||||
let mut response = (status, message).into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
|
||||
if self == Self::Limited {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::RETRY_AFTER, "2".parse().unwrap());
|
||||
}
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
/// Authenticate first, resolve the page from server schema, then bind its
|
||||
/// allowed blocks to that principal. Query fields may select sort/tier, never
|
||||
/// the set of readable keys. Implementations must not block the reactor.
|
||||
pub trait Source: Send + Sync + 'static {
|
||||
type Page: Page;
|
||||
fn open(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
headers: &HeaderMap,
|
||||
) -> impl Future<Output = Result<Self::Page, Error>> + Send;
|
||||
}
|
||||
|
||||
/// One authenticated page. A snapshot checks the session and permissions
|
||||
/// again, reads the journal and renders current values atomically. Omit keys
|
||||
/// outside this page or principal. Invalidate the journal atomically when
|
||||
/// schema or readable-key membership changes, including expanded grants.
|
||||
/// Notify on data, schema or access changes; closing the source ends streams.
|
||||
pub trait Page: Send + 'static {
|
||||
/// Opaque authenticated session identity, shared across pages/devices.
|
||||
fn session(&self) -> &str;
|
||||
fn subscribe(&self) -> watch::Receiver<u64>;
|
||||
/// Revalidate access before copying a value snapshot. Do not hold a
|
||||
/// synchronous lock across an await. The transport bounds this future
|
||||
/// by its ten-second progress deadline and cancels it on disconnect.
|
||||
fn snapshot(&self, since: u64) -> impl Future<Output = Result<Batch, Error>> + Send;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HtmlKind {
|
||||
Reading,
|
||||
State,
|
||||
Approvals,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum JsonKind {
|
||||
Action,
|
||||
Series,
|
||||
}
|
||||
|
||||
/// One current-value event, carrying the journal sequence of its rendering
|
||||
/// key. Multiple OOB elements of that key belong in the same HTML event.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Event {
|
||||
seq: u64,
|
||||
name: &'static str,
|
||||
data: String,
|
||||
html: bool,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
fn first_frame(events: Vec<Self>) -> Option<Self> {
|
||||
let mut events = events.into_iter();
|
||||
let mut first = events.next()?;
|
||||
for next in events {
|
||||
// Never advance an ID past a different, unsent event kind.
|
||||
if !first.html || !next.html || first.name != next.name {
|
||||
break;
|
||||
}
|
||||
first.seq = next.seq;
|
||||
first.data.push_str(&next.data);
|
||||
}
|
||||
Some(first)
|
||||
}
|
||||
|
||||
pub fn html(seq: u64, kind: HtmlKind, markup: Markup) -> Self {
|
||||
let name = match kind {
|
||||
HtmlKind::Reading => "r",
|
||||
HtmlKind::State => "st",
|
||||
HtmlKind::Approvals => "ap",
|
||||
};
|
||||
Self {
|
||||
seq,
|
||||
name,
|
||||
data: markup.into_string(),
|
||||
html: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn json(seq: u64, kind: JsonKind, value: Value) -> Self {
|
||||
let name = match kind {
|
||||
JsonKind::Action => "act",
|
||||
JsonKind::Series => "series",
|
||||
};
|
||||
Self {
|
||||
seq,
|
||||
name,
|
||||
data: value.to_string(),
|
||||
html: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode fields without allowing payload newlines to inject SSE fields.
|
||||
pub fn encode(&self) -> Result<Bytes, Error> {
|
||||
if self.seq > journal::MAX_SEQUENCE || self.data.len() > MAX_BYTES {
|
||||
return Err(Error::InvalidSource);
|
||||
}
|
||||
let mut out = format!("id: {}\nevent: {}\n", self.seq, self.name);
|
||||
for line in self
|
||||
.data
|
||||
.replace("\r\n", "\n")
|
||||
.replace('\r', "\n")
|
||||
.split('\n')
|
||||
{
|
||||
if out.len() + 6 + line.len() + 1 > MAX_BYTES - 1 {
|
||||
return Err(Error::InvalidSource);
|
||||
}
|
||||
out.push_str("data: ");
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
out.push('\n');
|
||||
Ok(out.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Events must have strictly increasing sequences above the cursor and no
|
||||
/// later than `seq`. A sequence advances only after that event is consumed,
|
||||
/// so reconnecting between events cannot skip the rest of a change set.
|
||||
pub enum Batch {
|
||||
Changes { seq: u64, events: Vec<Event> },
|
||||
Resync { seq: u64 },
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
fn checked(self, cursor: u64) -> Result<Self, Error> {
|
||||
let (seq, events) = match self {
|
||||
Self::Resync { seq } if seq <= journal::MAX_SEQUENCE => {
|
||||
return Ok(Self::Resync { seq })
|
||||
}
|
||||
Self::Resync { .. } => return Err(Error::InvalidSource),
|
||||
Self::Changes { seq, events } => (seq, events),
|
||||
};
|
||||
if seq > journal::MAX_SEQUENCE {
|
||||
return Err(Error::InvalidSource);
|
||||
}
|
||||
if seq < cursor || events.len() > journal::REPLAY_CAPACITY {
|
||||
return Ok(Self::Resync { seq });
|
||||
}
|
||||
let mut last = cursor;
|
||||
let mut bytes = 0usize;
|
||||
for event in &events {
|
||||
if event.seq <= last || event.seq > seq {
|
||||
return Err(Error::InvalidSource);
|
||||
}
|
||||
last = event.seq;
|
||||
let Ok(encoded) = event.encode() else {
|
||||
return Ok(Self::Resync { seq });
|
||||
};
|
||||
bytes += encoded.len();
|
||||
if bytes > MAX_BYTES {
|
||||
return Ok(Self::Resync { seq });
|
||||
}
|
||||
}
|
||||
Ok(Self::Changes { seq, events })
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner<S> {
|
||||
source: S,
|
||||
limits: Limits,
|
||||
counts: limits::Shared,
|
||||
}
|
||||
|
||||
/// Share one transport across all live routes to enforce global/session caps.
|
||||
pub struct Transport<S>(Arc<Inner<S>>);
|
||||
|
||||
impl<S> Clone for Transport<S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Source> Transport<S> {
|
||||
pub fn new(source: S, limits: Limits) -> Result<Self, &'static str> {
|
||||
if limits.global == 0 || limits.per_session == 0 || limits.poll_sessions == 0 {
|
||||
return Err("live limits must be positive");
|
||||
}
|
||||
Ok(Self(Arc::new(Inner {
|
||||
source,
|
||||
limits,
|
||||
counts: Arc::new(Mutex::new(Default::default())),
|
||||
})))
|
||||
}
|
||||
|
||||
/// Mount on each resolved page's `/events` route.
|
||||
pub fn events(&self) -> MethodRouter {
|
||||
get(handle::<S>).with_state(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Params {
|
||||
seq: Option<u64>,
|
||||
mode: Option<String>,
|
||||
}
|
||||
|
||||
fn cursor(params: &Params, headers: &HeaderMap) -> Result<u64, Error> {
|
||||
if params.mode.as_deref().is_some_and(|mode| mode != "poll") {
|
||||
return Err(Error::BadRequest);
|
||||
}
|
||||
let value = if params.mode.is_none() && headers.contains_key("last-event-id") {
|
||||
if headers.get_all("last-event-id").iter().count() != 1 {
|
||||
return Err(Error::BadRequest);
|
||||
}
|
||||
let text = headers["last-event-id"]
|
||||
.to_str()
|
||||
.map_err(|_| Error::BadRequest)?;
|
||||
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(Error::BadRequest);
|
||||
}
|
||||
text.parse().map_err(|_| Error::BadRequest)?
|
||||
} else {
|
||||
params.seq.ok_or(Error::BadRequest)?
|
||||
};
|
||||
if value > journal::MAX_SEQUENCE {
|
||||
return Err(Error::BadRequest);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
async fn handle<S: Source>(
|
||||
State(transport): State<Transport<S>>,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
headers: HeaderMap,
|
||||
Query(params): Query<Params>,
|
||||
) -> Result<Response, Error> {
|
||||
let page = transport.0.source.open(&uri, &headers).await?;
|
||||
let cursor = cursor(¶ms, &headers)?;
|
||||
if params.mode.is_some() {
|
||||
limits::poll(&transport.0.counts, transport.0.limits, page.session())?;
|
||||
return poll_response(checked_snapshot(&page, cursor).await?);
|
||||
}
|
||||
let lease = limits::acquire(&transport.0.counts, transport.0.limits, page.session())?;
|
||||
let changed = page.subscribe();
|
||||
// Return an ordinary error before sending streaming response headers.
|
||||
checked_snapshot(&page, cursor).await?;
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let ended = Arc::new(AtomicBool::new(false));
|
||||
let retry = rand::thread_rng().gen_range(2000..=5000);
|
||||
tokio::spawn(produce(
|
||||
page,
|
||||
changed,
|
||||
cursor,
|
||||
tx,
|
||||
Ended(ended.clone()),
|
||||
retry,
|
||||
));
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/event-stream"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
(header::HeaderName::from_static("x-accel-buffering"), "no"),
|
||||
],
|
||||
Body::from_stream(Frames {
|
||||
rx,
|
||||
ended,
|
||||
lease: Some(lease),
|
||||
}),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
fn checked_snapshot<P: Page>(
|
||||
page: &P,
|
||||
cursor: u64,
|
||||
) -> impl Future<Output = Result<Batch, Error>> + Send + '_ {
|
||||
let snapshot = page.snapshot(cursor);
|
||||
async move {
|
||||
tokio::time::timeout(STALL, snapshot)
|
||||
.await
|
||||
.map_err(|_| Error::Unavailable)?
|
||||
.and_then(|batch| batch.checked(cursor))
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_response(batch: Batch) -> Result<Response, Error> {
|
||||
let (status, seq, body) = match batch {
|
||||
Batch::Resync { seq } => (StatusCode::RESET_CONTENT, seq, String::new()),
|
||||
Batch::Changes { seq, events } => (
|
||||
StatusCode::OK,
|
||||
seq,
|
||||
events
|
||||
.into_iter()
|
||||
.filter(|event| event.html)
|
||||
.map(|event| event.data)
|
||||
.collect::<String>(),
|
||||
),
|
||||
};
|
||||
let mut response = (
|
||||
status,
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response();
|
||||
response.headers_mut().insert(
|
||||
"x-seq",
|
||||
seq.to_string().parse().map_err(|_| Error::InvalidSource)?,
|
||||
);
|
||||
if status == StatusCode::RESET_CONTENT {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-resync", "1".parse().unwrap());
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
type Frame = (Bytes, oneshot::Sender<()>);
|
||||
|
||||
struct Frames {
|
||||
rx: mpsc::Receiver<Frame>,
|
||||
ended: Arc<AtomicBool>,
|
||||
// Keep stalled HTTP responses charged until the body ends or is dropped.
|
||||
lease: Option<limits::Lease>,
|
||||
}
|
||||
|
||||
struct Ended(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for Ended {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for Frames {
|
||||
type Item = Result<Bytes, Infallible>;
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
if self.ended.load(Ordering::Acquire) {
|
||||
self.rx.close();
|
||||
while self.rx.try_recv().is_ok() {}
|
||||
self.lease.take();
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
self.rx.poll_recv(cx).map(|frame| {
|
||||
frame.map(|(bytes, ack)| {
|
||||
let _ = ack.send(());
|
||||
Ok(bytes)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(tx: &mpsc::Sender<Frame>, bytes: Bytes) -> bool {
|
||||
let (ack, consumed) = oneshot::channel();
|
||||
tokio::time::timeout(STALL, async {
|
||||
tx.send((bytes, ack)).await.map_err(|_| ())?;
|
||||
consumed.await.map_err(|_| ())
|
||||
})
|
||||
.await
|
||||
.is_ok_and(|result| result.is_ok())
|
||||
}
|
||||
|
||||
async fn produce<P: Page>(
|
||||
page: P,
|
||||
mut changed: watch::Receiver<u64>,
|
||||
mut cursor: u64,
|
||||
tx: mpsc::Sender<Frame>,
|
||||
_ended: Ended,
|
||||
retry: u32,
|
||||
) {
|
||||
if !send(&tx, format!("retry: {retry}\n\n").into()).await {
|
||||
return;
|
||||
}
|
||||
let mut next = Instant::now();
|
||||
let mut ping = Instant::now() + KEEPALIVE;
|
||||
loop {
|
||||
tokio::select! { _ = tx.closed() => return, _ = tokio::time::sleep_until(next) => {} }
|
||||
let batch = tokio::select! {
|
||||
_ = tx.closed() => return,
|
||||
result = checked_snapshot(&page, cursor) => result,
|
||||
};
|
||||
let Ok(batch) = batch else { return };
|
||||
match batch {
|
||||
Batch::Resync { seq } => {
|
||||
send(&tx, format!("id: {seq}\nevent: rs\ndata: \n\n").into()).await;
|
||||
return;
|
||||
}
|
||||
Batch::Changes { seq, events } => {
|
||||
if let Some(event) = Event::first_frame(events) {
|
||||
let Ok(bytes) = event.encode() else {
|
||||
return;
|
||||
};
|
||||
if !send(&tx, bytes).await {
|
||||
return;
|
||||
}
|
||||
cursor = event.seq;
|
||||
next = Instant::now() + COALESCE;
|
||||
ping = Instant::now() + KEEPALIVE;
|
||||
continue;
|
||||
}
|
||||
cursor = seq;
|
||||
}
|
||||
}
|
||||
if Instant::now() >= ping {
|
||||
if !send(&tx, Bytes::from_static(b": ping\n\n")).await {
|
||||
return;
|
||||
}
|
||||
ping = Instant::now() + KEEPALIVE;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tx.closed() => return,
|
||||
result = changed.changed() => if result.is_err() { return; },
|
||||
_ = tokio::time::sleep_until(ping) => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::time::{Duration, Instant};
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// Deployment caps. Polls have a separate bounded rate-limit table.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub per_session: usize,
|
||||
pub global: usize,
|
||||
pub poll_sessions: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
per_session: 4,
|
||||
global: 32,
|
||||
poll_sessions: 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Counts {
|
||||
streams: HashMap<String, usize>,
|
||||
total: usize,
|
||||
polls: HashMap<String, Instant>,
|
||||
}
|
||||
|
||||
pub(crate) type Shared = Arc<Mutex<Counts>>;
|
||||
|
||||
pub(crate) struct Lease {
|
||||
counts: Shared,
|
||||
session: String,
|
||||
}
|
||||
|
||||
fn session_ok(session: &str) -> Result<(), Error> {
|
||||
if session.is_empty() || session.len() > 256 {
|
||||
return Err(Error::InvalidSource);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(counts: &Shared, limits: Limits, session: &str) -> Result<Lease, Error> {
|
||||
session_ok(session)?;
|
||||
let mut c = counts.lock().map_err(|_| Error::Unavailable)?;
|
||||
if c.total >= limits.global
|
||||
|| c.streams.get(session).copied().unwrap_or(0) >= limits.per_session
|
||||
{
|
||||
return Err(Error::Limited);
|
||||
}
|
||||
*c.streams.entry(session.into()).or_default() += 1;
|
||||
c.total += 1;
|
||||
Ok(Lease {
|
||||
counts: counts.clone(),
|
||||
session: session.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn poll(counts: &Shared, limits: Limits, session: &str) -> Result<(), Error> {
|
||||
session_ok(session)?;
|
||||
let now = Instant::now();
|
||||
let mut c = counts.lock().map_err(|_| Error::Unavailable)?;
|
||||
c.polls
|
||||
.retain(|_, at| now.duration_since(*at) < Duration::from_secs(2));
|
||||
if c.polls.contains_key(session) || c.polls.len() >= limits.poll_sessions {
|
||||
return Err(Error::Limited);
|
||||
}
|
||||
c.polls.insert(session.into(), now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut c) = self.counts.lock() {
|
||||
if let Some(n) = c.streams.get_mut(&self.session) {
|
||||
*n -= 1;
|
||||
if *n == 0 {
|
||||
c.streams.remove(&self.session);
|
||||
}
|
||||
c.total -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,848 @@
|
||||
//! The d04 7.4 action routes against the real router: the checks before a send,
|
||||
//! the replies of each outcome and the status route. The fake host records
|
||||
//! every send, so a refused request is shown never to reach the device.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, HeaderMap, Request, StatusCode};
|
||||
use axum::Router;
|
||||
use flare_ui::actions::{
|
||||
ActionSpec, Confirm, Kind, LiveAction, Mode, ParamSpec, Params, Proof, Refusal, Tone,
|
||||
};
|
||||
use flare_ui_axum::actions::{router, ActionHost, ActionRoute, Resolved, Sent, Status};
|
||||
use flare_ui_axum::Error;
|
||||
use http_body_util::BodyExt;
|
||||
use maud::html;
|
||||
use serde_json::Value;
|
||||
use tower::ServiceExt;
|
||||
|
||||
const ID: &str = "0b8c4f7e-2d1a-4c3b-9e8f-5a6b7c8d9e0f";
|
||||
const TARGET: &str = "/system/overview/actions/system.restart";
|
||||
|
||||
/// What the fake device does with a checked action.
|
||||
#[derive(Clone)]
|
||||
enum Device {
|
||||
Done,
|
||||
Accept(&'static str),
|
||||
Refuse(Refusal),
|
||||
}
|
||||
|
||||
struct Host {
|
||||
live: LiveAction,
|
||||
cookie_session: bool,
|
||||
device: Device,
|
||||
status_state: &'static str,
|
||||
sends: Arc<AtomicUsize>,
|
||||
seen: Arc<Mutex<Vec<Params>>>,
|
||||
status_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl ActionHost for Host {
|
||||
fn resolve(
|
||||
&self,
|
||||
_headers: &HeaderMap,
|
||||
route: &ActionRoute,
|
||||
) -> impl Future<Output = Result<Resolved, Error>> + Send {
|
||||
let found =
|
||||
route.section == "system" && route.tab == "overview" && route.name == "system.restart";
|
||||
let answer = if found {
|
||||
Ok(Resolved {
|
||||
live: self.live.clone(),
|
||||
cookie_session: self.cookie_session,
|
||||
})
|
||||
} else {
|
||||
Err(Error::NotFound)
|
||||
};
|
||||
async move { answer }
|
||||
}
|
||||
|
||||
fn send(
|
||||
&self,
|
||||
_headers: &HeaderMap,
|
||||
_live: &LiveAction,
|
||||
params: &Params,
|
||||
) -> impl Future<Output = Result<Sent, Refusal>> + Send {
|
||||
self.sends.fetch_add(1, Ordering::SeqCst);
|
||||
self.seen.lock().unwrap().push(params.clone());
|
||||
let answer = match self.device.clone() {
|
||||
Device::Done => Ok(Sent::Done(html! { p { "Restarted" } })),
|
||||
Device::Accept(id) => Ok(Sent::Accepted(id.to_string())),
|
||||
Device::Refuse(refusal) => Err(refusal),
|
||||
};
|
||||
async move { answer }
|
||||
}
|
||||
|
||||
fn status(
|
||||
&self,
|
||||
_headers: &HeaderMap,
|
||||
_route: &ActionRoute,
|
||||
id: &str,
|
||||
) -> impl Future<Output = Result<Status, Error>> + Send {
|
||||
self.status_calls.fetch_add(1, Ordering::SeqCst);
|
||||
let answer = if id == ID {
|
||||
Ok(Status {
|
||||
id: id.to_string(),
|
||||
state: self.status_state,
|
||||
detail: "done here".into(),
|
||||
})
|
||||
} else {
|
||||
Err(Error::NotFound)
|
||||
};
|
||||
async move { answer }
|
||||
}
|
||||
}
|
||||
|
||||
fn live(confirm: Confirm, proof: Proof, fresh: bool) -> LiveAction {
|
||||
LiveAction {
|
||||
spec: ActionSpec {
|
||||
id: "system.restart".into(),
|
||||
confirm,
|
||||
proof,
|
||||
mode: Mode::Sync,
|
||||
params: Vec::new(),
|
||||
},
|
||||
label: "Restart system".into(),
|
||||
tone: Tone::Danger,
|
||||
target: TARGET.into(),
|
||||
confirm_url: format!("{TARGET}/confirm"),
|
||||
status_url: format!("{TARGET}/status"),
|
||||
back: "/system/overview".into(),
|
||||
proof_path: "/auth/proof".into(),
|
||||
proof_kind: "password".into(),
|
||||
csrf: "tok-live".into(),
|
||||
fresh_proof: fresh,
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
router: Router,
|
||||
sends: Arc<AtomicUsize>,
|
||||
seen: Arc<Mutex<Vec<Params>>>,
|
||||
status_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
fn app(live: LiveAction, cookie_session: bool, device: Device, status_state: &'static str) -> App {
|
||||
let sends = Arc::new(AtomicUsize::new(0));
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let status_calls = Arc::new(AtomicUsize::new(0));
|
||||
let host = Host {
|
||||
live,
|
||||
cookie_session,
|
||||
device,
|
||||
status_state,
|
||||
sends: sends.clone(),
|
||||
seen: seen.clone(),
|
||||
status_calls: status_calls.clone(),
|
||||
};
|
||||
App {
|
||||
router: router(host),
|
||||
sends,
|
||||
seen,
|
||||
status_calls,
|
||||
}
|
||||
}
|
||||
|
||||
async fn call(router: &Router, request: Request<Body>) -> (StatusCode, HeaderMap, String) {
|
||||
let response = router.clone().oneshot(request).await.unwrap();
|
||||
let status = response.status();
|
||||
let headers = response.headers().clone();
|
||||
let bytes = response.into_body().collect().await.unwrap().to_bytes();
|
||||
(status, headers, String::from_utf8(bytes.to_vec()).unwrap())
|
||||
}
|
||||
|
||||
fn post(path: &str, form: &str, htmx: bool) -> Request<Body> {
|
||||
let mut builder = Request::builder()
|
||||
.method("POST")
|
||||
.uri(path)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
|
||||
if htmx {
|
||||
builder = builder.header("hx-request", "true");
|
||||
}
|
||||
builder.body(Body::from(form.to_string())).unwrap()
|
||||
}
|
||||
|
||||
fn get(path: &str) -> Request<Body> {
|
||||
Request::get(path).body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_post_without_the_session_token_is_refused_and_never_sent() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
for form in ["", "csrf=tok-wrong", "csrf=tok-liv"] {
|
||||
let (status, _, body) = call(&app.router, post(TARGET, form, true)).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{form}");
|
||||
assert!(body.contains("role=\"alert\""), "{body}");
|
||||
}
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_checked_post_sends_once_and_redirects_without_script() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, _) = call(&app.router, post(TARGET, "csrf=tok-live", false)).await;
|
||||
assert_eq!(status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
headers.get(header::LOCATION).unwrap().to_str().unwrap(),
|
||||
"/system/overview"
|
||||
);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_htmx_post_gets_the_result_fragment() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, body) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, "<p>Restarted</p>");
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(header::CACHE_CONTROL)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"no-store"
|
||||
);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_wrong_typed_word_is_422_and_redraws_the_control() {
|
||||
let typed = Confirm::Typed("RESTART".into());
|
||||
let app = app(live(typed, Proof::Session, false), true, Device::Done, "ok");
|
||||
let (status, _, body) = call(
|
||||
&app.router,
|
||||
post(TARGET, "csrf=tok-live&confirm_word=rest", true),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(body.contains("name=\"confirm_word\""), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
let (status, _, _) = call(
|
||||
&app.router,
|
||||
post(TARGET, "csrf=tok-live&confirm_word=RESTART", true),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_missing_fresh_proof_is_403_with_the_prompt() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Fresh, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, _, body) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert!(body.contains("action=\"/auth/proof\""), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_console_action_refuses_a_bearer_token() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Console, false),
|
||||
false,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, _, body) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert!(body.contains("cannot run from here"), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn device_refusals_keep_their_status_and_plate() {
|
||||
let cases = [
|
||||
(
|
||||
Refusal::Unavailable,
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"did not answer",
|
||||
),
|
||||
(
|
||||
Refusal::Timeout,
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
"took too long",
|
||||
),
|
||||
];
|
||||
for (refusal, status, words) in cases {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Refuse(refusal),
|
||||
"ok",
|
||||
);
|
||||
let (got, _, body) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(got, status);
|
||||
assert!(body.contains(words), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_async_start_is_202_with_its_status_line() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Accept(ID),
|
||||
"running",
|
||||
);
|
||||
let (status, _, body) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
assert!(body.contains(&format!("data-action-id=\"{ID}\"")), "{body}");
|
||||
assert!(
|
||||
body.contains(&format!("data-status-url=\"{TARGET}/status\"")),
|
||||
"{body}"
|
||||
);
|
||||
// Without script the same start is a redirect to the page.
|
||||
let (status, headers, _) = call(&app.router, post(TARGET, "csrf=tok-live", false)).await;
|
||||
assert_eq!(status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
headers.get(header::LOCATION).unwrap().to_str().unwrap(),
|
||||
"/system/overview"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_host_status_id_that_is_not_safe_is_a_server_error() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Accept("A B"),
|
||||
"running",
|
||||
);
|
||||
let (status, _, _) = call(&app.router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_action_the_host_does_not_resolve_is_not_found() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let other = "/system/overview/actions/other";
|
||||
let (status, _, _) = call(&app.router, post(other, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
let (status, _, _) = call(&app.router, get(&format!("{other}/confirm"))).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_confirm_page_is_served_for_the_no_script_path() {
|
||||
let app = app(
|
||||
live(Confirm::Arm, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, _, body) = call(&app.router, get(&format!("{TARGET}/confirm"))).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(
|
||||
body.contains("data-action-confirm=\"system.restart\""),
|
||||
"{body}"
|
||||
);
|
||||
assert!(body.contains("name=\"csrf\" value=\"tok-live\""), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_status_route_answers_json_and_checks_the_id() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"failed",
|
||||
);
|
||||
let (status, headers, body) = call(&app.router, get(&format!("{TARGET}/status?id={ID}"))).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
headers.get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
|
||||
"application/json"
|
||||
);
|
||||
let value: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(value["id"], ID);
|
||||
assert_eq!(value["state"], "failed");
|
||||
assert_eq!(value["detail"], "done here");
|
||||
|
||||
let (status, _, _) = call(&app.router, get(&format!("{TARGET}/status"))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, _, _) = call(&app.router, get(&format!("{TARGET}/status?id=A%20B"))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let unknown = "0b8c4f7e-2d1a-4c3b-9e8f-5a6b7c8d9e00";
|
||||
let (status, _, _) = call(&app.router, get(&format!("{TARGET}/status?id={unknown}"))).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
|
||||
// A state outside the protocol is a host bug, not a status the page can draw.
|
||||
let odd = app_with_status(live(Confirm::None, Proof::Session, false), "constructor");
|
||||
let (status, _, _) = call(&odd, get(&format!("{TARGET}/status?id={ID}"))).await;
|
||||
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
fn app_with_status(live: LiveAction, status_state: &'static str) -> Router {
|
||||
app(live, true, Device::Done, status_state).router
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_post_runs_an_action_and_the_form_is_bounded() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, _, _) = call(&app.router, get(TARGET)).await;
|
||||
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
|
||||
// An 8 KiB form is read and checked like any other, under the 16 KiB bound (Q9).
|
||||
let fits = format!("csrf=tok-live&confirm_word={}", "a".repeat(8 * 1024));
|
||||
let (status, _, _) = call(&app.router, post(TARGET, &fits, true)).await;
|
||||
assert_ne!(status, StatusCode::PAYLOAD_TOO_LARGE);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
let big = format!("csrf=tok-live&confirm_word={}", "a".repeat(16 * 1024));
|
||||
let (status, _, _) = call(&app.router, post(TARGET, &big, true)).await;
|
||||
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// The profile-install `content_b64` as the Q9 amendment declares it: a str of at most
|
||||
/// 10924 characters, the base64 length of an 8,192-byte profile.
|
||||
fn profile_install() -> LiveAction {
|
||||
let params = vec![ParamSpec {
|
||||
name: "content_b64".into(),
|
||||
kind: Kind::Str {
|
||||
check: None,
|
||||
max_len: Some(10924),
|
||||
allow_empty: None,
|
||||
},
|
||||
}];
|
||||
with_params(live(Confirm::None, Proof::Session, false), params)
|
||||
}
|
||||
|
||||
/// Base64 text of an 8,192-byte profile: 10924 characters that cycle through the
|
||||
/// whole alphabet and end in the one `=` of the padding.
|
||||
fn profile_content() -> String {
|
||||
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut text: String = (0..10923).map(|i| char::from(ALPHABET[i % 64])).collect();
|
||||
text.push('=');
|
||||
text
|
||||
}
|
||||
|
||||
/// A form with one `content_b64` param, percent-encoded as a browser sends it, so
|
||||
/// each `+`, `/` and `=` takes three bytes on the wire.
|
||||
fn profile_form(content: &str) -> String {
|
||||
format!(
|
||||
"csrf=tok-live¶m.content_b64={}",
|
||||
form_urlencoded::byte_serialize(content.as_bytes()).collect::<String>()
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_profile_install_of_10924_characters_fits_the_form_and_the_kind() {
|
||||
// Q9: the 16 KiB form bound takes a whole profile with its token, and the declared
|
||||
// kind accepts 10924 characters and no more.
|
||||
let content = profile_content();
|
||||
let app = app(profile_install(), true, Device::Done, "ok");
|
||||
let (status, _, body) = call(&app.router, post(TARGET, &profile_form(&content), true)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
{
|
||||
let seen = app.seen.lock().unwrap();
|
||||
assert_eq!(
|
||||
seen[0].get("content_b64"),
|
||||
Some(&serde_json::json!(content))
|
||||
);
|
||||
}
|
||||
// One character more is outside the kind and never reaches the device.
|
||||
let longer = format!("{content}A");
|
||||
let (status, _, body) = call(&app.router, post(TARGET, &profile_form(&longer), true)).await;
|
||||
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(body.contains("A value is not allowed"), "{body}");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// A host whose viewer lacks the action's permission (d04 7.5). It never resolves the
|
||||
/// action, so the routes answer the denial and the device is never reached.
|
||||
struct DeniedHost {
|
||||
sends: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl ActionHost for DeniedHost {
|
||||
async fn resolve(&self, _headers: &HeaderMap, _route: &ActionRoute) -> Result<Resolved, Error> {
|
||||
Err(Error::ActionDenied)
|
||||
}
|
||||
|
||||
fn send(
|
||||
&self,
|
||||
_headers: &HeaderMap,
|
||||
_live: &LiveAction,
|
||||
_params: &Params,
|
||||
) -> impl Future<Output = Result<Sent, Refusal>> + Send {
|
||||
self.sends.fetch_add(1, Ordering::SeqCst);
|
||||
async { Ok(Sent::Done(html! { p { "Restarted" } })) }
|
||||
}
|
||||
|
||||
async fn status(
|
||||
&self,
|
||||
_headers: &HeaderMap,
|
||||
_route: &ActionRoute,
|
||||
_id: &str,
|
||||
) -> Result<Status, Error> {
|
||||
Err(Error::ActionDenied)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_denied_action_is_403_with_the_plate_and_no_data() {
|
||||
let sends = Arc::new(AtomicUsize::new(0));
|
||||
let router = router(DeniedHost {
|
||||
sends: sends.clone(),
|
||||
});
|
||||
let (status, headers, body) = call(&router, post(TARGET, "csrf=tok-live", true)).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(headers[header::CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert!(
|
||||
body.contains("You do not have permission for this action."),
|
||||
"{body}"
|
||||
);
|
||||
assert!(!body.contains("Restarted"), "{body}");
|
||||
assert_eq!(sends.load(Ordering::SeqCst), 0);
|
||||
// The confirm page and the status poll are denied the same way.
|
||||
let (status, _, body) = call(&router, get(&format!("{TARGET}/confirm"))).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert!(!body.contains("name=\"confirm_word\""), "{body}");
|
||||
let (status, _, _) = call(&router, get(&format!("{TARGET}/status?id={ID}"))).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
fn with_params(mut live: LiveAction, params: Vec<ParamSpec>) -> LiveAction {
|
||||
live.spec.params = params;
|
||||
live
|
||||
}
|
||||
|
||||
fn trips_and_on() -> Vec<ParamSpec> {
|
||||
vec![
|
||||
ParamSpec {
|
||||
name: "trips".into(),
|
||||
kind: Kind::Int {
|
||||
lo: 0,
|
||||
hi: 65535,
|
||||
step: None,
|
||||
units: None,
|
||||
},
|
||||
},
|
||||
ParamSpec {
|
||||
name: "on".into(),
|
||||
kind: Kind::Bool {},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_declared_param_is_checked_and_sent_with_its_value() {
|
||||
let live = with_params(live(Confirm::None, Proof::Session, false), trips_and_on());
|
||||
let app = app(live, true, Device::Done, "ok");
|
||||
// A bool posts its hidden false before the checkbox true, so the last value wins.
|
||||
let form = "csrf=tok-live¶m.trips=3¶m.on=false¶m.on=true";
|
||||
let (status, headers, _) = call(&app.router, post(TARGET, form, false)).await;
|
||||
assert_eq!(status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(headers.get(header::LOCATION).unwrap(), "/system/overview");
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 1);
|
||||
let seen = app.seen.lock().unwrap();
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert_eq!(seen[0].get("trips"), Some(&serde_json::json!(3)));
|
||||
assert_eq!(seen[0].get("on"), Some(&serde_json::json!(true)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_undeclared_or_out_of_kind_param_is_422_and_never_sent() {
|
||||
let live = with_params(live(Confirm::None, Proof::Session, false), trips_and_on());
|
||||
let app = app(live, true, Device::Done, "ok");
|
||||
for form in [
|
||||
// Outside the declared range.
|
||||
"csrf=tok-live¶m.trips=70000¶m.on=false",
|
||||
// The bool has no value at all.
|
||||
"csrf=tok-live¶m.trips=3",
|
||||
// A param the action does not declare.
|
||||
"csrf=tok-live¶m.trips=3¶m.on=false¶m.extra=1",
|
||||
// A repeated int, which takes exactly one value.
|
||||
"csrf=tok-live¶m.trips=3¶m.trips=4¶m.on=false",
|
||||
// Not an integer.
|
||||
"csrf=tok-live¶m.trips=3.5¶m.on=false",
|
||||
] {
|
||||
let (status, _, body) = call(&app.router, post(TARGET, form, true)).await;
|
||||
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{form}");
|
||||
assert!(body.contains("A value is not allowed"), "{body}");
|
||||
// The refusal draws the control again, so the viewer can retry on the page.
|
||||
assert!(body.contains("name=\"param.trips\""), "{body}");
|
||||
}
|
||||
assert_eq!(app.sends.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_confirm_page_prefills_the_params_it_is_given() {
|
||||
let live = with_params(live(Confirm::Arm, Proof::Session, false), trips_and_on());
|
||||
let app = app(live, true, Device::Done, "ok");
|
||||
let (status, _, body) = call(
|
||||
&app.router,
|
||||
get(&format!("{TARGET}/confirm?param.trips=7¶m.on=true")),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(body.contains("name=\"param.trips\""), "{body}");
|
||||
assert!(body.contains("value=\"7\""), "{body}");
|
||||
assert!(body.contains("checked"), "{body}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_api_client_gets_the_async_start_as_json_with_its_id() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Accept(ID),
|
||||
"running",
|
||||
);
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri(TARGET)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.body(Body::from("csrf=tok-live"))
|
||||
.unwrap();
|
||||
let (status, headers, body) = call(&app.router, request).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
assert_eq!(
|
||||
headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
"application/json"
|
||||
);
|
||||
let answer: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(answer, serde_json::json!({ "id": ID }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_htmx_client_that_accepts_json_gets_the_pending_line() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Accept(ID),
|
||||
"running",
|
||||
);
|
||||
// The htmx header wins over Accept: the start is the pending line, not the JSON id.
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri(TARGET)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header("hx-request", "true")
|
||||
.body(Body::from("csrf=tok-live"))
|
||||
.unwrap();
|
||||
let (status, headers, body) = call(&app.router, request).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
assert_eq!(
|
||||
headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
"text/html; charset=utf-8"
|
||||
);
|
||||
assert!(serde_json::from_str::<Value>(&body).is_err(), "{body}");
|
||||
assert!(body.contains(&format!("data-action-id=\"{ID}\"")), "{body}");
|
||||
assert!(
|
||||
body.contains(&format!("data-status-url=\"{TARGET}/status\"")),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_resolves_the_viewer_before_the_host_answers() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"running",
|
||||
);
|
||||
// An action this page does not have is refused before the host reads its state.
|
||||
let (status, _, _) = call(
|
||||
&app.router,
|
||||
get(&format!(
|
||||
"/system/other/actions/system.restart/status?id={ID}"
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.status_calls.load(Ordering::SeqCst), 0);
|
||||
let (status, _, _) = call(&app.router, get(&format!("{TARGET}/status?id={ID}"))).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(app.status_calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// A POST from an API client: it accepts JSON and sends no htmx header.
|
||||
fn post_json(path: &str, form: &str) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(path)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.body(Body::from(form.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Asserts a problem+json answer with this status and problem type (d05 11.4).
|
||||
fn assert_problem(
|
||||
status: StatusCode,
|
||||
headers: &HeaderMap,
|
||||
body: &str,
|
||||
want: StatusCode,
|
||||
kind: &str,
|
||||
) {
|
||||
assert_eq!(status, want, "{body}");
|
||||
assert_eq!(
|
||||
headers[header::CONTENT_TYPE],
|
||||
"application/problem+json",
|
||||
"{body}"
|
||||
);
|
||||
let problem: Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(
|
||||
problem,
|
||||
serde_json::json!({ "type": kind, "status": want.as_u16() })
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_api_client_gets_each_refusal_as_problem_json() {
|
||||
// d05 names csrf and proof_required; the other refusals answer their own names.
|
||||
let csrf = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, body) = call(&csrf.router, post_json(TARGET, "csrf=wrong")).await;
|
||||
assert_problem(status, &headers, &body, StatusCode::FORBIDDEN, "csrf");
|
||||
assert_eq!(csrf.sends.load(Ordering::SeqCst), 0);
|
||||
|
||||
let proof = app(
|
||||
live(Confirm::None, Proof::Fresh, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, body) = call(&proof.router, post_json(TARGET, "csrf=tok-live")).await;
|
||||
assert_problem(
|
||||
status,
|
||||
&headers,
|
||||
&body,
|
||||
StatusCode::FORBIDDEN,
|
||||
"proof_required",
|
||||
);
|
||||
assert_eq!(proof.sends.load(Ordering::SeqCst), 0);
|
||||
|
||||
let word = app(
|
||||
live(Confirm::Typed("restart".into()), Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, body) = call(&word.router, post_json(TARGET, "csrf=tok-live")).await;
|
||||
assert_problem(
|
||||
status,
|
||||
&headers,
|
||||
&body,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"confirm_word",
|
||||
);
|
||||
assert_eq!(word.sends.load(Ordering::SeqCst), 0);
|
||||
|
||||
// A device refusal is reached, so the send counter moves once.
|
||||
let device = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Refuse(Refusal::Unavailable),
|
||||
"ok",
|
||||
);
|
||||
let (status, headers, body) = call(&device.router, post_json(TARGET, "csrf=tok-live")).await;
|
||||
assert_problem(
|
||||
status,
|
||||
&headers,
|
||||
&body,
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"unavailable",
|
||||
);
|
||||
assert_eq!(device.sends.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_api_client_gets_a_denied_action_as_problem_json() {
|
||||
let sends = Arc::new(AtomicUsize::new(0));
|
||||
let router = router(DeniedHost {
|
||||
sends: sends.clone(),
|
||||
});
|
||||
let (status, headers, body) = call(&router, post_json(TARGET, "csrf=tok-live")).await;
|
||||
assert_problem(status, &headers, &body, StatusCode::FORBIDDEN, "forbidden");
|
||||
assert!(!body.contains("Restarted"), "{body}");
|
||||
assert_eq!(sends.load(Ordering::SeqCst), 0);
|
||||
// The status poll of a denied action is problem+json for the same client.
|
||||
let request = Request::builder()
|
||||
.method("GET")
|
||||
.uri(format!("{TARGET}/status?id={ID}"))
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let (status, headers, body) = call(&router, request).await;
|
||||
assert_problem(status, &headers, &body, StatusCode::FORBIDDEN, "forbidden");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refusal_for_an_htmx_or_browser_client_stays_the_plate() {
|
||||
let app = app(
|
||||
live(Confirm::None, Proof::Session, false),
|
||||
true,
|
||||
Device::Done,
|
||||
"ok",
|
||||
);
|
||||
// An htmx request that also accepts JSON still gets the HTML plate.
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri(TARGET)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header("hx-request", "true")
|
||||
.body(Body::from("csrf=wrong"))
|
||||
.unwrap();
|
||||
let (status, headers, body) = call(&app.router, request).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(headers[header::CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert!(body.contains("The page has expired"), "{body}");
|
||||
// A browser form post asks for HTML and keeps the plate.
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri(TARGET)
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header(header::ACCEPT, "text/html")
|
||||
.body(Body::from("csrf=wrong"))
|
||||
.unwrap();
|
||||
let (status, headers, body) = call(&app.router, request).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(headers[header::CONTENT_TYPE], "text/html; charset=utf-8");
|
||||
assert!(body.contains("The page has expired"), "{body}");
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
id: 101
|
||||
event: r
|
||||
data: <span id="r-temperature" hx-swap-oob="outerHTML">23</span>
|
||||
|
||||
+1007
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,122 @@
|
||||
//! Browser fixtures encoded by the maintained event transport.
|
||||
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::{HeaderMap, Request, StatusCode, Uri};
|
||||
use axum::Router;
|
||||
use flare_ui_axum::{
|
||||
Batch, Error, Event, HtmlKind, JsonKind, Limits, Page, Source, Transport, MAX_BYTES,
|
||||
};
|
||||
use maud::{html, PreEscaped};
|
||||
use serde_json::json;
|
||||
use tokio::sync::watch;
|
||||
use tower::ServiceExt;
|
||||
|
||||
fn events() -> Vec<Event> {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let reading =
|
||||
std::fs::read_to_string(root.join("../flare-ui/tests/golden/page-oob.html")).unwrap();
|
||||
vec![
|
||||
Event::html(
|
||||
43,
|
||||
HtmlKind::Reading,
|
||||
PreEscaped(reading.trim_end().to_owned()),
|
||||
),
|
||||
Event::html(
|
||||
44,
|
||||
HtmlKind::State,
|
||||
html! {
|
||||
span id="st-link" data-live data-live-event="st" hx-swap-oob="outerHTML" { "Link up" }
|
||||
},
|
||||
),
|
||||
Event::html(
|
||||
45,
|
||||
HtmlKind::Approvals,
|
||||
html! {
|
||||
span id="ap-count" data-live data-live-event="ap" hx-swap-oob="outerHTML" { "3 approvals" }
|
||||
},
|
||||
),
|
||||
Event::json(
|
||||
46,
|
||||
JsonKind::Action,
|
||||
json!({"id":"job","state":"ok","detail":"<script>text</script>"}),
|
||||
),
|
||||
Event::json(
|
||||
47,
|
||||
JsonKind::Series,
|
||||
json!({"id":"chart","key":"temp","p":[1000,27.5]}),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_browser_frames_match_transport() {
|
||||
let mut wire = Vec::new();
|
||||
for event in events() {
|
||||
wire.extend_from_slice(&event.encode().unwrap());
|
||||
}
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let file = root.join("../flare-ui/tests/golden/page-stream.sse");
|
||||
if std::env::var_os("UPDATE_GOLDEN").is_some() {
|
||||
std::fs::write(file, wire).unwrap();
|
||||
} else {
|
||||
assert_eq!(std::fs::read(file).unwrap(), wire);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BrowserPage;
|
||||
|
||||
impl Source for BrowserPage {
|
||||
type Page = Self;
|
||||
|
||||
async fn open(&self, _: &Uri, _: &HeaderMap) -> Result<Self, Error> {
|
||||
Ok(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Page for BrowserPage {
|
||||
fn session(&self) -> &str {
|
||||
"browser-fixture"
|
||||
}
|
||||
|
||||
fn subscribe(&self) -> watch::Receiver<u64> {
|
||||
watch::channel(47).1
|
||||
}
|
||||
|
||||
async fn snapshot(&self, since: u64) -> Result<Batch, Error> {
|
||||
assert_eq!(since, 42);
|
||||
Ok(Batch::Changes {
|
||||
seq: 47,
|
||||
events: events(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn page_browser_poll_matches_transport() {
|
||||
let transport = Transport::new(BrowserPage, Limits::default()).unwrap();
|
||||
let response = Router::new()
|
||||
.route("/status/events", transport.events())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/status/events?mode=poll&seq=42")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-seq"], "47");
|
||||
assert_eq!(
|
||||
response.headers()["content-type"],
|
||||
"text/html; charset=utf-8"
|
||||
);
|
||||
let body = to_bytes(response.into_body(), MAX_BYTES).await.unwrap();
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let file = root.join("../flare-ui/tests/golden/page-poll.html");
|
||||
if std::env::var_os("UPDATE_GOLDEN").is_some() {
|
||||
std::fs::write(file, &body).unwrap();
|
||||
} else {
|
||||
assert_eq!(std::fs::read(file).unwrap(), body);
|
||||
}
|
||||
}
|
||||
@@ -18,3 +18,11 @@ criterion = { version = "0.5", default-features = false }
|
||||
[[bench]]
|
||||
name = "chart"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "page"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "fields"
|
||||
harness = false
|
||||
|
||||
+117
-2
@@ -1,4 +1,21 @@
|
||||
/* Shared component styles. Every value comes from tokens.css. */
|
||||
/* Shared shell and components. Load tokens.css and theme.css first. */
|
||||
:root {
|
||||
background: var(--app-bg);
|
||||
color: var(--app-text);
|
||||
font-family: var(--bf-font-body);
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--app-bg);
|
||||
color: var(--app-text);
|
||||
}
|
||||
a {
|
||||
color: var(--app-link);
|
||||
}
|
||||
a:focus-visible {
|
||||
outline: 2px solid var(--app-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.bf-btn {
|
||||
display: inline-block;
|
||||
padding: var(--bf-space-2) var(--bf-space-4);
|
||||
@@ -31,14 +48,24 @@
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.bf-stale {
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
.bf-stale canvas {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.bf-card[data-readonly] .bf-input:disabled {
|
||||
color: var(--app-text);
|
||||
-webkit-text-fill-color: var(--app-text);
|
||||
opacity: 1;
|
||||
}
|
||||
.bf-shell {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.bf-sidebar {
|
||||
padding: var(--bf-space-4);
|
||||
background: var(--app-surface);
|
||||
border-inline-end: 1px solid var(--app-border);
|
||||
}
|
||||
.bf-nav-section {
|
||||
margin: 0 0 var(--bf-space-4);
|
||||
@@ -49,13 +76,19 @@
|
||||
.bf-nav-link {
|
||||
display: block;
|
||||
padding: var(--bf-space-1) var(--bf-space-2);
|
||||
color: var(--app-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.bf-nav-link:hover {
|
||||
background: var(--app-row-hover);
|
||||
}
|
||||
.bf-nav-active {
|
||||
font-weight: 700;
|
||||
background: var(--app-surface-alt);
|
||||
}
|
||||
.bf-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: var(--bf-space-4);
|
||||
}
|
||||
.bf-tabs {
|
||||
@@ -78,6 +111,7 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
.bf-input {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: var(--bf-space-2);
|
||||
}
|
||||
@@ -96,6 +130,8 @@
|
||||
}
|
||||
.bf-kv {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--bf-space-2);
|
||||
padding: var(--bf-space-1) 0;
|
||||
@@ -103,16 +139,29 @@
|
||||
.bf-kv-label {
|
||||
display: inline-block;
|
||||
}
|
||||
.bf-kv > .bf-kv-label,
|
||||
.bf-gauge > .bf-kv-label {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.bf-kv-value {
|
||||
flex-shrink: 0;
|
||||
max-width: 100%;
|
||||
margin-inline-start: auto;
|
||||
overflow-wrap: anywhere;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.bf-gauge {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--bf-space-2);
|
||||
}
|
||||
.bf-gauge-bar {
|
||||
flex: 1;
|
||||
flex: 1 1 6rem;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
.bf-hero {
|
||||
display: flex;
|
||||
@@ -159,6 +208,15 @@
|
||||
gap: var(--bf-space-1) var(--bf-space-4);
|
||||
margin: 0;
|
||||
}
|
||||
.bf-plate-message {
|
||||
margin: 0 0 var(--bf-space-2);
|
||||
padding: var(--bf-space-2) var(--bf-space-3);
|
||||
border: 1px solid var(--bf-border-subtle);
|
||||
}
|
||||
.bf-btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.bf-btn-danger {
|
||||
background: var(--bf-color-danger);
|
||||
color: #fff;
|
||||
@@ -170,6 +228,14 @@
|
||||
.bf-action-confirm {
|
||||
margin: 0 0 var(--bf-space-1);
|
||||
}
|
||||
.bf-action-field {
|
||||
display: block;
|
||||
margin: 0 0 var(--bf-space-1);
|
||||
}
|
||||
.bf-action-proof {
|
||||
display: block;
|
||||
margin: 0 0 var(--bf-space-2);
|
||||
}
|
||||
.bf-approvals {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
@@ -182,3 +248,52 @@
|
||||
align-items: center;
|
||||
padding: var(--bf-space-2) 0;
|
||||
}
|
||||
.bf-table-wrap {
|
||||
margin: var(--bf-space-2) 0;
|
||||
}
|
||||
.bf-table-scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.bf-table-tools {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--bf-space-2) var(--bf-space-3);
|
||||
align-items: center;
|
||||
margin-bottom: var(--bf-space-2);
|
||||
}
|
||||
.bf-table-count {
|
||||
margin: 0;
|
||||
}
|
||||
.bf-table-per {
|
||||
display: flex;
|
||||
gap: var(--bf-space-1);
|
||||
}
|
||||
.bf-table-filter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--bf-space-2);
|
||||
align-items: center;
|
||||
}
|
||||
.bf-table-pager {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--bf-space-3);
|
||||
align-items: center;
|
||||
margin-top: var(--bf-space-2);
|
||||
}
|
||||
.bf-table th {
|
||||
position: relative;
|
||||
text-align: left;
|
||||
}
|
||||
.bf-col-handle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
.bf-col-handle:focus-visible {
|
||||
outline: 2px solid var(--app-focus-ring);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
/* flare-ui live actions (d04 7.4, flare-ui#135). Four behaviours sit on top of
|
||||
* the forms the renderer draws. Each one fails safe without script:
|
||||
* arm A form[data-confirm="arm"] arms on its first press for four seconds
|
||||
* and sends nothing. A second press inside the window posts to
|
||||
* data-target with the CSRF token. Without script the form opens the
|
||||
* confirm page instead.
|
||||
* typed A form[data-confirm="typed"] keeps its submit disabled until the
|
||||
* typed word equals data-word. The server checks the word as well.
|
||||
* The gate is set again after each htmx swap, from the word the
|
||||
* field holds, so a form drawn by a swap starts gated.
|
||||
* async A status element [data-action-id] shows the act event with the same
|
||||
* id (flare:action) and polls its data-status-url every two seconds
|
||||
* until the state is terminal. A poll with no usable answer is kept
|
||||
* going; after 30 in a row the status reads unknown. Text is set,
|
||||
* never markup.
|
||||
* swap A failed htmx reply from an action form is swapped in, so the
|
||||
* refusal plate replaces the control. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory(root);
|
||||
else root.FlareActions = factory(root);
|
||||
})(typeof self !== "undefined" ? self : this, function (root) {
|
||||
"use strict";
|
||||
var ARM_MS = 4000;
|
||||
var POLL_MS = 2000;
|
||||
var ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
var STATES = { running: "Running", ok: "Done", failed: "Failed" };
|
||||
var TERMINAL = { ok: true, failed: true };
|
||||
var MAX_FAILURES = 30;
|
||||
var UNKNOWN_TEXT = "Status unknown: reload the page to check";
|
||||
var armed = new WeakMap();
|
||||
var pending = new WeakMap();
|
||||
var settled = new WeakSet();
|
||||
var failures = new WeakMap();
|
||||
|
||||
function attr(el, name) {
|
||||
return el && typeof el.getAttribute === "function" ? el.getAttribute(name) : null;
|
||||
}
|
||||
|
||||
function submitButton(form) {
|
||||
return form && typeof form.querySelector === "function"
|
||||
? form.querySelector('button[type="submit"]')
|
||||
: null;
|
||||
}
|
||||
|
||||
function goodId(id) {
|
||||
return typeof id === "string" && ID_RE.test(id);
|
||||
}
|
||||
|
||||
function preventDefault(evt) {
|
||||
if (evt && typeof evt.preventDefault === "function") evt.preventDefault();
|
||||
}
|
||||
|
||||
/* The first press shows the armed label and starts the window. */
|
||||
function arm(form, timers) {
|
||||
var button = submitButton(form);
|
||||
if (!button || attr(form, "data-armed") === "1") return;
|
||||
form.setAttribute("data-armed", "1");
|
||||
form.setAttribute("data-idle-text", button.textContent);
|
||||
button.textContent = attr(form, "data-armed-text") || button.textContent;
|
||||
armed.set(form, timers.setTimeout(function () { disarm(form, timers); }, ARM_MS));
|
||||
}
|
||||
|
||||
/* Ends the window and restores the idle label. Safe to call twice. */
|
||||
function disarm(form, timers) {
|
||||
var handle = armed.get(form);
|
||||
if (handle !== undefined) {
|
||||
timers.clearTimeout(handle);
|
||||
armed.delete(form);
|
||||
}
|
||||
var button = submitButton(form);
|
||||
var idle = attr(form, "data-idle-text");
|
||||
if (button && idle !== null) button.textContent = idle;
|
||||
form.removeAttribute("data-armed");
|
||||
form.removeAttribute("data-idle-text");
|
||||
}
|
||||
|
||||
/* Turns the armed GET form into the POST of the action, with its token. */
|
||||
function post(form, doc) {
|
||||
var target = attr(form, "data-target");
|
||||
if (!target || target.charAt(0) !== "/" || target.charAt(1) === "/") return false;
|
||||
var input = doc.createElement("input");
|
||||
input.setAttribute("type", "hidden");
|
||||
input.setAttribute("name", "csrf");
|
||||
input.setAttribute("value", attr(form, "data-csrf") || "");
|
||||
form.setAttribute("method", "post");
|
||||
form.setAttribute("action", target);
|
||||
form.appendChild(input);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Capture-phase submit handler. Returns true when the browser may send it. */
|
||||
function onSubmit(evt, doc, timers) {
|
||||
var form = evt && evt.target;
|
||||
if (attr(form, "data-confirm") !== "arm") return true;
|
||||
if (attr(form, "data-armed") !== "1") {
|
||||
preventDefault(evt);
|
||||
arm(form, timers);
|
||||
return false;
|
||||
}
|
||||
disarm(form, timers);
|
||||
if (!post(form, doc)) {
|
||||
preventDefault(evt);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function gate(form, value) {
|
||||
var button = submitButton(form);
|
||||
if (button) button.disabled = value !== attr(form, "data-word");
|
||||
}
|
||||
|
||||
/* The word field of a typed form, or null. */
|
||||
function wordField(form) {
|
||||
return form && typeof form.querySelector === "function"
|
||||
? form.querySelector('input[name="confirm_word"]')
|
||||
: null;
|
||||
}
|
||||
|
||||
/* Gates every typed form on the word its field holds now. Running it again
|
||||
* keeps a typed word, so it is safe after every htmx swap. */
|
||||
function initTyped(doc) {
|
||||
var forms = doc.querySelectorAll('form[data-confirm="typed"]');
|
||||
for (var i = 0; i < forms.length; i++) {
|
||||
var field = wordField(forms[i]);
|
||||
gate(forms[i], field ? field.value : "");
|
||||
}
|
||||
}
|
||||
|
||||
function onInput(evt) {
|
||||
var input = evt && evt.target;
|
||||
if (attr(input, "name") !== "confirm_word" || !input.form) return;
|
||||
if (attr(input.form, "data-confirm") === "typed") gate(input.form, input.value);
|
||||
}
|
||||
|
||||
function statusElement(doc, id) {
|
||||
if (!goodId(id) || typeof doc.querySelector !== "function") return null;
|
||||
return doc.querySelector('[data-action-id="' + id + '"]');
|
||||
}
|
||||
|
||||
function stop(el, timers) {
|
||||
var handle = pending.get(el);
|
||||
if (handle !== undefined) {
|
||||
timers.clearTimeout(handle);
|
||||
pending.delete(el);
|
||||
}
|
||||
}
|
||||
|
||||
/* Shows one state as text. Unknown states are ignored. */
|
||||
function show(el, state, detail, timers) {
|
||||
if (!el || !Object.prototype.hasOwnProperty.call(STATES, state)) return false;
|
||||
var text = STATES[state];
|
||||
if (state === "failed" && detail) text += ": " + String(detail);
|
||||
el.textContent = text;
|
||||
if (TERMINAL[state]) {
|
||||
settled.add(el);
|
||||
stop(el, timers);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The act event of an async action, delivered by the page transport. */
|
||||
function onAct(evt, doc, timers) {
|
||||
var detail = evt && evt.detail;
|
||||
if (!detail || !goodId(detail.id)) return;
|
||||
show(statusElement(doc, detail.id), detail.state, detail.detail, timers);
|
||||
}
|
||||
|
||||
function schedule(el, timers, fetchFn) {
|
||||
if (settled.has(el) || pending.has(el)) return;
|
||||
pending.set(el, timers.setTimeout(function () { tick(el, timers, fetchFn); }, POLL_MS));
|
||||
}
|
||||
|
||||
/* A poll with no usable answer: a non-OK reply, a rejected or throwing fetch,
|
||||
* a body that is not JSON, or a reply for another id. The poll goes on, up to
|
||||
* MAX_FAILURES in a row. Then the status reads unknown and polling stops, so
|
||||
* a page never shows Running with no poll left to change it. */
|
||||
function fail(el, timers, fetchFn) {
|
||||
var count = (failures.get(el) || 0) + 1;
|
||||
if (count < MAX_FAILURES) {
|
||||
failures.set(el, count);
|
||||
schedule(el, timers, fetchFn);
|
||||
return;
|
||||
}
|
||||
failures.delete(el);
|
||||
el.textContent = UNKNOWN_TEXT;
|
||||
settled.add(el);
|
||||
stop(el, timers);
|
||||
}
|
||||
|
||||
/* One status poll. Any answer usable for this id clears the failure count. */
|
||||
function tick(el, timers, fetchFn) {
|
||||
pending.delete(el);
|
||||
if (settled.has(el)) return;
|
||||
var url = attr(el, "data-status-url");
|
||||
var id = attr(el, "data-action-id");
|
||||
var reply;
|
||||
try {
|
||||
reply = Promise.resolve(fetchFn(url + "?id=" + encodeURIComponent(id), {
|
||||
credentials: "same-origin",
|
||||
headers: { Accept: "application/json" }
|
||||
}));
|
||||
} catch (err) {
|
||||
reply = Promise.reject(err);
|
||||
}
|
||||
reply.then(function (res) {
|
||||
return res && res.ok ? res.json() : null;
|
||||
}).then(function (body) {
|
||||
if (!body || body.id !== id || !Object.prototype.hasOwnProperty.call(STATES, body.state)) {
|
||||
fail(el, timers, fetchFn);
|
||||
return;
|
||||
}
|
||||
failures.delete(el);
|
||||
show(el, body.state, body.detail, timers);
|
||||
schedule(el, timers, fetchFn);
|
||||
}, function () {
|
||||
fail(el, timers, fetchFn);
|
||||
});
|
||||
}
|
||||
|
||||
/* Polls every pending status element that is not settled yet. */
|
||||
function start(doc, timers, fetchFn) {
|
||||
if (typeof fetchFn !== "function") return;
|
||||
var els = doc.querySelectorAll("[data-action-id][data-status-url]");
|
||||
for (var i = 0; i < els.length; i++) schedule(els[i], timers, fetchFn);
|
||||
}
|
||||
|
||||
/* htmx answers a refused action with 4xx or 5xx. Swap that reply in. */
|
||||
function onBeforeSwap(evt) {
|
||||
var detail = evt && evt.detail;
|
||||
var elt = detail && detail.elt;
|
||||
if (!elt || attr(elt, "data-action") === null) return;
|
||||
var status = detail.xhr && detail.xhr.status;
|
||||
if (status >= 400 && status < 600) {
|
||||
detail.shouldSwap = true;
|
||||
detail.isError = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Wires the listeners to a document. Returns a handle that removes them. */
|
||||
function bind(doc, options) {
|
||||
var opts = options || {};
|
||||
var timers = opts.timers || {
|
||||
setTimeout: function (fn, ms) { return root.setTimeout(fn, ms); },
|
||||
clearTimeout: function (handle) { root.clearTimeout(handle); }
|
||||
};
|
||||
var fetchFn = opts.fetch || (typeof root.fetch === "function" ? root.fetch.bind(root) : null);
|
||||
var listeners = [
|
||||
["submit", function (evt) { onSubmit(evt, doc, timers); }, true],
|
||||
["input", onInput, false],
|
||||
["flare:action", function (evt) { onAct(evt, doc, timers); }, false],
|
||||
["htmx:beforeSwap", onBeforeSwap, false],
|
||||
["htmx:afterSettle", function () { initTyped(doc); start(doc, timers, fetchFn); }, false]
|
||||
];
|
||||
for (var i = 0; i < listeners.length; i++) {
|
||||
doc.addEventListener(listeners[i][0], listeners[i][1], listeners[i][2]);
|
||||
}
|
||||
initTyped(doc);
|
||||
start(doc, timers, fetchFn);
|
||||
return {
|
||||
close: function () {
|
||||
for (var j = 0; j < listeners.length; j++) {
|
||||
doc.removeEventListener(listeners[j][0], listeners[j][1], listeners[j][2]);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof document !== "undefined" && document) {
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", function () { bind(document); });
|
||||
else bind(document);
|
||||
}
|
||||
|
||||
return {
|
||||
ARM_MS: ARM_MS,
|
||||
POLL_MS: POLL_MS,
|
||||
MAX_FAILURES: MAX_FAILURES,
|
||||
UNKNOWN_TEXT: UNKNOWN_TEXT,
|
||||
bind: bind,
|
||||
goodId: goodId,
|
||||
initTyped: initTyped,
|
||||
onAct: onAct,
|
||||
onBeforeSwap: onBeforeSwap,
|
||||
onInput: onInput,
|
||||
onSubmit: onSubmit,
|
||||
show: show,
|
||||
start: start
|
||||
};
|
||||
});
|
||||
+70
-10
@@ -1,11 +1,13 @@
|
||||
/* flare-ui page glue (UI-6): one call wires the live stream, stale marker,
|
||||
* chart island, table sort and the htmx CSRF header. Reads two optional
|
||||
* <meta> tags: bf-stream (SSE URL) and bf-csrf (token). No dependencies. */
|
||||
* chart island, table sort, column resize and the htmx CSRF header. Meta tags
|
||||
* declare the stream URL, protocol and CSRF token. A page without a stream
|
||||
* still mounts its chart islands, drawn from the values the server rendered. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory(root);
|
||||
else root.FlareBoot = factory(root);
|
||||
})(typeof self !== "undefined" ? self : this, function (root) {
|
||||
"use strict";
|
||||
var active = new WeakMap();
|
||||
|
||||
function meta(doc, name) {
|
||||
var m = doc.querySelector('meta[name="' + name + '"]');
|
||||
@@ -27,23 +29,81 @@
|
||||
};
|
||||
}
|
||||
|
||||
/* env: { Live, Charts, Islands, doc, loc } injected so tests need no browser. */
|
||||
/* The chart source of a page without a stream: no samples arrive, so each
|
||||
* chart draws the values the server rendered and then stays still. */
|
||||
function staticSource() {
|
||||
return { onChange: function () { return function () {}; }, samples: function () { return []; },
|
||||
chartSamples: function () { return []; }, stale: false, closed: false };
|
||||
}
|
||||
|
||||
/* Local storage, or null where the browser blocks it. */
|
||||
function storageOf(win) {
|
||||
try { return win.localStorage || null; } catch (e) { return null; }
|
||||
}
|
||||
|
||||
/* env: { Live, PageLive, Charts, Islands, doc, loc, storage }. A page declares its
|
||||
* protocol explicitly; a missing page client never falls back to legacy. */
|
||||
function boot(env) {
|
||||
var doc = env.doc;
|
||||
var result = { live: null, csrf: false };
|
||||
if (active.has(doc)) return active.get(doc);
|
||||
var cleanups = [], result = { live: null, csrf: false };
|
||||
active.set(doc, result);
|
||||
result.close = function () {
|
||||
if (active.get(doc) !== result) return;
|
||||
active.delete(doc);
|
||||
if (result.owner) result.owner.close();
|
||||
else if (result.live && result.live.close) result.live.close();
|
||||
for (var stop of cleanups) if (typeof stop === "function") stop();
|
||||
};
|
||||
var token = meta(doc, "bf-csrf");
|
||||
if (token) {
|
||||
doc.body.addEventListener("htmx:configRequest", csrfHeader(token));
|
||||
var csrf = csrfHeader(token);
|
||||
doc.body.addEventListener("htmx:configRequest", csrf);
|
||||
cleanups.push(function () { if (doc.body.removeEventListener) doc.body.removeEventListener("htmx:configRequest", csrf); });
|
||||
result.csrf = true;
|
||||
}
|
||||
if (env.Islands) env.Islands.bindTableSort(doc, env.loc);
|
||||
if (env.Islands && env.Islands.bindColumnResize) {
|
||||
cleanups.push(env.Islands.bindColumnResize(doc, env.storage || null));
|
||||
}
|
||||
var url = meta(doc, "bf-stream");
|
||||
if (url && safeStream(url) && env.Live) {
|
||||
var protocol = meta(doc, "bf-live-protocol");
|
||||
if (url && safeStream(url) && protocol === "page") {
|
||||
var roots = doc.querySelectorAll("[data-page][data-seq]");
|
||||
if (!env.PageLive || !env.PageLive.PageLive || roots.length !== 1) {
|
||||
result.error = "page live client or root unavailable";
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
var workerUrl = meta(doc, "bf-live-worker");
|
||||
if (workerUrl && (!env.PageOwner || !env.PageOwner.Owner)) throw new Error("page owner client unavailable");
|
||||
var page = new env.PageLive.PageLive({ root: roots[0], streamUrl: url,
|
||||
pageUrl: env.loc.pathname + env.loc.search,
|
||||
onAction: function (value) {
|
||||
doc.dispatchEvent(new doc.defaultView.CustomEvent("flare:action", { detail: value }));
|
||||
} });
|
||||
result.live = page;
|
||||
if (env.Charts) cleanups.push(env.Charts.bindCharts(page, doc));
|
||||
if (workerUrl) {
|
||||
result.owner = new env.PageOwner.Owner({ doc: doc, streamUrl: url,
|
||||
pageUrl: env.loc.pathname + env.loc.search, workerUrl: workerUrl }).attach(page);
|
||||
result.owner.start();
|
||||
} else page.start();
|
||||
} catch (error) {
|
||||
if (result.owner) result.owner.close();
|
||||
else if (result.live) result.live.close();
|
||||
result.error = error.message;
|
||||
}
|
||||
} else if (url && safeStream(url) && !protocol && env.Live) {
|
||||
var live = new env.Live.Live(url);
|
||||
env.Live.bindStaleMarker(live, doc);
|
||||
if (env.Charts) env.Charts.bindCharts(live, doc);
|
||||
cleanups.push(env.Live.bindStaleMarker(live, doc));
|
||||
if (env.Charts) cleanups.push(env.Charts.bindCharts(live, doc));
|
||||
live.start();
|
||||
result.live = live;
|
||||
} else if (url && safeStream(url) && protocol && protocol !== "page") {
|
||||
result.error = "unsupported live protocol";
|
||||
} else if (!url && env.Charts && doc.querySelector('[data-island="chart"]')) {
|
||||
cleanups.push(env.Charts.bindCharts(staticSource(), doc));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -51,8 +111,8 @@
|
||||
function auto() {
|
||||
if (typeof document === "undefined") return;
|
||||
boot({
|
||||
doc: document, loc: location,
|
||||
Live: root.FlareLive, Charts: root.FlareChart, Islands: root.FlareIslands
|
||||
doc: document, loc: location, storage: storageOf(root),
|
||||
Live: root.FlareLive, PageLive: root.FlarePageLive, PageOwner: root.FlarePageOwner, Charts: root.FlareChart, Islands: root.FlareIslands
|
||||
});
|
||||
}
|
||||
if (typeof document !== "undefined") {
|
||||
|
||||
+147
-1
@@ -71,9 +71,155 @@
|
||||
}
|
||||
}
|
||||
|
||||
var RESIZE_STEP = 8;
|
||||
var RESIZE_BIG = 32;
|
||||
|
||||
/* Stored widths: a JSON object of column key to width in pixels. Anything
|
||||
* else reads as no widths, and each width is clamped like a drag. */
|
||||
function parseWidths(text) {
|
||||
var out = {}, data = null;
|
||||
try { data = JSON.parse(text); } catch (e) { return out; }
|
||||
if (!data || typeof data !== "object" || Array.isArray(data)) return out;
|
||||
Object.keys(data).forEach(function (name) {
|
||||
if (/^[A-Za-z0-9_.-]{1,64}$/.test(name) && typeof data[name] === "number" && isFinite(data[name])) {
|
||||
out[name] = clampWidth(data[name]);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Width after a pointer drag of dx pixels from the start width. */
|
||||
function dragWidth(start, dx) {
|
||||
return clampWidth(Number(start) + Number(dx));
|
||||
}
|
||||
|
||||
/* Width after an arrow key: left and right move one step, shift moves four.
|
||||
* Any other key leaves the width alone (null). */
|
||||
function keyWidth(current, key, shift) {
|
||||
var step = shift ? RESIZE_BIG : RESIZE_STEP;
|
||||
if (key === "ArrowLeft" || key === "ArrowDown") return clampWidth(Number(current) - step);
|
||||
if (key === "ArrowRight" || key === "ArrowUp") return clampWidth(Number(current) + step);
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Local storage key of a table's widths, bf.tbl.<table id>. */
|
||||
function storageKey(tableId) {
|
||||
return "bf.tbl." + tableId;
|
||||
}
|
||||
|
||||
/* Storage is optional: a missing, blocked or full store means no kept widths. */
|
||||
function readWidths(storage, key) {
|
||||
if (!storage) return {};
|
||||
try { return parseWidths(storage.getItem(key)); } catch (e) { return {}; }
|
||||
}
|
||||
|
||||
function writeWidths(storage, key, widths) {
|
||||
if (!storage) return;
|
||||
try { storage.setItem(key, JSON.stringify(widths)); } catch (e) { /* not kept */ }
|
||||
}
|
||||
|
||||
/* One resize handle on a header's right edge. Returns a function that removes
|
||||
* the handle again. Widths reach the table only through style.width (CSSOM). */
|
||||
function addHandle(doc, th, col, name, key, storage, widths) {
|
||||
var handle = doc.createElement("span");
|
||||
handle.className = "bf-col-handle";
|
||||
handle.setAttribute("role", "separator");
|
||||
handle.setAttribute("aria-orientation", "vertical");
|
||||
handle.setAttribute("aria-label", "Resize column " + String(th.textContent || name));
|
||||
handle.setAttribute("tabindex", "0");
|
||||
th.appendChild(handle);
|
||||
var drag = null;
|
||||
function current() {
|
||||
var width = parseFloat(col.style.width);
|
||||
if (isFinite(width)) return width;
|
||||
return th.getBoundingClientRect ? th.getBoundingClientRect().width : MIN_COL;
|
||||
}
|
||||
function apply(width) {
|
||||
col.style.width = width + "px";
|
||||
widths[name] = width;
|
||||
}
|
||||
function save() { writeWidths(storage, key, widths); }
|
||||
function reset() {
|
||||
col.style.width = "";
|
||||
delete widths[name];
|
||||
save();
|
||||
}
|
||||
function onDown(ev) {
|
||||
if (ev.button !== undefined && ev.button !== 0) return;
|
||||
ev.preventDefault();
|
||||
drag = { x: ev.clientX, w: current() };
|
||||
if (handle.setPointerCapture) handle.setPointerCapture(ev.pointerId);
|
||||
}
|
||||
function onMove(ev) {
|
||||
if (drag) apply(dragWidth(drag.w, ev.clientX - drag.x));
|
||||
}
|
||||
function onUp() {
|
||||
if (drag) save();
|
||||
drag = null;
|
||||
}
|
||||
function onDouble(ev) {
|
||||
ev.preventDefault();
|
||||
reset();
|
||||
}
|
||||
function onKey(ev) {
|
||||
if (ev.key === "Home") {
|
||||
ev.preventDefault();
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
var next = keyWidth(current(), ev.key, ev.shiftKey);
|
||||
if (next === null) return;
|
||||
ev.preventDefault();
|
||||
apply(next);
|
||||
save();
|
||||
}
|
||||
handle.addEventListener("pointerdown", onDown);
|
||||
handle.addEventListener("pointermove", onMove);
|
||||
handle.addEventListener("pointerup", onUp);
|
||||
handle.addEventListener("pointercancel", onUp);
|
||||
handle.addEventListener("dblclick", onDouble);
|
||||
handle.addEventListener("keydown", onKey);
|
||||
return function () {
|
||||
if (handle.parentNode) handle.parentNode.removeChild(handle);
|
||||
};
|
||||
}
|
||||
|
||||
/* Column resize for every table that names its id (d04 9.3). Stored widths
|
||||
* apply on bind. The binder runs on load and after each htmx swap, so a
|
||||
* table that htmx replaced gets its handles again. Returns the unbinder. */
|
||||
function bindColumnResize(doc, storage) {
|
||||
var removers = [];
|
||||
function bindTable(table) {
|
||||
var id = table.getAttribute("data-resize");
|
||||
var cols = table.querySelectorAll("colgroup col[data-col]");
|
||||
var heads = table.querySelectorAll("thead th");
|
||||
if (!id || !cols.length || cols.length !== heads.length) return;
|
||||
var key = storageKey(id), widths = readWidths(storage, key);
|
||||
for (var i = 0; i < cols.length; i++) {
|
||||
var name = cols[i].getAttribute("data-col");
|
||||
if (Object.prototype.hasOwnProperty.call(widths, name)) cols[i].style.width = widths[name] + "px";
|
||||
if (heads[i].querySelector(".bf-col-handle")) continue;
|
||||
removers.push(addHandle(doc, heads[i], cols[i], name, key, storage, widths));
|
||||
}
|
||||
}
|
||||
function scan() {
|
||||
var tables = doc.querySelectorAll("table[data-resize]");
|
||||
for (var t = 0; t < tables.length; t++) bindTable(tables[t]);
|
||||
}
|
||||
scan();
|
||||
doc.addEventListener("htmx:afterSwap", scan);
|
||||
return function () {
|
||||
doc.removeEventListener("htmx:afterSwap", scan);
|
||||
removers.forEach(function (remove) { remove(); });
|
||||
removers = [];
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
parseSort: parseSort, nextSortQuery: nextSortQuery, compareCells: compareCells,
|
||||
sortRows: sortRows, clampWidth: clampWidth, bindTableSort: bindTableSort,
|
||||
MIN_COL: MIN_COL, MAX_COL: MAX_COL
|
||||
parseWidths: parseWidths, dragWidth: dragWidth, keyWidth: keyWidth,
|
||||
storageKey: storageKey, bindColumnResize: bindColumnResize,
|
||||
MIN_COL: MIN_COL, MAX_COL: MAX_COL, RESIZE_STEP: RESIZE_STEP, RESIZE_BIG: RESIZE_BIG
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
/* Named page events over one bounded, cancellable fetch stream. The parser
|
||||
* observes comment heartbeats; HTML application accepts read-only nodes. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory();
|
||||
else root.FlarePageLive = factory();
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
|
||||
var MAX_BYTES = 64 * 1024, MAX_NODES = 2048, MAX_TARGETS = 256;
|
||||
var MAX_SEQ = Number.MAX_SAFE_INTEGER, QUIET_MS = 20000, RELOAD_MS = 10000, POLL_MS = 3000;
|
||||
var owners = new WeakMap();
|
||||
|
||||
function invalid(message) {
|
||||
var error = new Error(message); error.protocol = true; return error;
|
||||
}
|
||||
|
||||
function sequence(value) {
|
||||
if (typeof value !== "string" || !/^[0-9]{1,16}$/.test(value)) throw invalid("invalid sequence");
|
||||
var number = Number(value);
|
||||
if (!Number.isSafeInteger(number) || number < 0 || number > MAX_SEQ) throw invalid("invalid sequence");
|
||||
return number;
|
||||
}
|
||||
|
||||
/* Bytes are bounded before decoding. A line may span arbitrary reads,
|
||||
* including inside UTF-8 characters or between the CR and LF of CRLF. */
|
||||
function Parser(consume) {
|
||||
this.consume = consume;
|
||||
this.line = new Uint8Array(MAX_BYTES);
|
||||
this.length = 0; this.bytes = 0; this.cr = false; this.first = true; this.stopped = false;
|
||||
this.decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||
this.reset();
|
||||
}
|
||||
Parser.prototype.reset = function () {
|
||||
this.event = ""; this.id = null; this.data = []; this.hasData = false;
|
||||
this.retry = null; this.heartbeat = false;
|
||||
};
|
||||
Parser.prototype.endLine = function () {
|
||||
var line;
|
||||
try { line = this.decoder.decode(this.line.subarray(0, this.length)); }
|
||||
catch (_) { throw invalid("invalid UTF-8"); }
|
||||
this.length = 0;
|
||||
if (this.first) { this.first = false; if (line.charCodeAt(0) === 0xfeff) line = line.slice(1); }
|
||||
if (!line) {
|
||||
var frame = { event: this.event, id: this.id, data: this.data.join("\n"),
|
||||
hasData: this.hasData, retry: this.retry, heartbeat: this.heartbeat };
|
||||
this.reset(); this.bytes = 0;
|
||||
if (this.consume(frame) === false) this.stopped = true;
|
||||
return;
|
||||
}
|
||||
if (line.charAt(0) === ":") { this.heartbeat = true; return; }
|
||||
var colon = line.indexOf(":"), key = colon < 0 ? line : line.slice(0, colon);
|
||||
var value = colon < 0 ? "" : line.slice(colon + 1);
|
||||
if (value.charAt(0) === " ") value = value.slice(1);
|
||||
if (key === "data") { this.hasData = true; this.data.push(value); }
|
||||
else if (key === "event") this.event = value;
|
||||
else if (key === "id" && value.indexOf("\0") < 0) this.id = value;
|
||||
else if (key === "retry" && /^[0-9]+$/.test(value)) {
|
||||
var delay = Number(value);
|
||||
if (!Number.isSafeInteger(delay) || delay < 2000 || delay > 5000) throw invalid("invalid retry interval");
|
||||
this.retry = delay;
|
||||
}
|
||||
};
|
||||
Parser.prototype.push = function (chunk) {
|
||||
if (!(chunk instanceof Uint8Array)) throw invalid("stream chunks must be bytes");
|
||||
for (var i = 0; i < chunk.length && !this.stopped; i++) {
|
||||
var byte = chunk[i];
|
||||
if (this.cr) {
|
||||
this.cr = false;
|
||||
if (byte === 10) {
|
||||
if (++this.bytes > MAX_BYTES) throw invalid("event exceeds byte limit");
|
||||
this.endLine(); continue;
|
||||
}
|
||||
this.endLine();
|
||||
if (this.stopped) break;
|
||||
}
|
||||
if (++this.bytes > MAX_BYTES) throw invalid("event exceeds byte limit");
|
||||
if (byte === 13) this.cr = true;
|
||||
else if (byte === 10) this.endLine();
|
||||
else this.line[this.length++] = byte;
|
||||
}
|
||||
};
|
||||
Parser.prototype.finish = function () {
|
||||
if (this.cr && !this.stopped) { this.cr = false; this.endLine(); }
|
||||
// EOF never dispatches an incomplete event or advances its cursor.
|
||||
this.reset(); this.length = 0; this.bytes = 0; this.stopped = true;
|
||||
};
|
||||
|
||||
function safeUrl(value, location) {
|
||||
if (typeof value !== "string" || value.charAt(0) !== "/" || value.charAt(1) === "/" ||
|
||||
/[\\\x00-\x20\x7f]/.test(value)) throw invalid("unsafe page URL");
|
||||
var url = new URL(value, location.href);
|
||||
if (url.origin !== location.origin || url.hash || url.username || url.password) throw invalid("unsafe page URL");
|
||||
return url;
|
||||
}
|
||||
|
||||
var TAGS = new Set(["DIV", "SPAN", "P", "SECTION", "H2", "H3", "STRONG", "EM", "SMALL", "TIME", "DL", "DT", "DD"]);
|
||||
var ATTRS = new Set(["id", "class", "title", "role", "aria-label", "aria-hidden", "aria-live",
|
||||
"data-live", "data-key", "data-state", "data-stale", "data-live-event", "data-page", "data-seq", "hx-swap-oob"]);
|
||||
var EDITS = "input,textarea,select,button,form,[contenteditable]";
|
||||
|
||||
function readOnly(root) {
|
||||
if (!root || !root.ownerDocument || root.matches(EDITS) || root.querySelector(EDITS) ||
|
||||
root.closest("[contenteditable]")) throw invalid("page contains editable controls");
|
||||
}
|
||||
|
||||
function checkedTree(root, oob) {
|
||||
var nodes = [root].concat(Array.from(root.querySelectorAll("*")));
|
||||
if (nodes.length > MAX_NODES) throw invalid("fragment exceeds node limit");
|
||||
for (var node of nodes) {
|
||||
if (!TAGS.has(node.tagName)) throw invalid("unsupported fragment element");
|
||||
for (var attr of node.attributes) {
|
||||
if (!ATTRS.has(attr.name) || attr.value.length > 4096) throw invalid("unsupported fragment attribute");
|
||||
if ((oob || node !== root) && (attr.name === "data-page" || attr.name === "data-seq")) throw invalid("nested page identity");
|
||||
if (attr.name === "id" && (node !== root && oob)) throw invalid("nested live identity");
|
||||
if (attr.name === "hx-swap-oob" && (node !== root || !oob || attr.value !== "outerHTML")) throw invalid("unsupported swap");
|
||||
}
|
||||
}
|
||||
return nodes.length;
|
||||
}
|
||||
|
||||
function parseHtml(doc, html) {
|
||||
if (typeof html !== "string" || new TextEncoder().encode(html).length > MAX_BYTES) throw invalid("HTML exceeds byte limit");
|
||||
var template = doc.createElement("template"); template.innerHTML = html;
|
||||
for (var child of template.content.childNodes) {
|
||||
if (child.nodeType !== 1 && !(child.nodeType === 3 && !child.textContent.trim())) throw invalid("unexpected fragment content");
|
||||
}
|
||||
return Array.from(template.content.children);
|
||||
}
|
||||
|
||||
/* Validate every target before changing any node. This read-only subset
|
||||
* deliberately rejects forms and executable or URL-bearing markup. */
|
||||
function applyReadOnly(root, kind, html) {
|
||||
readOnly(root);
|
||||
if (kind !== null && !["r", "st", "ap"].includes(kind)) throw invalid("unsupported HTML event");
|
||||
var nodes = parseHtml(root.ownerDocument, html), swaps = [], ids = new Set(), count = 0;
|
||||
if (!nodes.length || nodes.length > MAX_TARGETS) throw invalid("invalid swap count");
|
||||
for (var node of nodes) {
|
||||
count += checkedTree(node, true);
|
||||
if (count > MAX_NODES) throw invalid("event exceeds node limit");
|
||||
var id = node.getAttribute("id");
|
||||
if (!id || !/^[a-z][a-z0-9_.:-]{0,127}$/.test(id) || ids.has(id) ||
|
||||
node.getAttribute("hx-swap-oob") !== "outerHTML") throw invalid("invalid live target");
|
||||
ids.add(id);
|
||||
var target = root.ownerDocument.getElementById(id);
|
||||
if (!target || !root.contains(target) || target === root || !target.hasAttribute("data-live") ||
|
||||
root.ownerDocument.querySelectorAll('[id="' + id + '"]').length !== 1) throw invalid("missing or ambiguous live target");
|
||||
var declared = target.getAttribute("data-live-event") || (/^r-[a-f0-9]{8}$/.test(id) ? "r" : null);
|
||||
if (!["r", "st", "ap"].includes(declared) || kind !== null && declared !== kind || !node.hasAttribute("data-live") ||
|
||||
node.getAttribute("data-key") !== target.getAttribute("data-key") ||
|
||||
node.getAttribute("data-live-event") !== target.getAttribute("data-live-event")) throw invalid("live target changed identity");
|
||||
for (var prior of swaps) if (prior.target.contains(target) || target.contains(prior.target)) throw invalid("overlapping live targets");
|
||||
swaps.push({ target: target, node: node });
|
||||
}
|
||||
for (var swap of swaps) swap.target.replaceWith(swap.node);
|
||||
}
|
||||
|
||||
function applyPoll(root, html, previous, next) {
|
||||
if (!root.isConnected || !Number.isSafeInteger(previous) || !Number.isSafeInteger(next) ||
|
||||
previous < 0 || next < previous || next === previous && html.trim()) throw invalid("invalid poll sequence");
|
||||
if (html.trim()) applyReadOnly(root, null, html);
|
||||
}
|
||||
|
||||
function replacement(root, html) {
|
||||
readOnly(root);
|
||||
var nodes = parseHtml(root.ownerDocument, html);
|
||||
if (nodes.length !== 1) throw invalid("page reload must contain one root");
|
||||
var next = nodes[0]; checkedTree(next, false); readOnly(next);
|
||||
if (!root.getAttribute("data-page") || next.getAttribute("data-page") !== root.getAttribute("data-page")) throw invalid("page reload changed identity");
|
||||
var seq = sequence(next.getAttribute("data-seq")), ids = new Set();
|
||||
for (var node of [next].concat(Array.from(next.querySelectorAll("[id]")))) {
|
||||
var id = node.getAttribute("id");
|
||||
if (!id) continue;
|
||||
if (!/^[a-z][a-z0-9_.:-]{0,127}$/.test(id) || ids.has(id)) throw invalid("duplicate page identity");
|
||||
ids.add(id);
|
||||
for (var old of root.ownerDocument.querySelectorAll('[id="' + id + '"]')) {
|
||||
if (!root.contains(old)) throw invalid("page identity escapes its root");
|
||||
}
|
||||
}
|
||||
return { root: next, seq: seq };
|
||||
}
|
||||
|
||||
function responseIdentity(response, url) {
|
||||
if (response.type === "opaqueredirect" || response.redirected ||
|
||||
response.status >= 300 && response.status < 400) throw invalid("redirected page request");
|
||||
if (response.status === 401 || response.status === 403 || response.status === 404) throw invalid("page access refused");
|
||||
var finalUrl;
|
||||
try { finalUrl = new URL(response.url); } catch (_) { throw invalid("invalid page response URL"); }
|
||||
if (finalUrl.origin !== url.origin || finalUrl.pathname !== url.pathname || finalUrl.search !== url.search) throw invalid("page response changed URL");
|
||||
}
|
||||
|
||||
function limited(response) {
|
||||
var retry = response.headers.get("retry-after");
|
||||
if (!retry || !/^[0-9]{1,2}$/.test(retry) || Number(retry) < 1 || Number(retry) > 64) throw invalid("invalid retry interval");
|
||||
var failure = new Error("page request limit reached"); failure.retryMs = Number(retry) * 1000; return failure;
|
||||
}
|
||||
|
||||
function responseType(response, type, url) {
|
||||
responseIdentity(response, url);
|
||||
if (!response.ok) throw new Error("page request failed: " + response.status);
|
||||
if ((response.headers.get("content-type") || "").split(";")[0].trim().toLowerCase() !== type || !response.body) throw invalid("unexpected page response");
|
||||
}
|
||||
|
||||
function aborted() { var error = new Error("page request aborted"); error.name = "AbortError"; return error; }
|
||||
|
||||
function cancellable(promise, signal) {
|
||||
if (signal.aborted) return Promise.reject(aborted());
|
||||
return new Promise(function (resolve, reject) {
|
||||
function stop() { reject(aborted()); }
|
||||
signal.addEventListener("abort", stop, { once: true });
|
||||
Promise.resolve(promise).then(resolve, reject).finally(function () { signal.removeEventListener("abort", stop); });
|
||||
});
|
||||
}
|
||||
|
||||
async function cancelReader(reader) {
|
||||
if (!reader) return;
|
||||
try { await reader.cancel(); } catch (_) {}
|
||||
try { reader.releaseLock(); } catch (_) {}
|
||||
}
|
||||
|
||||
async function readText(response, signal) {
|
||||
if (!response.body) return "";
|
||||
var reader = response.body.getReader(), size = 0, parts = [], decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
try {
|
||||
for (;;) {
|
||||
var chunk = await cancellable(reader.read(), signal);
|
||||
if (chunk.done) {
|
||||
try { parts.push(decoder.decode()); } catch (_) { throw invalid("invalid page UTF-8"); }
|
||||
break;
|
||||
}
|
||||
size += chunk.value.length; if (size > MAX_BYTES) throw invalid("page body exceeds byte limit");
|
||||
try { parts.push(decoder.decode(chunk.value, { stream: true })); } catch (_) { throw invalid("invalid page UTF-8"); }
|
||||
}
|
||||
return parts.join("");
|
||||
} finally { await cancelReader(reader); }
|
||||
}
|
||||
|
||||
function mode(value) {
|
||||
if (value !== "stream" && value !== "poll") throw invalid("invalid page transport mode");
|
||||
return value;
|
||||
}
|
||||
|
||||
/* A host may supply loadPage({url, signal}) returning HX body text. The
|
||||
* canonical validator and replacement remain here, after fresh access. */
|
||||
function PageLive(options, env) {
|
||||
env = env || {}; options = options || {};
|
||||
this.root = options.root; readOnly(this.root);
|
||||
this.doc = this.root.ownerDocument;
|
||||
this.location = env.location || this.doc.defaultView.location;
|
||||
this.url = safeUrl(options.streamUrl, this.location);
|
||||
this.pageUrl = safeUrl(options.pageUrl || this.location.pathname + this.location.search, this.location);
|
||||
this.cursor = sequence(this.root.getAttribute("data-seq"));
|
||||
if (!this.root.getAttribute("data-page") || sequence(this.url.searchParams.get("seq")) !== this.cursor) throw invalid("stream and page sequence differ");
|
||||
this.fetch = env.fetch || globalThis.fetch.bind(globalThis);
|
||||
this.setT = function (fn, ms) { return (env.setTimeout || setTimeout)(fn, ms); };
|
||||
this.clearT = function (id) { return (env.clearTimeout || clearTimeout)(id); };
|
||||
this.onState = options.onState || function () {};
|
||||
this.onAction = options.onAction || function () {};
|
||||
this.onClose = options.onClose || function () {};
|
||||
this.loadPage = options.loadPage || null;
|
||||
this.mode = mode(options.mode || "stream"); this.pollAdmission = false; this.bodyAdmission = false;
|
||||
this.controller = null; this.timer = null; this.watchdog = null;
|
||||
this.epoch = 0; this.closed = true; this.state = "connecting"; this.stale = false;
|
||||
this.retry = 3000; this.attempt = 0; this.resync = false; this.reload = null; this.poll = null;
|
||||
this.listeners = []; this.series = Object.create(null); this.seriesCount = 0;
|
||||
}
|
||||
|
||||
PageLive.prototype.onChange = function (listener) {
|
||||
var self = this; this.listeners.push(listener);
|
||||
return function () { var i = self.listeners.indexOf(listener); if (i >= 0) self.listeners.splice(i, 1); };
|
||||
};
|
||||
PageLive.prototype._observerFailure = function (error) {
|
||||
this.lastError = error; if (!this.close("terminal")) return; this.state = "error"; this.stale = true;
|
||||
this.doc.documentElement.setAttribute("data-live", "off"); this._mark();
|
||||
};
|
||||
PageLive.prototype._notify = function (listener, value) {
|
||||
var epoch = this.epoch, closed = this.closed;
|
||||
try { listener(value, this); return this.closed === closed && this.epoch === epoch; }
|
||||
catch (error) {
|
||||
if (this.closed === closed && this.epoch === epoch) this._observerFailure(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
PageLive.prototype._emit = function (what) {
|
||||
for (var listener of this.listeners.slice()) if (!this._notify(listener, what)) return false;
|
||||
return true;
|
||||
};
|
||||
PageLive.prototype.samples = function () { return []; };
|
||||
PageLive.prototype.chartSamples = function (id, key) {
|
||||
var ring = this.series[JSON.stringify([id, key])]; return ring ? ring.slice() : [];
|
||||
};
|
||||
PageLive.prototype._mark = function () {
|
||||
for (var node of this.root.querySelectorAll("[data-live]")) {
|
||||
node.classList.toggle("bf-stale", this.stale || node.hasAttribute("data-stale") || node.getAttribute("data-state") === "stale");
|
||||
}
|
||||
};
|
||||
PageLive.prototype._state = function (state) {
|
||||
var wasStale = this.stale, oldState = this.state;
|
||||
this.state = state;
|
||||
if (state === "open" || state === "poll") this.stale = false;
|
||||
else if (state !== "connecting") this.stale = true;
|
||||
this.doc.documentElement.setAttribute("data-live", state === "paused" ? "off" : this.mode === "poll" && state !== "error" ? "poll" :
|
||||
state === "connecting" ? "connecting" : this.stale ? "off" : "on");
|
||||
this._mark();
|
||||
if (wasStale !== this.stale && !this._emit("stale")) return false;
|
||||
if (oldState !== state) return this._notify(this.onState, state);
|
||||
return true;
|
||||
};
|
||||
PageLive.prototype._arm = function (epoch) {
|
||||
var self = this;
|
||||
if (this.watchdog !== null) this.clearT(this.watchdog);
|
||||
this.watchdog = this.setT(function () {
|
||||
self.watchdog = null;
|
||||
if (self.closed || self.epoch !== epoch) return;
|
||||
if (!self._state("quiet")) return;
|
||||
if (self.controller) self.controller.abort();
|
||||
}, QUIET_MS);
|
||||
};
|
||||
PageLive.prototype._touch = function (epoch) {
|
||||
this.attempt = 0; this._arm(epoch); return this._state("open");
|
||||
};
|
||||
PageLive.prototype.start = function (refresh) {
|
||||
if (!this.closed) return;
|
||||
var owner = owners.get(this.doc);
|
||||
if (owner && owner !== this) throw invalid("page already owns a live connection");
|
||||
owners.set(this.doc, this); this.closed = false;
|
||||
if (refresh) this._reload(++this.epoch); else this._begin();
|
||||
};
|
||||
PageLive.prototype._begin = function () { if (this.mode === "poll") this._poll(); else this._connect(); };
|
||||
PageLive.prototype.setMode = function (value) {
|
||||
value = mode(value);
|
||||
if (value === this.mode) return;
|
||||
var running = !this.closed; if (!this.close("mode")) return; this.mode = value; this.attempt = 0;
|
||||
if (running) this.start();
|
||||
};
|
||||
PageLive.prototype.close = function (reason) {
|
||||
var running = !this.closed;
|
||||
this.closed = true; this.epoch++;
|
||||
if (this.controller) { this.controller.abort(); this.controller = null; }
|
||||
if (this.timer !== null) { this.clearT(this.timer); this.timer = null; }
|
||||
if (this.watchdog !== null) { this.clearT(this.watchdog); this.watchdog = null; }
|
||||
if (this.reload) { this.clearT(this.reload.timeout); this.reload.controller.abort(); this.reload = null; }
|
||||
if (this.poll) { this.clearT(this.poll.timeout); this.clearT(this.poll.waitTimer); this.poll.controller.abort(); this.poll = null; }
|
||||
if (owners.get(this.doc) === this) owners.delete(this.doc);
|
||||
var epoch = this.epoch;
|
||||
if (running) {
|
||||
try { if (this.onClose(reason || "manual", this) === false) return false; }
|
||||
catch (error) { this.lastError = error; return false; }
|
||||
}
|
||||
return this.closed && this.epoch === epoch;
|
||||
};
|
||||
PageLive.prototype._stop = function (error) { this.lastError = error; if (this.close("terminal")) this._state("error"); };
|
||||
PageLive.prototype._schedule = function (minimum) {
|
||||
var self = this, epoch = this.epoch;
|
||||
if (this.closed || this.timer !== null) return;
|
||||
if (!this._state("retry")) return;
|
||||
var delay = Math.max(minimum || 0, Math.min(64000, this.retry * Math.pow(2, Math.min(this.attempt++, 8))));
|
||||
this.timer = this.setT(function () {
|
||||
self.timer = null;
|
||||
if (!self.closed && self.epoch === epoch && self.mode === "stream") self._connect();
|
||||
}, delay);
|
||||
};
|
||||
PageLive.prototype._json = function (kind, data) {
|
||||
var value;
|
||||
try { value = JSON.parse(data); } catch (_) { throw invalid("invalid JSON event"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.id !== "string" ||
|
||||
!value.id.length || value.id.length > 128) throw invalid("invalid JSON identity");
|
||||
if (kind === "series") {
|
||||
if (Object.keys(value).some(function (k) { return !["id", "key", "p"].includes(k); }) ||
|
||||
typeof value.key !== "string" || !value.key.length || value.key.length > 256 ||
|
||||
!Array.isArray(value.p) || value.p.length !== 2 ||
|
||||
!value.p.every(function (v) { return typeof v === "number" && Number.isFinite(v); })) throw invalid("invalid chart point");
|
||||
var key = JSON.stringify([value.id, value.key]), ring = this.series[key];
|
||||
if (!ring) {
|
||||
if (this.seriesCount >= 64) throw invalid("chart series limit exceeded");
|
||||
ring = this.series[key] = []; this.seriesCount++;
|
||||
}
|
||||
ring.push({ t: value.p[0], v: value.p[1] }); if (ring.length > 60) ring.shift();
|
||||
} else {
|
||||
if (Object.keys(value).some(function (k) { return !["id", "state", "detail"].includes(k); }) ||
|
||||
typeof value.state !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(value.state) ||
|
||||
typeof value.detail !== "string" || value.detail.length > 4096) throw invalid("invalid action progress");
|
||||
return this._notify(this.onAction, value);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
PageLive.prototype._frame = function (frame, epoch) {
|
||||
if (this.closed || this.epoch !== epoch) return false;
|
||||
if (frame.retry !== null) this.retry = frame.retry;
|
||||
if (!frame.hasData) {
|
||||
if (frame.event || frame.id !== null) throw invalid("event has no data field");
|
||||
if (frame.heartbeat) return this._touch(epoch);
|
||||
return;
|
||||
}
|
||||
var seq = sequence(frame.id);
|
||||
if (frame.event === "rs") {
|
||||
if (frame.data !== "") throw invalid("resync event has data");
|
||||
this.resync = true; return false;
|
||||
}
|
||||
if (seq <= this.cursor) throw invalid("event sequence did not advance");
|
||||
if (!this.root.isConnected) throw invalid("page root was detached");
|
||||
if (["r", "st", "ap"].includes(frame.event)) applyReadOnly(this.root, frame.event, frame.data);
|
||||
else if (["act", "series"].includes(frame.event)) {
|
||||
if (!this._json(frame.event, frame.data)) return false;
|
||||
}
|
||||
else throw invalid("unsupported page event");
|
||||
this.cursor = seq;
|
||||
if (!this._touch(epoch)) return false;
|
||||
if (frame.event === "series") return this._emit("data");
|
||||
};
|
||||
PageLive.prototype._connect = async function () {
|
||||
if (this.closed || this.mode !== "stream") return;
|
||||
var epoch = ++this.epoch, self = this, controller = new AbortController(), reader = null, failure = null;
|
||||
this.controller = controller; this.resync = false;
|
||||
if (!this._state("connecting")) return;
|
||||
this._arm(epoch);
|
||||
var url = new URL(this.url.href); url.searchParams.delete("mode"); url.searchParams.set("seq", String(this.cursor));
|
||||
try {
|
||||
var response = await cancellable(this.fetch(url.href, { credentials: "same-origin", redirect: "manual", cache: "no-store",
|
||||
headers: { "Accept": "text/event-stream", "Last-Event-ID": String(this.cursor) }, signal: controller.signal }), controller.signal);
|
||||
responseIdentity(response, url);
|
||||
if (response.status === 429) throw limited(response);
|
||||
responseType(response, "text/event-stream", url);
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
reader = response.body.getReader();
|
||||
var parser = new Parser(function (frame) { return self._frame(frame, epoch); });
|
||||
while (!this.closed && this.epoch === epoch && !parser.stopped) {
|
||||
var chunk = await cancellable(reader.read(), controller.signal);
|
||||
if (chunk.done) { parser.finish(); break; }
|
||||
parser.push(chunk.value);
|
||||
}
|
||||
} catch (error) { failure = error; }
|
||||
finally {
|
||||
controller.abort(); await cancelReader(reader);
|
||||
if (this.epoch === epoch) {
|
||||
this.controller = null;
|
||||
if (this.watchdog !== null) { this.clearT(this.watchdog); this.watchdog = null; }
|
||||
}
|
||||
}
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (failure && failure.protocol) { this._stop(failure); return; }
|
||||
if (this.resync) { await this._reload(epoch); return; }
|
||||
this._schedule(failure && failure.retryMs);
|
||||
};
|
||||
|
||||
PageLive.prototype._poll = async function () {
|
||||
if (this.closed || this.mode !== "poll") return;
|
||||
var epoch = ++this.epoch, self = this, controller = new AbortController();
|
||||
var poll = { epoch: epoch, controller: controller, timeout: null, waitTimer: null }, failure = null, resync = false;
|
||||
this.controller = controller; this.poll = poll;
|
||||
if (!this._state("connecting")) return;
|
||||
poll.timeout = this.setT(function () { controller.abort(); }, this.pollAdmission ? 384000 : RELOAD_MS);
|
||||
if (this.pollAdmission) poll.waitTimer = this.setT(function () {
|
||||
if (!self.closed && self.epoch === epoch) self._state("quiet");
|
||||
}, QUIET_MS);
|
||||
function admitted() {
|
||||
if (self.closed || self.epoch !== epoch) return;
|
||||
self.clearT(poll.timeout); self.clearT(poll.waitTimer); poll.waitTimer = null;
|
||||
poll.timeout = self.setT(function () { controller.abort(); }, RELOAD_MS);
|
||||
}
|
||||
var url = new URL(this.url.href); url.searchParams.set("seq", String(this.cursor)); url.searchParams.set("mode", "poll");
|
||||
try {
|
||||
var response = await cancellable(this.fetch(url.href, { credentials: "same-origin", redirect: "manual", cache: "no-store",
|
||||
headers: { "Accept": "text/html" }, signal: controller.signal, onAdmission: this.pollAdmission ? admitted : null }), controller.signal);
|
||||
responseIdentity(response, url);
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (response.status === 429) throw limited(response);
|
||||
if (!response.ok) throw new Error("page request failed: " + response.status);
|
||||
if (![200, 205].includes(response.status) ||
|
||||
(response.headers.get("content-type") || "").split(";")[0].trim().toLowerCase() !== "text/html") throw invalid("unexpected poll response");
|
||||
var seq = sequence(response.headers.get("x-seq")), flag = response.headers.get("x-resync");
|
||||
if (response.status === 205 ? flag !== "1" : flag !== null) throw invalid("invalid poll resync marker");
|
||||
var html = await readText(response, controller.signal);
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (response.status === 205) {
|
||||
if (html) throw invalid("resync response has a body");
|
||||
resync = true;
|
||||
} else {
|
||||
applyPoll(this.root, html, this.cursor, seq); this.cursor = seq; this.attempt = 0;
|
||||
if (!this._state("poll")) return;
|
||||
}
|
||||
} catch (error) { failure = error; }
|
||||
finally {
|
||||
this.clearT(poll.timeout); this.clearT(poll.waitTimer); controller.abort();
|
||||
if (this.controller === controller) this.controller = null;
|
||||
if (this.poll === poll) this.poll = null;
|
||||
}
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (failure && failure.protocol) { this._stop(failure); return; }
|
||||
if (resync) { await this._reload(epoch); return; }
|
||||
var delay = POLL_MS;
|
||||
if (failure) {
|
||||
if (!this._state("retry")) return;
|
||||
delay = Math.max(failure.retryMs || 0, Math.min(64000, POLL_MS * Math.pow(2, Math.min(this.attempt++, 8))));
|
||||
}
|
||||
this.timer = this.setT(function () {
|
||||
self.timer = null;
|
||||
if (!self.closed && self.epoch === epoch && self.mode === "poll") self._poll();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
PageLive.prototype._body = async function (controller, onAdmission) {
|
||||
if (this.loadPage) return cancellable(this.loadPage({ url: this.pageUrl.href, signal: controller.signal }), controller.signal);
|
||||
var response = await cancellable(this.fetch(this.pageUrl.href, { credentials: "same-origin", redirect: "manual", cache: "no-store",
|
||||
headers: { "Accept": "text/html", "HX-Request": "true" }, signal: controller.signal, onAdmission: onAdmission }), controller.signal);
|
||||
responseType(response, "text/html", this.pageUrl);
|
||||
return readText(response, controller.signal);
|
||||
};
|
||||
PageLive.prototype._reload = async function (epoch) {
|
||||
if (this.closed || this.epoch !== epoch || this.reload && this.reload.epoch === epoch) return;
|
||||
if (!this._state("resync")) return;
|
||||
var controller = new AbortController(); this.controller = controller;
|
||||
var self = this, timeout = this.setT(function () { controller.abort(); }, this.bodyAdmission ? 384000 : RELOAD_MS);
|
||||
var reload = { epoch: epoch, controller: controller, timeout: timeout }; this.reload = reload;
|
||||
function admitted() {
|
||||
if (self.closed || self.epoch !== epoch) return;
|
||||
self.clearT(timeout); timeout = self.setT(function () { controller.abort(); }, RELOAD_MS); reload.timeout = timeout;
|
||||
}
|
||||
try {
|
||||
readOnly(this.root);
|
||||
if (!this.root.isConnected) throw invalid("page root was detached");
|
||||
var html = await this._body(controller, this.bodyAdmission ? admitted : null);
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (!this.root.isConnected) throw invalid("page root was detached");
|
||||
var next = replacement(this.root, html);
|
||||
this.root.replaceWith(next.root); this.root = next.root; this.cursor = next.seq;
|
||||
this.series = Object.create(null); this.seriesCount = 0; this.resync = false;
|
||||
var wasStale = this.stale; this.stale = false; this._mark();
|
||||
if (wasStale && !this._emit("stale")) return;
|
||||
} catch (error) {
|
||||
if (!this.closed && this.epoch === epoch) this._stop(error);
|
||||
return;
|
||||
} finally {
|
||||
this.clearT(timeout); controller.abort();
|
||||
if (this.controller === controller) this.controller = null;
|
||||
if (this.reload === reload) this.reload = null;
|
||||
}
|
||||
if (!this.closed && this.epoch === epoch) this._begin();
|
||||
};
|
||||
|
||||
return { Parser: Parser, sequence: sequence, safeUrl: safeUrl,
|
||||
applyReadOnly: applyReadOnly, applyPoll: applyPoll, replacement: replacement,
|
||||
PageLive: PageLive, MAX_BYTES: MAX_BYTES, QUIET_MS: QUIET_MS };
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
/* One origin-wide request owner. Values are sent only to their bound port. */
|
||||
(function (scope, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory;
|
||||
else factory(scope);
|
||||
})(typeof self !== "undefined" ? self : this, function (scope) {
|
||||
"use strict";
|
||||
var VERSION = 1, MAX_PORTS = 32, STREAMS = 3, CHUNK = 16384;
|
||||
var ports = new Set(), clients = new Map(), pumping = false;
|
||||
var short = { poll: { queue: [], active: null, timer: null }, body: { queue: [], active: null, timer: null } };
|
||||
var setT = function (fn, ms) { return scope.setTimeout(fn, ms); };
|
||||
var clearT = function (id) { scope.clearTimeout(id); };
|
||||
function shape(value, keys) {
|
||||
return value && typeof value === "object" && !Array.isArray(value) &&
|
||||
Object.keys(value).every(function (key) { return keys.includes(key); });
|
||||
}
|
||||
function send(client, value, transfer) {
|
||||
try { client.port.postMessage(value, transfer || []); return true; }
|
||||
catch (_) { remove(client); return false; }
|
||||
}
|
||||
function url(value) {
|
||||
if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") ||
|
||||
value.startsWith("//") || /[\\\x00-\x20\x7f]/.test(value)) throw new Error("unsafe URL");
|
||||
var parsed = new URL(value, scope.location.href);
|
||||
if (parsed.origin !== scope.location.origin || parsed.hash || parsed.username || parsed.password) throw new Error("unsafe URL");
|
||||
return parsed;
|
||||
}
|
||||
function sequence(value) { return Number.isSafeInteger(value) && value >= 0; }
|
||||
function abort(client) {
|
||||
var request = client.request;
|
||||
if (!request) return;
|
||||
client.request = null;
|
||||
if (request.queued) {
|
||||
short[request.kind].queue = short[request.kind].queue.filter(function (entry) { return entry.current !== request; });
|
||||
request.queued = false;
|
||||
}
|
||||
request.controller.abort();
|
||||
releaseShort(request);
|
||||
clearT(request.timer);
|
||||
if (request.ack) { request.ack(); request.ack = null; }
|
||||
if (request.reader) Promise.resolve(request.reader.cancel()).catch(function () {});
|
||||
}
|
||||
function remove(client) {
|
||||
if (!ports.delete(client)) return;
|
||||
abort(client); clearT(client.deadline); clearT(client.hiddenTimer);
|
||||
if (clients.get(client.key) === client) clients.delete(client.key);
|
||||
try { client.port.close(); } catch (_) {}
|
||||
pump();
|
||||
}
|
||||
function live(client) {
|
||||
clearT(client.deadline);
|
||||
client.deadline = setT(function () { remove(client); }, 35000);
|
||||
}
|
||||
function pause(client) {
|
||||
client.eligible = false; client.paused = true; client.slot = false;
|
||||
clearT(client.hiddenTimer); client.hiddenTimer = null; abort(client);
|
||||
send(client, { type: "mode", mode: "paused" });
|
||||
}
|
||||
function pump() {
|
||||
if (pumping) return;
|
||||
pumping = true;
|
||||
var count = 0;
|
||||
for (var client of clients.values()) if (client.slot) count++;
|
||||
for (var entry of clients.values()) {
|
||||
if (entry.slot || !entry.eligible || !entry.visible) continue;
|
||||
if (count >= STREAMS) {
|
||||
for (var prior of clients.values()) {
|
||||
if (prior.slot && !prior.visible) { pause(prior); count--; break; }
|
||||
}
|
||||
}
|
||||
if (count < STREAMS) {
|
||||
entry.slot = true; entry.paused = false; count++;
|
||||
if (!send(entry, { type: "mode", mode: "stream" })) count--;
|
||||
}
|
||||
}
|
||||
pumping = false;
|
||||
}
|
||||
function visibility(client, visible) {
|
||||
clearT(client.hiddenTimer); client.hiddenTimer = null; client.visible = visible;
|
||||
if (visible) {
|
||||
client.paused = false; client.eligible = !client.pollOnly; pump();
|
||||
send(client, { type: "mode", mode: client.slot ? "stream" : "poll" });
|
||||
return;
|
||||
}
|
||||
if (client.paused) return;
|
||||
if (!client.slot || client.request && client.request.kind !== "stream") { pause(client); pump(); return; }
|
||||
client.hiddenTimer = setT(function () { pause(client); pump(); }, 30000);
|
||||
pump();
|
||||
}
|
||||
function releaseShort(current) {
|
||||
var group = short[current.kind];
|
||||
if (!group || group.active !== current) return;
|
||||
group.active = null;
|
||||
group.timer = setT(function () { group.timer = null; pumpShort(current.kind); }, 2000);
|
||||
}
|
||||
function pumpShort(kind) {
|
||||
var group = short[kind];
|
||||
if (group.active || group.timer !== null) return;
|
||||
while (group.queue.length) {
|
||||
var entry = group.queue.shift(), client = entry.client, current = entry.current;
|
||||
current.queued = false;
|
||||
if (!ports.has(client) || client.paused || client.request !== current) continue;
|
||||
group.active = current; execute(client, entry.message, current); return;
|
||||
}
|
||||
}
|
||||
function request(client, message) {
|
||||
abort(client);
|
||||
var current = { id: message.id, kind: message.kind, controller: new AbortController(), reader: null,
|
||||
ack: null, index: 0, timer: null, queued: message.kind !== "stream" };
|
||||
client.request = current;
|
||||
if (current.queued) {
|
||||
current.timer = setT(function () {
|
||||
if (client.request === current) { send(client, { type: "error", id: current.id, error: "admission deadline" }); abort(client); }
|
||||
}, 384000);
|
||||
short[current.kind].queue.push({ client: client, message: message, current: current }); pumpShort(current.kind);
|
||||
} else execute(client, message, current);
|
||||
}
|
||||
async function execute(client, message, current) {
|
||||
function active() { return ports.has(client) && client.request === current && !current.controller.signal.aborted; }
|
||||
var target = new URL(message.kind === "body" ? client.page.href : client.events.href);
|
||||
var headers = { Accept: message.kind === "stream" ? "text/event-stream" : "text/html" };
|
||||
if (message.kind === "body") headers["HX-Request"] = "true";
|
||||
else {
|
||||
target.searchParams.set("seq", String(message.seq));
|
||||
if (message.kind === "poll") target.searchParams.set("mode", "poll");
|
||||
else { target.searchParams.delete("mode"); headers["Last-Event-ID"] = String(message.seq); }
|
||||
}
|
||||
clearT(current.timer);
|
||||
current.timer = setT(function () {
|
||||
if (active()) { send(client, { type: "error", id: current.id, error: "request deadline" }); abort(client); }
|
||||
}, message.kind === "stream" ? 20000 : 10000);
|
||||
try {
|
||||
if (message.kind !== "stream" && !send(client, { type: "admitted", id: current.id })) return;
|
||||
if (!active()) return;
|
||||
var response = await scope.fetch(target.href, { headers: headers, signal: current.controller.signal,
|
||||
credentials: "same-origin", redirect: "manual", cache: "no-store" });
|
||||
if (!active()) return;
|
||||
var fields = {};
|
||||
for (var key of ["content-type", "x-seq", "x-resync", "retry-after"]) {
|
||||
var value = response.headers.get(key);
|
||||
if (value !== null) { if (value.length > 256) throw new Error("oversized header"); fields[key] = value; }
|
||||
}
|
||||
if (!send(client, { type: "head", id: current.id, status: response.status, url: response.url,
|
||||
redirected: response.redirected, responseType: response.type, headers: fields })) return;
|
||||
if (response.body) {
|
||||
current.reader = response.body.getReader();
|
||||
while (active()) {
|
||||
var part = await current.reader.read();
|
||||
if (!active()) return;
|
||||
if (part.done) break;
|
||||
if (!(part.value instanceof Uint8Array) || part.value.byteLength > 262144) throw new Error("oversized network chunk");
|
||||
for (var offset = 0; offset < part.value.byteLength && active(); offset += CHUNK) {
|
||||
var chunk = part.value.slice(offset, offset + CHUNK);
|
||||
if (current.kind === "stream") {
|
||||
clearT(current.timer);
|
||||
current.timer = setT(function () {
|
||||
if (active()) { send(client, { type: "error", id: current.id, error: "reader deadline" }); abort(client); }
|
||||
}, 20000);
|
||||
}
|
||||
await new Promise(function (resolve) {
|
||||
current.ack = resolve;
|
||||
if (!send(client, { type: "chunk", id: current.id, index: ++current.index, data: chunk.buffer }, [chunk.buffer])) resolve();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (active()) send(client, { type: "end", id: current.id });
|
||||
} catch (_) {
|
||||
if (active()) send(client, { type: "error", id: current.id, error: "request failed" });
|
||||
} finally {
|
||||
current.controller.abort(); clearT(current.timer); releaseShort(current);
|
||||
if (current.ack) current.ack();
|
||||
if (current.reader) {
|
||||
try { await current.reader.cancel(); } catch (_) {}
|
||||
try { current.reader.releaseLock(); } catch (_) {}
|
||||
}
|
||||
if (client.request === current) client.request = null;
|
||||
}
|
||||
}
|
||||
function receive(client, message) {
|
||||
if (!ports.has(client)) return;
|
||||
if (!client.key) {
|
||||
if (!shape(message, ["type", "version", "client", "events", "page", "visible", "streams"]) || message.type !== "bind" ||
|
||||
message.version !== VERSION || typeof message.client !== "string" || !/^[a-z0-9-]{16,80}$/.test(message.client) ||
|
||||
typeof message.visible !== "boolean" || typeof message.streams !== "boolean") throw new Error("invalid binding");
|
||||
client.events = url(message.events); client.page = url(message.page);
|
||||
if (!/^[0-9]{1,16}$/.test(client.events.searchParams.get("seq") || "") ||
|
||||
!sequence(Number(client.events.searchParams.get("seq")))) throw new Error("invalid sequence");
|
||||
var prior = clients.get(message.client);
|
||||
if (prior) remove(prior);
|
||||
client.key = message.client; clients.set(client.key, client);
|
||||
client.pollOnly = !message.streams; client.eligible = message.streams && message.visible;
|
||||
client.visible = message.visible; client.paused = !message.visible; client.slot = false; client.lastId = 0;
|
||||
live(client);
|
||||
var outerPump = pumping; pumping = true;
|
||||
try {
|
||||
var used = [...clients.values()].filter(function (entry) { return entry.slot; }).length;
|
||||
if (client.eligible && used >= STREAMS) {
|
||||
for (var prior of clients.values()) {
|
||||
if (prior.slot && !prior.visible) { pause(prior); used--; break; }
|
||||
}
|
||||
}
|
||||
if (client.eligible && used < STREAMS) client.slot = true;
|
||||
send(client, { type: "ready", version: VERSION, mode: client.paused ? "paused" : client.slot ? "stream" : "poll" });
|
||||
} finally { pumping = outerPump; }
|
||||
pump(); return;
|
||||
}
|
||||
if (shape(message, ["type"]) && message.type === "close") { remove(client); return; }
|
||||
if (shape(message, ["type"]) && message.type === "ping") { live(client); send(client, { type: "pong" }); return; }
|
||||
if (shape(message, ["type", "visible"]) && message.type === "visibility" && typeof message.visible === "boolean") {
|
||||
visibility(client, message.visible); return;
|
||||
}
|
||||
if (shape(message, ["type", "id", "index"]) && (message.type === "abort" || message.type === "ack") && sequence(message.id)) {
|
||||
if (client.request && client.request.id === message.id) {
|
||||
if (message.type === "abort") abort(client);
|
||||
else if (client.request.ack && message.index === client.request.index) { var ack = client.request.ack; client.request.ack = null; ack(); }
|
||||
}
|
||||
if (message.type === "abort") send(client, { type: "aborted", id: message.id });
|
||||
return;
|
||||
}
|
||||
if (!shape(message, ["type", "id", "kind", "seq"]) || message.type !== "request" ||
|
||||
!sequence(message.id) || message.id <= client.lastId || !["stream", "poll", "body"].includes(message.kind) ||
|
||||
message.kind !== "body" && !sequence(message.seq)) throw new Error("invalid request");
|
||||
client.lastId = message.id;
|
||||
if (client.paused || message.kind === "stream" && !client.slot) { send(client, { type: "error", id: message.id, error: "stream slot unavailable" }); return; }
|
||||
request(client, message);
|
||||
}
|
||||
scope.onconnect = function (event) {
|
||||
var port = event.ports[0];
|
||||
if (!port) return;
|
||||
if (ports.size >= MAX_PORTS) { port.postMessage({ type: "refused" }); port.close(); return; }
|
||||
var client = { port: port, request: null, key: null, deadline: null, hiddenTimer: null };
|
||||
ports.add(client); live(client);
|
||||
port.onmessage = function (event) { try { receive(client, event.data); } catch (_) { send(client, { type: "refused" }); remove(client); } };
|
||||
port.onmessageerror = function () { remove(client); };
|
||||
port.start();
|
||||
};
|
||||
return { clients: clients, ports: ports };
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
/* SharedWorker admission and a private fetch bridge for one canonical page. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory();
|
||||
else root.FlarePageOwner = factory();
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
var NAME = "bf-live", VERSION = 1;
|
||||
function error(message) { return new Error(message); }
|
||||
function aborted() { var value = error("owned page request aborted"); value.name = "AbortError"; return value; }
|
||||
function safe(value, location) {
|
||||
if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") || value.startsWith("//") ||
|
||||
/[\\\x00-\x20\x7f]/.test(value)) throw error("unsafe owner URL");
|
||||
var url = new URL(value, location.href);
|
||||
if (url.origin !== location.origin || url.hash || url.username || url.password) throw error("unsafe owner URL");
|
||||
return url;
|
||||
}
|
||||
function Owner(options, env) {
|
||||
env = env || {}; this.env = env; this.doc = options.doc;
|
||||
this.location = env.location || this.doc.defaultView.location;
|
||||
this.events = safe(options.streamUrl, this.location); this.page = safe(options.pageUrl, this.location);
|
||||
this.workerUrl = safe(options.workerUrl, this.location);
|
||||
if (this.workerUrl.search) throw error("worker URL must be stable");
|
||||
this.Worker = env.SharedWorker || this.doc.defaultView.SharedWorker;
|
||||
this.Channel = env.BroadcastChannel || this.doc.defaultView.BroadcastChannel;
|
||||
this.channel = null; this.bcHealthy = false; this.peers = new Map();
|
||||
this.nativeFetch = env.fetch || this.doc.defaultView.fetch.bind(this.doc.defaultView);
|
||||
this.setT = function (fn, ms) { return (env.setTimeout || setTimeout)(fn, ms); };
|
||||
this.clearT = function (id) { return (env.clearTimeout || clearTimeout)(id); };
|
||||
this.key = "page-" + Math.random().toString(36).slice(2) + "-" + Math.random().toString(36).slice(2);
|
||||
this.port = null; this.worker = null; this.requests = new Map(); this.next = 0;
|
||||
this.epoch = 0; this.closed = true; this.admitted = false; this.everOwned = false;
|
||||
this.fallback = false; this.paused = false; this.hiddenTimer = null; this.timer = null; this.pulse = null; this.deadline = null; this.live = null;
|
||||
this.visible = this.doc.visibilityState !== "hidden";
|
||||
this.changed = this.visibility.bind(this); this.leave = this.close.bind(this);
|
||||
}
|
||||
Owner.prototype.attach = function (live) {
|
||||
if (this.live || !live.closed) throw error("owner requires an unstarted page");
|
||||
if (live.loadPage) throw error("coordinated pages require the canonical body fetch");
|
||||
var self = this, previous = live.onClose || function () {};
|
||||
live.onClose = function (reason, page) {
|
||||
if (reason !== "mode" && reason !== "owner" && self.live === page) self.close();
|
||||
var epoch = self.epoch; previous(reason, page);
|
||||
return self.epoch === epoch;
|
||||
};
|
||||
this.live = live; live.fetch = this.fetch.bind(this); live.pollAdmission = true; live.bodyAdmission = true; return this;
|
||||
};
|
||||
Owner.prototype.send = function (value) {
|
||||
if (!this.port) return false;
|
||||
try { this.port.postMessage(value); return true; }
|
||||
catch (_) { this.lost(); return false; }
|
||||
};
|
||||
Owner.prototype.start = function () {
|
||||
if (!this.closed) return;
|
||||
if (!this.live) throw error("owner has no page");
|
||||
this.closed = false; this.visible = this.doc.visibilityState !== "hidden";
|
||||
this.cooperate();
|
||||
this.doc.addEventListener("visibilitychange", this.changed);
|
||||
this.doc.defaultView.addEventListener("pagehide", this.leave);
|
||||
this.connect();
|
||||
};
|
||||
Owner.prototype.clear = function () {
|
||||
this.clearT(this.timer); this.clearT(this.pulse); this.clearT(this.deadline); this.clearT(this.hiddenTimer);
|
||||
this.timer = this.pulse = this.deadline = this.hiddenTimer = null;
|
||||
};
|
||||
Owner.prototype.disconnect = function () {
|
||||
this.epoch++; this.admitted = false; this.clear();
|
||||
if (this.port) { try { this.port.postMessage({ type: "close" }); this.port.close(); } catch (_) {} }
|
||||
this.port = null; this.worker = null;
|
||||
for (var request of this.requests.values()) this.fail(request, aborted());
|
||||
this.requests.clear();
|
||||
};
|
||||
Owner.prototype.close = function () {
|
||||
if (this.closed) return;
|
||||
this.closed = true; this.disconnect();
|
||||
if (this.channel) this.channel.close();
|
||||
this.channel = null; this.bcHealthy = false; this.peers.clear();
|
||||
this.doc.removeEventListener("visibilitychange", this.changed);
|
||||
this.doc.defaultView.removeEventListener("pagehide", this.leave);
|
||||
if (!this.live.closed) this.live.close("owner");
|
||||
};
|
||||
Owner.prototype.lost = function () {
|
||||
if (this.closed) return;
|
||||
this.disconnect(); var epoch = this.epoch; this.paused = true;
|
||||
this.live.close("owner");
|
||||
if (this.closed || this.epoch !== epoch) return;
|
||||
if (!this.live._state("quiet") || this.closed || this.epoch !== epoch) return;
|
||||
var self = this;
|
||||
this.timer = this.setT(function () { self.timer = null; if (!self.closed && self.epoch === epoch) self.connect(); }, 3000);
|
||||
};
|
||||
Owner.prototype.pollFallback = function () {
|
||||
if (this.closed || this.everOwned) { this.lost(); return; }
|
||||
this.disconnect(); var epoch = this.epoch; this.fallback = true;
|
||||
if (!this.visible) this.pause();
|
||||
else if (!this.closed && this.epoch === epoch) this.applyMode("poll");
|
||||
};
|
||||
Owner.prototype.connect = function () {
|
||||
if (this.closed) return;
|
||||
this.fallback = false;
|
||||
var self = this, epoch = ++this.epoch;
|
||||
function current() { return !self.closed && self.epoch === epoch; }
|
||||
try {
|
||||
if (!this.Worker) throw error("page coordination unavailable");
|
||||
this.worker = new this.Worker(this.workerUrl.href, { name: NAME });
|
||||
this.port = this.worker.port;
|
||||
this.port.onmessage = function (event) { if (current()) self.receive(event.data); };
|
||||
this.port.onmessageerror = function () { if (current()) self.lost(); };
|
||||
this.worker.onerror = function () { if (current()) self.everOwned ? self.lost() : self.pollFallback(); };
|
||||
this.port.start();
|
||||
this.timer = this.setT(function () { if (current()) self.everOwned ? self.lost() : self.pollFallback(); }, 2000);
|
||||
this.send({ type: "bind", version: VERSION, client: this.key, events: this.events.pathname + this.events.search,
|
||||
page: this.page.pathname + this.page.search, visible: this.visible, streams: this.bcHealthy });
|
||||
} catch (_) { this.everOwned ? this.lost() : this.pollFallback(); }
|
||||
};
|
||||
Owner.prototype.cooperate = function () {
|
||||
var self = this;
|
||||
try {
|
||||
if (!this.Channel) return;
|
||||
this.channel = new this.Channel(NAME); this.bcHealthy = true;
|
||||
this.channel.onmessage = function (event) {
|
||||
var value = event.data;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 4 ||
|
||||
value.version !== VERSION || value.type !== "mode" || typeof value.client !== "string" ||
|
||||
!/^[a-z0-9-]{16,80}$/.test(value.client) || !["pending", "stream", "poll", "paused"].includes(value.mode) || value.client === self.key) return;
|
||||
if (!self.peers.has(value.client) && self.peers.size >= 32) self.peers.delete(self.peers.keys().next().value);
|
||||
self.peers.set(value.client, value.mode);
|
||||
};
|
||||
this.channel.onmessageerror = function () {
|
||||
if (self.closed) return;
|
||||
self.bcHealthy = false; self.channel.close(); self.channel = null; self.peers.clear();
|
||||
self.everOwned ? self.lost() : self.pollFallback();
|
||||
};
|
||||
this.announce("pending");
|
||||
} catch (_) { if (this.channel) this.channel.close(); this.channel = null; this.bcHealthy = false; }
|
||||
};
|
||||
Owner.prototype.announce = function (mode) {
|
||||
if (!this.channel) return;
|
||||
try { this.channel.postMessage({ version: VERSION, type: "mode", client: this.key, mode: mode }); }
|
||||
catch (_) { this.channel.onmessageerror(); }
|
||||
};
|
||||
Owner.prototype.heartbeat = function () {
|
||||
var self = this, epoch = this.epoch;
|
||||
this.clearT(this.pulse);
|
||||
this.pulse = this.setT(function () {
|
||||
self.pulse = null;
|
||||
if (!self.closed && self.epoch === epoch && self.send({ type: "ping" }) && self.epoch === epoch && !self.closed) self.heartbeat();
|
||||
}, 5000);
|
||||
};
|
||||
Owner.prototype.fresh = function () {
|
||||
var self = this, epoch = this.epoch;
|
||||
this.clearT(this.deadline);
|
||||
this.deadline = this.setT(function () { if (!self.closed && self.epoch === epoch) self.lost(); }, 15000);
|
||||
};
|
||||
Owner.prototype.pause = function () {
|
||||
if (this.closed) return;
|
||||
var epoch = this.epoch; this.paused = true; this.live.close("owner");
|
||||
if (!this.closed && this.epoch === epoch) this.live._state("paused");
|
||||
};
|
||||
Owner.prototype.applyMode = function (mode) {
|
||||
if (mode === "paused" || !this.visible && (mode === "poll" || this.paused || this.live.closed)) { this.pause(); return; }
|
||||
var epoch = this.epoch, refresh = this.paused; this.paused = false; this.live.setMode(mode);
|
||||
if (!this.closed && this.epoch === epoch && this.live.closed) this.live.start(refresh);
|
||||
};
|
||||
Owner.prototype.visibility = function () {
|
||||
this.visible = this.doc.visibilityState !== "hidden";
|
||||
if (this.admitted) this.send({ type: "visibility", visible: this.visible });
|
||||
else if (this.fallback) {
|
||||
this.clearT(this.hiddenTimer); this.hiddenTimer = null;
|
||||
if (this.visible) { if (this.paused) this.applyMode("poll"); }
|
||||
else this.pause();
|
||||
}
|
||||
};
|
||||
Owner.prototype.fail = function (request, reason) {
|
||||
if (request.done) return;
|
||||
request.done = true; request.signal.removeEventListener("abort", request.stop);
|
||||
if (request.controller) { try { request.controller.error(reason); } catch (_) {} }
|
||||
request.reject(reason);
|
||||
this.requests.delete(request.id);
|
||||
};
|
||||
Owner.prototype.receive = function (message) {
|
||||
if (!message || typeof message !== "object" || this.closed) { this.lost(); return; }
|
||||
if (message.type === "ready") {
|
||||
if (this.admitted || message.version !== VERSION || !["stream", "poll", "paused"].includes(message.mode) ||
|
||||
!this.bcHealthy && message.mode === "stream") { this.lost(); return; }
|
||||
this.clearT(this.timer); this.timer = null; this.admitted = true; this.everOwned = true;
|
||||
this.fresh(); this.heartbeat(); var epoch = this.epoch;
|
||||
this.send({ type: "visibility", visible: this.visible }); this.announce(message.mode);
|
||||
if (!this.closed && this.admitted && this.epoch === epoch) this.applyMode(message.mode); return;
|
||||
}
|
||||
if (message.type === "refused") { this.everOwned ? this.lost() : this.pollFallback(); return; }
|
||||
if (!this.admitted) { this.lost(); return; }
|
||||
if (message.type === "pong") { this.fresh(); return; }
|
||||
if (message.type === "mode") {
|
||||
if (!["stream", "poll", "paused"].includes(message.mode)) { this.lost(); return; }
|
||||
if (!this.bcHealthy && message.mode === "stream") { this.lost(); return; }
|
||||
var epoch = this.epoch; this.announce(message.mode);
|
||||
if (!this.closed && this.epoch === epoch) this.applyMode(message.mode); return;
|
||||
}
|
||||
var request = this.requests.get(message.id);
|
||||
if (!request || request.done) return;
|
||||
if (message.type === "admitted") {
|
||||
if (!["poll", "body"].includes(request.kind) || request.admitted) { this.lost(); return; }
|
||||
request.admitted = true;
|
||||
try { if (request.onAdmission) request.onAdmission(); }
|
||||
catch (reason) { this.send({ type: "abort", id: request.id }); this.fail(request, reason); }
|
||||
return;
|
||||
}
|
||||
if (message.type === "error") { this.fail(request, error("owner request failed")); return; }
|
||||
if (message.type === "aborted") { this.fail(request, aborted()); return; }
|
||||
if (message.type === "head") {
|
||||
if (request.kind !== "stream" && !request.admitted || request.controller || !Number.isInteger(message.status) || message.status < 0 || message.status > 599 ||
|
||||
typeof message.url !== "string" || message.url.length > 4096 || !message.headers || typeof message.headers !== "object") { this.lost(); return; }
|
||||
var self = this;
|
||||
var body = new ReadableStream({
|
||||
start: function (controller) { request.controller = controller; },
|
||||
pull: function () { request.demand = true; self.deliver(request); },
|
||||
cancel: function () {
|
||||
self.send({ type: "abort", id: request.id }); self.fail(request, aborted());
|
||||
}
|
||||
}, { highWaterMark: 0 });
|
||||
request.resolve({ status: message.status, ok: message.status >= 200 && message.status < 300,
|
||||
url: message.url, redirected: message.redirected, type: message.responseType,
|
||||
headers: new Headers(message.headers), body: body }); return;
|
||||
}
|
||||
if (message.type === "chunk") {
|
||||
if (!request.controller || request.chunk || !(message.data instanceof ArrayBuffer) ||
|
||||
message.data.byteLength > 16384 || !Number.isSafeInteger(message.index) || message.index !== request.index + 1) { this.lost(); return; }
|
||||
request.index = message.index; request.chunk = new Uint8Array(message.data); this.deliver(request); return;
|
||||
}
|
||||
if (message.type === "end") {
|
||||
if (!request.controller || request.chunk) { this.lost(); return; }
|
||||
request.done = true; request.signal.removeEventListener("abort", request.stop);
|
||||
request.controller.close(); this.requests.delete(request.id); return;
|
||||
}
|
||||
this.lost();
|
||||
};
|
||||
Owner.prototype.deliver = function (request) {
|
||||
if (request.done || !request.demand || !request.chunk) return;
|
||||
request.controller.enqueue(request.chunk); request.chunk = null; request.demand = false;
|
||||
this.send({ type: "ack", id: request.id, index: request.index });
|
||||
};
|
||||
Owner.prototype.fetch = function (value, options) {
|
||||
if (this.closed) return Promise.reject(aborted());
|
||||
if (this.fallback) {
|
||||
if (this.paused) return Promise.reject(aborted());
|
||||
if (options.onAdmission) options.onAdmission();
|
||||
return this.nativeFetch(value, options);
|
||||
}
|
||||
if (!this.admitted) return Promise.reject(error("page owner unavailable"));
|
||||
if (this.requests.size) return Promise.reject(error("page request already active"));
|
||||
var target = new URL(value), base = new URL(target.href), events = new URL(this.events.href), kind, seq;
|
||||
var headers = new Headers(options.headers);
|
||||
if (headers.get("hx-request") === "true" && target.href === this.page.href && headers.get("accept") === "text/html") kind = "body";
|
||||
else {
|
||||
seq = target.searchParams.get("seq"); base.searchParams.delete("seq"); events.searchParams.delete("seq");
|
||||
var poll = base.searchParams.get("mode") === "poll"; base.searchParams.delete("mode"); events.searchParams.delete("mode");
|
||||
if (base.href !== events.href || !/^[0-9]{1,16}$/.test(seq || "") || !Number.isSafeInteger(Number(seq)) ||
|
||||
headers.get("accept") !== (poll ? "text/html" : "text/event-stream")) return Promise.reject(error("unbound owner request"));
|
||||
kind = poll ? "poll" : "stream"; seq = Number(seq);
|
||||
}
|
||||
if (!options.signal || options.signal.aborted) return Promise.reject(aborted());
|
||||
var self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
var request = { id: ++self.next, resolve: resolve, reject: reject, signal: options.signal,
|
||||
done: false, controller: null, chunk: null, demand: false, index: 0, kind: kind,
|
||||
admitted: false, onAdmission: options.onAdmission };
|
||||
request.stop = function () { self.send({ type: "abort", id: request.id }); self.fail(request, aborted()); };
|
||||
self.requests.set(request.id, request); options.signal.addEventListener("abort", request.stop, { once: true });
|
||||
self.send({ type: "request", id: request.id, kind: kind, seq: seq });
|
||||
});
|
||||
};
|
||||
return { Owner: Owner, NAME: NAME, VERSION: VERSION };
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
||||
use flare_ui::page::{
|
||||
compile_page, generic_page, PagePrincipal, ReadingView, RenderCx, ValueSource,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use wschema::dsl::{DocBuilder, SettingBuilder};
|
||||
use wschema::model::{Block, Kind, Reading, Surface};
|
||||
|
||||
struct Host;
|
||||
impl PagePrincipal for Host {
|
||||
fn can(&self, permission: &str) -> bool {
|
||||
matches!(permission, "site.read" | "site.manage")
|
||||
}
|
||||
}
|
||||
impl ValueSource for Host {
|
||||
fn seq(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
fn setting(&self, _: &str) -> Option<&Value> {
|
||||
None
|
||||
}
|
||||
fn reading(&self, _: &Reading) -> ReadingView {
|
||||
panic!("settings-only page")
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("schema_fields");
|
||||
for count in [16, 128] {
|
||||
let mut builder = DocBuilder::base();
|
||||
builder.card("settings", |card| {
|
||||
for index in 0..count {
|
||||
card.add(
|
||||
SettingBuilder::new(
|
||||
&format!("settings.field{index}"),
|
||||
&format!("Field {index}"),
|
||||
"Stored setting.",
|
||||
Kind::Str {
|
||||
check: None,
|
||||
max_len: None,
|
||||
allow_empty: None,
|
||||
},
|
||||
)
|
||||
.default_value(json!("value")),
|
||||
);
|
||||
}
|
||||
});
|
||||
let mut block = Block::new("card", 0);
|
||||
block.section = Some("settings".into());
|
||||
builder.page("settings.main", vec![block]);
|
||||
let schema = wschema::merge(&builder.build(), &[]).unwrap();
|
||||
let cx = RenderCx {
|
||||
schema: &schema,
|
||||
principal: &Host,
|
||||
values: &Host,
|
||||
surface: Surface::Flare,
|
||||
};
|
||||
let snapshot = compile_page("settings.main", &cx).unwrap();
|
||||
assert_eq!(
|
||||
generic_page(&snapshot)
|
||||
.unwrap()
|
||||
.0
|
||||
.matches("data-path=")
|
||||
.count(),
|
||||
count
|
||||
);
|
||||
group.bench_function(BenchmarkId::new("compile", count), |b| {
|
||||
b.iter(|| compile_page(black_box("settings.main"), black_box(&cx)).unwrap())
|
||||
});
|
||||
group.bench_function(BenchmarkId::new("body", count), |b| {
|
||||
b.iter(|| generic_page(black_box(&snapshot)).unwrap())
|
||||
});
|
||||
let form = flare_ui::page::FormState {
|
||||
page: "settings.main".into(),
|
||||
card: "blocks/index/0".into(),
|
||||
schema_hash: schema.hash.clone(),
|
||||
revision: "host-revision".into(),
|
||||
action: "/save".into(),
|
||||
csrf: "benchmark-csrf".into(),
|
||||
fields: schema
|
||||
.doc
|
||||
.settings
|
||||
.iter()
|
||||
.map(|s| {
|
||||
(
|
||||
s.path.clone(),
|
||||
flare_ui::page::FieldState {
|
||||
provenance: flare_ui::page::Provenance::Default,
|
||||
submitted: None,
|
||||
error: None,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let binding = &form;
|
||||
let mut pairs = vec![
|
||||
("__bf_page", binding.page.as_str()),
|
||||
("__bf_card", binding.card.as_str()),
|
||||
("__bf_schema", binding.schema_hash.as_str()),
|
||||
("__bf_revision", binding.revision.as_str()),
|
||||
("__bf_csrf", binding.csrf.as_str()),
|
||||
];
|
||||
pairs.extend(binding.fields.keys().map(|path| (path.as_str(), "value")));
|
||||
let limits = flare_ui::form::Limits {
|
||||
max_fields: count,
|
||||
max_bytes: 65536,
|
||||
};
|
||||
let flare_ui::page::Submission::Save(ops) =
|
||||
binding.decode(&schema, &pairs, limits).unwrap()
|
||||
else {
|
||||
panic!("save expected")
|
||||
};
|
||||
assert_eq!(ops.len(), count);
|
||||
group.bench_function(BenchmarkId::new("host_decode", count), |b| {
|
||||
b.iter(|| {
|
||||
binding
|
||||
.decode(black_box(&schema), black_box(&pairs), limits)
|
||||
.unwrap()
|
||||
})
|
||||
});
|
||||
let form = [form];
|
||||
let writable =
|
||||
flare_ui::page::compile_page_with_forms("settings.main", &cx, &form).unwrap();
|
||||
group.bench_function(BenchmarkId::new("form_compile", count), |b| {
|
||||
b.iter(|| {
|
||||
flare_ui::page::compile_page_with_forms(
|
||||
black_box("settings.main"),
|
||||
black_box(&cx),
|
||||
black_box(&form),
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
});
|
||||
group.bench_function(BenchmarkId::new("form_body", count), |b| {
|
||||
b.iter(|| generic_page(black_box(&writable)).unwrap())
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn forms(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("native_forms");
|
||||
for count in [16, 128] {
|
||||
let mut builder = DocBuilder::base();
|
||||
let names: Vec<_> = (0..count)
|
||||
.map(|index| format!("settings.field{index}"))
|
||||
.collect();
|
||||
builder.card("settings", |card| {
|
||||
for name in &names {
|
||||
card.add(SettingBuilder::new(
|
||||
name,
|
||||
"Enabled",
|
||||
"Native switch.",
|
||||
Kind::Bool {},
|
||||
));
|
||||
}
|
||||
});
|
||||
let schema = wschema::merge(&builder.build(), &[]).unwrap();
|
||||
let names: Vec<_> = names.iter().map(String::as_str).collect();
|
||||
let pairs: Vec<_> = names
|
||||
.iter()
|
||||
.flat_map(|&name| [(name, "false"), (name, "true")])
|
||||
.collect();
|
||||
let limits = flare_ui::form::Limits {
|
||||
max_fields: count,
|
||||
max_bytes: 65536,
|
||||
};
|
||||
assert_eq!(
|
||||
flare_ui::form::decode(&schema, &names, &pairs, limits)
|
||||
.unwrap()
|
||||
.len(),
|
||||
count
|
||||
);
|
||||
group.bench_function(BenchmarkId::new("decode", count), |b| {
|
||||
b.iter(|| {
|
||||
flare_ui::form::decode(
|
||||
black_box(&schema),
|
||||
black_box(&names),
|
||||
black_box(&pairs),
|
||||
limits,
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, fields, forms);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,115 @@
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
||||
use flare_ui::page::{
|
||||
compile_page, generic_page, PagePrincipal, ReadingView, RenderCx, ValueSource,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use wschema::dsl::DocBuilder;
|
||||
use wschema::model::{Block, Reading, Surface};
|
||||
use wschema::{merge, Effective};
|
||||
|
||||
struct Host;
|
||||
impl PagePrincipal for Host {
|
||||
fn can(&self, permission: &str) -> bool {
|
||||
permission == "site.read"
|
||||
}
|
||||
}
|
||||
impl ValueSource for Host {
|
||||
fn seq(&self) -> u64 {
|
||||
42
|
||||
}
|
||||
fn setting(&self, _: &str) -> Option<&Value> {
|
||||
None
|
||||
}
|
||||
fn reading(&self, _: &Reading) -> ReadingView {
|
||||
ReadingView {
|
||||
value: Some(json!(23.5)),
|
||||
age_ms: Some(10),
|
||||
stale: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(count: usize, panel_escape: bool) -> Effective {
|
||||
let mut builder = DocBuilder::base();
|
||||
let mut block = Block::new("readings", 0);
|
||||
block.id = Some("values".into());
|
||||
block.title = Some("Values".into());
|
||||
for index in 0..count {
|
||||
let id = format!("sensor.reading{index}");
|
||||
builder.doc_mut().readings.push(
|
||||
serde_json::from_value(json!({
|
||||
"id":id,"label":format!("Reading {index}"),"kind":"measure","precision":1,
|
||||
"source":{"doc":"io/state","member":id}
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
block.readings.push(id);
|
||||
}
|
||||
let mut blocks = vec![block];
|
||||
if panel_escape {
|
||||
blocks.push(
|
||||
serde_json::from_value(json!({
|
||||
"kind":"escape", "order":1, "id":"native",
|
||||
"escape":{"panel":{
|
||||
"builder":"warden_screen_set_monitor_build", "replaces":["values"]
|
||||
}}
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
builder.page("status.main", blocks);
|
||||
merge(&builder.build(), &[]).unwrap()
|
||||
}
|
||||
|
||||
fn pages(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("schema_page");
|
||||
for count in [16, 128] {
|
||||
let schema = fixture(count, false);
|
||||
let cx = RenderCx {
|
||||
schema: &schema,
|
||||
principal: &Host,
|
||||
values: &Host,
|
||||
surface: Surface::Web,
|
||||
};
|
||||
let snapshot = compile_page("status.main", &cx).unwrap();
|
||||
assert_eq!(snapshot.readable_keys().len(), count);
|
||||
assert!(generic_page(&snapshot)
|
||||
.unwrap()
|
||||
.into_string()
|
||||
.contains("23.5"));
|
||||
group.bench_function(BenchmarkId::new("compile", count), |b| {
|
||||
b.iter(|| compile_page(black_box("status.main"), black_box(&cx)).unwrap())
|
||||
});
|
||||
group.bench_function(BenchmarkId::new("body", count), |b| {
|
||||
b.iter(|| generic_page(black_box(&snapshot)).unwrap())
|
||||
});
|
||||
group.bench_function(BenchmarkId::new("oob", count), |b| {
|
||||
b.iter(|| {
|
||||
snapshot
|
||||
.reading_oob(black_box("sensor.reading0"))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
})
|
||||
});
|
||||
let panel = fixture(count, true);
|
||||
let panel_cx = RenderCx {
|
||||
schema: &panel,
|
||||
..cx
|
||||
};
|
||||
let twin = compile_page("status.main", &panel_cx).unwrap();
|
||||
assert_eq!(twin.readable_keys(), snapshot.readable_keys());
|
||||
assert_eq!(
|
||||
generic_page(&twin).unwrap().into_string(),
|
||||
generic_page(&snapshot).unwrap().into_string()
|
||||
);
|
||||
group.bench_function(BenchmarkId::new("compile_panel", count), |b| {
|
||||
b.iter(|| compile_page(black_box("status.main"), black_box(&panel_cx)).unwrap())
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, pages);
|
||||
criterion_main!(benches);
|
||||
+688
-5
@@ -1,11 +1,29 @@
|
||||
//! Action and approval block renderers (LD-06): buttons that post through htmx.
|
||||
//! Action and approval block renderers (LD-06) and the live action contract
|
||||
//! (d04 7.4, flare-ui#135).
|
||||
//!
|
||||
//! Every action is a `<form method="post">` so it works without script; the
|
||||
//! `hx-post` attributes only upgrade it in place. Targets must be same-origin
|
||||
//! absolute paths (`/...`, not `//`), and each form carries the CSRF token the
|
||||
//! caller supplies. Text is escaped by maud and classes are allowlisted.
|
||||
//! Every action that runs is a `<form method="post">` so it works without script;
|
||||
//! the `hx-post` attributes only upgrade it in place. The arm and proof controls
|
||||
//! are `GET` forms to the confirm page, so they also work without script. Targets
|
||||
//! must be same-origin absolute paths (`/...`, not `//`), and each form carries
|
||||
//! the CSRF token the caller supplies. Text is escaped by maud and classes are
|
||||
//! allowlisted.
|
||||
//!
|
||||
//! A live action ([`LiveAction`]) is one action node with the `button` display.
|
||||
//! Its confirm rule shapes the control: `none` posts at once; `arm` opens the
|
||||
//! confirm page without script and arms in place with `assets/js/actions.js`;
|
||||
//! `typed:<word>` takes the word in the form and the server checks it. Declared
|
||||
//! params draw one field each in the same form, so the POST carries them. A
|
||||
//! fresh proof that the session lacks sends the viewer to the confirm page,
|
||||
//! which asks for the password again. [`decide`] applies the same rules to the
|
||||
//! POST, checks the params against their kinds, and the host runs it before it
|
||||
//! sends any command.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::Value;
|
||||
pub use wschema::model::Kind;
|
||||
|
||||
/// True when `path` is a same-origin absolute path safe to post to.
|
||||
pub fn safe_target(path: &str) -> bool {
|
||||
@@ -56,6 +74,21 @@ pub fn action_button(
|
||||
})
|
||||
}
|
||||
|
||||
/// A plain button carrying the action's label, drawn disabled. The page compiler
|
||||
/// uses it only where no route exists: the P-09 fallback of an unknown action
|
||||
/// display when the host gives no scope, and a live action whose `enabled_when`
|
||||
/// is false (d04 7.2). It has no route target or CSRF token, so it never submits.
|
||||
/// An unknown display with a scope draws a live control ([`live_control`]).
|
||||
pub fn plain_button(action_id: &str, label: &str) -> Markup {
|
||||
html! {
|
||||
span class="bf-action" {
|
||||
button type="button" class="bf-btn bf-text-button" disabled data-action=(action_id) {
|
||||
(label)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pending approval awaiting a decision.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Approval {
|
||||
@@ -95,3 +128,653 @@ pub fn approvals(base: &str, items: &[Approval], csrf: &str) -> Markup {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Live actions (d04 7.4) -----------------------------------------------
|
||||
|
||||
/// Longest typed confirmation word, in bytes.
|
||||
const WORD_MAX: usize = 32;
|
||||
|
||||
/// Longest action id, in bytes.
|
||||
const ID_MAX: usize = 64;
|
||||
|
||||
/// The field-name prefix of a declared param: `param.<name>`. The prefix keeps a
|
||||
/// param named `csrf` or `confirm_word` apart from the fixed fields.
|
||||
const PARAM_PREFIX: &str = "param.";
|
||||
|
||||
/// The validated params of one action request, keyed by param name.
|
||||
pub type Params = BTreeMap<String, Value>;
|
||||
|
||||
/// True for a typed confirmation word: 1 to 32 ASCII letters, digits, `-` or `_`.
|
||||
pub fn word_ok(word: &str) -> bool {
|
||||
(1..=WORD_MAX).contains(&word.len())
|
||||
&& word
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
/// True for an id that is safe as one URL segment and one attribute value: it
|
||||
/// starts with a lower-case letter or digit, continues with lower-case letters,
|
||||
/// digits, `.`, `-` or `_`, and is at most 64 bytes.
|
||||
pub fn id_ok(id: &str) -> bool {
|
||||
(1..=ID_MAX).contains(&id.len())
|
||||
&& id
|
||||
.bytes()
|
||||
.next()
|
||||
.is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
&& id.bytes().all(|b| {
|
||||
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'-' | b'_')
|
||||
})
|
||||
}
|
||||
|
||||
/// One declared param of a live action (d02 `params`): its name and the kind the
|
||||
/// schema gives it. A posted value is checked with [`Kind::accepts`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ParamSpec {
|
||||
pub name: String,
|
||||
pub kind: Kind,
|
||||
}
|
||||
|
||||
/// The confirmation a live action needs before it is sent (d02 `confirm`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Confirm {
|
||||
/// The action is sent at once.
|
||||
None,
|
||||
/// The first press arms the button for four seconds; the second sends it.
|
||||
Arm,
|
||||
/// The viewer types this word; the server checks `confirm_word`.
|
||||
Typed(String),
|
||||
}
|
||||
|
||||
impl Confirm {
|
||||
/// Parses the d02 `confirm` member: `none`, `arm` or `typed:<word>`.
|
||||
pub fn parse(raw: &str) -> Option<Self> {
|
||||
match raw {
|
||||
"none" => Some(Self::None),
|
||||
"arm" => Some(Self::Arm),
|
||||
_ => raw
|
||||
.strip_prefix("typed:")
|
||||
.filter(|word| word_ok(word))
|
||||
.map(|word| Self::Typed(word.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The d02 spelling of the rule, as the page layout records it.
|
||||
pub fn spelling(&self) -> String {
|
||||
match self {
|
||||
Self::None => "none".into(),
|
||||
Self::Arm => "arm".into(),
|
||||
Self::Typed(word) => format!("typed:{word}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The proof a live action needs on the web (d02 `proof`, d05 10.4).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Proof {
|
||||
/// The page's own permission only.
|
||||
None,
|
||||
/// Any valid session or scoped token.
|
||||
Session,
|
||||
/// A password re-entry no older than five minutes.
|
||||
Fresh,
|
||||
/// The cookie session only; a bearer token is refused.
|
||||
Console,
|
||||
/// Physical presence at the panel; the web does not offer the action.
|
||||
Local,
|
||||
}
|
||||
|
||||
impl Proof {
|
||||
/// Parses the d02 `proof` member.
|
||||
pub fn parse(raw: &str) -> Option<Self> {
|
||||
Some(match raw {
|
||||
"none" => Self::None,
|
||||
"session" => Self::Session,
|
||||
"fresh" => Self::Fresh,
|
||||
"console" => Self::Console,
|
||||
"local" => Self::Local,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The d02 spelling of the rule, as the page layout records it.
|
||||
pub fn spelling(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "none",
|
||||
Self::Session => "session",
|
||||
Self::Fresh => "fresh",
|
||||
Self::Console => "console",
|
||||
Self::Local => "local",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the device answers an action (d02 `mode`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// The reply is the result.
|
||||
Sync,
|
||||
/// The reply is `202` with an id; the result follows as an `act` event or
|
||||
/// on the status route.
|
||||
Async,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// Parses the d02 `mode` member.
|
||||
pub fn parse(raw: &str) -> Option<Self> {
|
||||
match raw {
|
||||
"sync" => Some(Self::Sync),
|
||||
"async" => Some(Self::Async),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The confirm, proof, mode and params of one action node.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ActionSpec {
|
||||
pub id: String,
|
||||
pub confirm: Confirm,
|
||||
pub proof: Proof,
|
||||
pub mode: Mode,
|
||||
/// The declared params, in schema order. Each one draws a field.
|
||||
pub params: Vec<ParamSpec>,
|
||||
}
|
||||
|
||||
/// What the host knows about one submitted action request. Each field comes
|
||||
/// from the authenticated session or from the request's own checks.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Submit<'a> {
|
||||
/// The CSRF token matched the session.
|
||||
pub csrf_ok: bool,
|
||||
/// The request carried the cookie session, not a bearer token.
|
||||
pub cookie_session: bool,
|
||||
/// The session holds a proof no older than five minutes.
|
||||
pub fresh_proof: bool,
|
||||
/// The typed confirmation word, when the request carried one.
|
||||
pub confirm_word: Option<&'a str>,
|
||||
/// Every field of the request as posted, in order. The params are read here.
|
||||
pub fields: &'a [(String, String)],
|
||||
}
|
||||
|
||||
/// A refused action request. The statuses follow d04 7.4 and d05 5.9, 10.4.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Refusal {
|
||||
/// The CSRF token did not match the session.
|
||||
Csrf,
|
||||
/// A fresh proof is required and missing or expired.
|
||||
ProofRequired,
|
||||
/// The re-entered password did not match.
|
||||
ProofInvalid,
|
||||
/// The action needs a cookie session and the request carried a bearer token.
|
||||
Forbidden,
|
||||
/// The typed word is missing or wrong.
|
||||
ConfirmWord,
|
||||
/// A declared param is missing or repeated, an undeclared param was sent, or
|
||||
/// a value is outside its kind.
|
||||
Param,
|
||||
/// The action is not offered on this surface.
|
||||
NotOffered,
|
||||
/// The viewer lacks the action's permission. Its routes answer 403 with this
|
||||
/// plate and no data (d04 7.5); an unknown or hidden action stays 404.
|
||||
Denied,
|
||||
/// The device did not answer (`E_UNAVAILABLE`).
|
||||
Unavailable,
|
||||
/// The device did not answer in time (`E_TIMEOUT`).
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl Refusal {
|
||||
/// The HTTP status the refusal answers with.
|
||||
pub fn status(self) -> u16 {
|
||||
match self {
|
||||
Self::Csrf
|
||||
| Self::ProofRequired
|
||||
| Self::ProofInvalid
|
||||
| Self::Forbidden
|
||||
| Self::Denied => 403,
|
||||
Self::ConfirmWord | Self::Param => 422,
|
||||
Self::NotOffered => 404,
|
||||
Self::Unavailable => 503,
|
||||
Self::Timeout => 504,
|
||||
}
|
||||
}
|
||||
|
||||
/// The problem type of a JSON answer (d05 11.4). d05 names `csrf`,
|
||||
/// `forbidden`, `proof_required` and `proof_invalid`. The other refusals
|
||||
/// answer their own name, which the amendment row for action refusals
|
||||
/// records as not yet named in d05.
|
||||
pub fn problem(self) -> &'static str {
|
||||
match self {
|
||||
Self::Csrf => "csrf",
|
||||
Self::ProofRequired => "proof_required",
|
||||
Self::ProofInvalid => "proof_invalid",
|
||||
Self::Forbidden | Self::Denied => "forbidden",
|
||||
Self::ConfirmWord => "confirm_word",
|
||||
Self::Param => "param",
|
||||
Self::NotOffered => "not_offered",
|
||||
Self::Unavailable => "unavailable",
|
||||
Self::Timeout => "timeout",
|
||||
}
|
||||
}
|
||||
|
||||
fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Csrf => "The page has expired. Reload it and try again.",
|
||||
Self::ProofRequired => "Re-enter your password to run this action.",
|
||||
Self::ProofInvalid => "That password did not match. Try again.",
|
||||
Self::Forbidden => "This action cannot run from here.",
|
||||
Self::ConfirmWord => "Type the word exactly as shown to confirm.",
|
||||
Self::Param => "A value is not allowed. Check the form and try again.",
|
||||
Self::NotOffered => "This action is not offered here.",
|
||||
Self::Denied => "You do not have permission for this action.",
|
||||
Self::Unavailable => "The device did not answer. Try again.",
|
||||
Self::Timeout => "The device took too long to answer.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `next` is the confirm page of an action on the surface at route
|
||||
/// prefix `prefix` (d04 7.4, d05 10.4). It must be the canonical path
|
||||
/// `{prefix}/{section}/{tab}/actions/{name}/confirm`, with no query or fragment,
|
||||
/// and `is_action` must confirm that the tab shows that action. The proof route
|
||||
/// uses it to return a no-script viewer only to a page the surface could draw.
|
||||
pub fn confirm_next_ok(
|
||||
next: &str,
|
||||
prefix: &str,
|
||||
is_action: impl Fn(&str, &str, &str) -> bool,
|
||||
) -> bool {
|
||||
if !safe_target(next) || !safe_target(prefix) {
|
||||
return false;
|
||||
}
|
||||
let Some(rest) = next
|
||||
.strip_prefix(prefix)
|
||||
.and_then(|rest| rest.strip_prefix('/'))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let parts: Vec<&str> = rest.split('/').collect();
|
||||
let [section, tab, "actions", name, "confirm"] = parts.as_slice() else {
|
||||
return false;
|
||||
};
|
||||
slug_ok(section) && slug_ok(tab) && id_ok(name) && is_action(section, tab, name)
|
||||
}
|
||||
|
||||
/// A menu slug: one to 64 ASCII letters, digits, `-`, `_` or `.`.
|
||||
fn slug_ok(slug: &str) -> bool {
|
||||
!slug.is_empty()
|
||||
&& slug.len() <= 64
|
||||
&& slug
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
|
||||
}
|
||||
|
||||
/// True when `posted` is the session's CSRF token `expected`. Every byte is read
|
||||
/// whatever the first mismatch, so the time taken does not show how much matched.
|
||||
/// An empty expected token never matches.
|
||||
pub fn token_matches(posted: &str, expected: &str) -> bool {
|
||||
!expected.is_empty()
|
||||
&& posted.len() == expected.len()
|
||||
&& posted
|
||||
.bytes()
|
||||
.zip(expected.bytes())
|
||||
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
|
||||
== 0
|
||||
}
|
||||
|
||||
/// The server side of the action rules (d04 7.4). The host runs it on every
|
||||
/// POST before it sends a command. The order is CSRF, the offer on this
|
||||
/// surface, the fresh proof, the cookie session, the typed word and then the
|
||||
/// declared params. It returns the validated params. A confirm arm cannot be
|
||||
/// checked on the server: it guards against a mistaken touch and is not
|
||||
/// authentication.
|
||||
pub fn decide(spec: &ActionSpec, submit: &Submit<'_>) -> Result<Params, Refusal> {
|
||||
if !submit.csrf_ok {
|
||||
return Err(Refusal::Csrf);
|
||||
}
|
||||
match spec.proof {
|
||||
Proof::Local => return Err(Refusal::NotOffered),
|
||||
Proof::Fresh if !submit.fresh_proof => return Err(Refusal::ProofRequired),
|
||||
Proof::Console if !submit.cookie_session => return Err(Refusal::Forbidden),
|
||||
Proof::None | Proof::Session | Proof::Fresh | Proof::Console => {}
|
||||
}
|
||||
match &spec.confirm {
|
||||
Confirm::Typed(word) if submit.confirm_word != Some(word.as_str()) => {
|
||||
return Err(Refusal::ConfirmWord)
|
||||
}
|
||||
Confirm::None | Confirm::Arm | Confirm::Typed(_) => {}
|
||||
}
|
||||
check_params(&spec.params, submit.fields)
|
||||
}
|
||||
|
||||
/// Checks the posted params against the declared ones. An undeclared
|
||||
/// `param.` field refuses the request. Every declared param is required. A
|
||||
/// bool takes one value, or the pair a hidden `false` then a checked `true`
|
||||
/// posts (d04 7.2), which reads as `true`. Any other repeat refuses the request
|
||||
/// (422), and any other param takes exactly one value.
|
||||
fn check_params(specs: &[ParamSpec], fields: &[(String, String)]) -> Result<Params, Refusal> {
|
||||
let undeclared = fields.iter().any(|(key, _)| {
|
||||
key.strip_prefix(PARAM_PREFIX)
|
||||
.is_some_and(|name| !specs.iter().any(|spec| spec.name == name))
|
||||
});
|
||||
if undeclared {
|
||||
return Err(Refusal::Param);
|
||||
}
|
||||
let mut params = Params::new();
|
||||
for spec in specs {
|
||||
let key = format!("{PARAM_PREFIX}{}", spec.name);
|
||||
let posted: Vec<&str> = fields
|
||||
.iter()
|
||||
.filter(|(name, _)| *name == key)
|
||||
.map(|(_, value)| value.as_str())
|
||||
.collect();
|
||||
let raw = match (&spec.kind, posted.as_slice()) {
|
||||
(_, [only]) => *only,
|
||||
(Kind::Bool {}, ["false", "true"]) => "true",
|
||||
_ => return Err(Refusal::Param),
|
||||
};
|
||||
let value = param_value(&spec.kind, raw).ok_or(Refusal::Param)?;
|
||||
params.insert(spec.name.clone(), value);
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
/// One posted value as a JSON value of its kind, or None when it is outside the
|
||||
/// kind. The kind's own check runs, and a named string check must pass too.
|
||||
fn param_value(kind: &Kind, raw: &str) -> Option<Value> {
|
||||
let value = match kind {
|
||||
Kind::Bool {} => match raw {
|
||||
"true" => Value::Bool(true),
|
||||
"false" => Value::Bool(false),
|
||||
_ => return None,
|
||||
},
|
||||
Kind::Int { .. } | Kind::IntSet { .. } => Value::from(raw.parse::<i64>().ok()?),
|
||||
Kind::Str { check, .. } => {
|
||||
if let Some(spec) = check {
|
||||
if wschema::checks::run(spec, raw) != Some(true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Value::String(raw.to_string())
|
||||
}
|
||||
Kind::Enum { .. } => Value::String(raw.to_string()),
|
||||
_ => return None,
|
||||
};
|
||||
kind.accepts(&value, &[]).ok()?;
|
||||
Some(value)
|
||||
}
|
||||
|
||||
/// A live action control: one `button` action with the route, CSRF token and
|
||||
/// proof state of one viewer (d04 7.4).
|
||||
#[derive(Clone)]
|
||||
pub struct LiveAction {
|
||||
pub spec: ActionSpec,
|
||||
pub label: String,
|
||||
pub tone: Tone,
|
||||
/// The POST target, `<routes>/{section}/{tab}/actions/{name}`.
|
||||
pub target: String,
|
||||
/// The GET confirm page of this action.
|
||||
pub confirm_url: String,
|
||||
/// The status route of an async action, polled with `?id=` (d04 7.4).
|
||||
pub status_url: String,
|
||||
/// The page the confirm page links back to.
|
||||
pub back: String,
|
||||
/// This surface's proof re-entry route (d05 5.5, `/auth/proof`).
|
||||
pub proof_path: String,
|
||||
/// `password` or `local`: the proof kind the re-entry form posts.
|
||||
pub proof_kind: String,
|
||||
/// The per-session CSRF token. It is never written to logs or identities.
|
||||
pub csrf: String,
|
||||
/// True when the session holds a proof no older than five minutes.
|
||||
pub fresh_proof: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for LiveAction {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("LiveAction")
|
||||
.field("spec", &self.spec)
|
||||
.field("label", &self.label)
|
||||
.field("tone", &self.tone)
|
||||
.field("target", &self.target)
|
||||
.field("confirm_url", &self.confirm_url)
|
||||
.field("status_url", &self.status_url)
|
||||
.field("back", &self.back)
|
||||
.field("proof_path", &self.proof_path)
|
||||
.field("proof_kind", &self.proof_kind)
|
||||
.field("fresh_proof", &self.fresh_proof)
|
||||
.field("csrf", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// How a live action is drawn for its state.
|
||||
enum Shape<'a> {
|
||||
/// A POST form that submits at once.
|
||||
Direct,
|
||||
/// A GET form to the confirm page, which script arms in place.
|
||||
Arm,
|
||||
/// A POST form with a word field; the server checks the word.
|
||||
Typed(&'a str),
|
||||
/// A GET form to the confirm page, which asks for the proof first.
|
||||
Page,
|
||||
}
|
||||
|
||||
impl LiveAction {
|
||||
/// True when the viewer must re-enter a password before the action is sent.
|
||||
pub fn proof_needed(&self) -> bool {
|
||||
self.spec.proof == Proof::Fresh && !self.fresh_proof
|
||||
}
|
||||
|
||||
fn shape(&self) -> Shape<'_> {
|
||||
if self.proof_needed() {
|
||||
return Shape::Page;
|
||||
}
|
||||
match &self.spec.confirm {
|
||||
Confirm::None => Shape::Direct,
|
||||
Confirm::Arm => Shape::Arm,
|
||||
Confirm::Typed(word) => Shape::Typed(word),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The armed label of an arm control. The viewer reads it before the second press.
|
||||
fn armed_text(label: &str) -> String {
|
||||
format!("Confirm: {label}")
|
||||
}
|
||||
|
||||
/// The form fields of the declared params, in schema order. `given` prefills
|
||||
/// them from the query of a confirm page.
|
||||
fn param_fields(params: &[ParamSpec], given: &[(String, String)]) -> Markup {
|
||||
html! {
|
||||
@for param in params {
|
||||
(param_field(param, given))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One param field. A bool draws the hidden `false` and a checkbox `true` under
|
||||
/// one name, so an unticked box still posts a value without script. A text
|
||||
/// field carries the schema's length cap and its empty rule.
|
||||
fn param_field(param: &ParamSpec, given: &[(String, String)]) -> Markup {
|
||||
let name = format!("{PARAM_PREFIX}{}", param.name);
|
||||
let value = given
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(key, _)| *key == name)
|
||||
.map(|(_, value)| value.as_str());
|
||||
html! {
|
||||
@match ¶m.kind {
|
||||
Kind::Str { max_len, allow_empty, .. } => {
|
||||
@let cap = max_len.map(|m| m.to_string());
|
||||
@let required = !allow_empty.unwrap_or(false);
|
||||
label class="bf-action-field bf-text-body" {
|
||||
(param.name)
|
||||
input class="bf-input" type="text" name=(name) value=[value] maxlength=[cap] autocomplete="off" required[required];
|
||||
}
|
||||
}
|
||||
Kind::Int { lo, hi, step, .. } => {
|
||||
@let step = step.unwrap_or(1);
|
||||
label class="bf-action-field bf-text-body" {
|
||||
(param.name)
|
||||
input class="bf-input" type="number" name=(name) value=[value] min=(lo) max=(hi) step=(step) required;
|
||||
}
|
||||
}
|
||||
Kind::Enum { values, .. } => {
|
||||
label class="bf-action-field bf-text-body" {
|
||||
(param.name)
|
||||
select class="bf-input" name=(name) required {
|
||||
@for item in values {
|
||||
option value=(item.v) selected[value == Some(item.v.as_str())] { (item.label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::IntSet { values } => {
|
||||
label class="bf-action-field bf-text-body" {
|
||||
(param.name)
|
||||
select class="bf-input" name=(name) required {
|
||||
@for item in values {
|
||||
@let key = item.v.to_string();
|
||||
@let text = item.label.clone().unwrap_or_else(|| key.clone());
|
||||
option value=(key) selected[value == Some(key.as_str())] { (text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::Bool {} => {
|
||||
label class="bf-action-field bf-text-body" {
|
||||
input type="hidden" name=(name) value="false";
|
||||
input type="checkbox" name=(name) value="true" checked[value == Some("true")];
|
||||
" " (param.name)
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The live control of one action. Its shape follows the confirm and proof
|
||||
/// rules: a POST that submits at once, an arm form that opens the confirm page
|
||||
/// without script, an inline typed word, or a link to the confirm page while a
|
||||
/// fresh proof is missing. The POST forms carry `hx-post`, so script swaps the
|
||||
/// reply in place. Without script they post and the host redirects. The param
|
||||
/// fields sit inside the form that submits them, so the arm's second press posts
|
||||
/// them with the token.
|
||||
pub fn live_control(action: &LiveAction) -> Markup {
|
||||
let tone = action.tone.class();
|
||||
match action.shape() {
|
||||
Shape::Direct => html! {
|
||||
form class="bf-action" method="post" action=(action.target) hx-post=(action.target) hx-swap="outerHTML" data-action=(action.spec.id) {
|
||||
input type="hidden" name="csrf" value=(action.csrf);
|
||||
(param_fields(&action.spec.params, &[]))
|
||||
button type="submit" class=(tone) { (action.label) }
|
||||
}
|
||||
},
|
||||
Shape::Arm => html! {
|
||||
form class="bf-action" method="get" action=(action.confirm_url) data-action=(action.spec.id) data-confirm="arm" data-target=(action.target) data-csrf=(action.csrf) data-armed-text=(armed_text(&action.label)) {
|
||||
(param_fields(&action.spec.params, &[]))
|
||||
button type="submit" class=(tone) { (action.label) }
|
||||
}
|
||||
},
|
||||
Shape::Typed(word) => html! {
|
||||
form class="bf-action" method="post" action=(action.target) hx-post=(action.target) hx-swap="outerHTML" data-action=(action.spec.id) data-confirm="typed" data-word=(word) {
|
||||
input type="hidden" name="csrf" value=(action.csrf);
|
||||
(param_fields(&action.spec.params, &[]))
|
||||
label class="bf-action-field bf-text-body" {
|
||||
"Type " (word) " to confirm"
|
||||
input class="bf-input" type="text" name="confirm_word" autocomplete="off" required;
|
||||
}
|
||||
button type="submit" class=(tone) { (action.label) }
|
||||
}
|
||||
},
|
||||
Shape::Page => html! {
|
||||
form class="bf-action" method="get" action=(action.confirm_url) data-action=(action.spec.id) data-confirm="page" {
|
||||
button type="submit" class=(tone) { (action.label) }
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The confirm page of one action. It shows the proof prompt while a fresh
|
||||
/// proof is missing, and otherwise the POST form, with the word field when the
|
||||
/// rule has one and a field per param. `given` prefills the params from the
|
||||
/// query the arm form sent. It is the no-script path of the arm and typed rules.
|
||||
pub fn confirm_page(action: &LiveAction) -> Markup {
|
||||
confirm_page_with(action, &[])
|
||||
}
|
||||
|
||||
/// [`confirm_page`] with its params prefilled from `given`, the query of an arm form.
|
||||
pub fn confirm_page_with(action: &LiveAction, given: &[(String, String)]) -> Markup {
|
||||
html! {
|
||||
section class="bf-card" data-action-confirm=(action.spec.id) {
|
||||
p class="bf-text-label" { "Confirm action" }
|
||||
h3 class="bf-card-title bf-text-h3" { (action.label) }
|
||||
@if action.proof_needed() {
|
||||
(proof_prompt(action))
|
||||
} @else {
|
||||
form class="bf-action" method="post" action=(action.target) {
|
||||
input type="hidden" name="csrf" value=(action.csrf);
|
||||
(param_fields(&action.spec.params, given))
|
||||
@if let Confirm::Typed(word) = &action.spec.confirm {
|
||||
label class="bf-action-field bf-text-body" {
|
||||
"Type " (word) " to confirm"
|
||||
input class="bf-input" type="text" name="confirm_word" autocomplete="off" required;
|
||||
}
|
||||
}
|
||||
button type="submit" class=(action.tone.class()) { (action.label) }
|
||||
}
|
||||
}
|
||||
p class="bf-note bf-text-body" { a href=(action.back) { "Back to the page" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The re-entry prompt of a fresh proof (d05 10.4). It posts the password to
|
||||
/// this surface's proof route. A viewer without script also posts `next`, the
|
||||
/// confirm page, which returns them there (AM-UI5-4, ruling Q6). The field sits
|
||||
/// in a `noscript` element: with script on, the browser keeps it as raw text, so
|
||||
/// the form never carries `next` for a script client.
|
||||
pub fn proof_prompt(action: &LiveAction) -> Markup {
|
||||
html! {
|
||||
form class="bf-action-proof" method="post" action=(action.proof_path) {
|
||||
input type="hidden" name="csrf" value=(action.csrf);
|
||||
input type="hidden" name="kind" value=(action.proof_kind);
|
||||
noscript {
|
||||
input type="hidden" name="next" value=(action.confirm_url);
|
||||
}
|
||||
p class="bf-action-confirm bf-text-body" { "The proof lasts five minutes." }
|
||||
label class="bf-action-field bf-text-body" {
|
||||
"Password"
|
||||
input class="bf-input" type="password" name="value" autocomplete="current-password" required;
|
||||
}
|
||||
button type="submit" class="bf-btn bf-btn-primary bf-text-button" { "Confirm password" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The plate that answers a refused action. A missing proof adds the re-entry
|
||||
/// prompt, and a wrong typed word or a bad param draws the control again, so the
|
||||
/// viewer can retry on the same page. Pass `None` when no control is at hand.
|
||||
pub fn refusal_plate(refusal: Refusal, action: Option<&LiveAction>) -> Markup {
|
||||
let extra = match (refusal, action) {
|
||||
(Refusal::ProofRequired | Refusal::ProofInvalid, Some(a)) => proof_prompt(a),
|
||||
(Refusal::ConfirmWord | Refusal::Param, Some(a)) => live_control(a),
|
||||
_ => html! {},
|
||||
};
|
||||
html! {
|
||||
p class="bf-plate-message bf-text-body" role="alert" { (refusal.message()) }
|
||||
(extra)
|
||||
}
|
||||
}
|
||||
|
||||
/// The status line of an async action, which answered `202` with an id.
|
||||
/// Script updates it from the `act` event with the same id, or polls the
|
||||
/// status route every two seconds. Returns `None` for an id or status route
|
||||
/// that is not safe to draw.
|
||||
pub fn pending_plate(id: &str, status_url: &str) -> Option<Markup> {
|
||||
if !id_ok(id) || !safe_target(status_url) {
|
||||
return None;
|
||||
}
|
||||
Some(html! {
|
||||
p class="bf-plate-message bf-text-body" role="status" data-action-id=(id) data-status-url=(status_url) { "Running" }
|
||||
})
|
||||
}
|
||||
|
||||
+53
-1
@@ -16,9 +16,20 @@ pub const ISLANDS_JS: &str = include_str!("../assets/js/islands.js");
|
||||
/// Page glue: stream, stale marker, charts, table sort, htmx CSRF header.
|
||||
pub const BOOT_JS: &str = include_str!("../assets/js/boot.js");
|
||||
|
||||
/// Live action controls: the arm confirm, the typed word gate, the async status
|
||||
/// and the htmx error swap (d04 7.4). A page that draws live actions loads it.
|
||||
pub const ACTIONS_JS: &str = include_str!("../assets/js/actions.js");
|
||||
|
||||
/// Chart island and reading glue (draws series, writes pushed values).
|
||||
pub const CHART_JS: &str = include_str!("../assets/js/chart.js");
|
||||
|
||||
/// Named page events, bounded HTML updates and snapshot resync.
|
||||
pub const PAGE_LIVE_JS: &str = include_str!("../assets/js/page-live.js");
|
||||
|
||||
/// Shared request owner and the page-side private port bridge.
|
||||
pub const PAGE_OWNER_WORKER_JS: &str = include_str!("../assets/js/page-owner-worker.js");
|
||||
pub const PAGE_OWNER_JS: &str = include_str!("../assets/js/page-owner.js");
|
||||
|
||||
/// Browsers cap plain HTTP/1.1 connections per origin at 6. One is kept free
|
||||
/// for page loads and API calls, so at most 5 SSE streams per page.
|
||||
pub const PLAIN_HTTP_SSE_BUDGET: usize = 5;
|
||||
@@ -105,7 +116,11 @@ pub fn lint(
|
||||
/// The crate's own scripts never use a secure-context-only API.
|
||||
pub fn builtin_script(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"actions.js" => Some(ACTIONS_JS),
|
||||
"live.js" => Some(LIVE_JS),
|
||||
"page-live.js" => Some(PAGE_LIVE_JS),
|
||||
"page-owner.js" => Some(PAGE_OWNER_JS),
|
||||
"page-owner-worker.js" => Some(PAGE_OWNER_WORKER_JS),
|
||||
"islands.js" => Some(ISLANDS_JS),
|
||||
"chart.js" => Some(CHART_JS),
|
||||
"boot.js" => Some(BOOT_JS),
|
||||
@@ -136,19 +151,56 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn builtin_scripts_pass_plain_http_lint() {
|
||||
let a = pa(&["live.js", "islands.js", "chart.js", "boot.js"], 5);
|
||||
let a = pa(
|
||||
&[
|
||||
"actions.js",
|
||||
"live.js",
|
||||
"page-live.js",
|
||||
"page-owner.js",
|
||||
"page-owner-worker.js",
|
||||
"islands.js",
|
||||
"chart.js",
|
||||
"boot.js",
|
||||
],
|
||||
5,
|
||||
);
|
||||
let f = lint(&a, Delivery::PlainHttp, &|s| {
|
||||
builtin_script(s).map(String::from)
|
||||
});
|
||||
assert!(f.is_empty(), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actions_script_is_registered_and_linted() {
|
||||
// The lint skips unknown scripts, so a registered name must resolve to the
|
||||
// real file, and the file must be scanned for secure-only APIs.
|
||||
assert_eq!(builtin_script("actions.js"), Some(ACTIONS_JS));
|
||||
assert!(ACTIONS_JS.is_ascii());
|
||||
assert!(ACTIONS_JS.contains("FlareActions"));
|
||||
let a = pa(&["actions.js"], 0);
|
||||
let src = |s: &str| builtin_script(s).map(String::from);
|
||||
assert!(lint(&a, Delivery::PlainHttp, &src).is_empty());
|
||||
let probe = |_: &str| Some("navigator.clipboard.writeText(1)".to_string());
|
||||
assert_eq!(
|
||||
lint(&a, Delivery::PlainHttp, &probe),
|
||||
vec![Finding::SecureOnlyApi {
|
||||
script: "actions.js".into(),
|
||||
api: "navigator.clipboard"
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_script_is_ascii_and_exports() {
|
||||
assert!(BOOT_JS.is_ascii());
|
||||
assert!(BOOT_JS.contains("FlareBoot"));
|
||||
assert!(CHART_JS.is_ascii());
|
||||
assert!(CHART_JS.contains("FlareChart"));
|
||||
assert!(PAGE_LIVE_JS.is_ascii());
|
||||
assert!(PAGE_LIVE_JS.contains("FlarePageLive"));
|
||||
assert!(PAGE_OWNER_JS.is_ascii());
|
||||
assert!(PAGE_OWNER_WORKER_JS.is_ascii());
|
||||
assert!(PAGE_OWNER_JS.contains("FlarePageOwner"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+13
-1
@@ -141,6 +141,16 @@ impl Chart {
|
||||
/// `path` is the canonical page path without a query or fragment.
|
||||
/// Tier changes remain normal links when JavaScript is unavailable.
|
||||
pub fn render(&self, path: &str) -> Result<Markup, Error> {
|
||||
self.render_with_latest(path, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// As [`Chart::render`], with the latest value of each series as text in
|
||||
/// the accessible table. A series without such text shows its last point.
|
||||
pub fn render_with_latest(
|
||||
&self,
|
||||
path: &str,
|
||||
latest: &BTreeMap<String, String>,
|
||||
) -> Result<Markup, Error> {
|
||||
if !path.starts_with('/')
|
||||
|| path.starts_with("//")
|
||||
|| path
|
||||
@@ -168,7 +178,9 @@ impl Chart {
|
||||
tr {
|
||||
th scope="row" { (series.label) }
|
||||
td data-chart-value=(series.key) {
|
||||
@if let Some((_, value)) = self.points.get(&series.key).and_then(|p| p.last()) {
|
||||
@if let Some(latest_text) = latest.get(&series.key) {
|
||||
(latest_text)
|
||||
} @else if let Some((_, value)) = self.points.get(&series.key).and_then(|p| p.last()) {
|
||||
(value)
|
||||
} @else { "--" }
|
||||
" " (series.unit)
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
//! Ordered native form values for scalar settings.
|
||||
//!
|
||||
//! The host selects fields from its authorized form state, bounds the HTTP body,
|
||||
//! and preserves repeated names while parsing it. Decoding does not authorize a
|
||||
//! write: refresh grants, check CSRF and the configuration revision, compare the
|
||||
//! rendered baseline, and run `wschema::validate_batch` before committing.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
use wschema::{Effective, Kind, Op};
|
||||
|
||||
/// Host-selected bounds, applied before copying submitted values.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub max_fields: usize,
|
||||
/// Combined UTF-8 bytes of submitted names and values, after form decoding.
|
||||
pub max_bytes: usize,
|
||||
}
|
||||
|
||||
/// Failure reasons contain no submitted values, including secret values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Code {
|
||||
Limit,
|
||||
Field,
|
||||
Missing,
|
||||
Repeated,
|
||||
Invalid,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Error {
|
||||
/// Absent for a whole-body limit failure.
|
||||
pub path: Option<String>,
|
||||
pub code: Code,
|
||||
}
|
||||
|
||||
fn error(path: &str, code: Code) -> Error {
|
||||
Error {
|
||||
path: Some(path.to_owned()),
|
||||
code,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn definitions<'schema, 'path>(
|
||||
schema: &'schema Effective,
|
||||
fields: impl IntoIterator<Item = &'path str>,
|
||||
) -> BTreeMap<&'path str, Option<&'schema wschema::model::Setting>> {
|
||||
let mut definitions: BTreeMap<_, _> = fields.into_iter().map(|path| (path, None)).collect();
|
||||
for setting in &schema.doc.settings {
|
||||
if setting.path.contains('*') {
|
||||
// Preserve Effective::setting precedence before refusing map fields.
|
||||
for (&path, found) in &mut definitions {
|
||||
if found.is_none() && wschema::path::matches(&setting.path, path) {
|
||||
*found = Some(setting);
|
||||
}
|
||||
}
|
||||
} else if let Some(found) = definitions.get_mut(setting.path.as_str()) {
|
||||
found.get_or_insert(setting);
|
||||
}
|
||||
}
|
||||
definitions
|
||||
}
|
||||
|
||||
/// Decode one complete selection of native scalar controls.
|
||||
///
|
||||
/// `fields` comes from the host's rendered form state, never the submitted body.
|
||||
/// Pass only setting pairs after separately checking reserved fields such as
|
||||
/// CSRF. Unknown, missing and duplicate scalar names fail the whole decode.
|
||||
/// A switch accepts exactly `false` or ordered `false,true`. Empty secret input
|
||||
/// produces no operation. No input produces `Op::Reset`.
|
||||
///
|
||||
/// Lists, wildcard settings and action-backed writes need separate contracts and
|
||||
/// return `Unsupported`. Kind bounds and membership are checked here; named,
|
||||
/// group, permission and cross-field checks still require `validate_batch`.
|
||||
pub fn decode(
|
||||
schema: &Effective,
|
||||
fields: &[&str],
|
||||
pairs: &[(&str, &str)],
|
||||
limits: Limits,
|
||||
) -> Result<Vec<Op>, Error> {
|
||||
let limit = || Error {
|
||||
path: None,
|
||||
code: Code::Limit,
|
||||
};
|
||||
if fields.len() > limits.max_fields || pairs.len() > fields.len().saturating_mul(2) {
|
||||
return Err(limit());
|
||||
}
|
||||
let mut bytes = 0usize;
|
||||
for (name, value) in pairs {
|
||||
bytes = bytes
|
||||
.checked_add(name.len())
|
||||
.and_then(|sum| sum.checked_add(value.len()))
|
||||
.filter(|sum| *sum <= limits.max_bytes)
|
||||
.ok_or_else(limit)?;
|
||||
}
|
||||
let definitions = definitions(schema, fields.iter().copied());
|
||||
let mut selected = BTreeMap::new();
|
||||
for &path in fields {
|
||||
if wschema::path::path_problem(path, false).is_some() {
|
||||
return Err(error(path, Code::Field));
|
||||
}
|
||||
let setting = definitions[path].ok_or_else(|| error(path, Code::Field))?;
|
||||
if setting.path.contains('*')
|
||||
|| setting.hidden == Some(true)
|
||||
|| setting.write_via.is_some()
|
||||
|| setting.secret_upload == Some(true)
|
||||
|| matches!(setting.kind, Kind::List { .. })
|
||||
{
|
||||
return Err(error(path, Code::Unsupported));
|
||||
}
|
||||
if selected.insert(path, (setting, Vec::new())).is_some() {
|
||||
return Err(error(path, Code::Repeated));
|
||||
}
|
||||
}
|
||||
for &(name, value) in pairs {
|
||||
let (setting, values) = selected
|
||||
.get_mut(name)
|
||||
.ok_or_else(|| error(name, Code::Field))?;
|
||||
let cap = if matches!(setting.kind, Kind::Bool {}) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
if values.len() == cap {
|
||||
return Err(error(name, Code::Repeated));
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
let vocabs = schema.vocabs();
|
||||
let mut ops = Vec::with_capacity(fields.len());
|
||||
for &path in fields {
|
||||
let (setting, values) = &selected[path];
|
||||
if values.is_empty() {
|
||||
return Err(error(path, Code::Missing));
|
||||
}
|
||||
let value = match &setting.kind {
|
||||
Kind::Bool {} => match values.as_slice() {
|
||||
["false"] => Value::Bool(false),
|
||||
["false", "true"] => Value::Bool(true),
|
||||
_ => return Err(error(path, Code::Invalid)),
|
||||
},
|
||||
Kind::Secret { .. } if values[0].is_empty() => continue,
|
||||
Kind::Int { .. } | Kind::IntSet { .. } => {
|
||||
let raw = values[0];
|
||||
let digits = raw.strip_prefix('-').unwrap_or(raw);
|
||||
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(error(path, Code::Invalid));
|
||||
}
|
||||
let number = raw.parse::<i64>().map_err(|_| error(path, Code::Invalid))?;
|
||||
Value::from(number)
|
||||
}
|
||||
Kind::Str { .. } | Kind::Enum { .. } | Kind::Secret { .. } => {
|
||||
Value::String(values[0].to_owned())
|
||||
}
|
||||
Kind::List { .. } => return Err(error(path, Code::Unsupported)),
|
||||
};
|
||||
setting
|
||||
.kind
|
||||
.accepts(&value, &vocabs)
|
||||
.map_err(|_| error(path, Code::Invalid))?;
|
||||
ops.push(Op::Set {
|
||||
path: path.to_owned(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
Ok(ops)
|
||||
}
|
||||
+7
-1
@@ -6,12 +6,15 @@
|
||||
//! - [`url`]: URL builders for the console and FLARE route tables, and the
|
||||
//! closed query-parameter set (d04 sections 4.2, 4.3).
|
||||
//! - [`components`]: maud components that emit only allowlisted classes.
|
||||
//! - [`actions`]: action buttons and approval lists (htmx upgrade over plain forms).
|
||||
//! - [`actions`]: action buttons, live action controls with their confirm and
|
||||
//! proof rules (d04 7.4), and approval lists (htmx upgrade over plain forms).
|
||||
//! - [`assets`]: page asset declarations, head tags and the plain-HTTP lint.
|
||||
//! - [`live`]: the SSE client script (ring, caps, reconnect, stale marker).
|
||||
//! - [`readings`]: live reading and block renderers.
|
||||
//! - [`page`]: authorized read-only schema pages and matching OOB fragments.
|
||||
//! - [`chart`]: typed chart props, tier links and latest-value fallback.
|
||||
//! - [`render`]: renders schema settings by display type and validates forms.
|
||||
//! - [`form`]: decodes ordered native form values for host-selected scalar fields.
|
||||
//! - [`shell`]: page shell (sidebar, tab strip, main area).
|
||||
//! - [`tokens`]: design tokens stylesheet and the CSS class allowlist.
|
||||
//! - [`resolve`]: maps a request path to a route, with canonical redirects
|
||||
@@ -26,13 +29,16 @@ pub mod assets;
|
||||
pub mod chart;
|
||||
pub mod components;
|
||||
pub mod display_types;
|
||||
pub mod form;
|
||||
pub mod live;
|
||||
pub mod nav;
|
||||
pub mod page;
|
||||
pub mod readings;
|
||||
pub mod render;
|
||||
pub mod resolve;
|
||||
pub mod shell;
|
||||
pub mod studio;
|
||||
pub mod table;
|
||||
pub mod tokens;
|
||||
pub mod url;
|
||||
|
||||
|
||||
+1775
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,596 @@
|
||||
//! Bounded, read-only settings cards. Writable forms need host form state.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::{json, Value};
|
||||
use wschema::model::{Block, Display, Kind, Owner, Setting, Surface};
|
||||
use wschema::Rows;
|
||||
|
||||
use super::{bounded, path_ok, text, visible, Error, RenderCx, Unsupported, MAX_BLOCKS, MAX_CELLS};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Field {
|
||||
markup: Markup,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Card {
|
||||
pub body: Markup,
|
||||
pub layout: Vec<Value>,
|
||||
pub unsupported: Vec<Unsupported>,
|
||||
/// Enabled `write_via` actions drawn as live controls, for the page's
|
||||
/// action lookup (the route an action POST resolves against).
|
||||
pub live: Vec<crate::actions::LiveAction>,
|
||||
/// `write_via` actions this viewer may not run, for the page's denied set (d04 7.5).
|
||||
pub denied: BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn allowed(
|
||||
setting: &Setting,
|
||||
cx: &RenderCx<'_>,
|
||||
denied: &mut BTreeSet<String>,
|
||||
) -> Result<bool, Error> {
|
||||
let read = setting
|
||||
.perm
|
||||
.as_ref()
|
||||
.and_then(|p| p.read.as_deref())
|
||||
.unwrap_or("site.read");
|
||||
if read.is_empty() || read.len() > 256 || setting.owner == Owner::Escrow {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
if setting.hidden == Some(true)
|
||||
|| !setting.surfaces.as_ref().map_or_else(
|
||||
|| setting.owner != Owner::DeviceOnly || cx.surface != Surface::Flare,
|
||||
|surfaces| surfaces.contains(&cx.surface),
|
||||
)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
if !cx.principal.can(read) {
|
||||
// d04 7.5: the write_via action of a setting the viewer may not read answers 403.
|
||||
if let Some(action_id) = setting.write_via.as_deref() {
|
||||
super::deny_action_id(cx, action_id, denied);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
// A map entry whose visibility names a map path cannot be evaluated by a
|
||||
// card, because the path has no entry key here. Such an entry is left to
|
||||
// the dynamic-path check, which reports it unsupported. It is not a schema
|
||||
// error: the document is valid.
|
||||
if setting.path.contains('*') && setting.visible_when.as_ref().is_some_and(names_map_path) {
|
||||
return Ok(true);
|
||||
}
|
||||
condition(&setting.visible_when, cx)
|
||||
}
|
||||
|
||||
/// True when a visibility expression names a path with a wildcard.
|
||||
fn names_map_path(expr: &Value) -> bool {
|
||||
match expr {
|
||||
Value::String(text) => text.contains('*'),
|
||||
Value::Array(items) => items.iter().any(names_map_path),
|
||||
Value::Object(map) => map.values().any(names_map_path),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn condition(expr: &Option<Value>, cx: &RenderCx<'_>) -> Result<bool, Error> {
|
||||
match expr {
|
||||
None => Ok(true),
|
||||
Some(expr) => {
|
||||
let mut budget = MAX_BLOCKS;
|
||||
Ok(visible(cx, expr, 1, &mut budget)? == Some(true))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn display(setting: &Setting, surface: Surface) -> Result<Display, Error> {
|
||||
let mut display = setting.display.clone();
|
||||
let surface = match surface {
|
||||
Surface::Panel => "panel",
|
||||
Surface::Web => "web",
|
||||
Surface::Flare => "flare",
|
||||
};
|
||||
if let Some(value) = setting.display_by.as_ref().and_then(|by| by.get(surface)) {
|
||||
for (key, value) in value.as_object().ok_or(Error::InvalidSchema)? {
|
||||
if key == "t" {
|
||||
display.t = value.as_str().ok_or(Error::InvalidSchema)?.into();
|
||||
} else {
|
||||
display.params.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(display)
|
||||
}
|
||||
|
||||
fn supported(setting: &Setting) -> bool {
|
||||
if setting.write_via.is_some() {
|
||||
return false;
|
||||
}
|
||||
// P-09: an id outside the registry draws its kind's plain control, marked
|
||||
// degraded (render::field). Its params are not read, so they do not block it.
|
||||
if wschema::display::find(&setting.display.t).is_none() {
|
||||
return true;
|
||||
}
|
||||
if !setting.display.params.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// A registry display binds only the kinds of the d02 display table, which
|
||||
// wschema lint (display_legal) enforces too. Swatch is an enum display.
|
||||
matches!(
|
||||
(&setting.kind, setting.display.t.as_str()),
|
||||
(Kind::Str { .. }, "text")
|
||||
| (Kind::Secret { .. }, "secret")
|
||||
| (
|
||||
Kind::Enum { .. } | Kind::IntSet { .. },
|
||||
"dropdown" | "segmented"
|
||||
)
|
||||
| (Kind::Enum { .. }, "swatch")
|
||||
| (Kind::Bool {}, "switch")
|
||||
| (Kind::Int { .. }, "slider" | "stepper" | "number")
|
||||
| (Kind::List { .. }, "list")
|
||||
)
|
||||
}
|
||||
|
||||
fn choices(setting: &Setting, cx: &RenderCx<'_>) -> Result<(), Error> {
|
||||
let mut options = Vec::new();
|
||||
match &setting.kind {
|
||||
Kind::Enum { values, vocab } => {
|
||||
if let Some(id) = vocab {
|
||||
if !values.is_empty() {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
let vocab = cx.schema.vocab(id).ok_or(Error::InvalidSchema)?;
|
||||
if vocab.values.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for value in &vocab.values {
|
||||
text(&value.v)?;
|
||||
text(&value.label)?;
|
||||
}
|
||||
options.extend(vocab.values.iter().map(|v| (v.v.clone(), v.label.as_str())));
|
||||
} else {
|
||||
if values.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for value in values {
|
||||
text(&value.v)?;
|
||||
text(&value.label)?;
|
||||
}
|
||||
options.extend(values.iter().map(|v| (v.v.clone(), v.label.as_str())));
|
||||
}
|
||||
}
|
||||
Kind::IntSet { values } => {
|
||||
if values.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for value in values {
|
||||
exact(value.v)?;
|
||||
options.push((value.v.to_string(), value.label.as_deref().unwrap_or("")));
|
||||
}
|
||||
}
|
||||
_ => return Ok(()),
|
||||
}
|
||||
if options.is_empty() || options.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
if setting.display.t == "segmented" && options.len() > 4 {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for (value, label) in options {
|
||||
text(&value)?;
|
||||
text(label)?;
|
||||
if !seen.insert(value) {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exact(value: i64) -> Result<(), Error> {
|
||||
if value.unsigned_abs() > super::MAX_SEQUENCE {
|
||||
Err(Error::Limit)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn value_bounded(value: &Value) -> Result<(), Error> {
|
||||
match value {
|
||||
Value::String(value) => text(value),
|
||||
Value::Array(values) => {
|
||||
if values.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for value in values {
|
||||
if let Value::String(value) = value {
|
||||
text(value)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::Number(value) => {
|
||||
if let Some(value) = value.as_i64() {
|
||||
exact(value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn status(setting: &Setting, value: &str) -> Markup {
|
||||
html! {
|
||||
div class="bf-field" data-path=(setting.path) data-degraded=[crate::render::degraded_display(setting)] {
|
||||
span class="bf-field-label bf-text-label" { (setting.label) }
|
||||
p class="bf-text-body" { (value) }
|
||||
@if !setting.help.is_empty() {
|
||||
p class="bf-field-help bf-text-body-sm" { (setting.help) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn secret(setting: &Setting, cx: &RenderCx<'_>) -> Result<Markup, Error> {
|
||||
let value = match cx.values.secret_metadata(setting) {
|
||||
None => "Status unavailable".into(),
|
||||
Some(meta) => {
|
||||
text(&meta.t)?;
|
||||
if !meta.fp.is_empty()
|
||||
&& (meta.fp.len() != 16 || !meta.fp.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
{
|
||||
"Status unavailable".into()
|
||||
} else if meta.set {
|
||||
if meta.fp.is_empty() {
|
||||
"Set".into()
|
||||
} else {
|
||||
format!("Set ({})", meta.fp)
|
||||
}
|
||||
} else {
|
||||
"Not set".into()
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(html! {
|
||||
(status(setting, &value))
|
||||
@if setting.owner == Owner::FlareOnly && cx.surface != Surface::Flare {
|
||||
p class="bf-field-help bf-text-body-sm" { "Managed by FLARE" }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_shape(setting: &Setting, cx: &RenderCx<'_>) -> Result<(), Error> {
|
||||
text(&setting.label)?;
|
||||
text(&setting.help)?;
|
||||
choices(setting, cx)?;
|
||||
if let Kind::Int {
|
||||
lo,
|
||||
hi,
|
||||
step,
|
||||
units,
|
||||
} = &setting.kind
|
||||
{
|
||||
exact(*lo)?;
|
||||
exact(*hi)?;
|
||||
exact(step.unwrap_or(1))?;
|
||||
if lo > hi || step.is_some_and(|step| step <= 0) {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
text(units.as_deref().unwrap_or(""))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn field(setting: &Setting, cx: &RenderCx<'_>) -> Result<Field, Error> {
|
||||
validate_shape(setting, cx)?;
|
||||
let enabled = condition(&setting.enabled_when, cx)?;
|
||||
let markup = if matches!(setting.kind, Kind::Secret { .. }) {
|
||||
secret(setting, cx)?
|
||||
} else {
|
||||
let unit = if let Kind::Int { units, .. } = &setting.kind {
|
||||
units.as_deref().unwrap_or("")
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let value = cx
|
||||
.values
|
||||
.setting(&setting.path)
|
||||
.or(setting.default.value.as_ref());
|
||||
if let Some(value) = value {
|
||||
value_bounded(value)?;
|
||||
}
|
||||
if let Some(value) = value.filter(|v| setting.kind.accepts(v, &cx.schema.vocabs()).is_ok())
|
||||
{
|
||||
let rows: Rows = [(setting.path.clone(), value.clone())].into();
|
||||
let errors = BTreeMap::new();
|
||||
let mut shown = setting.clone();
|
||||
let detail = if setting.display.t == "slider" {
|
||||
let suffix = if unit.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {unit}")
|
||||
};
|
||||
format!("Current value: {value}{suffix}.")
|
||||
} else if !unit.is_empty() {
|
||||
format!("Unit: {unit}.")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
if !detail.is_empty() {
|
||||
if !shown.help.is_empty() {
|
||||
shown.help.push(' ');
|
||||
}
|
||||
shown.help.push_str(&detail);
|
||||
text(&shown.help)?;
|
||||
}
|
||||
crate::render::field(
|
||||
&shown,
|
||||
&setting.path,
|
||||
&crate::render::View {
|
||||
eff: cx.schema,
|
||||
rows: &rows,
|
||||
errors: &errors,
|
||||
surface: cx.surface,
|
||||
can_write: false,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
status(setting, "Value unavailable")
|
||||
}
|
||||
};
|
||||
Ok(Field {
|
||||
markup: bounded(markup)?,
|
||||
enabled,
|
||||
})
|
||||
}
|
||||
|
||||
/// Compiles one card or fields block. The `write_via` actions this viewer may not
|
||||
/// run are returned in `Card::denied`, so their routes answer 403 (d04 7.5).
|
||||
pub(super) fn compile(
|
||||
block: &Block,
|
||||
cx: &RenderCx<'_>,
|
||||
path: &str,
|
||||
cache: &mut BTreeMap<String, Field>,
|
||||
count: &mut usize,
|
||||
form: Option<&super::FormState>,
|
||||
actions: Option<&super::ActionCx<'_>>,
|
||||
) -> Result<Card, Error> {
|
||||
let mut card = Card {
|
||||
body: html! {},
|
||||
layout: Vec::new(),
|
||||
unsupported: Vec::new(),
|
||||
live: Vec::new(),
|
||||
denied: BTreeSet::new(),
|
||||
};
|
||||
let unsupported = |kind: &str| Unsupported {
|
||||
path: path.into(),
|
||||
kind: kind.into(),
|
||||
};
|
||||
if block.section.is_some() != block.items.is_empty()
|
||||
|| !block.readings.is_empty()
|
||||
|| block.reading.is_some()
|
||||
|| block.columns.is_some()
|
||||
|| block.series.is_some()
|
||||
|| block.sort.is_some()
|
||||
|| block.source.is_some()
|
||||
|| !block.actions.is_empty()
|
||||
|| block.text.is_some()
|
||||
|| block.format.is_some()
|
||||
|| block.escape.is_some()
|
||||
{
|
||||
card.unsupported.push(unsupported("card members"));
|
||||
return Ok(card);
|
||||
}
|
||||
let mut definitions = Vec::new();
|
||||
if let Some(section) = &block.section {
|
||||
path_ok(section)?;
|
||||
definitions.extend(
|
||||
cx.schema
|
||||
.doc
|
||||
.settings
|
||||
.iter()
|
||||
.filter(|s| &s.section == section),
|
||||
);
|
||||
definitions.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.path.cmp(&b.path)));
|
||||
} else {
|
||||
if block.items.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for item in &block.items {
|
||||
if item.contains('*') {
|
||||
card.unsupported.push(unsupported("dynamic setting path"));
|
||||
continue;
|
||||
}
|
||||
path_ok(item)?;
|
||||
let setting = cx.schema.setting(item).ok_or(Error::InvalidSchema)?;
|
||||
definitions.push(setting);
|
||||
}
|
||||
}
|
||||
if definitions.is_empty() {
|
||||
card.unsupported.push(unsupported("empty card"));
|
||||
return Ok(card);
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut writable_paths = BTreeSet::new();
|
||||
let mut fields = Vec::new();
|
||||
let mut after_form = Vec::new();
|
||||
for definition in definitions {
|
||||
if !seen.insert(&definition.path) {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
if !allowed(definition, cx, &mut card.denied)? {
|
||||
continue;
|
||||
}
|
||||
if definition.path.contains('*') {
|
||||
card.unsupported.push(unsupported("dynamic setting path"));
|
||||
continue;
|
||||
}
|
||||
path_ok(&definition.path)?;
|
||||
if let Some(action_id) = definition.write_via.as_deref() {
|
||||
// A write_via setting is drawn as its action (d04 7.2). The action's display
|
||||
// decides the control, as in a buttons block: an unknown display is a live
|
||||
// plain button with a scope and the disabled one without (P-09), and a known
|
||||
// `button` display needs a scope.
|
||||
let mut matching = cx.schema.doc.actions.iter().filter(|a| a.id == action_id);
|
||||
let action = matching.next();
|
||||
if matching.next().is_some() {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
let Some(action) = action else {
|
||||
card.unsupported.push(unsupported("unknown action"));
|
||||
continue;
|
||||
};
|
||||
if action
|
||||
.surfaces
|
||||
.as_ref()
|
||||
.is_some_and(|surfaces| !surfaces.contains(&cx.surface))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !cx.principal.can(super::action_permission(&action.perm)?) {
|
||||
// d04 7.5: the route of a denied write_via action answers 403 with the plate.
|
||||
super::deny_action(cx, action, &mut card.denied);
|
||||
continue;
|
||||
}
|
||||
let unknown = action
|
||||
.display
|
||||
.as_ref()
|
||||
.is_some_and(|display| wschema::display::find(&display.t).is_none());
|
||||
// Physical presence at the panel: the web and FLARE do not offer a local
|
||||
// action, not even as the disabled plain button of an unknown display (d04 7.4).
|
||||
if unknown
|
||||
&& crate::actions::Proof::parse(&action.proof) == Some(crate::actions::Proof::Local)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// enabled_when (d04 7.2) disables the action; it never removes the member.
|
||||
let enabled = condition(&definition.enabled_when, cx)?;
|
||||
// Without a scope an unknown display has no route, so it is the disabled plain
|
||||
// button. With a scope it draws below as a live control (draw_action).
|
||||
let (control, layout) = if unknown && actions.is_none() {
|
||||
text(&action.label)?;
|
||||
(
|
||||
crate::actions::plain_button(&action.id, &action.label),
|
||||
json!([definition.path, "action", action.id, "plain"]),
|
||||
)
|
||||
} else {
|
||||
let Some(actx) = actions else {
|
||||
card.unsupported
|
||||
.push(unsupported("setting display or action"));
|
||||
continue;
|
||||
};
|
||||
let live = match super::draw_action(cx, actx, action)? {
|
||||
super::ActionDrawn::Hidden => continue,
|
||||
super::ActionDrawn::Unsupported(kind) => {
|
||||
card.unsupported.push(unsupported(kind));
|
||||
continue;
|
||||
}
|
||||
super::ActionDrawn::Live(live) => live,
|
||||
};
|
||||
let control = if enabled {
|
||||
crate::actions::live_control(&live)
|
||||
} else {
|
||||
crate::actions::plain_button(&live.spec.id, &live.label)
|
||||
};
|
||||
let layout = json!([
|
||||
definition.path,
|
||||
"action",
|
||||
live.spec.id,
|
||||
live.spec.confirm.spelling(),
|
||||
live.spec.proof.spelling(),
|
||||
live.target,
|
||||
enabled,
|
||||
live.proof_needed()
|
||||
]);
|
||||
if enabled {
|
||||
card.live.push((*live).clone());
|
||||
}
|
||||
(control, layout)
|
||||
};
|
||||
*count += 1;
|
||||
if *count > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
card.layout.push(layout);
|
||||
let member = html! {
|
||||
div class="bf-field" data-path=(definition.path) data-action=(action.id) {
|
||||
span class="bf-field-label bf-text-label" { (definition.label) }
|
||||
(control)
|
||||
@if !definition.help.is_empty() {
|
||||
p class="bf-field-help bf-text-body-sm" { (definition.help) }
|
||||
}
|
||||
}
|
||||
};
|
||||
// A bound card's form holds only its fields: a nested form is invalid HTML.
|
||||
if form.is_some() {
|
||||
after_form.push(member);
|
||||
} else {
|
||||
fields.push(member);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut setting = definition.clone();
|
||||
setting.display = display(&setting, cx.surface)?;
|
||||
if !supported(&setting) {
|
||||
card.unsupported
|
||||
.push(unsupported("setting display or action"));
|
||||
continue;
|
||||
}
|
||||
*count += 1;
|
||||
if *count > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
if let Some(form) = form {
|
||||
// P-09: the bound slice writes no list or secret member. An unknown
|
||||
// display id on a member it refuses draws read-only instead, outside
|
||||
// the writable set; a known id keeps the refusal (page_forms pins it).
|
||||
let form_refused = !super::forms::supported(&setting);
|
||||
if form_refused && crate::render::degraded_display(&setting).is_none() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let enabled = condition(&setting.enabled_when, cx)?;
|
||||
let writable = !form_refused && enabled && super::forms::writable(&setting, cx)?;
|
||||
if writable {
|
||||
validate_shape(&setting, cx)?;
|
||||
let state = form.fields.get(&setting.path).ok_or(Error::InvalidForm)?;
|
||||
writable_paths.insert(setting.path.clone());
|
||||
card.layout.push(json!([
|
||||
setting.path,
|
||||
setting.display,
|
||||
enabled,
|
||||
"writable",
|
||||
state.provenance == super::Provenance::Stored
|
||||
]));
|
||||
fields.push(super::forms::field(&setting, state, cx)?);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !cache.contains_key(&setting.path) {
|
||||
cache.insert(setting.path.clone(), field(&setting, cx)?);
|
||||
}
|
||||
let field = &cache[&setting.path];
|
||||
card.layout
|
||||
.push(json!([setting.path, setting.display, field.enabled]));
|
||||
fields.push(field.markup.clone());
|
||||
}
|
||||
let mut body = bounded(html! { @for field in fields { (field) } })?;
|
||||
if let Some(form) = form {
|
||||
if writable_paths != form.fields.keys().cloned().collect() {
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
card.layout.push(json!([
|
||||
"form",
|
||||
form.page,
|
||||
form.card,
|
||||
form.schema_hash,
|
||||
form.action
|
||||
]));
|
||||
body = form.wrap(body)?;
|
||||
}
|
||||
if !after_form.is_empty() {
|
||||
body = bounded(html! { (body) @for member in after_form { (member) } })?;
|
||||
}
|
||||
card.body = body;
|
||||
Ok(card)
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Host state for an opt-in scalar settings card.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::Value;
|
||||
use wschema::model::{Kind, Owner, Setting, Surface};
|
||||
|
||||
use super::{bounded, text, Error, RenderCx, MAX_CELLS};
|
||||
|
||||
/// Provenance of the rendered setting, supplied by the host's config snapshot.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Provenance {
|
||||
Stored,
|
||||
Default,
|
||||
}
|
||||
|
||||
/// Non-secret display state. The host retains the authorized baseline separately.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldState {
|
||||
pub provenance: Provenance,
|
||||
/// Exact decoded scalar input after a failed save, never a secret value.
|
||||
pub submitted: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// One host-owned form bound to an exact page, card and schema.
|
||||
///
|
||||
/// This state is not deserialized from a request. The host refreshes access and
|
||||
/// supplies it from the same immutable config snapshot as `ValueSource`.
|
||||
/// `revision` is opaque and independent of the event cursor. Keep the rendered
|
||||
/// baseline and recheck CSRF, grants and revision atomically before a commit.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FormState {
|
||||
pub page: String,
|
||||
/// Stable compiler block path, such as `blocks/id/network`.
|
||||
pub card: String,
|
||||
pub schema_hash: String,
|
||||
pub revision: String,
|
||||
/// Origin-relative path. Query strings, fragments and escapes are refused.
|
||||
pub action: String,
|
||||
pub csrf: String,
|
||||
/// Exactly the visible, writable scalar fields in this card. Read-only
|
||||
/// members, including an unknown-display list or secret, are drawn without
|
||||
/// state and must not be named here.
|
||||
pub fields: BTreeMap<String, FieldState>,
|
||||
}
|
||||
|
||||
/// A single explicit native form intent. Neither variant commits a change.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Submission {
|
||||
Save(Vec<wschema::Op>),
|
||||
Reset(wschema::Op),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SubmissionError {
|
||||
Binding,
|
||||
Values(crate::form::Error),
|
||||
UnsupportedInput,
|
||||
}
|
||||
|
||||
impl FormState {
|
||||
pub(super) fn check(&self, page: &str, cx: &RenderCx<'_>) -> Result<(), Error> {
|
||||
for value in [
|
||||
&self.page,
|
||||
&self.card,
|
||||
&self.schema_hash,
|
||||
&self.revision,
|
||||
&self.action,
|
||||
&self.csrf,
|
||||
] {
|
||||
text(value)?;
|
||||
if value.is_empty() || value.chars().any(char::is_control) {
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
}
|
||||
if self.page != page || self.schema_hash != cx.schema.hash || self.fields.is_empty() {
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
if self.fields.len() > MAX_CELLS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
// A closed path grammar avoids browser URL normalization and authority changes.
|
||||
if !self.action.starts_with('/')
|
||||
|| self.action.starts_with("//")
|
||||
|| self
|
||||
.action
|
||||
.split('/')
|
||||
.any(|part| matches!(part, "." | ".."))
|
||||
|| !self
|
||||
.action
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"/-_~.".contains(&b))
|
||||
{
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
for (path, field) in &self.fields {
|
||||
super::path_ok(path)?;
|
||||
for value in [&field.submitted, &field.error].into_iter().flatten() {
|
||||
text(value)?;
|
||||
}
|
||||
if field
|
||||
.submitted
|
||||
.as_deref()
|
||||
.is_some_and(|raw| !single_line(raw))
|
||||
{
|
||||
return Err(Error::UnsupportedInput);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn wrap(&self, body: Markup) -> Result<Markup, Error> {
|
||||
bounded(html! {
|
||||
form method="post" action=(self.action) data-form-card=(self.card) {
|
||||
input type="hidden" name="__bf_page" value=(self.page);
|
||||
input type="hidden" name="__bf_card" value=(self.card);
|
||||
input type="hidden" name="__bf_schema" value=(self.schema_hash);
|
||||
input type="hidden" name="__bf_revision" value=(self.revision);
|
||||
input type="hidden" name="__bf_csrf" value=(self.csrf);
|
||||
// The first submit button also owns native implicit Enter submission.
|
||||
button class="bf-btn bf-btn-primary bf-text-button" type="submit" { "Save" }
|
||||
(body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode a bounded submission against retained host state.
|
||||
/// This checks binding and intent, not CSRF authenticity, current grants or
|
||||
/// atomic revision validity. Recompile with fresh access before committing.
|
||||
pub fn decode(
|
||||
&self,
|
||||
schema: &wschema::Effective,
|
||||
pairs: &[(&str, &str)],
|
||||
limits: crate::form::Limits,
|
||||
) -> Result<Submission, SubmissionError> {
|
||||
let binding = || SubmissionError::Binding;
|
||||
if self.schema_hash != schema.hash
|
||||
|| self.fields.len() > limits.max_fields
|
||||
|| pairs.len() > self.fields.len().saturating_mul(2).saturating_add(6)
|
||||
{
|
||||
return Err(binding());
|
||||
}
|
||||
let mut bytes = 0usize;
|
||||
for (name, value) in pairs {
|
||||
bytes = bytes
|
||||
.checked_add(name.len())
|
||||
.and_then(|n| n.checked_add(value.len()))
|
||||
.filter(|n| *n <= limits.max_bytes)
|
||||
.ok_or_else(binding)?;
|
||||
}
|
||||
let expected = [
|
||||
("__bf_page", self.page.as_str()),
|
||||
("__bf_card", self.card.as_str()),
|
||||
("__bf_schema", self.schema_hash.as_str()),
|
||||
("__bf_revision", self.revision.as_str()),
|
||||
("__bf_csrf", self.csrf.as_str()),
|
||||
];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut values = Vec::new();
|
||||
let mut reset = None;
|
||||
for &(name, value) in pairs {
|
||||
if let Some((_, wanted)) = expected.iter().find(|(key, _)| *key == name) {
|
||||
if value != *wanted || !seen.insert(name) {
|
||||
return Err(binding());
|
||||
}
|
||||
} else if name == "__bf_reset" {
|
||||
if reset.replace(value).is_some() {
|
||||
return Err(binding());
|
||||
}
|
||||
} else {
|
||||
values.push((name, value));
|
||||
}
|
||||
}
|
||||
if seen.len() != expected.len() {
|
||||
return Err(binding());
|
||||
}
|
||||
let definitions = crate::form::definitions(schema, self.fields.keys().map(String::as_str));
|
||||
let mut selected = BTreeMap::new();
|
||||
for path in self.fields.keys() {
|
||||
let setting = definitions[path.as_str()].ok_or_else(binding)?;
|
||||
if !supported(setting)
|
||||
|| setting.path.contains('*')
|
||||
|| setting.hidden == Some(true)
|
||||
|| wschema::path::path_problem(path, false).is_some()
|
||||
{
|
||||
return Err(binding());
|
||||
}
|
||||
selected.insert(path.as_str(), (setting, Vec::new()));
|
||||
}
|
||||
for &(name, value) in &values {
|
||||
if !single_line(value) {
|
||||
return Err(SubmissionError::UnsupportedInput);
|
||||
}
|
||||
let (_, entries) = selected.get_mut(name).ok_or_else(binding)?;
|
||||
entries.push(value);
|
||||
}
|
||||
for (setting, entries) in selected.values() {
|
||||
if matches!(setting.kind, Kind::Bool {}) {
|
||||
if !matches!(entries.as_slice(), ["false"] | ["false", "true"]) {
|
||||
return Err(binding());
|
||||
}
|
||||
} else if entries.len() != 1 {
|
||||
return Err(binding());
|
||||
}
|
||||
}
|
||||
if let Some(path) = reset {
|
||||
if !self
|
||||
.fields
|
||||
.get(path)
|
||||
.is_some_and(|f| f.provenance == Provenance::Stored)
|
||||
{
|
||||
return Err(binding());
|
||||
}
|
||||
return Ok(Submission::Reset(wschema::Op::Reset { path: path.into() }));
|
||||
}
|
||||
let fields: Vec<_> = self.fields.keys().map(String::as_str).collect();
|
||||
crate::form::decode(schema, &fields, &values, limits)
|
||||
.map(Submission::Save)
|
||||
.map_err(SubmissionError::Values)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn writable(setting: &Setting, cx: &RenderCx<'_>) -> Result<bool, Error> {
|
||||
let permission = setting
|
||||
.perm
|
||||
.as_ref()
|
||||
.and_then(|p| p.write.as_deref())
|
||||
.unwrap_or("site.manage");
|
||||
if permission.is_empty() || permission.len() > 256 {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
Ok(cx.principal.can(permission)
|
||||
&& match setting.owner {
|
||||
Owner::Synced => true,
|
||||
Owner::DeviceOnly => cx.surface != Surface::Flare,
|
||||
Owner::FlareOnly => cx.surface == Surface::Flare,
|
||||
Owner::Escrow => false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn supported(setting: &Setting) -> bool {
|
||||
setting.group.is_none()
|
||||
&& !setting.guarded
|
||||
&& setting.guard.is_none()
|
||||
&& setting.write_via.is_none()
|
||||
&& setting.secret_upload != Some(true)
|
||||
&& !matches!(setting.kind, Kind::Secret { .. } | Kind::List { .. })
|
||||
}
|
||||
|
||||
fn single_line(value: &str) -> bool {
|
||||
!value.bytes().any(|b| matches!(b, 0 | b'\r' | b'\n'))
|
||||
}
|
||||
|
||||
pub(super) fn field(
|
||||
setting: &Setting,
|
||||
state: &FieldState,
|
||||
cx: &RenderCx<'_>,
|
||||
) -> Result<Markup, Error> {
|
||||
// The page compile refuses a declared display that does not fit its kind
|
||||
// (fields.rs `supported`). The copy below may show text, so the declared
|
||||
// setting is checked here, and the copy is drawn without that check.
|
||||
if crate::render::refused_display(setting).is_some() {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let mut shown = setting.clone();
|
||||
let mut rows = BTreeMap::new();
|
||||
if let Some(raw) = &state.submitted {
|
||||
let candidate = match &setting.kind {
|
||||
Kind::Bool {} => match raw.as_str() {
|
||||
"true" => Some(Value::Bool(true)),
|
||||
"false" => Some(Value::Bool(false)),
|
||||
_ => return Err(Error::UnsupportedInput),
|
||||
},
|
||||
Kind::Int { .. } | Kind::IntSet { .. } => raw.parse::<i64>().ok().map(Value::from),
|
||||
_ => Some(Value::String(raw.clone())),
|
||||
};
|
||||
// Number inputs sanitize invalid text; display it as escaped text until corrected.
|
||||
// Noncanonical numeric spelling is retained instead of silently normalizing it.
|
||||
let canonical = candidate.as_ref().is_some_and(|v| {
|
||||
setting.kind.accepts(v, &cx.schema.vocabs()).is_ok()
|
||||
&& match v {
|
||||
Value::String(s) => s == raw,
|
||||
Value::Bool(value) => raw == if *value { "true" } else { "false" },
|
||||
Value::Number(_) => {
|
||||
let digits = raw.strip_prefix('-').unwrap_or(raw);
|
||||
digits.bytes().all(|b| b.is_ascii_digit())
|
||||
&& (raw == "0" || !digits.starts_with('0'))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
let value = if canonical {
|
||||
candidate.unwrap()
|
||||
} else {
|
||||
shown.display.t = "text".into();
|
||||
Value::String(raw.clone())
|
||||
};
|
||||
rows.insert(setting.path.clone(), value);
|
||||
} else if let Some(value) = cx
|
||||
.values
|
||||
.setting(&setting.path)
|
||||
.or(setting.default.value.as_ref())
|
||||
{
|
||||
super::fields::value_bounded(value)?;
|
||||
if value.as_str().is_some_and(|raw| !single_line(raw)) {
|
||||
return Err(Error::UnsupportedInput);
|
||||
}
|
||||
if setting.kind.accepts(value, &cx.schema.vocabs()).is_err() {
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
rows.insert(setting.path.clone(), value.clone());
|
||||
} else {
|
||||
return Err(Error::InvalidForm);
|
||||
}
|
||||
let errors: BTreeMap<_, _> = state
|
||||
.error
|
||||
.as_ref()
|
||||
.map(|error| (setting.path.clone(), error.clone()))
|
||||
.into_iter()
|
||||
.collect();
|
||||
// An invalid submitted value is shown as text (above), which must keep the
|
||||
// degraded marker of the setting as declared.
|
||||
let rendered = crate::render::field_marked(
|
||||
&shown,
|
||||
&setting.path,
|
||||
&crate::render::View {
|
||||
eff: cx.schema,
|
||||
rows: &rows,
|
||||
errors: &errors,
|
||||
surface: cx.surface,
|
||||
can_write: true,
|
||||
},
|
||||
crate::render::degraded_display(setting),
|
||||
);
|
||||
bounded(html! {
|
||||
(rendered)
|
||||
@if state.provenance == Provenance::Stored {
|
||||
button class="bf-btn bf-text-button" type="submit" name="__bf_reset"
|
||||
value=(setting.path) formnovalidate { "Reset " (setting.label) }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -141,3 +141,9 @@ pub fn plate(items: &[(String, String)]) -> Markup {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Message plate: one line of text in a bordered box (d04 `plate`). It shows
|
||||
/// the d02 fallback text of a block kind this build does not know.
|
||||
pub fn message_plate(text: &str) -> Markup {
|
||||
html! { p class="bf-plate-message bf-text-body" { (text) } }
|
||||
}
|
||||
|
||||
+177
-20
@@ -1,15 +1,19 @@
|
||||
//! Schema renderer (LD-06): settings from the wschema model to HTML.
|
||||
//!
|
||||
//! [`field`] renders one setting by its display type; [`card`] renders every
|
||||
//! setting of one section in `order`. [`validate_form`] runs a submitted
|
||||
//! batch through `wschema::validate_batch`, so the page shows the same
|
||||
//! failures the daemon would return. Secrets are write-only: no stored value
|
||||
//! is ever placed in the output. Text is escaped by maud, and every class is
|
||||
//! in the stylesheet allowlist.
|
||||
//! [`field`] renders one setting by its display type. An id outside the registry
|
||||
//! is unknown to this build (P-09) and draws the plain control of its kind,
|
||||
//! marked `data-degraded`. A registry id that does not bind the setting's kind,
|
||||
//! or names another node kind, is refused: its label and a diagnostic draw, and
|
||||
//! no control does. [`card`] renders every setting of one section in `order`.
|
||||
//! [`validate_form`] runs a submitted batch through `wschema::validate_batch`, so
|
||||
//! the page shows the same failures the daemon would return. Secrets are
|
||||
//! write-only: no stored value is ever placed in the output. Text is escaped by
|
||||
//! maud, and every class is in the stylesheet allowlist.
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use wschema::display::Bind;
|
||||
use wschema::model::{Kind, Setting, Surface};
|
||||
use wschema::{validate_batch, Ctx, Effective, Op, Origin, Rows};
|
||||
|
||||
@@ -73,17 +77,94 @@ fn text_of(v: Option<&Value>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn list_text(v: Option<&Value>) -> String {
|
||||
/// The items of a list joined by `sep`: one per line in the textarea, or one
|
||||
/// line for the plain control of an unknown list.
|
||||
fn list_text(v: Option<&Value>, sep: &str) -> String {
|
||||
match v {
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.map(|x| text_of(Some(x)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
.join(sep),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Display ids with a control of their own in this renderer. A registry id
|
||||
/// outside this list names another node kind and is refused (`refused_display`).
|
||||
/// An id outside the registry is unknown to this build (a newer schema) and
|
||||
/// draws its kind's plain control. Kept equal to the registry's setting ids by
|
||||
/// `setting_displays_match_the_registry`.
|
||||
const SETTING_DISPLAYS: &[&str] = &[
|
||||
"text",
|
||||
"secret",
|
||||
"dropdown",
|
||||
"segmented",
|
||||
"swatch",
|
||||
"switch",
|
||||
"slider",
|
||||
"stepper",
|
||||
"number",
|
||||
"list",
|
||||
];
|
||||
|
||||
/// The plain control of a setting whose display id is unknown, as the d02
|
||||
/// "Display Library" fallback table sets it per kind (setting row): a text
|
||||
/// input, select, checkbox or number input; `{set}` text for a secret; one
|
||||
/// line of text for a list. `secret-text` and `list-line` are internal ids
|
||||
/// outside `SETTING_DISPLAYS`, so no schema id can select them.
|
||||
fn plain_display(kind: &Kind) -> &'static str {
|
||||
match kind {
|
||||
Kind::Str { .. } => "text",
|
||||
Kind::Secret { .. } => "secret-text",
|
||||
Kind::Enum { .. } | Kind::IntSet { .. } => "dropdown",
|
||||
Kind::Bool {} => "switch",
|
||||
Kind::Int { .. } => "number",
|
||||
Kind::List { .. } => "list-line",
|
||||
}
|
||||
}
|
||||
|
||||
/// The node kind a setting's display must bind in the registry.
|
||||
fn bind_of(kind: &Kind) -> Bind {
|
||||
match kind {
|
||||
Kind::Str { .. } => Bind::Str,
|
||||
Kind::Secret { .. } => Bind::Secret,
|
||||
Kind::Enum { .. } => Bind::Enum,
|
||||
Kind::IntSet { .. } => Bind::IntSet,
|
||||
Kind::Bool {} => Bind::Bool,
|
||||
Kind::Int { .. } => Bind::Int,
|
||||
Kind::List { .. } => Bind::List,
|
||||
}
|
||||
}
|
||||
|
||||
/// The display id of `s` when this build does not know it (P-09): an id outside
|
||||
/// the registry. A registry id is known, even when it is refused.
|
||||
pub(crate) fn degraded_display(s: &Setting) -> Option<&str> {
|
||||
let id = s.display.t.as_str();
|
||||
wschema::display::find(id).is_none().then_some(id)
|
||||
}
|
||||
|
||||
/// The display id of `s` when this build refuses it: a registry id that does not
|
||||
/// bind the setting's kind, or that names another node kind (map, reading, action
|
||||
/// or block). Lint refuses both (`display_legal`), so only a hand-built setting
|
||||
/// reaches this. A refused setting draws no control.
|
||||
pub(crate) fn refused_display(s: &Setting) -> Option<&str> {
|
||||
let id = s.display.t.as_str();
|
||||
let d = wschema::display::find(id)?;
|
||||
let fits = SETTING_DISPLAYS.contains(&id) && d.binds.contains(&bind_of(&s.kind));
|
||||
(!fits).then_some(id)
|
||||
}
|
||||
|
||||
/// The display `s` is drawn with: its own id, or the plain control of its kind
|
||||
/// when this build does not know the id. A refused id never reaches a control.
|
||||
fn drawn_display(s: &Setting) -> &str {
|
||||
if degraded_display(s).is_some() {
|
||||
plain_display(&s.kind)
|
||||
} else {
|
||||
s.display.t.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
fn control(
|
||||
s: &Setting,
|
||||
path: &str,
|
||||
@@ -99,11 +180,7 @@ fn control(
|
||||
Kind::Int { lo, hi, step, .. } => (*lo, *hi, step.unwrap_or(1)),
|
||||
_ => (0, 0, 1),
|
||||
};
|
||||
match s.display.t.as_str() {
|
||||
"text" => html! {
|
||||
input class="bf-input" type="text" name=(path) value=(cur) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
match drawn_display(s) {
|
||||
"secret" => html! {
|
||||
input class="bf-input" type="password" name=(path) value=""
|
||||
placeholder="unchanged" autocomplete="new-password" disabled[off]
|
||||
@@ -120,7 +197,7 @@ fn control(
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] {
|
||||
@for c in &ch {
|
||||
label class="bf-segment" {
|
||||
input type="radio" name=(path) value=(c.v) checked[c.v == cur] disabled[off];
|
||||
input type="radio" name=[(!off).then_some(path)] value=(c.v) checked[c.v == cur] disabled[off];
|
||||
span { (c.label) }
|
||||
}
|
||||
}
|
||||
@@ -148,17 +225,46 @@ fn control(
|
||||
},
|
||||
"list" => html! {
|
||||
textarea class="bf-input" name=(path) rows="4" disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] { (list_text(v)) }
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] { (list_text(v, "\n")) }
|
||||
},
|
||||
other => html! {
|
||||
p class="bf-field-help bf-text-body-sm" { "Unsupported display: " (other) }
|
||||
// Always read-only: no grammar reads a one-line list back yet (schema-pages.md).
|
||||
"list-line" => html! {
|
||||
input class="bf-input" type="text" name=(path) value=(list_text(v, ", ")) disabled
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
// Secrets are write-only: the plain control shows the redaction text only.
|
||||
// Pages draw a secret's status text instead (docs/schema-pages.md), so this
|
||||
// arm serves direct callers of the public `card` and `field` functions.
|
||||
"secret-text" => html! {
|
||||
p class="bf-text-body" { "{set}" }
|
||||
},
|
||||
// Only "text" is left: unknown and refused ids never reach this match.
|
||||
_ => html! {
|
||||
input class="bf-input" type="text" name=(path) value=(cur) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one setting at the concrete `path` (equal to `s.path` unless the
|
||||
/// setting belongs to a map).
|
||||
/// setting belongs to a map). A setting whose display does not fit is refused.
|
||||
pub fn field(s: &Setting, path: &str, view: &View<'_>) -> Markup {
|
||||
match refused_display(s) {
|
||||
Some(id) => refused(s, path, id),
|
||||
None => field_marked(s, path, view, degraded_display(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`field`] drawn as given, with the degraded marker supplied by the caller, so
|
||||
/// a setting drawn from a changed copy (the form path shows invalid input as
|
||||
/// text) keeps the marker of the setting as declared. The caller checks the
|
||||
/// declared setting with [`refused_display`]; the copy's display is not checked.
|
||||
pub(crate) fn field_marked(
|
||||
s: &Setting,
|
||||
path: &str,
|
||||
view: &View<'_>,
|
||||
marker: Option<&str>,
|
||||
) -> Markup {
|
||||
let v = current(s, view.rows, path);
|
||||
let off = !view.can_write || s.hidden == Some(true);
|
||||
let err = view.errors.get(path);
|
||||
@@ -169,9 +275,14 @@ pub fn field(s: &Setting, path: &str, view: &View<'_>) -> Markup {
|
||||
});
|
||||
let description = error_description.as_deref().unwrap_or(&s.help);
|
||||
let description = (!description.is_empty()).then_some(description);
|
||||
let display = drawn_display(s);
|
||||
html! {
|
||||
div class="bf-field" data-path=(path) {
|
||||
@if matches!(s.display.t.as_str(), "text" | "secret" | "dropdown" | "switch" | "slider" | "stepper" | "number" | "list") {
|
||||
div class="bf-field" data-path=(path) data-degraded=[marker] {
|
||||
@if display == "switch" {
|
||||
// Native forms omit unchecked checkboxes. Keep the fallback first.
|
||||
input type="hidden" name=(path) value="false" disabled[off];
|
||||
}
|
||||
@if matches!(display, "text" | "secret" | "dropdown" | "switch" | "slider" | "stepper" | "number" | "list" | "list-line") {
|
||||
// Implicit labels also work when another form repeats the field.
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { (s.label) }
|
||||
@@ -187,6 +298,19 @@ pub fn field(s: &Setting, path: &str, view: &View<'_>) -> Markup {
|
||||
}
|
||||
}
|
||||
|
||||
/// A refused setting: its label, the diagnostic and the help draw, and no control
|
||||
/// does, at any permission. The page path refuses these displays before it
|
||||
/// renders (page/fields.rs `supported`).
|
||||
fn refused(s: &Setting, path: &str, id: &str) -> Markup {
|
||||
html! {
|
||||
div class="bf-field" data-path=(path) {
|
||||
span class="bf-field-label bf-text-label" { (s.label) }
|
||||
p class="bf-field-help bf-text-body-sm" { "Unsupported display: " (id) }
|
||||
@if !s.help.is_empty() { p class="bf-field-help bf-text-body-sm" { (s.help) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_surface(s: &Setting, surface: Surface) -> bool {
|
||||
s.surfaces.as_ref().is_none_or(|l| l.contains(&surface))
|
||||
}
|
||||
@@ -229,3 +353,36 @@ pub fn validate_form(
|
||||
.map(|f| (f.path, f.msg))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use wschema::display::{Bind, REGISTRY};
|
||||
|
||||
use super::SETTING_DISPLAYS;
|
||||
|
||||
/// Every registry id that binds a setting kind has a control here, and no
|
||||
/// other id does. Ids for other node kinds (map, reading, action, block) are
|
||||
/// not setting displays: `field` refuses them with an unsupported diagnostic
|
||||
/// and no control (`refused_display`, docs/schema-pages.md).
|
||||
#[test]
|
||||
fn setting_displays_match_the_registry() {
|
||||
let setting_kinds = [
|
||||
Bind::Str,
|
||||
Bind::Enum,
|
||||
Bind::IntSet,
|
||||
Bind::Bool,
|
||||
Bind::Int,
|
||||
Bind::Secret,
|
||||
Bind::List,
|
||||
];
|
||||
let mut registry: Vec<&str> = REGISTRY
|
||||
.iter()
|
||||
.filter(|d| d.binds.iter().any(|b| setting_kinds.contains(b)))
|
||||
.map(|d| d.id)
|
||||
.collect();
|
||||
registry.sort_unstable();
|
||||
let mut drawn = SETTING_DISPLAYS.to_vec();
|
||||
drawn.sort_unstable();
|
||||
assert_eq!(drawn, registry);
|
||||
}
|
||||
}
|
||||
|
||||
+860
@@ -0,0 +1,860 @@
|
||||
//! Table blocks of a schema page: columns, server-side sort and markup
|
||||
//! (d04 9.3, D64).
|
||||
//!
|
||||
//! The server sorts, and the order lives in the URL (`?sort=<key>&dir=asc`),
|
||||
//! so a sorted table is an ordinary link target that works without script.
|
||||
//! Rows whose sort values tie keep the order of their row key, then of their
|
||||
//! position. A missing or invalid sort value sorts after every valid one.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::page::Error;
|
||||
|
||||
/// Rows one table may draw. A reading with more rows refuses the page.
|
||||
pub const MAX_ROWS: usize = 256;
|
||||
/// Columns one table may draw.
|
||||
pub const MAX_COLUMNS: usize = 16;
|
||||
|
||||
/// How one column sorts (d02 table `columns[].sort`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Sort {
|
||||
/// Natural order: digit runs compare by value, the rest ignores case.
|
||||
Text,
|
||||
/// Numbers by value. `bytes` takes this order too.
|
||||
Num,
|
||||
/// Dotted IPv4 addresses by value.
|
||||
Ip,
|
||||
}
|
||||
|
||||
/// One column of a table block.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Column {
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
pub sort: Sort,
|
||||
}
|
||||
|
||||
/// The sort the URL names, or the block default. `key` is a column key.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Order {
|
||||
pub key: Option<String>,
|
||||
pub desc: bool,
|
||||
}
|
||||
|
||||
/// Columns of a block. Refuses an empty or oversized list, a bad key, a
|
||||
/// duplicate key and a sort kind this build does not know.
|
||||
pub fn columns(value: &Value) -> Result<Vec<Column>, Error> {
|
||||
let items = value
|
||||
.as_array()
|
||||
.filter(|items| !items.is_empty() && items.len() <= MAX_COLUMNS)
|
||||
.ok_or(Error::InvalidSchema)?;
|
||||
let mut out: Vec<Column> = Vec::with_capacity(items.len());
|
||||
for item in items {
|
||||
let object = item.as_object().ok_or(Error::InvalidSchema)?;
|
||||
let key = object
|
||||
.get("key")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|key| key_ok(key))
|
||||
.ok_or(Error::InvalidSchema)?;
|
||||
let label = object
|
||||
.get("label")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|label| label.len() <= crate::page::MAX_TEXT_BYTES)
|
||||
.ok_or(Error::InvalidSchema)?;
|
||||
let sort = match object.get("sort").and_then(Value::as_str).unwrap_or("text") {
|
||||
"text" => Sort::Text,
|
||||
"num" | "bytes" => Sort::Num,
|
||||
"ip" => Sort::Ip,
|
||||
_ => return Err(Error::Unsupported),
|
||||
};
|
||||
if out.iter().any(|column| column.key == key) {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
out.push(Column {
|
||||
key: key.to_owned(),
|
||||
label: label.to_owned(),
|
||||
sort,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The block default sort `{"key": <column>, "dir": "asc" | "desc"}`.
|
||||
pub fn default_order(value: Option<&Value>, columns: &[Column]) -> Result<Order, Error> {
|
||||
let Some(value) = value else {
|
||||
return Ok(Order::default());
|
||||
};
|
||||
let object = value.as_object().ok_or(Error::InvalidSchema)?;
|
||||
let key = object
|
||||
.get("key")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(Error::InvalidSchema)?;
|
||||
if !columns.iter().any(|column| column.key == key) {
|
||||
return Err(Error::InvalidSchema);
|
||||
}
|
||||
let desc = match object.get("dir").and_then(Value::as_str).unwrap_or("asc") {
|
||||
"asc" => false,
|
||||
"desc" => true,
|
||||
_ => return Err(Error::InvalidSchema),
|
||||
};
|
||||
Ok(Order {
|
||||
key: Some(key.to_owned()),
|
||||
desc,
|
||||
})
|
||||
}
|
||||
|
||||
/// The order a URL asks for. A key that is not a column of this table is
|
||||
/// ignored, so a stale or forged link draws the default order.
|
||||
pub fn order_from_query(
|
||||
columns: &[Column],
|
||||
sort: Option<&str>,
|
||||
desc: bool,
|
||||
default: Order,
|
||||
) -> Order {
|
||||
match sort.and_then(|key| columns.iter().find(|column| column.key == key)) {
|
||||
Some(column) => Order {
|
||||
key: Some(column.key.clone()),
|
||||
desc,
|
||||
},
|
||||
None => default,
|
||||
}
|
||||
}
|
||||
|
||||
fn key_ok(key: &str) -> bool {
|
||||
!key.is_empty()
|
||||
&& key.len() <= 64
|
||||
&& key
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
|
||||
}
|
||||
|
||||
/// Text of one cell. A missing or null value is a dash; a nested value
|
||||
/// cannot be drawn in a cell and keeps the page unsupported.
|
||||
fn cell_text(row: &Map<String, Value>, key: &str) -> Result<String, Error> {
|
||||
match row.get(key) {
|
||||
None | Some(Value::Null) => Ok("-".into()),
|
||||
Some(Value::String(text)) if text.len() <= crate::page::MAX_TEXT_BYTES => Ok(text.clone()),
|
||||
Some(Value::String(_)) => Err(Error::Limit),
|
||||
Some(Value::Number(number)) => Ok(number.to_string()),
|
||||
Some(Value::Bool(flag)) => Ok(flag.to_string()),
|
||||
Some(_) => Err(Error::Unsupported),
|
||||
}
|
||||
}
|
||||
|
||||
/// The row key: the row's own `key` member when it is text or a number, else
|
||||
/// the row position.
|
||||
fn row_key(row: &Map<String, Value>, position: usize) -> String {
|
||||
match row.get("key") {
|
||||
Some(Value::String(key)) => key.clone(),
|
||||
Some(Value::Number(key)) => key.to_string(),
|
||||
_ => format!("{position:020}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum SortKey {
|
||||
Text(String),
|
||||
Num(f64),
|
||||
Ip(u32),
|
||||
}
|
||||
|
||||
fn sort_key(sort: Sort, text: &str) -> Option<SortKey> {
|
||||
match sort {
|
||||
Sort::Text => Some(SortKey::Text(text.to_owned())),
|
||||
Sort::Num => text
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|value| value.is_finite())
|
||||
.map(SortKey::Num),
|
||||
Sort::Ip => text
|
||||
.trim()
|
||||
.parse::<Ipv4Addr>()
|
||||
.ok()
|
||||
.map(|addr| SortKey::Ip(u32::from(addr))),
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_keys(a: &SortKey, b: &SortKey) -> Ordering {
|
||||
match (a, b) {
|
||||
(SortKey::Text(x), SortKey::Text(y)) => natural(x, y),
|
||||
(SortKey::Num(x), SortKey::Num(y)) => x.total_cmp(y),
|
||||
(SortKey::Ip(x), SortKey::Ip(y)) => x.cmp(y),
|
||||
// One column has one sort kind, so mixed kinds do not occur.
|
||||
_ => Ordering::Equal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Natural order over the lower-cased text: runs of digits compare by value.
|
||||
fn natural(a: &str, b: &str) -> Ordering {
|
||||
let (a, b) = (a.to_lowercase(), b.to_lowercase());
|
||||
let (mut x, mut y) = (a.as_bytes(), b.as_bytes());
|
||||
loop {
|
||||
match (x.first(), y.first()) {
|
||||
(None, None) => return Ordering::Equal,
|
||||
(None, Some(_)) => return Ordering::Less,
|
||||
(Some(_), None) => return Ordering::Greater,
|
||||
(Some(p), Some(q)) if p.is_ascii_digit() && q.is_ascii_digit() => {
|
||||
let (dx, rest_x) = split_digits(x);
|
||||
let (dy, rest_y) = split_digits(y);
|
||||
let (tx, ty) = (trim_zeros(dx), trim_zeros(dy));
|
||||
let order = tx.len().cmp(&ty.len()).then_with(|| tx.cmp(ty));
|
||||
if order != Ordering::Equal {
|
||||
return order;
|
||||
}
|
||||
x = rest_x;
|
||||
y = rest_y;
|
||||
}
|
||||
(Some(p), Some(q)) => {
|
||||
if p != q {
|
||||
return p.cmp(q);
|
||||
}
|
||||
x = &x[1..];
|
||||
y = &y[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn split_digits(text: &[u8]) -> (&[u8], &[u8]) {
|
||||
let count = text.iter().take_while(|b| b.is_ascii_digit()).count();
|
||||
text.split_at(count)
|
||||
}
|
||||
|
||||
fn trim_zeros(digits: &[u8]) -> &[u8] {
|
||||
let count = digits.iter().take_while(|b| **b == b'0').count();
|
||||
&digits[count..]
|
||||
}
|
||||
|
||||
/// The cells of every row, in display order. `rows` are the reading's
|
||||
/// objects; each cell is text.
|
||||
pub fn sorted_cells(
|
||||
columns: &[Column],
|
||||
rows: &[Value],
|
||||
order: &Order,
|
||||
) -> Result<Vec<Vec<String>>, Error> {
|
||||
if rows.len() > MAX_ROWS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let mut drawn: Vec<(Option<SortKey>, String, usize, Vec<String>)> =
|
||||
Vec::with_capacity(rows.len());
|
||||
for (position, row) in rows.iter().enumerate() {
|
||||
let object = row.as_object().ok_or(Error::Unsupported)?;
|
||||
let cells = columns
|
||||
.iter()
|
||||
.map(|column| cell_text(object, &column.key))
|
||||
.collect::<Result<Vec<String>, Error>>()?;
|
||||
let primary = match &order.key {
|
||||
Some(key) => {
|
||||
let index = columns
|
||||
.iter()
|
||||
.position(|column| &column.key == key)
|
||||
.ok_or(Error::InvalidSchema)?;
|
||||
sort_key(columns[index].sort, &cells[index])
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
drawn.push((primary, row_key(object, position), position, cells));
|
||||
}
|
||||
if order.key.is_some() {
|
||||
drawn.sort_by(|a, b| {
|
||||
let primary = match (&a.0, &b.0) {
|
||||
(Some(x), Some(y)) => {
|
||||
let o = compare_keys(x, y);
|
||||
if order.desc {
|
||||
o.reverse()
|
||||
} else {
|
||||
o
|
||||
}
|
||||
}
|
||||
(None, None) => Ordering::Equal,
|
||||
(None, Some(_)) => Ordering::Greater,
|
||||
(Some(_), None) => Ordering::Less,
|
||||
};
|
||||
primary
|
||||
.then_with(|| natural(&a.1, &b.1))
|
||||
.then_with(|| a.2.cmp(&b.2))
|
||||
});
|
||||
}
|
||||
Ok(drawn.into_iter().map(|(_, _, _, cells)| cells).collect())
|
||||
}
|
||||
|
||||
/// Rows per page when the URL names no `per`. d04 9.3 gives the bounds of
|
||||
/// `per` and leaves its default open.
|
||||
pub const PER_DEFAULT: usize = 50;
|
||||
/// Smallest and largest page size the closed query set allows (d04 4.2).
|
||||
pub const PER_MIN: usize = 10;
|
||||
pub const PER_MAX: usize = 200;
|
||||
/// The page sizes the table controls link to.
|
||||
const PER_CHOICES: [usize; 5] = [10, 25, 50, 100, 200];
|
||||
/// Longest filter text the URL may carry, in bytes.
|
||||
pub const MAX_FILTER: usize = 128;
|
||||
|
||||
/// Rows per page from the URL: a whole number clamped to 10 to 200, or the
|
||||
/// default when the value is absent or is not a number.
|
||||
pub fn per_from_query(value: Option<&str>) -> usize {
|
||||
value
|
||||
.and_then(|text| text.parse::<usize>().ok())
|
||||
.map_or(PER_DEFAULT, |per| per.clamp(PER_MIN, PER_MAX))
|
||||
}
|
||||
|
||||
/// The page the URL names. Absent, zero or invalid values read as page 1.
|
||||
pub fn page_from_query(value: Option<&str>) -> usize {
|
||||
value
|
||||
.and_then(|text| text.parse::<usize>().ok())
|
||||
.filter(|page| *page >= 1)
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
/// The filter text the URL names: trimmed, at most [`MAX_FILTER`] bytes, and
|
||||
/// absent when it is empty or holds a control character.
|
||||
pub fn filter_from_query(value: Option<&str>) -> Option<String> {
|
||||
let text = value?.trim();
|
||||
(!text.is_empty() && text.len() <= MAX_FILTER && !text.chars().any(char::is_control))
|
||||
.then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// Keeps the rows that have the filter text in some cell, ignoring case. The
|
||||
/// rows keep their order.
|
||||
pub fn filter_cells(cells: Vec<Vec<String>>, filter: Option<&str>) -> Vec<Vec<String>> {
|
||||
let Some(needle) = filter.map(str::to_lowercase) else {
|
||||
return cells;
|
||||
};
|
||||
cells
|
||||
.into_iter()
|
||||
.filter(|row| row.iter().any(|cell| cell.to_lowercase().contains(&needle)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One page of rows. `page` is the page drawn, clamped to the last page.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Paged {
|
||||
pub page: usize,
|
||||
pub pages: usize,
|
||||
pub rows: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
/// The rows of page `page` at `per` rows a page. An empty table has one empty
|
||||
/// page.
|
||||
pub fn paginate(rows: Vec<Vec<String>>, page: usize, per: usize) -> Paged {
|
||||
let per = per.max(1);
|
||||
let pages = rows.len().div_ceil(per).max(1);
|
||||
let page = page.clamp(1, pages);
|
||||
let rows = rows.into_iter().skip((page - 1) * per).take(per).collect();
|
||||
Paged { page, pages, rows }
|
||||
}
|
||||
|
||||
/// The DOM id of a table, `table-<id>`, derived from its block path. Every
|
||||
/// character outside `[A-Za-z0-9_-]` becomes `-`, so the id is a plain CSS
|
||||
/// selector for the htmx target.
|
||||
pub fn dom_id(block_path: &str) -> String {
|
||||
let safe: String = block_path
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
format!("table-{safe}")
|
||||
}
|
||||
|
||||
/// What one table draws: its page of rows and the URL state its links keep
|
||||
/// (d04 9.3). `path` is the canonical page path. `None` draws plain headers,
|
||||
/// no controls and no links, so no link can leave the page. `dom_id` names
|
||||
/// the wrapper that htmx replaces.
|
||||
pub struct Table<'a> {
|
||||
pub path: Option<&'a str>,
|
||||
pub dom_id: &'a str,
|
||||
pub columns: &'a [Column],
|
||||
pub order: &'a Order,
|
||||
pub per: usize,
|
||||
pub filter: Option<&'a str>,
|
||||
pub tier: Option<&'a str>,
|
||||
/// Rows after the filter, before paging.
|
||||
pub total: usize,
|
||||
pub paged: Paged,
|
||||
}
|
||||
|
||||
/// The query of one link: the sort and direction when the order has a key,
|
||||
/// the page past the first, the page size when it is not the default, the
|
||||
/// filter and the tier. Each link names its whole state, so it never keeps a
|
||||
/// parameter it does not name.
|
||||
fn query(
|
||||
table: &Table<'_>,
|
||||
order: &Order,
|
||||
page: usize,
|
||||
per: usize,
|
||||
filter: Option<&str>,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let mut pairs = Vec::new();
|
||||
if let Some(key) = &order.key {
|
||||
pairs.push(("sort", key.clone()));
|
||||
pairs.push(("dir", if order.desc { "desc" } else { "asc" }.to_owned()));
|
||||
}
|
||||
if page > 1 {
|
||||
pairs.push(("page", page.to_string()));
|
||||
}
|
||||
if per != PER_DEFAULT {
|
||||
pairs.push(("per", per.to_string()));
|
||||
}
|
||||
if let Some(text) = filter {
|
||||
pairs.push(("q", text.to_owned()));
|
||||
}
|
||||
if let Some(tier) = table.tier {
|
||||
pairs.push(("tier", tier.to_owned()));
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// The href of a query on `path`. Unknown and out-of-domain values are dropped
|
||||
/// by [`crate::url::with_query`].
|
||||
fn href(path: &str, pairs: &[(&str, String)]) -> String {
|
||||
let refs: Vec<(&str, &str)> = pairs
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, value.as_str()))
|
||||
.collect();
|
||||
crate::url::with_query(path, refs, &[])
|
||||
}
|
||||
|
||||
/// A link that htmx swaps into the table wrapper and that is a plain link
|
||||
/// without script. The response is the page body, so `hx-select` takes the
|
||||
/// wrapper out of it, and `outerHTML` replaces the wrapper with that copy.
|
||||
fn table_link(href: &str, target: &str, rel: Option<&str>, current: bool, label: &str) -> Markup {
|
||||
html! {
|
||||
a href=(href) hx-get=(href) hx-target=(target) hx-select=(target)
|
||||
hx-swap="outerHTML" hx-push-url="true" rel=[rel]
|
||||
aria-current=[current.then_some("true")] { (label) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The controls above the table: the row count, the page sizes, the filter
|
||||
/// and, while a filter is set, a link that clears it.
|
||||
fn controls(table: &Table<'_>, path: &str, target: &str) -> Markup {
|
||||
let hidden = query(table, table.order, 1, table.per, None);
|
||||
html! {
|
||||
div class="bf-table-tools" {
|
||||
p class="bf-table-count bf-text-body-sm" { (table.total) " rows" }
|
||||
nav class="bf-table-per" aria-label="Rows per page" {
|
||||
@for choice in PER_CHOICES {
|
||||
(table_link(
|
||||
&href(path, &query(table, table.order, 1, choice, table.filter)),
|
||||
target,
|
||||
None,
|
||||
choice == table.per,
|
||||
&choice.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
form class="bf-table-filter" role="search" method="get" action=(path)
|
||||
hx-get=(path) hx-target=(target) hx-select=(target)
|
||||
hx-swap="outerHTML" hx-push-url="true" {
|
||||
@for (key, value) in &hidden {
|
||||
input type="hidden" name=(key) value=(value);
|
||||
}
|
||||
label class="bf-text-body-sm" {
|
||||
"Filter rows "
|
||||
input type="search" name="q" value=(table.filter.unwrap_or(""))
|
||||
maxlength=(MAX_FILTER);
|
||||
}
|
||||
button class="bf-btn" type="submit" { "Filter" }
|
||||
}
|
||||
@if table.filter.is_some() {
|
||||
(table_link(
|
||||
&href(path, &query(table, table.order, 1, table.per, None)),
|
||||
target,
|
||||
None,
|
||||
false,
|
||||
"Clear filter",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The previous and next links below the table, when there is more than one
|
||||
/// page.
|
||||
fn pager(table: &Table<'_>, path: &str, target: &str) -> Markup {
|
||||
let page = table.paged.page;
|
||||
let last = table.paged.pages;
|
||||
html! {
|
||||
@if last > 1 {
|
||||
nav class="bf-table-pager" aria-label="Table pages" {
|
||||
@if page > 1 {
|
||||
(table_link(
|
||||
&href(path, &query(table, table.order, page - 1, table.per, table.filter)),
|
||||
target,
|
||||
Some("prev"),
|
||||
false,
|
||||
"Previous",
|
||||
))
|
||||
}
|
||||
span class="bf-text-body-sm" { "Page " (page) " of " (last) }
|
||||
@if page < last {
|
||||
(table_link(
|
||||
&href(path, &query(table, table.order, page + 1, table.per, table.filter)),
|
||||
target,
|
||||
Some("next"),
|
||||
false,
|
||||
"Next",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Markup of the table. The wrapper `table-<id>` holds the controls, the
|
||||
/// table, and the pager; htmx replaces the wrapper on every link. The
|
||||
/// `colgroup` gives each column an element the column-resize island sizes.
|
||||
pub fn render(table: &Table<'_>) -> Markup {
|
||||
let target = format!("#{}", table.dom_id);
|
||||
html! {
|
||||
div id=(table.dom_id) class="bf-table-wrap" {
|
||||
@if let Some(path) = table.path {
|
||||
(controls(table, path, &target))
|
||||
}
|
||||
div class="bf-table-scroll" {
|
||||
table class="bf-table" data-resize=(table.dom_id) {
|
||||
colgroup {
|
||||
@for column in table.columns {
|
||||
col data-col=(column.key);
|
||||
}
|
||||
}
|
||||
thead {
|
||||
tr {
|
||||
@for column in table.columns {
|
||||
@let current = table.order.key.as_deref() == Some(column.key.as_str());
|
||||
@let aria = match (current, table.order.desc) {
|
||||
(true, false) => "ascending",
|
||||
(true, true) => "descending",
|
||||
_ => "none",
|
||||
};
|
||||
@let next_desc = current && !table.order.desc;
|
||||
th scope="col" aria-sort=(aria) {
|
||||
@if let Some(path) = table.path {
|
||||
(table_link(
|
||||
&href(path, &query(
|
||||
table,
|
||||
&Order {
|
||||
key: Some(column.key.clone()),
|
||||
desc: next_desc,
|
||||
},
|
||||
1,
|
||||
table.per,
|
||||
table.filter,
|
||||
)),
|
||||
&target,
|
||||
None,
|
||||
false,
|
||||
&column.label,
|
||||
))
|
||||
} @else {
|
||||
(column.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
@if table.paged.rows.is_empty() {
|
||||
tr {
|
||||
td colspan=(table.columns.len()) {
|
||||
@if table.filter.is_some() { "No rows match" } @else { "No rows" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@for row in &table.paged.rows {
|
||||
tr { @for cell in row { td { (cell) } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@if let Some(path) = table.path {
|
||||
(pager(table, path, &target))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn cols() -> Vec<Column> {
|
||||
columns(&json!([
|
||||
{"key": "name", "label": "Name", "sort": "text"},
|
||||
{"key": "size", "label": "Size", "sort": "num"},
|
||||
{"key": "addr", "label": "Address", "sort": "ip"}
|
||||
]))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn natural_order_compares_digit_runs_by_value() {
|
||||
assert_eq!(natural("rack2", "rack10"), Ordering::Less);
|
||||
assert_eq!(natural("Rack02", "rack2"), Ordering::Equal);
|
||||
assert_eq!(natural("b", "A"), Ordering::Greater);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascending_numeric_ties_follow_the_row_key() {
|
||||
let rows = vec![
|
||||
json!({"key": "b", "name": "x", "size": "2", "addr": "10.0.0.2"}),
|
||||
json!({"key": "a", "name": "y", "size": "2", "addr": "10.0.0.3"}),
|
||||
json!({"key": "c", "name": "z", "size": "1", "addr": "10.0.0.1"}),
|
||||
];
|
||||
let order = Order {
|
||||
key: Some("size".into()),
|
||||
desc: false,
|
||||
};
|
||||
let cells = sorted_cells(&cols(), &rows, &order).unwrap();
|
||||
let names: Vec<&str> = cells.iter().map(|row| row[0].as_str()).collect();
|
||||
assert_eq!(names, ["z", "y", "x"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_values_sort_last_in_both_directions() {
|
||||
let rows = vec![
|
||||
json!({"key": "a", "name": "p", "size": "-", "addr": "10.0.0.9"}),
|
||||
json!({"key": "b", "name": "q", "size": "5", "addr": "10.0.0.1"}),
|
||||
];
|
||||
for desc in [false, true] {
|
||||
let order = Order {
|
||||
key: Some("size".into()),
|
||||
desc,
|
||||
};
|
||||
let cells = sorted_cells(&cols(), &rows, &order).unwrap();
|
||||
assert_eq!(cells[1][0], "p", "desc {desc}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ip_sort_is_numeric_not_textual() {
|
||||
let rows = vec![
|
||||
json!({"key": "a", "name": "p", "size": "1", "addr": "10.0.0.10"}),
|
||||
json!({"key": "b", "name": "q", "size": "1", "addr": "10.0.0.9"}),
|
||||
];
|
||||
let order = Order {
|
||||
key: Some("addr".into()),
|
||||
desc: false,
|
||||
};
|
||||
let cells = sorted_cells(&cols(), &rows, &order).unwrap();
|
||||
assert_eq!(cells[0][2], "10.0.0.9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_for_an_unknown_column_draws_the_default() {
|
||||
let default = Order {
|
||||
key: Some("name".into()),
|
||||
desc: false,
|
||||
};
|
||||
assert_eq!(
|
||||
order_from_query(&cols(), Some("nope"), true, default.clone()),
|
||||
default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_limit_and_column_limit_refuse() {
|
||||
let rows: Vec<Value> = (0..=MAX_ROWS)
|
||||
.map(|i| json!({"key": i.to_string(), "name": "n", "size": "1", "addr": "10.0.0.1"}))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sorted_cells(&cols(), &rows, &Order::default()),
|
||||
Err(Error::Limit)
|
||||
);
|
||||
let too_many: Vec<Value> = (0..=MAX_COLUMNS)
|
||||
.map(|i| json!({"key": format!("c{i}"), "label": "x"}))
|
||||
.collect();
|
||||
assert_eq!(columns(&Value::Array(too_many)), Err(Error::InvalidSchema));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_cell_values_keep_the_page_unsupported() {
|
||||
let rows = vec![json!({"key": "a", "name": {"x": 1}, "size": "1", "addr": "10.0.0.1"})];
|
||||
assert_eq!(
|
||||
sorted_cells(&cols(), &rows, &Order::default()),
|
||||
Err(Error::Unsupported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_and_page_read_the_url_within_bounds() {
|
||||
assert_eq!(per_from_query(None), PER_DEFAULT);
|
||||
assert_eq!(per_from_query(Some("10")), 10);
|
||||
assert_eq!(per_from_query(Some("3")), PER_MIN);
|
||||
assert_eq!(per_from_query(Some("500")), PER_MAX);
|
||||
assert_eq!(per_from_query(Some("abc")), PER_DEFAULT);
|
||||
assert_eq!(per_from_query(Some("99999999999999999999999")), PER_DEFAULT);
|
||||
assert_eq!(page_from_query(None), 1);
|
||||
assert_eq!(page_from_query(Some("0")), 1);
|
||||
assert_eq!(page_from_query(Some("-2")), 1);
|
||||
assert_eq!(page_from_query(Some("3")), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paging_clamps_the_page_and_keeps_the_row_order() {
|
||||
let rows: Vec<Vec<String>> = (0..25).map(|i| vec![i.to_string()]).collect();
|
||||
let second = paginate(rows.clone(), 2, 10);
|
||||
assert_eq!((second.page, second.pages), (2, 3));
|
||||
assert_eq!(second.rows.len(), 10);
|
||||
assert_eq!(second.rows[0][0], "10");
|
||||
let beyond = paginate(rows, 99, 10);
|
||||
assert_eq!((beyond.page, beyond.pages, beyond.rows.len()), (3, 3, 5));
|
||||
let empty = paginate(Vec::new(), 4, 10);
|
||||
assert_eq!((empty.page, empty.pages, empty.rows.len()), (1, 1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_matches_any_cell_ignoring_case_and_keeps_the_order() {
|
||||
let rows = vec![
|
||||
vec!["Rack2".to_string(), "10.0.0.2".to_string()],
|
||||
vec!["edge".to_string(), "10.0.0.9".to_string()],
|
||||
vec!["rack10".to_string(), "10.0.0.1".to_string()],
|
||||
];
|
||||
let kept = filter_cells(rows.clone(), Some("RACK"));
|
||||
assert_eq!(kept.len(), 2);
|
||||
assert_eq!(kept[0][0], "Rack2");
|
||||
assert_eq!(kept[1][0], "rack10");
|
||||
assert_eq!(filter_cells(rows.clone(), Some("0.0.9")).len(), 1);
|
||||
assert_eq!(filter_cells(rows, None).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_text_is_trimmed_bounded_and_control_free() {
|
||||
assert_eq!(filter_from_query(Some(" rack ")), Some("rack".into()));
|
||||
assert_eq!(filter_from_query(Some(" ")), None);
|
||||
assert_eq!(filter_from_query(None), None);
|
||||
assert_eq!(filter_from_query(Some("a\nb")), None);
|
||||
let long = "x".repeat(MAX_FILTER + 1);
|
||||
assert_eq!(filter_from_query(Some(&long)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dom_id_is_a_plain_selector() {
|
||||
assert_eq!(dom_id("blocks/id/devices"), "table-blocks-id-devices");
|
||||
assert_eq!(dom_id("blocks/index/3"), "table-blocks-index-3");
|
||||
assert_eq!(dom_id("a b.c"), "table-a-b-c");
|
||||
}
|
||||
|
||||
fn render_with(
|
||||
path: Option<&str>,
|
||||
per: usize,
|
||||
filter: Option<&str>,
|
||||
page: usize,
|
||||
sort: Option<&str>,
|
||||
) -> String {
|
||||
let columns = cols();
|
||||
let order = Order {
|
||||
key: sort.map(str::to_owned),
|
||||
desc: false,
|
||||
};
|
||||
let rows: Vec<Vec<String>> = (0..30)
|
||||
.map(|i| vec![format!("row{i}"), i.to_string(), "10.0.0.1".into()])
|
||||
.collect();
|
||||
let total = rows.len();
|
||||
let paged = paginate(rows, page, per);
|
||||
render(&Table {
|
||||
path,
|
||||
dom_id: "table-x",
|
||||
columns: &columns,
|
||||
order: &order,
|
||||
per,
|
||||
filter,
|
||||
tier: None,
|
||||
total,
|
||||
paged,
|
||||
})
|
||||
.into_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_carry_htmx_attributes_and_the_whole_url_state() {
|
||||
let html = render_with(Some("/net/main"), 10, Some("row"), 2, Some("size"));
|
||||
assert!(
|
||||
html.contains(r#"<div id="table-x" class="bf-table-wrap">"#),
|
||||
"{html}"
|
||||
);
|
||||
assert!(html.contains(r##"hx-target="#table-x""##), "{html}");
|
||||
assert!(html.contains(r##"hx-select="#table-x""##), "{html}");
|
||||
assert!(html.contains(r#"hx-swap="outerHTML""#), "{html}");
|
||||
assert!(html.contains(r#"hx-push-url="true""#), "{html}");
|
||||
// The pager keeps sort, page size and filter, and moves the page.
|
||||
assert!(
|
||||
html.contains("/net/main?sort=size&dir=asc&page=3&per=10&q=row"),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains("/net/main?sort=size&dir=asc&page=1&per=10&q=row")
|
||||
|| html.contains("/net/main?sort=size&dir=asc&per=10&q=row"),
|
||||
"{html}"
|
||||
);
|
||||
// A header link resets the page and flips the direction.
|
||||
assert!(
|
||||
html.contains("/net/main?sort=size&dir=desc&per=10&q=row"),
|
||||
"{html}"
|
||||
);
|
||||
// The page-size links name every choice but the default, which the URL
|
||||
// leaves out; the current choice is marked.
|
||||
for choice in PER_CHOICES
|
||||
.into_iter()
|
||||
.filter(|choice| *choice != PER_DEFAULT)
|
||||
{
|
||||
assert!(html.contains(&format!("per={choice}")), "{choice}: {html}");
|
||||
}
|
||||
assert!(
|
||||
html.contains("/net/main?sort=size&dir=asc&q=row"),
|
||||
"{html}"
|
||||
);
|
||||
assert!(html.contains(r#"aria-current="true""#), "{html}");
|
||||
assert!(html.contains(r#"name="q""#), "{html}");
|
||||
assert!(html.contains("Clear filter"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colgroup_names_each_column_for_the_resize_island() {
|
||||
let html = render_with(Some("/net/main"), PER_DEFAULT, None, 1, None);
|
||||
assert!(html.contains(r#"data-resize="table-x""#), "{html}");
|
||||
assert!(html.contains(r#"<col data-col="name">"#), "{html}");
|
||||
assert!(html.contains(r#"<col data-col="size">"#), "{html}");
|
||||
assert!(html.contains(r#"<col data-col="addr">"#), "{html}");
|
||||
assert!(!html.contains("Clear filter"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_without_a_path_has_no_controls_or_links() {
|
||||
let html = render_with(None, PER_DEFAULT, Some("row"), 1, None);
|
||||
assert!(!html.contains("<a "), "{html}");
|
||||
assert!(!html.contains("<form"), "{html}");
|
||||
assert!(!html.contains("hx-get"), "{html}");
|
||||
assert!(html.contains("<table class=\"bf-table\""), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_filter_result_says_no_rows_match() {
|
||||
let columns = cols();
|
||||
let order = Order::default();
|
||||
let paged = paginate(Vec::new(), 1, PER_DEFAULT);
|
||||
let html = render(&Table {
|
||||
path: Some("/net/main"),
|
||||
dom_id: "table-x",
|
||||
columns: &columns,
|
||||
order: &order,
|
||||
per: PER_DEFAULT,
|
||||
filter: Some("zzz"),
|
||||
tier: None,
|
||||
total: 0,
|
||||
paged,
|
||||
})
|
||||
.into_string();
|
||||
assert!(html.contains("No rows match"), "{html}");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user