From: Jakub Czajka Date: Tue, 24 Nov 2026 23:21:43 +0000 (+0000) Subject: [test] Add a PC VM test and share the VM test harness. X-Git-Url: https://git.ekhem.eu.org/?a=commitdiff_plain;ds=sidebyside;p=guix.git [test] Add a PC VM test and share the VM test harness. Turn home.scm and system.scm into importable modules exporting pc-home-environment and pc-operating-system, then split the tests into tests/base.scm for the marionette harness, tests/home.scm for the shared home activation prelude and checks, and tests/{pc,vps}/ for the suites. The PC suite logs in through GDM's greeter, runs the home activation as the X session, and then execs Guix's xinitrc, so dwm and the home services start through the real login path; one test case checks the login screen, dwm ownership, and the paseo-daemon, status-bar, and xcompmgr services. The test user gets a known password so GDM can authenticate it. The harness now wraps every OS in marionette-operating-system, runs the prelude before the tests, and aborts when it fails; it uses the qemu64 CPU model so the tests also run without KVM. The VPS suite keeps the sshd, daemon, and claude-proxy checks and uses assert-vm-true for the guest-side assertions. Move the claude-proxy live test and fake upstream under tests/vps, add a test-pc Makefile target, and let 20-env.sh keep GDM's DISPLAY instead of always forcing :1. Co-Authored-By: Claude --- diff --git a/Makefile b/Makefile index c3aff2c..07edbe3 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,10 @@ guix-env := env -u GUILE_LOAD_PATH -u GUILE_LOAD_COMPILED_PATH \ -u GUILE_EXTENSIONS_PATH GUIX_PACKAGE_PATH=$(CURDIR) vps-test := $(guix-env) guix build -L $(CURDIR) \ - -e '(@ (tests base) %vps-system-test)' + -e '(@ (tests vps base) %vps-system-test)' + +pc-test := $(guix-env) PROFILE=nonfree guix build -L $(CURDIR) \ + -e '(@ (tests pc base) %system-test)' stop-home-services: @for svc in claude-proxy paseo-daemon; do \ @@ -64,8 +67,11 @@ test-vps-fresh: build-vps-system [ -z "$$out" ] || guix gc --delete "$$out" || exit 1; \ $(vps-test) +test-pc: build-system-nonfree + @$(pc-test) + test-claude-proxy-live: - @tests/claude-proxy-live.sh + @tests/vps/claude-proxy-live.sh tags: gv=$$($(guix-env) guix show guix | sed --quiet 's/^version: //p'); \ diff --git a/bash/.config/profile.d/20-env.sh b/bash/.config/profile.d/20-env.sh index 07ae4e2..97e4629 100644 --- a/bash/.config/profile.d/20-env.sh +++ b/bash/.config/profile.d/20-env.sh @@ -1,9 +1,9 @@ -# Copyright (c) 2022-2024 Jakub Czajka +# Copyright (c) 2022-2026 Jakub Czajka # License: GPL-3.0 or later. # # 20-env.sh - generic environment variables. export EDITOR="emacs" -export DISPLAY=":1" +export DISPLAY="${DISPLAY:-:1}" export PATH="${HOME}/.local/bin:${PATH}" export TERM="st-256color" diff --git a/home.scm b/home.scm index d4f8396..e15ae29 100644 --- a/home.scm +++ b/home.scm @@ -7,38 +7,44 @@ ;; PROFILE=nonfree -- allows non-free software. ;; PROFILE=libre -- free software only. -(use-modules (gnu home) - (conf home bash) - (conf home claude) - (conf home emoji) - (conf home desktop) - (conf home emacs) - (conf home guix) - (conf home notify) - (conf home paseo) - (conf home pi) - (conf home suckless) - (gnu packages gnuzilla) - (nongnu packages mozilla)) +(define-module (home) + #:use-module (gnu home) + #:use-module (conf home bash) + #:use-module (conf home claude) + #:use-module (conf home emoji) + #:use-module (conf home desktop) + #:use-module (conf home emacs) + #:use-module (conf home guix) + #:use-module (conf home notify) + #:use-module (conf home paseo) + #:use-module (conf home pi) + #:use-module (conf home suckless) + #:use-module (gnu packages gnuzilla) + #:use-module (nongnu packages mozilla) + #:export (pc-home-environment)) -(let ((profile (string->symbol (or (getenv "PROFILE") "nonfree")))) - (home-environment - (packages (case profile - ((nonfree) - (list firefox - pi - claude-code - paseo - select-emoji - st-libxft-bgra)) - ((libre) - (list icecat-minimal select-emoji st-libxft-bgra)))) - (services - (case profile - ((nonfree) - (append (list autorandr-service channels-service notify-service - paseo-daemon-service screenshot-service) bash-services - desktop-services emacs-services)) - ((libre) - (append (list autorandr-service notify-service screenshot-service) - bash-services desktop-services emacs-services)))))) +(define pc-home-environment + (let ((profile (string->symbol (or (getenv "PROFILE") "nonfree")))) + (home-environment + (packages (case profile + ((nonfree) + (list firefox + pi + claude-code + paseo + select-emoji + st-libxft-bgra)) + ((libre) + (list icecat-minimal select-emoji st-libxft-bgra)))) + (services + (case profile + ((nonfree) + (append (list autorandr-service channels-service notify-service + paseo-daemon-service screenshot-service) bash-services + desktop-services emacs-services)) + ((libre) + (append (list autorandr-service notify-service screenshot-service) + bash-services desktop-services emacs-services))))))) + +;; Keep the file usable as a `guix home reconfigure' script. +pc-home-environment diff --git a/system.scm b/system.scm index 9c14adc..bfa7aaa 100644 --- a/system.scm +++ b/system.scm @@ -7,144 +7,157 @@ ;; PROFILE=nonfree — allows non-free firmware. ;; PROFILE=libre — free software only. -(use-modules (conf common substitutes) - (conf system bluetooth) - (conf system desktop) - (conf system volume) - (gnu) - (gnu system) - (gnu system nss)) +(define-module (system) + #:use-module (conf common substitutes) + #:use-module (conf system bluetooth) + #:use-module (conf system desktop) + #:use-module (conf system volume) + #:use-module (gnu) + #:use-module (gnu system) + #:use-module (gnu system linux-initrd) + #:use-module (gnu system nss) + #:use-module (nongnu packages linux) + #:use-module (nongnu system linux-initrd) + #:export (pc-operating-system)) + +(use-package-modules base + certs + gnome + linux + pulseaudio + xdisorg) +(use-service-modules desktop networking xorg) +(use-system-modules setuid) -(use-package-modules base certs linux pulseaudio xdisorg) +(define %nonfree-root-uuid + "b8be09cf-d416-4a49-ab69-173ee227acb6") -(use-service-modules desktop networking xorg) +(define %libre-root-uuid + "565d174f-3d96-45a1-8bef-fdab38e4d35a") -(use-system-modules setuid) +(define pc-operating-system + (let ((profile (string->symbol (or (getenv "PROFILE") "nonfree")))) + (operating-system + (initrd (case profile + ((nonfree) + microcode-initrd) + ((libre) + base-initrd))) -(use-modules (nongnu packages linux) - (nongnu system linux-initrd)) -(use-modules (gnu system linux-initrd)) - -(let ((profile (string->symbol (or (getenv "PROFILE") "nonfree")))) - (operating-system - (initrd (case profile - ((nonfree) - microcode-initrd) - ((libre) - base-initrd))) - - (kernel (case profile - ((nonfree) - linux) - ((libre) - linux-libre))) - - (firmware (case profile + (kernel (case profile ((nonfree) - (list linux-firmware)) + linux) ((libre) - '()))) - - (locale "en_US.UTF-8") - (timezone "Europe/Warsaw") - - (keyboard-layout (keyboard-layout "us")) - - (host-name "dak") - (users (append (list (user-account - (name "dak") - (group "users") - (supplementary-groups '("audio" "cdrom" - "lp" - "netdev" - "tape" - "video" - "wheel")))) - %base-user-accounts)) - - (bootloader (case profile + linux-libre))) + + (firmware (case profile ((nonfree) - (bootloader-configuration - (bootloader grub-efi-bootloader) - (targets '("/boot/efi")) - (keyboard-layout keyboard-layout))) + (list linux-firmware)) ((libre) - (bootloader-configuration - (bootloader (bootloader (inherit grub-bootloader) - (installer #~(const #t)))) - (keyboard-layout keyboard-layout))))) - - (mapped-devices (case profile - ((nonfree) - (list (mapped-device - (source (uuid - "b8be09cf-d416-4a49-ab69-173ee227acb6")) - (target "root") - (type luks-device-mapping)))) - ((libre) - (list (mapped-device - (source (uuid - "565d174f-3d96-45a1-8bef-fdab38e4d35a")) - (target "root") - (type luks-device-mapping)) - (mapped-device - (source "matrix") - (targets (list "matrix-rootvol" - "matrix-swapvol")) - (type lvm-device-mapping)))))) - - (file-systems (append (case profile - ((nonfree) - (list (file-system - (type "ext4") - (mount-point "/") - (device (file-system-label "root")) - (dependencies mapped-devices)) - (file-system - (type "vfat") - (mount-point "/boot/efi") - (device (file-system-label "EFI")) - (needed-for-boot? #t)))) - ((libre) - (list (file-system - (type "ext4") - (mount-point "/") - (device (file-system-label "root")) - (flags '(no-atime)) - (needed-for-boot? #t) - (dependencies mapped-devices))))) - %base-file-systems)) - - (swap-devices (list (swap-space - (target (file-system-label "swap")) - (dependencies mapped-devices)))) - - (name-service-switch %mdns-host-lookup-nss) - - (setuid-programs (let* ((xsecurelock-path - "/libexec/xsecurelock/authproto_pam") - (xsecurelock-auth (file-append xsecurelock - xsecurelock-path))) - (cons* (setuid-program (program xsecurelock-auth)) - %setuid-programs))) - - (sudoers-file (let ((content (string-append "root ALL=(ALL) ALL\n" - "%wheel ALL=(ALL) ALL\n" - "dak ALL=(ALL) NOPASSWD: " - "/run/current-system/profile/bin/guix " - "system reconfigure *\n"))) - (plain-file "sudoers" content))) - - (packages (append (list gnu-make bluez pulseaudio volume) - dwm-desktop-packages %base-packages)) - - (services - (modify-services (append (list bluez-service %resolv-conf-service - keyboard-layout-service) - %custom-desktop-services) - (guix-service-type config => - (case profile - ((nonfree) - (augment-guix-configuration config)) - ((libre) - config))))))) + '()))) + + (locale "en_US.UTF-8") + (timezone "Europe/Warsaw") + + (keyboard-layout (keyboard-layout "us")) + + (host-name "dak") + (users (append (list (user-account + (name "dak") + (group "users") + (supplementary-groups '("audio" "cdrom" + "lp" + "netdev" + "tape" + "video" + "wheel")))) + %base-user-accounts)) + + (bootloader (case profile + ((nonfree) + (bootloader-configuration + (bootloader grub-efi-bootloader) + (targets '("/boot/efi")) + (keyboard-layout keyboard-layout))) + ((libre) + (bootloader-configuration + (bootloader (bootloader (inherit grub-bootloader) + (installer #~(const #t)))) + (keyboard-layout keyboard-layout))))) + + (mapped-devices (case profile + ((nonfree) + (list (mapped-device + (source (uuid %nonfree-root-uuid)) + (target "root") + (type luks-device-mapping)))) + ((libre) + (list (mapped-device + (source (uuid %libre-root-uuid)) + (target "root") + (type luks-device-mapping)) + (mapped-device + (source "matrix") + (targets (list "matrix-rootvol" + "matrix-swapvol")) + (type lvm-device-mapping)))))) + + (file-systems (append (case profile + ((nonfree) + (list (file-system + (type "ext4") + (mount-point "/") + (device (file-system-label "root")) + (dependencies mapped-devices)) + (file-system + (type "vfat") + (mount-point "/boot/efi") + (device (file-system-label "EFI")) + (needed-for-boot? #t)))) + ((libre) + (list (file-system + (type "ext4") + (mount-point "/") + (device (file-system-label "root")) + (flags '(no-atime)) + (needed-for-boot? #t) + (dependencies mapped-devices))))) + %base-file-systems)) + + (swap-devices (list (swap-space + (target (file-system-label "swap")) + (dependencies mapped-devices)))) + + (name-service-switch %mdns-host-lookup-nss) + + (setuid-programs (let* ((xsecurelock-path + "/libexec/xsecurelock/authproto_pam") + (xsecurelock-auth (file-append xsecurelock + xsecurelock-path))) + (cons* (setuid-program (program xsecurelock-auth)) + %setuid-programs))) + + (sudoers-file (let ((content (string-append "root ALL=(ALL) ALL\n" + "%wheel ALL=(ALL) ALL\n" + "dak ALL=(ALL) NOPASSWD: " + "/run/current-system/profile/bin/guix " + "system reconfigure *\n"))) + (plain-file "sudoers" content))) + + (packages (append (list gnu-make gsettings-desktop-schemas bluez + pulseaudio volume) dwm-desktop-packages + %base-packages)) + + (services + (modify-services (append (list bluez-service %resolv-conf-service + keyboard-layout-service) + %custom-desktop-services) + (guix-service-type config => + (case profile + ((nonfree) + (augment-guix-configuration config)) + ((libre) + config)))))))) + +;; Keep the file usable as a `guix system reconfigure' script. +pc-operating-system diff --git a/tests/base.scm b/tests/base.scm index 412832b..dd79aa3 100644 --- a/tests/base.scm +++ b/tests/base.scm @@ -1,38 +1,55 @@ ;; Copyright (c) 2026 Jakub Czajka ;; License: GPL-3.0 or later. ;; -;; The VPS VM test harness. +;; The VM test harness. (define-module (tests base) - #:use-module (gnu tests) #:use-module (gnu system vm) + #:use-module (gnu tests) #:use-module (guix gexp) - #:use-module (tests vps-home) - #:use-module (tests vps-system) - #:export (%vps-system-test)) + #:export (%test-user assert-vm-true vm-system-test)) + +(define %test-user + "dak") + +(define (assert-vm-true vm label body) + #~(test-equal #$label #t + (marionette-eval '#$body + #$vm))) + +(define %vm-imported-modules + '((gnu services herd))) -(define (run-vps-test test-cases) - (let* ((vm (virtual-machine (operating-system - %vps-test-os) - (memory-size 1024))) - (builder #~(begin - (use-modules (gnu build marionette) - (srfi srfi-64)) - ;; -cpu host requires KVM. - (define marionette - (make-marionette (list #$vm "-cpu" "host"))) - (marionette-eval '(use-modules (gnu services herd)) - marionette) - (test-runner-current (system-test-runner #$output)) - (test-begin "vps") - #$@(map (lambda (test-case) - (test-case #~marionette)) test-cases) - (test-end "vps")))) - (gexp->derivation "vps-test" builder - #:modules '((gnu build marionette))))) +(define (vm-test-builder name machine test-cases prelude) + #~(begin + (use-modules (gnu build marionette) + (ice-9 format) + (srfi srfi-64)) + ;; -cpu host requires KVM; qemu64 also works under TCG. + (define vm + (make-marionette (list #$machine "-cpu" "qemu64"))) + (unless (marionette-eval '#$(cons 'begin + (append prelude + '(#t))) vm) + (error "guest test prelude failed")) + (test-runner-current (system-test-runner #$output)) + (test-begin #$name) + #$@(map (lambda (test-case) + (test-case #~vm)) test-cases) + (test-end #$name))) -(define %vps-system-test - (system-test (name "vps") - (description "VPS test suite.") - (value (run-vps-test (list sshd-test-cases daemons-test-cases - vps-home-test-cases))))) +(define (vm-system-test name os test-cases prelude memory-size) + (let* ((vm-os (marionette-operating-system os + #:imported-modules + %vm-imported-modules)) + (machine (virtual-machine (operating-system + vm-os) + (memory-size memory-size))) + (test-builder (vm-test-builder name machine test-cases prelude)) + (test-modules '((gnu build marionette))) + (test-derivation (gexp->derivation (string-append name "-test") + test-builder + #:modules test-modules))) + (system-test (name name) + (description (string-append name " test suite.")) + (value test-derivation)))) diff --git a/tests/claude-proxy-live.sh b/tests/claude-proxy-live.sh deleted file mode 100755 index 90a41c4..0000000 --- a/tests/claude-proxy-live.sh +++ /dev/null @@ -1,183 +0,0 @@ -#!/bin/sh -# Copyright (c) 2026 Jakub Czajka -# License: GPL-3.0 or later. -# -# Differential test against the live claude-proxy: for each sample, send it -# to both the deployed service and this build, then diff their canonicalized -# log-and-response transcripts; the key and live log are host state. - -repo_root=$(cd "$(dirname "$0")/.." && pwd) -src_port=16890 -src_log="${XDG_STATE_HOME:-$HOME/.local/state}/claude-proxy.log" - -tag=$(printf '%s' "$repo_root" | cksum | cut --delimiter=' ' --fields=1) -dst_port=$((17000 + tag % 1000)) -base="/tmp/$tag-claude-proxy-live" - -report() { - echo "❌ $1" - shift - printf ' %s\n' "$@" -} - -die() { - report "$@" - exit 1 -} - -canonicalize_log_slice() { - sed --regexp-extended \ - --expression 's/^[0-9-]+ [0-9:]+ //' \ - --expression '/New request\. peer=/d; s/req=[0-9a-f]+ /req=X /' \ - --expression 's/ ms=[0-9]+//g; s/ query=[^ ]*//' -} - -canonicalize_response() { - sed --regexp-extended \ - --expression 's/"(id|text|thinking|signature)":"[^"]*"/"\1":"X"/g' \ - --expression 's/"([a-z_]+_tokens)":[0-9]+/"\1":N/g' \ - --expression '/event: ping/d; /"type":"ping"/d' "$1" | uniq -} - -diff_files() { - diff --unified "$1" "$2" - diff_status=$? - [ "$diff_status" -le 1 ] && return "$diff_status" - die "diff failed with status $diff_status; no comparison." \ - "Reference: $1" "This tree: $2" -} - -accept_difference() { - printf ' accept this difference? [y/N] ' - if ! read -r answer || [ "$answer" != y ]; then - die "not accepted: an unchanged build skips the test," \ - "so change the proxy before rerunning." - fi - echo " difference accepted." -} - -sample_side() { - label=$1 side=$2 route=$3 port=$4 log=$5 - shift 5 - mark=$(( $(wc --lines < "$log") + 1 )) - response="$base.$side.response" transcript="$base.$side.transcript" - id= proto= code= rest= polls=0 - curl --silent --show-error --include --no-buffer --max-time 90 \ - --header 'content-type: application/json' \ - --header "x-api-key: $key" "$@" \ - "http://127.0.0.1:$port$route" > "$response" 2>&1 - if ! read -r proto code rest < "$response" || [ "$code" != 200 ]; then - die "the $label sample on $response returned: $proto $code $rest" \ - "Two identical failures would pass the diff." - fi - id=$(tail --lines=+"$mark" "$log" | grep --fixed-strings "probe=$tag" \ - | grep --only-matching --extended-regexp 'req=[0-9a-f]+' \ - | head --lines=1) - [ -n "$id" ] || - die "the $label sample is not tagged in $log." \ - "Does the deployed build log the query?" - until tail --lines=+"$mark" "$log" | grep --quiet \ - --extended-regexp "$id (event=rsp|Done\.|Aborted\.)"; do - [ "$polls" -lt 100 ] || - die "the $label sample did not finish in 10 s;" "see $log." - sleep 0.1 - polls=$((polls + 1)) - done - tail --lines=+"$mark" "$log" | grep --fixed-strings "$id " \ - | canonicalize_log_slice > "$transcript" - canonicalize_response "$response" >> "$transcript" -} - -compare_sample() { - name=$1 endpoint=$2 - shift 2 - sample_side "$name" src "$endpoint" "$src_port" "$src_log" "$@" - sample_side "$name" dst "$endpoint" "$dst_port" "$base.log" "$@" - echo "--- $name:" - if diff_files "$base.src.transcript" "$base.dst.transcript"; then - echo "transcripts IDENTICAL" - else - report "the two proxies' transcripts differ for $name." \ - "Blanked above: timestamps, request ids, timings, the query," \ - "ids, text, thinking, signatures, token counts and pings. A" \ - "hunk is a change in the relay or the deployed service." \ - "Transcripts: $base.src.transcript $base.dst.transcript" \ - "raw responses: $base.src.response $base.dst.response" - accept_difference - fi -} - -stop_proxy() { - kill "$dst_pid" 2>/dev/null - waits=0 - while [ "$waits" -lt 20 ]; do - kill -0 "$dst_pid" 2>/dev/null || return 0 - sleep 0.1 - waits=$((waits + 1)) - done - kill -KILL "$dst_pid" 2>/dev/null -} - -rm --force "$base".* - -# Drop GUILE_* so the system profile's modules don't shadow guix's. -build_proxy() { - env -u GUILE_LOAD_PATH -u GUILE_LOAD_COMPILED_PATH \ - -u GUILE_EXTENSIONS_PATH GUIX_PACKAGE_PATH="$repo_root" \ - guix build --load-path="$repo_root" \ - --expression='(@ (conf home claude-proxy) claude-proxy)' "$@" -} - -# A dry run prints the program to stdout only when the store already has it; -# missing derivations go to stderr, so empty output means the build must run. -cached=$(build_proxy --dry-run --no-substitutes) || - die "cannot evaluate the claude-proxy package." -if [ -n "$cached" ]; then - echo "claude-proxy is already in the store ($cached);" - echo "skipping the differential." - exit 0 -fi -dst_proxy=$(build_proxy) || die "the claude-proxy build failed." -dst_proxy=$dst_proxy/bin/claude-proxy - -read -r key 2>/dev/null < "/run/user/$(id --user)/claude-apikey" - -env PROXY_PORT="$dst_port" \ - CLAUDE_PROXY_UPSTREAM=https://api.deepseek.com/anthropic \ - CLAUDE_PROXY_TIMEOUT=60 \ - "$dst_proxy" > "$base.log" 2>&1 & -dst_pid=$! -trap stop_proxy 0 - -tries=0 -until grep --quiet "Startup. listen=$dst_port" "$base.log"; do - [ "$tries" -lt 50 ] || - die "the proxy did not start on $dst_port within 5 s." \ - "Its log is at $base.log." - sleep 0.1 - tries=$((tries + 1)) -done - -echo "--- this tree on $dst_port against the live service on $src_port:" - -# Health never reaches the upstream, so override the default timeout. -compare_sample health "/?probe=$tag" --max-time 10 - -compare_sample plain "/v1/messages?probe=$tag" \ - --data '{"stream":false,"model":"deepseek-chat", - "max_tokens":32,"messages":[{"role":"user", - "content":"Reply with the single word OK"}]}' -compare_sample stream "/v1/messages?probe=$tag" \ - --data '{"stream":true,"model":"deepseek-chat", - "max_tokens":32,"messages":[{"role":"user", - "content":"Reply with the single word OK"}]}' -compare_sample count_tokens \ - "/v1/messages/count_tokens?probe=$tag" \ - --data '{"model":"deepseek-chat", - "messages":[{"role":"user","content": - "Reply with the single word OK"}]}' - -echo "--- this tree's proxy log:" -cat "$base.log" -echo "--- proxy log events:" -grep --only-matching 'event=[a-z-]*' "$base.log" | sort | uniq --count diff --git a/tests/claude-proxy-test-cert.pem b/tests/claude-proxy-test-cert.pem deleted file mode 100644 index 5b72072..0000000 --- a/tests/claude-proxy-test-cert.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDHDCCAgSgAwIBAgIUOX0m6IigoZ9XlXsv4tFfa8LcbaQwDQYJKoZIhvcNAQEL -BQAwFDESMBAGA1UEAwwJMTI3LjAuMC4xMCAXDTI2MDkwMzE3NTQyOFoYDzIxMjYw -ODEwMTc1NDI4WjAUMRIwEAYDVQQDDAkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQC7OSYfhTQwzUSYcY2QPm0PoMiuysvlEpd+18b/b8pO -T7vBA+w/0QPPtExrX4TbO9nZox7/SW9+WOigcsy2gaTRs5vCsKCpPQlH5atao4Pv -cLJ3uESt+XqwMpowIp/GXFp3NL3j0q0rcrvisa2pcOOpLiVi2lmAVqmhKXVL+ITG -u8HtDnw4duTErXFVQBRslkwrbcwW1itiiqdJXZ6oz18u5aQ/e5rRV5Rk7Vojxzus -lN4vqpDTmUiPVk5aCQrOdgiTcIYEKI8Sy4rtGyBgKmAUEBzqIu8iphshlKWJ5B/N -i9PQsQV+Zyx8rY72tlpj3NLcg6KhW8RnJ2qkV9QhFTpLAgMBAAGjZDBiMB0GA1Ud -DgQWBBRKBG6nhcv95RLD+OfDnNFg+Y5pNjAfBgNVHSMEGDAWgBRKBG6nhcv95RLD -+OfDnNFg+Y5pNjAPBgNVHREECDAGhwR/AAABMA8GA1UdEwEB/wQFMAMBAf8wDQYJ -KoZIhvcNAQELBQADggEBACrqbJ7HzFIBecusXnh+MpiyZ9y1VLwvMNe7MqdBY5Qt -w/d2UxS+jgyyt/TR4V7y4ZsfWZdtLNCK414+3eiQqHXjD2O0Yc2upoC0lziahYNU -O68ehOFUyrf1HTpCbBZDzxxKdvCekCEbE5nj6a4Gv+OTqiEt4+kHcBkS8fmiZwdc -RQuuMdel3BpBBwb0o9a+SiKV+3MOr2BD8BnA/9u0lEo1xONBY6K4yikWp9lztmqw -vuuyCM+VZg5tsm1CQISIdthoAr9bVFsO1Zc2ER6HAWy+yJBXdF12Juj7bBHFS7a6 -9l8PDR6eSWU9ebKvCAcfN46Vrm4CIhr2UPH3DVHRIWw= ------END CERTIFICATE----- diff --git a/tests/claude-proxy-test-key.pem b/tests/claude-proxy-test-key.pem deleted file mode 100644 index d0c0183..0000000 --- a/tests/claude-proxy-test-key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7OSYfhTQwzUSY -cY2QPm0PoMiuysvlEpd+18b/b8pOT7vBA+w/0QPPtExrX4TbO9nZox7/SW9+WOig -csy2gaTRs5vCsKCpPQlH5atao4PvcLJ3uESt+XqwMpowIp/GXFp3NL3j0q0rcrvi -sa2pcOOpLiVi2lmAVqmhKXVL+ITGu8HtDnw4duTErXFVQBRslkwrbcwW1itiiqdJ -XZ6oz18u5aQ/e5rRV5Rk7VojxzuslN4vqpDTmUiPVk5aCQrOdgiTcIYEKI8Sy4rt -GyBgKmAUEBzqIu8iphshlKWJ5B/Ni9PQsQV+Zyx8rY72tlpj3NLcg6KhW8RnJ2qk -V9QhFTpLAgMBAAECggEAMlFGLzOAFtucI3JlTw6QBiK6vMtxKBQqliMM7wrO7uQb -/GB/Bpm4sgJthXALB1bbElR2WLsWVXk0sCaaYTSPpPJmGtmYnFN0opeVyYrnwxrh -RC7Ieo9xy1gWO3iaw1d/0sjgfhHZi7NOzrrdBwx5izcFQj+XzVe9SDyZszzMBpLp -ma80qvyNw34RHQEQpUTvl1fXuIh1VH42SUwIRQtMrUYpyoEQOJfc7Cwy0/dzMnt+ -XCF9mXu9wyzrfXvnGJv2TjobzqhUx1JkqHiW5TGI/3cKpTecrT6WMUGzt0v3xTS4 -TxGhmnCy4qE5xT9po29k94vulBhVD9PT4/1OaSke9QKBgQD/GkaxIKYqqtPGnqf8 -Li4GKJspMuhbF7gM3LCqIqM6wgUlIazBPVedk9BTXlMiYQAQYBlp5Rh6xxxh8+Dg -UFVMPFq2LAIb41IEV51efkZNgGnVC0zeyLYmI0tVBJEp4A8itqgerizD4Lbg9sBP -7q5cClgu12LSaFMZuXmlRaIcDwKBgQC74b8Pc8y70LsKoaIQJLALwOONpJuPCLDj -B89mh7RtYRH0slB8QiJYRNOVp9mw9FYZFQkwBBbCCiTagjtBcTLiDc/OkZdln2pa -KWzRztDN97Ijnj3zCac8SyrJHoUu12yUjzQ2GrC2kQSEjj/RkpsQ3vYd6aEkKmAw -6mKqKNRyBQKBgQCDxtEJorHzjHcFPOPN0xUXPVaZe6CnnaMHkeD4ohfrvFnoCnMx -Bz0BO1/8ENelBLKBwwKdvyhcFArHVrGtbhIB5ZN+U1FrkovFjnTOYTBzzIfe841r -8AaXwNejPU63cPSgm/ZQkuyw6p3Nq+k/4S3Ugct3tu9nfVigCz2ZcFUDZQKBgEec -JGlsVqVjSlckAhQrF5pzO4gaLFxZEKqHqIpIwQFLlT9x03F494QzP330CuoCRuqq -dOUDOfVdTmymZJVt4tn8L69pGI5YM34H+f0B2d4XQaOHxc7jaAV4FOexJUwUOcNp -zZmtlJsRLOqlGTf0q/vDL4V5Lb0OFbmvLEn04/xNAoGBAIfcx+E8sdVvs0gIrOv5 -wsmyx0Mcr10GF01QlePxgBgZNfWIVuZomGc82gT606K5R6L4R129Jzvs087gBLVK -C/j9JqbFZ146gKD91lQMinGffCGa9XcXLzLph2MCeAyO46z5jNqSuWk0TL3tP8o7 -XCrVbiudrikX2WtdtF3aNz02 ------END PRIVATE KEY----- diff --git a/tests/fake-llm.scm b/tests/fake-llm.scm deleted file mode 100644 index 83acb05..0000000 --- a/tests/fake-llm.scm +++ /dev/null @@ -1,112 +0,0 @@ -;; Copyright (c) 2026 Jakub Czajka -;; License: GPL-3.0 or later. -;; -;; The build sandbox has no network route or API key, so this fake stands -;; in for DeepSeek; use make test-claude-proxy-live for the live diff. - -(define-module (tests fake-llm) - #:use-module (gnutls) - #:use-module (ice-9 threads) - #:use-module (json) - #:use-module (rnrs bytevectors) - #:use-module (web request) - #:use-module (web uri) - #:export (run-fake-llm)) - -(define (raw-response status content-type extra-header body) - (string-append "HTTP/1.1 " status "\r\nContent-Type: " content-type - (string-append "\r\n" extra-header - "Connection: close\r\n\r\n" body))) - -(define (respond! sock text) - (display text sock) - (force-output sock)) - -(define (respond-sized! sock status content-type body) - (let ((byte-count (number->string (bytevector-length (string->utf8 body))))) - (respond! sock - (raw-response status content-type - (string-append "Content-Length: " byte-count - "\r\n") body)))) - -(define (chunk text) - (string-append (number->string (bytevector-length (string->utf8 text)) 16) - "\r\n" text "\r\n")) - -(define (respond-stream! sock) - (respond! sock - (raw-response "200 OK" "text/event-stream" - "Transfer-Encoding: chunked\r\n" "")) - (respond! sock - (chunk (string-append "event: message_start\ndata: " - (scm->json-string '((type . "message_start"))) - "\n\n"))) - (sleep 3) - (respond! sock - (string-append (chunk "data: [DONE]\n\n") "0\r\n\r\n"))) - -(define %claude-reply - (scm->json-string `((id . "msg_test") (type . "message") - (role . "assistant") - (model . "claude-sonnet-4-6") - (content unquote - #(((type . "text") (text . "Hello from fake")))) - (stop_reason . "end_turn") - (stop_sequence . null) - (usage (input_tokens . 1) - (output_tokens . 3))))) - -(define (read-request-fields sock) - (let* ((request (read-request sock)) - (uri (request-uri request)) - (body (read-request-body request))) - (list (uri-path uri) - (uri-query uri) - (utf8->string (or body #vu8()))))) - -(define %unauthorized-body - (scm->json-string '((error (type . "authentication_error"))))) - -(define (dispatch-request! sock path query body-str) - (cond - ((and (equal? path "/v1/messages") - (equal? query "beta=true")) - (respond-sized! sock "200 OK" "application/json" %claude-reply)) - ((and (equal? path "/v1/messages") - (string-contains body-str "\"stream\":true")) - (respond-stream! sock)) - ((or (equal? path "/v1/messages") - (equal? path "/v1/messages/count_tokens")) - (respond-sized! sock "200 OK" "application/json" body-str)) - (else (respond-sized! sock "401 Unauthorized" "application/json" - %unauthorized-body)))) - -(define (serve-tls-session! conn cert key) - (let ((session (make-session connection-end/server)) - (cred (make-certificate-credentials))) - (set-session-priorities! session "NORMAL:%COMPAT:-VERS-SSL3.0") - (set-session-transport-fd! session - (fileno conn)) - (set-certificate-credentials-x509-key-files! cred cert key - x509-certificate-format/pem) - (set-session-credentials! session cred) - (handshake session) - (let ((sock (session-record-port session))) - (false-if-exception (apply dispatch-request! sock - (read-request-fields sock))) - (false-if-exception (close-port sock))))) - -(define (run-fake-llm cert key port) - (sigaction SIGPIPE SIG_IGN) - (let ((listener (socket PF_INET SOCK_STREAM 0))) - (setsockopt listener SOL_SOCKET SO_REUSEADDR 1) - (bind listener - (make-socket-address AF_INET INADDR_LOOPBACK port)) - (listen listener 16) - (let loop - ((conn (car (accept listener)))) - (call-with-new-thread (lambda () - (false-if-exception (serve-tls-session! conn - cert key)) - (false-if-exception (close-port conn)))) - (loop (car (accept listener)))))) diff --git a/tests/home.scm b/tests/home.scm new file mode 100644 index 0000000..ae1ab65 --- /dev/null +++ b/tests/home.scm @@ -0,0 +1,99 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. +;; +;; Generic home activation test cases. + +(define-module (tests home) + #:use-module (gnu packages admin) + #:use-module (gnu packages base) + #:use-module (guix gexp) + #:use-module (tests base) + #:export (home-activation-test home-system-test wait-for-home-service)) + +(define (home-prelude extra) + `((use-modules (gnu services herd) + (ice-9 popen) + (ice-9 rdelim)) + (define (wait-for ok? seconds) + (let loop + ((remaining seconds)) + (or (ok?) + (and (positive? remaining) + (sleep 1) + (loop (- remaining 1)))))) + + (define runtime-dir + (string-append "/run/user/" + (number->string (passwd:uid (getpwnam ,%test-user))))) + + (define (test-user-command command) + (let* ((timeout ,(file-append coreutils "/bin/timeout")) + (sudo ,(file-append sudo "/bin/sudo")) + (env ,(file-append coreutils "/bin/env")) + (prefix (string-append timeout " 90 " + (string-append sudo " -n -u " + ,%test-user " -- " env) + " HOME=")) + (home-directory (passwd:dir (getpwnam ,%test-user))) + (environment (string-append " XDG_RUNTIME_DIR=" runtime-dir " "))) + (string-append prefix home-directory environment command))) + + (define (run-as-test-user command) + (let* ((wrapped-command (string-append (test-user-command command) + " 2>&1")) + (port (open-input-pipe wrapped-command)) + (output (read-string port))) + (list (eqv? 0 + (status:exit-val (close-pipe port))) output))) + + (define (run-as-test-user-inheriting-output command) + (eqv? 0 + (status:exit-val (system (test-user-command command))))) + + ,@extra)) + +(define (home-system-test name os test-cases extra-prelude memory-size) + (vm-system-test name os test-cases + (home-prelude extra-prelude) memory-size)) + +(define (activate-home home-environment environment) + (let ((activate (file-append home-environment "/activate"))) + `(begin + (system* ,(file-append coreutils "/bin/install") "--directory" + "--mode=700" + ,(string-append "--owner=" %test-user) runtime-dir) + (run-as-test-user-inheriting-output (string-append ,environment + ,activate))))) + +(define (wait-for-home-service home-environment service) + (let ((herd (file-append home-environment "/profile/bin/herd"))) + `(wait-for (lambda () + (let ((result (run-as-test-user (string-append ,herd + " status " + ,service)))) + (and (car result) + (string-contains (cadr result) "It is running") #t))) + 60))) + +(define (home-service-assertions vm home-environment services assertions) + (append (map (lambda (service) + (assert-vm-true vm + (string-append service " is running") + (wait-for-home-service home-environment + service))) services) + (map (lambda (assertion) + (assert-vm-true vm + (car assertion) + (cdr assertion))) assertions))) + +(define* (home-activation-test home-environment + #:key (services '()) + (environment "") + (assertions '())) + (lambda (vm) + (let ((checks (home-service-assertions vm home-environment services + assertions))) + #~(begin + #$(assert-vm-true vm "home activates" + (activate-home home-environment environment)) + #$@checks)))) diff --git a/tests/pc/base.scm b/tests/pc/base.scm new file mode 100644 index 0000000..e016045 --- /dev/null +++ b/tests/pc/base.scm @@ -0,0 +1,58 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. + +(define-module (tests pc base) + #:use-module (gnu bootloader) + #:use-module (gnu bootloader grub) + #:use-module (gnu services) + #:use-module (gnu services xorg) + #:use-module (gnu system) + #:use-module (gnu system shadow) + #:use-module (guix gexp) + #:use-module (home) + #:use-module (system) + #:use-module (tests base) + #:use-module (tests home) + #:use-module (tests pc home) + #:export (%system-test)) + +;; GDM's session runs activation with DISPLAY, then Guix's xinitrc. +(define %home-session + (let ((activate (file-append pc-home-environment "/activate"))) + (program-file "home-session" + #~(begin + (unless (zero? (system* #$activate)) + (exit 1)) + (execl #$(xinitrc) "xinitrc"))))) + +;; The greeter test logs in as %test-user with this password. +(define %test-users + (map (lambda (user) + (if (string=? (user-account-name user) %test-user) + (user-account + (inherit user) + (password (crypt "test" "$6$abc"))) user)) + (operating-system-users pc-operating-system))) + +(define %services + (modify-services (operating-system-user-services pc-operating-system) + (gdm-service-type config => + (gdm-configuration (inherit config) + (x-session %home-session))))) + +;; The VM boots via -kernel; its MBR image rejects grub-efi. +(define %test-os + (operating-system + (inherit pc-operating-system) + (mapped-devices '()) + (bootloader (bootloader-configuration + (bootloader grub-bootloader) + (targets '("/dev/vda")))) + (users %test-users) + (services + %services))) + +(define %system-test + (home-system-test "pc" %test-os + (list (login-session-test pc-home-environment)) + %x-session-prelude 2048)) diff --git a/tests/pc/home.scm b/tests/pc/home.scm new file mode 100644 index 0000000..a17eafe --- /dev/null +++ b/tests/pc/home.scm @@ -0,0 +1,57 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. + +(define-module (tests pc home) + #:use-module (gnu packages ocr) + #:use-module (guix gexp) + #:use-module (tests base) + #:use-module (tests home) + #:export (%x-session-prelude login-session-test)) + +(define %x-session-prelude + `((use-modules (ice-9 ftw) + (srfi srfi-1)) + (define (find-process name) + (find (lambda (pid) + (let* ((file (string-append "/proc/" pid "/comm")) + (comm (false-if-exception (call-with-input-file file + read-string)))) + (string=? (string-append name "\n") + (or comm "")))) + (scandir "/proc"))))) + +(define (session-check home-environment) + `(and (let ((pid (wait-for (lambda () + (find-process "dwm")) 120))) + (and pid + (= (stat:uid (stat (string-append "/proc/" pid))) + (passwd:uid (getpwnam ,%test-user))))) + ,@(map (lambda (service) + (wait-for-home-service home-environment service)) + '("paseo-daemon" "status-bar" "xcompmgr")))) + +(define (login-session-test home-environment) + (lambda (vm) + #~(begin + (let ((vm #$vm) + (ocr #$(file-append ocrad "/bin/ocrad"))) + (format #t "waiting for GDM~%") + (test-assert "GDM starts" + (wait-for-file "/var/run/gdm/gdm.pid" vm + #:timeout 120)) + (format #t "waiting for the login screen~%") + (test-assert "GDM login screen is up" + (wait-for-screen-text vm + (lambda (text) + (string-contains text "Guix")) + #:ocr ocr + #:ocr-arguments '("--invert") + #:timeout 120)) + (test-assert "PC logs in and starts dwm" + (begin + ;; Select the user tile, then type the test password. + (marionette-type "\n" vm) + (sleep 2) + (marionette-type "test\n" vm) + (marionette-eval '#$(session-check home-environment) + vm))))))) diff --git a/tests/vps-home.scm b/tests/vps-home.scm deleted file mode 100644 index ae30c70..0000000 --- a/tests/vps-home.scm +++ /dev/null @@ -1,271 +0,0 @@ -;; Copyright (c) 2026 Jakub Czajka -;; License: GPL-3.0 or later. -;; -;; Run the Guix Home activate script and then the home tests. - -(define-module (tests vps-home) - #:use-module (gnu packages admin) - #:use-module (gnu packages base) - #:use-module (guix gexp) - #:use-module (guix packages) - #:use-module (conf home pi) - #:use-module (tests vps-system) - #:use-module (vps-home) - #:export (vps-home-test-cases)) - -(define %home-proxy-port - 16890) - -(define %activate - (file-append vps-home-environment "/activate")) -(define %herd - (file-append vps-home-environment "/profile/bin/herd")) -(define %claude - (file-append vps-home-environment "/profile/bin/claude")) -(define %pi - (file-append vps-home-environment "/profile/bin/pi")) -(define %timeout - (file-append coreutils "/bin/timeout")) - -(define %home-prelude - `(begin - (use-modules (ice-9 popen) - (ice-9 rdelim) - (ice-9 rw)) - - (define (run-command-output command) - (let* ((port (open-input-pipe command)) - (output (read-string port))) - (list (eqv? 0 - (status:exit-val (close-pipe port))) output))) - - (define one-second - internal-time-units-per-second) - (define (read-timed socket start) - (let loop - ((chunks '()) - (first-tick #f)) - (let* ((buffer (make-string 8192)) - (n (or (false-if-exception (read-string!/partial buffer socket)) - 0))) - (cond - ((positive? n) - (loop (cons (substring buffer 0 n) chunks) - (or first-tick - (- (get-internal-real-time) start)))) - ((pair? (car (select (list socket) - '() - '() 0))) - (list first-tick - (- (get-internal-real-time) start) - (string-concatenate-reverse chunks))) - (else #f))))) - - (define (proxy-request request) - (false-if-exception (let ((socket (socket PF_INET SOCK_STREAM 0)) - (address (make-socket-address AF_INET - INADDR_LOOPBACK - ,%home-proxy-port)) - (start (get-internal-real-time))) - (connect socket address) - (setsockopt socket SOL_SOCKET SO_RCVTIMEO - (cons 4 0)) - (display request socket) - (force-output socket) - (let ((response (read-timed socket start))) - (close-port socket) response)))) - - (define (fetch path body) - (let ((head (string-append "POST " path " HTTP/1.1\r\n" - "Host: 127.0.0.1\r\n")) - (tail (string-append "Content-Length: " - (number->string (string-length body)) - "\r\n\r\n" body))) - (proxy-request (string-append head - "Content-Type: application/json\r\n" - "x-api-key: sk-test\r\n" tail)))) - - (define (wait-for-port port) - (let ((address (make-socket-address AF_INET INADDR_LOOPBACK port))) - (let loop - ((remaining 20)) - (let ((socket (socket PF_INET SOCK_STREAM 0))) - (let ((accepting? (false-if-exception (connect socket address)))) - (close-port socket) - (if accepting? #t - (and (positive? remaining) - (sleep 1) - (loop (- remaining 1))))))))) - - (define-syntax ok? - (syntax-rules () - ((_ result body check ...) - (let ((response result)) - (and response - (let ((body (caddr response))) - (and check ...))))))) - - (define runtime-dir - (format #f "/run/user/~a" - (passwd:uid (getpwnam ,%test-user)))) - (system* ,(file-append coreutils "/bin/install") "--directory" - "--mode=700" - ,(string-append "--owner=" %test-user) runtime-dir) - (define (run command) - (let ((prefix (format #f - "~a 90 ~a -n -u ~a -- ~a XDG_RUNTIME_DIR=" - ,%timeout - ,(file-append sudo "/bin/sudo") - ,%test-user - ,(file-append coreutils "/bin/env")))) - (run-command-output (string-append prefix runtime-dir " " command - " 2>&1")))) - - (define (run-contains command needle) - (let ((result (run command))) - (and (car result) - (string-contains (cadr result) needle) #t))))) - -(define (req-with-options stream fields) - (string-append "{\"stream\":" stream - ",\"model\":\"deepseek-chat\",\"max_tokens\":16," fields - "\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}")) - -(define %req-classifier-fields - "\"reasoning_effort\":\"high\",\"output_config\":{\"budget\":\"auto\"},") - -(define %stream-request - (req-with-options "true" "")) - -(define %req-thinking-fields - "\"thinking\":{\"type\":\"enabled\",\"budget_tokens\":1000},") - -(define %count-tokens-request - (string-append "{\"model\":\"deepseek-chat\"," %req-classifier-fields - "\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}")) - -(define %home-activation-body - `(let* ((env (string-append "CLAUDE_PROXY_UPSTREAM=https://127.0.0.1:" - (number->string ,fake-upstream-port) - " GUILE_TLS_CERTIFICATE_DIRECTORY=" - ,claude-proxy-test-ca-dir " ")) - (result (run (string-append env - ,%activate " > /tmp/home-activate.log")))) - (unless (car result) - (format (current-error-port) "~a" - (call-with-input-file "/tmp/home-activate.log" - read-string))) - (car result))) - -(define (home-herd-body service) - `(run-contains (string-append ,%herd " status " - ,service) "It is running")) - -(define %health-stream-body - `(let ((stream (fetch "/v1/messages" - ,%stream-request))) - (and (ok? (proxy-request "GET /health HTTP/1.1\nHost: 127.0.0.1\n\n") - body - (string-contains body "200") - (string-contains body "\"status\":\"ok\"")) - (ok? stream body - (string-contains body "data: [DONE]") - (string-contains body "message_start")) - (< (car stream) - (* 5/2 one-second)) - (>= (cadr stream) - (* 5/2 one-second))))) - -(define %classifier-rewrite-body - `(let* ((plain (fetch "/v1/messages" - ,(req-with-options "false" %req-classifier-fields))) - (explicit (fetch "/v1/messages" - ,(req-with-options "false" %req-thinking-fields))) - (tokens (fetch "/v1/messages/count_tokens" - ,%count-tokens-request))) - (and (ok? plain - body - (string-contains body "200") - (string-contains body "\"type\":\"disabled\"") - (not (string-contains body "reasoning_effort")) - (not (string-contains body "output_config"))) - (ok? explicit body - (string-contains body "\"type\":\"enabled\"") - (string-contains body "budget_tokens")) - (ok? tokens - body - (string-contains body "200") - (string-contains body "reasoning_effort") - (string-contains body "output_config") - (not (string-contains body "thinking")))))) - -(define %relay-and-fail-fast-body - `(and (ok? (fetch "/other" - "{\"stream\":false,\"model\":\"x\",\"max_tokens\":1}") - body - (string-contains body "401") - (string-contains body "authentication_error")) - (stop-service 'fake-upstream) - (let ((down (fetch "/v1/messages" - ,%stream-request))) - (and (ok? down body - (string-contains body "502") - (string-contains body "upstream unavailable")) - (< (cadr down) - (* 2 one-second)) - (start-service 'fake-upstream) - (wait-for-port ,fake-upstream-port))))) - -(define %claude-e2e-body - `(let* ((env (string-append - "HOME=/tmp/claude-e2e ANTHROPIC_API_KEY=test-key " - "ANTHROPIC_BASE_URL=http://127.0.0.1:" - (number->string ,%home-proxy-port) " DISABLE_TELEMETRY=1 " - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 ")) - (claude ,%claude) - (args " --bare --model claude-sonnet-4-6 -p hello 2>&1 < /dev/null") - (command (string-append env - ,%timeout " 90 " claude args)) - (result (run-command-output command))) - (and (car result) - (string-contains (cadr result) "Hello from fake") #t))) - -(define %pi-version-body - `(run-contains (string-append "HOME=/tmp/pi-e2e " - ,%pi " --version") - ,(package-version pi))) - -(define (assert-home marionette label body) - #~(test-assert #$label - (let ((result (marionette-eval '#$body - #$marionette))) - (or (eq? result #t) - (begin - (format (current-error-port) "~a: ~s~%" - #$label result) #f))))) - -(define (vps-home-test-cases marionette) - #~(begin - (marionette-eval '#$%home-prelude - #$marionette) - #$(assert-home marionette "home: vps-home activates" - %home-activation-body) - #$(assert-home marionette "home: claude-proxy is listening" - `(wait-for-port ,%home-proxy-port)) - #$(assert-home marionette "home: claude-proxy is running" - (home-herd-body "claude-proxy")) - #$(assert-home marionette "home: paseo-daemon is running" - (home-herd-body "paseo-daemon")) - #$(assert-home marionette "home: pi runs" %pi-version-body) - #$(assert-home marionette - "home: claude-proxy: health and incremental SSE" - %health-stream-body) - #$(assert-home marionette - "home: claude-proxy: thinking rewrite only for classifier calls" - %classifier-rewrite-body) - #$(assert-home marionette - "home: claude-proxy: Claude Code -p gets a reply" - %claude-e2e-body) - #$(assert-home marionette - "home: claude-proxy: upstream errors relay and fail fast" - %relay-and-fail-fast-body))) diff --git a/tests/vps-system.scm b/tests/vps-system.scm deleted file mode 100644 index aca765c..0000000 --- a/tests/vps-system.scm +++ /dev/null @@ -1,154 +0,0 @@ -;; Copyright (c) 2026 Jakub Czajka -;; License: GPL-3.0 or later. -;; -;; System tests and the VM test operating system. - -(define-module (tests vps-system) - #:use-module (gnu tests) - #:use-module (gnu system) - #:use-module ((gnu services) - #:select ((delete . remove-service) service simple-service - modify-services)) - #:use-module (gnu services shepherd) - #:use-module (gnu services base) - #:use-module (gnu services ssh) - #:use-module (gnu services networking) - #:use-module (gnu packages guile) - #:use-module (gnu packages ssh) - #:use-module (gnu packages tls) - #:use-module (conf vps sshd) - #:use-module (guix gexp) - #:use-module (vps-system) - #:export (%vps-test-os %test-user daemons-test-cases sshd-test-cases - fake-upstream-port claude-proxy-test-ca-dir)) - -(define %test-user - "dak") - -(define %sshd-login-keypair - (computed-file "sshd-login-keypair" - #~(begin - (mkdir #$output) - (chdir #$output) - (let ((keygen #$(file-append openssh "/bin/ssh-keygen")) - (args '("-t" "ed25519" "-f" "login-key" "-N" ""))) - (unless (zero? (apply system* keygen args)) - (exit 1)))))) - -(define %sshd-key-auth-body - `(let ((ssh ,(file-append openssh "/bin/ssh")) - (key "/tmp/login-key")) - (copy-file ,(file-append %sshd-login-keypair "/login-key") key) - (chmod key #o600) - (zero? (system* ssh "-n" "-i" key - ,@(append '("-oStrictHostKeyChecking=no" - "-oUserKnownHostsFile=/dev/null" - "-oBatchMode=yes" "-oConnectTimeout=10" "-p") - (list (number->string %sshd-port) - (string-append %test-user "@localhost") - "true")))))) - -(define (sshd-test-cases marionette) - #~(test-assert "sshd: shell command via key auth" - (begin - (marionette-eval '(start-service 'ssh-daemon) - #$marionette) - (wait-for-tcp-port #$%sshd-port - #$marionette) - (marionette-eval '#$%sshd-key-auth-body - #$marionette)))) - -;; QEMU's default e1000 NIC is ens3, not eth0. -(define %static-network-config-to-avoid-qemu-dhcp-hang - (let ((addr (network-address (device "ens3") - (value "10.0.2.15/24"))) - (route (network-route (destination "default") - (gateway "10.0.2.2")))) - (static-networking (addresses (list addr)) - (routes (list route))))) - -(define %static-networking - (service static-networking-service-type - (list %static-network-config-to-avoid-qemu-dhcp-hang))) - -(define fake-tls-cert - (local-file "claude-proxy-test-cert.pem")) - -(define claude-proxy-test-ca-dir - (file-union "claude-proxy-test-ca" - `(("ca.pem" ,fake-tls-cert)))) - -(define fake-upstream-port - 19998) - -(define (fake-upstream-script cert key port) - (with-imported-modules '((tests fake-llm)) - (with-extensions (list guile-gnutls guile-json-4) - #~(begin - (use-modules (tests fake-llm)) - (run-fake-llm #$cert - #$key - #$port))))) - -(define fake-upstream-program - (program-file "fake-claude-upstream" - (fake-upstream-script fake-tls-cert - (local-file "claude-proxy-test-key.pem") - fake-upstream-port))) - -(define fake-upstream-start - #~(make-forkexec-constructor (list #$fake-upstream-program) - #:log-file "/var/log/fake-upstream.log")) - -(define fake-upstream-service - (shepherd-service (provision '(fake-upstream)) - (start fake-upstream-start) - (stop #~(make-kill-destructor)) - (auto-start? #t))) - -(define (authorize-login config) - (let ((public-key (file-append %sshd-login-keypair "/login-key.pub"))) - (openssh-configuration (inherit config) - (authorized-keys `((,%test-user ,public-key)))))) - -(define %test-services - (cons* %static-networking - (simple-service 'fake-upstream shepherd-root-service-type - (list fake-upstream-service)) - (modify-services (operating-system-user-services vps-operating-system) - (remove-service dhcpcd-service-type) - (openssh-service-type config => - (authorize-login config))))) - -(define %nonguix-signing-key - "C1FD53E5D4CE971933EC50C9F307AE2171A2D3B52C804642A7A35F84F3A4EA98") - -(define %nonguix-acl-test - `(begin - (use-modules (ice-9 string-fun) - (ice-9 textual-ports)) - (call-with-input-file "/etc/guix/acl" - (lambda (port) - (string-contains (get-string-all port) - ,%nonguix-signing-key))))) - -(define (daemons-test-cases marionette) - #~(begin - (test-assert "services: resolv.conf is installed" - (marionette-eval '(file-exists? "/etc/resolv.conf") - #$marionette)) - (test-assert "services: DNS and NTP are up" - (and (wait-for-tcp-port 53 - #$marionette) - (marionette-eval '(start-service 'ntpd) - #$marionette))) - (test-assert "services: nonguix substitutes are authorized" - (marionette-eval '#$%nonguix-acl-test - #$marionette)))) - -(define %vps-test-os - (marionette-operating-system (operating-system - (inherit vps-operating-system) - (services - %test-services)) - #:imported-modules '((gnu services herd)))) diff --git a/tests/vps/base.scm b/tests/vps/base.scm new file mode 100644 index 0000000..4d09943 --- /dev/null +++ b/tests/vps/base.scm @@ -0,0 +1,22 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. +;; +;; The VPS VM test entry point. + +(define-module (tests vps base) + #:use-module (tests home) + #:use-module (tests vps home) + #:use-module (tests vps system) + #:use-module (vps-home) + #:export (%vps-system-test)) + +(define %vps-system-test + (home-system-test "vps" %vps-test-os + (list daemons-test-case + (home-activation-test vps-home-environment + #:services '("claude-proxy" + "paseo-daemon") + #:environment + %activation-environment + #:assertions %proxy-assertions) + sshd-test-case) %proxy-prelude 1024)) diff --git a/tests/vps/claude-proxy-live.sh b/tests/vps/claude-proxy-live.sh new file mode 100755 index 0000000..0d504fc --- /dev/null +++ b/tests/vps/claude-proxy-live.sh @@ -0,0 +1,183 @@ +#!/bin/sh +# Copyright (c) 2026 Jakub Czajka +# License: GPL-3.0 or later. +# +# Differential test against the live claude-proxy: for each sample, send it +# to both the deployed service and this build, then diff their canonicalized +# log-and-response transcripts; the key and live log are host state. + +repo_root=$(cd "$(dirname "$0")/../.." && pwd) +src_port=16890 +src_log="${XDG_STATE_HOME:-$HOME/.local/state}/claude-proxy.log" + +tag=$(printf '%s' "$repo_root" | cksum | cut --delimiter=' ' --fields=1) +dst_port=$((17000 + tag % 1000)) +base="/tmp/$tag-claude-proxy-live" + +report() { + echo "❌ $1" + shift + printf ' %s\n' "$@" +} + +die() { + report "$@" + exit 1 +} + +canonicalize_log_slice() { + sed --regexp-extended \ + --expression 's/^[0-9-]+ [0-9:]+ //' \ + --expression '/New request\. peer=/d; s/req=[0-9a-f]+ /req=X /' \ + --expression 's/ ms=[0-9]+//g; s/ query=[^ ]*//' +} + +canonicalize_response() { + sed --regexp-extended \ + --expression 's/"(id|text|thinking|signature)":"[^"]*"/"\1":"X"/g' \ + --expression 's/"([a-z_]+_tokens)":[0-9]+/"\1":N/g' \ + --expression '/event: ping/d; /"type":"ping"/d' "$1" | uniq +} + +diff_files() { + diff --unified "$1" "$2" + diff_status=$? + [ "$diff_status" -le 1 ] && return "$diff_status" + die "diff failed with status $diff_status; no comparison." \ + "Reference: $1" "This tree: $2" +} + +accept_difference() { + printf ' accept this difference? [y/N] ' + if ! read -r answer || [ "$answer" != y ]; then + die "not accepted: an unchanged build skips the test," \ + "so change the proxy before rerunning." + fi + echo " difference accepted." +} + +sample_side() { + label=$1 side=$2 route=$3 port=$4 log=$5 + shift 5 + mark=$(( $(wc --lines < "$log") + 1 )) + response="$base.$side.response" transcript="$base.$side.transcript" + id= proto= code= rest= polls=0 + curl --silent --show-error --include --no-buffer --max-time 90 \ + --header 'content-type: application/json' \ + --header "x-api-key: $key" "$@" \ + "http://127.0.0.1:$port$route" > "$response" 2>&1 + if ! read -r proto code rest < "$response" || [ "$code" != 200 ]; then + die "the $label sample on $response returned: $proto $code $rest" \ + "Two identical failures would pass the diff." + fi + id=$(tail --lines=+"$mark" "$log" | grep --fixed-strings "probe=$tag" \ + | grep --only-matching --extended-regexp 'req=[0-9a-f]+' \ + | head --lines=1) + [ -n "$id" ] || + die "the $label sample is not tagged in $log." \ + "Does the deployed build log the query?" + until tail --lines=+"$mark" "$log" | grep --quiet \ + --extended-regexp "$id (event=rsp|Done\.|Aborted\.)"; do + [ "$polls" -lt 100 ] || + die "the $label sample did not finish in 10 s;" "see $log." + sleep 0.1 + polls=$((polls + 1)) + done + tail --lines=+"$mark" "$log" | grep --fixed-strings "$id " \ + | canonicalize_log_slice > "$transcript" + canonicalize_response "$response" >> "$transcript" +} + +compare_sample() { + name=$1 endpoint=$2 + shift 2 + sample_side "$name" src "$endpoint" "$src_port" "$src_log" "$@" + sample_side "$name" dst "$endpoint" "$dst_port" "$base.log" "$@" + echo "--- $name:" + if diff_files "$base.src.transcript" "$base.dst.transcript"; then + echo "transcripts IDENTICAL" + else + report "the two proxies' transcripts differ for $name." \ + "Blanked above: timestamps, request ids, timings, the query," \ + "ids, text, thinking, signatures, token counts and pings. A" \ + "hunk is a change in the relay or the deployed service." \ + "Transcripts: $base.src.transcript $base.dst.transcript" \ + "raw responses: $base.src.response $base.dst.response" + accept_difference + fi +} + +stop_proxy() { + kill "$dst_pid" 2>/dev/null + waits=0 + while [ "$waits" -lt 20 ]; do + kill -0 "$dst_pid" 2>/dev/null || return 0 + sleep 0.1 + waits=$((waits + 1)) + done + kill -KILL "$dst_pid" 2>/dev/null +} + +rm --force "$base".* + +# Drop GUILE_* so the system profile's modules don't shadow guix's. +build_proxy() { + env -u GUILE_LOAD_PATH -u GUILE_LOAD_COMPILED_PATH \ + -u GUILE_EXTENSIONS_PATH GUIX_PACKAGE_PATH="$repo_root" \ + guix build --load-path="$repo_root" \ + --expression='(@ (conf home claude-proxy) claude-proxy)' "$@" +} + +# A dry run prints the program to stdout only when the store already has it; +# missing derivations go to stderr, so empty output means the build must run. +cached=$(build_proxy --dry-run --no-substitutes) || + die "cannot evaluate the claude-proxy package." +if [ -n "$cached" ]; then + echo "claude-proxy is already in the store ($cached);" + echo "skipping the differential." + exit 0 +fi +dst_proxy=$(build_proxy) || die "the claude-proxy build failed." +dst_proxy=$dst_proxy/bin/claude-proxy + +read -r key 2>/dev/null < "/run/user/$(id --user)/claude-apikey" + +env PROXY_PORT="$dst_port" \ + CLAUDE_PROXY_UPSTREAM=https://api.deepseek.com/anthropic \ + CLAUDE_PROXY_TIMEOUT=60 \ + "$dst_proxy" > "$base.log" 2>&1 & +dst_pid=$! +trap stop_proxy 0 + +tries=0 +until grep --quiet "Startup. listen=$dst_port" "$base.log"; do + [ "$tries" -lt 50 ] || + die "the proxy did not start on $dst_port within 5 s." \ + "Its log is at $base.log." + sleep 0.1 + tries=$((tries + 1)) +done + +echo "--- this tree on $dst_port against the live service on $src_port:" + +# Health never reaches the upstream, so override the default timeout. +compare_sample health "/?probe=$tag" --max-time 10 + +compare_sample plain "/v1/messages?probe=$tag" \ + --data '{"stream":false,"model":"deepseek-chat", + "max_tokens":32,"messages":[{"role":"user", + "content":"Reply with the single word OK"}]}' +compare_sample stream "/v1/messages?probe=$tag" \ + --data '{"stream":true,"model":"deepseek-chat", + "max_tokens":32,"messages":[{"role":"user", + "content":"Reply with the single word OK"}]}' +compare_sample count_tokens \ + "/v1/messages/count_tokens?probe=$tag" \ + --data '{"model":"deepseek-chat", + "messages":[{"role":"user","content": + "Reply with the single word OK"}]}' + +echo "--- this tree's proxy log:" +cat "$base.log" +echo "--- proxy log events:" +grep --only-matching 'event=[a-z-]*' "$base.log" | sort | uniq --count diff --git a/tests/vps/claude-proxy-test-cert.pem b/tests/vps/claude-proxy-test-cert.pem new file mode 100644 index 0000000..5b72072 --- /dev/null +++ b/tests/vps/claude-proxy-test-cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDHDCCAgSgAwIBAgIUOX0m6IigoZ9XlXsv4tFfa8LcbaQwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJMTI3LjAuMC4xMCAXDTI2MDkwMzE3NTQyOFoYDzIxMjYw +ODEwMTc1NDI4WjAUMRIwEAYDVQQDDAkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQC7OSYfhTQwzUSYcY2QPm0PoMiuysvlEpd+18b/b8pO +T7vBA+w/0QPPtExrX4TbO9nZox7/SW9+WOigcsy2gaTRs5vCsKCpPQlH5atao4Pv +cLJ3uESt+XqwMpowIp/GXFp3NL3j0q0rcrvisa2pcOOpLiVi2lmAVqmhKXVL+ITG +u8HtDnw4duTErXFVQBRslkwrbcwW1itiiqdJXZ6oz18u5aQ/e5rRV5Rk7Vojxzus +lN4vqpDTmUiPVk5aCQrOdgiTcIYEKI8Sy4rtGyBgKmAUEBzqIu8iphshlKWJ5B/N +i9PQsQV+Zyx8rY72tlpj3NLcg6KhW8RnJ2qkV9QhFTpLAgMBAAGjZDBiMB0GA1Ud +DgQWBBRKBG6nhcv95RLD+OfDnNFg+Y5pNjAfBgNVHSMEGDAWgBRKBG6nhcv95RLD ++OfDnNFg+Y5pNjAPBgNVHREECDAGhwR/AAABMA8GA1UdEwEB/wQFMAMBAf8wDQYJ +KoZIhvcNAQELBQADggEBACrqbJ7HzFIBecusXnh+MpiyZ9y1VLwvMNe7MqdBY5Qt +w/d2UxS+jgyyt/TR4V7y4ZsfWZdtLNCK414+3eiQqHXjD2O0Yc2upoC0lziahYNU +O68ehOFUyrf1HTpCbBZDzxxKdvCekCEbE5nj6a4Gv+OTqiEt4+kHcBkS8fmiZwdc +RQuuMdel3BpBBwb0o9a+SiKV+3MOr2BD8BnA/9u0lEo1xONBY6K4yikWp9lztmqw +vuuyCM+VZg5tsm1CQISIdthoAr9bVFsO1Zc2ER6HAWy+yJBXdF12Juj7bBHFS7a6 +9l8PDR6eSWU9ebKvCAcfN46Vrm4CIhr2UPH3DVHRIWw= +-----END CERTIFICATE----- diff --git a/tests/vps/claude-proxy-test-key.pem b/tests/vps/claude-proxy-test-key.pem new file mode 100644 index 0000000..d0c0183 --- /dev/null +++ b/tests/vps/claude-proxy-test-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7OSYfhTQwzUSY +cY2QPm0PoMiuysvlEpd+18b/b8pOT7vBA+w/0QPPtExrX4TbO9nZox7/SW9+WOig +csy2gaTRs5vCsKCpPQlH5atao4PvcLJ3uESt+XqwMpowIp/GXFp3NL3j0q0rcrvi +sa2pcOOpLiVi2lmAVqmhKXVL+ITGu8HtDnw4duTErXFVQBRslkwrbcwW1itiiqdJ +XZ6oz18u5aQ/e5rRV5Rk7VojxzuslN4vqpDTmUiPVk5aCQrOdgiTcIYEKI8Sy4rt +GyBgKmAUEBzqIu8iphshlKWJ5B/Ni9PQsQV+Zyx8rY72tlpj3NLcg6KhW8RnJ2qk +V9QhFTpLAgMBAAECggEAMlFGLzOAFtucI3JlTw6QBiK6vMtxKBQqliMM7wrO7uQb +/GB/Bpm4sgJthXALB1bbElR2WLsWVXk0sCaaYTSPpPJmGtmYnFN0opeVyYrnwxrh +RC7Ieo9xy1gWO3iaw1d/0sjgfhHZi7NOzrrdBwx5izcFQj+XzVe9SDyZszzMBpLp +ma80qvyNw34RHQEQpUTvl1fXuIh1VH42SUwIRQtMrUYpyoEQOJfc7Cwy0/dzMnt+ +XCF9mXu9wyzrfXvnGJv2TjobzqhUx1JkqHiW5TGI/3cKpTecrT6WMUGzt0v3xTS4 +TxGhmnCy4qE5xT9po29k94vulBhVD9PT4/1OaSke9QKBgQD/GkaxIKYqqtPGnqf8 +Li4GKJspMuhbF7gM3LCqIqM6wgUlIazBPVedk9BTXlMiYQAQYBlp5Rh6xxxh8+Dg +UFVMPFq2LAIb41IEV51efkZNgGnVC0zeyLYmI0tVBJEp4A8itqgerizD4Lbg9sBP +7q5cClgu12LSaFMZuXmlRaIcDwKBgQC74b8Pc8y70LsKoaIQJLALwOONpJuPCLDj +B89mh7RtYRH0slB8QiJYRNOVp9mw9FYZFQkwBBbCCiTagjtBcTLiDc/OkZdln2pa +KWzRztDN97Ijnj3zCac8SyrJHoUu12yUjzQ2GrC2kQSEjj/RkpsQ3vYd6aEkKmAw +6mKqKNRyBQKBgQCDxtEJorHzjHcFPOPN0xUXPVaZe6CnnaMHkeD4ohfrvFnoCnMx +Bz0BO1/8ENelBLKBwwKdvyhcFArHVrGtbhIB5ZN+U1FrkovFjnTOYTBzzIfe841r +8AaXwNejPU63cPSgm/ZQkuyw6p3Nq+k/4S3Ugct3tu9nfVigCz2ZcFUDZQKBgEec +JGlsVqVjSlckAhQrF5pzO4gaLFxZEKqHqIpIwQFLlT9x03F494QzP330CuoCRuqq +dOUDOfVdTmymZJVt4tn8L69pGI5YM34H+f0B2d4XQaOHxc7jaAV4FOexJUwUOcNp +zZmtlJsRLOqlGTf0q/vDL4V5Lb0OFbmvLEn04/xNAoGBAIfcx+E8sdVvs0gIrOv5 +wsmyx0Mcr10GF01QlePxgBgZNfWIVuZomGc82gT606K5R6L4R129Jzvs087gBLVK +C/j9JqbFZ146gKD91lQMinGffCGa9XcXLzLph2MCeAyO46z5jNqSuWk0TL3tP8o7 +XCrVbiudrikX2WtdtF3aNz02 +-----END PRIVATE KEY----- diff --git a/tests/vps/fake-llm.scm b/tests/vps/fake-llm.scm new file mode 100644 index 0000000..fb1bc13 --- /dev/null +++ b/tests/vps/fake-llm.scm @@ -0,0 +1,112 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. +;; +;; The build sandbox has no network route or API key, so this fake stands +;; in for DeepSeek; use make test-claude-proxy-live for the live diff. + +(define-module (tests vps fake-llm) + #:use-module (gnutls) + #:use-module (ice-9 threads) + #:use-module (json) + #:use-module (rnrs bytevectors) + #:use-module (web request) + #:use-module (web uri) + #:export (run-fake-llm)) + +(define (raw-response status content-type extra-header body) + (string-append "HTTP/1.1 " status "\r\nContent-Type: " content-type + (string-append "\r\n" extra-header + "Connection: close\r\n\r\n" body))) + +(define (respond! sock text) + (display text sock) + (force-output sock)) + +(define (respond-sized! sock status content-type body) + (let ((byte-count (number->string (bytevector-length (string->utf8 body))))) + (respond! sock + (raw-response status content-type + (string-append "Content-Length: " byte-count + "\r\n") body)))) + +(define (chunk text) + (string-append (number->string (bytevector-length (string->utf8 text)) 16) + "\r\n" text "\r\n")) + +(define (respond-stream! sock) + (respond! sock + (raw-response "200 OK" "text/event-stream" + "Transfer-Encoding: chunked\r\n" "")) + (respond! sock + (chunk (string-append "event: message_start\ndata: " + (scm->json-string '((type . "message_start"))) + "\n\n"))) + (sleep 3) + (respond! sock + (string-append (chunk "data: [DONE]\n\n") "0\r\n\r\n"))) + +(define %claude-reply + (scm->json-string `((id . "msg_test") (type . "message") + (role . "assistant") + (model . "claude-sonnet-4-6") + (content unquote + #(((type . "text") (text . "Hello from fake")))) + (stop_reason . "end_turn") + (stop_sequence . null) + (usage (input_tokens . 1) + (output_tokens . 3))))) + +(define (read-request-fields sock) + (let* ((request (read-request sock)) + (uri (request-uri request)) + (body (read-request-body request))) + (list (uri-path uri) + (uri-query uri) + (utf8->string (or body #vu8()))))) + +(define %unauthorized-response + (scm->json-string '((error (type . "authentication_error"))))) + +(define (dispatch-request! sock path query body-str) + (cond + ((and (equal? path "/v1/messages") + (equal? query "beta=true")) + (respond-sized! sock "200 OK" "application/json" %claude-reply)) + ((and (equal? path "/v1/messages") + (string-contains body-str "\"stream\":true")) + (respond-stream! sock)) + ((or (equal? path "/v1/messages") + (equal? path "/v1/messages/count_tokens")) + (respond-sized! sock "200 OK" "application/json" body-str)) + (else (respond-sized! sock "401 Unauthorized" "application/json" + %unauthorized-response)))) + +(define (serve-tls-session! conn cert key) + (let ((session (make-session connection-end/server)) + (cred (make-certificate-credentials))) + (set-session-priorities! session "NORMAL:%COMPAT:-VERS-SSL3.0") + (set-session-transport-fd! session + (fileno conn)) + (set-certificate-credentials-x509-key-files! cred cert key + x509-certificate-format/pem) + (set-session-credentials! session cred) + (handshake session) + (let ((sock (session-record-port session))) + (false-if-exception (apply dispatch-request! sock + (read-request-fields sock))) + (false-if-exception (close-port sock))))) + +(define (run-fake-llm cert key port) + (sigaction SIGPIPE SIG_IGN) + (let ((listener (socket PF_INET SOCK_STREAM 0))) + (setsockopt listener SOL_SOCKET SO_REUSEADDR 1) + (bind listener + (make-socket-address AF_INET INADDR_LOOPBACK port)) + (listen listener 16) + (let loop + ((conn (car (accept listener)))) + (call-with-new-thread (lambda () + (false-if-exception (serve-tls-session! conn + cert key)) + (false-if-exception (close-port conn)))) + (loop (car (accept listener)))))) diff --git a/tests/vps/home.scm b/tests/vps/home.scm new file mode 100644 index 0000000..d973a8a --- /dev/null +++ b/tests/vps/home.scm @@ -0,0 +1,184 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. +;; +;; VPS home tests and claude-proxy assertions. + +(define-module (tests vps home) + #:use-module (conf home pi) + #:use-module (guix gexp) + #:use-module (guix packages) + #:use-module (tests vps system) + #:use-module (vps-home) + #:export (%activation-environment %proxy-assertions %proxy-prelude)) + +(define %home-proxy-port + 16890) + +(define %claude + (file-append vps-home-environment "/profile/bin/claude")) + +(define %pi + (file-append vps-home-environment "/profile/bin/pi")) + +(define %activation-environment + `(string-append "CLAUDE_PROXY_UPSTREAM=https://127.0.0.1:" + ,(number->string fake-upstream-port) + " GUILE_TLS_CERTIFICATE_DIRECTORY=" + ,claude-proxy-test-ca-dir " ")) + +(define %proxy-prelude + `((use-modules (ice-9 rw)) + (define one-second + internal-time-units-per-second) + + (define (read-timed socket start) + (let loop + ((chunks '()) + (first-tick #f)) + (let* ((buffer (make-string 8192)) + (n (or (false-if-exception (read-string!/partial buffer socket)) + 0))) + (cond + ((positive? n) + (loop (cons (substring buffer 0 n) chunks) + (or first-tick + (- (get-internal-real-time) start)))) + ((pair? (car (select (list socket) + '() + '() 0))) + (list first-tick + (- (get-internal-real-time) start) + (string-concatenate-reverse chunks))) + (else #f))))) + + (define (proxy-request request) + (let ((port ,%home-proxy-port)) + (false-if-exception (let ((socket (socket PF_INET SOCK_STREAM 0)) + (address (make-socket-address AF_INET + INADDR_LOOPBACK port)) + (start (get-internal-real-time))) + (connect socket address) + (setsockopt socket SOL_SOCKET SO_RCVTIMEO + (cons 4 0)) + (display request socket) + (force-output socket) + (let ((response (read-timed socket start))) + (close-port socket) response))))) + + (define (fetch path body) + (let ((head (string-append "POST " path " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n")) + (tail (string-append "Content-Length: " + (number->string (string-length body)) + "\r\n\r\n" body))) + (proxy-request (string-append head + "Content-Type: application/json\r\n" + "x-api-key: sk-test\r\n" tail)))) + + (define (wait-for-port port) + (let ((address (make-socket-address AF_INET INADDR_LOOPBACK port))) + (wait-for (lambda () + (let ((socket (socket PF_INET SOCK_STREAM 0))) + (let ((accepting? (false-if-exception (connect socket + address)))) + (close-port socket) accepting?))) 20))) + + (define (body-contains? response text) + (and response + (string-contains (caddr response) text))))) + +(define (req-with-options stream fields) + (string-append "{\"stream\":" stream + ",\"model\":\"deepseek-chat\",\"max_tokens\":16," fields + "\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}")) + +(define %req-classifier-fields + "\"reasoning_effort\":\"high\",\"output_config\":{\"budget\":\"auto\"},") + +(define %stream-request + (req-with-options "true" "")) + +(define %req-thinking-fields + "\"thinking\":{\"type\":\"enabled\",\"budget_tokens\":1000},") + +(define %count-tokens-request + (string-append "{\"model\":\"deepseek-chat\"," %req-classifier-fields + "\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}")) + +(define check-proxy-health-and-stream + `(let ((health (proxy-request "GET /health HTTP/1.1\nHost: 127.0.0.1\n\n")) + (stream (fetch "/v1/messages" + ,%stream-request))) + (and (body-contains? health "200") + (body-contains? health "\"status\":\"ok\"") + (body-contains? stream "data: [DONE]") + (body-contains? stream "message_start") + (< (car stream) + (* 5/2 one-second)) + (>= (cadr stream) + (* 5/2 one-second))))) + +(define check-classifier-rewrite + `(let* ((plain (fetch "/v1/messages" + ,(req-with-options "false" %req-classifier-fields))) + (explicit (fetch "/v1/messages" + ,(req-with-options "false" %req-thinking-fields))) + (tokens (fetch "/v1/messages/count_tokens" + ,%count-tokens-request))) + (and (body-contains? plain "200") + (body-contains? plain "\"type\":\"disabled\"") + (not (body-contains? plain "reasoning_effort")) + (not (body-contains? plain "output_config")) + (body-contains? explicit "\"type\":\"enabled\"") + (body-contains? explicit "budget_tokens") + (body-contains? tokens "200") + (body-contains? tokens "reasoning_effort") + (body-contains? tokens "output_config") + (not (body-contains? tokens "thinking"))))) + +(define check-relay-and-fail-fast + `(let ((other (fetch "/other" + "{\"stream\":false,\"model\":\"x\",\"max_tokens\":1}"))) + (and (body-contains? other "401") + (body-contains? other "authentication_error") + (stop-service 'fake-upstream) + (let ((down (fetch "/v1/messages" + ,%stream-request))) + (and (body-contains? down "502") + (body-contains? down "upstream unavailable") + (< (cadr down) + (* 2 one-second)) + (start-service 'fake-upstream) + (wait-for-port ,fake-upstream-port)))))) + +(define check-claude-reply + `(let* ((env (string-append + "HOME=/tmp/claude-e2e ANTHROPIC_API_KEY=test-key " + "ANTHROPIC_BASE_URL=http://127.0.0.1:" + (number->string ,%home-proxy-port) " DISABLE_TELEMETRY=1 " + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 ")) + (args " --bare --model claude-sonnet-4-6 -p hello < /dev/null") + (result (run-as-test-user (string-append env + ,%claude args)))) + (and (car result) + (string-contains (cadr result) "Hello from fake") #t))) + +(define check-pi-version + `(let ((result (run-as-test-user (string-append "HOME=/tmp/pi-e2e " + ,%pi " --version")))) + (and (car result) + (string-contains (cadr result) + ,(package-version pi)) #t))) + +(define %proxy-assertions + (list (cons "home: claude-proxy: accepts connections" + `(wait-for-port ,%home-proxy-port)) + (cons "home: claude-proxy: Claude Code -p gets a reply" + check-claude-reply) + (cons "home: claude-proxy: health and incremental SSE" + check-proxy-health-and-stream) + (cons "home: claude-proxy: thinking rewrite only for classifier calls" + check-classifier-rewrite) + (cons "home: claude-proxy: upstream errors relay and fail fast" + check-relay-and-fail-fast) + (cons "home: pi runs" check-pi-version))) diff --git a/tests/vps/system.scm b/tests/vps/system.scm new file mode 100644 index 0000000..5b228e0 --- /dev/null +++ b/tests/vps/system.scm @@ -0,0 +1,143 @@ +;; Copyright (c) 2026 Jakub Czajka +;; License: GPL-3.0 or later. +;; +;; System tests and the VM test operating system. + +(define-module (tests vps system) + #:use-module (conf vps sshd) + #:use-module (gnu packages guile) + #:use-module (gnu packages ssh) + #:use-module (gnu packages tls) + #:use-module ((gnu services) + #:select ((delete . remove-service) modify-services service + simple-service)) + #:use-module (gnu services base) + #:use-module (gnu services networking) + #:use-module (gnu services shepherd) + #:use-module (gnu services ssh) + #:use-module (gnu system) + #:use-module (guix gexp) + #:use-module (tests base) + #:use-module (vps-system) + #:export (%vps-test-os claude-proxy-test-ca-dir daemons-test-case + fake-upstream-port sshd-test-case)) + +(define %sshd-login-keypair + (computed-file "sshd-login-keypair" + #~(begin + (mkdir #$output) + (chdir #$output) + (let ((keygen #$(file-append openssh "/bin/ssh-keygen")) + (args '("-t" "ed25519" "-f" "login-key" "-N" ""))) + (unless (zero? (apply system* keygen args)) + (exit 1)))))) + +(define check-ssh-key-auth + `(let ((ssh ,(file-append openssh "/bin/ssh")) + (key "/tmp/login-key")) + (copy-file ,(file-append %sshd-login-keypair "/login-key") key) + (chmod key #o600) + (zero? (system* ssh "-n" "-i" key + ,@(append '("-oStrictHostKeyChecking=no" + "-oUserKnownHostsFile=/dev/null" + "-oBatchMode=yes" "-oConnectTimeout=10" "-p") + (list (number->string %sshd-port) + (string-append %test-user "@localhost") + "true")))))) + +(define (sshd-test-case vm) + #~(begin + (marionette-eval '(start-service 'ssh-daemon) + #$vm) + (wait-for-tcp-port #$%sshd-port + #$vm) + #$(assert-vm-true vm "sshd: shell command via key auth" + check-ssh-key-auth))) + +;; QEMU's e1000 NIC is ens3; static addressing avoids a DHCP hang. +(define %static-networking + (let ((address (network-address (device "ens3") + (value "10.0.2.15/24")))) + (service static-networking-service-type + (list (static-networking (inherit %qemu-static-networking) + (addresses (list address)) + (name-servers '())))))) + +(define fake-tls-cert + (local-file "claude-proxy-test-cert.pem")) + +(define claude-proxy-test-ca-dir + (file-union "claude-proxy-test-ca" + `(("ca.pem" ,fake-tls-cert)))) + +(define fake-upstream-port + 19998) + +(define (fake-upstream-script cert key port) + (with-imported-modules '((tests vps fake-llm)) + (with-extensions (list guile-gnutls guile-json-4) + #~(begin + (use-modules (tests vps fake-llm)) + (run-fake-llm #$cert + #$key + #$port))))) + +(define fake-upstream-program + (program-file "fake-claude-upstream" + (fake-upstream-script fake-tls-cert + (local-file "claude-proxy-test-key.pem") + fake-upstream-port))) + +(define fake-upstream-start + #~(make-forkexec-constructor (list #$fake-upstream-program) + #:log-file "/var/log/fake-upstream.log")) + +(define fake-upstream-service + (shepherd-service (provision '(fake-upstream)) + (start fake-upstream-start) + (stop #~(make-kill-destructor)) + (auto-start? #t))) + +(define (authorize-login config) + (let ((public-key (file-append %sshd-login-keypair "/login-key.pub"))) + (openssh-configuration (inherit config) + (authorized-keys `((,%test-user ,public-key)))))) + +(define %test-services + (cons* %static-networking + (simple-service 'fake-upstream shepherd-root-service-type + (list fake-upstream-service)) + (modify-services (operating-system-user-services vps-operating-system) + (remove-service dhcpcd-service-type) + (openssh-service-type config => + (authorize-login config))))) + +(define %nonguix-signing-key + "C1FD53E5D4CE971933EC50C9F307AE2171A2D3B52C804642A7A35F84F3A4EA98") + +(define %nonguix-acl-test + `(begin + (use-modules (ice-9 string-fun) + (ice-9 textual-ports)) + (call-with-input-file "/etc/guix/acl" + (lambda (port) + (string-contains (get-string-all port) + ,%nonguix-signing-key))))) + +(define (daemons-test-case vm) + #~(begin + #$(assert-vm-true vm "services: resolv.conf is installed" + '(file-exists? "/etc/resolv.conf")) + (test-assert "services: DNS and NTP are up" + (and (wait-for-tcp-port 53 + #$vm) + (marionette-eval '(start-service 'ntpd) + #$vm))) + #$(assert-vm-true vm "services: nonguix substitutes are authorized" + %nonguix-acl-test))) + +(define %vps-test-os + (operating-system + (inherit vps-operating-system) + (services + %test-services)))