From 20ea9b32f76d552f95a9f67e25d1c7bb9304ded0 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Tue, 17 Nov 2026 21:21:21 +0100 Subject: [PATCH] Add e2e script to the repo, Dockerfile, and a Nix flake with a NixOS module - scripts/e2e.sh (+ scripts/e2e/*.ts): the two-node end-to-end test, now self-contained and cleaning up after itself; `make e2e`, part of `make check` - Dockerfile/.dockerignore: static Go build in a non-root alpine image, data in /data, defaults to region u1j; `make docker` - flake.nix, nix/: package (buildGoModule), dev shell, NixOS module services.allmende (hardened systemd unit that waits for `allmende-admin init`), and a NixOS VM test run by `nix flake check` - README: running a node with Docker and NixOS Co-Authored-By: Claude Sonnet 5.5 --- .dockerignore | 7 ++ .gitignore | 1 + Dockerfile | 35 ++++++++++ Makefile | 10 ++- README.md | 44 ++++++++++++ flake.lock | 27 ++++++++ flake.nix | 54 +++++++++++++++ nix/module.nix | 160 +++++++++++++++++++++++++++++++++++++++++++ nix/package.nix | 45 ++++++++++++ nix/test.nix | 53 ++++++++++++++ scripts/e2e.sh | 129 ++++++++++++++++++++++++++++++++++ scripts/e2e/buyer.ts | 31 +++++++++ scripts/e2e/renew.ts | 10 +++ 13 files changed, 604 insertions(+), 2 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nix/module.nix create mode 100644 nix/package.nix create mode 100644 nix/test.nix create mode 100755 scripts/e2e.sh create mode 100644 scripts/e2e/buyer.ts create mode 100644 scripts/e2e/renew.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..fdf1466 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +bin +*.key +web/node_modules +web/test +scripts +docs diff --git a/.gitignore b/.gitignore index 59cbac7..6588e52 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /bin/ +/result *.key node_modules/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..508e21c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +# Allmende node. The web UI is already built and embedded (web/dist is +# committed), so only Go is needed here. +# +# docker build -t allmende . +# docker run --rm -it -v allmende-data:/data allmende init # once; shows the recovery phrase +# docker run -d --name allmende -v allmende-data:/data \ +# -p 127.0.0.1:8080:8080 -p 4001:4001 allmende # run (Bonn by default) +# +# The HTTP port also serves the owner API, which the admin token protects, so +# publish it on 127.0.0.1 only and put a TLS proxy in front for public use. +# Port 4001 is the libp2p port other nodes connect to. + +ARG GO_VERSION=1.27 + +FROM golang:${GO_VERSION}-alpine AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/allmende ./cmd/allmende + +FROM alpine:3.22 +RUN adduser -D -u 10001 allmende && mkdir /data && chown allmende /data +COPY --from=build /out/allmende /usr/local/bin/allmende +USER allmende +ENV ALLMENDE_DATA=/data +VOLUME /data +EXPOSE 8080 4001 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD wget -qO- http://127.0.0.1:8080/api/v1/status >/dev/null || exit 1 +ENTRYPOINT ["allmende"] +# Override the whole command to change regions or add peers, e.g. +# docker run ... allmende run --http 0.0.0.0:8080 --listen /ip4/0.0.0.0/tcp/4001 \ +# --region u1j --region u1h --bootstrap /ip4/203.0.113.5/tcp/4001/p2p/ +CMD ["run", "--http", "0.0.0.0:8080", "--listen", "/ip4/0.0.0.0/tcp/4001", "--region", "u1j"] diff --git a/Makefile b/Makefile index 6d6b5f5..7b71b60 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ REGION ?= u1j# Bonn; several are allowed: make run REGION="u1j u1h" (u1h is Colo DATA ?= FLAGS := $(if $(DATA),--data $(DATA)) -.PHONY: help build run init test vet web web-test check clean +.PHONY: help build run init test vet web web-test e2e check clean docker help: ## list the targets @grep -E '^[a-z-]+:.*## ' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-10s %s\n", $$1, $$2}' @@ -17,6 +17,9 @@ init: build ## create your identity (once): make init [DATA=dir] run: build ## run a node (default region Bonn): make run [REGION=u1j] [DATA=dir] $(BIN) run $(FLAGS) $(foreach r,$(REGION),--region $(r)) +docker: ## build the container image (allmende:dev) + docker build -t allmende:dev . + vet: ## go vet go vet ./... @@ -29,7 +32,10 @@ web: ## rebuild web/dist after changing web/src (needs Node.js) web-test: ## type-check and test the web UI (needs Node.js) cd web && npm ci && npm run typecheck && npm test -check: vet test web-test ## everything: vet, Go tests, web checks +e2e: ## two real nodes end to end (needs Node.js and web/node_modules) + scripts/e2e.sh + +check: vet test web-test e2e ## everything: vet, Go tests, web checks, end to end clean: ## remove built binaries rm -rf bin diff --git a/README.md b/README.md index d95f759..30830d9 100644 --- a/README.md +++ b/README.md @@ -30,4 +30,48 @@ listings can be edited, renewed (30 days, manually) or deleted there. A second node on the same network finds this one automatically (mDNS); across networks, pass `--bootstrap /ip4//tcp//p2p/`. +## Running a node for real + +A node needs to stay up to receive messages and keep your listings alive. Make +targets: `make build run test check e2e docker` (`make help` lists them). + +**Docker** + +``` +docker build -t allmende . # or: make docker +docker run --rm -it -v allmende-data:/data allmende init # once; write down the phrase +docker run -d --name allmende -v allmende-data:/data \ + -p 127.0.0.1:8080:8080 -p 4001:4001 allmende # Bonn (u1j) by default +docker logs allmende | grep -A1 'Owner login' # the sign-in link +``` + +The image runs as a non-root user and keeps its data in the `/data` volume. +To change regions or add peers, replace the command (see the end of the +`Dockerfile`). Publish port 8080 on `127.0.0.1` only: it also serves the owner +API. For public use put a TLS reverse proxy in front. + +**NixOS** (flake) + +```nix +{ + inputs.allmende.url = "git+ssh://git@git.stinnesbeck.com:2222/nils/allmende.git"; + outputs = { nixpkgs, allmende, ... }: { + nixosConfigurations.myhost = nixpkgs.lib.nixosSystem { + modules = [ + allmende.nixosModules.default + { services.allmende = { enable = true; regions = [ "u1j" ]; openFirewall = true; }; } + ]; + }; + }; +} +``` + +After `nixos-rebuild switch`, do the one-time setup (it shows the recovery +phrase, so it is not part of the service): `sudo allmende-admin init && sudo +systemctl start allmende`. The sign-in link is in `journalctl -u allmende`. +Without NixOS, from a checkout: `nix run . -- run --region u1j`, or +`nix develop` for a shell with Go, Node.js and the other tools `make check` +needs. `nix flake check` builds the package and boots a NixOS VM that tests the +module. After changing `go.mod`, update `vendorHash` in `nix/package.nix`. + Licensed under the [GNU AGPL-3.0](LICENSE): free for everyone, and it stays free. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..6c335e2 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1794537146, + "narHash": "sha256-Wpz/7x/YWnDIBu7yj6ixe8j6fIMsidd9Y+o1PqPF3iM=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "d5cc6833999746cffdfe0598f7bc801a57b887a9", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..217c355 --- /dev/null +++ b/flake.nix @@ -0,0 +1,54 @@ +{ + description = "Allmende: a free, distributed marketplace for homes"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = + { self, nixpkgs }: + let + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + version = "0.1.0-${self.shortRev or self.dirtyShortRev or "dev"}"; + in + { + # nix build -> ./result/bin/allmende + # nix run . -- run --region u1j + packages = forAll (pkgs: rec { + allmende = pkgs.callPackage ./nix/package.nix { inherit version; }; + default = allmende; + }); + + # nix develop: everything `make check` needs. + devShells = forAll (pkgs: { + default = pkgs.mkShell { + packages = with pkgs; [ + go + gopls + nodejs + gnumake + curl + python3 + ]; + }; + }); + + # imports = [ allmende.nixosModules.default ]; services.allmende.enable = true; + nixosModules.default = import ./nix/module.nix self; + + # nix flake check: builds the package and boots a VM running the module. + checks.x86_64-linux = { + package = self.packages.x86_64-linux.default; + vm = import ./nix/test.nix { + pkgs = nixpkgs.legacyPackages.x86_64-linux; + module = self.nixosModules.default; + }; + }; + + formatter = forAll (pkgs: pkgs.nixfmt); + }; +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..92e7313 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,160 @@ +self: +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.services.allmende; + exe = lib.getExe cfg.package; + + # `allmende init` and `recover` run as the service's user and need a terminal + # (they show and check the recovery phrase), so they are not part of the unit. + admin = pkgs.writeShellScriptBin "allmende-admin" '' + exec sudo -u allmende env ALLMENDE_DATA=${lib.escapeShellArg cfg.dataDir} ${exe} "$@" + ''; + + args = + [ + "run" + "--http" + cfg.httpAddress + "--listen" + "/ip4/0.0.0.0/tcp/${toString cfg.p2pPort}" + ] + ++ lib.concatMap (r: [ + "--region" + r + ]) cfg.regions + ++ lib.concatMap (b: [ + "--bootstrap" + b + ]) cfg.bootstrap + ++ cfg.extraArgs; +in +{ + options.services.allmende = { + enable = lib.mkEnableOption "an Allmende node (a free, distributed marketplace for homes)"; + + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.default; + defaultText = lib.literalExpression "allmende.packages.\${system}.default"; + description = "The allmende package to run."; + }; + + regions = lib.mkOption { + type = lib.types.listOf lib.types.str; + example = [ "u1j" ]; + description = '' + Regions to replicate: 3-character geohashes, each about 150 km wide. + `u1j` is Bonn, `u1h` Cologne, `u1x` Hamburg. + ''; + }; + + bootstrap = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ "/ip4/203.0.113.5/tcp/4001/p2p/12D3KooW..." ]; + description = "Known peers to connect to, as multiaddrs ending in /p2p/."; + }; + + httpAddress = lib.mkOption { + type = lib.types.str; + default = "127.0.0.1:8080"; + description = '' + Where the web UI and API listen. The same port serves the owner API, + which the admin token protects, so keep it on loopback and put a TLS + reverse proxy in front for public use. + ''; + }; + + p2pPort = lib.mkOption { + type = lib.types.port; + default = 4001; + description = "TCP port other nodes connect to."; + }; + + openFirewall = lib.mkOption { + type = lib.types.bool; + default = false; + description = "Open the peer-to-peer port ({option}`p2pPort`) in the firewall."; + }; + + dataDir = lib.mkOption { + type = lib.types.path; + default = "/var/lib/allmende"; + description = "Where keys, the admin token and the database live."; + }; + + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ "--no-mdns" ]; + description = "Further arguments for `allmende run`."; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = cfg.regions != [ ]; + message = "services.allmende.regions needs at least one region, for example [ \"u1j\" ]."; + } + ]; + + users.users.allmende = { + isSystemUser = true; + group = "allmende"; + home = cfg.dataDir; + description = "Allmende node"; + }; + users.groups.allmende = { }; + + systemd.tmpfiles.rules = [ "d ${cfg.dataDir} 0700 allmende allmende -" ]; + + # One-time setup, because it shows the recovery phrase: + # sudo allmende-admin init && sudo systemctl start allmende + # The unit is skipped (not failed) until that has happened. + systemd.services.allmende = { + description = "Allmende node"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + unitConfig.ConditionPathExists = "${cfg.dataDir}/admin.token"; + environment.ALLMENDE_DATA = cfg.dataDir; + serviceConfig = { + ExecStart = "${exe} ${lib.escapeShellArgs args}"; + User = "allmende"; + Group = "allmende"; + Restart = "on-failure"; + RestartSec = "5s"; + + NoNewPrivileges = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectSystem = "strict"; + ProtectHome = true; + ReadWritePaths = [ cfg.dataDir ]; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictSUIDSGID = true; + LockPersonality = true; + # libp2p reads the network interfaces over netlink to find its addresses. + RestrictAddressFamilies = [ + "AF_INET" + "AF_INET6" + "AF_UNIX" + "AF_NETLINK" + ]; + }; + }; + + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.p2pPort ]; + + environment.systemPackages = [ admin ]; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..64e873f --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,45 @@ +{ + lib, + buildGoModule, + version, +}: + +buildGoModule { + pname = "allmende"; + inherit version; + + # Only what the Go build reads, so editing docs or tests does not rebuild. + # web/dist is the pre-built UI that the binary embeds. + src = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + ../go.mod + ../go.sum + ../cmd + ../internal + ../web/embed.go + ../web/dist + ]; + }; + + # Changes whenever go.mod or go.sum do: set it to lib.fakeHash, build, and + # copy the hash from the error. + vendorHash = "sha256-vUBmsqyS+/qXo3UDYzZmZQYik7rMhOrX7csy56UJbLU="; + + subPackages = [ "cmd/allmende" ]; + env.CGO_ENABLED = "0"; + ldflags = [ + "-s" + "-w" + ]; + + # The tests start libp2p nodes and need loopback networking and mDNS, which + # the build sandbox does not give. `make test` runs them. + doCheck = false; + + meta = { + description = "A free, distributed marketplace for buying, selling and renting"; + license = lib.licenses.agpl3Only; + mainProgram = "allmende"; + }; +} diff --git a/nix/test.nix b/nix/test.nix new file mode 100644 index 0000000..b593554 --- /dev/null +++ b/nix/test.nix @@ -0,0 +1,53 @@ +{ pkgs, module }: + +pkgs.testers.runNixOSTest { + name = "allmende"; + + nodes.machine = { + imports = [ module ]; + services.allmende = { + enable = true; + regions = [ "u1j" ]; + openFirewall = true; + }; + }; + + testScript = '' + machine.wait_for_unit("multi-user.target") + + with subtest("the service waits for setup instead of failing"): + machine.succeed("systemctl show allmende -p ActiveState | grep -q inactive") + machine.fail("systemctl is-failed allmende") + + with subtest("init creates the identity, as the service's own user"): + # The VM's shell is a terminal, where init would wait for the phrase to be + # typed back; empty input makes it skip that check, as in a script. + out = machine.succeed("allmende-admin init /dev/null; done + wait 2>/dev/null + if [ -n "${E2E_KEEP:-}" ]; then echo "kept $W"; else rm -rf "$W"; fi +} +trap cleanup EXIT +ok() { echo "PASS: $*"; } +bad() { echo "FAIL: $*"; echo "--- node A log"; tail -15 "$W/a.log"; echo "--- node B log"; tail -15 "$W/b.log"; exit 1; } +wait_for() { # description, timeout, command... + local what=$1 t=$2; shift 2 + for _ in $(seq 1 $((t*10))); do if "$@" >/dev/null 2>&1; then return 0; fi; sleep 0.1; done + bad "timed out: $what" +} +DIFF=10 +COMMON="--region u1x --no-mdns --difficulty $DIFF" + +echo "== init" +$BIN init --data $A > $W/init-a.txt || bad "init A" +$BIN init --data $B > $W/init-b.txt || bad "init B" +grep -q "12 words" $W/init-a.txt && ok "init prints the recovery phrase" +PHRASE=$(grep -E '^ +[0-9]+\.' $W/init-a.txt | sed -E 's/[0-9]+\.//g' | tr -s ' \n' ' ' | sed 's/^ //; s/ $//') +[ "$(echo $PHRASE | wc -w)" = 12 ] && ok "captured 12-word phrase" || bad "phrase parse: '$PHRASE'" +[ ! -e $A/root.key ] && ! grep -rqi "$(echo $PHRASE | cut -d' ' -f1-3)" $A && ok "phrase is not stored in the data dir" +[ "$(stat -c %a $A/device.key)" = 600 ] && [ "$(stat -c %a $A/admin.token)" = 600 ] && ok "key and token are mode 0600" +$BIN init --data $A >/dev/null 2>&1 && bad "init must refuse to run twice" || ok "init refuses to overwrite an existing identity" + +echo "== run two nodes" +$BIN run --data $A $COMMON --http 127.0.0.1:18101 --listen /ip4/127.0.0.1/tcp/14101 2> $W/a.log & +PIDS+=($!) +wait_for "A http" 10 curl -sf http://127.0.0.1:18101/api/v1/status +PEER=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peer_id"])') +$BIN run --data $B $COMMON --http 127.0.0.1:18102 --listen /ip4/127.0.0.1/tcp/14102 \ + --bootstrap /ip4/127.0.0.1/tcp/14101/p2p/$PEER 2> $W/b.log & +PIDS+=($!) +wait_for "B http" 10 curl -sf http://127.0.0.1:18102/api/v1/status +wait_for "nodes connected" 15 test "$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peers"])')" -ge 1 +ok "nodes connected" + +echo "== publish on A, read on B" +TOKEN=$(cat $A/admin.token) +DRAFT='{"kind":"rent","category":"apartment","geohash":"u1xjhx","price":{"amount_cents":95000,"currency":"EUR","period":"month"},"area_m2":48,"rooms_x2":4,"title":"Helle Wohnung","description":"Ruhig."}' +curl -s -o /dev/null -w "%{http_code}" -X POST -d "$DRAFT" http://127.0.0.1:18101/api/v1/listings | grep -q 401 && ok "publishing without the token is refused" +RESP=$(curl -s -X POST -H "Authorization: Bearer $TOKEN" -d "$DRAFT" http://127.0.0.1:18101/api/v1/listings) +ID=$(echo "$RESP" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])') || bad "create: $RESP" +ok "published listing $ID" +count_b() { curl -s "http://127.0.0.1:18102/api/v1/listings?geohash=u1x" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; } +wait_for "B receives the listing" 15 test "$(count_b)" = 1 +ok "node B has the listing via gossip" + +echo "== UI-style edit and renew on A (draft built by the UI's own code)" +RENEW=$ROOT/scripts/e2e/renew.ts +AUTHOR0=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["author"])') +CUR=$(curl -s http://127.0.0.1:18101/api/v1/listings/$AUTHOR0/$ID) +EDIT=$(echo "$CUR" | node $RENEW "Helle Wohnung, renoviert" 20) || bad "draft from listing" +PUTR=$(curl -s -X PUT -H "Authorization: Bearer $TOKEN" -d "$EDIT" http://127.0.0.1:18101/api/v1/listings/$ID) +echo "$PUTR" | python3 -c 'import json,sys; l=json.load(sys.stdin); assert l["title"]=="Helle Wohnung, renoviert" and l["seq"]==2, l' && ok "edit accepted: new version, seq 2" || bad "edit refused: $PUTR" +RENEWED=$(echo "$PUTR" | node $RENEW "" 30) || bad "renew draft" +PUTR=$(curl -s -X PUT -H "Authorization: Bearer $TOKEN" -d "$RENEWED" http://127.0.0.1:18101/api/v1/listings/$ID) +echo "$PUTR" | python3 -c 'import json,sys; l=json.load(sys.stdin); assert l["seq"]==3 and l["expires_at"]-l["created_at"]>29*86400, l' && ok "renew accepted: seq 3, fresh 30-day term" || bad "renew refused: $PUTR" +wait_for "B has the renewed version" 15 test "$(curl -s http://127.0.0.1:18102/api/v1/listings/$AUTHOR0/$ID | python3 -c 'import json,sys; print(json.load(sys.stdin)["seq"])')" = 3 +ok "node B serves the renewed version" +MOVED=$(echo "$PUTR" | node $RENEW "" 30 | python3 -c 'import json,sys; d=json.load(sys.stdin); d["geohash"]="u28xyz"; print(json.dumps(d))') +curl -s -o /dev/null -w "%{http_code}" -X PUT -H "Authorization: Bearer $TOKEN" -d "$MOVED" http://127.0.0.1:18101/api/v1/listings/$ID | grep -q 400 && ok "moving a listing to another region is refused" || bad "region change was not refused" + +echo "== messaging: buyer -> B -> A, reply A -> B -> buyer" +BUYER=$ROOT/scripts/e2e/buyer.ts +AUTHOR=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["author"])') +SECRET=$(node $BUYER send http://127.0.0.1:18102 $AUTHOR $ID) || bad "buyer could not send via B" +ok "buyer posted an encrypted message to node B" +inbox_a() { curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; } +wait_for "A receives the message" 20 test "$(inbox_a)" = 1 +ok "owner's node A decrypted it (via gossip through B)" +THREAD=$(curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox | python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["thread"])') +curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox/$ID/$THREAD | grep -q "Ist die Wohnung noch frei" && ok "owner reads the buyer's text" +curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18101/api/v1/inbox | grep -q 401 && ok "inbox needs the admin token" +curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18101/api/v1/mine | grep -q 401 && ok "my-listings overview needs the admin token" +curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/mine | python3 -c 'import json,sys; m=json.load(sys.stdin); assert len(m)==1 and m[0]["threads"]==1 and m[0]["needs_reply"]==1, m' && ok "owner overview counts the request that needs a reply" +curl -s -o /dev/null -w "%{http_code}" -X PUT -H "Authorization: Bearer $TOKEN" -d '{"address":"Musterweg 7, 20095 Hamburg"}' http://127.0.0.1:18101/api/v1/listings/$ID/address | grep -qE "^(200|204)$" && ok "address stored privately on A" +curl -s http://127.0.0.1:18102/api/v1/listings/$AUTHOR/$ID | grep -q "Musterweg" && bad "address leaked into the public listing" +ok "address is not part of the public listing" +curl -s -o /dev/null -w "%{http_code}" -X POST -H "Authorization: Bearer $TOKEN" -d '{"type":"grant","address":"Musterweg 7, 20095 Hamburg","note":"Samstag 10 Uhr","valid_days":7}' http://127.0.0.1:18101/api/v1/inbox/$ID/$THREAD | grep -qE "^(200|201|202)$" || bad "grant reply refused" +ok "owner sent a signed address grant" +wait_for "buyer sees the grant via B" 20 bash -c "node $BUYER read http://127.0.0.1:18102 $AUTHOR $ID $SECRET | grep -q 'OK grant Musterweg'" +ok "buyer's browser code verified and read the grant from B" +node $BUYER read http://127.0.0.1:18102 $AUTHOR $ID $(node -e 'console.log("77".repeat(32))') | grep -q . && bad "another thread key saw a reply" +ok "a different thread key sees nothing" + +echo "== recover on A (simulate a stolen machine)" +OLD_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])') +kill ${PIDS[0]}; wait ${PIDS[0]} 2>/dev/null +echo "$PHRASE" | $BIN recover --data $A --difficulty $DIFF > $W/recover.txt 2>&1 || { cat $W/recover.txt; bad "recover"; } +grep -q "1 of your listings were re-signed" $W/recover.txt && ok "recover re-signed the owner's listing" || { cat $W/recover.txt; bad "recover output"; } +ls $A | grep -q "device.key.revoked-" && ok "old device key was moved aside, not destroyed" +echo "wrong words here" | $BIN recover --data $A >/dev/null 2>&1 && bad "bad phrase accepted" || ok "recover rejects a wrong phrase" + +# The recovered node has a new peer ID, so B's bootstrap entry for the old one +# is stale. Like a real recovered node, A dials out to its own bootstrap peer. +PEER_B=$(curl -s http://127.0.0.1:18102/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peer_id"])') +$BIN run --data $A $COMMON --http 127.0.0.1:18101 --listen /ip4/127.0.0.1/tcp/14101 \ + --bootstrap /ip4/127.0.0.1/tcp/14102/p2p/$PEER_B 2> $W/a.log & +PIDS[0]=$! +wait_for "A http again" 10 curl -sf http://127.0.0.1:18101/api/v1/status +NEW_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])') +[ "$OLD_DEVICE" != "$NEW_DEVICE" ] && ok "A runs with a new device key" || bad "device did not change" +OLDTOKEN=$TOKEN +curl -s -o /dev/null -w "%{http_code}" -X POST -H "Authorization: Bearer $OLDTOKEN" -d "$DRAFT" http://127.0.0.1:18101/api/v1/listings | grep -q 401 && ok "old admin token no longer works" + +# B should learn of the revocation and the re-signed listing (seq 2, new device). +dev_on_b() { curl -s "http://127.0.0.1:18102/api/v1/listings?geohash=u1x" | python3 -c ' +import json,sys +l=json.load(sys.stdin) +print(l[0]["device"] if len(l)==1 else "none")'; } +wait_for "B switches to the new device's version" 60 test "$(dev_on_b)" = "$NEW_DEVICE" +ok "node B now serves the listing re-signed by the new device (old device revoked network-wide)" +echo "ALL E2E CHECKS PASSED" diff --git a/scripts/e2e/buyer.ts b/scripts/e2e/buyer.ts new file mode 100644 index 0000000..dfb66f3 --- /dev/null +++ b/scripts/e2e/buyer.ts @@ -0,0 +1,31 @@ +// A stand-in for the browser, for the e2e script: node buyer.ts send|read [secretHex] +import { buildToOwner, mailbox, newThreadSecret, openReply, threadPublic, toHex } from "../../web/src/message.ts"; +import { canonicalize } from "../../web/src/jcs.ts"; + +const [cmd, gw, author, id, secretHex] = process.argv.slice(2) as [string, string, string, string, string?]; +const now = Math.floor(Date.now() / 1000); + +if (cmd === "send") { + const listing = (await (await fetch(`${gw}/api/v1/listings/${author}/${id}`)).json()) as { device: string }; + const status = (await (await fetch(`${gw}/api/v1/status`)).json()) as { message_difficulty: number }; + const secret = newThreadSecret(); + const env = await buildToOwner({ + listing: { author, id, device: listing.device }, + threadSecret: secret, + text: secretHex ?? "Ist die Wohnung noch frei?", + n: 1, + now, + difficulty: status.message_difficulty, + first: true, + }); + const res = await fetch(`${gw}/api/v1/messages`, { method: "POST", body: canonicalize(env) }); + if (res.status !== 202) throw new Error(`post: ${res.status} ${await res.text()}`); + console.log(toHex(secret)); +} else { + const secret = Uint8Array.from(Buffer.from(secretHex!, "hex")); + const envs = (await (await fetch(`${gw}/api/v1/messages?mailbox=${mailbox(threadPublic(secret))}&since=${now - 7200}`)).json()) as unknown[]; + for (const e of envs) { + const r = openReply(e, secret, { author, id }); + console.log(r.ok ? `OK ${r.plain.t} ${r.plain.text ?? r.plain.address}` : `BAD ${r.error}`); + } +} diff --git a/scripts/e2e/renew.ts b/scripts/e2e/renew.ts new file mode 100644 index 0000000..072d767 --- /dev/null +++ b/scripts/e2e/renew.ts @@ -0,0 +1,10 @@ +// Prints the draft the UI's Renew button would PUT for a listing, read from stdin (the listing JSON). +import { readFileSync } from "node:fs"; +import { draftFromListing } from "../../web/src/draft.ts"; +import type { Listing } from "../../web/src/verify.ts"; + +const l = JSON.parse(readFileSync(0, "utf8")) as Listing; +const title = process.argv[2]; +const d = draftFromListing(l, Number(process.argv[3] ?? 30)); +if (title) d.title = title; +process.stdout.write(JSON.stringify(d));