CI: one pipeline to the CI standard: PHP 8.4 lint, audits, scans, API and MCP tests (#136) #139

Open
jared wants to merge 3 commits from ci-standard into development
pull from: ci-standard
34 changed files with 2924 additions and 193 deletions

No files matched your search

+5
View File
@@ -99,3 +99,8 @@ RATE_LIMIT_API=60
; closed less than this many days ago reopens it; an older one opens a new
; ticket linked to the old one.
AUTO_REOPEN_WINDOW_DAYS=7
; 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
+334
View File
@@ -0,0 +1,334 @@
name: CI
# One pipeline (#136; the standard is wiki: Infrastructure/ci-standard, modelled
# on Pulse and Thor): lint, dependency audit, scans, API and MCP tests against
# MariaDB, and Playwright UI tests must all pass before beta or production
# deploys. Actions are pinned to full commit SHAs (version in the trailing comment).
# Pushes build only the two deploy branches (development -> beta, main ->
# production); other branches build through their pull request, so nothing
# runs twice. The weekly run catches new advisories and re-scans the history.
on:
push:
branches: [main, development]
pull_request:
branches: ["**"]
schedule:
- cron: '0 6 * * 1'
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/development' }}
# Job images: node:22-trixie is Debian 13, whose PHP 8.4 packages are the ones
# production runs (CT 132), and it has the Node that actions/checkout needs.
# No setup-node/setup-php: the runner shares one tool cache between concurrent
# jobs, and parallel setup actions overwrite each other's installs.
jobs:
lint:
name: Lint (PHP 8.4, phpcs, eslint)
runs-on: ubuntu-latest
timeout-minutes: 15
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
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 8.4
run: WITH_DB=0 tests/ci/setup.sh
- name: Every PHP file parses on PHP 8.4 (production's version)
run: |
git config --global --add safe.directory "$PWD"
git ls-files -z '*.php' | xargs -0 -n1 -P4 php -l -d display_errors=stderr > /dev/null
- name: Runtime requirements (version and extensions)
run: php scripts/check_requirements.php
- name: phpcs (pinned, verified checksum)
run: |
curl -fsSLo /tmp/phpcs.phar https://github.com/PHPCSStandards/PHP_CodeSniffer/releases/download/4.0.4/phpcs.phar
echo "4b010cd21d8bc8a17e2504792e3c77ef8259126f24caf7eafe7eddef1fa871e9 /tmp/phpcs.phar" | sha256sum -c
php /tmp/phpcs.phar --standard=.phpcs.xml .
- name: eslint (lockfile only; warnings may only go down)
working-directory: tests/lint
run: |
npm ci --no-audit --no-fund
npm run lint
audit:
name: Security (composer and npm audit)
runs-on: ubuntu-latest
timeout-minutes: 15
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
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 8.4 and Composer (pinned, verified checksum)
run: |
WITH_DB=0 EXTRA_PKGS="unzip" tests/ci/setup.sh
curl -fsSLo /usr/local/bin/composer https://getcomposer.org/download/2.11.3/composer.phar
echo "04f8b003da4e3a2459056591fbfebd02b4dc3e5adeb158616b90cf55a65113ec /usr/local/bin/composer" | sha256sum -c
chmod +x /usr/local/bin/composer
- name: composer.json and composer.lock agree
run: COMPOSER_ALLOW_SUPERUSER=1 composer validate --no-check-publish --strict
- name: PHP dependencies (composer audit; ignores are listed with reasons in composer.json)
run: COMPOSER_ALLOW_SUPERUSER=1 composer audit --locked --no-interaction --abandoned=fail
- name: npm dependencies of the test tooling (audit, signatures)
run: |
for dir in tests/ui tests/lint; do
echo "== $dir"
(cd "$dir" && npm ci --ignore-scripts --no-audit --no-fund && npm audit signatures)
# Retry only when the registry itself fails; a real advisory fails at once.
for attempt in 1 2 3; do
if out=$(cd "$dir" && npm audit --audit-level=high 2>&1); then echo "$out"; break; fi
echo "$out"
echo "$out" | grep -q "audit endpoint returned an error" || exit 1
[ "$attempt" = 3 ] && exit 1
echo "npm registry error (attempt $attempt); retrying in 20s"
sleep 20
done
done
scan:
name: Scan (secrets, workflows, shell, patterns)
runs-on: ubuntu-latest
timeout-minutes: 20
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
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 # gitleaks scans the whole history, not just this commit
- name: Install scanners (pinned versions, verified checksums)
run: |
cd /tmp
curl -fsSLo gitleaks.tgz https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz
echo "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb gitleaks.tgz" | sha256sum -c
curl -fsSLo actionlint.tgz https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz
echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 actionlint.tgz" | sha256sum -c
tar -xzf gitleaks.tgz -C /usr/local/bin gitleaks
tar -xzf actionlint.tgz -C /usr/local/bin actionlint
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends shellcheck python3-venv >/dev/null # venv: zizmor and semgrep
- name: Secrets in code and history (gitleaks; reviewed false positives in .gitleaks.toml)
run: |
git config --global --add safe.directory "$PWD"
gitleaks git --no-banner --redact --exit-code 1 .
- name: Workflow files (actionlint, with shellcheck on run scripts)
run: actionlint .gitea/workflows/*.yml
- name: Shell scripts (shellcheck)
run: git ls-files -z '*.sh' | xargs -0 shellcheck
- name: Workflow security (zizmor)
run: |
python3 -m venv /tmp/zizmor && /tmp/zizmor/bin/pip install -q zizmor==1.32.0
/tmp/zizmor/bin/zizmor --offline --format plain .gitea/workflows/*.yml
- name: Code patterns (semgrep)
# Rule packs come from the semgrep registry, so new rules can surface new
# findings: fix them, or suppress one line with `nosemgrep: <rule id>` and a reason.
# The three excluded PHP rules were reviewed when semgrep was added (security.yml).
run: |
python3 -m venv /tmp/semgrep && /tmp/semgrep/bin/pip install -q semgrep==1.184.0
/tmp/semgrep/bin/semgrep scan --metrics=off --error \
--config p/php --config p/owasp-top-ten --config p/javascript \
--config p/secrets --config p/security-audit \
--exclude-rule=php.lang.security.injection.echoed-request.echoed-request \
--exclude-rule=php.lang.security.injection.tainted-filename.tainted-filename \
--exclude-rule=php.lang.security.injection.tainted-callable.tainted-callable \
--exclude vendor --exclude node_modules
api:
name: API and MCP (PHP 8.4, MariaDB)
runs-on: ubuntu-latest
timeout-minutes: 20
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
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 8.4, MariaDB and Composer (pinned, verified checksum)
run: |
EXTRA_PKGS="unzip" tests/ci/setup.sh
curl -fsSLo /usr/local/bin/composer https://getcomposer.org/download/2.11.3/composer.phar
echo "04f8b003da4e3a2459056591fbfebd02b4dc3e5adeb158616b90cf55a65113ec /usr/local/bin/composer" | sha256sum -c
chmod +x /usr/local/bin/composer
- name: Composer dependencies, as the deploy installs them (MCP endpoint)
run: |
COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --no-interaction --no-progress \
--no-plugins --no-scripts --classmap-authoritative
- name: Start Tinker Tickets (port 8400, fresh database, migrations, seed data)
run: tests/ui/stack.sh . 8400 tinker_ui_api
- name: Fixtures (system user, API keys, MCP users)
run: php tests/api/fixtures.php /tmp/api-keys.json
- name: MCP write tools (comments, links)
run: php tests/api/mcp_test.php
- name: Bearer API contract (create, dedup, recurrence, lookup, links) under three workflow setups
run: python3 tests/api/test_api.py
- name: No PHP warnings while serving the tests
run: tests/ci/php-warnings.sh .ui-stack/server.log
- name: Server log
if: always()
run: tail -n 200 .ui-stack/server.log || true
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/ci/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: No PHP warnings while serving the tests
run: tests/ci/php-warnings.sh .ui-stack/server.log
- 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/ci/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
timeout-minutes: 10
needs: [lint, audit, scan, api, ui]
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/development')
# One deploy per site at a time; queue instead of cancelling one mid-way.
concurrency:
group: deploy-${{ github.ref_name }}
cancel-in-progress: false
permissions:
contents: write # deploy tag
steps:
- name: Trigger webhook
env:
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
GIT_REF: ${{ github.ref }}
run: |
if [ "$GIT_REF" = "refs/heads/main" ]; then
HOOK_ID="tinker-deploy"
else
HOOK_ID="tinker-beta-deploy"
fi
PAYLOAD="{\"ref\":\"${GIT_REF}\"}"
SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}')
curl -sf --connect-timeout 10 \
-X POST \
-H "Content-Type: application/json" \
-H "X-Gitea-Signature: ${SIG}" \
-d "$PAYLOAD" \
"http://10.10.10.45:9000/hooks/${HOOK_ID}"
- name: Tag deployed commit
if: github.ref == 'refs/heads/main'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUN_NUMBER: ${{ github.run_number }}
GIT_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
TAG="deploy-$(date -u +%Y.%m.%d)-${RUN_NUMBER}"
curl -sf -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${GIT_SHA}\",\"message\":\"Deployed to production\"}" \
"https://code.lotusguild.org/api/v1/repos/${REPO}/tags"
notify:
name: Notify
runs-on: ubuntu-latest
timeout-minutes: 5
needs: [lint, audit, scan, api, ui, deploy]
# Alert on any failure on a deploy branch or in the weekly run, and on every deploy.
if: >-
always() && (
(failure() && (github.event_name == 'push' || github.event_name == 'schedule')) ||
needs.deploy.result == 'success'
)
steps:
- name: Send Matrix alert
env:
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
REPO: ${{ github.repository }}
BRANCH: ${{ github.ref_name }}
SHA: ${{ github.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
RESULTS: "lint=${{ needs.lint.result }} audit=${{ needs.audit.result }} scan=${{ needs.scan.result }} api=${{ needs.api.result }} ui=${{ needs.ui.result }} deploy=${{ needs.deploy.result }}"
DEPLOYED: ${{ needs.deploy.result == 'success' }}
run: |
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
if [ "$DEPLOYED" = "true" ]; then
MSG="DEPLOYED: ${REPO} @ ${BRANCH} (${SHA:0:7})"
else
MSG="CI FAILED: ${REPO} @ ${BRANCH} [${RESULTS}]"
fi
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"${MSG}: ${RUN_URL}\"}"
-110
View File
@@ -1,110 +0,0 @@
name: Lint
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
jobs:
php-lint:
name: PHP (phpcs PSR-12)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- name: Install PHP and phpcs
run: |
apt-get update -qq
apt-get install -y -qq php-cli php-xml
curl -sL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar -o /usr/local/bin/phpcs
chmod +x /usr/local/bin/phpcs
- name: Run phpcs
run: phpcs --standard=.phpcs.xml .
js-lint:
name: JS (eslint)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- name: Install ESLint
run: npm install --save-dev eslint@8
- name: Run ESLint
run: npx eslint assets/js/
requirements:
name: PHP requirements (version + extensions)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- name: Install PHP with required extensions
run: |
apt-get update -qq
# Install the extensions declared in config/requirements.php so the
# check verifies they are actually installable + loadable, and so this
# build fails if a required extension can't be provided.
apt-get install -y -qq php-cli php-ldap php-mysql php-curl php-mbstring
- name: Verify runtime requirements
run: php scripts/check_requirements.php
deploy:
name: Deploy
runs-on: ubuntu-latest
needs: [php-lint, js-lint, requirements]
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/development')
permissions:
contents: write
steps:
- name: Trigger webhook
env:
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
GIT_REF: ${{ github.ref }}
run: |
if [ "$GIT_REF" = "refs/heads/main" ]; then
HOOK_ID="tinker-deploy"
else
HOOK_ID="tinker-beta-deploy"
fi
PAYLOAD="{\"ref\":\"${GIT_REF}\"}"
SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}')
curl -sf --connect-timeout 10 \
-X POST \
-H "Content-Type: application/json" \
-H "X-Gitea-Signature: ${SIG}" \
-d "$PAYLOAD" \
"http://10.10.10.45:9000/hooks/${HOOK_ID}"
- name: Tag deployed commit
if: github.ref == 'refs/heads/main'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
TAG="deploy-$(date -u +%Y.%m.%d)-${{ github.run_number }}"
curl -sf -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \
"https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags"
notify-failure:
name: Notify on failure
runs-on: ubuntu-latest
needs: [php-lint, js-lint, requirements]
if: failure() && github.event_name == 'push'
steps:
- name: Send Matrix alert
env:
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
REPO: ${{ github.repository }}
BRANCH: ${{ github.ref_name }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"CI FAILED: ${REPO} @ ${BRANCH} — ${RUN_URL}\"}"
-32
View File
@@ -1,32 +0,0 @@
name: Security
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
schedule:
- cron: '0 6 * * 1'
jobs:
semgrep:
name: PHP Security (semgrep)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- name: Install semgrep
run: |
apt-get update -qq
apt-get install -y -qq python3 python3-pip
# Debian's Python is externally managed (PEP 668); the runner is
# ephemeral so installing system-wide is fine here.
pip3 install --break-system-packages semgrep
- name: Run semgrep
run: |
semgrep --config=p/php --config=p/owasp-top-ten --error \
--exclude-rule=php.lang.security.injection.echoed-request.echoed-request \
--exclude-rule=php.lang.security.injection.tainted-filename.tainted-filename \
--exclude-rule=php.lang.security.injection.tainted-callable.tainted-callable \
.
+5
View File
@@ -9,3 +9,8 @@ uploads/*
!uploads/.htaccess
# Composer dependencies (used only by the MCP endpoint; installed at deploy time)
vendor/
.ui-stack/
ui-screenshots/
# Python bytecode (tests/api)
__pycache__/
+13
View File
@@ -0,0 +1,13 @@
# gitleaks configuration (CI: the scan job runs `gitleaks git` over the full history).
# Default rules, plus an allowlist for reviewed false positives only. Each entry
# says why it is safe; a real secret is rotated and purged, never allowlisted.
[extend]
useDefault = true
[[allowlists]]
description = "API key help page (views/admin/ApiKeysView.php): example curl commands use the literal placeholder YOUR_API_KEY"
condition = "AND"
regexTarget = "match"
regexes = ['''Bearer YOUR_API_KEY''']
paths = ['''^views/admin/ApiKeysView\.php$''']
+1
View File
@@ -7,6 +7,7 @@
<exclude-pattern>*/migrations/*</exclude-pattern>
<exclude-pattern>*/.gitea/*</exclude-pattern>
<exclude-pattern>*/vendor/*</exclude-pattern>
<exclude-pattern>*/node_modules/*</exclude-pattern>
<arg name="extensions" value="php"/>
<arg name="colors"/>
+42 -11
View File
@@ -1,7 +1,6 @@
# Tinker Tickets
[![Lint](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions/workflows/lint.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions?workflow=lint.yml)
[![Security](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions/workflows/security.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions?workflow=security.yml)
[![CI](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions/workflows/ci.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/tinker_tickets/actions?workflow=ci.yml)
A feature-rich PHP-based ticketing system designed for tracking and managing data center infrastructure issues with enterprise-grade workflow management and a retro terminal aesthetic.
@@ -198,7 +197,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
@@ -693,18 +692,50 @@ Key conventions and gotchas for working with this codebase:
## CI / CD
| Workflow | Purpose | Triggers |
|---|---|---|
| `lint.yml` (php-lint) | phpcs PSR-12 standard | Every push and PR |
| `lint.yml` (js-lint) | ESLint on `assets/js/` | Every push and PR |
| `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 |
| `notify-failure` job in `lint.yml` | Posts CI failure alert to Matrix via webhook | Push to any branch when lint fails |
One pipeline, `.gitea/workflows/ci.yml`, following the shared [CI standard](https://wiki.lotusguild.org/Infrastructure/ci-standard) (#136). It runs on pull requests, on pushes to `main` and `development` (the two deploy branches), and every Monday at 06:00 UTC, so new advisories and secrets in history surface without a push. Actions, job images and downloaded tools are pinned (commit SHAs, image digests, SHA-256 checksums).
Branch protection is enabled on `main` — both lint jobs must pass before any PR can merge.
| Job | Checks |
|---|---|
| **Lint** | `php -l` on every PHP file under PHP 8.4 (Debian 13's packages, as on CT 132); `scripts/check_requirements.php`; phpcs 4.0.4 with `.phpcs.xml`; eslint 8.57.1 from `tests/lint/` (lockfile) with `--max-warnings` at today's count, so warnings can only go down |
| **Security** | `composer validate --strict`; `composer audit --locked --abandoned=fail` (reviewed ignores are listed with their reason under `config.audit.ignore` in `composer.json`); `npm audit` (high) and `npm audit signatures` for the test tooling |
| **Scan** | gitleaks over the full history (false positives in `.gitleaks.toml`, each with its reason); actionlint; shellcheck on every `*.sh`; zizmor; semgrep (`p/php`, `p/owasp-top-ten`, `p/javascript`, `p/secrets`, `p/security-audit`) |
| **API and MCP** | A fresh MariaDB, all migrations, seed data and fixtures, then `tests/api/mcp_test.php` (MCP comment and link tools) and `tests/api/test_api.py` (the Bearer API contract for automated reporters: dedup by key and title, escalation, the reopen window under three Workflow Designer setups, recurrence chains, concurrent creates, lookup by `dedup_key`, the source filter, the link API). Fails on any PHP warning in the server log |
| **UI (playwright)** | `tests/ui/` against a seeded instance (desktop and Pixel 7); fails on page errors, console errors, failed requests or PHP warnings |
| **UI screenshots** | PRs that change `assets/` or `views/`: before/after screenshots of the base branch and the PR, uploaded as the `ui-screenshots` artifact |
| **Deploy** | Only after Lint, Security, Scan, API and UI pass: calls the deploy webhook on CT 132 (`tinker-deploy` for `main`, `tinker-beta-deploy` for `development`) and tags production deploys `deploy-YYYY.MM.DD-N`. Deploys queue, never cancel |
| **Notify** | Matrix alert on any failure on a deploy branch or in the weekly run, and on every deploy |
The required status checks of the `main` and `development` branch protection must name these jobs (e.g. `CI / Lint (PHP 8.4, phpcs, eslint) (pull_request)`).
Lint config: `.phpcs.xml` (PSR-12 with project-specific tweaks), `.eslintrc.json` (root, browser env).
### API and MCP tests
Run them against a stack started by `stack.sh` (below), with the server's temp dir pointed somewhere the test can clear the workflow cache:
```bash
TMPDIR=/tmp/tinker-api-tmp tests/ui/stack.sh /tmp/tinker-ui 8400 tinker_ui_api
cd /tmp/tinker-ui && composer install --no-dev
php tests/api/fixtures.php /tmp/api-keys.json # system user, API keys, MCP users
php tests/api/mcp_test.php
TINKER_CACHE_DIR=/tmp/tinker-api-tmp python3 tests/api/test_api.py
```
Both refuse to run unless the configured database name starts with `tinker_ui`.
### 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';" # tests/ci/setup.sh does this in CI
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 <out-dir> before=http://127.0.0.1:8401 after=http://127.0.0.1:8400`.
## License
Internal use only - LotusGuild Infrastructure
+5
View File
@@ -28,6 +28,11 @@
"optimize-autoloader": true,
"allow-plugins": {
"php-http/discovery": false
},
"audit": {
"ignore": {
"PKSA-s52d-n7sx-trsg": "GHSA-f4rf-6ghj-mhr6 (mcp/sdk 0.8.x, low): unbounded request bodies on the SDK's OAuthProxyMiddleware /token and ClientRegistrationMiddleware /register endpoints. mcp/server.php uses neither (tokens come from Authelia). Upgrade to 0.9+ is tinker_tickets#138; remove this entry with it."
}
}
}
}
Generated
+44 -36
View File
@@ -1064,7 +1064,8 @@
"issues": "https://github.com/php-fig/container/issues",
"source": "https://github.com/php-fig/container/tree/2.0.2"
},
"time": "2021-11-05T16:47:00+00:00"
"time": "2021-11-05T16:47:00+00:00",
"published-time": "2021-11-05T16:53:27+00:00"
},
{
"name": "psr/event-dispatcher",
@@ -1437,7 +1438,8 @@
"support": {
"source": "https://github.com/php-fig/log/tree/3.0.2"
},
"time": "2024-09-11T13:17:53+00:00"
"time": "2024-09-11T13:17:53+00:00",
"published-time": "2024-09-11T13:21:14+00:00"
},
{
"name": "psr/simple-cache",
@@ -1675,16 +1677,16 @@
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.7.1",
"version": "v3.8.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d"
"reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3",
"reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3",
"shasum": ""
},
"require": {
@@ -1697,7 +1699,7 @@
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.7-dev"
"dev-main": "3.8-dev"
}
},
"autoload": {
@@ -1722,7 +1724,7 @@
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1"
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1"
},
"funding": [
{
@@ -1742,20 +1744,21 @@
"type": "tidelift"
}
],
"time": "2026-06-05T06:23:12+00:00"
"time": "2026-09-16T14:15:10+00:00",
"published-time": "2026-11-04T11:25:34+00:00"
},
{
"name": "symfony/http-client",
"version": "v7.4.19",
"version": "v7.4.25",
"source": {
"type": "git",
"url": "https://github.com/symfony/http-client.git",
"reference": "3a523f38dc399337ec45b2ab9628e8c37ceb23c7"
"reference": "fe047cdc68aee54b315b2f142ab4c0e9c705cefc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/http-client/zipball/3a523f38dc399337ec45b2ab9628e8c37ceb23c7",
"reference": "3a523f38dc399337ec45b2ab9628e8c37ceb23c7",
"url": "https://api.github.com/repos/symfony/http-client/zipball/fe047cdc68aee54b315b2f142ab4c0e9c705cefc",
"reference": "fe047cdc68aee54b315b2f142ab4c0e9c705cefc",
"shasum": ""
},
"require": {
@@ -1788,6 +1791,7 @@
"symfony/amphp-http-client-meta": "^1.0|^2.0",
"symfony/cache": "^6.4|^7.0|^8.0",
"symfony/dependency-injection": "^6.4|^7.0|^8.0",
"symfony/http-foundation": "^6.4.50|^7.4.23|^8.1.11",
"symfony/http-kernel": "^6.4|^7.0|^8.0",
"symfony/messenger": "^6.4|^7.0|^8.0",
"symfony/process": "^6.4|^7.0|^8.0",
@@ -1823,7 +1827,7 @@
"http"
],
"support": {
"source": "https://github.com/symfony/http-client/tree/v7.4.19"
"source": "https://github.com/symfony/http-client/tree/v7.4.25"
},
"funding": [
{
@@ -1843,20 +1847,21 @@
"type": "tidelift"
}
],
"time": "2026-09-08T13:28:43+00:00"
"time": "2026-11-27T13:02:26+00:00",
"published-time": "2026-11-27T14:42:41+00:00"
},
{
"name": "symfony/http-client-contracts",
"version": "v3.7.3",
"version": "v3.8.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/http-client-contracts.git",
"reference": "35be0019e2c2c9fba80f9dc033290a5240f7b44f"
"reference": "f9f94260f787446c6fd430b2ae1969fe41ae1ba8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/35be0019e2c2c9fba80f9dc033290a5240f7b44f",
"reference": "35be0019e2c2c9fba80f9dc033290a5240f7b44f",
"url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/f9f94260f787446c6fd430b2ae1969fe41ae1ba8",
"reference": "f9f94260f787446c6fd430b2ae1969fe41ae1ba8",
"shasum": ""
},
"require": {
@@ -1869,7 +1874,7 @@
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.7-dev"
"dev-main": "3.8-dev"
}
},
"autoload": {
@@ -1905,7 +1910,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/http-client-contracts/tree/v3.7.3"
"source": "https://github.com/symfony/http-client-contracts/tree/v3.8.1"
},
"funding": [
{
@@ -1925,20 +1930,21 @@
"type": "tidelift"
}
],
"time": "2026-08-04T08:41:16+00:00"
"time": "2026-10-04T15:04:25+00:00",
"published-time": "2026-11-04T11:25:37+00:00"
},
{
"name": "symfony/polyfill-php83",
"version": "v1.41.0",
"version": "v1.43.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php83.git",
"reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6"
"reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/5ea99087fb99c273a9b9236ed4c31e78b16103c6",
"reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6",
"url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/80ccff923a8d61f73ebe9da0aa94e25232f004ce",
"reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce",
"shasum": ""
},
"require": {
@@ -1985,7 +1991,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php83/tree/v1.41.0"
"source": "https://github.com/symfony/polyfill-php83/tree/v1.43.0"
},
"funding": [
{
@@ -2005,7 +2011,8 @@
"type": "tidelift"
}
],
"time": "2026-07-01T12:47:55+00:00"
"time": "2026-09-25T15:50:05+00:00",
"published-time": "2026-09-30T10:23:43+00:00"
},
{
"name": "symfony/polyfill-uuid",
@@ -2092,16 +2099,16 @@
},
{
"name": "symfony/service-contracts",
"version": "v3.7.3",
"version": "v3.8.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/service-contracts.git",
"reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257"
"reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257",
"reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/052852a96fd5e5ebdb617dba22031e41a3300fb5",
"reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5",
"shasum": ""
},
"require": {
@@ -2119,7 +2126,7 @@
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.7-dev"
"dev-main": "3.8-dev"
}
},
"autoload": {
@@ -2155,7 +2162,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/service-contracts/tree/v3.7.3"
"source": "https://github.com/symfony/service-contracts/tree/v3.8.1"
},
"funding": [
{
@@ -2175,7 +2182,8 @@
"type": "tidelift"
}
],
"time": "2026-07-27T15:39:01+00:00"
"time": "2026-10-20T17:38:25+00:00",
"published-time": "2026-11-04T11:25:33+00:00"
},
{
"name": "symfony/uid",
@@ -2417,5 +2425,5 @@
"platform-overrides": {
"php": "8.2.0"
},
"plugin-api-version": "2.9.0"
"plugin-api-version": "2.11.0"
}
+2
View File
@@ -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
// Automated reporters (create_ticket_api.php): a report matching a ticket
// closed less than this many days ago reopens it; an older one gets a new
+19 -2
View File
@@ -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);
+5 -2
View File
@@ -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) {
+78
View File
@@ -0,0 +1,78 @@
<?php
/**
* Fixtures for tests/api/test_api.py: the "system" user that API writes run
* as, and four Bearer keys, written to a JSON file as {name: key}:
*
* thor, gandalf read_write, public tickets only (automated reporters)
* reader read, public tickets only
* allseeing read_write, sees every visibility level
*
* php tests/api/fixtures.php /tmp/api-keys.json
*
* CLI only, and only against a database whose name starts with tinker_ui (the
* .env tests/ui/stack.sh writes). Replaces every API key in that database.
*/
if (php_sapi_name() !== 'cli') {
http_response_code(403);
exit('CLI access only');
}
$root = dirname(__DIR__, 2);
require_once $root . '/config/config.php';
require_once $root . '/helpers/Database.php';
require_once $root . '/models/ApiKeyModel.php';
$out = $argv[1] ?? '';
if ($out === '') {
fwrite(STDERR, "usage: php tests/api/fixtures.php <keys.json>\n");
exit(2);
}
if (!str_starts_with((string)($GLOBALS['config']['DB_NAME'] ?? ''), 'tinker_ui')) {
fwrite(STDERR, "refusing: the configured database must start with tinker_ui\n");
exit(2);
}
$conn = Database::getConnection();
// Users: system (API writes), an admin, and two ordinary users for the MCP
// permission checks (tests/api/mcp_test.php).
foreach ([['system', 'System', 1], ['ci.tester', 'CI Tester', 1], ['alice', 'Alice', 0], ['bob', 'Bob', 0]] as [$name, $display, $admin]) {
$stmt = $conn->prepare(
"INSERT INTO users (username, display_name, email, is_admin) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE is_admin = VALUES(is_admin)"
);
$email = $name . '@example.invalid';
$stmt->bind_param('sssi', $name, $display, $email, $admin);
$stmt->execute();
}
$uid = fn(string $name): int => (int)$conn->query(
"SELECT user_id FROM users WHERE username = '" . $conn->real_escape_string($name) . "'"
)->fetch_row()[0];
$creator = $uid('system');
// A confidential ticket only ci.tester (its creator, an admin) can see, and a
// system comment (no user_id) like the ones automated reporters leave.
$admin = $uid('ci.tester');
$conn->query("DELETE FROM ticket_comments WHERE ticket_id = '100000009'");
$conn->query("DELETE FROM tickets WHERE ticket_id = '100000009'");
$conn->query(
"INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, created_by, visibility)
VALUES ('100000009', '[test-node-09][manual][security] Confidential fixture', 'fixture', 'Open', 3,
'Security', 'Task', $admin, 'confidential')"
);
$conn->query(
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled)
VALUES ('100000001', NULL, 'hwmonDaemon', 'System comment fixture', 0)"
);
$conn->query("DELETE FROM api_keys");
$model = new ApiKeyModel($conn);
$keys = [];
foreach ([['thor', 'read_write', false], ['gandalf', 'read_write', false], ['reader', 'read', false], ['allseeing', 'read_write', true]] as [$name, $scope, $seeAll]) {
$keys[$name] = $model->createKey($name, $creator, null, $scope, $seeAll)['api_key'];
}
file_put_contents($out, json_encode($keys));
chmod($out, 0600);
echo 'API keys: ' . implode(', ', array_keys($keys)) . " -> $out\n";
+178
View File
@@ -0,0 +1,178 @@
<?php
/**
* MCP write tools against a real database: edit_comment / delete_comment
* (permissions, hidden tickets, nested replies, audit) and link_tickets /
* unlink_tickets (normalisation, duplicates, hidden and missing tickets).
* Calls the tool classes directly as a signed-in user; the OAuth layer in
* front of them is not exercised here.
*
* tests/ui/stack.sh . 8400 tinker_ui_api # database + seed tickets 100000001-3
* php tests/api/fixtures.php /tmp/api-keys.json
* php tests/api/mcp_test.php
*
* CLI only, and only against a database whose name starts with tinker_ui.
* Needs vendor/ (composer install).
*/
if (php_sapi_name() !== 'cli') {
http_response_code(403);
exit('CLI access only');
}
$root = dirname(__DIR__, 2);
require $root . '/config/config.php';
require $root . '/vendor/autoload.php';
foreach (
[
'helpers/Database.php', 'helpers/UrlHelper.php', 'models/UserModel.php', 'models/TicketModel.php',
'models/CommentModel.php', 'models/StatsModel.php', 'services/CommentService.php',
'services/DependencyService.php', 'mcp/src/Auth/McpIdentity.php', 'mcp/src/Tools/TicketWriteTools.php',
'mcp/src/ToolCatalog.php',
] as $file
) {
require_once "$root/$file";
}
use TinkerTickets\Mcp\Auth\McpIdentity;
use TinkerTickets\Mcp\Tools\TicketWriteTools;
use TinkerTickets\Mcp\ToolCatalog;
if (!str_starts_with((string)($GLOBALS['config']['DB_NAME'] ?? ''), 'tinker_ui')) {
fwrite(STDERR, "refusing: the configured database must start with tinker_ui\n");
exit(2);
}
$conn = Database::getConnection();
$users = new UserModel($conn);
$as = function (string $username) use ($users): void {
McpIdentity::set($users->getUserByUsername($username), ['tickets:write']);
};
$tools = new TicketWriteTools($conn);
$pass = 0;
$fail = 0;
$check = function (string $name, bool $ok, $detail = '') use (&$pass, &$fail): void {
$ok ? $pass++ : $fail++;
echo ($ok ? 'PASS ' : 'FAIL ') . $name . ($ok ? '' : ' ' . json_encode($detail)) . "\n";
};
$err = function (callable $fn): ?string {
try {
$fn();
return null;
} catch (\Mcp\Exception\ToolCallException $e) {
return $e->getMessage();
}
};
$row = fn(int $id) => $conn->query(
"SELECT comment_text, markdown_enabled FROM ticket_comments WHERE comment_id = $id"
)->fetch_assoc();
$audit = fn(string $action, int $id) => $conn->query(
"SELECT details FROM audit_log WHERE action_type = '$action' AND entity_type = 'comment'
AND entity_id = '$id' ORDER BY audit_id DESC LIMIT 1"
)->fetch_assoc();
echo "== comments\n";
$check('edit_comment is a write tool', ToolCatalog::isWriteTool('edit_comment'));
$check('delete_comment is a write tool', ToolCatalog::isWriteTool('delete_comment'));
// Edit own comment
$as('alice');
$a = $tools->addComment('100000001', 'first draft', true)['comment_id'];
$r = $tools->editComment($a, " **final** text ", false);
$check('alice edits her comment', $r === ['comment_id' => $a, 'ticket_id' => '100000001', 'edited' => true], $r);
$check(
'text trimmed and stored, markdown off',
$row($a) === ['comment_text' => '**final** text', 'markdown_enabled' => '0'],
$row($a)
);
$check('edit is audit-logged', str_contains($audit('update', $a)['details'] ?? '', '100000001'), $audit('update', $a));
$e = $err(fn() => $tools->editComment($a, ' '));
$check('empty text rejected', $e === 'Comment text cannot be empty', $e);
$e = $err(fn() => $tools->editComment(999999, 'x'));
$check('missing comment: not found', $e === 'Comment 999999 not found', $e);
// Someone else's comment
$as('bob');
$e = $err(fn() => $tools->editComment($a, 'hijack'));
$check('bob cannot edit alice\'s comment', $e === 'You do not have permission to edit this comment', $e);
$e = $err(fn() => $tools->deleteComment($a));
$check('bob cannot delete alice\'s comment', $e === 'You do not have permission to delete this comment', $e);
$check('alice\'s text unchanged', $row($a)['comment_text'] === '**final** text', $row($a));
// A comment on a ticket alice can't see reads as not found
$as('ci.tester');
$c = $tools->addComment('100000009', 'confidential note')['comment_id'];
$as('alice');
$e = $err(fn() => $tools->editComment($c, 'peek'));
$check('hidden ticket: edit says not found', $e === "Comment $c not found", $e);
$e = $err(fn() => $tools->deleteComment($c));
$check('hidden ticket: delete says not found', $e === "Comment $c not found", $e);
$check('hidden comment untouched', $row($c)['comment_text'] === 'confidential note', $row($c));
// An admin can edit anyone's comment, including a system comment with no user_id
$as('ci.tester');
$sys = (int)$conn->query("SELECT comment_id FROM ticket_comments WHERE user_id IS NULL LIMIT 1")->fetch_row()[0];
$r = $tools->editComment($sys, 'edited by admin');
$check('admin edits a system comment', $r['edited'] === true && $row($sys)['comment_text'] === 'edited by admin', $r);
$as('alice');
$e = $err(fn() => $tools->editComment($sys, 'x'));
$check('alice cannot edit a system comment', $e === 'You do not have permission to edit this comment', $e);
// Delete with nested replies
$as('bob');
$r1 = $tools->addComment('100000001', 'reply 1', true, $a)['comment_id'];
$as('alice');
$r2 = $tools->addComment('100000001', 'reply 2', true, $r1)['comment_id'];
$r = $tools->deleteComment($a);
$check(
'alice deletes her comment, 2 replies go with it',
$r === ['comment_id' => $a, 'ticket_id' => '100000001', 'deleted' => true, 'replies_removed' => 2],
$r
);
$check('comment and replies gone', $row($a) === null && $row($r1) === null && $row($r2) === null);
$check(
'delete audit has replies_removed',
str_contains($audit('delete', $a)['details'] ?? '', '"replies_removed":2'),
$audit('delete', $a)
);
$e = $err(fn() => $tools->deleteComment($a));
$check('deleting again: not found', $e === "Comment $a not found", $e);
$as('ci.tester');
$tools->deleteComment($c);
echo "== links\n";
$conn->query(
"DELETE FROM ticket_dependencies WHERE ticket_id IN ('100000001','100000002','100000003')
OR depends_on_id IN ('100000001','100000002','100000003')"
);
$as('alice');
$r = $tools->linkTickets('100000001', 'Blocks', ' 100000002 ');
$check(
'link (relation case and id spaces normalised)',
$r === ['ticket_id' => '100000001', 'relation' => 'blocks', 'other_ticket_id' => '100000002'],
$r
);
$e = $err(fn() => $tools->linkTickets('100000001', 'blocks', '100000002'));
$check('duplicate link refused', $e !== null, $e);
$e = $err(fn() => $tools->linkTickets('100000002', 'blocked_by', '100000001'));
$check('inverse of an existing link refused', $e !== null, $e);
$e = $err(fn() => $tools->linkTickets('100000001', 'causes', '100000002'));
$check('bad relation message', $e === 'relation must be one of: blocks, blocked_by, relates_to, duplicates', $e);
$e = $err(fn() => $tools->linkTickets('100000001', 'relates_to', '100000001'));
$check('self link message', $e === 'A ticket cannot be linked to itself', $e);
$e = $err(fn() => $tools->linkTickets('abc', 'relates_to', '100000001'));
$check('non-digit id: not found', $e === 'Ticket abc not found', $e);
$e = $err(fn() => $tools->linkTickets('100000001', 'relates_to', '100000009'));
$check('hidden target: not found', $e === 'Ticket 100000009 not found', $e);
$e = $err(fn() => $tools->linkTickets('999999998', 'relates_to', '100000001'));
$check('missing source: not found', $e === 'Ticket 999999998 not found', $e);
$r = $tools->unlinkTickets('100000002', 'blocked_by', '100000001');
$check('unlink stated from the other side', $r['removed'] === true, $r);
$e = $err(fn() => $tools->unlinkTickets('100000001', 'blocks', '100000002'));
$check('unlink again: no such link', $e === 'No blocks link between 100000001 and 100000002', $e);
$tools->linkTickets('100000003', 'duplicates', '100000001');
$r = $tools->unlinkTickets('100000003', 'duplicates', '100000001');
$check('duplicates link unlinks (one-way relation)', $r['removed'] === true, $r);
echo "\n$pass passed, $fail failed\n";
exit($fail || !$pass ? 1 : 0);
+260
View File
@@ -0,0 +1,260 @@
"""API contract tests for the Bearer endpoints automated reporters use
(gandalf, hwmonDaemon, thor): create_ticket_api.php dedup and recurrence
(#116, #123, #126), lookup by dedup_key, the source filter and the link API.
Runs against a Tinker instance started by tests/ui/stack.sh on a throwaway
database (name starting with tinker_ui) with keys from tests/api/fixtures.php:
tests/ui/stack.sh . 8400 tinker_ui_api
php tests/api/fixtures.php /tmp/api-keys.json
python3 tests/api/test_api.py
Environment (defaults in brackets):
TINKER_API_URL the instance [http://127.0.0.1:8400]
TINKER_API_DB its database, must start with tinker_ui [tinker_ui_api]
TINKER_API_KEYS the keys file fixtures.php wrote [/tmp/api-keys.json]
TINKER_CACHE_DIR the server's temp dir, for the workflow cache [/tmp]
The database is read and changed directly with the mariadb client over the
local socket (as root in CI). Every check runs under three Workflow Designer
setups for Closed -> Open: "prod" (admin + comment, as on production), "open"
(no requirements) and "none" (no such transition: noted, stays Closed).
Synthetic data only.
"""
import concurrent.futures
import hashlib
import json
import os
import pathlib
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
BASE = os.environ.get("TINKER_API_URL", "http://127.0.0.1:8400")
DB = os.environ.get("TINKER_API_DB", "tinker_ui_api")
KEYS = json.loads(pathlib.Path(os.environ.get("TINKER_API_KEYS", "/tmp/api-keys.json")).read_text())
CACHE = pathlib.Path(os.environ.get("TINKER_CACHE_DIR", "/tmp")) / "tinker_tickets_cache"
ROOT = pathlib.Path(__file__).resolve().parents[2]
if not DB.startswith("tinker_ui"):
sys.exit("refusing: TINKER_API_DB must start with tinker_ui")
results = []
def check(name, ok, detail=""):
results.append(ok)
print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" {detail}"), flush=True)
def call(method, path, body=None, key="thor"):
req = urllib.request.Request(BASE + path, method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Authorization": f"Bearer {KEYS[key]}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw)
except ValueError:
return e.code, raw.decode()
def sql(q):
out = subprocess.run(["mariadb", "-N", "-B", DB, "-e", q], capture_output=True, text=True, check=True).stdout
return [line.split("\t") for line in out.strip().splitlines()] if out.strip() else []
def one(q):
rows = sql(q)
return rows[0][0] if rows else None
def create(title, key="thor", **extra):
return call("POST", "/create_ticket_api.php", {"title": title, "description": "synthetic test", "priority": 3,
"category": "Hardware", "type": "Issue", **extra}, key)
def legacy_hash(title):
php = f"require {json.dumps(str(ROOT / 'helpers/TicketHash.php'))}; echo TicketHash::generate(['title' => {json.dumps(title)}]);"
return subprocess.run(["php", "-r", php], capture_output=True, text=True, check=True).stdout
def run_mode(MODE):
"""One pass of every check under one Closed -> Open workflow setup."""
print(f"== workflow: {MODE}", flush=True)
REOPEN = "recurrence_noted" if MODE == "none" else "reopened"
# The app caches workflow transitions for 10 minutes in its temp dir.
shutil.rmtree(CACHE, ignore_errors=True)
# clean slate for this test's data, and the workflow for this mode
sql("DELETE FROM status_transitions WHERE from_status='Closed'")
sql("INSERT INTO status_transitions (from_status,to_status,requires_comment,requires_admin,is_active) VALUES "
"('Closed','In Progress',0,1,1),('Closed','Open',%d,%d,%d)" % ((0, 0, 1) if MODE == "open" else (1, 1, 0 if MODE == "none" else 1)))
sql("DELETE FROM ticket_dependencies WHERE ticket_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test') "
"OR depends_on_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test')")
sql("DELETE FROM ticket_comments WHERE ticket_id IN (SELECT ticket_id FROM tickets WHERE description='synthetic test')")
sql("DELETE FROM tickets WHERE description='synthetic test' OR dedup_key LIKE 'cluster:ceph:%'")
KEY = "host:test-node-01:oom"
T = "[test-node-01][auto][thor][software] Out of memory: CT 999 [single-node][production][issue]"
# 1. keyed create
st, r = create(T, dedup_key=KEY)
A = r.get("ticket_id")
check("keyed create -> created", st == 200 and r.get("action") == "created", r)
row = sql(f"SELECT source, dedup_key, hash, recurrence_of FROM tickets WHERE ticket_id='{A}'")[0]
check("source, dedup_key and key hash stored",
row[:2] == ["thor", KEY] and row[2] == hashlib.sha256(("key:" + KEY).encode()).hexdigest() and row[3] == "NULL", row)
# 2. same key, different title, higher severity -> escalation on the same ticket, comment by thor
st, r = create("[test-node-01][auto][thor][software] Out of memory again, worse", dedup_key=KEY, priority=2)
check("same key, new title -> same ticket updated", r.get("ticket_id") == A and r.get("action") == "updated", r)
c = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{A}' ORDER BY comment_id DESC LIMIT 1")
check("escalation comment is by thor and names thor", c and c[0][0] == "thor" and c[0][1].startswith("**thor raised priority"), c)
# 3. invalid key
st, r = create(T, dedup_key="Host:Bad Key!")
check("invalid dedup_key -> 400", st == 400, (st, r))
# 4. legacy keyless create by gandalf
LT = "[test-node-02][auto][production][issue][network][single-node] Interface eth9 link-down"
st, r = create(LT, key="gandalf")
G = r.get("ticket_id")
row = sql(f"SELECT source, dedup_key, hash FROM tickets WHERE ticket_id='{G}'")[0]
check("keyless create keeps the legacy hash, source gandalf",
row[0] == "gandalf" and row[1] == "NULL" and row[2] == legacy_hash(LT), row)
# 5. closed 2 days ago -> reopened, comment by thor
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 2 DAY, created_at=NOW() - INTERVAL 25 DAY WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
check(f"closed 2 days ago -> {REOPEN}", r.get("ticket_id") == A and r.get("action") == REOPEN, r)
check("status after that report", one(f"SELECT status FROM tickets WHERE ticket_id='{A}'") == ("Closed" if MODE == "none" else "Open"))
c = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{A}' ORDER BY comment_id DESC LIMIT 1")
check("recurrence comment by thor", c and c[0][0] == "thor" and "thor detected this condition again" in c[0][1], c)
if MODE == "none":
check("note says the ticket stays Closed", c and c[0][1].startswith("**Issue recurred; the ticket stays Closed.**"), c)
n_before = one(f"SELECT COUNT(*) FROM ticket_comments WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
check("second report while Closed -> recurrence_noted again", r.get("action") == "recurrence_noted", r)
check("no second note in the same closed period", one(f"SELECT COUNT(*) FROM ticket_comments WHERE ticket_id='{A}'") == n_before)
check("both reports audited", one(f"SELECT COUNT(*) FROM audit_log WHERE entity_id='{A}' AND details LIKE '%recurrence detected but%'") == "2")
else:
check("reopen audit names the workflow skip",
"skips the Workflow Designer" in (one(f"SELECT details FROM audit_log WHERE entity_type='ticket' AND entity_id='{A}' ORDER BY audit_id DESC LIMIT 1") or ""))
# 6. closed 10 days ago -> new_recurrence
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 10 DAY WHERE ticket_id='{A}'")
st, r = create(T, dedup_key=KEY)
B = r.get("ticket_id")
check("closed 10 days ago -> new_recurrence", st == 200 and r.get("action") == "new_recurrence" and r.get("previous_ticket_id") == A and B != A, r)
check("old ticket gave up the hash, kept its key",
sql(f"SELECT hash, dedup_key, status FROM tickets WHERE ticket_id='{A}'")[0] == ["NULL", KEY, "Closed"])
check("new ticket holds hash, key, source, recurrence_of",
sql(f"SELECT dedup_key, source, recurrence_of, hash FROM tickets WHERE ticket_id='{B}'")[0]
== [KEY, "thor", A, hashlib.sha256(("key:" + KEY).encode()).hexdigest()])
check("relates_to link new -> old",
one(f"SELECT COUNT(*) FROM ticket_dependencies WHERE ticket_id='{B}' AND depends_on_id='{A}' AND dependency_type='relates_to'") == "1")
h = sql(f"SELECT user_name, comment_text FROM ticket_comments WHERE ticket_id='{B}'")
# chain: A created 25 days ago, auto-reopened today (step 5), B created today
# ("none": two noted reports instead of one reopen)
W, M = (3, 4) if MODE == "none" else (2, 3)
check(f"history comment: recurrence of A, {W} in 7 days, {M} in 30 days",
len(h) == 1 and h[0][0] == "thor" and h[0][1].startswith(f"**Recurrence of #{A}.**")
and f"Seen {W} times in the last 7 days and {M} times in the last 30 days" in h[0][1], h)
check("old ticket audit says where it continued",
f"continued in {B}" in (one(f"SELECT details FROM audit_log WHERE entity_type='ticket' AND entity_id='{A}' ORDER BY audit_id DESC LIMIT 1") or ""))
st, r = create(T, dedup_key=KEY)
check("next report dedups onto the new ticket", r.get("ticket_id") == B and r.get("action") in ("deduplicated", "updated"), r)
# 7. legacy (keyless) recurrence too
sql(f"UPDATE tickets SET status='Closed', closed_at=NOW() - INTERVAL 30 DAY WHERE ticket_id='{G}'")
st, r = create(LT, key="gandalf")
G2 = r.get("ticket_id")
check("keyless report after the window -> new_recurrence",
r.get("action") == "new_recurrence" and r.get("previous_ticket_id") == G, r)
check("keyless recurrence: hash moved, no key", sql(f"SELECT hash, dedup_key, recurrence_of FROM tickets WHERE ticket_id='{G2}'")[0]
== [legacy_hash(LT), "NULL", G] and one(f"SELECT hash FROM tickets WHERE ticket_id='{G}'") == "NULL")
# 7b. closed_at missing: falls back to updated_at
sql(f"UPDATE tickets SET status='Closed', closed_at=NULL, updated_at=NOW() - INTERVAL 1 DAY WHERE ticket_id='{G2}'")
st, r = create(LT, key="gandalf")
check(f"closed without closed_at, updated yesterday -> {REOPEN}", r.get("ticket_id") == G2 and r.get("action") == REOPEN, r)
# 8. concurrency: 8 identical new keyed reports at once -> one ticket
CK = "host:test-node-03:disk"
with concurrent.futures.ThreadPoolExecutor(8) as ex:
outs = list(ex.map(lambda _: create("[test-node-03][auto][thor][storage] Disk full", dedup_key=CK), range(8)))
ids = {o[1].get("ticket_id") for o in outs}
check("8 concurrent identical creates -> 1 ticket, all 200",
len(ids) == 1 and all(o[0] == 200 for o in outs) and one(f"SELECT COUNT(*) FROM tickets WHERE dedup_key='{CK}'") == "1",
[o for o in outs])
# 8b. upper case keys are allowed and case-sensitive
UK = "cluster:ceph:BLUESTORE_SLOW_OP_ALERT"
st, r1 = create("[proxmox-cluster][auto][thor][ceph] BlueStore slow ops", dedup_key=UK)
st2, r2 = create("[proxmox-cluster][auto][thor][ceph] BlueStore slow ops", dedup_key=UK.lower())
check("upper case key accepted; lower-case variant is a different key",
st == 200 and st2 == 200 and r1.get("action") == "created" and r2.get("action") == "created"
and r1.get("ticket_id") != r2.get("ticket_id"), (r1, r2))
st, r = call("GET", f"/api/tickets_api.php?dedup_key={UK}", key="reader")
check("lookup is case-sensitive", st == 200 and r["ticket"]["ticket_id"] == r1.get("ticket_id"), (st, r))
# 9. lookup by key
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="reader")
check("lookup by key (read key) -> newest ticket + recurrences",
st == 200 and r["ticket"]["ticket_id"] == B and r["recurrences"] == [A] and r["ticket"]["source"] == "thor", (st, r if st != 200 else r["recurrences"]))
st, r = call("GET", "/api/tickets_api.php?dedup_key=host:nothing:here", key="reader")
check("lookup miss -> 404", st == 404, (st, r))
st, r = call("GET", "/api/tickets_api.php?dedup_key=BAD%20KEY", key="reader")
check("lookup invalid key -> 400", st == 400, (st, r))
sql(f"UPDATE tickets SET visibility='confidential' WHERE ticket_id='{B}'")
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="reader")
check("confidential match, public-only key -> 404", st == 404, (st, r))
st, r = call("GET", f"/api/tickets_api.php?dedup_key={KEY}", key="allseeing")
check("confidential match, see-all key -> 200", st == 200 and r["ticket"]["ticket_id"] == B, st)
# 10. source filter on the list
st, r = call("GET", "/api/tickets_api.php?status=Open,Closed&source=gandalf&limit=100", key="allseeing")
srcs = {t["source"] for t in r.get("tickets", [])}
check("list ?source=gandalf only returns gandalf tickets", st == 200 and srcs == {"gandalf"}, (st, srcs))
# 11. link API
C = ids.pop()
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks"})
check("link A blocks C -> 200", st == 200 and r == {"success": True, "ticket_id": A, "relation": "blocks", "other_ticket_id": C}, (st, r))
check("link audit records the key name",
'"api_key":"thor"' in (one("SELECT details FROM audit_log WHERE entity_type='dependency' AND action_type='create' ORDER BY audit_id DESC LIMIT 1") or ""))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks"})
check("same link again -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocked_by"})
check("inverse of an existing link -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocks"})
check("circular blocking -> 409", st == 409, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": C, "other_ticket_id": A, "relation": "blocked_by", "action": "unlink"})
check("unlink stated from the other side -> removed", st == 200 and r.get("removed") is True, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "blocks", "action": "unlink"})
check("unlink again -> 404", st == 404, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": B, "other_ticket_id": C, "relation": "relates_to"})
check("link to a confidential ticket, public-only key -> 404 not found", st == 404 and r.get("error") == f"Ticket {B} not found", (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": B, "other_ticket_id": C, "relation": "relates_to"}, key="allseeing")
check("same with a see-all key -> 200", st == 200, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "relates_to"}, key="reader")
check("read-only key -> 403", st == 403, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": C, "relation": "causes"})
check("bad relation -> 400", st == 400, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": A, "relation": "relates_to"})
check("self link -> 400", st == 400, (st, r))
st, r = call("POST", "/api/ticket_link_api.php", {"ticket_id": A, "other_ticket_id": "999999999", "relation": "relates_to"})
check("missing ticket -> 404", st == 404 and r.get("error") == "Ticket 999999999 not found", (st, r))
st, r = call("GET", "/api/ticket_link_api.php")
check("GET -> 405", st == 405, (st, r))
for mode in ("prod", "open", "none"):
run_mode(mode)
print(f"\n{sum(results)} passed, {len(results) - sum(results)} failed")
sys.exit(0 if results and all(results) else 1)
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
# CI only: fails if a server log holds any PHP warning, notice, deprecation or
# error, in PHP's own format ("PHP Warning: ...") or helpers/ErrorHandler.php's
# ("[...] [WARNING] ..."). A page can render fine while logging these: the
# E_STRICT deprecation and "Array to string conversion" in #130 did.
#
# tests/ci/php-warnings.sh .ui-stack/server.log
set -euo pipefail
LOG=${1:?server log}
PATTERN='\[(WARNING|NOTICE|DEPRECATED|USER_WARNING|USER_NOTICE|USER_DEPRECATED|RECOVERABLE_ERROR|ERROR|FATAL|PARSE|CORE_ERROR|COMPILE_ERROR)\]|PHP (Warning|Notice|Deprecated|Fatal error|Parse error)'
if grep -E "$PATTERN" "$LOG"; then
echo "::error::PHP logged the warnings, notices or errors above while serving the tests ($LOG)."
exit 1
fi
echo "No PHP warnings, notices or errors in $LOG"
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
# CI only: installs PHP (and, unless WITH_DB=0, a throwaway MariaDB on
# 127.0.0.1:3306 with a 'tinker_ui' user) inside a job container, as root.
#
# tests/ci/setup.sh # PHP + MariaDB (api and ui jobs)
# WITH_DB=0 tests/ci/setup.sh # PHP only (lint and audit jobs)
# EXTRA_PKGS="unzip" tests/ci/setup.sh
#
# Works in the node:22-trixie job image (Debian 13: PHP 8.4, the same packages
# as production on CT 132) and in the Playwright image (Ubuntu 24.04: PHP 8.3).
# 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 and Thor).
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="php-cli php-mysql php-mbstring php-curl php-ldap php-xml ${EXTRA_PKGS:-}"
[ "${WITH_DB:-1}" = 1 ] && PKGS="mariadb-server $PKGS"
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
if [ "${WITH_DB:-1}" = 1 ]; then
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';"
mariadb --version
fi
php --version | head -1
+1
View File
@@ -0,0 +1 @@
node_modules/
+1250
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
{
"name": "tinker-tickets-lint",
"private": true,
"description": "Pinned eslint for CI (the scan of assets/js/ uses the repository's .eslintrc.json).",
"scripts": {
"lint": "eslint --no-eslintrc -c ../../.eslintrc.json --max-warnings=66 ../../assets/js/"
},
"devDependencies": {
"eslint": "8.57.1"
}
}
+3
View File
@@ -0,0 +1,3 @@
node_modules/
playwright-report/
test-results/
+61
View File
@@ -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': '[email protected]',
'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_<app>).
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 };
+56
View File
@@ -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("<script>window.__seedXss = 1</script>");
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');
});
+58
View File
@@ -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"
}
}
}
}
+11
View File
@@ -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"
}
}
+42
View File
@@ -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);
});
+29
View File
@@ -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' },
],
});
+26
View File
@@ -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);
});
}
+23
View File
@@ -0,0 +1,23 @@
<?php
/**
* Router for PHP's built-in server in the UI tests (tests/ui/stack.sh): static
* files are served as-is, PHP files run, everything else goes to index.php, as
* nginx's try_files does in production.
*/
if (php_sapi_name() !== 'cli-server') {
http_response_code(404);
exit;
}
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = $_SERVER['DOCUMENT_ROOT'] . $path;
if ($path !== '/' && is_file($file)) {
if (!str_ends_with($file, '.php')) {
return false;
}
require $file;
return true;
}
require $_SERVER['DOCUMENT_ROOT'] . '/index.php';
+112
View File
@@ -0,0 +1,112 @@
'use strict';
// Before/after screenshots for UI pull requests.
//
// node tests/ui/screenshots.js <out-dir> before=<url> after=<url>
//
// 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 (<page>-<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 = `<!doctype html><meta charset="utf-8"><style>
body{margin:0;background:#0b0e14;color:#ddd;font:16px monospace}
.row{display:flex;gap:16px;padding:16px;align-items:flex-start}
.col{flex:1;min-width:0} h2{margin:0 0 8px;font-size:16px}
.b h2{color:#ff7878}.a h2{color:#78ffa0} img{width:100%;border:1px solid #333}
</style><div class="row">
<div class="col b"><h2>BEFORE (base) ${name}</h2><img src="${b64(before)}"></div>
<div class="col a"><h2>AFTER (this PR) ${name}</h2><img src="${b64(after)}"></div>
</div>`;
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 <out-dir> before=<url> after=<url>');
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); });
+115
View File
@@ -0,0 +1,115 @@
<?php
/**
* Synthetic seed data for the UI tests and before/after screenshots.
*
* CLI only, and only into a database whose name starts with tinker_ui:
*
* DB_NAME=tinker_ui php tests/ui/seed.php
*
* Connects as the throwaway tinker_ui user (tests/ci/setup.sh), never with the
* app's .env credentials. Replaces only the tickets it owns (ids 1000000xx),
* so it can be re-run. Every value here is made up.
*/
if (php_sapi_name() !== 'cli') {
http_response_code(404);
exit;
}
$dbName = (string)getenv('DB_NAME');
if (!str_starts_with($dbName, 'tinker_ui')) {
fwrite(STDERR, "refusing: DB_NAME must start with tinker_ui\n");
exit(2);
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('127.0.0.1', 'tinker_ui', 'ci-only', $dbName);
$db->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: <script>window.__seedXss = 1</script> 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";
+72
View File
@@ -0,0 +1,72 @@
#!/bin/bash
# Starts one Tinker Tickets instance for the UI tests on a fresh database:
#
# tests/ui/stack.sh <checkout-dir> <port> <db-name>
#
# 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/ci/setup.sh in
# CI) and root access to it over the local socket. Logs go to
# <checkout>/.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" <<EOF
; tinker-ui-stack: throwaway UI test settings, safe to delete
DB_HOST=127.0.0.1
DB_USER=tinker_ui
DB_PASS=ci-only
DB_NAME=$DB
LDAP_ENABLED=false
TIMEZONE=UTC
; One client IP makes every request in a test run; the default limits would
; turn later pages into 429s.
RATE_LIMIT_DEFAULT=100000
RATE_LIMIT_API=100000
RATE_LIMIT_IP=100000
RATE_LIMIT_IP_API=100000
EOF
# This branch's migration runner, run from inside the checkout so it reads
# that checkout's config and migrations: a base branch with an older runner
# (before the comment fix) still gets its schema.
cp "$HERE/../../migrations/migrate.php" "$CHECKOUT/migrations/.ui-migrate.php"
php "$CHECKOUT/migrations/.ui-migrate.php"
rm -f "$CHECKOUT/migrations/.ui-migrate.php"
DB_NAME=$DB php "$HERE/seed.php"
mkdir -p "$CHECKOUT/.ui-stack"
(cd "$CHECKOUT" && setsid php -S "127.0.0.1:$PORT" -t . "$HERE/router.php" \
> "$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: [email protected]' -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
+5
View File
@@ -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) {