From f1decca31f8e8bf380c4c7d9abf6f9c4ca234d37 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Mon, 23 Nov 2026 19:06:52 -0500 Subject: [PATCH] Add Playwright UI tests and before/after screenshots to CI New UI (playwright) job: PHP and MariaDB inside the Playwright image, a seeded instance (tests/ui/stack.sh, synthetic data only) and 21 tests: every main page loads with no page errors, console errors or failed requests, description and comment markdown render safely (#114), and pages fit a phone screen. Deploys now wait for it. New UI screenshots (before/after) job: for PRs that change assets/ or views/, runs the base branch and the PR side by side with the same data and uploads one side-by-side PNG per page and view (dark, light, phone). Modelled on Pulse's ui and ui-screenshots jobs. Fixes found while building it: - migrate.php split statements on semicolons inside -- comments, so 001 and 003 failed on a fresh database. - API endpoints applied rate limiting before loading config, so RATE_LIMIT_DEFAULT/RATE_LIMIT_API from .env and TRUSTED_PROXIES were ignored there: every user behind the proxy shared one per-IP bucket. The limiter now loads config itself; the per-IP limits are configurable (RATE_LIMIT_IP, RATE_LIMIT_IP_API) with unchanged defaults. - The avatar error fallback was registered in the footer, after the header avatar, so a fast 404 left a broken image instead of initials. Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 + .gitea/workflows/lint.yml | 84 ++++++++++++++++++++- .gitignore | 2 + .phpcs.xml | 1 + README.md | 19 ++++- config/config.php | 2 + middleware/RateLimitMiddleware.php | 21 +++++- migrations/migrate.php | 7 +- tests/ui/.gitignore | 3 + tests/ui/fixtures.js | 61 +++++++++++++++ tests/ui/markdown.ui.js | 56 ++++++++++++++ tests/ui/package-lock.json | 58 +++++++++++++++ tests/ui/package.json | 11 +++ tests/ui/pages.ui.js | 42 +++++++++++ tests/ui/playwright.config.js | 29 ++++++++ tests/ui/responsive.ui.js | 26 +++++++ tests/ui/router.php | 23 ++++++ tests/ui/screenshots.js | 112 ++++++++++++++++++++++++++++ tests/ui/seed.php | 115 +++++++++++++++++++++++++++++ tests/ui/setup.sh | 32 ++++++++ tests/ui/stack.sh | 72 ++++++++++++++++++ views/layout_footer.php | 5 ++ 22 files changed, 777 insertions(+), 8 deletions(-) create mode 100644 tests/ui/.gitignore create mode 100644 tests/ui/fixtures.js create mode 100644 tests/ui/markdown.ui.js create mode 100644 tests/ui/package-lock.json create mode 100644 tests/ui/package.json create mode 100644 tests/ui/pages.ui.js create mode 100644 tests/ui/playwright.config.js create mode 100644 tests/ui/responsive.ui.js create mode 100644 tests/ui/router.php create mode 100644 tests/ui/screenshots.js create mode 100644 tests/ui/seed.php create mode 100755 tests/ui/setup.sh create mode 100755 tests/ui/stack.sh diff --git a/.env.example b/.env.example index 36e7aed..c689a6e 100644 --- a/.env.example +++ b/.env.example @@ -94,3 +94,7 @@ AVATAR_CACHE_TTL=3600 ; Bearer-key API traffic is rate-limited separately, per API key. RATE_LIMIT_DEFAULT=100 RATE_LIMIT_API=60 +; Per client IP limits (requests per 60s window), on top of the session ones, +; so new sessions can't get around them. +RATE_LIMIT_IP=300 +RATE_LIMIT_IP_API=120 diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 1c57ace..d3f58db 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -52,10 +52,90 @@ jobs: - name: Verify runtime requirements run: php scripts/check_requirements.php + ui: + name: UI (playwright) + runs-on: ubuntu-latest + timeout-minutes: 30 + # Official image with Chromium and its system libraries; its version must + # match @playwright/test in tests/ui/package.json. + container: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:2f05f8a734509a7b3f26a912639488ee08f58a7b292d14d62271bcff9038768f + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false # no job pushes; keep the token out of .git/config + - name: Install PHP and MariaDB + run: tests/ui/setup.sh + - name: Start Tinker Tickets (port 8400, seeded test data) + run: tests/ui/stack.sh . 8400 tinker_ui + - name: Install Playwright (lockfile only) + working-directory: tests/ui + run: npm ci + - name: Run Playwright (desktop and mobile) + working-directory: tests/ui + run: npx playwright test + - name: Server log + if: always() + run: tail -n 200 .ui-stack/server.log || true + - name: Upload report, traces and screenshots + if: failure() + uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea) + with: + name: playwright-report + path: | + tests/ui/playwright-report/ + tests/ui/test-results/ + retention-days: 14 + + ui-screenshots: + name: UI screenshots (before/after) + runs-on: ubuntu-latest + timeout-minutes: 30 + if: github.event_name == 'pull_request' + container: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:2f05f8a734509a7b3f26a912639488ee08f58a7b292d14d62271bcff9038768f + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false # no job pushes; keep the token out of .git/config + fetch-depth: 0 + - name: Did this PR change the UI? + id: ui + run: | + git config --global --add safe.directory "$PWD" + if git diff --quiet "$BASE_SHA" HEAD -- assets/ views/; then + echo "No UI files changed; no screenshots needed." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + - name: Install PHP and MariaDB + if: steps.ui.outputs.changed == 'true' + run: tests/ui/setup.sh + - name: Start this PR's Tinker Tickets (port 8400) + if: steps.ui.outputs.changed == 'true' + run: tests/ui/stack.sh . 8400 tinker_ui + - name: Start the base branch's Tinker Tickets (port 8401) + if: steps.ui.outputs.changed == 'true' + run: | + git worktree add /tmp/base "$BASE_SHA" + tests/ui/stack.sh /tmp/base 8401 tinker_ui_base + - name: Capture before/after screenshots + if: steps.ui.outputs.changed == 'true' + run: | + (cd tests/ui && npm ci) + node tests/ui/screenshots.js ui-screenshots before=http://127.0.0.1:8401 after=http://127.0.0.1:8400 + - name: Upload screenshots + if: steps.ui.outputs.changed == 'true' + uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea) + with: + name: ui-screenshots + path: ui-screenshots/ + retention-days: 30 + deploy: name: Deploy runs-on: ubuntu-latest - needs: [php-lint, js-lint, requirements] + needs: [php-lint, js-lint, requirements, ui] if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/development') permissions: contents: write @@ -94,7 +174,7 @@ jobs: notify-failure: name: Notify on failure runs-on: ubuntu-latest - needs: [php-lint, js-lint, requirements] + needs: [php-lint, js-lint, requirements, ui] if: failure() && github.event_name == 'push' steps: - name: Send Matrix alert diff --git a/.gitignore b/.gitignore index ee4c9de..c191094 100755 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ uploads/* !uploads/.htaccess # Composer dependencies (used only by the MCP endpoint; installed at deploy time) vendor/ +.ui-stack/ +ui-screenshots/ diff --git a/.phpcs.xml b/.phpcs.xml index 74d6774..633112f 100644 --- a/.phpcs.xml +++ b/.phpcs.xml @@ -7,6 +7,7 @@ */migrations/* */.gitea/* */vendor/* + */node_modules/* diff --git a/README.md b/README.md index ad5cf5e..ab5b1ae 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ How it fits together (see issue #111 for the full design): ### Security Features - **CSRF Protection**: Token-based protection with constant-time comparison. `bootstrap.php` rotates the token on a successful write and returns the current token in every response (including on rejection); the client (`lt.api`) resyncs from that value. Rejected requests do not rotate the token. -- **Rate Limiting**: Session-based AND IP-based rate limiting to prevent abuse +- **Rate Limiting**: Session-based AND IP-based rate limiting to prevent abuse. Limits are requests per minute from `.env`: `RATE_LIMIT_DEFAULT` / `RATE_LIMIT_API` per session, `RATE_LIMIT_IP` / `RATE_LIMIT_IP_API` per client IP (defaults 100 / 60 / 300 / 120). The client IP is read through `TRUSTED_PROXIES`. - **Security Headers**: CSP with nonces (no unsafe-inline), X-Frame-Options, X-Content-Type-Options - **SQL Injection Prevention**: All queries use prepared statements with parameter binding - **XSS Protection**: HTML escaped in markdown parser, CSP headers block inline scripts @@ -685,14 +685,29 @@ Key conventions and gotchas for working with this codebase: |---|---|---| | `lint.yml` (php-lint) | phpcs PSR-12 standard | Every push and PR | | `lint.yml` (js-lint) | ESLint on `assets/js/` | Every push and PR | +| `lint.yml` (ui) | Playwright UI tests in `tests/ui/` against a seeded instance (desktop and Pixel 7) | Every push and PR | +| `lint.yml` (ui-screenshots) | Before/after screenshots of the base branch and the PR, uploaded as the `ui-screenshots` artifact | PRs that change `assets/` or `views/` | | `security.yml` | semgrep with `p/php` + `p/owasp-top-ten` configs | Every push, PR, and weekly (Monday 6am) | -| `deploy` job in `lint.yml` | Calls deploy webhooks on CT132 (10.10.10.45): `tinker-deploy` (main) or `tinker-beta-deploy` (development); tags deployed commit `deploy-YYYY.MM.DD-N` | Push to `main` or `development`, after both lint jobs pass | +| `deploy` job in `lint.yml` | Calls deploy webhooks on CT132 (10.10.10.45): `tinker-deploy` (main) or `tinker-beta-deploy` (development); tags deployed commit `deploy-YYYY.MM.DD-N` | Push to `main` or `development`, after the lint, requirements and UI jobs pass | | `notify-failure` job in `lint.yml` | Posts CI failure alert to Matrix via webhook | Push to any branch when lint fails | Branch protection is enabled on `main` — both lint jobs must pass before any PR can merge. Lint config: `.phpcs.xml` (PSR-12 with project-specific tweaks), `.eslintrc.json` (root, browser env). +### UI tests + +`tests/ui/` holds the Playwright suite, the synthetic seed data and the scripts CI uses. Every test fails on a page error, console error or failed local request. To run them locally (needs PHP, MariaDB with root socket access, and Node): + +```bash +mariadb -e "CREATE USER IF NOT EXISTS 'tinker_ui'@'127.0.0.1' IDENTIFIED BY 'ci-only';" +git worktree add /tmp/tinker-ui HEAD # stack.sh writes a throwaway .env into the checkout +tests/ui/stack.sh /tmp/tinker-ui 8400 tinker_ui +cd tests/ui && npm ci && npx playwright install chromium && npx playwright test +``` + +`stack.sh` only touches databases named `tinker_ui*` and refuses to overwrite a `.env` it didn't write. It raises the rate limits in that `.env`, since one IP makes every request in a run. For before/after shots, start a base checkout on another port and run `node tests/ui/screenshots.js before=http://127.0.0.1:8401 after=http://127.0.0.1:8400`. + ## License Internal use only - LotusGuild Infrastructure diff --git a/config/config.php b/config/config.php index 1bc3543..c7342f4 100644 --- a/config/config.php +++ b/config/config.php @@ -152,6 +152,8 @@ $GLOBALS['config'] = [ // Rate limiting (requests per minute; read by RateLimitMiddleware) 'RATE_LIMIT_DEFAULT' => (int)($envVars['RATE_LIMIT_DEFAULT'] ?? 100), // Session-based, general endpoints 'RATE_LIMIT_API' => (int)($envVars['RATE_LIMIT_API'] ?? 60), // Session-based, API endpoints + 'RATE_LIMIT_IP' => (int)($envVars['RATE_LIMIT_IP'] ?? 300), // Per client IP, general endpoints + 'RATE_LIMIT_IP_API' => (int)($envVars['RATE_LIMIT_IP_API'] ?? 120), // Per client IP, API endpoints // Audit log settings 'AUDIT_LOG_RETENTION_DAYS' => 90, diff --git a/middleware/RateLimitMiddleware.php b/middleware/RateLimitMiddleware.php index b5eb0c4..c8570b5 100644 --- a/middleware/RateLimitMiddleware.php +++ b/middleware/RateLimitMiddleware.php @@ -13,7 +13,8 @@ class RateLimitMiddleware { // Fallback limits, used only if $GLOBALS['config'] isn't populated // (e.g. very early in bootstrap, or a test harness). Normal requests read - // RATE_LIMIT_DEFAULT/RATE_LIMIT_API from config (backed by .env). + // RATE_LIMIT_DEFAULT/RATE_LIMIT_API/RATE_LIMIT_IP/RATE_LIMIT_IP_API from + // config (backed by .env). public const DEFAULT_LIMIT = 100; // requests per window (session) public const API_LIMIT = 60; // API requests per window (session) public const IP_LIMIT = 300; // IP-based requests per window (more generous) @@ -24,6 +25,18 @@ class RateLimitMiddleware // Directory for IP rate limit storage private static ?string $rateLimitDir = null; + /** + * Load config.php if the caller hasn't yet. API endpoints apply rate + * limiting before they load config, which left the limits, and + * TRUSTED_PROXIES for the client IP, at their fallbacks. + */ + private static function loadConfig(): void + { + if (!isset($GLOBALS['config'])) { + require_once dirname(__DIR__) . '/config/config.php'; + } + } + private static function sessionLimit(string $type): int { $configKey = $type === 'api' ? 'RATE_LIMIT_API' : 'RATE_LIMIT_DEFAULT'; @@ -208,7 +221,9 @@ class RateLimitMiddleware */ private static function checkIpRateLimit(string $type = 'default'): bool { - $limit = $type === 'api' ? self::IP_API_LIMIT : self::IP_LIMIT; + $limit = $type === 'api' + ? (int)($GLOBALS['config']['RATE_LIMIT_IP_API'] ?? self::IP_API_LIMIT) + : (int)($GLOBALS['config']['RATE_LIMIT_IP'] ?? self::IP_LIMIT); return self::checkCounter(self::ipBucketKey($type), $limit); } @@ -285,6 +300,7 @@ class RateLimitMiddleware */ public static function check(string $type = 'default'): bool { + self::loadConfig(); // First check IP-based rate limit (prevents session bypass) if (!self::checkIpRateLimit($type)) { return false; @@ -380,6 +396,7 @@ class RateLimitMiddleware */ public static function getStatus(string $type = 'default'): array { + self::loadConfig(); $token = self::getBearerToken(); if ($token !== null) { return self::peekCounter(self::apiKeyBucketKey($token), self::API_KEY_LIMIT); diff --git a/migrations/migrate.php b/migrations/migrate.php index b34a8b4..35d6f51 100644 --- a/migrations/migrate.php +++ b/migrations/migrate.php @@ -140,8 +140,11 @@ foreach ($pending as $file) { // where a previous run left off rather than re-executing already-applied // DDL. try { - // Split by semicolon but respect statements properly - // Note: This doesn't handle semicolons in strings, but our migrations are simple + // Drop whole-line `--` comments first: a `;` inside a comment (001 and + // 003 have one) would otherwise split the statement in two and run + // the comment's tail as SQL. Then split on semicolons. This still + // doesn't handle semicolons inside strings; our migrations have none. + $sql = preg_replace('/^\s*--.*$/m', '', $sql); $statements = array_values(array_filter( array_map('trim', explode(';', $sql)), function($stmt) { diff --git a/tests/ui/.gitignore b/tests/ui/.gitignore new file mode 100644 index 0000000..945fcd0 --- /dev/null +++ b/tests/ui/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +playwright-report/ +test-results/ diff --git a/tests/ui/fixtures.js b/tests/ui/fixtures.js new file mode 100644 index 0000000..391c166 --- /dev/null +++ b/tests/ui/fixtures.js @@ -0,0 +1,61 @@ +'use strict'; + +// Shared fixture: every test gets a page signed in through Authelia-style +// Remote-* headers (TRUSTED_PROXIES is empty in the test .env, so they are +// accepted from 127.0.0.1), and fails if the page throws, logs a console error, +// or any local request returns >= 400. +const { test: base, expect } = require('@playwright/test'); + +const SSO = { + 'Remote-User': 'ci.tester', + 'Remote-Name': 'CI Tester', + 'Remote-Email': 'ci@example.invalid', + 'Remote-Groups': 'admin', +}; + +const isLocal = url => /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(url); +// Users without an lldap avatar get a 404 and the initials fallback; that is +// the designed behaviour, not a failure (LDAP is off in the tests). +const isAvatar = url => url.includes('/api/user_avatar.php'); + +const test = base.extend({ + extraHTTPHeaders: [SSO, { option: true }], + + // Problems seen on the page; tests that expect one can clear the list. + // eslint-disable-next-line no-empty-pattern -- Playwright requires the destructuring + problems: async ({}, use) => { await use([]); }, + + page: async ({ page, problems }, use) => { + // Nothing leaves the machine: no SSO headers to third parties and no + // dependence on Google Fonts. The fallback fonts are fine for assertions. + await page.route(url => !isLocal(url.href), route => route.abort()); + + page.on('pageerror', e => problems.push(`page error: ${e.message}`)); + page.on('console', m => { + if (m.type() !== 'error') return; + const src = (m.location() && m.location().url) || ''; + if (src && !isLocal(src)) return; + if (/Failed to load resource: net::ERR_FAILED/.test(m.text())) return; // the blocked external requests + if (isAvatar(src)) return; // the avatar 404 below + problems.push(`console error: ${m.text()}`); + }); + page.on('response', r => { + if (isLocal(r.url()) && r.status() >= 400 && !(r.status() === 404 && isAvatar(r.url()))) { + problems.push(`HTTP ${r.status()} ${r.request().method()} ${r.url()}`); + } + }); + + // Skip the once-per-session boot overlay (base.js runBoot, lt_booted_). + await page.addInitScript(() => { + const get = Storage.prototype.getItem; + Storage.prototype.getItem = function (k) { + return String(k).startsWith('lt_booted_') ? '1' : get.call(this, k); + }; + }); + + await use(page); + expect(problems, 'page errors, console errors or failed requests').toEqual([]); + }, +}); + +module.exports = { test, expect, SSO, isLocal }; diff --git a/tests/ui/markdown.ui.js b/tests/ui/markdown.ui.js new file mode 100644 index 0000000..050c6eb --- /dev/null +++ b/tests/ui/markdown.ui.js @@ -0,0 +1,56 @@ +'use strict'; + +// Ticket descriptions and comments render as markdown (#114), safely. +const { test, expect } = require('./fixtures'); + +test('description markdown renders as formatted HTML', async ({ page }) => { + await page.goto('/ticket/100000001'); + const view = page.locator('#ticketDescriptionView'); + await expect(view.locator('h2', { hasText: 'Goal' })).toBeVisible(); + await expect(view.locator('strong', { hasText: 'PBS datastore' })).toBeVisible(); + await expect(view.locator('table tr')).toHaveCount(4); + await expect(view.locator('pre code')).toContainText('proxmox-backup-manager datastore create'); + await expect(view.locator('a[href="https://wiki.example.invalid/backups"]')).toBeVisible(); + await expect(view.locator('a[href$="/ticket/100000002"]')).toBeVisible(); + await expect(view).not.toContainText('## Goal'); +}); + +test('HTML and javascript: links in a description stay inert', async ({ page }) => { + await page.goto('/ticket/100000001'); + const view = page.locator('#ticketDescriptionView'); + await expect(view).toContainText(""); + await expect(view.locator('script')).toHaveCount(0); + await expect(view.locator('a[href^="javascript:"]')).toHaveCount(0); + expect(await page.evaluate(() => window.__seedXss)).toBeUndefined(); +}); + +test('underscores inside identifiers stay literal', async ({ page }) => { + await page.goto('/ticket/100000002'); + const view = page.locator('#ticketDescriptionView'); + await expect(view).toContainText('node_network_up is 0'); + await expect(view.locator('em', { hasText: 'Opened automatically by Gandalf.' })).toBeVisible(); +}); + +test('plain text keeps its paragraphs', async ({ page }) => { + await page.goto('/ticket/100000003'); + const view = page.locator('#ticketDescriptionView'); + await expect(view).toContainText('Tried a new roll, same result.'); + await expect(view).toContainText('Not urgent, the spare printer works.'); +}); + +test('edit mode shows the raw markdown source', async ({ page }) => { + await page.goto('/ticket/100000001'); + await page.click('#editButton'); + const textarea = page.locator('#ticketDescription'); + await expect(textarea).toBeVisible(); + await expect(textarea).toHaveValue(/^## Goal\n/); +}); + +test('markdown comments render', async ({ page }) => { + await page.goto('/ticket/100000001'); + await page.click('#comments-tab-btn'); + const comment = page.locator('.comment-text').first(); + await expect(comment.locator('strong', { hasText: 'Next:' })).toBeVisible(); + await expect(comment.locator('code', { hasText: 'snake_case_job' })).toBeVisible(); + await expect(comment).toContainText('verify_jobs'); +}); diff --git a/tests/ui/package-lock.json b/tests/ui/package-lock.json new file mode 100644 index 0000000..9763f19 --- /dev/null +++ b/tests/ui/package-lock.json @@ -0,0 +1,58 @@ +{ + "name": "tinker-tickets-ui-tests", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tinker-tickets-ui-tests", + "devDependencies": { + "@playwright/test": "1.64.1" + } + }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/tests/ui/package.json b/tests/ui/package.json new file mode 100644 index 0000000..7b62ab0 --- /dev/null +++ b/tests/ui/package.json @@ -0,0 +1,11 @@ +{ + "name": "tinker-tickets-ui-tests", + "private": true, + "description": "Playwright UI tests and before/after screenshots for Tinker Tickets (CI only).", + "scripts": { + "test": "playwright test" + }, + "devDependencies": { + "@playwright/test": "1.64.1" + } +} diff --git a/tests/ui/pages.ui.js b/tests/ui/pages.ui.js new file mode 100644 index 0000000..64f5784 --- /dev/null +++ b/tests/ui/pages.ui.js @@ -0,0 +1,42 @@ +'use strict'; + +// Every main page loads for a signed-in admin with no page errors, console +// errors or failed requests (checked by the fixture). +const { test, expect } = require('./fixtures'); + +const PAGES = [ + ['/', 'dashboard'], + ['/ticket/100000001', 'markdown ticket'], + ['/ticket/100000002', 'alert ticket'], + ['/ticket/100000003', 'plain-text ticket'], + ['/ticket/create', 'create ticket'], + ['/admin/templates', 'templates admin'], + ['/admin/workflow', 'workflow admin'], + ['/admin/audit-log', 'audit log'], + ['/admin/api-keys', 'API keys'], +]; + +for (const [path, name] of PAGES) { + test(`${name} (${path}) loads cleanly`, async ({ page }) => { + const res = await page.goto(path); + expect(res.status()).toBe(200); + await page.waitForLoadState('networkidle'); + await expect(page.locator('body')).not.toContainText('Fatal error'); + await expect(page.locator('body')).not.toContainText('Warning:'); + }); +} + +test('the dashboard lists the seeded tickets', async ({ page }) => { + await page.goto('/'); + await expect(page.getByRole('heading', { level: 1 })).toContainText('TICKETS'); + for (const id of ['100000001', '100000002', '100000003']) { + await expect(page.locator(`a[href*="/ticket/${id}"]`).first()).toBeVisible(); + } +}); + +test('requests without the SSO headers are not let in', async ({ baseURL }) => { + // Plain fetch: Playwright's own request contexts pick up the fixture's SSO + // headers. + const res = await fetch(new URL('/', baseURL), { redirect: 'manual' }); + expect(res.status, 'anonymous request to the dashboard').toBe(401); +}); diff --git a/tests/ui/playwright.config.js b/tests/ui/playwright.config.js new file mode 100644 index 0000000..05fe463 --- /dev/null +++ b/tests/ui/playwright.config.js @@ -0,0 +1,29 @@ +'use strict'; + +// Playwright UI tests. They expect a running instance with the seed data: +// tests/ui/stack.sh starts one (see the README's "UI tests" section). +const { defineConfig, devices } = require('@playwright/test'); + +const CI = !!process.env.CI; + +module.exports = defineConfig({ + testDir: '.', + testMatch: '**/*.ui.js', + // One shared database: run serially so tests can't race each other. + workers: 1, + fullyParallel: false, + forbidOnly: CI, + retries: CI ? 1 : 0, + timeout: 30_000, + expect: { timeout: 10_000 }, + reporter: CI ? [['list'], ['html', { open: 'never' }]] : 'list', + use: { + baseURL: process.env.TINKER_UI_URL || 'http://127.0.0.1:8400', + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + }, + projects: [ + { name: 'desktop', use: { ...devices['Desktop Chrome'], viewport: { width: 1280, height: 900 } }, testIgnore: '**/responsive.ui.js' }, + { name: 'mobile', use: { ...devices['Pixel 7'] }, testMatch: '**/responsive.ui.js' }, + ], +}); diff --git a/tests/ui/responsive.ui.js b/tests/ui/responsive.ui.js new file mode 100644 index 0000000..3986d29 --- /dev/null +++ b/tests/ui/responsive.ui.js @@ -0,0 +1,26 @@ +'use strict'; + +// Runs in the `mobile` project (Pixel 7): pages must fit the phone width, +// with no horizontal page scroll. Wide content (tables, code) scrolls inside +// its own box instead. +const { test, expect } = require('./fixtures'); + +const PATHS = ['/', '/ticket/100000001', '/ticket/100000002', '/ticket/create']; + +for (const path of PATHS) { + test(`${path} fits a phone screen`, async ({ page }) => { + await page.goto(path); + await page.waitForLoadState('networkidle'); + const overflow = await page.evaluate(() => { + const doc = document.documentElement; + const wide = [...document.querySelectorAll('body *')] + .filter(el => el.getBoundingClientRect().right > doc.clientWidth + 1 && el.getClientRects().length) + .slice(0, 5) + .map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + + (typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\s+/).join('.') : '')); + return { scrollWidth: doc.scrollWidth, clientWidth: doc.clientWidth, wide }; + }); + expect(overflow.scrollWidth, `wider than the screen: ${overflow.wide.join(', ')}`) + .toBeLessThanOrEqual(overflow.clientWidth); + }); +} diff --git a/tests/ui/router.php b/tests/ui/router.php new file mode 100644 index 0000000..1744672 --- /dev/null +++ b/tests/ui/router.php @@ -0,0 +1,23 @@ + before= after= +// +// Both instances run tests/ui/stack.sh, so they hold the same seed data and +// differences come from the code. Captures each page on desktop (dark and +// light theme) and on a phone, then composes one side-by-side image per page +// and view (-.png), rendered in the browser so no image tooling is +// needed. Views that look identical are listed in unchanged.txt. +const fs = require('fs'); +const path = require('path'); +const { chromium, devices } = require('@playwright/test'); +const { SSO, isLocal } = require('./fixtures'); + +// The day after the seed's timestamps, so "1d ago" reads the same on both sides. +const NOW = new Date('2026-11-21T09:00:00Z'); + +const PAGES = { + dashboard: '/', + 'ticket-markdown': '/ticket/100000001', + 'ticket-alert': '/ticket/100000002', + 'ticket-plain': '/ticket/100000003', + 'ticket-create': '/ticket/create', +}; +const VIEWS = { + dark: { theme: 'dark', opts: { viewport: { width: 1280, height: 900 } } }, + light: { theme: 'light', opts: { viewport: { width: 1280, height: 900 } } }, + phone: { theme: 'dark', opts: { ...devices['Pixel 7'] } }, +}; + +async function capture(browser, label, base, dir) { + const shots = {}; + for (const [view, { theme, opts }] of Object.entries(VIEWS)) { + const ctx = await browser.newContext({ ...opts, colorScheme: theme, extraHTTPHeaders: SSO, reducedMotion: 'reduce', timezoneId: 'UTC' }); + await ctx.route(u => !isLocal(u.href), r => r.abort()); + await ctx.addInitScript(t => { + try { localStorage.setItem('lt_theme', t); } catch (e) { /* ignore */ } + const get = Storage.prototype.getItem; + Storage.prototype.getItem = function (k) { + return String(k).startsWith('lt_booted_') ? '1' : get.call(this, k); + }; + }, theme); + const page = await ctx.newPage(); + await page.clock.setFixedTime(NOW); + for (const [name, p] of Object.entries(PAGES)) { + await page.goto(base + p); + await page.waitForLoadState('networkidle'); + // Every image settled: loaded, or (avatars without an lldap photo) + // swapped for the initials fallback. + await page.waitForFunction(() => [...document.images].every(i => i.complete + && (i.naturalWidth > 0 || !i.closest('.lt-avatar') || i.classList.contains('lt-avatar-img-err'))), null, { timeout: 5000 }) + .catch(() => {}); + await page.evaluate(t => document.documentElement.setAttribute('data-theme', t), theme); + await page.waitForTimeout(500); + const key = `${name}-${view}`; + const file = path.join(dir, `${label}-${key}.png`); + await page.screenshot({ path: file, fullPage: true }); + shots[key] = file; + } + await ctx.close(); + } + return shots; +} + +async function compose(browser, name, before, after, out) { + const b64 = f => 'data:image/png;base64,' + fs.readFileSync(f).toString('base64'); + const html = `
+

BEFORE (base) ${name}

+

AFTER (this PR) ${name}

+
`; + const page = await browser.newPage({ viewport: { width: 1600, height: 800 } }); + await page.setContent(html); + await page.screenshot({ path: out, fullPage: true }); + await page.close(); +} + +(async () => { + const [outDir, ...targets] = process.argv.slice(2); + const urls = Object.fromEntries(targets.map(t => t.split('='))); + if (!outDir || !urls.before || !urls.after) { + console.error('usage: screenshots.js before= after='); + process.exit(2); + } + const raw = path.join(outDir, 'raw'); + fs.mkdirSync(raw, { recursive: true }); + + const browser = await chromium.launch(); + try { + const before = await capture(browser, 'before', urls.before, raw); + const after = await capture(browser, 'after', urls.after, raw); + const unchanged = []; + for (const name of Object.keys(after)) { + if (before[name] && fs.readFileSync(before[name]).equals(fs.readFileSync(after[name]))) { + unchanged.push(name); + continue; + } + await compose(browser, name, before[name], after[name], path.join(outDir, `${name}.png`)); + console.log(`changed: ${name}`); + } + fs.writeFileSync(path.join(outDir, 'unchanged.txt'), unchanged.join('\n') + '\n'); + console.log(`unchanged: ${unchanged.length ? unchanged.join(', ') : 'none'}`); + } finally { + await browser.close(); + } +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/tests/ui/seed.php b/tests/ui/seed.php new file mode 100644 index 0000000..01a9363 --- /dev/null +++ b/tests/ui/seed.php @@ -0,0 +1,115 @@ +set_charset('utf8mb4'); +// Fixed times, so before/after screenshots match (screenshots.js pins the +// browser clock to the day after). +$db->query("SET time_zone = '+00:00'"); +$created = '2026-11-20 09:00:00'; + +// A manual or MCP ticket written in markdown: everything #114 renders. +$markdown = <<<'MD' +## Goal +Replace the shared NAS backup target with the new **PBS datastore** on `storage-02`, so nightly jobs stop competing with Ceph recovery traffic. + +## Plan +- [x] Create datastore `pbs-main` (ZFS mirror, 2 x 8 TB) +- [x] Add the datastore to all six nodes +- [ ] Move the nightly jobs to the new target +- [ ] Remove the old NFS export + +## Sizing +| Dataset | Used | Growth / month | +|---|---|---| +| VM disks | 2.1 TB | 40 GB | +| LXC rootfs | 310 GB | 6 GB | +| Config backups | 2 GB | under 1 GB | + +## Commands +```bash +proxmox-backup-manager datastore create pbs-main /mnt/datastore/pbs-main +pvesm add pbs pbs-main --server 10.0.0.20 --datastore pbs-main +``` + +See the runbook at https://wiki.example.invalid/backups and the related ticket #100000002. + +Escaping check: and [a bad link](javascript:window.__seedXss=1) must stay inert. +MD; + +// A Gandalf-style alert: identifiers with underscores must stay literal. +$gandalf = <<<'MD' +## Network Interface Alert + +- **Host:** node-03 +- **Interface:** `enp5s0` +- **Detected:** 2026-11-20 06:09:05 UTC +- **Consecutive check failures:** 2 + +Interface enp5s0 on node-03 was up and is now reporting link-down via node_exporter (node_network_up is 0). node-03 itself is still reporting, so it may be reachable over its other interfaces. + +### What to check +1. Check the switch port: is it down on the switch side too? +2. Reseat or swap the cable or DAC; for an optic, check the module for a fault. +3. On node-03, check `ip link show enp5s0` and `dmesg` for NIC or driver errors. + +_Opened automatically by Gandalf._ +MD; + +// A plain-text ticket with no markdown at all. +$plain = "The label printer in the rack room jams on every second label.\n" + . "Tried a new roll, same result.\n\nNot urgent, the spare printer works."; + +$tickets = [ + ['100000001', '[backup][manual][storage] Move nightly backups to the new PBS datastore', $markdown, 'Task', 3], + ['100000002', '[node-03][auto][network] Interface enp5s0 link-down', $gandalf, 'Issue', 2], + ['100000003', 'Label printer jams on every second label', $plain, 'Issue', 4], +]; +$comment = "Datastore is up. **Next:** move the jobs.\n\n" + . "- verify `snake_case_job` still runs\n- check the verify_jobs list after the move"; + +$ids = implode(',', array_map(fn($t) => "'" . $t[0] . "'", $tickets)); +$db->query("DELETE FROM ticket_comments WHERE ticket_id IN ($ids)"); +$db->query("DELETE FROM tickets WHERE ticket_id IN ($ids)"); + +$insert = $db->prepare( + "INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, hash, created_at, updated_at) + VALUES (?, ?, ?, 'Open', ?, 'Hardware', ?, ?, ?, ?)" +); +foreach ($tickets as [$id, $title, $description, $type, $priority]) { + $hash = hash('sha256', 'tinker-ui-seed-' . $id); + $insert->bind_param('sssissss', $id, $title, $description, $priority, $type, $hash, $created, $created); + $insert->execute(); +} + +$addComment = $db->prepare( + "INSERT INTO ticket_comments (ticket_id, user_name, comment_text, markdown_enabled, created_at) + VALUES ('100000001', 'Seed User', ?, 1, ?)" +); +$addComment->bind_param('ss', $comment, $created); +$addComment->execute(); + +echo 'seeded ' . count($tickets) . " tickets into $dbName\n"; diff --git a/tests/ui/setup.sh b/tests/ui/setup.sh new file mode 100755 index 0000000..67a2700 --- /dev/null +++ b/tests/ui/setup.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# CI only: installs PHP and a throwaway MariaDB inside the Playwright job +# container (Ubuntu, as root) and starts MariaDB on 127.0.0.1:3306. Run once per +# job, before tests/ui/stack.sh. MariaDB runs in the job container rather than +# as a service container because the Gitea runner puts jobs on Docker's default +# bridge network, where services can't be reached by name (same as Pulse). +set -euo pipefail + +# The Playwright image points apt at Azure's Ubuntu mirror, which our runner +# can't always reach; use the main Ubuntu mirror instead, and retry. +for f in /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do + [ -f "$f" ] && sed -i 's#http://azure\.archive\.ubuntu\.com/#http://archive.ubuntu.com/#g' "$f" +done +PKGS="mariadb-server php-cli php-mysql php-mbstring php-curl php-ldap php-xml" +for attempt in 1 2 3; do + # shellcheck disable=SC2086 + if apt-get -o Acquire::Retries=3 update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y -qq --no-install-recommends $PKGS >/dev/null; then + break + fi + [ "$attempt" = 3 ] && { echo "::error::could not install $PKGS"; exit 1; } + echo "apt failed (attempt $attempt); retrying in 10s" + sleep 10 +done + +mkdir -p /run/mysqld && chown mysql:mysql /run/mysqld +if ! mariadb-admin ping --silent 2>/dev/null; then + (mariadbd --user=mysql --bind-address=127.0.0.1 --port=3306 >/tmp/mariadb.log 2>&1 &) +fi +for _ in $(seq 1 30); do mariadb-admin ping --silent 2>/dev/null && break; sleep 1; done +mariadb -e "CREATE USER IF NOT EXISTS 'tinker_ui'@'127.0.0.1' IDENTIFIED BY 'ci-only';" +echo "$(php --version | head -1), $(mariadb --version)" diff --git a/tests/ui/stack.sh b/tests/ui/stack.sh new file mode 100755 index 0000000..f87c406 --- /dev/null +++ b/tests/ui/stack.sh @@ -0,0 +1,72 @@ +#!/bin/bash +# Starts one Tinker Tickets instance for the UI tests on a fresh database: +# +# tests/ui/stack.sh +# +# Creates the database, writes the checkout's .env (throwaway values only), +# applies the checkout's migrations, loads the synthetic seed +# data and serves the checkout with PHP's built-in server. The seed and router +# always come from this script's directory, so the same data goes into the +# base branch's checkout for before/after screenshots. +# +# Needs a MariaDB on 127.0.0.1 with a 'tinker_ui' user (tests/ui/setup.sh in +# CI) and root access to it over the local socket. Logs go to +# /.ui-stack/server.log. +set -euo pipefail +CHECKOUT=$(cd "${1:?checkout dir}" && pwd) +PORT=${2:?port} +DB=${3:?database name} +HERE=$(cd "$(dirname "$0")" && pwd) + +case "$DB" in + tinker_ui*) ;; + *) echo "refusing: database name must start with tinker_ui" >&2; exit 2 ;; +esac + +mariadb -e "DROP DATABASE IF EXISTS \`$DB\`; CREATE DATABASE \`$DB\`; + GRANT ALL ON \`$DB\`.* TO 'tinker_ui'@'127.0.0.1';" + +if [ -e "$CHECKOUT/.env" ] && ! grep -q "^; tinker-ui-stack" "$CHECKOUT/.env"; then + echo "refusing: $CHECKOUT/.env exists and was not written by this script" >&2 + exit 2 +fi +cat > "$CHECKOUT/.env" < "$CHECKOUT/.ui-stack/server.log" 2>&1 &) + +for _ in $(seq 1 30); do + code=$(curl -s -o /dev/null -w '%{http_code}' -H 'Remote-User: ci.tester' -H 'Remote-Name: CI Tester' \ + -H 'Remote-Email: ci@example.invalid' -H 'Remote-Groups: admin' "http://127.0.0.1:$PORT/" || true) + if [ "$code" = 200 ]; then + echo "Tinker Tickets ($CHECKOUT) on http://127.0.0.1:$PORT, database $DB" + exit 0 + fi + sleep 1 +done +echo "::error::Tinker Tickets did not answer on port $PORT (last HTTP ${code:-none})" +tail -n 50 "$CHECKOUT/.ui-stack/server.log" || true +exit 1 diff --git a/views/layout_footer.php b/views/layout_footer.php index 8992dd6..f9e9500 100644 --- a/views/layout_footer.php +++ b/views/layout_footer.php @@ -297,6 +297,11 @@ e.target.classList.add('lt-avatar-img-err'); } }, true); + // Images above this script (the header avatar) can fail before the + // listener exists; catch those too. + document.querySelectorAll('.lt-avatar img').forEach(function(img) { + if (img.complete && img.naturalWidth === 0) img.classList.add('lt-avatar-img-err'); + }); // Footer hint bar actions (keyboard help + settings — work on all pages) document.addEventListener('click', function(e) {