From 322f2cf96e284bc733d4d747e53a5de3d30d0f93 Mon Sep 17 00:00:00 2001 From: githubflyideas <36397539+githubflyideas@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:28:36 +0900 Subject: [PATCH] Add OpenAPI spec, split newMux, Caps Lock hint --- .github/workflows/quality.yml | 35 + README.md | 4 + browser/.gitignore | 1 + browser/login_capslock.test.cjs | 95 +++ browser/package-lock.json | 60 ++ browser/package.json | 10 + browser_server_test.go | 39 ++ docs/API.md | 3 + docs/openapi.yaml | 1019 +++++++++++++++++++++++++++ i18n/strings.json | 12 + openapi_test.go | 161 +++++ static/login.html | 17 +- web.go | 1140 +++++++++++++++++-------------- 13 files changed, 2064 insertions(+), 532 deletions(-) create mode 100644 .github/workflows/quality.yml create mode 100644 browser/.gitignore create mode 100644 browser/login_capslock.test.cjs create mode 100644 browser/package-lock.json create mode 100644 browser/package.json create mode 100644 browser_server_test.go create mode 100644 docs/openapi.yaml create mode 100644 openapi_test.go diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml new file mode 100644 index 0000000..9f566c7 --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,35 @@ +name: quality + +# Keeps three things from drifting: the router's complexity, the OpenAPI spec +# against the registered routes, and the sign-in page's Caps Lock hint in a +# real browser. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: { go-version: '1.27.4' } + - name: gocyclo (router stays small) + run: | + go install github.com/fzipp/gocyclo/cmd/gocyclo@v0.6.0 + gocyclo -over 15 web.go stats.go + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: { node-version: '22', cache: npm, cache-dependency-path: browser/package-lock.json } + - name: OpenAPI lint + run: npx --yes @redocly/cli@2.82.0 lint docs/openapi.yaml + - name: Browser tests + working-directory: browser + run: | + npm ci --ignore-scripts + npx playwright install --with-deps chromium + npm test diff --git a/README.md b/README.md index b5422cf..f4e3c09 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,10 @@ Off by default. Start with `--zabbix` and a token of 16+ characters in `PINGPING **Before restarting a service**, `pingping check` with the same flags says whether it would start and why not (flags, token, data directory, database, port), without touching the running one. Every start logs a short security summary; anything exposed is marked `!`. +### HTTP API + +The console, the tray icon and the Zabbix template all use one JSON API: [docs/API.md](docs/API.md) · OpenAPI 3.1: [docs/openapi.yaml](docs/openapi.yaml). + ### No ads, no outbound requests pingping has no advertising and makes no requests of its own beyond the probes you configure. diff --git a/browser/.gitignore b/browser/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/browser/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/browser/login_capslock.test.cjs b/browser/login_capslock.test.cjs new file mode 100644 index 0000000..9c412d9 --- /dev/null +++ b/browser/login_capslock.test.cjs @@ -0,0 +1,95 @@ +// Browser test for the sign-in page's Caps Lock hint, against the real Go +// router (so the page's CSP applies). Run: cd browser && npm ci && npm test +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const {spawn} = require('node:child_process'); +const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const catalogue = require('../i18n/strings.json'); + +function startServer() { + const child = spawn('go', ['test', '-count=1', '-run', '^TestBrowserServer$'], { + cwd: path.join(__dirname, '..'), + env: {...process.env, BROWSER_TEST_SERVE: '1'}, + stdio: ['ignore', 'pipe', 'inherit'], + detached: true, // its own process group, so the test binary stops with it + }); + return new Promise((resolve, reject) => { + let out = ''; + const timer = setTimeout(() => reject(new Error('server did not start\n' + out)), 120000); + child.stdout.on('data', b => { + out += b; + const m = out.match(/BROWSER_TEST_URL=(\S+)/); + if (m) { clearTimeout(timer); resolve({child, url: m[1]}); } + }); + child.on('exit', code => reject(new Error('server exited ' + code + '\n' + out))); + }); +} + +// Chromium cannot toggle the real Caps Lock from a test, so the events carry +// the modifier state the way a browser reports it. +const key = (page, sel, type, caps) => page.locator(sel).evaluate((el, [type, caps]) => + el.dispatchEvent(new KeyboardEvent(type, {key: caps ? 'A' : 'a', bubbles: true, modifierCapsLock: caps})), + [type, caps]); + +test('login page shows a Caps Lock hint only while it is on', {timeout: 180000}, async () => { + const {child, url} = await startServer(); + const browser = await chromium.launch(); + try { + const page = await browser.newPage(); + const errors = []; + page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); }); + page.on('pageerror', e => errors.push(e.message)); + await page.goto(url + '/login'); + await page.evaluate(() => window.i18nReady); + const hint = page.locator('#caps'); + assert.equal(await hint.getAttribute('aria-live'), 'polite'); + assert.match(await page.locator('#pass').getAttribute('aria-describedby'), /\bcaps\b/); + assert.equal(await hint.textContent(), ''); + + await page.locator('#pass').focus(); + await key(page, '#pass', 'keydown', true); + assert.match(await hint.textContent(), /\S/); + assert.ok(await hint.isVisible(), 'hint is visible'); + + await key(page, '#pass', 'keyup', false); + assert.equal(await hint.textContent(), ''); + + // On, then focus moves away: hidden; back to the password field: shown. + await key(page, '#pass', 'keydown', true); + await page.locator('#user').focus(); + assert.equal(await hint.textContent(), ''); + await page.locator('#pass').focus(); + assert.match(await hint.textContent(), /\S/); + + // Typing in the username field with Caps Lock on shows nothing there. + await page.locator('#user').focus(); + await key(page, '#user', 'keydown', true); + assert.equal(await hint.textContent(), ''); + + // Every language the console ships says it in that language. + const want = catalogue.strings['login.capsLock']; + for (const lang of catalogue.langs) { + await page.evaluate(l => localStorage.setItem('pingping_lang', l), lang); + await page.reload(); + await page.evaluate(() => window.i18nReady); + await page.locator('#pass').focus(); + await key(page, '#pass', 'keydown', true); + assert.equal(await hint.textContent(), want[lang], lang); + } + + // Switching language while it shows updates it (focus stays in the field). + await page.evaluate(() => { + const sel = document.querySelector('.lang-picker'); + sel.value = 'en'; + sel.dispatchEvent(new Event('change')); + }); + await page.waitForFunction(() => document.documentElement.lang === 'en'); + assert.equal(await hint.textContent(), want.en); + + assert.deepEqual(errors, [], 'no console errors (a CSP violation would be one)'); + } finally { + await browser.close(); + process.kill(-child.pid, 'SIGTERM'); + } +}); diff --git a/browser/package-lock.json b/browser/package-lock.json new file mode 100644 index 0000000..4baf1ae --- /dev/null +++ b/browser/package-lock.json @@ -0,0 +1,60 @@ +{ + "name": "pingping-browser-tests", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pingping-browser-tests", + "devDependencies": { + "playwright": "1.62.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.62.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/browser/package.json b/browser/package.json new file mode 100644 index 0000000..e2ca292 --- /dev/null +++ b/browser/package.json @@ -0,0 +1,10 @@ +{ + "name": "pingping-browser-tests", + "private": true, + "scripts": { + "test": "node --test" + }, + "devDependencies": { + "playwright": "1.62.1" + } +} diff --git a/browser_server_test.go b/browser_server_test.go new file mode 100644 index 0000000..e79d779 --- /dev/null +++ b/browser_server_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "context" + "fmt" + "net/http/httptest" + "os" + "os/signal" + "syscall" + "testing" + "time" +) + +// TestBrowserServer serves the real router, login and CSP included, on a +// random loopback port for the browser tests in browser/. It is skipped +// unless they start it, and stops when they signal it (or after 5 minutes). +func TestBrowserServer(t *testing.T) { + if os.Getenv("BROWSER_TEST_SERVE") == "" { + t.Skip("started by the browser tests in browser/") + } + s, err := NewStore(t.TempDir(), nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if err := s.CreateUser("admin", "browser-test-password", RoleAdmin); err != nil { + t.Fatal(err) + } + run := NewRunner(ProbeCfg{Packets: 1, TimeoutMs: 50}, s, NewDetector(s)) + defer run.Stop() + srv := httptest.NewServer(newMux(&Config{}, s, run)) + defer srv.Close() + fmt.Println("BROWSER_TEST_URL=" + srv.URL) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + <-ctx.Done() +} diff --git a/docs/API.md b/docs/API.md index effd154..42b3216 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4,6 +4,9 @@ pingping's console, its notification-area icon and the Zabbix template talk to pingping through this API. The same rules hold in fogping and vrf-ping, so a client written for one reads the others the same way. +The same API in machine-readable form: [openapi.yaml](openapi.yaml) (OpenAPI 3.1). +A test (`TestOpenAPIMatchesRoutes`) fails when it and the registered routes differ. + ## Rules These are enforced by tests (`api_test.go`): code that breaks one does not pass CI. diff --git a/docs/openapi.yaml b/docs/openapi.yaml new file mode 100644 index 0000000..72eea6b --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,1019 @@ +openapi: 3.1.0 +info: + title: pingping HTTP API + version: "1" + summary: The API the pingping web UI and the console, its tray icon and the Zabbix template use. + description: | + Machine-readable form of [API.md](API.md); the rules there apply. + Every `/api/` response carries `API-Version: 1`. Every error is + `{"error", "code"}` (schema `Error`). A wrong method on a known path is + `405` with an `Allow` header; an unknown path under `/api/` is `404`. + + "session" below means the `pingping_session` cookie from `POST /api/login`. + An account is an `admin` or a `viewer`; a viewer gets `403` on anything that + changes the instance. `GET /api/stats` is the only endpoint that takes a bearer + token, and that token is read-only. + + `openapi_test.go` (`TestOpenAPIMatchesRoutes`) fails when this file and the + routes the code registers differ. + license: + name: Apache-2.0 + identifier: Apache-2.0 +servers: + - url: / + description: The pingping instance serving this API . +tags: + - name: pages + description: HTML pages and static files, outside `/api/`. + - name: auth + description: Sign in and out. + - name: info + description: Build and probe-type information. + - name: accounts + description: Accounts and console settings. + - name: brand + description: The custom logo. + - name: targets + description: Read and change what is probed. + - name: data + description: Measurements. +security: + - session: [] +paths: + /: + get: + tags: [pages] + operationId: getIndex + summary: The console. + security: [] + responses: + "200": + description: The page. + content: + text/html: {} + "302": + description: "Redirect: to `/setup` before the first account exists, else to `/login` when signed out." + headers: + Location: + schema: { type: string } + "405": + description: Wrong method (plain text; not under `/api/`). + /login: + get: + tags: [pages] + operationId: getLoginPage + summary: The sign-in page. + security: [] + responses: + "200": + description: The page. + content: + text/html: {} + "302": + description: "Redirect: to `/setup` before the first account exists." + headers: + Location: + schema: { type: string } + "405": + description: Wrong method (plain text; not under `/api/`). + /setup: + get: + tags: [pages] + operationId: getSetupPage + summary: The first-run page. + security: [] + responses: + "200": + description: The page. + content: + text/html: {} + "302": + description: "Redirect: to `/login` once an account exists." + headers: + Location: + schema: { type: string } + "405": + description: Wrong method (plain text; not under `/api/`). + /settings: + get: + tags: [pages] + operationId: getSettingsPage + summary: Accounts, port and logo settings. + security: [] + responses: + "200": + description: The page. + content: + text/html: {} + "302": + description: "Redirect: to `/setup` before the first account exists, else to `/login` when signed out." + headers: + Location: + schema: { type: string } + "405": + description: Wrong method (plain text; not under `/api/`). + /static/{path}: + get: + tags: [pages] + operationId: getStatic + summary: Embedded static files (the route is the prefix `/static/`), with an ETag. + security: [] + parameters: + - name: path + in: path + required: true + description: File path below `/static/`; may contain `/`. + schema: { type: string } + responses: + "200": + description: The file. + content: + "*/*": {} + "304": + description: Not modified (ETag matched). + "404": + description: No such file (plain text, not under `/api/`). + "405": + description: Wrong method (plain text; not under `/api/`). + /api/setup: + post: + tags: [auth] + operationId: setup + summary: "First run only: create the admin account and sign in." + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + user: { type: string, description: Defaults to `admin`. } + pass: { type: string } + responses: + "200": + description: Account created; the session cookie is set. + headers: + Set-Cookie: + description: "`pingping_session`; HttpOnly, SameSite=Lax, 7 days." + schema: { type: string } + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "500": { $ref: "#/components/responses/Internal" } + /api/login: + post: + tags: [auth] + operationId: login + summary: Sign in and get the session cookie. + security: [] + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/Credentials" } + responses: + "200": + description: Signed in. + headers: + Set-Cookie: + description: "`pingping_session`; HttpOnly, SameSite=Lax, 7 days." + schema: { type: string } + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "429": { $ref: "#/components/responses/RateLimited" } + /api/logout: + post: + tags: [auth] + operationId: logout + summary: Sign out; the session also ends on the server. Safe without one. + security: [] + responses: + "200": + description: Signed out; the cookie is cleared. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/password: + post: + tags: [auth] + operationId: changePassword + summary: Change your own password; ends all your sessions. + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + old: { type: string } + new: { type: string } + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + /api/me: + get: + tags: [accounts] + operationId: getMe + summary: Who you are, and the console settings you may see. + responses: + "200": + description: The signed-in account. + content: + application/json: + schema: { $ref: "#/components/schemas/Me" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/users: + get: + tags: [accounts] + operationId: listUsers + summary: Accounts and their roles (admin only). + responses: + "200": + description: Accounts. + content: + application/json: + schema: + type: array + items: { $ref: "#/components/schemas/User" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "500": { $ref: "#/components/responses/Internal" } + post: + tags: [accounts] + operationId: createUser + summary: Create an account (admin only). + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: { type: string } + pass: { type: string } + role: { type: string, enum: [admin, viewer], description: Defaults to `viewer`. } + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + /api/users/{name}/password: + parameters: + - name: name + in: path + required: true + schema: { type: string } + post: + tags: [accounts] + operationId: setUserPassword + summary: Set another account's password (admin only); ends its sessions. + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + pass: { type: string } + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + /api/users/{name}/role: + parameters: + - name: name + in: path + required: true + schema: { type: string } + post: + tags: [accounts] + operationId: setUserRole + summary: Change an account's role (admin only); ends its sessions. + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + role: { type: string, enum: [admin, viewer] } + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + /api/users/{name}: + parameters: + - name: name + in: path + required: true + schema: { type: string } + delete: + tags: [accounts] + operationId: deleteUser + summary: "Delete an account (admin only): not your own, not the last admin." + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + /api/settings/port: + post: + tags: [accounts] + operationId: setConsolePort + summary: Console port and bind address for the next start (admin only). + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + port: { type: integer, description: 0 leaves it unchanged. } + bind: { type: string, description: Empty leaves it unchanged. } + responses: + "200": + description: Stored; applied after a restart. + content: + application/json: + schema: + type: object + required: [ok, port, bind, applied, note] + properties: + ok: { type: boolean } + port: { type: integer } + bind: { type: string } + applied: { type: boolean, const: false } + note: { type: string } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + /api/health: + get: + tags: [info] + operationId: getHealth + summary: Counts for the notification-area icon. + description: Answers only to loopback requests without forwarding headers; `404` otherwise. + security: [] + responses: + "200": + description: Counts. + content: + application/json: + schema: + type: object + required: [version, needs_setup, targets, down, port, port_configured] + properties: + version: { type: string } + needs_setup: { type: boolean } + targets: { type: integer } + down: { type: integer } + port: { type: integer } + port_configured: { type: integer } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/brand/logo: + get: + tags: [brand] + operationId: getLogo + summary: The custom logo image. + responses: + "200": + description: The image, served with `nosniff` and a sandbox CSP. + content: + image/png: {} + image/jpeg: {} + image/gif: {} + image/webp: {} + "401": { $ref: "#/components/responses/Unauthorized" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + post: + tags: [brand] + operationId: setLogo + summary: Upload a custom logo (admin only); the body is the image file. + description: PNG, JPEG, GIF or WebP, up to 256 KB; the type is read from the bytes. + requestBody: + required: true + content: + application/octet-stream: + schema: { type: string, contentMediaType: application/octet-stream } + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + delete: + tags: [brand] + operationId: clearLogo + summary: Remove the custom logo (admin only). + responses: + "200": + description: Done. + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "500": { $ref: "#/components/responses/Internal" } + /api/i18n: + get: + tags: [info] + operationId: getStrings + summary: Console strings for one language. + security: [] + parameters: + - name: lang + in: query + description: Language tag; without it, the best match for `Accept-Language`. + schema: { type: string } + responses: + "200": + description: The catalogue. + content: + application/json: + schema: + type: object + required: [lang, langs, names, s] + properties: + lang: { type: string } + langs: { type: array, items: { type: string } } + names: { type: object, additionalProperties: { type: string } } + s: + type: object + description: Message id to translated string. + additionalProperties: { type: string } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/version: + get: + tags: [info] + operationId: getVersion + summary: Build version; instance settings too with a session. + security: + - {} + - session: [] + responses: + "200": + description: > + `version` for everyone; with a session also `retention_days`, + `hot_days`, `has_logo`, `needs_setup` and `authed`. + content: + application/json: + schema: + type: object + required: [version] + properties: + version: { type: string } + retention_days: { type: integer } + hot_days: { type: integer } + has_logo: { type: boolean } + needs_setup: { type: boolean } + authed: { type: boolean } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/probe-types: + get: + tags: [info] + operationId: getProbeTypes + summary: The probe types this build can run, in display order. + responses: + "200": + description: Probe types. + content: + application/json: + schema: + type: array + items: { $ref: "#/components/schemas/ProbeType" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/targets: + get: + tags: [targets] + operationId: listTargets + summary: Every target with its last-hour and last-day summary. + responses: + "200": + description: Targets. + content: + application/json: + schema: + type: array + items: { $ref: "#/components/schemas/TargetItem" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + post: + tags: [targets] + operationId: createTarget + summary: Create a target (admin only). Unknown fields are refused. + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/TargetInput" } + responses: + "200": + description: The created target. + content: + application/json: + schema: { $ref: "#/components/schemas/Target" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "500": { $ref: "#/components/responses/Internal" } + /api/targets/{id}: + parameters: + - $ref: "#/components/parameters/TargetID" + put: + tags: [targets] + operationId: replaceTarget + summary: Replace a target (admin only). + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/TargetInput" } + responses: + "200": + description: The replaced target. + content: + application/json: + schema: { $ref: "#/components/schemas/Target" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "500": { $ref: "#/components/responses/Internal" } + delete: + tags: [targets] + operationId: deleteTarget + summary: Delete a target (admin only); its history is kept. + responses: + "200": + description: The deleted target as it was. + content: + application/json: + schema: { $ref: "#/components/schemas/Target" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "500": { $ref: "#/components/responses/Internal" } + /api/targets/export: + get: + tags: [targets] + operationId: exportTargets + summary: The target list as a `netping-targets` file download. + responses: + "200": + description: See [targets-format.md](targets-format.md). + headers: + Content-Disposition: + schema: { type: string } + content: + application/json: + schema: { $ref: "#/components/schemas/TargetsFile" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "500": { $ref: "#/components/responses/Internal" } + /api/targets/import: + post: + tags: [targets] + operationId: importTargets + summary: Import a `netping-targets` file (admin only). + parameters: + - name: dry_run + in: query + description: "`1`, `true` or `yes`: report the plan without applying it." + schema: { type: string } + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/TargetsFile" } + responses: + "200": + description: What was (or would be) imported. + content: + application/json: + schema: { $ref: "#/components/schemas/ImportPlan" } + "400": { $ref: "#/components/responses/BadRequest" } + "401": { $ref: "#/components/responses/Unauthorized" } + "403": { $ref: "#/components/responses/Forbidden" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "409": { $ref: "#/components/responses/Conflict" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "500": { $ref: "#/components/responses/Internal" } + /api/series: + get: + tags: [data] + operationId: getSeries + summary: Rounds for one target, raw up to a day and hourly beyond. + parameters: + - name: target + in: query + required: true + schema: { type: string } + - name: minutes + in: query + description: Recent window; default 360, at most 300 days. Used when `from` or `to` is missing. + schema: { type: integer } + - name: from + in: query + description: Unix seconds. + schema: { type: integer, format: int64 } + - name: to + in: query + description: Unix seconds. + schema: { type: integer, format: int64 } + responses: + "200": + description: See "`/api/series` format" in API.md. + content: + application/json: + schema: { $ref: "#/components/schemas/Series" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/stats: + get: + tags: [data] + operationId: getStats + summary: Per-target summary of the last 5 minutes, for Zabbix. + description: Registered only when pingping runs with `--zabbix` and a token. + security: + - bearer: [] + responses: + "200": + description: Summary. + headers: + Cache-Control: + schema: { type: string, const: no-store } + content: + application/json: + schema: { $ref: "#/components/schemas/StatsReport" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "429": { $ref: "#/components/responses/RateLimited" } +components: + securitySchemes: + session: + type: apiKey + in: cookie + name: pingping_session + bearer: + type: http + scheme: bearer + description: The read-only Zabbix token; accepted by `GET /api/stats` only. + parameters: + TargetID: + name: id + in: path + required: true + schema: { type: integer, format: int64, minimum: 1 } + responses: + BadRequest: + description: Bad input. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + Unauthorized: + description: Missing or bad credential. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + Forbidden: + description: A viewer account, or a cross-origin browser request. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + NotFound: + description: Not found. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + MethodNotAllowed: + description: Wrong method for this path. + headers: + Allow: + schema: { type: string } + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + Conflict: + description: Conflicts with the current state (name taken, last admin, already set up). + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + TooLarge: + description: Request body too large. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + UnsupportedMediaType: + description: Content-Type is not `application/json`. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + RateLimited: + description: Too many failed attempts from this address. + headers: + Retry-After: + description: Seconds to wait. + schema: { type: integer } + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + Internal: + description: Server error. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + schemas: + Error: + type: object + required: [error, code] + properties: + error: { type: string, description: For a person. } + code: + type: string + description: For a program; fixed per status. + enum: [bad_request, unauthorized, forbidden, not_found, method_not_allowed, conflict, + too_large, unsupported_media_type, rate_limited, unavailable, internal] + Credentials: + type: object + properties: + user: { type: string } + pass: { type: string } + User: + type: object + required: [name, role, created] + properties: + name: { type: string } + role: { type: string, enum: [admin, viewer] } + created: { type: integer, format: int64, description: Unix seconds. } + Me: + type: object + required: [user, role, version, data_dir, listen, port, bind, bind_pending, retention_days, has_logo] + properties: + user: { type: string } + role: { type: string, enum: [admin, viewer] } + version: { type: string } + data_dir: { type: string } + listen: { type: string } + port: { type: integer } + bind: { type: string, description: Bind address in use now. } + bind_pending: { type: string, description: Bind address stored for the next start. } + retention_days: { type: integer } + has_logo: { type: boolean } + Ok: + type: object + required: [ok] + properties: + ok: { type: boolean, const: true } + OptionSpec: + type: object + required: [key, label, kind] + properties: + key: { type: string } + label: { type: string } + help: { type: string } + kind: { type: string } + required: { type: boolean } + default: {} + min: { type: integer } + max: { type: integer } + max_len: { type: integer } + choices: { type: array, items: { type: string } } + ProbeType: + type: object + required: [type, label, uses_port, options] + properties: + type: { type: string } + label: { type: string } + uses_port: { type: boolean } + options: { type: array, items: { $ref: "#/components/schemas/OptionSpec" } } + TargetInput: + type: object + additionalProperties: false + properties: + id: { type: integer, format: int64, description: Ignored; the path id wins on PUT. } + name: { type: string } + type: { type: string, description: A probe type from `/api/probe-types`; `icmp` when empty. } + host: { type: string } + port: { type: integer } + pace: { type: string, enum: ["", fast, normal, slow] } + interval_sec: { type: integer } + options: { type: object, description: Keys per the type's options in `/api/probe-types`. } + Target: + type: object + required: [id, name, type, host, port, pace, interval_sec] + properties: + id: { type: integer, format: int64 } + name: { type: string } + type: { type: string } + host: { type: string } + port: { type: integer } + pace: { type: string } + interval_sec: { type: integer } + options: { type: object } + Stats: + type: object + required: [rounds, p50, p90, p99, loss_pct, bursts] + properties: + rounds: { type: integer } + p50: { type: number } + p90: { type: number } + p99: { type: number } + loss_pct: { type: number } + bursts: { type: integer } + TargetItem: + type: object + required: [id, name, type, host, port, addr, interval_sec, interval_set, pace, down, last_1h, last_24h] + properties: + id: { type: integer, format: int64 } + name: { type: string } + type: { type: string } + host: { type: string } + port: { type: integer } + addr: { type: string } + interval_sec: { type: integer, description: Effective interval. } + interval_set: { type: integer, description: Explicit override; 0 means from pace. } + pace: { type: string } + options: { type: object } + down: { type: boolean } + last_1h: { $ref: "#/components/schemas/Stats" } + last_24h: { $ref: "#/components/schemas/Stats" } + TargetsFile: + type: object + description: A `netping-targets` file; full schema in [targets.schema.json](targets.schema.json). + required: [format, version, targets] + properties: + format: { type: string, const: netping-targets } + version: { type: integer } + name: { type: string } + description: { type: string } + targets: { type: array, items: { type: object } } + ImportPlan: + type: object + required: [total, add, skip, invalid, dry_run, imported] + properties: + name: { type: string } + description: { type: string } + total: { type: integer } + add: + type: array + items: + type: object + required: [row, type, host] + properties: + row: { type: integer } + name: { type: string } + type: { type: string } + host: { type: string } + port: { type: integer } + pace: { type: string } + interval: { type: integer } + options: { type: object } + restores_history: { type: boolean } + skip: + type: array + items: + type: object + required: [row, name, code, reason] + properties: + row: { type: integer } + name: { type: string } + code: { type: string, enum: [exists, duplicate] } + reason: { type: string } + invalid: + type: array + items: + type: object + required: [row, error] + properties: + row: { type: integer } + name: { type: string } + error: { type: string } + dry_run: { type: boolean } + imported: { type: integer } + Round: + type: object + required: [t, s, r, ms] + properties: + t: { type: integer, format: int64, description: Unix seconds. } + s: { type: integer, description: Packets sent. } + r: { type: integer, description: Replies received. } + ms: { type: [array, "null"], items: { type: number } } + b: { type: boolean, description: Flagged as a loss burst. } + z: { type: number, description: Robust z-score behind the flag. } + Bucket: + type: object + required: [t, loss, n] + properties: + t: { type: integer, format: int64 } + q: { type: array, items: { type: number }, description: "min, p50, p90, p99, max in ms." } + loss: { type: number, description: Percent of packets lost. } + n: { type: integer } + bursts: { type: integer } + Series: + type: object + required: [tier] + properties: + tier: { type: string, enum: [raw, hourly] } + rounds: { type: array, items: { $ref: "#/components/schemas/Round" } } + buckets: { type: array, items: { $ref: "#/components/schemas/Bucket" } } + StatsTarget: + type: object + required: [id, name, rounds, bursts] + properties: + id: { type: integer, format: int64 } + name: { type: string } + rounds: { type: integer } + p50: { type: number } + p90: { type: number } + p99: { type: number } + loss_pct: { type: number } + bursts: { type: integer } + up: { type: integer, enum: [0, 1] } + StatsReport: + type: object + required: [window_sec, targets] + properties: + window_sec: { type: integer } + targets: { type: array, items: { $ref: "#/components/schemas/StatsTarget" } } diff --git a/i18n/strings.json b/i18n/strings.json index 0aa81b9..c6c1aa3 100644 --- a/i18n/strings.json +++ b/i18n/strings.json @@ -396,6 +396,18 @@ "ja": "パスワード", "ko": "비밀번호" }, + "login.capsLock": { + "en": "Caps Lock is on", + "zh": "大写锁定已开启", + "es": "Bloq Mayús está activado", + "fr": "Verr. Maj est activé", + "pt": "Caps Lock está ativado", + "ru": "Включён Caps Lock", + "id": "Caps Lock aktif", + "de": "Feststelltaste ist aktiviert", + "ja": "Caps Lock がオンです", + "ko": "Caps Lock이 켜져 있습니다" + }, "login.signIn": { "en": "Sign in", "zh": "登录", diff --git a/openapi_test.go b/openapi_test.go new file mode 100644 index 0000000..4f2f5a8 --- /dev/null +++ b/openapi_test.go @@ -0,0 +1,161 @@ +package main + +import ( + "bufio" + "go/ast" + "go/parser" + "go/token" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +// openAPIMux is the router with every optional route switched on. +func openAPIMux() *http.ServeMux { + return buildMux(&Config{ZabbixToken: "t"}, nil, nil) +} + +// registeredPatterns returns every "METHOD /path" pattern passed as a string +// literal to Handle or HandleFunc in the package's non-test source. +func registeredPatterns(t *testing.T) []string { + t.Helper() + files, _ := filepath.Glob("*.go") + fset := token.NewFileSet() + var out []string + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(fset, name, nil, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(f, func(n ast.Node) bool { + if p, ok := handlePattern(n); ok { + out = append(out, p) + } + return true + }) + } + return out +} + +func handlePattern(n ast.Node) (string, bool) { + call, ok := n.(*ast.CallExpr) + if !ok || len(call.Args) != 2 { + return "", false + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || (sel.Sel.Name != "Handle" && sel.Sel.Name != "HandleFunc") { + return "", false + } + lit, ok := call.Args[0].(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return "", false + } + s, err := strconv.Unquote(lit.Value) + return s, err == nil +} + +// specPath turns a mux pattern's path into the OpenAPI path that documents it: +// "/{$}" is "/", and a prefix pattern "/static/" is "/static/{path}". +func specPath(p string) string { + switch { + case p == "/{$}": + return "/" + case strings.HasSuffix(p, "/"): + return p + "{path}" + } + return p +} + +// specOperations reads "METHOD /path" pairs from the paths section of +// docs/openapi.yaml: path keys are indented two spaces, methods four. +func specOperations(t *testing.T) []string { + t.Helper() + f, err := os.Open("docs/openapi.yaml") + if err != nil { + t.Fatal(err) + } + defer f.Close() + pathRe := regexp.MustCompile(`^ (/[^:]*):\s*$`) + opRe := regexp.MustCompile(`^ (get|put|post|delete|patch|head|options|trace):`) + var out []string + inPaths, cur := false, "" + sc := bufio.NewScanner(f) + for sc.Scan() { + line := sc.Text() + if !strings.HasPrefix(line, " ") && line != "" { + inPaths = line == "paths:" + continue + } + if !inPaths { + continue + } + if m := pathRe.FindStringSubmatch(line); m != nil { + cur = m[1] + } else if m := opRe.FindStringSubmatch(line); m != nil { + out = append(out, strings.ToUpper(m[1])+" "+cur) + } + } + return out +} + +// TestOpenAPIMatchesRoutes keeps docs/openapi.yaml and the router in step: the +// spec documents exactly the routes the code registers, and the router really +// serves each of them. +func TestOpenAPIMatchesRoutes(t *testing.T) { + mux := openAPIMux() + code := map[string]bool{} + for _, p := range registeredPatterns(t) { + method, path, ok := strings.Cut(p, " ") + if !ok { + t.Errorf("%q has no method", p) + continue + } + code[method+" "+specPath(path)] = true + url := strings.NewReplacer("{$}", "", "{id}", "1", "{name}", "x").Replace(path) + if strings.HasSuffix(url, "/") && url != "/" { + url += "x" + } + req := httptest.NewRequest(method, url, nil) + if _, got := mux.Handler(req); got != p { + t.Errorf("router serves %s %s with %q, want %q", method, url, got, p) + } + } + spec := map[string]bool{} + for _, op := range specOperations(t) { + spec[op] = true + } + if len(code) == 0 || len(spec) == 0 { + t.Fatalf("found %d routes in code and %d in the spec", len(code), len(spec)) + } + for _, k := range sortedKeys(code) { + if !spec[k] { + t.Errorf("route %s is not in docs/openapi.yaml", k) + } + } + for _, k := range sortedKeys(spec) { + if !code[k] { + t.Errorf("docs/openapi.yaml documents %s, which the code does not register", k) + } + } + if !t.Failed() { + t.Logf("%d operations match", len(spec)) + } +} + +func sortedKeys(m map[string]bool) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/static/login.html b/static/login.html index 85cc1fd..64ee83f 100644 --- a/static/login.html +++ b/static/login.html @@ -30,6 +30,7 @@ border-radius:4px; padding:11px; cursor:pointer; } button:hover { background:rgba(232,180,74,.12); } .err { color:var(--alert); font-size:12px; margin-top:12px; min-height:16px; } + .caps { color:var(--amber); font-size:12px; margin-top:6px; } html[data-theme="daylight"] { --bg:#f4f1e8; --panel:#faf8f1; --screen:#fffef9; --line:#e0dbc9; --ctl:#89887c; @@ -51,7 +52,8 @@
Sign in to pingping
- + + @@ -76,6 +78,19 @@