diff --git a/.env.example b/.env.example index 9c37255..da3134b 100644 --- a/.env.example +++ b/.env.example @@ -19,3 +19,7 @@ PRINT_AGENT_API_SECRET="your-api-secret" # Optional — health check server (leave empty to disable) # PRINT_AGENT_HEALTH_ADDR=:8080 + +# Optional — only if the GitHub repository becomes private: read-only token used +# by `printer update` (see README, "Dépôt privé"). +# PRINTER_GITHUB_TOKEN= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..39a39e4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - run: go vet ./... + - run: go test ./... + - run: CGO_ENABLED=0 go build -o /dev/null ./cmd/printer + - run: bash -n deploy/install.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2213928 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,68 @@ +name: Release + +# Push a tag vX.Y.Z on main to publish a release: +# git tag -a v1.0.0 -m "v1.0.0" && git push origin v1.0.0 +on: + push: + tags: ["v*"] + +permissions: + contents: write + +# One release at a time; never cancel a release half-published. +concurrency: + group: release + cancel-in-progress: false + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Check the tag is a release version + run: | + if ! [[ "$GITHUB_REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "::error::tag $GITHUB_REF_NAME is not vMAJOR.MINOR.PATCH" + exit 1 + fi + + - name: Check the tagged commit is on main + run: | + git fetch --no-tags origin main + if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then + echo "::error::$GITHUB_REF_NAME ($GITHUB_SHA) is not on main: tag a commit of main" + exit 1 + fi + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + + - name: Vet and test + run: | + go vet ./... + go test ./... + + - name: Build + run: | + mkdir -p dist + for arch in amd64 arm64; do + CGO_ENABLED=0 GOOS=linux GOARCH="$arch" go build -trimpath \ + -ldflags "-s -w -X main.version=${GITHUB_REF_NAME} -X main.commit=${GITHUB_SHA::7} -X main.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + -o "dist/printer_linux_${arch}" ./cmd/printer + done + ./dist/printer_linux_amd64 version + test "$(./dist/printer_linux_amd64 version --short)" = "$GITHUB_REF_NAME" + (cd dist && sha256sum printer_linux_* > checksums.txt && cat checksums.txt) + + - name: Publish the GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: | + prerelease=() + if [[ "$GITHUB_REF_NAME" == *-* ]]; then prerelease=(--prerelease); fi + gh release create "$GITHUB_REF_NAME" dist/* \ + --verify-tag --title "$GITHUB_REF_NAME" --generate-notes "${prerelease[@]}" diff --git a/.gitignore b/.gitignore index 1e248ad..fe26acc 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,7 @@ venv/ .venv/ __pycache__/ *.pyc + +# Local builds +/printer +/dist/ diff --git a/CLAUDE.md b/CLAUDE.md index f382aff..4ef9e90 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,8 +9,11 @@ Go-based print job distribution agent for POS systems. Polls or listens (SSE/Mer ## Commands ```bash -# Build -go build -o print-agent ./cmd/print-agent +# Build (single binary: agent + management CLI) +go build -o printer ./cmd/printer + +# Install the local build on this machine (systemd user service, like a release) +./deploy/install.sh --from-source # Run all tests go test ./... @@ -30,7 +33,9 @@ go test -v ./internal/agent **Dual-mode agent**: SSE via Mercure (primary, real-time) + HTTP polling (fallback). Falls back to polling if Mercure is unavailable; polling interval widens (2s → 30s) when SSE is active. -**Entry point**: `cmd/print-agent/main.go` — CLI with subcommands (`run`, `detect`, `receipt-test`, `open-drawer`, `label`, `sticker-address`, `sticker-image`). +**Entry point**: `cmd/printer/main.go` — CLI with subcommands: the agent (`run`), printing tools (`detect`, `receipt-test`, `open-drawer`, `label`, `sticker-address`, `sticker-image`) and the management commands in `manage.go`/`update.go`/`setup.go` (`status`, `start|stop|restart`, `log`, `update`, `rollback`, `config`, `test`, `autoupdate`, `setup`, `version`). The version is injected with `-ldflags "-X main.version=vX.Y.Z"`. + +**Deployment**: systemd user service `print-agent.service` running `~/.local/bin/printer run`, config `~/.config/print-agent/env`. Units, config template and label scripts are embedded in the binary (`assets.go`, root package `printagent`). Releases: `.github/workflows/release.yml` on tag `v*` publishes `printer_linux_{amd64,arm64}` + `checksums.txt`; `printer update` (`internal/selfupdate`) verifies the sha256, swaps atomically, restarts and rolls back if the service does not stay up (`internal/service`). **Core loop** (`internal/agent/agent.go`): `Start()` runs concurrent goroutines for SSE listening, polling, heartbeat pings (30s), and printer sync (10s). Jobs are fetched via `FetchNextJob()`, dispatched, then acknowledged. @@ -39,7 +44,10 @@ go test -v ./internal/agent - `internal/dispatcher/` — Routes jobs to printer drivers by type. Per-printer mutexes prevent concurrent access. 3-attempt retry with exponential backoff. - `internal/registry/` — Detects printers at `/dev/usb/*`, `/dev/lp*`, `/dev/ttyUSB*`. Tracks availability changes and syncs with server. - `internal/receipt/` — ESC/POS receipt printer driver (native Go) -- `internal/label/` — Wraps Python scripts (`print.py`, `print_sticker.py`) for label/sticker printing via subprocess +- `internal/label/` — Wraps Python scripts (`print.py`, `print_sticker.py`) for label/sticker printing via subprocess (embedded copies extracted to `~/.cache/print-agent/scripts/` when not found next to the binary) +- `internal/envfile/` — Parses, validates and masks the systemd EnvironmentFile config +- `internal/selfupdate/` — GitHub release lookup, version comparison, checksum, atomic swap/rollback +- `internal/service/` — `systemctl --user` wrapper and post-restart health check **Job types**: `receipt`, `put_aside`, `label`, `sticker_image`, `open_drawer` diff --git a/README.md b/README.md index 2279f29..a541ac9 100644 --- a/README.md +++ b/README.md @@ -1,51 +1,234 @@ -# print-agent +# printer — agent d'impression de la caisse -Agent d'impression pour points de vente. Fonctionne en mode autonome (polling API) ou en CLI. +Agent d'impression des points de vente Chapitre Neuf : il récupère les jobs de l'API (Mercure SSE + polling de +secours) et imprime tickets ESC/POS, étiquettes et stickers, ouvre le tiroir-caisse. -## Installation +Tout tient dans **un seul binaire, `printer`** : l'agent lui-même (`printer run`, lancé par systemd) et les commandes +d'exploitation (`printer status`, `printer log`, `printer update`…). Il tourne en arrière-plan comme service systemd +*utilisateur*, démarre au boot sans session ouverte (linger) et se met à jour depuis les GitHub Releases. -### Pré-requis système +| Emplacement | Rôle | +|---|---| +| `~/.local/bin/printer` | le binaire (`printer.prev` : version précédente, pour `printer rollback`) | +| `~/.local/bin/print-agent` | lien vers `printer` (compatibilité avec l'ancienne installation) | +| `~/.config/print-agent/env` | la configuration (identifiants API, imprimantes, adresse du magasin), droits `600` | +| `~/.config/systemd/user/print-agent.service` | le service (réécrit par `printer setup`, ne pas l'éditer) | +| `~/.config/systemd/user/printer-update.{service,timer}` | la mise à jour automatique (désactivée par défaut) | -- Linux avec accès aux devices imprimante (`/dev/usb/*`, `/dev/lp*`) -- Python 3 -- `brother_ql` CLI (pour étiquettes Brother QL) -- Pillow (Python imaging) +## Installation sur un PC neuf -### Dépendances Python +Pré-requis : Ubuntu (ou dérivé) avec systemd, `curl`, l'utilisateur de la caisse. **Pas besoin de Go.** ```sh -python3 -m pip install pillow brother_ql +# en tant qu'utilisateur de la caisse (pas root, pas sudo) +curl -fsSL https://raw.githubusercontent.com/ICTools/printer-agent/main/deploy/install.sh | bash ``` -### Permissions device +Le script télécharge le binaire de la dernière release pour le processeur du PC (`amd64` ou `arm64`), vérifie son +sha256 contre `checksums.txt`, puis lance `printer setup`, qui : + +1. installe `~/.local/bin/printer` ; +2. crée `~/.config/print-agent/env` depuis le modèle **s'il n'existe pas** (une config existante n'est jamais écrasée) ; +3. installe les unités systemd utilisateur et active le service au boot (dès que la config est valide) ; +4. active le *linger* (`loginctl enable-linger`) : le service démarre au boot sans que personne ne se connecte ; +5. vérifie le PATH, l'accès aux imprimantes, `python3` et `brother_ql` ; +6. démarre le service si la config est remplie. + +Ensuite : ```sh -# Vérifier les permissions -ls -l /dev/usb/lp0 +printer config edit # renseigner PRINT_AGENT_API_URL / _KEY / _SECRET ; valide puis redémarre +printer status +printer test # imprime un ticket de test +``` + +Si `printer` n'est pas trouvé, ouvrir un nouveau terminal (Ubuntu ajoute `~/.local/bin` au PATH à la connexion) ou +utiliser `~/.local/bin/printer`. + +Options : une version précise `curl -fsSL …/install.sh | bash -s -- --version v1.2.0`. +Relancer le script (ou `printer setup`) est sans risque : il répare l'installation et garde la config. + +### Dépendances système -# Ajouter l'utilisateur au groupe lp si nécessaire -sudo usermod -aG lp $USER +```sh +sudo usermod -aG lp $USER # accès à /dev/usb/lp* (puis redémarrer la session / le PC) +sudo apt install python3-pil # étiquettes et stickers +python3 -m pip install brother_ql # étiquettes Brother QL (ou pipx install brother_ql) +``` + +Les scripts Python d'étiquettes (`scripts/print.py`, `scripts/print_sticker.py`) et `scripts/sticker.png` sont +**embarqués dans le binaire** et extraits ensemble au besoin dans `~/.cache/print-agent/scripts//`. +`LABEL_SCRIPT_PATH` / `STICKER_SCRIPT_PATH` restent prioritaires **si le fichier existe** ; sinon l'agent journalise un +avertissement et prend la copie embarquée (`printer config check` et `printer setup` signalent un chemin absent). + +### Dépôt privé + +Le dépôt est public aujourd'hui : rien à faire. S'il devient privé, les releases demandent une authentification : + +- installation : `raw.githubusercontent.com` ne sert plus le script ; avec `gh` connecté (`gh auth login`) : + `gh api repos/ICTools/printer-agent/contents/deploy/install.sh -H 'Accept: application/vnd.github.raw' | bash`. + Le script bascule tout seul sur `gh release download` quand le téléchargement public échoue (`gh` utilise + `GH_TOKEN`/`GITHUB_TOKEN` s'ils sont définis) ; +- `printer update` (manuel ou automatique) prend, dans l'ordre : `PRINTER_GITHUB_TOKEN`, `GH_TOKEN`, `GITHUB_TOKEN` + (environnement, ou ligne `PRINTER_GITHUB_TOKEN=…` dans `~/.config/print-agent/env`), puis le token de `gh`. Un + token *fine-grained* en lecture seule sur ce seul dépôt (Contents: read) suffit. + +## Commandes + +| Commande | Effet | +|---|---| +| `printer status` | version, état du service, démarrage au boot, linger, config, imprimantes, derniers logs | +| `printer start` / `stop` / `restart` | pilote le service ; `start`/`restart` refusent une config invalide et vérifient que l'agent reste démarré | +| `printer log` | suit les logs en temps réel (50 dernières lignes puis la suite) | +| `printer log -n 200` | les 200 dernières lignes, sans suivre (`-f` pour suivre aussi) | +| `printer log --since today --errors` | erreurs du jour (`--since "1 hour ago"`, `--since 2026-11-06`…) | +| `printer update --check` | compare la version installée à la dernière release | +| `printer update` | installe la dernière release (voir ci-dessous) | +| `printer update --version v1.2.0` | installe une version précise (aussi pour revenir en arrière) | +| `printer rollback` | revient au binaire remplacé par la dernière mise à jour (et inversement) | +| `printer version` | version, commit, date de build (`--short` : juste la version) | +| `printer config` | affiche la config, secrets masqués (`PRINT_AGENT_API_SECRET=********`, clé API tronquée) | +| `printer config edit` | ouvre `$VISUAL`/`$EDITOR`/nano, valide, propose de corriger, puis active et redémarre le service | +| `printer config check` / `path` | valide la config / affiche son chemin | +| `printer test` | imprime un ticket « TEST IMPRESSION » (version, poste, date, device) sur l'imprimante ticket, sans tiroir | +| `printer autoupdate on` / `off` / `status` | mise à jour automatique quotidienne | +| `printer setup` | installe ou répare tout (idempotent) | +| `printer run` | l'agent au premier plan (ce que lance systemd) — options : `printer run --help` | +| `printer detect`, `receipt-test`, `open-drawer`, `label`, `sticker-address`, `sticker-image` | outils d'impression manuels (voir « Mode CLI ») | + +## Mise à jour + +```sh +printer update --check +printer update ``` -## Build +`printer update` : + +1. interroge l'API GitHub (`releases/latest`) et compare les versions (semver ; un build de dev est toujours remplacé) ; +2. télécharge `printer_linux_` et `checksums.txt`, **vérifie le sha256** (rien n'est installé sinon) ; +3. exécute le nouveau binaire (`version --short`) pour vérifier qu'il tourne et annonce la bonne version ; +4. remplace `~/.local/bin/printer` par un `rename` **atomique**, l'ancien est gardé en `printer.prev` ; +5. si le service tournait, le redémarre et vérifie pendant 20 s (`--wait`) qu'il reste actif sans redémarrage + automatique de systemd ; +6. sinon **rollback** : remet l'ancien binaire et redémarre. Si l'ancien ne tient pas non plus, le problème n'est pas + la mise à jour (réseau, API, config) : voir `printer log -n 100`. + +Un verrou empêche deux mises à jour (ou un `rollback`, un `setup`) simultanés. Une version annulée par le rollback +automatique est mémorisée (`~/.local/bin/.printer-refused-version`) : `printer update` et le timer ne la réinstallent +plus ; une version plus récente est installée normalement, et `printer update --version vX.Y.Z` force celle-là. +`--version` avec une version plus ancienne fait un *downgrade* (annoncé comme tel). + +Les téléchargements passent uniquement en https vers GitHub (`github.com`, `api.github.com`, +`*.githubusercontent.com`, redirections comprises) et sont limités à 100 Mo. `PRINTER_GITHUB_API` (GitHub Enterprise) +doit être en https ; `PRINTER_UPDATE_INSECURE=1` lève ces contrôles pour un serveur de test local, jamais en production. + +Si les unités systemd changent entre deux versions, les notes de release le disent : lancer alors `printer setup`. + +### Mise à jour automatique (désactivée par défaut) ```sh -go build -o print-agent ./cmd/print-agent +printer autoupdate on # tous les jours vers 05:00 (+ jusqu'à 30 min aléatoires) +printer autoupdate off +journalctl --user -u printer-update.service # historique ``` ---- +Désactivée par défaut : une mise à jour redémarre l'agent, et une caisse doit changer de version quand on l'a décidé +(après une release testée). Le timer n'est pas *persistent* : un PC éteint à 05:00 n'est pas mis à jour au démarrage, +en pleine ouverture. Le rollback automatique s'applique aussi. -## Mode Agent (recommandé) +## Logs -L'agent se connecte à une API distante, récupère les jobs d'impression et les exécute automatiquement. +Les logs vont dans journald (rotation gérée par journald) : -### Démarrage +```sh +printer log # suivi temps réel +printer log -n 100 # 100 dernières lignes +printer log --since today --errors # erreurs du jour +journalctl --user -u print-agent --since "2026-11-06 09:00" --until "2026-11-06 10:00" +``` + +## Dépannage + +| Symptôme | Piste | +|---|---| +| `printer: command not found` | nouveau terminal, ou `~/.local/bin/printer` | +| `status` : `activating (auto-restart)`, restarts qui montent | l'agent quitte au démarrage : `printer log -n 50` ; souvent identifiants refusés ou API injoignable (`printer config check`) | +| `Failed to connect to bus` / `systemctl --user` échoue | lancer les commandes en session normale de l'utilisateur de la caisse, pas via `sudo` | +| le service ne démarre qu'après connexion | linger off : `printer setup` (ou `sudo loginctl enable-linger $USER`) | +| `Permission denied` sur `/dev/usb/lp0` | `sudo usermod -aG lp $USER` puis redémarrer ; `printer status` liste les devices et leur accès | +| aucune imprimante détectée | câble / alimentation ; `printer detect` | +| `brother_ql not found` | installer `brother_ql` (voir Dépendances) ; vérifier `PATH`/`PYTHON_PATH` | +| `update` : `checksum mismatch` | téléchargement corrompu ou release modifiée : rien n'a été installé, relancer ; sinon vérifier la release | +| `update` : `no matching release` | aucune release publiée, ou dépôt privé sans token (voir « Dépôt privé ») | +| une mise à jour pose problème | `printer rollback`, ou `printer update --version vX.Y.Z` | +| texte illisible sur le ticket | les accents sont convertis en ASCII (normal) | +| TLS en local | `printer run -insecure` | + +## Migration depuis l'ancienne installation + +Ancienne installation (`deploy/install.sh` d'avant, build Go local) : binaire `~/.local/bin/print-agent`, service +`print-agent`, config `~/.config/print-agent/env`. Le nouveau binaire garde **le même nom de service et la même +config**, la migration est donc : ```sh -./print-agent run \ - -api-url https://api.monsite.com \ - -api-key $API_KEY \ - -api-secret $API_SECRET +cp ~/.config/print-agent/env ~/print-agent-env.backup # sécurité +grep -E '^(LABEL|STICKER)_SCRIPT_PATH' ~/.config/print-agent/env # chemins vers l'ancien clone ? +curl -fsSL https://raw.githubusercontent.com/ICTools/printer-agent/main/deploy/install.sh | bash +printer status # active (running), config OK +printer test # ticket de test +``` + +`printer setup` (lancé par le script) : garde `~/.config/print-agent/env` tel quel (droits passés à `600`), réécrit +`print-agent.service` avec `ExecStart=%h/.local/bin/printer run`, déplace l'ancien binaire en +`~/.local/bin/print-agent.legacy` et le remplace par un lien vers `printer`, puis redémarre le service. + +**Avant de supprimer l'ancien clone Go** : si la config contient `LABEL_SCRIPT_PATH` ou `STICKER_SCRIPT_PATH` pointant +dans ce clone, retirer ces lignes (`printer config edit`) pour utiliser les scripts embarqués. `printer config check` +avertit si un de ces chemins n'existe pas. Le clone n'est ensuite plus nécessaire. + +Retour arrière (si besoin) : `mv ~/.local/bin/print-agent.legacy ~/.local/bin/print-agent` (remplace le lien), remettre +`ExecStart=%h/.local/bin/print-agent run` dans `~/.config/systemd/user/print-agent.service`, puis +`systemctl --user daemon-reload && systemctl --user restart print-agent`. + +## Désinstallation + +```sh +systemctl --user disable --now print-agent printer-update.timer +rm ~/.config/systemd/user/print-agent.service ~/.config/systemd/user/printer-update.* +systemctl --user daemon-reload +rm ~/.local/bin/printer ~/.local/bin/printer.prev ~/.local/bin/print-agent +# la config ~/.config/print-agent/env contient les identifiants : la supprimer si le poste est retiré +``` + +## Développement + +```sh +go vet ./... && go test ./... +go build -o printer ./cmd/printer +./deploy/install.sh --from-source # installe le build local (version = git describe) +``` + +### Publier une release + +Les releases sont produites par `.github/workflows/release.yml` sur un tag `v*` : tests, build `linux/amd64` et +`linux/arm64` (statiques, `CGO_ENABLED=0`, version injectée par `-ldflags -X main.version`), `checksums.txt`, puis +GitHub Release avec notes générées. Un tag `vX.Y.Z-rc.1` crée une pré-release (ignorée par `printer update`). + +```sh +git checkout main && git pull +git tag -a v1.0.0 -m "v1.0.0" +git push origin v1.0.0 +``` + +--- + +## Mode Agent (`printer run`) + +Ce que lance le service. À la main (tests) : + +```sh +printer run -api-url https://api.monsite.com -api-key $API_KEY -api-secret $API_SECRET ``` ### Options @@ -68,7 +251,7 @@ L'agent se connecte à une API distante, récupère les jobs d'impression et les ### Test local (sans imprimante) ```sh -./print-agent run \ +printer run \ -api-url https://localhost \ -api-key $API_KEY \ -api-secret $API_SECRET \ @@ -404,37 +587,37 @@ Commandes pour tests manuels ou intégration scripts. ### Détecter les imprimantes ```sh -./print-agent detect +printer detect ``` ### Imprimer un ticket test ```sh -./print-agent receipt-test --device /dev/usb/epson_tmt20iii --logo /path/logo.png +printer receipt-test --device /dev/usb/epson_tmt20iii --logo /path/logo.png ``` ### Ouvrir le tiroir-caisse ```sh -./print-agent open-drawer --device /dev/usb/epson_tmt20iii +printer open-drawer --device /dev/usb/epson_tmt20iii ``` ### Imprimer une étiquette prix ```sh -./print-agent label "Livre" "12.90 €" 9781234567890 --footer "Chapitre Neuf" +printer label "Livre" "12.90 €" 9781234567890 --footer "Chapitre Neuf" ``` ### Imprimer un sticker adresse ```sh -./print-agent sticker-address "Chapitre Neuf" "21 Avenue des Combattants" "1370 Jodoigne" +printer sticker-address "Chapitre Neuf" "21 Avenue des Combattants" "1370 Jodoigne" ``` ### Imprimer une image ```sh -./print-agent sticker-image ./path/to/image.png +printer sticker-image ./path/to/image.png ``` --- @@ -476,8 +659,8 @@ Commandes pour tests manuels ou intégration scripts. ### Tickets et tiroir (ESC/POS vers fichier) ```sh -RECEIPT_PRINTER_DEVICE=/tmp/receipt.bin ./print-agent receipt-test -./print-agent open-drawer --device /tmp/drawer.bin +RECEIPT_PRINTER_DEVICE=/tmp/receipt.bin printer receipt-test +printer open-drawer --device /tmp/drawer.bin ``` ### Étiquettes (mock brother_ql) @@ -486,7 +669,7 @@ RECEIPT_PRINTER_DEVICE=/tmp/receipt.bin ./print-agent receipt-test export PATH="$(pwd)/scripts:$PATH" chmod +x scripts/mock_brother_ql.sh ln -sf mock_brother_ql.sh scripts/brother_ql -./print-agent label "Test" "9.99 €" 1234567890123 +printer label "Test" "9.99 €" 1234567890123 ``` --- @@ -500,10 +683,3 @@ Si `-health-addr` est configuré, l'agent expose : - `GET /status` - Statut combiné local + serveur --- - -## Troubleshooting - -- **brother_ql not found** : vérifier installation et PATH -- **Permission denied** : vérifier groupe `lp` et règles udev -- **Texte illisible** : les accents sont convertis en ASCII -- **TLS error en local** : utiliser `-insecure` diff --git a/assets.go b/assets.go new file mode 100644 index 0000000..fabd346 --- /dev/null +++ b/assets.go @@ -0,0 +1,41 @@ +// Package printagent embeds the files the single release binary needs at +// install time and at run time: the systemd units, the config template and +// the Python label scripts. +package printagent + +import _ "embed" + +// EnvTemplate is the config file written by `printer setup` when none exists. +// +//go:embed .env.example +var EnvTemplate []byte + +// ServiceUnit is the systemd user unit of the agent (print-agent.service). +// +//go:embed deploy/print-agent.service +var ServiceUnit []byte + +// UpdateServiceUnit runs `printer update` once (printer-update.service). +// +//go:embed deploy/printer-update.service +var UpdateServiceUnit []byte + +// UpdateTimerUnit schedules UpdateServiceUnit daily (printer-update.timer). +// +//go:embed deploy/printer-update.timer +var UpdateTimerUnit []byte + +// LabelScript is scripts/print.py (price labels and address stickers). +// +//go:embed scripts/print.py +var LabelScript []byte + +// StickerScript is scripts/print_sticker.py (image stickers). +// +//go:embed scripts/print_sticker.py +var StickerScript []byte + +// StickerImage is scripts/sticker.png, used by print.py for address stickers. +// +//go:embed scripts/sticker.png +var StickerImage []byte diff --git a/cmd/print-agent/main.go b/cmd/printer/main.go similarity index 85% rename from cmd/print-agent/main.go rename to cmd/printer/main.go index e3fd6b0..4ff5bad 100644 --- a/cmd/print-agent/main.go +++ b/cmd/printer/main.go @@ -21,6 +21,14 @@ func main() { os.Exit(1) } + if manage, ok := managementCommands[os.Args[1]]; ok { + if err := manage(os.Args[2:]); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } + return + } + switch os.Args[1] { case "run": cmdRun(os.Args[2:]) @@ -36,6 +44,8 @@ func main() { cmdStickerAddress(os.Args[2:]) case "sticker-image": cmdStickerImage(os.Args[2:]) + case "--version", "-v": + fmt.Println(version) case "help", "-h", "--help": printUsage() default: @@ -46,10 +56,26 @@ func main() { } func printUsage() { - fmt.Println("Usage: print-agent [options]") + fmt.Println("Usage: printer [options]") + fmt.Println() + fmt.Println("Manage the background service:") + fmt.Println(" status Service, boot start, config, printers and recent logs") + fmt.Println(" start | stop | restart") + fmt.Println(" Control the print-agent systemd user service") + fmt.Println(" log [-n N] [-f] Follow the logs (default), or print the last N lines") + fmt.Println(" update [--check] Install the latest GitHub release (sha256 verified, rollback on failure)") + fmt.Println(" rollback Go back to the binary replaced by the last update") + fmt.Println(" version [--short] Print the version") + fmt.Println(" config [show|edit|check|path]") + fmt.Println(" Show the config (secrets masked), edit it then restart, or check it") + fmt.Println(" test [--device D] Print a test ticket on the receipt printer") + fmt.Println(" autoupdate [on|off|status]") + fmt.Println(" Daily automatic update at 05:00 (off by default)") + fmt.Println(" setup [--no-start]") + fmt.Println(" Install or repair: binary, service, config, boot start") fmt.Println() - fmt.Println("Commands:") - fmt.Println(" run Start the agent (poll API for print jobs)") + fmt.Println("Agent and printing tools:") + fmt.Println(" run Start the agent in the foreground (what the service runs)") fmt.Println(" detect List detected printer devices") fmt.Println(" receipt-test Print a sample receipt") fmt.Println(" open-drawer Open cash drawer") @@ -57,7 +83,7 @@ func printUsage() { fmt.Println(" sticker-address Print an address sticker") fmt.Println(" sticker-image Print a sticker image") fmt.Println() - fmt.Println("Run 'print-agent run --help' for agent options.") + fmt.Println("Run 'printer run --help' for agent options.") } func cmdDetect() { @@ -136,7 +162,7 @@ func cmdLabel(args []string) { posArgs := fs.Args() if len(posArgs) < 3 { - fmt.Fprintln(os.Stderr, "Usage: print-agent label [options] ") + fmt.Fprintln(os.Stderr, "Usage: printer label [options] ") os.Exit(1) } @@ -163,7 +189,7 @@ func cmdStickerAddress(args []string) { posArgs := fs.Args() if len(posArgs) < 2 { - fmt.Fprintln(os.Stderr, "Usage: print-agent sticker-address [options] [line3]") + fmt.Fprintln(os.Stderr, "Usage: printer sticker-address [options] [line3]") os.Exit(1) } @@ -198,7 +224,7 @@ func cmdStickerImage(args []string) { posArgs := fs.Args() if len(posArgs) < 1 { - fmt.Fprintln(os.Stderr, "Usage: print-agent sticker-image [options] ") + fmt.Fprintln(os.Stderr, "Usage: printer sticker-image [options] ") os.Exit(1) } @@ -218,7 +244,7 @@ func cmdStickerImage(args []string) { func cmdRun(args []string) { fs := flag.NewFlagSet("run", flag.ExitOnError) fs.Usage = func() { - fmt.Println("Usage: print-agent run [options]") + fmt.Println("Usage: printer run [options]") fmt.Println() fmt.Println("Start the print agent to poll for jobs from a remote API.") fmt.Println() @@ -322,7 +348,7 @@ func cmdRun(args []string) { // Create and start agent with auth a := agent.NewWithAuth(client, auth, reg, config) - fmt.Println("Starting print-agent...") + fmt.Printf("Starting print-agent %s...\n", version) fmt.Printf(" API URL: %s\n", *apiURL) fmt.Printf(" Poll interval: %s\n", *pollInterval) fmt.Printf(" Ping interval: %s\n", *pingInterval) diff --git a/cmd/printer/manage.go b/cmd/printer/manage.go new file mode 100644 index 0000000..8224ad9 --- /dev/null +++ b/cmd/printer/manage.go @@ -0,0 +1,465 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "flag" + "fmt" + "net/url" + "os" + "os/exec" + "os/user" + "path/filepath" + "runtime" + "strings" + "syscall" + "time" + + "print-agent/internal/envfile" + "print-agent/internal/receipt" + "print-agent/internal/service" +) + +// Set at build time: go build -ldflags "-X main.version=v1.2.3 -X main.commit=abc1234 -X main.date=..." +var ( + version = "dev" + commit = "" + date = "" +) + +// Replaced in tests. +var ( + newSystemd = service.New + healthPollStep = 500 * time.Millisecond +) + +var managementCommands = map[string]func([]string) error{ + "version": cmdVersion, + "status": cmdStatus, + "start": func(args []string) error { return cmdStartRestart("start", args) }, + "restart": func(args []string) error { return cmdStartRestart("restart", args) }, + "stop": cmdStop, + "log": cmdLog, + "logs": cmdLog, + "update": cmdUpdate, + "rollback": cmdRollback, + "config": cmdConfig, + "test": cmdTest, + "autoupdate": cmdAutoUpdate, + "setup": cmdSetup, +} + +// layout is where everything lives on the till PC. The systemd unit uses the +// same fixed paths (%h/.local/bin/printer, %h/.config/print-agent/env). +type layout struct { + Bin string // ~/.local/bin/printer + LegacyBin string // ~/.local/bin/print-agent (old installer, now a symlink) + ConfigDir string // ~/.config/print-agent + ConfigFile string // ~/.config/print-agent/env + UnitDir string // ~/.config/systemd/user +} + +func paths() layout { + home, err := os.UserHomeDir() + if err != nil || home == "" { + home = "." + } + return layout{ + Bin: filepath.Join(home, ".local", "bin", "printer"), + LegacyBin: filepath.Join(home, ".local", "bin", "print-agent"), + ConfigDir: filepath.Join(home, ".config", "print-agent"), + ConfigFile: filepath.Join(home, ".config", "print-agent", "env"), + UnitDir: filepath.Join(home, ".config", "systemd", "user"), + } +} + +// tildePath shortens a path under $HOME for display. +func tildePath(p string) string { + if home, err := os.UserHomeDir(); err == nil && home != "" && strings.HasPrefix(p, home+"/") { + return "~" + strings.TrimPrefix(p, home) + } + return p +} + +func cmdVersion(args []string) error { + fs := flag.NewFlagSet("version", flag.ExitOnError) + short := fs.Bool("short", false, "Print only the version") + _ = fs.Parse(args) + if *short { + fmt.Println(version) + return nil + } + fmt.Printf("printer %s", version) + if commit != "" { + fmt.Printf(" (commit %s", commit) + if date != "" { + fmt.Printf(", built %s", date) + } + fmt.Print(")") + } + fmt.Printf(" %s/%s %s\n", runtime.GOOS, runtime.GOARCH, runtime.Version()) + return nil +} + +func cmdStatus(args []string) error { + ctx := context.Background() + p := paths() + sd := newSystemd() + + fmt.Printf("printer %s (%s/%s)\n\n", version, runtime.GOOS, runtime.GOARCH) + + props, err := sd.Show(ctx, service.Agent) + switch { + case err != nil: + fmt.Printf("Service cannot query systemd: %v\n", err) + case props["LoadState"] == "not-found": + fmt.Println("Service not installed — run `printer setup`") + default: + line := fmt.Sprintf("%s (%s)", props["ActiveState"], props["SubState"]) + if props.Active() && props["ActiveEnterTimestamp"] != "" { + line += " since " + props["ActiveEnterTimestamp"] + } + fmt.Printf("Service %s: %s\n", service.Agent, line) + boot := "enabled at boot" + if props["UnitFileState"] != "enabled" { + boot = "NOT enabled at boot (" + props["UnitFileState"] + ") — run `printer setup`" + } + fmt.Printf(" %s, %d automatic restart(s)\n", boot, props.Restarts()) + } + + if linger, err := lingerEnabled(ctx); err != nil { + fmt.Printf("Boot linger unknown: %v\n", err) + } else { + if linger { + fmt.Println("Boot linger on: starts at boot without anyone logging in") + } else { + fmt.Println("Boot linger OFF: starts only once the user logs in — run `printer setup`") + } + } + + if data, err := os.ReadFile(p.ConfigFile); err != nil { + fmt.Printf("Config %s missing — run `printer setup`\n", tildePath(p.ConfigFile)) + } else { + entries, problems := envfile.Validate(data) + state := "OK" + if envfile.HasFatal(problems) { + state = "INVALID — run `printer config check`" + } + api := envfile.MaskURL(envfile.Map(entries)["PRINT_AGENT_API_URL"]) + fmt.Printf("Config %s: %s (API %s)\n", tildePath(p.ConfigFile), state, api) + } + + devices, _ := receipt.DetectPrinters() + if len(devices) == 0 { + fmt.Println("Printers none detected") + } + for i, d := range devices { + label := "Printers " + if i > 0 { + label = " " + } + state := "writable" + if !d.IsAvailable { + state = "NOT writable — check the lp group (see README)" + } + fmt.Printf("%s %s (%s)\n", label, d.Path, state) + } + + if timer, err := sd.Show(ctx, service.UpdateTimer); err == nil && timer["LoadState"] == "loaded" { + if timer["UnitFileState"] == "enabled" { + fmt.Println("Updates automatic daily update ON (`printer autoupdate off` to disable)") + } else { + fmt.Println("Updates automatic update off — `printer update --check` to compare") + } + } + + if out, err := exec.Command("journalctl", "--user", "-u", service.Agent, "-n", "8", + "--no-pager", "-o", "short-iso").Output(); err == nil && len(bytes.TrimSpace(out)) > 0 { + fmt.Println("\nRecent logs (`printer log` to follow):") + for _, l := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { + fmt.Println(" " + l) + } + } + return nil +} + +// currentUsername falls back to $USER and `id -un` when user.Current fails +// (no /etc/passwd entry, e.g. LDAP users with a static binary). +func currentUsername() (string, error) { + if u, err := user.Current(); err == nil && u.Username != "" { + return u.Username, nil + } + if name := strings.TrimSpace(os.Getenv("USER")); name != "" { + return name, nil + } + if out, err := exec.Command("id", "-un").Output(); err == nil && len(bytes.TrimSpace(out)) > 0 { + return string(bytes.TrimSpace(out)), nil + } + return "", errors.New("cannot determine the current user name") +} + +func lingerEnabled(ctx context.Context) (bool, error) { + name, err := currentUsername() + if err != nil { + return false, err + } + out, err := exec.CommandContext(ctx, "loginctl", "show-user", name, "-p", "Linger", "--value").Output() + if err != nil { + return false, err + } + return strings.TrimSpace(string(out)) == "yes", nil +} + +// checkConfig refuses to (re)start the service with a config that cannot work. +func checkConfig(path string) error { + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("config %s: %w (run `printer setup`)", tildePath(path), err) + } + _, problems := envfile.Validate(data) + if envfile.HasFatal(problems) { + printProblems(problems) + return fmt.Errorf("config %s is invalid: fix it with `printer config edit`", tildePath(path)) + } + return nil +} + +func printProblems(problems []envfile.Problem) { + for _, pr := range problems { + fmt.Fprintln(os.Stderr, " "+pr.String()) + } +} + +func cmdStartRestart(action string, args []string) error { + fs := flag.NewFlagSet(action, flag.ExitOnError) + wait := fs.Duration("wait", 10*time.Second, "How long the service must stay up to be reported healthy") + _ = fs.Parse(args) + if err := checkConfig(paths().ConfigFile); err != nil { + return err + } + return restartAndWatch(action, *wait) +} + +func restartAndWatch(action string, wait time.Duration) error { + ctx := context.Background() + sd := newSystemd() + if err := sd.Ctl(ctx, action, service.Agent); err != nil { + return err + } + fmt.Printf("%s: %s, checking it stays up for %s...\n", service.Agent, action, wait) + if err := sd.WaitHealthy(ctx, service.Agent, wait, healthPollStep); err != nil { + return fmt.Errorf("%w — see `printer log -n 50`", err) + } + fmt.Println("OK: the agent is running.") + return nil +} + +func cmdStop(args []string) error { + if err := newSystemd().Ctl(context.Background(), "stop", service.Agent); err != nil { + return err + } + fmt.Println("Stopped. It will start again at the next boot (or `printer start`).") + return nil +} + +func cmdLog(args []string) error { + fs := flag.NewFlagSet("log", flag.ExitOnError) + lines := fs.Int("n", 0, "Print the last N lines (without -f: do not follow)") + follow := fs.Bool("f", false, "Follow new lines (default when -n is not given)") + since := fs.String("since", "", "Only lines since, e.g. today, \"1 hour ago\", 2026-11-06") + errorsOnly := fs.Bool("errors", false, "Only errors") + _ = fs.Parse(args) + + jargs := []string{"journalctl", "--user", "-u", service.Agent, "--no-pager", "-o", "short-iso"} + switch { + case *lines > 0: + jargs = append(jargs, "-n", fmt.Sprint(*lines)) + if *follow { + jargs = append(jargs, "-f") + } + case *since != "": + if *follow { + jargs = append(jargs, "-f") + } + default: + jargs = append(jargs, "-n", "50", "-f") + } + if *since != "" { + jargs = append(jargs, "--since", *since) + } + if *errorsOnly { + jargs = append(jargs, "-p", "err") + } + bin, err := exec.LookPath("journalctl") + if err != nil { + return err + } + return syscall.Exec(bin, jargs, os.Environ()) +} + +func cmdConfig(args []string) error { + sub := "show" + if len(args) > 0 { + sub = args[0] + } + p := paths() + switch sub { + case "show": + return configShow(p.ConfigFile) + case "path": + fmt.Println(p.ConfigFile) + return nil + case "check": + data, err := os.ReadFile(p.ConfigFile) + if err != nil { + return err + } + _, problems := envfile.Validate(data) + printProblems(problems) + if envfile.HasFatal(problems) { + return errors.New("config is invalid") + } + fmt.Printf("%s: OK\n", tildePath(p.ConfigFile)) + return nil + case "edit": + return configEdit(p.ConfigFile) + default: + return fmt.Errorf("unknown config command %q (show, edit, check, path)", sub) + } +} + +func configShow(path string) error { + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("%w (run `printer setup`)", err) + } + entries, problems := envfile.Validate(data) + fmt.Printf("# %s (secrets masked)\n", tildePath(path)) + for _, e := range entries { + fmt.Printf("%s=%s\n", e.Key, envfile.Mask(e.Key, e.Value)) + } + if len(problems) > 0 { + fmt.Println() + printProblems(problems) + } + return nil +} + +func editorCommand() []string { + for _, k := range []string{"VISUAL", "EDITOR"} { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return strings.Fields(v) + } + } + for _, e := range []string{"nano", "vi"} { + if _, err := exec.LookPath(e); err == nil { + return []string{e} + } + } + return []string{"vi"} +} + +func configEdit(path string) error { + before, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("%w (run `printer setup`)", err) + } + in := bufio.NewReader(os.Stdin) + for { + ed := editorCommand() + cmd := exec.Command(ed[0], append(ed[1:], path)...) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("editor %s: %w", ed[0], err) + } + after, err := os.ReadFile(path) + if err != nil { + return err + } + _, problems := envfile.Validate(after) + printProblems(problems) + if !envfile.HasFatal(problems) { + if bytes.Equal(before, after) { + fmt.Println("No change.") + return nil + } + break + } + fmt.Print("The config is invalid. Edit it again? [Y/n] ") + answer, _ := in.ReadString('\n') + if a := strings.ToLower(strings.TrimSpace(answer)); a == "n" || a == "no" || a == "non" { + return errors.New("config left invalid: the service was not restarted") + } + } + fmt.Println("Config saved, restarting the service...") + if err := newSystemd().Ctl(context.Background(), "enable", service.Agent); err != nil { + return err + } + return restartAndWatch("restart", 10*time.Second) +} + +func cmdTest(args []string) error { + fs := flag.NewFlagSet("test", flag.ExitOnError) + device := fs.String("device", "", "Receipt printer device (default: RECEIPT_PRINTER_DEVICE or auto-detect)") + _ = fs.Parse(args) + // Read the same settings as the service (RECEIPT_PRINTER_DEVICE...). + _ = envfile.Load(paths().ConfigFile) + + pr := receipt.NewPrinter(*device) + host, _ := os.Hostname() + lines := []string{ + "Version : " + version, + "Poste : " + host, + "Date : " + time.Now().Format("02/01/2006 15:04:05"), + "Device : " + pr.Device, + } + if u, err := url.Parse(os.Getenv("PRINT_AGENT_API_URL")); err == nil && u.Host != "" { + lines = append(lines, "API : "+u.Host) + } + if err := pr.PrintTestPage(lines); err != nil { + return fmt.Errorf("print on %s: %w (see `printer status`, lp group)", pr.Device, err) + } + fmt.Printf("Test ticket sent to %s.\n", pr.Device) + return nil +} + +func cmdAutoUpdate(args []string) error { + ctx := context.Background() + sd := newSystemd() + sub := "status" + if len(args) > 0 { + sub = args[0] + } + switch sub { + case "on": + if err := sd.Ctl(ctx, "enable", "--now", service.UpdateTimer); err != nil { + return fmt.Errorf("%w (run `printer setup` first)", err) + } + fmt.Println("Automatic update ON: every day around 05:00 when the PC is on.") + case "off": + if err := sd.Ctl(ctx, "disable", "--now", service.UpdateTimer); err != nil { + return err + } + fmt.Println("Automatic update OFF. Update by hand with `printer update`.") + case "status": + props, err := sd.Show(ctx, service.UpdateTimer) + if err != nil { + return err + } + if props["LoadState"] != "loaded" { + fmt.Println("Update timer not installed: run `printer setup`.") + return nil + } + if props["UnitFileState"] == "enabled" { + fmt.Println("Automatic update ON (daily around 05:00).") + } else { + fmt.Println("Automatic update OFF (`printer autoupdate on` to enable).") + } + fmt.Println("Last runs: `journalctl --user -u " + service.UpdateService + "`") + default: + return fmt.Errorf("unknown autoupdate command %q (on, off, status)", sub) + } + return nil +} diff --git a/cmd/printer/setup.go b/cmd/printer/setup.go new file mode 100644 index 0000000..268ead2 --- /dev/null +++ b/cmd/printer/setup.go @@ -0,0 +1,254 @@ +package main + +import ( + "bytes" + "context" + "errors" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + printagent "print-agent" + "print-agent/internal/envfile" + "print-agent/internal/receipt" + "print-agent/internal/selfupdate" + "print-agent/internal/service" +) + +// cmdSetup installs or repairs everything; it is idempotent and never +// overwrites an existing config. install.sh downloads the binary and runs it. +func cmdSetup(args []string) error { + fs := flag.NewFlagSet("setup", flag.ExitOnError) + noStart := fs.Bool("no-start", false, "Do not (re)start the service") + _ = fs.Parse(args) + + ctx := context.Background() + p := paths() + sd := newSystemd() + + fmt.Println("[1/6] Binary") + if err := os.MkdirAll(filepath.Dir(p.Bin), 0o755); err != nil { + return err + } + unlock, err := selfupdate.Lock(filepath.Dir(p.Bin)) + if err != nil { + return err + } + defer unlock() + if err := installSelf(p.Bin); err != nil { + return err + } + if err := migrateLegacyBinary(p); err != nil { + return err + } + + fmt.Println("[2/6] Config") + if err := ensureConfig(p); err != nil { + return err + } + + fmt.Println("[3/6] systemd user units") + for name, content := range map[string][]byte{ + service.Agent: printagent.ServiceUnit, + service.UpdateService: printagent.UpdateServiceUnit, + service.UpdateTimer: printagent.UpdateTimerUnit, + } { + changed, err := writeIfChanged(filepath.Join(p.UnitDir, name), content, 0o644) + if err != nil { + return err + } + if changed { + fmt.Printf(" wrote %s\n", tildePath(filepath.Join(p.UnitDir, name))) + } + } + if err := sd.Ctl(ctx, "daemon-reload"); err != nil { + return fmt.Errorf("%w\n (run setup from a normal login session of the till user, not via sudo)", err) + } + data, _ := os.ReadFile(p.ConfigFile) + _, problems := envfile.Validate(data) + configOK := !envfile.HasFatal(problems) + if configOK { + if err := sd.Ctl(ctx, "enable", service.Agent); err != nil { + return err + } + fmt.Printf(" %s enabled at boot\n", service.Agent) + } else { + // Enabling it now would crash-loop at every boot until the config is filled in. + fmt.Printf(" %s will be enabled at boot once the config is valid\n", service.Agent) + } + + fmt.Println("[4/6] Start at boot without login (linger)") + if on, err := lingerEnabled(ctx); err == nil && on { + fmt.Println(" already on") + } else if name, err := currentUsername(); err != nil { + fmt.Printf(" could not determine the user (%v): run `sudo loginctl enable-linger `\n", err) + } else if out, err := exec.CommandContext(ctx, "loginctl", "enable-linger", name).CombinedOutput(); err != nil { + fmt.Printf(" could not enable it (%s): run `sudo loginctl enable-linger %s`\n", + strings.TrimSpace(string(out)), name) + } else { + fmt.Println(" enabled") + } + + fmt.Println("[5/6] Checks") + runChecks(p) + + fmt.Println("[6/6] Service") + if *noStart { + fmt.Println(" not started (--no-start)") + return nil + } + if !configOK { + printProblems(problems) + fmt.Println("\n Fill in the config, the service starts when you save it:") + fmt.Println(" printer config edit") + return nil + } + return restartAndWatch("restart", 15*time.Second) +} + +// installSelf copies the running binary to bin unless it already is bin. +func installSelf(bin string) error { + exe, err := os.Executable() + if err != nil { + return err + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + if target, err := filepath.EvalSymlinks(bin); err == nil && target == exe { + fmt.Printf(" %s %s already in place\n", tildePath(bin), version) + return nil + } + dir := filepath.Dir(bin) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + in, err := os.ReadFile(exe) + if err != nil { + return err + } + if current, err := os.ReadFile(bin); err == nil && bytes.Equal(current, in) { + // Same build already installed: keep printer.prev as it is. + fmt.Printf(" %s %s already in place\n", tildePath(bin), version) + return nil + } + tmp, err := os.CreateTemp(dir, ".printer-setup-*") + if err != nil { + return err + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(in); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Chmod(tmp.Name(), 0o755); err != nil { + return err + } + if err := selfupdate.Swap(tmp.Name(), bin); err != nil { + return err + } + fmt.Printf(" installed %s %s\n", tildePath(bin), version) + return nil +} + +// migrateLegacyBinary handles a PC installed by the old install.sh: the +// binary ~/.local/bin/print-agent is kept as print-agent.legacy and replaced +// by a symlink to printer, so anything still calling print-agent keeps working. +func migrateLegacyBinary(p layout) error { + info, err := os.Lstat(p.LegacyBin) + if errors.Is(err, os.ErrNotExist) { + return os.Symlink("printer", p.LegacyBin) + } + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + backup := p.LegacyBin + ".legacy" + if err := os.Rename(p.LegacyBin, backup); err != nil { + return err + } + if err := os.Symlink("printer", p.LegacyBin); err != nil { + return err + } + fmt.Printf(" old binary moved to %s, %s now points to printer\n", tildePath(backup), tildePath(p.LegacyBin)) + return nil +} + +func ensureConfig(p layout) error { + if err := os.MkdirAll(p.ConfigDir, 0o700); err != nil { + return err + } + if _, err := os.Stat(p.ConfigFile); err == nil { + // It holds the API secret: readable by the till user only. + _ = os.Chmod(p.ConfigFile, 0o600) + fmt.Printf(" kept existing %s\n", tildePath(p.ConfigFile)) + return nil + } + if err := os.WriteFile(p.ConfigFile, printagent.EnvTemplate, 0o600); err != nil { + return err + } + fmt.Printf(" created %s from the template\n", tildePath(p.ConfigFile)) + return nil +} + +func writeIfChanged(path string, content []byte, mode os.FileMode) (bool, error) { + if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, content) { + return false, nil + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return false, err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, content, mode); err != nil { + return false, err + } + return true, os.Rename(tmp, path) +} + +func runChecks(p layout) { + ok := true + binDir := filepath.Dir(p.Bin) + if !pathContains(os.Getenv("PATH"), binDir) { + ok = false + fmt.Printf(" %s is not in PATH yet: open a new terminal (Ubuntu adds it at login), or use %s\n", + tildePath(binDir), tildePath(p.Bin)) + } + if devices, _ := receipt.DetectPrinters(); len(devices) > 0 { + for _, d := range devices { + if !d.IsAvailable { + ok = false + fmt.Printf(" %s is not writable: `sudo usermod -aG lp $USER` then reboot\n", d.Path) + } + } + } else { + fmt.Println(" no printer detected right now (plugged in and powered?)") + } + if _, err := exec.LookPath("python3"); err != nil { + ok = false + fmt.Println(" python3 not found: needed for labels and stickers (`sudo apt install python3-pil`)") + } + if _, err := exec.LookPath("brother_ql"); err != nil { + fmt.Println(" brother_ql not found: needed only for Brother QL labels (see README)") + } + if ok { + fmt.Println(" OK") + } +} + +func pathContains(pathEnv, dir string) bool { + for _, d := range filepath.SplitList(pathEnv) { + if filepath.Clean(d) == filepath.Clean(dir) { + return true + } + } + return false +} diff --git a/cmd/printer/setup_test.go b/cmd/printer/setup_test.go new file mode 100644 index 0000000..30c9455 --- /dev/null +++ b/cmd/printer/setup_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + printagent "print-agent" +) + +func testLayout(t *testing.T) layout { + t.Helper() + home := t.TempDir() + l := layout{ + Bin: filepath.Join(home, ".local", "bin", "printer"), + LegacyBin: filepath.Join(home, ".local", "bin", "print-agent"), + ConfigDir: filepath.Join(home, ".config", "print-agent"), + ConfigFile: filepath.Join(home, ".config", "print-agent", "env"), + UnitDir: filepath.Join(home, ".config", "systemd", "user"), + } + if err := os.MkdirAll(filepath.Dir(l.Bin), 0o755); err != nil { + t.Fatal(err) + } + return l +} + +func TestMigrateLegacyBinary(t *testing.T) { + l := testLayout(t) + if err := os.WriteFile(l.LegacyBin, []byte("old build"), 0o755); err != nil { + t.Fatal(err) + } + if err := migrateLegacyBinary(l); err != nil { + t.Fatal(err) + } + if target, err := os.Readlink(l.LegacyBin); err != nil || target != "printer" { + t.Fatalf("print-agent -> %q, %v", target, err) + } + if b, err := os.ReadFile(l.LegacyBin + ".legacy"); err != nil || string(b) != "old build" { + t.Fatalf("legacy backup = %q, %v", b, err) + } + // Idempotent: a second setup leaves the symlink and the backup alone. + if err := migrateLegacyBinary(l); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(l.LegacyBin + ".legacy"); string(b) != "old build" { + t.Fatal("backup overwritten") + } +} + +func TestEnsureConfigKeepsExistingFile(t *testing.T) { + l := testLayout(t) + if err := os.MkdirAll(l.ConfigDir, 0o755); err != nil { + t.Fatal(err) + } + existing := []byte("PRINT_AGENT_API_URL=https://app.example.test\n") + if err := os.WriteFile(l.ConfigFile, existing, 0o644); err != nil { + t.Fatal(err) + } + if err := ensureConfig(l); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(l.ConfigFile) + info, _ := os.Stat(l.ConfigFile) + if string(got) != string(existing) || info.Mode().Perm() != 0o600 { + t.Fatalf("config = %q mode %v", got, info.Mode()) + } +} + +func TestEnsureConfigCreatesFromTemplate(t *testing.T) { + l := testLayout(t) + if err := ensureConfig(l); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(l.ConfigFile) + if string(got) != string(printagent.EnvTemplate) { + t.Fatal("config not created from the template") + } +} + +func TestWriteIfChanged(t *testing.T) { + path := filepath.Join(t.TempDir(), "units", "a.service") + for i, want := range []bool{true, false} { + changed, err := writeIfChanged(path, []byte("x"), 0o644) + if err != nil || changed != want { + t.Fatalf("call %d: changed=%v err=%v", i, changed, err) + } + } + if changed, _ := writeIfChanged(path, []byte("y"), 0o644); !changed { + t.Fatal("new content not written") + } +} + +func TestPathContains(t *testing.T) { + if !pathContains("/usr/bin:/home/u/.local/bin/", "/home/u/.local/bin") { + t.Fatal("not found") + } + if pathContains("/usr/bin", "/home/u/.local/bin") { + t.Fatal("false positive") + } +} + +func TestEmbeddedUnitRunsPrinter(t *testing.T) { + if !contains(string(printagent.ServiceUnit), "ExecStart=%h/.local/bin/printer run") || + !contains(string(printagent.ServiceUnit), "EnvironmentFile=%h/.config/print-agent/env") { + t.Fatal("service unit must run ~/.local/bin/printer with the existing config path") + } +} + +func contains(s, sub string) bool { return strings.Contains(s, sub) } diff --git a/cmd/printer/update.go b/cmd/printer/update.go new file mode 100644 index 0000000..cd444fc --- /dev/null +++ b/cmd/printer/update.go @@ -0,0 +1,215 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "print-agent/internal/envfile" + "print-agent/internal/selfupdate" + "print-agent/internal/service" +) + +func repo() string { + if r := os.Getenv("PRINTER_REPO"); r != "" { + return r + } + return selfupdate.DefaultRepo +} + +func cmdUpdate(args []string) error { + fs := flag.NewFlagSet("update", flag.ExitOnError) + check := fs.Bool("check", false, "Only compare the installed version with the latest release") + tag := fs.String("version", "", "Install this release tag (e.g. v1.2.0) instead of the latest, also to downgrade") + wait := fs.Duration("wait", 20*time.Second, "How long the restarted service must stay up before the update is kept") + _ = fs.Parse(args) + + if runtime.GOOS != "linux" { + return errors.New("update is only supported on Linux") + } + // PRINTER_GITHUB_TOKEN may be set in the config (private repository). + _ = envfile.Load(paths().ConfigFile) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + defer cancel() + + client := selfupdate.NewClient(repo()) + var rel selfupdate.Release + var err error + if *tag != "" { + rel, err = client.ByTag(ctx, *tag) + } else { + rel, err = client.Latest(ctx) + } + if err != nil { + return err + } + + p := paths() + dir := filepath.Dir(p.Bin) + refused := readRefused(dir) + + decision, err := selfupdate.Decide(version, rel.TagName) + if err != nil { + return err + } + if *tag != "" { + msg, install := describeExplicit(version, rel.TagName) + fmt.Println(msg) + if !install || *check { + return nil + } + } else { + switch decision { + case selfupdate.UpToDate: + fmt.Printf("Installed %s, latest release %s: up to date.\n", version, rel.TagName) + case selfupdate.UpdateAvailable: + fmt.Printf("Installed %s, latest release %s: update available.\n", version, rel.TagName) + case selfupdate.DevBuild: + fmt.Printf("Installed %s (development build), latest release %s.\n", version, rel.TagName) + } + if decision != selfupdate.UpToDate && refused == rel.TagName { + fmt.Printf("%s was rolled back on this PC after failing to start: skipped.\n"+ + "Install it anyway with `printer update --version %s` once the cause is fixed.\n", rel.TagName, rel.TagName) + return nil + } + if *check { + if decision == selfupdate.UpdateAvailable { + fmt.Println("Run `printer update` to install it.") + } + return nil + } + if decision == selfupdate.UpToDate { + return nil + } + } + + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + unlock, err := selfupdate.Lock(dir) + if err != nil { + return err + } + defer unlock() + + asset := selfupdate.AssetName(runtime.GOOS, runtime.GOARCH) + fmt.Printf("Downloading %s %s...\n", asset, rel.TagName) + staged, err := selfupdate.Stage(ctx, client, rel, asset, dir) + if err != nil { + return err + } + defer func() { _ = os.Remove(staged) }() // no-op once installed + fmt.Println("sha256 checksum verified.") + if got, err := selfupdate.Probe(ctx, staged); err != nil { + return err + } else if got != rel.TagName { + return fmt.Errorf("downloaded binary reports version %q, expected %s", got, rel.TagName) + } + + return installAndRestart(ctx, staged, p.Bin, rel.TagName, *wait) +} + +// describeExplicit explains what `update --version` will do and whether to install. +func describeExplicit(current, target string) (string, bool) { + if current == target { + return fmt.Sprintf("%s is already installed.", target), false + } + cv, errC := selfupdate.ParseVersion(current) + tv, errT := selfupdate.ParseVersion(target) + switch { + case errC != nil || errT != nil: + return fmt.Sprintf("Installed %s, installing %s.", current, target), true + case tv.Compare(cv) < 0: + return fmt.Sprintf("Installed %s: downgrade to %s.", current, target), true + default: + return fmt.Sprintf("Installed %s: upgrade to %s.", current, target), true + } +} + +// The tag of a release rolled back by the automatic health check, so the +// daily timer does not reinstall it every night. +const refusedFile = ".printer-refused-version" + +func readRefused(dir string) string { + b, err := os.ReadFile(filepath.Join(dir, refusedFile)) + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} + +func writeRefused(dir, tag string) { + _ = os.WriteFile(filepath.Join(dir, refusedFile), []byte(tag+"\n"), 0o644) +} + +func clearRefused(dir string) { + _ = os.Remove(filepath.Join(dir, refusedFile)) +} + +// installAndRestart swaps the binary in and, when the service was running, +// restarts it and rolls back if the new version does not stay up. +func installAndRestart(ctx context.Context, staged, bin, newVersion string, wait time.Duration) error { + sd := newSystemd() + props, err := sd.Show(ctx, service.Agent) + wasActive := err == nil && props.Active() + + if err := selfupdate.Swap(staged, bin); err != nil { + return fmt.Errorf("install %s: %w", tildePath(bin), err) + } + fmt.Printf("Installed %s at %s (previous binary kept as %s).\n", + newVersion, tildePath(bin), tildePath(bin+selfupdate.PrevSuffix)) + + if !wasActive { + clearRefused(filepath.Dir(bin)) + fmt.Println("The service was not running: it was not started (`printer start`).") + return nil + } + healthErr := restartAndWatch("restart", wait) + if healthErr == nil { + clearRefused(filepath.Dir(bin)) + return nil + } + writeRefused(filepath.Dir(bin), newVersion) + + fmt.Fprintf(os.Stderr, "The new version does not stay up: %v\nRolling back...\n", healthErr) + if err := selfupdate.Rollback(bin); err != nil { + return fmt.Errorf("rollback failed: %w (the previous binary is %s)", err, tildePath(bin+selfupdate.PrevSuffix)) + } + if err := restartAndWatch("restart", wait); err != nil { + return fmt.Errorf("rolled back to the previous binary, but it does not stay up either: %w"+ + " — probably not the update (network, API, config): check `printer log -n 100`", err) + } + return fmt.Errorf("update to %s rolled back, the previous version is running again", newVersion) +} + +func cmdRollback(args []string) error { + p := paths() + unlock, err := selfupdate.Lock(filepath.Dir(p.Bin)) + if err != nil { + return err + } + defer unlock() + if err := selfupdate.Rollback(p.Bin); err != nil { + return err + } + fmt.Printf("Restored the previous binary (now: %s).\n", probeVersion(p.Bin)) + sd := newSystemd() + if props, err := sd.Show(context.Background(), service.Agent); err == nil && props.Active() { + return restartAndWatch("restart", 10*time.Second) + } + return nil +} + +func probeVersion(bin string) string { + v, err := selfupdate.Probe(context.Background(), bin) + if err != nil { + return "unknown version" + } + return v +} diff --git a/cmd/printer/update_test.go b/cmd/printer/update_test.go new file mode 100644 index 0000000..a94f555 --- /dev/null +++ b/cmd/printer/update_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "print-agent/internal/selfupdate" + "print-agent/internal/service" +) + +// fakeSystemd simulates a running agent; after the restarts listed in +// crashAfter, it reports a crash loop. +func fakeSystemd(t *testing.T, crashAfter map[int]bool) *[]string { + t.Helper() + var calls []string + restarts := 0 + runner := func(ctx context.Context, name string, args ...string) (string, error) { + calls = append(calls, strings.Join(args, " ")) + if len(args) > 1 && args[1] == "restart" { + restarts++ + } + if len(args) > 1 && args[1] == "show" { + if crashAfter[restarts] { + return "ActiveState=activating\nSubState=auto-restart\nNRestarts=1\nResult=exit-code\n", nil + } + return "ActiveState=active\nSubState=running\nNRestarts=0\n", nil + } + return "", nil + } + old, oldStep := newSystemd, healthPollStep + newSystemd = func() *service.Systemd { return &service.Systemd{Run: runner, Sleep: func(time.Duration) {}} } + healthPollStep = time.Millisecond + t.Cleanup(func() { newSystemd, healthPollStep = old, oldStep }) + return &calls +} + +func stage(t *testing.T, dir, content string) (bin, staged string) { + t.Helper() + bin = filepath.Join(dir, "printer") + staged = filepath.Join(dir, ".printer-update-x") + if err := os.WriteFile(bin, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(staged, []byte(content), 0o755); err != nil { + t.Fatal(err) + } + return bin, staged +} + +func read(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestInstallAndRestartKeepsHealthyUpdate(t *testing.T) { + fakeSystemd(t, nil) + dir := t.TempDir() + bin, staged := stage(t, dir, "new") + writeRefused(dir, "v1.1.0") + if err := installAndRestart(context.Background(), staged, bin, "v1.1.0", 5*time.Millisecond); err != nil { + t.Fatal(err) + } + if read(t, bin) != "new" || read(t, bin+selfupdate.PrevSuffix) != "old" { + t.Fatal("update not kept") + } + if readRefused(dir) != "" { + t.Fatal("a successful install must clear the refused version") + } +} + +func TestInstallAndRestartRollsBackCrashingUpdate(t *testing.T) { + calls := fakeSystemd(t, map[int]bool{1: true}) // first restart (new binary) crashes + dir := t.TempDir() + bin, staged := stage(t, dir, "new") + err := installAndRestart(context.Background(), staged, bin, "v1.1.0", 5*time.Millisecond) + if err == nil || !strings.Contains(err.Error(), "rolled back") { + t.Fatalf("err = %v", err) + } + if read(t, bin) != "old" { + t.Fatal("previous binary not restored") + } + if readRefused(dir) != "v1.1.0" { + t.Fatal("the rolled back version must be remembered") + } + n := 0 + for _, c := range *calls { + if strings.Contains(c, "restart print-agent.service") { + n++ + } + } + if n != 2 { + t.Fatalf("restarts = %d, want 2 (new, then rollback)", n) + } +} + +func TestInstallAndRestartReportsWhenOldVersionFailsToo(t *testing.T) { + fakeSystemd(t, map[int]bool{1: true, 2: true}) + dir := t.TempDir() + bin, staged := stage(t, dir, "new") + err := installAndRestart(context.Background(), staged, bin, "v1.1.0", 5*time.Millisecond) + if err == nil || !strings.Contains(err.Error(), "does not stay up either") { + t.Fatalf("err = %v", err) + } +} + +func TestDescribeExplicit(t *testing.T) { + cases := []struct { + current, target, want string + install bool + }{ + {"v1.2.0", "v1.1.0", "downgrade to v1.1.0", true}, + {"v1.1.0", "v1.2.0", "upgrade to v1.2.0", true}, + {"v1.2.0", "v1.2.0", "already installed", false}, + {"dev", "v1.2.0", "installing v1.2.0", true}, + } + for _, c := range cases { + msg, install := describeExplicit(c.current, c.target) + if !strings.Contains(msg, c.want) || install != c.install { + t.Errorf("%s -> %s: %q %v", c.current, c.target, msg, install) + } + } +} diff --git a/deploy/README.md b/deploy/README.md index f763ee7..fc4101a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,99 +1,12 @@ -# Deploying print-agent as a systemd service +# deploy/ -## Quick install +| Fichier | Rôle | +|---|---| +| `install.sh` | installation en une commande (`curl -fsSL https://raw.githubusercontent.com/ICTools/printer-agent/main/deploy/install.sh \| bash`), ou `--from-source` depuis un clone | +| `print-agent.service` | service systemd utilisateur de l'agent (`printer run`) | +| `printer-update.service`, `printer-update.timer` | mise à jour automatique quotidienne (désactivée par défaut, `printer autoupdate on`) | -```bash -./deploy/install.sh -``` +Les trois unités sont **embarquées dans le binaire** (`assets.go`) et écrites dans `~/.config/systemd/user/` par +`printer setup` : modifier ces fichiers ici, pas sur le PC. -This script: -1. Builds the `print-agent` binary -2. Installs the binary to `~/.local/bin/print-agent` -3. Creates `~/.config/print-agent/env` from `.env.example` (if it doesn't exist) -4. Installs the systemd user service -5. Enables lingering (service starts at boot without login) -6. Enables the service - -## Manual install - -### 1. Build and install the binary - -```bash -go build -o print-agent ./cmd/print-agent -mkdir -p ~/.local/bin -install -m 0755 print-agent ~/.local/bin/print-agent -``` - -### 2. Configure environment - -```bash -mkdir -p ~/.config/print-agent -cp .env.example ~/.config/print-agent/env -nano ~/.config/print-agent/env # fill in API credentials -``` - -The env file uses systemd `EnvironmentFile=` format: -- No `export` prefix -- Double-quote values with spaces: `KEY="value with spaces"` -- `#` for comments - -### 3. Install the service - -```bash -mkdir -p ~/.config/systemd/user -cp deploy/print-agent.service ~/.config/systemd/user/ -systemctl --user daemon-reload -systemctl --user enable print-agent -``` - -### 4. Enable start at boot (without login) - -```bash -loginctl enable-linger $(whoami) -``` - -### 5. Start - -```bash -systemctl --user start print-agent -``` - -## Managing the service - -| Action | Command | -|--------|---------| -| Start | `systemctl --user start print-agent` | -| Stop | `systemctl --user stop print-agent` | -| Restart | `systemctl --user restart print-agent` | -| Status | `systemctl --user status print-agent` | -| Enable at boot | `systemctl --user enable print-agent` | -| Disable at boot | `systemctl --user disable print-agent` | - -## Viewing logs - -Logs go to journald (stdout/stderr are captured automatically). - -```bash -# Follow logs in real time -journalctl --user -u print-agent -f - -# Today's logs -journalctl --user -u print-agent --since today - -# Errors only -journalctl --user -u print-agent -p err - -# Last 100 lines -journalctl --user -u print-agent -n 100 -``` - -Log rotation is handled by journald (configured in `/etc/systemd/journald.conf`). - -## Uninstall - -```bash -systemctl --user stop print-agent -systemctl --user disable print-agent -rm ~/.config/systemd/user/print-agent.service -systemctl --user daemon-reload -``` +Installation, commandes, mise à jour, migration et dépannage : voir le [README](../README.md). diff --git a/deploy/install.sh b/deploy/install.sh index 9f8de99..42d102a 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -1,61 +1,133 @@ #!/usr/bin/env bash +# Install (or repair, or migrate) the print agent on a till PC, without Go: +# +# curl -fsSL https://raw.githubusercontent.com/ICTools/printer-agent/main/deploy/install.sh | bash +# +# Options (after `bash -s --` when piped): +# --version vX.Y.Z install that release instead of the latest +# --from-source build from this checkout with Go (development) +# +# It downloads the binary of the GitHub release for this CPU, checks its sha256 +# against checksums.txt, then runs `printer setup`, which installs the binary +# to ~/.local/bin/printer, the systemd user service, the config +# ~/.config/print-agent/env (never overwritten) and enables start at boot. +# +# Private repository: export GITHUB_TOKEN=... (or log in with `gh auth login`). set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_DIR="$(dirname "$SCRIPT_DIR")" -SERVICE_NAME="print-agent" -CONFIG_DIR="${HOME}/.config/${SERVICE_NAME}" -SYSTEMD_DIR="${HOME}/.config/systemd/user" -BIN_DIR="${HOME}/.local/bin" - -echo "=== print-agent installer ===" -echo - -# 1. Build the binary -echo "[1/6] Building print-agent..." -cd "$REPO_DIR" -go build -o print-agent ./cmd/print-agent -echo " Built: ${REPO_DIR}/print-agent" - -# 2. Install binary to ~/.local/bin -echo "[2/6] Installing binary to ${BIN_DIR}..." -mkdir -p "$BIN_DIR" -install -m 0755 "${REPO_DIR}/print-agent" "${BIN_DIR}/${SERVICE_NAME}" -echo " Installed: ${BIN_DIR}/${SERVICE_NAME}" - -# 3. Create config directory and env file if missing -echo "[3/6] Setting up config directory..." -mkdir -p "$CONFIG_DIR" -if [ ! -f "${CONFIG_DIR}/env" ]; then - cp "${REPO_DIR}/.env.example" "${CONFIG_DIR}/env" - echo " Created: ${CONFIG_DIR}/env (from .env.example)" - echo " >>> EDIT THIS FILE with your API credentials before starting the service <<<" +# Everything runs from main(), called on the last line: if `curl | bash` is cut +# off mid-download, bash never runs a partial script. +main() { +REPO="${PRINTER_REPO:-ICTools/printer-agent}" +VERSION="latest" +FROM_SOURCE=0 + +usage() { + cat <<'USAGE' +Usage: install.sh [--version vX.Y.Z] [--from-source] + piped: curl -fsSL https://raw.githubusercontent.com/ICTools/printer-agent/main/deploy/install.sh | bash -s -- --version v1.0.0 + --version vX.Y.Z install that release instead of the latest + --from-source build from this checkout with Go (development) +Private repository: export GITHUB_TOKEN=... or `gh auth login` first. +USAGE +} + +while [ $# -gt 0 ]; do + case "$1" in + --version) VERSION="${2:?--version needs a tag, e.g. v1.0.0}"; shift 2 ;; + --from-source) FROM_SOURCE=1; shift ;; + -h|--help) usage; exit 0 ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +if [ "$(id -u)" -eq 0 ]; then + echo "Run this as the till user, not root/sudo: the service is a systemd *user* service." >&2 + exit 1 +fi +if [ "$(uname -s)" != "Linux" ]; then + echo "Linux only." >&2 + exit 1 +fi + +# Not /tmp: it may be mounted noexec, and the downloaded binary is executed. +mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}" +TMP="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/printer-install.XXXXXX")" +trap 'rm -rf "$TMP"' EXIT + +if [ "$FROM_SOURCE" -eq 1 ]; then + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + REPO_DIR="$(dirname "$SCRIPT_DIR")" + if [ ! -f "$REPO_DIR/go.mod" ]; then + echo "--from-source must be run from a checkout: ./deploy/install.sh --from-source" >&2 + exit 1 + fi + command -v go >/dev/null || { echo "Go is required for --from-source." >&2; exit 1; } + BUILD_VERSION="$(git -C "$REPO_DIR" describe --tags --always --dirty 2>/dev/null || echo dev)" + echo "Building printer ${BUILD_VERSION} from ${REPO_DIR}..." + (cd "$REPO_DIR" && CGO_ENABLED=0 go build -trimpath \ + -ldflags "-s -w -X main.version=${BUILD_VERSION}" -o "$TMP/printer" ./cmd/printer) + "$TMP/printer" setup &2; exit 1 ;; +esac +ASSET="printer_linux_${ARCH}" + +if [ "$VERSION" = "latest" ]; then + BASE="https://github.com/${REPO}/releases/latest/download" else - echo " Config already exists: ${CONFIG_DIR}/env (not overwritten)" + BASE="https://github.com/${REPO}/releases/download/${VERSION}" fi -# 4. Install systemd unit -echo "[4/6] Installing systemd service..." -mkdir -p "$SYSTEMD_DIR" -cp "${SCRIPT_DIR}/${SERVICE_NAME}.service" "${SYSTEMD_DIR}/${SERVICE_NAME}.service" -systemctl --user daemon-reload -echo " Installed: ${SYSTEMD_DIR}/${SERVICE_NAME}.service" - -# 5. Enable lingering (start service at boot, even without login) -echo "[5/6] Enabling lingering for user $(whoami)..." -loginctl enable-linger "$(whoami)" -echo " Linger enabled" - -# 6. Enable (but don't start yet — user needs to configure env first) -echo "[6/6] Enabling service..." -systemctl --user enable "$SERVICE_NAME" -echo " Service enabled (will start at next boot)" - -echo -echo "=== Installation complete ===" -echo -echo "Next steps:" -echo " 1. Edit your config: nano ${CONFIG_DIR}/env" -echo " 2. Start the service: systemctl --user start ${SERVICE_NAME}" -echo " 3. Check status: systemctl --user status ${SERVICE_NAME}" -echo " 4. View logs: journalctl --user -u ${SERVICE_NAME} -f" +download_public() { + curl -fsSL --retry 3 -o "$TMP/$ASSET" "$BASE/$ASSET" && + curl -fsSL --retry 3 -o "$TMP/checksums.txt" "$BASE/checksums.txt" +} + +download_gh() { + command -v gh >/dev/null || return 1 + local tag=() + if [ "$VERSION" != "latest" ]; then tag=("$VERSION"); fi + # gh uses GH_TOKEN / GITHUB_TOKEN when set, else its own login. + gh release download "${tag[@]}" -R "$REPO" -p "$ASSET" -p checksums.txt -D "$TMP" --clobber +} + +echo "Downloading ${ASSET} (${VERSION}) from ${REPO}..." +if ! download_public 2>/dev/null; then + echo "Public download failed, trying the gh CLI (private repository?)..." + if ! download_gh; then + cat >&2 <, then retry. +EOF + exit 1 + fi +fi + +echo "Verifying sha256..." +if ! (cd "$TMP" && grep -E "^[0-9a-f]{64} [ *]${ASSET}\$" checksums.txt | sha256sum -c --strict -); then + echo "Checksum verification FAILED: nothing was installed." >&2 + exit 1 +fi +chmod 0755 "$TMP/$ASSET" + +"$TMP/$ASSET" setup 0 { + return fmt.Sprintf("%s: line %d: %s", level, p.Line, p.Message) + } + return fmt.Sprintf("%s: %s", level, p.Message) +} + +var keyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// Parse reads the file the way systemd does for the common cases: blank +// lines and lines starting with # or ; are ignored, values may be wrapped in +// single or double quotes. Syntax errors are returned as fatal problems. +func Parse(data []byte) ([]Entry, []Problem) { + var entries []Entry + var problems []Problem + sc := bufio.NewScanner(bytes.NewReader(data)) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || line[0] == '#' || line[0] == ';' { + continue + } + if strings.HasPrefix(line, "export ") { + problems = append(problems, Problem{n, "remove the 'export' prefix (systemd EnvironmentFile format)", true}) + continue + } + key, value, ok := strings.Cut(line, "=") + key = strings.TrimSpace(key) + if !ok || !keyRe.MatchString(key) { + // Never echo the line: it may hold a secret (a pasted token, a key with a typo). + problems = append(problems, Problem{n, "expected KEY=VALUE (line not shown, it may contain a secret)", true}) + continue + } + v, err := unquote(strings.TrimSpace(value)) + if err != nil { + problems = append(problems, Problem{n, fmt.Sprintf("%s: %v", key, err), true}) + continue + } + entries = append(entries, Entry{Line: n, Key: key, Value: v}) + } + return entries, problems +} + +func unquote(v string) (string, error) { + if v == "" { + return "", nil + } + q := v[0] + if q != '"' && q != '\'' { + return v, nil + } + if len(v) < 2 || v[len(v)-1] != q { + return "", fmt.Errorf("unterminated quote") + } + inner := v[1 : len(v)-1] + if q == '"' { + inner = strings.NewReplacer(`\"`, `"`, `\\`, `\`).Replace(inner) + } + return inner, nil +} + +// Map returns the last value of each key. +func Map(entries []Entry) map[string]string { + m := make(map[string]string, len(entries)) + for _, e := range entries { + m[e.Key] = e.Value + } + return m +} + +// Known lists the variables the agent reads (README "Variables d'environnement"). +var Known = map[string]bool{ + "PRINT_AGENT_API_URL": true, "PRINT_AGENT_API_KEY": true, "PRINT_AGENT_API_SECRET": true, + "PRINT_AGENT_POLL_INTERVAL": true, "PRINT_AGENT_PING_INTERVAL": true, "PRINT_AGENT_SYNC_INTERVAL": true, + "PRINT_AGENT_HEALTH_ADDR": true, "RECEIPT_PRINTER_DEVICE": true, "RECEIPT_LOGO_PATH": true, + "RECEIPT_PRINTABLE_DOTS": true, "STORE_ADDRESS_LINE1": true, "STORE_ADDRESS_LINE2": true, + "STORE_PHONE": true, "STORE_VAT_NUMBER": true, "STORE_SOCIAL_HANDLE": true, "STORE_WEBSITE": true, + "PYTHON_PATH": true, "LABEL_SCRIPT_PATH": true, "STICKER_SCRIPT_PATH": true, + "PRINTER_GITHUB_TOKEN": true, "GITHUB_TOKEN": true, "GH_TOKEN": true, +} + +// placeholders are the values of .env.example that must be replaced. +var placeholders = map[string]bool{ + "https://your-api.example.com": true, "your-api-key": true, "your-api-secret": true, +} + +// Validate parses the file and checks what the agent needs to start. +func Validate(data []byte) ([]Entry, []Problem) { + entries, problems := Parse(data) + m := Map(entries) + for _, key := range []string{"PRINT_AGENT_API_URL", "PRINT_AGENT_API_KEY", "PRINT_AGENT_API_SECRET"} { + v, ok := m[key] + switch { + case !ok || v == "": + problems = append(problems, Problem{0, key + " is required", true}) + case placeholders[v]: + problems = append(problems, Problem{lineOf(entries, key), key + " still has the example value", true}) + } + } + if raw := m["PRINT_AGENT_API_URL"]; raw != "" && !placeholders[raw] { + if u, err := url.Parse(raw); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + problems = append(problems, Problem{lineOf(entries, "PRINT_AGENT_API_URL"), + "PRINT_AGENT_API_URL must be an http(s) URL, e.g. https://app.example.com", true}) + } + } + for _, key := range []string{"PRINT_AGENT_POLL_INTERVAL", "PRINT_AGENT_PING_INTERVAL", "PRINT_AGENT_SYNC_INTERVAL"} { + if v := m[key]; v != "" { + if d, err := time.ParseDuration(v); err != nil || d <= 0 { + problems = append(problems, Problem{lineOf(entries, key), + fmt.Sprintf("%s=%q is not a positive duration (e.g. 2s, 1m)", key, v), true}) + } + } + } + for _, key := range []string{"LABEL_SCRIPT_PATH", "STICKER_SCRIPT_PATH", "RECEIPT_LOGO_PATH"} { + if v := m[key]; v != "" { + if _, err := os.Stat(v); err != nil { + msg := key + " points to a missing file" + if key != "RECEIPT_LOGO_PATH" { + msg += ": remove the line to use the script built into the binary" + } + problems = append(problems, Problem{lineOf(entries, key), msg, false}) + } + } + } + for _, e := range entries { + if !Known[e.Key] { + problems = append(problems, Problem{e.Line, "unknown variable " + e.Key + " (typo?)", false}) + } + } + return entries, problems +} + +// HasFatal reports whether one of the problems prevents starting the agent. +func HasFatal(problems []Problem) bool { + for _, p := range problems { + if p.Fatal { + return true + } + } + return false +} + +func lineOf(entries []Entry, key string) int { + line := 0 + for _, e := range entries { + if e.Key == key { + line = e.Line + } + } + return line +} + +// IsSecret reports whether a variable holds a credential that must never be +// printed in full. +func IsSecret(key string) bool { + k := strings.ToUpper(key) + for _, s := range []string{"SECRET", "PASSWORD", "PASSWD", "TOKEN", "KEY"} { + if strings.Contains(k, s) { + return true + } + } + return false +} + +// Mask returns the value to display: secrets are hidden, API keys keep their +// first 4 characters so two configs can be told apart. +func Mask(key, value string) string { + if strings.HasSuffix(strings.ToUpper(key), "_URL") { + return MaskURL(value) + } + if !IsSecret(key) || value == "" { + return value + } + k := strings.ToUpper(key) + if strings.HasSuffix(k, "_KEY") && !strings.Contains(k, "SECRET") && len(value) > 8 { + return value[:4] + "********" + } + return "********" +} + +// Load reads the file at path into the process environment without +// overriding variables already set, so the CLI sees what the service sees. +func Load(path string) error { + data, err := os.ReadFile(path) + if err != nil { + return err + } + entries, _ := Parse(data) + for _, e := range entries { + if _, set := os.LookupEnv(e.Key); !set { + if err := os.Setenv(e.Key, e.Value); err != nil { + return err + } + } + } + return nil +} + +// MaskURL hides the password of credentials embedded in a URL (user:pass@host). +func MaskURL(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.User == nil { + return raw + } + if _, hasPass := u.User.Password(); hasPass { + u.User = url.UserPassword(u.User.Username(), "xxxxx") + return strings.Replace(u.String(), "xxxxx", "********", 1) + } + return raw +} diff --git a/internal/envfile/envfile_test.go b/internal/envfile/envfile_test.go new file mode 100644 index 0000000..41450a8 --- /dev/null +++ b/internal/envfile/envfile_test.go @@ -0,0 +1,148 @@ +package envfile + +import ( + "os" + "path/filepath" + "strings" + "testing" + + printagent "print-agent" +) + +func TestParse(t *testing.T) { + data := []byte(`# comment +; other comment + +PRINT_AGENT_API_URL=https://app.example.test +STORE_ADDRESS_LINE1="Rue de l'Exemple 1" +STORE_PHONE='01 23' +QUOTED="a \"b\" c" +EMPTY= +`) + entries, problems := Parse(data) + if len(problems) != 0 { + t.Fatalf("problems: %v", problems) + } + m := Map(entries) + want := map[string]string{ + "PRINT_AGENT_API_URL": "https://app.example.test", + "STORE_ADDRESS_LINE1": "Rue de l'Exemple 1", + "STORE_PHONE": "01 23", + "QUOTED": `a "b" c`, + "EMPTY": "", + } + for k, v := range want { + if m[k] != v { + t.Errorf("%s = %q, want %q", k, m[k], v) + } + } + if entries[0].Line != 4 { + t.Errorf("line = %d", entries[0].Line) + } +} + +func TestParseSyntaxErrors(t *testing.T) { + for _, bad := range []string{"export A=1", "NOEQUALS", "1A=x", `A="open`} { + _, problems := Parse([]byte(bad)) + if !HasFatal(problems) { + t.Errorf("%q: no fatal problem", bad) + } + } +} + +func TestValidate(t *testing.T) { + good := []byte("PRINT_AGENT_API_URL=https://app.example.test\nPRINT_AGENT_API_KEY=k123456789\n" + + "PRINT_AGENT_API_SECRET=\"s3cr3t\"\nPRINT_AGENT_POLL_INTERVAL=2s\n") + if _, problems := Validate(good); len(problems) != 0 { + t.Fatalf("problems: %v", problems) + } + + _, problems := Validate(printagent.EnvTemplate) + if !HasFatal(problems) { + t.Fatal("the untouched template must not validate") + } + + bad := []byte("PRINT_AGENT_API_URL=app.example.test\nPRINT_AGENT_API_KEY=k\n" + + "PRINT_AGENT_API_SECRET=s\nPRINT_AGENT_SYNC_INTERVAL=10\nSTORE_PHON=1\n") + _, problems = Validate(bad) + joined := "" + for _, p := range problems { + joined += p.String() + "\n" + } + for _, want := range []string{"must be an http(s) URL", "PRINT_AGENT_SYNC_INTERVAL", "warning: line 5: unknown variable STORE_PHON"} { + if !strings.Contains(joined, want) { + t.Errorf("missing %q in:\n%s", want, joined) + } + } + + _, problems = Validate([]byte("PRINT_AGENT_API_URL=https://x.test\n")) + if !HasFatal(problems) { + t.Fatal("missing credentials must be fatal") + } +} + +func TestMask(t *testing.T) { + cases := []struct{ key, value, want string }{ + {"PRINT_AGENT_API_SECRET", "topsecretvalue", "********"}, + {"PRINT_AGENT_API_KEY", "abcd1234efgh", "abcd********"}, + {"PRINT_AGENT_API_KEY", "short", "********"}, + {"GITHUB_TOKEN", "ghp_xxxxxxxxxxxx", "********"}, + {"PRINT_AGENT_API_URL", "https://app.example.test", "https://app.example.test"}, + {"PRINT_AGENT_API_SECRET", "", ""}, + } + for _, c := range cases { + if got := Mask(c.key, c.value); got != c.want { + t.Errorf("Mask(%s, %q) = %q, want %q", c.key, c.value, got, c.want) + } + } +} + +func TestLoadDoesNotOverride(t *testing.T) { + path := filepath.Join(t.TempDir(), "env") + if err := os.WriteFile(path, []byte("ENVFILE_TEST_A=fromfile\nENVFILE_TEST_B=fromfile\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("ENVFILE_TEST_A", "fromenv") + t.Setenv("ENVFILE_TEST_B", "") + _ = os.Unsetenv("ENVFILE_TEST_B") + if err := Load(path); err != nil { + t.Fatal(err) + } + if os.Getenv("ENVFILE_TEST_A") != "fromenv" || os.Getenv("ENVFILE_TEST_B") != "fromfile" { + t.Fatalf("A=%q B=%q", os.Getenv("ENVFILE_TEST_A"), os.Getenv("ENVFILE_TEST_B")) + } +} + +func TestProblemsNeverEchoSecrets(t *testing.T) { + data := []byte("PRINT_AGENT_API_URL=https://app.example.test\nPRINT_AGENT_API_KEY=k123456789\n" + + "PRINT_AGENT_API_SECRET=s\nPRINT AGENT API SECRET=leakme-s3cr3t\nghp_leakme_token\n" + + "PRINT_AGENT_API_SECRET=\"leakme-unterminated\n") + _, problems := Validate(data) + if len(problems) < 3 { + t.Fatalf("problems: %v", problems) + } + for _, p := range problems { + if strings.Contains(p.String(), "leakme") { + t.Errorf("secret echoed: %s", p) + } + } +} + +func TestValidateWarnsAboutMissingScriptPath(t *testing.T) { + data := []byte("PRINT_AGENT_API_URL=https://app.example.test\nPRINT_AGENT_API_KEY=k123456789\n" + + "PRINT_AGENT_API_SECRET=s\nLABEL_SCRIPT_PATH=/nonexistent/clone/scripts/print.py\n") + _, problems := Validate(data) + if HasFatal(problems) || len(problems) != 1 || !strings.Contains(problems[0].Message, "LABEL_SCRIPT_PATH points to a missing file") { + t.Fatalf("problems: %v", problems) + } +} + +func TestMaskURLCredentials(t *testing.T) { + if got := Mask("PRINT_AGENT_API_URL", "https://bob:hunter2@app.example.test/api"); strings.Contains(got, "hunter2") || + !strings.Contains(got, "bob:********@app.example.test") { + t.Fatalf("got %q", got) + } + if got := Mask("PRINT_AGENT_API_URL", "https://app.example.test"); got != "https://app.example.test" { + t.Fatalf("got %q", got) + } +} diff --git a/internal/label/label.go b/internal/label/label.go index 5d4c825..c72ac6d 100644 --- a/internal/label/label.go +++ b/internal/label/label.go @@ -1,12 +1,19 @@ package label import ( + "bytes" "context" + "crypto/sha256" + "encoding/hex" "fmt" + "log" "os" "os/exec" "path/filepath" + "sort" "time" + + printagent "print-agent" ) type LabelOptions struct { @@ -85,25 +92,105 @@ func PrintStickerImage(ctx context.Context, opts StickerImageOptions) error { } func defaultScriptPath(scriptName string) string { - if env := os.Getenv("LABEL_SCRIPT_PATH"); env != "" && scriptName == "print.py" { - return env + envKey := "" + switch scriptName { + case "print.py": + envKey = "LABEL_SCRIPT_PATH" + case "print_sticker.py": + envKey = "STICKER_SCRIPT_PATH" } - if env := os.Getenv("STICKER_SCRIPT_PATH"); env != "" && scriptName == "print_sticker.py" { - return env + if env := os.Getenv(envKey); envKey != "" && env != "" { + if _, err := os.Stat(env); err == nil { + return env + } + // Typically a path into a repository clone deleted after the migration + // to release binaries: fall back to the copy built into the binary. + log.Printf("[WARN] %s=%s not found, using the script built into the binary", envKey, env) } - execPath, err := os.Executable() - if err != nil { - return scriptName + if execPath, err := os.Executable(); err == nil { + candidate := filepath.Join(filepath.Dir(execPath), "scripts", scriptName) + if _, err := os.Stat(candidate); err == nil { + return candidate + } } - base := filepath.Dir(execPath) - candidate := filepath.Join(base, "scripts", scriptName) - if _, err := os.Stat(candidate); err == nil { - return candidate + if dir, err := extractEmbeddedScripts(); err == nil { + return filepath.Join(dir, scriptName) } return scriptName } +// embeddedFiles are written together in one directory: print.py looks for +// ./sticker.png in its working directory (the script directory). +func embeddedFiles() map[string][]byte { + return map[string][]byte{ + "print.py": printagent.LabelScript, + "print_sticker.py": printagent.StickerScript, + "sticker.png": printagent.StickerImage, + } +} + +// extractEmbeddedScripts writes the files built into the binary to the user +// cache (one directory per content hash, so an updated binary never runs a +// stale script) and returns the directory. It lets a release binary print +// labels without a checkout of the repository. +func extractEmbeddedScripts() (string, error) { + cacheDir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return extractTo(filepath.Join(cacheDir, "print-agent", "scripts"), embeddedFiles()) +} + +func extractTo(root string, files map[string][]byte) (string, error) { + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + sort.Strings(names) + h := sha256.New() + for _, name := range names { + h.Write([]byte(name)) + h.Write(files[name]) + } + dir := filepath.Join(root, hex.EncodeToString(h.Sum(nil))[:12]) + for _, name := range names { + if _, err := writeScriptOnce(dir, name, files[name]); err != nil { + return "", err + } + } + return dir, nil +} + +func writeScriptOnce(dir, scriptName string, content []byte) (string, error) { + target := filepath.Join(dir, scriptName) + if existing, err := os.ReadFile(target); err == nil && bytes.Equal(existing, content) { + return target, nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + tmp, err := os.CreateTemp(dir, "."+scriptName+"-*") + if err != nil { + return "", err + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(content); err != nil { + _ = tmp.Close() + return "", err + } + if err := tmp.Close(); err != nil { + return "", err + } + if err := os.Chmod(tmp.Name(), 0o755); err != nil { + return "", err + } + if err := os.Rename(tmp.Name(), target); err != nil { + return "", err + } + return target, nil +} + func getEnvOrDefault(key, fallback string) string { if value := os.Getenv(key); value != "" { return value diff --git a/internal/label/label_test.go b/internal/label/label_test.go new file mode 100644 index 0000000..f39dc57 --- /dev/null +++ b/internal/label/label_test.go @@ -0,0 +1,75 @@ +package label + +import ( + "bytes" + "os" + "path/filepath" + "testing" +) + +func TestWriteScriptOnceWritesExecutableCopy(t *testing.T) { + dir := filepath.Join(t.TempDir(), "scripts", "abc") + path, err := writeScriptOnce(dir, "print.py", []byte("print('hi')\n")) + if err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil || string(got) != "print('hi')\n" { + t.Fatalf("content = %q, %v", got, err) + } + info, _ := os.Stat(path) + if info.Mode().Perm()&0o100 == 0 { + t.Fatalf("script not executable: %v", info.Mode()) + } + // Second call with the same content is a no-op; different content replaces it. + if _, err := writeScriptOnce(dir, "print.py", []byte("print('hi')\n")); err != nil { + t.Fatal(err) + } + if _, err := writeScriptOnce(dir, "print.py", []byte("print('new')\n")); err != nil { + t.Fatal(err) + } + got, _ = os.ReadFile(path) + if string(got) != "print('new')\n" { + t.Fatalf("content not replaced: %q", got) + } +} + +func TestDefaultScriptPathPrefersExistingEnvPath(t *testing.T) { + custom := filepath.Join(t.TempDir(), "print.py") + if err := os.WriteFile(custom, []byte("x"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("LABEL_SCRIPT_PATH", custom) + if got := defaultScriptPath("print.py"); got != custom { + t.Fatalf("got %q", got) + } +} + +func TestDefaultScriptPathIgnoresMissingEnvPath(t *testing.T) { + t.Setenv("LABEL_SCRIPT_PATH", filepath.Join(t.TempDir(), "deleted-clone", "print.py")) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + got := defaultScriptPath("print.py") + if got == os.Getenv("LABEL_SCRIPT_PATH") { + t.Fatal("a missing LABEL_SCRIPT_PATH must not be used") + } + if _, err := os.Stat(got); err != nil { + t.Fatalf("fallback %q: %v", got, err) + } +} + +func TestDefaultScriptPathFallsBackToEmbeddedScripts(t *testing.T) { + t.Setenv("STICKER_SCRIPT_PATH", "") + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + got := defaultScriptPath("print_sticker.py") + if filepath.Base(got) != "print_sticker.py" || !filepath.IsAbs(got) { + t.Fatalf("got %q", got) + } + // print.py and sticker.png must sit next to it: print.py reads ./sticker.png. + dir := filepath.Dir(got) + for name, want := range embeddedFiles() { + b, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil || !bytes.Equal(b, want) || len(want) == 0 { + t.Errorf("%s: %d bytes, %v", name, len(b), err) + } + } +} diff --git a/internal/receipt/testpage.go b/internal/receipt/testpage.go new file mode 100644 index 0000000..f7436c9 --- /dev/null +++ b/internal/receipt/testpage.go @@ -0,0 +1,40 @@ +package receipt + +import ( + "io" + "os" + "strings" +) + +// PrintTestPage prints a short ticket with the given lines (no price, no +// barcode, no drawer kick): `printer test` uses it to check the printer path. +func (p *Printer) PrintTestPage(lines []string) error { + f, err := os.OpenFile(p.Device, os.O_WRONLY, 0) + if err != nil { + return err + } + defer func() { + _ = f.Sync() + _ = f.Close() + }() + return writeTestPage(f, lines) +} + +func writeTestPage(w io.Writer, lines []string) error { + var b strings.Builder + b.Write([]byte{0x1b, '@'}) // initialize + b.Write([]byte{0x1b, 't', 0x13}) // character table + b.Write([]byte{0x1b, 'a', 1}) // center + b.Write([]byte{0x1b, 'E', 1}) // bold + b.WriteString("TEST IMPRESSION\n") + b.Write([]byte{0x1b, 'E', 0}) + b.WriteString(strings.Repeat("-", 32) + "\n") + b.Write([]byte{0x1b, 'a', 0}) // left + for _, l := range lines { + b.WriteString(removeAccents(l) + "\n") + } + b.WriteString("\n\n\n\n") + b.Write([]byte{0x1d, 'V', 1}) // partial cut + _, err := io.WriteString(w, b.String()) + return err +} diff --git a/internal/receipt/testpage_test.go b/internal/receipt/testpage_test.go new file mode 100644 index 0000000..bc71062 --- /dev/null +++ b/internal/receipt/testpage_test.go @@ -0,0 +1,23 @@ +package receipt + +import ( + "bytes" + "strings" + "testing" +) + +func TestWriteTestPage(t *testing.T) { + var buf bytes.Buffer + if err := writeTestPage(&buf, []string{"Version: v1.0.0", "Poste: caisse-é"}); err != nil { + t.Fatal(err) + } + out := buf.String() + for _, want := range []string{"TEST IMPRESSION", "Version: v1.0.0", "Poste: caisse-e", "\x1dV\x01"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q", want) + } + } + if strings.Contains(out, "\x1bp") { + t.Error("the test page must not kick the cash drawer") + } +} diff --git a/internal/selfupdate/checksum.go b/internal/selfupdate/checksum.go new file mode 100644 index 0000000..9b6f387 --- /dev/null +++ b/internal/selfupdate/checksum.go @@ -0,0 +1,72 @@ +package selfupdate + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "strings" +) + +// ParseChecksums reads a sha256sum file (" " per line, the name +// optionally prefixed by "*" for binary mode) into a name -> hex digest map. +func ParseChecksums(data []byte) (map[string]string, error) { + sums := map[string]string{} + sc := bufio.NewScanner(bytes.NewReader(data)) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Fields(line) + if len(fields) != 2 { + return nil, fmt.Errorf("checksums line %d: malformed %q", n, line) + } + digest := strings.ToLower(fields[0]) + if b, err := hex.DecodeString(digest); err != nil || len(b) != sha256.Size { + return nil, fmt.Errorf("checksums line %d: invalid sha256 %q", n, fields[0]) + } + sums[strings.TrimPrefix(fields[1], "*")] = digest + } + if err := sc.Err(); err != nil { + return nil, err + } + if len(sums) == 0 { + return nil, fmt.Errorf("checksums file is empty") + } + return sums, nil +} + +// ExpectedChecksum returns the digest published for the asset. +func ExpectedChecksum(checksums []byte, asset string) (string, error) { + sums, err := ParseChecksums(checksums) + if err != nil { + return "", err + } + digest, ok := sums[asset] + if !ok { + return "", fmt.Errorf("no checksum published for %s", asset) + } + return digest, nil +} + +// VerifyFile checks that the file at path has the expected sha256 digest. +func VerifyFile(path, expected string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return err + } + got := hex.EncodeToString(h.Sum(nil)) + if !strings.EqualFold(got, expected) { + return fmt.Errorf("checksum mismatch: got %s, expected %s", got, expected) + } + return nil +} diff --git a/internal/selfupdate/github.go b/internal/selfupdate/github.go new file mode 100644 index 0000000..ee2c531 --- /dev/null +++ b/internal/selfupdate/github.go @@ -0,0 +1,225 @@ +package selfupdate + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + neturl "net/url" + "os" + "os/exec" + "strings" + "time" +) + +// DefaultRepo is the GitHub repository the releases are published to. +const DefaultRepo = "ICTools/printer-agent" + +// ChecksumsAsset is the name of the sha256sum file attached to each release. +const ChecksumsAsset = "checksums.txt" + +// AssetName is the release asset holding the binary for a platform. +func AssetName(goos, goarch string) string { + return fmt.Sprintf("printer_%s_%s", goos, goarch) +} + +// Asset is a file attached to a GitHub release. +type Asset struct { + Name string `json:"name"` + // URL is the API URL; with "Accept: application/octet-stream" it serves + // the file, also for a private repository (with a token). + URL string `json:"url"` + BrowserDownloadURL string `json:"browser_download_url"` + Size int64 `json:"size"` +} + +// Release is the subset of a GitHub release the updater uses. +type Release struct { + TagName string `json:"tag_name"` + HTMLURL string `json:"html_url"` + Assets []Asset `json:"assets"` +} + +// FindAsset returns the asset with that exact name. +func (r Release) FindAsset(name string) (Asset, error) { + for _, a := range r.Assets { + if a.Name == name { + return a, nil + } + } + return Asset{}, fmt.Errorf("release %s has no asset %s", r.TagName, name) +} + +// Client talks to the GitHub REST API. +type Client struct { + Repo string + BaseURL string // https://api.github.com, overridable in tests + Token string // optional: needed only for a private repository + HTTP *http.Client + // MaxSize bounds every download (DefaultMaxSize when 0). + MaxSize int64 + // AllowInsecure accepts http:// and any host: local test servers only + // (PRINTER_UPDATE_INSECURE=1). Otherwise every request, redirects included, + // must be https to GitHub (or to the PRINTER_GITHUB_API host). + AllowInsecure bool +} + +// DefaultMaxSize is far above the size of a release binary (~10 MB). +const DefaultMaxSize = 100 << 20 + +// githubHosts serve the API, the release pages and the asset redirects. +func githubHost(host string) bool { + return host == "github.com" || host == "api.github.com" || strings.HasSuffix(host, ".githubusercontent.com") +} + +// checkURL refuses anything but https to GitHub (or the configured API host). +func (c *Client) checkURL(u *neturl.URL) error { + if c.AllowInsecure { + return nil + } + if u.Scheme != "https" { + return fmt.Errorf("refusing non-https URL %s", u.Redacted()) + } + host := u.Hostname() + if githubHost(host) { + return nil + } + if base, err := neturl.Parse(c.BaseURL); err == nil && base.Hostname() == host { + return nil + } + return fmt.Errorf("refusing download from unexpected host %s", host) +} + +func (c *Client) do(req *http.Request) (*http.Response, error) { + if err := c.checkURL(req.URL); err != nil { + return nil, err + } + hc := *c.HTTP + hc.CheckRedirect = func(r *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return fmt.Errorf("too many redirects") + } + return c.checkURL(r.URL) + } + return hc.Do(req) +} + +// NewClient returns a client for repo, authenticated when a token is found +// (see TokenFromEnv). +func NewClient(repo string) *Client { + base := "https://api.github.com" + if v := os.Getenv("PRINTER_GITHUB_API"); v != "" { // GitHub Enterprise, or a local test server + base = v + } + return &Client{ + Repo: repo, + BaseURL: base, + Token: TokenFromEnv(), + HTTP: &http.Client{Timeout: 5 * time.Minute}, + AllowInsecure: os.Getenv("PRINTER_UPDATE_INSECURE") == "1", + } +} + +// TokenFromEnv returns PRINTER_GITHUB_TOKEN, GH_TOKEN or GITHUB_TOKEN, else +// the token of the gh CLI when it is installed and logged in, else "". +func TokenFromEnv() string { + for _, k := range []string{"PRINTER_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"} { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return v + } + } + if _, err := exec.LookPath("gh"); err == nil { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if out, err := exec.CommandContext(ctx, "gh", "auth", "token").Output(); err == nil { + return strings.TrimSpace(string(out)) + } + } + return "" +} + +// Latest returns the latest published (non-draft, non-prerelease) release. +func (c *Client) Latest(ctx context.Context) (Release, error) { + return c.release(ctx, "releases/latest") +} + +// ByTag returns the release of a given tag. +func (c *Client) ByTag(ctx context.Context, tag string) (Release, error) { + return c.release(ctx, "releases/tags/"+tag) +} + +func (c *Client) release(ctx context.Context, path string) (Release, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, + fmt.Sprintf("%s/repos/%s/%s", strings.TrimRight(c.BaseURL, "/"), c.Repo, path), nil) + if err != nil { + return Release{}, err + } + req.Header.Set("Accept", "application/vnd.github+json") + c.authorize(req) + resp, err := c.do(req) + if err != nil { + return Release{}, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode == http.StatusNotFound { + hint := "no release published yet?" + if c.Token == "" { + hint += " If the repository is private, set GITHUB_TOKEN or run `gh auth login`." + } + return Release{}, fmt.Errorf("GitHub: no matching release for %s (%s)", c.Repo, hint) + } + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + return Release{}, fmt.Errorf("GitHub API: %s: %s", resp.Status, strings.TrimSpace(string(body))) + } + var r Release + if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { + return Release{}, fmt.Errorf("GitHub API: %w", err) + } + return r, nil +} + +// Download streams an asset to w. +func (c *Client) Download(ctx context.Context, a Asset, w io.Writer) error { + url := a.BrowserDownloadURL + if c.Token != "" && a.URL != "" { + url = a.URL + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/octet-stream") + if url == a.URL { + c.authorize(req) + } + resp, err := c.do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("download %s: %s", a.Name, resp.Status) + } + limit := c.MaxSize + if limit <= 0 { + limit = DefaultMaxSize + } + n, err := io.Copy(w, io.LimitReader(resp.Body, limit+1)) + if err != nil { + return err + } + if n > limit { + return fmt.Errorf("download %s: larger than %d bytes, refused", a.Name, limit) + } + return nil +} + +func (c *Client) authorize(req *http.Request) { + if c.Token != "" { + req.Header.Set("Authorization", "Bearer "+c.Token) + } + req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + req.Header.Set("User-Agent", "printer-agent-updater") +} diff --git a/internal/selfupdate/install.go b/internal/selfupdate/install.go new file mode 100644 index 0000000..e3ca480 --- /dev/null +++ b/internal/selfupdate/install.go @@ -0,0 +1,157 @@ +package selfupdate + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "time" +) + +// PrevSuffix names the copy of the previous binary kept next to the current one. +const PrevSuffix = ".prev" + +// Stage downloads the asset and its checksum into dir (which must be on the +// same filesystem as the final binary so the swap is an atomic rename), +// verifies the sha256 and makes the file executable. The caller removes the +// returned file if it does not install it. +func Stage(ctx context.Context, c *Client, rel Release, assetName, dir string) (string, error) { + asset, err := rel.FindAsset(assetName) + if err != nil { + return "", err + } + sumsAsset, err := rel.FindAsset(ChecksumsAsset) + if err != nil { + return "", err + } + var sums strings.Builder + if err := c.Download(ctx, sumsAsset, &sums); err != nil { + return "", err + } + expected, err := ExpectedChecksum([]byte(sums.String()), assetName) + if err != nil { + return "", err + } + + f, err := os.CreateTemp(dir, ".printer-update-*") + if err != nil { + return "", err + } + path := f.Name() + fail := func(err error) (string, error) { + _ = f.Close() + _ = os.Remove(path) + return "", err + } + if err := c.Download(ctx, asset, f); err != nil { + return fail(err) + } + if err := f.Close(); err != nil { + return fail(err) + } + if err := VerifyFile(path, expected); err != nil { + return fail(err) + } + if err := os.Chmod(path, 0o755); err != nil { + return fail(err) + } + return path, nil +} + +// Probe runs " version --short" and returns what it prints: it proves +// the binary executes on this machine and reports the expected version. +func Probe(ctx context.Context, bin string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, bin, "version", "--short").Output() + if err != nil { + return "", fmt.Errorf("new binary does not run: %w", err) + } + return strings.TrimSpace(string(out)), nil +} + +// Swap atomically replaces target with staged. The binary it replaces is kept +// as target+PrevSuffix for Rollback. A running process keeps executing its +// old inode, so swapping the binary of a running service is safe. +func Swap(staged, target string) error { + prev := target + PrevSuffix + if _, err := os.Stat(target); err == nil { + if err := os.Remove(prev); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + if err := linkOrCopy(target, prev); err != nil { + return fmt.Errorf("keep previous binary: %w", err) + } + } + return os.Rename(staged, target) +} + +// Rollback exchanges target and target+PrevSuffix: the previous binary +// becomes current and the current one is kept as the new ".prev", so a +// second Rollback undoes the first. +func Rollback(target string) error { + prev := target + PrevSuffix + if _, err := os.Stat(prev); err != nil { + return fmt.Errorf("no previous binary to restore (%s): %w", prev, err) + } + hold := target + ".rollback" + _ = os.Remove(hold) + hasCurrent := false + if _, err := os.Stat(target); err == nil { + if err := linkOrCopy(target, hold); err != nil { + return err + } + hasCurrent = true + } + if err := os.Rename(prev, target); err != nil { + _ = os.Remove(hold) + return err + } + if hasCurrent { + return os.Rename(hold, prev) + } + return nil +} + +func linkOrCopy(src, dst string) error { + if err := os.Link(src, dst); err == nil { + return nil + } + in, err := os.Open(src) + if err != nil { + return err + } + defer func() { _ = in.Close() }() + out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + _ = out.Close() + return err + } + return out.Close() +} + +// Lock takes an exclusive, non-blocking lock so a manual update and the +// daily timer never run at the same time. +func Lock(dir string) (func(), error) { + path := filepath.Join(dir, ".printer-update.lock") + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = f.Close() + return nil, fmt.Errorf("another update is running (%s)", path) + } + return func() { + _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + _ = f.Close() + }, nil +} diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.go new file mode 100644 index 0000000..92c9871 --- /dev/null +++ b/internal/selfupdate/selfupdate_test.go @@ -0,0 +1,328 @@ +package selfupdate + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestParseVersion(t *testing.T) { + ok := map[string]Version{ + "v1.2.3": {1, 2, 3, ""}, + "1.2.3": {1, 2, 3, ""}, + "v0.10.0-rc.1": {0, 10, 0, "rc.1"}, + " v2.0.0 \n": {2, 0, 0, ""}, + "v1.0.0-beta-2": {1, 0, 0, "beta-2"}, + } + for in, want := range ok { + got, err := ParseVersion(in) + if err != nil || got != want { + t.Errorf("ParseVersion(%q) = %v, %v; want %v", in, got, err, want) + } + } + for _, in := range []string{"dev", "", "a82ed4d", "v1.2", "v1.2.3-4-ga82ed4d", "v1.2.3-dirty", "a82ed4d-dirty", "1.2.3.4"} { + if _, err := ParseVersion(in); err == nil { + t.Errorf("ParseVersion(%q) accepted", in) + } + } +} + +func TestVersionCompare(t *testing.T) { + cases := []struct { + a, b string + want int + }{ + {"v1.0.0", "v1.0.0", 0}, + {"v1.0.1", "v1.0.0", 1}, + {"v1.0.0", "v1.0.1", -1}, + {"v1.10.0", "v1.9.9", 1}, + {"v2.0.0", "v1.99.99", 1}, + {"v1.0.0", "v1.0.0-rc.1", 1}, + {"v1.0.0-rc.1", "v1.0.0", -1}, + {"v1.0.0-rc.2", "v1.0.0-rc.10", -1}, + {"v1.0.0-alpha", "v1.0.0-alpha.1", -1}, + {"v1.0.0-alpha.1", "v1.0.0-beta", -1}, + {"v1.0.0-1", "v1.0.0-alpha", -1}, + } + for _, c := range cases { + a, _ := ParseVersion(c.a) + b, _ := ParseVersion(c.b) + if got := a.Compare(b); got != c.want { + t.Errorf("%s vs %s = %d, want %d", c.a, c.b, got, c.want) + } + } +} + +func TestDecide(t *testing.T) { + cases := []struct { + current, latest string + want Decision + }{ + {"v1.0.0", "v1.1.0", UpdateAvailable}, + {"v1.1.0", "v1.1.0", UpToDate}, + {"v1.2.0", "v1.1.0", UpToDate}, + {"dev", "v1.1.0", DevBuild}, + {"v1.1.0-2-gabc1234", "v1.1.0", DevBuild}, + } + for _, c := range cases { + got, err := Decide(c.current, c.latest) + if err != nil || got != c.want { + t.Errorf("Decide(%q, %q) = %v, %v; want %v", c.current, c.latest, got, err, c.want) + } + } + if _, err := Decide("v1.0.0", "nightly"); err == nil { + t.Error("a non-semver release tag must be an error") + } +} + +const sumA = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + +func TestParseChecksums(t *testing.T) { + data := []byte(sumA + " printer_linux_amd64\n" + + strings.ToUpper(sumA) + " *printer_linux_arm64\n\n# comment\n") + sums, err := ParseChecksums(data) + if err != nil { + t.Fatal(err) + } + if sums["printer_linux_amd64"] != sumA || sums["printer_linux_arm64"] != sumA { + t.Fatalf("sums = %v", sums) + } + for _, bad := range []string{"", "nothex file\n", sumA + "\n", "abcd file\n"} { + if _, err := ParseChecksums([]byte(bad)); err == nil { + t.Errorf("ParseChecksums(%q) accepted", bad) + } + } + if _, err := ExpectedChecksum(data, "printer_darwin_amd64"); err == nil { + t.Error("missing asset must be an error") + } +} + +func TestVerifyFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "bin") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := VerifyFile(path, sumA); err != nil { + t.Fatal(err) + } + if err := VerifyFile(path, strings.Repeat("0", 64)); err == nil { + t.Fatal("mismatch accepted") + } +} + +func TestAssetSelection(t *testing.T) { + if got := AssetName("linux", "arm64"); got != "printer_linux_arm64" { + t.Fatalf("AssetName = %q", got) + } + rel := Release{TagName: "v1.0.0", Assets: []Asset{ + {Name: "printer_linux_amd64.sig"}, + {Name: "printer_linux_amd64"}, + {Name: "checksums.txt"}, + }} + a, err := rel.FindAsset("printer_linux_amd64") + if err != nil || a.Name != "printer_linux_amd64" { + t.Fatalf("FindAsset = %v, %v", a, err) + } + if _, err := rel.FindAsset("printer_linux_arm64"); err == nil { + t.Fatal("missing asset must be an error") + } +} + +// fakeGitHub serves a release whose binary is content and whose checksums +// file announces sum for it. +func fakeGitHub(t *testing.T, content, sum string) (*Client, Release) { + t.Helper() + mux := http.NewServeMux() + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + rel := Release{TagName: "v1.2.0", Assets: []Asset{ + {Name: "printer_linux_amd64", BrowserDownloadURL: srv.URL + "/dl/bin", URL: srv.URL + "/api/bin"}, + {Name: "checksums.txt", BrowserDownloadURL: srv.URL + "/dl/sums", URL: srv.URL + "/api/sums"}, + }} + mux.HandleFunc("/repos/acme/printer/releases/latest", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(rel) + }) + serve := func(body string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprint(w, body) } + } + sums := sum + " printer_linux_amd64\n" + mux.HandleFunc("/dl/bin", serve(content)) + mux.HandleFunc("/dl/sums", serve(sums)) + mux.HandleFunc("/api/bin", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer tok" || r.Header.Get("Accept") != "application/octet-stream" { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + _, _ = fmt.Fprint(w, content) + }) + mux.HandleFunc("/api/sums", serve(sums)) + return &Client{Repo: "acme/printer", BaseURL: srv.URL, HTTP: srv.Client(), AllowInsecure: true}, rel +} + +func sha(s string) string { + h := sha256.Sum256([]byte(s)) + return hex.EncodeToString(h[:]) +} + +func TestStageVerifiesChecksum(t *testing.T) { + content := "#!/bin/sh\necho v1.2.0\n" + c, _ := fakeGitHub(t, content, sha(content)) + rel, err := c.Latest(context.Background()) + if err != nil || rel.TagName != "v1.2.0" { + t.Fatalf("Latest = %v, %v", rel, err) + } + dir := t.TempDir() + path, err := Stage(context.Background(), c, rel, "printer_linux_amd64", dir) + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil || info.Mode().Perm() != 0o755 || filepath.Dir(path) != dir { + t.Fatalf("staged %s: %v %v", path, info, err) + } + if v, err := Probe(context.Background(), path); err != nil || v != "v1.2.0" { + t.Fatalf("Probe = %q, %v", v, err) + } +} + +func TestStageRejectsTamperedBinary(t *testing.T) { + c, rel := fakeGitHub(t, "tampered", sha("original")) + dir := t.TempDir() + if _, err := Stage(context.Background(), c, rel, "printer_linux_amd64", dir); err == nil || + !strings.Contains(err.Error(), "checksum mismatch") { + t.Fatalf("err = %v", err) + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Fatalf("staged file left behind: %v", entries) + } +} + +func TestStageUsesAPIURLWithToken(t *testing.T) { + content := "binary" + c, rel := fakeGitHub(t, content, sha(content)) + c.Token = "tok" + if _, err := Stage(context.Background(), c, rel, "printer_linux_amd64", t.TempDir()); err != nil { + t.Fatal(err) + } +} + +func TestLatestNotFoundHintsAtToken(t *testing.T) { + srv := httptest.NewServer(http.NotFoundHandler()) + defer srv.Close() + c := &Client{Repo: "acme/printer", BaseURL: srv.URL, HTTP: srv.Client(), AllowInsecure: true} + if _, err := c.Latest(context.Background()); err == nil || !strings.Contains(err.Error(), "GITHUB_TOKEN") { + t.Fatalf("err = %v", err) + } +} + +func TestSwapAndRollback(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "printer") + write := func(p, s string) { + if err := os.WriteFile(p, []byte(s), 0o755); err != nil { + t.Fatal(err) + } + } + read := func(p string) string { + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) + } + write(target, "old") + staged := filepath.Join(dir, ".printer-update-1") + write(staged, "new") + + if err := Swap(staged, target); err != nil { + t.Fatal(err) + } + if read(target) != "new" || read(target+PrevSuffix) != "old" { + t.Fatal("swap did not keep the previous binary") + } + if _, err := os.Stat(staged); !os.IsNotExist(err) { + t.Fatal("staged file still present") + } + if err := Rollback(target); err != nil { + t.Fatal(err) + } + if read(target) != "old" || read(target+PrevSuffix) != "new" { + t.Fatal("rollback did not exchange the binaries") + } + if err := Rollback(target); err != nil || read(target) != "new" { + t.Fatalf("second rollback: %v", err) + } +} + +func TestSwapWithoutExistingTarget(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "printer") + staged := filepath.Join(dir, "staged") + if err := os.WriteFile(staged, []byte("new"), 0o755); err != nil { + t.Fatal(err) + } + if err := Swap(staged, target); err != nil { + t.Fatal(err) + } + if err := Rollback(target); err == nil { + t.Fatal("rollback without a previous binary must fail") + } +} + +func TestLockIsExclusive(t *testing.T) { + dir := t.TempDir() + unlock, err := Lock(dir) + if err != nil { + t.Fatal(err) + } + if _, err := Lock(dir); err == nil { + t.Fatal("second lock acquired") + } + unlock() + unlock2, err := Lock(dir) + if err != nil { + t.Fatal(err) + } + unlock2() +} + +func TestDownloadRefusesNonHTTPSAndForeignHosts(t *testing.T) { + content := "binary" + c, rel := fakeGitHub(t, content, sha(content)) + c.AllowInsecure = false + if _, err := c.Latest(context.Background()); err == nil || !strings.Contains(err.Error(), "non-https") { + t.Fatalf("http API accepted: %v", err) + } + c.BaseURL = "https://api.github.com" + for _, raw := range []string{"https://evil.example/printer", "http://github.com/x"} { + err := c.Download(context.Background(), Asset{Name: "x", BrowserDownloadURL: raw}, io.Discard) + if err == nil || !strings.Contains(err.Error(), "refusing") { + t.Errorf("%s: err = %v", raw, err) + } + } + _ = rel + u, _ := url.Parse("https://release-assets.githubusercontent.com/a") + if err := c.checkURL(u); err != nil { + t.Fatalf("GitHub asset host refused: %v", err) + } +} + +func TestDownloadSizeLimit(t *testing.T) { + content := strings.Repeat("x", 2048) + c, rel := fakeGitHub(t, content, sha(content)) + c.MaxSize = 1024 + if _, err := Stage(context.Background(), c, rel, "printer_linux_amd64", t.TempDir()); err == nil || + !strings.Contains(err.Error(), "larger than") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/selfupdate/version.go b/internal/selfupdate/version.go new file mode 100644 index 0000000..1a10187 --- /dev/null +++ b/internal/selfupdate/version.go @@ -0,0 +1,128 @@ +// Package selfupdate finds, downloads, verifies and installs printer releases +// published on GitHub. +package selfupdate + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +// Version is a semantic version "vMAJOR.MINOR.PATCH[-PRERELEASE]". +type Version struct { + Major, Minor, Patch int + Prerelease string +} + +var semverRe = regexp.MustCompile(`^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$`) + +// gitDescribeRe matches the "-N-gSHA" suffix git describe adds after a tag. +var gitDescribeRe = regexp.MustCompile(`-\d+-g[0-9a-f]+(-dirty)?$`) + +// ParseVersion parses a release version. Development builds ("dev", a bare +// commit hash, a git describe output such as "v1.2.0-3-gabc1234-dirty") are +// rejected: they are not releases and cannot be ordered against one. +func ParseVersion(s string) (Version, error) { + s = strings.TrimSpace(s) + if gitDescribeRe.MatchString(s) || strings.HasSuffix(s, "-dirty") { + return Version{}, fmt.Errorf("%q is a development build", s) + } + m := semverRe.FindStringSubmatch(s) + if m == nil { + return Version{}, fmt.Errorf("%q is not a release version (vX.Y.Z)", s) + } + v := Version{Prerelease: m[4]} + v.Major, _ = strconv.Atoi(m[1]) + v.Minor, _ = strconv.Atoi(m[2]) + v.Patch, _ = strconv.Atoi(m[3]) + return v, nil +} + +func (v Version) String() string { + s := fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch) + if v.Prerelease != "" { + s += "-" + v.Prerelease + } + return s +} + +// Compare returns -1, 0 or 1 as v is older than, equal to or newer than o, +// following the semver precedence rules (a prerelease precedes its release). +func (v Version) Compare(o Version) int { + for _, d := range [][2]int{{v.Major, o.Major}, {v.Minor, o.Minor}, {v.Patch, o.Patch}} { + if d[0] != d[1] { + return cmpInt(d[0], d[1]) + } + } + return comparePrerelease(v.Prerelease, o.Prerelease) +} + +func comparePrerelease(a, b string) int { + switch { + case a == b: + return 0 + case a == "": + return 1 + case b == "": + return -1 + } + pa, pb := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < len(pa) && i < len(pb); i++ { + if pa[i] == pb[i] { + continue + } + na, errA := strconv.Atoi(pa[i]) + nb, errB := strconv.Atoi(pb[i]) + switch { + case errA == nil && errB == nil: + return cmpInt(na, nb) + case errA == nil: // numeric identifiers have lower precedence + return -1 + case errB == nil: + return 1 + default: + return strings.Compare(pa[i], pb[i]) + } + } + return cmpInt(len(pa), len(pb)) +} + +func cmpInt(a, b int) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} + +// Decision is the outcome of comparing the running version with a release. +type Decision int + +const ( + // UpToDate: the running version is the release or newer. + UpToDate Decision = iota + // UpdateAvailable: the release is newer than the running version. + UpdateAvailable + // DevBuild: the running binary is not a release; installing the release + // replaces it with a published build. + DevBuild +) + +// Decide compares the running version with the latest release tag. +func Decide(current, latest string) (Decision, error) { + lv, err := ParseVersion(latest) + if err != nil { + return UpToDate, fmt.Errorf("latest release: %w", err) + } + cv, err := ParseVersion(current) + if err != nil { + return DevBuild, nil + } + if lv.Compare(cv) > 0 { + return UpdateAvailable, nil + } + return UpToDate, nil +} diff --git a/internal/service/service.go b/internal/service/service.go new file mode 100644 index 0000000..dbe0957 --- /dev/null +++ b/internal/service/service.go @@ -0,0 +1,110 @@ +// Package service drives the agent's systemd user units through systemctl. +package service + +import ( + "context" + "fmt" + "os/exec" + "strconv" + "strings" + "time" +) + +// Unit names. +const ( + Agent = "print-agent.service" + UpdateService = "printer-update.service" + UpdateTimer = "printer-update.timer" +) + +// Runner runs a command and returns its combined output. +type Runner func(ctx context.Context, name string, args ...string) (string, error) + +// ExecRunner runs real commands. +func ExecRunner(ctx context.Context, name string, args ...string) (string, error) { + out, err := exec.CommandContext(ctx, name, args...).CombinedOutput() + if err != nil { + return string(out), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return string(out), nil +} + +// Systemd calls `systemctl --user`. +type Systemd struct { + Run Runner + Sleep func(time.Duration) +} + +// New returns a Systemd running real commands. +func New() *Systemd { return &Systemd{Run: ExecRunner, Sleep: time.Sleep} } + +// Ctl runs `systemctl --user `. +func (s *Systemd) Ctl(ctx context.Context, args ...string) error { + _, err := s.Run(ctx, "systemctl", append([]string{"--user"}, args...)...) + return err +} + +// Props are unit properties from `systemctl --user show`. +type Props map[string]string + +// Active reports whether the unit is up and its process running. +func (p Props) Active() bool { return p["ActiveState"] == "active" } + +// Restarts is the number of automatic restarts systemd made. +func (p Props) Restarts() int { + n, _ := strconv.Atoi(p["NRestarts"]) + return n +} + +// Show returns the properties of a unit. +func (s *Systemd) Show(ctx context.Context, unit string) (Props, error) { + out, err := s.Run(ctx, "systemctl", "--user", "show", unit, "--no-pager", + "-p", "ActiveState", "-p", "SubState", "-p", "NRestarts", "-p", "UnitFileState", + "-p", "LoadState", "-p", "ActiveEnterTimestamp", "-p", "MainPID", "-p", "Result", + "-p", "NextElapseUSecRealtime", "-p", "LastTriggerUSec") + if err != nil { + return nil, err + } + props := Props{} + for _, line := range strings.Split(out, "\n") { + if k, v, ok := strings.Cut(strings.TrimSpace(line), "="); ok { + props[k] = v + } + } + return props, nil +} + +// WaitHealthy checks that the unit, just (re)started, stays active for the +// whole window: the agent exits on a bad config or rejected credentials and +// systemd then schedules an automatic restart, which this detects. +func (s *Systemd) WaitHealthy(ctx context.Context, unit string, window, poll time.Duration) error { + start, err := s.Show(ctx, unit) + if err != nil { + return err + } + baseline := start.Restarts() + for waited := time.Duration(0); ; waited += poll { + p, err := s.Show(ctx, unit) + if err != nil { + return err + } + switch { + case p["ActiveState"] == "failed": + return fmt.Errorf("%s failed (%s)", unit, p["Result"]) + case p.Restarts() > baseline || p["SubState"] == "auto-restart": + return fmt.Errorf("%s exited and is being restarted by systemd (%s)", unit, p["Result"]) + case p["ActiveState"] == "inactive" || p["ActiveState"] == "deactivating": + return fmt.Errorf("%s stopped (%s)", unit, p["Result"]) + } + if waited >= window { + if !p.Active() { + return fmt.Errorf("%s not active after %s (%s/%s)", unit, window, p["ActiveState"], p["SubState"]) + } + return nil + } + if err := ctx.Err(); err != nil { + return err + } + s.Sleep(poll) + } +} diff --git a/internal/service/service_test.go b/internal/service/service_test.go new file mode 100644 index 0000000..d442268 --- /dev/null +++ b/internal/service/service_test.go @@ -0,0 +1,78 @@ +package service + +import ( + "context" + "fmt" + "strings" + "testing" + "time" +) + +// scripted returns a Runner answering each `show` call with the next state. +func scripted(states ...string) (Runner, *[]string) { + var calls []string + i := 0 + return func(ctx context.Context, name string, args ...string) (string, error) { + calls = append(calls, name+" "+strings.Join(args, " ")) + if len(args) > 1 && args[1] == "show" { + s := states[min(i, len(states)-1)] + i++ + return s, nil + } + return "", nil + }, &calls +} + +func state(active, sub string, restarts int) string { + return fmt.Sprintf("ActiveState=%s\nSubState=%s\nNRestarts=%d\nResult=success\n", active, sub, restarts) +} + +func newTest(r Runner) *Systemd { return &Systemd{Run: r, Sleep: func(time.Duration) {}} } + +func TestWaitHealthyStable(t *testing.T) { + r, _ := scripted(state("active", "running", 2)) + if err := newTest(r).WaitHealthy(context.Background(), Agent, 3*time.Second, time.Second); err != nil { + t.Fatal(err) + } +} + +func TestWaitHealthyDetectsCrashLoop(t *testing.T) { + r, _ := scripted( + state("active", "running", 0), + state("active", "running", 0), + state("activating", "auto-restart", 1), + ) + err := newTest(r).WaitHealthy(context.Background(), Agent, 10*time.Second, time.Second) + if err == nil || !strings.Contains(err.Error(), "restarted") { + t.Fatalf("err = %v", err) + } +} + +func TestWaitHealthyDetectsRestartBetweenPolls(t *testing.T) { + r, _ := scripted(state("active", "running", 0), state("active", "running", 1)) + if err := newTest(r).WaitHealthy(context.Background(), Agent, 10*time.Second, time.Second); err == nil { + t.Fatal("a restart between two polls must be detected") + } +} + +func TestWaitHealthyDetectsFailed(t *testing.T) { + r, _ := scripted(state("active", "running", 0), state("failed", "failed", 0)) + if err := newTest(r).WaitHealthy(context.Background(), Agent, 10*time.Second, time.Second); err == nil { + t.Fatal("failed state must be an error") + } +} + +func TestShowAndCtl(t *testing.T) { + r, calls := scripted("ActiveState=active\nUnitFileState=enabled\nNRestarts=3\n") + s := newTest(r) + p, err := s.Show(context.Background(), Agent) + if err != nil || !p.Active() || p["UnitFileState"] != "enabled" || p.Restarts() != 3 { + t.Fatalf("props = %v, %v", p, err) + } + if err := s.Ctl(context.Background(), "restart", Agent); err != nil { + t.Fatal(err) + } + if last := (*calls)[len(*calls)-1]; last != "systemctl --user restart print-agent.service" { + t.Fatalf("call = %q", last) + } +} diff --git a/scripts/run-local-tests.sh b/scripts/run-local-tests.sh index 42428a9..7318a76 100755 --- a/scripts/run-local-tests.sh +++ b/scripts/run-local-tests.sh @@ -12,7 +12,7 @@ chmod +x "$bin_dir/brother_ql" printf "Building CLI...\n" ( cd "$root_dir" - go build -o "$tmp_dir/print-agent" ./cmd/print-agent + go build -o "$tmp_dir/print-agent" ./cmd/printer ) printf "Testing receipt output (file device)...\n"