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 @@

pingping

Sign in to pingping

- + +

@@ -76,6 +78,19 @@

pingping

$('err').textContent = d.error || `${T('login.failed')} (HTTP ${res.status})`; } $('go').onclick = login; +// Caps Lock hint: the state is read from any key or mouse event (a focus event +// does not carry it) and shown only while the password field has focus. +let capsOn = false; +const showCaps = () => { + $('caps').textContent = capsOn && document.activeElement === $('pass') ? T('login.capsLock', 'Caps Lock is on') : ''; +}; +const readCaps = e => { + if (typeof e.getModifierState === 'function') { capsOn = e.getModifierState('CapsLock'); showCaps(); } +}; +for (const type of ['keydown', 'keyup', 'mousedown']) document.addEventListener(type, readCaps); +$('pass').addEventListener('focus', showCaps); +$('pass').addEventListener('blur', showCaps); +document.addEventListener('i18n', showCaps); document.addEventListener('keydown', e => { if (e.key === 'Enter') login(); }); diff --git a/web.go b/web.go index 37bd646..49eb9ba 100644 --- a/web.go +++ b/web.go @@ -83,389 +83,451 @@ func (s *sessions) drop(tok string) { const sessionCookie = "pingping_session" +// webApp holds what the HTTP handlers share. newMux only wires routes; each +// area of the console registers its own, so no single function grows past a +// screenful. +type webApp struct { + cfg *Config + store *Store + run *Runner + sess *sessions + throttle *loginThrottle + as *assets +} + func newMux(cfg *Config, store *Store, run *Runner) http.Handler { - sess := newSessions() - throttle := newLoginThrottle() + return securityHeaders(apiRules(buildMux(cfg, store, run))) +} + +// buildMux is newMux without the outer wrappers, so tests can ask the router +// which pattern serves a request. +func buildMux(cfg *Config, store *Store, run *Runner) *http.ServeMux { + a := &webApp{cfg: cfg, store: store, run: run, sess: newSessions(), + throttle: newLoginThrottle(), as: embeddedAssets()} mux := http.NewServeMux() + a.registerPages(mux) + a.registerAuth(mux) + a.registerUsers(mux) + a.registerInfo(mux) + a.registerBrand(mux) + a.registerTargets(mux) + registerStats(mux, cfg.ZabbixToken, store, run) + return mux +} - token := func(r *http.Request) string { - c, err := r.Cookie(sessionCookie) - if err != nil { - return "" - } - return c.Value - } - current := func(r *http.Request) (session, bool) { return sess.get(token(r)) } - authed := func(r *http.Request) bool { _, ok := current(r); return ok } - setCookie := func(w http.ResponseWriter, tok string, maxAge int) { - http.SetCookie(w, &http.Cookie{ - Name: sessionCookie, Value: tok, Path: "/", - HttpOnly: true, MaxAge: maxAge, SameSite: http.SameSiteLaxMode, - }) - } - - // guard is the only gate. There is no anonymous read path: an open console - // would expose which hosts this machine watches, which is itself a map of the - // network. - guard := func(h http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !authed(r) { - jsonErr(w, http.StatusUnauthorized, "sign in first") - return - } - t0 := time.Now() - h(w, r) - if d := time.Since(t0); d > time.Second { - log.Printf("slow request: %s %s took %v", r.URL.Path, r.URL.RawQuery, d) - } - } +func sessionToken(r *http.Request) string { + c, err := r.Cookie(sessionCookie) + if err != nil { + return "" } - // write additionally refuses cross-origin form posts. A JSON content type - // forces a CORS preflight that we never answer, so a page on another site - // cannot drive these endpoints with the operator's cookie. - write := func(h http.HandlerFunc) http.HandlerFunc { - return guard(func(w http.ResponseWriter, r *http.Request) { - if !sameOrigin(r) { - jsonErr(w, http.StatusForbidden, "cross-origin request refused") - return - } - h(w, r) - }) - } - // admin wraps a write that changes what this host probes, or who may sign in. - // A viewer reaching one gets 403 rather than 404: they are authenticated, and - // pretending the endpoint does not exist would only make the UI confusing. - admin := func(h http.HandlerFunc) http.HandlerFunc { - return write(func(w http.ResponseWriter, r *http.Request) { - sn, _ := current(r) - if sn.role != RoleAdmin { - jsonErr(w, http.StatusForbidden, "this account is read-only") - return - } - h(w, r) - }) - } - // Pages and assets both go through assets.serve, which gives them an ETag and - // `no-cache`. See assets.go for why: without a validator a browser is entitled - // to keep serving the markup from the version you just upgraded away from. - as := embeddedAssets() - page := func(name string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Referrer-Policy", "same-origin") - w.Header().Set("Content-Security-Policy", pageCSPFor(as.fs, "static/"+name)) - as.serve(w, r, "static/"+name, "text/html; charset=utf-8") + return c.Value +} + +func (a *webApp) current(r *http.Request) (session, bool) { return a.sess.get(sessionToken(r)) } + +func (a *webApp) authed(r *http.Request) bool { _, ok := a.current(r); return ok } + +func setSessionCookie(w http.ResponseWriter, tok string, maxAge int) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookie, Value: tok, Path: "/", + HttpOnly: true, MaxAge: maxAge, SameSite: http.SameSiteLaxMode, + }) +} + +// guard is the only gate. There is no anonymous read path: an open console +// would expose which hosts this machine watches, which is itself a map of the +// network. +func (a *webApp) guard(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !a.authed(r) { + jsonErr(w, http.StatusUnauthorized, "sign in first") + return + } + t0 := time.Now() + h(w, r) + if d := time.Since(t0); d > time.Second { + log.Printf("slow request: %s %s took %v", r.URL.Path, r.URL.RawQuery, d) } } +} - // Pages are bound to GET like every endpoint, so the router itself can tell a - // wrong method (405) from a wrong path (404); a catch-all "/" would answer - // every request it does not recognise with 404, API calls included. - mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { - if store.NeedsSetup() { - http.Redirect(w, r, "/setup", http.StatusFound) +// write additionally refuses cross-origin form posts. A JSON content type +// forces a CORS preflight that we never answer, so a page on another site +// cannot drive these endpoints with the operator's cookie. +func (a *webApp) write(h http.HandlerFunc) http.HandlerFunc { + return a.guard(func(w http.ResponseWriter, r *http.Request) { + if !sameOrigin(r) { + jsonErr(w, http.StatusForbidden, "cross-origin request refused") return } - if !authed(r) { - http.Redirect(w, r, "/login", http.StatusFound) + h(w, r) + }) +} + +// admin wraps a write that changes what this host probes, or who may sign in. +// A viewer reaching one gets 403 rather than 404: they are authenticated, and +// pretending the endpoint does not exist would only make the UI confusing. +func (a *webApp) admin(h http.HandlerFunc) http.HandlerFunc { + return a.write(func(w http.ResponseWriter, r *http.Request) { + sn, _ := a.current(r) + if sn.role != RoleAdmin { + jsonErr(w, http.StatusForbidden, "this account is read-only") return } - page("index.html")(w, r) + h(w, r) }) - mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { - if store.NeedsSetup() { +} + +// page serves one HTML page. Pages and assets both go through assets.serve, +// which gives them an ETag and `no-cache`. See assets.go for why: without a +// validator a browser is entitled to keep serving the markup from the version +// you just upgraded away from. +func (a *webApp) page(w http.ResponseWriter, r *http.Request, name string) { + w.Header().Set("Referrer-Policy", "same-origin") + w.Header().Set("Content-Security-Policy", pageCSPFor(a.as.fs, "static/"+name)) + a.as.serve(w, r, "static/"+name, "text/html; charset=utf-8") +} + +// pageGate serves a page, or redirects first: to /setup while no account +// exists (unless this is /setup), and to /login when signed out and the page +// needs a session. +func (a *webApp) pageGate(name string, needsSession bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if a.store.NeedsSetup() { http.Redirect(w, r, "/setup", http.StatusFound) return } - page("login.html")(w, r) - }) - mux.HandleFunc("GET /setup", func(w http.ResponseWriter, r *http.Request) { - if !store.NeedsSetup() { + if needsSession && !a.authed(r) { http.Redirect(w, r, "/login", http.StatusFound) return } - page("setup.html")(w, r) - }) - mux.HandleFunc("GET /settings", func(w http.ResponseWriter, r *http.Request) { - if store.NeedsSetup() { - http.Redirect(w, r, "/setup", http.StatusFound) - return - } - if !authed(r) { + a.page(w, r, name) + } +} + +func (a *webApp) registerPages(mux *http.ServeMux) { + // Pages are bound to GET like every endpoint, so the router itself can tell a + // wrong method (405) from a wrong path (404); a catch-all "/" would answer + // every request it does not recognise with 404, API calls included. + mux.HandleFunc("GET /{$}", a.pageGate("index.html", true)) + mux.HandleFunc("GET /login", a.pageGate("login.html", false)) + mux.HandleFunc("GET /setup", func(w http.ResponseWriter, r *http.Request) { + if !a.store.NeedsSetup() { http.Redirect(w, r, "/login", http.StatusFound) return } - page("settings.html")(w, r) + a.page(w, r, "setup.html") }) + mux.HandleFunc("GET /settings", a.pageGate("settings.html", true)) mux.HandleFunc("GET /static/", func(w http.ResponseWriter, r *http.Request) { name := assetPath(r.URL.Path) if name == "" || name == "static" { http.NotFound(w, r) return } - as.serve(w, r, name, "") + a.as.serve(w, r, name, "") }) +} +func (a *webApp) registerAuth(mux *http.ServeMux) { // ---- first run ---- // Open until a password exists, closed forever after. The window is the same // one Technitium leaves open, and it is why the installer tells the operator to // open the console straight away. - mux.HandleFunc("POST /api/setup", func(w http.ResponseWriter, r *http.Request) { - if !store.NeedsSetup() { - jsonErr(w, http.StatusConflict, "already set up") - return - } - if !sameOrigin(r) { - jsonErr(w, http.StatusForbidden, "cross-origin request refused") - return - } - var body struct{ User, Pass string } - if !decodeJSON(w, r, &body) { - return - } - if body.User == "" { - body.User = "admin" - } - if err := validateUsername(body.User); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - if err := validatePassword(body.Pass); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - if err := store.CreateUser(body.User, body.Pass, RoleAdmin); err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - log.Printf("console: admin account %q created", body.User) - setCookie(w, sess.issue(body.User, RoleAdmin), 7*24*3600) - writeJSON(w, map[string]bool{"ok": true}) - }) - - mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) { - // The lockout is per client address, not per account (see - // loginthrottle.go), so an attacker can lock out only themselves and never - // the operator. - key := loginClientKey(r) - if wait, ok := throttle.begin(key); !ok { - w.Header().Set("Retry-After", retryAfter(wait)) - jsonErr(w, http.StatusTooManyRequests, - fmt.Sprintf("too many failed logins; try again in %s seconds", retryAfter(wait))) - return - } - var body struct{ User, Pass string } - if !decodeJSON(w, r, &body) { - throttle.release(key) - return - } - role, ok := store.Authenticate(body.User, body.Pass) - if !ok { - time.Sleep(loginFailDelay) - if lock := throttle.fail(key); lock > 0 { - log.Printf("console: failed login for %q from %s; address locked for %v", body.User, r.RemoteAddr, lock) - } else { - log.Printf("console: failed login for %q from %s", body.User, r.RemoteAddr) - } - jsonErr(w, http.StatusUnauthorized, "wrong username or password") - return - } - throttle.success(key) - setCookie(w, sess.issue(body.User, role), 7*24*3600) - writeJSON(w, map[string]bool{"ok": true}) - }) - + mux.HandleFunc("POST /api/setup", a.handleSetup) + mux.HandleFunc("POST /api/login", a.handleLogin) mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) { - sess.drop(token(r)) - setCookie(w, "", -1) + a.sess.drop(sessionToken(r)) + setSessionCookie(w, "", -1) writeJSON(w, map[string]bool{"ok": true}) }) - // Changing your own password needs the old one. Viewers may do this too: it is // their account. - mux.HandleFunc("POST /api/password", write(func(w http.ResponseWriter, r *http.Request) { - sn, _ := current(r) - var body struct{ Old, New string } - if !decodeJSON(w, r, &body) { - return - } - if _, ok := store.Authenticate(sn.user, body.Old); !ok { - time.Sleep(time.Second) - jsonErr(w, http.StatusUnauthorized, "current password is wrong") - return - } - if err := store.SetPassword(sn.user, body.New); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - sess.dropUser(sn.user) - log.Printf("console: %q changed their password; their sessions were invalidated", sn.user) - writeJSON(w, map[string]bool{"ok": true}) - })) + mux.HandleFunc("POST /api/password", a.write(a.handlePassword)) +} - // ---- accounts and settings ---- +func (a *webApp) handleSetup(w http.ResponseWriter, r *http.Request) { + if !a.store.NeedsSetup() { + jsonErr(w, http.StatusConflict, "already set up") + return + } + if !sameOrigin(r) { + jsonErr(w, http.StatusForbidden, "cross-origin request refused") + return + } + var body struct{ User, Pass string } + if !decodeJSON(w, r, &body) { + return + } + if body.User == "" { + body.User = "admin" + } + if err := validateCredentials(body.User, body.Pass); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := a.store.CreateUser(body.User, body.Pass, RoleAdmin); err != nil { + jsonErr(w, http.StatusInternalServerError, err.Error()) + return + } + log.Printf("console: admin account %q created", body.User) + setSessionCookie(w, a.sess.issue(body.User, RoleAdmin), 7*24*3600) + writeJSON(w, map[string]bool{"ok": true}) +} +func validateCredentials(user, pass string) error { + if err := validateUsername(user); err != nil { + return err + } + return validatePassword(pass) +} + +func (a *webApp) handleLogin(w http.ResponseWriter, r *http.Request) { + // The lockout is per client address, not per account (see + // loginthrottle.go), so an attacker can lock out only themselves and never + // the operator. + key := loginClientKey(r) + if wait, ok := a.throttle.begin(key); !ok { + w.Header().Set("Retry-After", retryAfter(wait)) + jsonErr(w, http.StatusTooManyRequests, + fmt.Sprintf("too many failed logins; try again in %s seconds", retryAfter(wait))) + return + } + var body struct{ User, Pass string } + if !decodeJSON(w, r, &body) { + a.throttle.release(key) + return + } + role, ok := a.store.Authenticate(body.User, body.Pass) + if !ok { + a.loginFailed(w, r, key, body.User) + return + } + a.throttle.success(key) + setSessionCookie(w, a.sess.issue(body.User, role), 7*24*3600) + writeJSON(w, map[string]bool{"ok": true}) +} + +func (a *webApp) loginFailed(w http.ResponseWriter, r *http.Request, key, user string) { + time.Sleep(loginFailDelay) + if lock := a.throttle.fail(key); lock > 0 { + log.Printf("console: failed login for %q from %s; address locked for %v", user, r.RemoteAddr, lock) + } else { + log.Printf("console: failed login for %q from %s", user, r.RemoteAddr) + } + jsonErr(w, http.StatusUnauthorized, "wrong username or password") +} + +func (a *webApp) handlePassword(w http.ResponseWriter, r *http.Request) { + sn, _ := a.current(r) + var body struct{ Old, New string } + if !decodeJSON(w, r, &body) { + return + } + if _, ok := a.store.Authenticate(sn.user, body.Old); !ok { + time.Sleep(time.Second) + jsonErr(w, http.StatusUnauthorized, "current password is wrong") + return + } + if err := a.store.SetPassword(sn.user, body.New); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + a.sess.dropUser(sn.user) + log.Printf("console: %q changed their password; their sessions were invalidated", sn.user) + writeJSON(w, map[string]bool{"ok": true}) +} + +// ---- accounts and settings ---- + +func (a *webApp) registerUsers(mux *http.ServeMux) { // Who am I, and what may I do. The console asks this first and hides what the // answer says is unavailable — the server still enforces it, the UI just stops // offering buttons that would 403. - mux.HandleFunc("GET /api/me", guard(func(w http.ResponseWriter, r *http.Request) { - sn, _ := current(r) - writeJSON(w, map[string]any{ - "user": sn.user, - "role": sn.role, - "version": version, - "data_dir": cfg.DataDir, - "listen": cfg.Listen, - "port": portNum(cfg.Listen), - // What is running now, and what is stored for next time. They differ - // between a change and the restart that applies it, and the page has - // to be able to say which is which. - "bind": hostOf(cfg.Listen), - "bind_pending": store.ConsoleBind(), - "retention_days": cfg.RetentionDays, - "has_logo": func() bool { _, _, ok := store.Logo(); return ok }(), - }) - })) + mux.HandleFunc("GET /api/me", a.guard(a.handleMe)) + mux.HandleFunc("GET /api/users", a.guard(a.handleListUsers)) + mux.HandleFunc("POST /api/users", a.admin(a.handleCreateUser)) + mux.HandleFunc("POST /api/users/{name}/password", a.admin(a.handleResetPassword)) + mux.HandleFunc("POST /api/users/{name}/role", a.admin(a.handleSetRole)) + mux.HandleFunc("DELETE /api/users/{name}", a.admin(a.handleDeleteUser)) + // The console port is a stored setting, not a service argument, so it can be + // changed here. It cannot take effect until the listener is rebuilt, and + // rebuilding it underneath the request that asked would drop that request — so + // this records the intent and the answer says what to do next. + mux.HandleFunc("POST /api/settings/port", a.admin(a.handleSettingsPort)) +} - mux.HandleFunc("GET /api/users", guard(func(w http.ResponseWriter, r *http.Request) { - if sn, _ := current(r); sn.role != RoleAdmin { - jsonErr(w, http.StatusForbidden, "this account is read-only") - return - } - us, err := store.Users() - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if us == nil { - us = []User{} - } - writeJSON(w, us) - })) +func (a *webApp) hasLogo() bool { _, _, ok := a.store.Logo(); return ok } + +func (a *webApp) handleMe(w http.ResponseWriter, r *http.Request) { + sn, _ := a.current(r) + writeJSON(w, map[string]any{ + "user": sn.user, + "role": sn.role, + "version": version, + "data_dir": a.cfg.DataDir, + "listen": a.cfg.Listen, + "port": portNum(a.cfg.Listen), + // What is running now, and what is stored for next time. They differ + // between a change and the restart that applies it, and the page has + // to be able to say which is which. + "bind": hostOf(a.cfg.Listen), + "bind_pending": a.store.ConsoleBind(), + "retention_days": a.cfg.RetentionDays, + "has_logo": a.hasLogo(), + }) +} - userErr := func(w http.ResponseWriter, err error) bool { - switch { - case err == nil: - return false - case errors.Is(err, errUserExists), errors.Is(err, errLastAdmin): - jsonErr(w, http.StatusConflict, err.Error()) - case errors.Is(err, errUserNotFound): - jsonErr(w, http.StatusNotFound, err.Error()) - default: - jsonErr(w, http.StatusBadRequest, err.Error()) - } - return true +func (a *webApp) handleListUsers(w http.ResponseWriter, r *http.Request) { + if sn, _ := a.current(r); sn.role != RoleAdmin { + jsonErr(w, http.StatusForbidden, "this account is read-only") + return + } + us, err := a.store.Users() + if err != nil { + jsonErr(w, http.StatusInternalServerError, err.Error()) + return } + if us == nil { + us = []User{} + } + writeJSON(w, us) +} - mux.HandleFunc("POST /api/users", admin(func(w http.ResponseWriter, r *http.Request) { - var b struct{ Name, Pass, Role string } - if !decodeJSON(w, r, &b) { - return - } - if b.Role == "" { - b.Role = RoleViewer // the safe default: looking, not changing - } - if userErr(w, store.CreateUser(b.Name, b.Pass, b.Role)) { - return - } - log.Printf("console: account %q created with role %s", b.Name, b.Role) - writeJSON(w, map[string]bool{"ok": true}) - })) +// userErr answers an account error and reports whether there was one. +func userErr(w http.ResponseWriter, err error) bool { + switch { + case err == nil: + return false + case errors.Is(err, errUserExists), errors.Is(err, errLastAdmin): + jsonErr(w, http.StatusConflict, err.Error()) + case errors.Is(err, errUserNotFound): + jsonErr(w, http.StatusNotFound, err.Error()) + default: + jsonErr(w, http.StatusBadRequest, err.Error()) + } + return true +} - mux.HandleFunc("POST /api/users/{name}/password", admin(func(w http.ResponseWriter, r *http.Request) { - name := r.PathValue("name") - var b struct{ Pass string } - if !decodeJSON(w, r, &b) { - return - } - if userErr(w, store.SetPassword(name, b.Pass)) { - return - } - sess.dropUser(name) - log.Printf("console: password reset for %q; their sessions were invalidated", name) - writeJSON(w, map[string]bool{"ok": true}) - })) +func (a *webApp) handleCreateUser(w http.ResponseWriter, r *http.Request) { + var b struct{ Name, Pass, Role string } + if !decodeJSON(w, r, &b) { + return + } + if b.Role == "" { + b.Role = RoleViewer // the safe default: looking, not changing + } + if userErr(w, a.store.CreateUser(b.Name, b.Pass, b.Role)) { + return + } + log.Printf("console: account %q created with role %s", b.Name, b.Role) + writeJSON(w, map[string]bool{"ok": true}) +} - mux.HandleFunc("POST /api/users/{name}/role", admin(func(w http.ResponseWriter, r *http.Request) { - name := r.PathValue("name") - var b struct{ Role string } - if !decodeJSON(w, r, &b) { - return - } - if userErr(w, store.SetRole(name, b.Role)) { - return - } - // The role is carried in the session, so it has to be re-issued. - sess.dropUser(name) - log.Printf("console: %q is now %s", name, b.Role) - writeJSON(w, map[string]bool{"ok": true}) - })) +func (a *webApp) handleResetPassword(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var b struct{ Pass string } + if !decodeJSON(w, r, &b) { + return + } + if userErr(w, a.store.SetPassword(name, b.Pass)) { + return + } + a.sess.dropUser(name) + log.Printf("console: password reset for %q; their sessions were invalidated", name) + writeJSON(w, map[string]bool{"ok": true}) +} - mux.HandleFunc("DELETE /api/users/{name}", admin(func(w http.ResponseWriter, r *http.Request) { - name := r.PathValue("name") - if sn, _ := current(r); name == sn.user { - jsonErr(w, http.StatusConflict, "you cannot delete the account you are signed in with") - return - } - if userErr(w, store.DeleteUser(name)) { - return - } - sess.dropUser(name) - log.Printf("console: account %q deleted", name) - writeJSON(w, map[string]bool{"ok": true}) - })) +func (a *webApp) handleSetRole(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var b struct{ Role string } + if !decodeJSON(w, r, &b) { + return + } + if userErr(w, a.store.SetRole(name, b.Role)) { + return + } + // The role is carried in the session, so it has to be re-issued. + a.sess.dropUser(name) + log.Printf("console: %q is now %s", name, b.Role) + writeJSON(w, map[string]bool{"ok": true}) +} - // The console port is a stored setting, not a service argument, so it can be - // changed here. It cannot take effect until the listener is rebuilt, and - // rebuilding it underneath the request that asked would drop that request — so - // this records the intent and the answer says what to do next. - mux.HandleFunc("POST /api/settings/port", admin(func(w http.ResponseWriter, r *http.Request) { - var b struct { - Port int - Bind string - } - if !decodeJSON(w, r, &b) { - return - } - // Validate both before storing either. Half-applying this pair is how a - // service ends up bound to an address it cannot reach on a port nothing - // admits, with no console left to correct it from. - if b.Port != 0 { - if err := validatePortValue(b.Port); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - } - if b.Bind != "" { - if err := validateBind(b.Bind); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } +func (a *webApp) handleDeleteUser(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if sn, _ := a.current(r); name == sn.user { + jsonErr(w, http.StatusConflict, "you cannot delete the account you are signed in with") + return + } + if userErr(w, a.store.DeleteUser(name)) { + return + } + a.sess.dropUser(name) + log.Printf("console: account %q deleted", name) + writeJSON(w, map[string]bool{"ok": true}) +} + +func (a *webApp) handleSettingsPort(w http.ResponseWriter, r *http.Request) { + var b struct { + Port int + Bind string + } + if !decodeJSON(w, r, &b) { + return + } + // Validate both before storing either. Half-applying this pair is how a + // service ends up bound to an address it cannot reach on a port nothing + // admits, with no console left to correct it from. + if err := validateConsoleAddr(b.Port, b.Bind); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := a.storeConsoleAddr(b.Port, b.Bind); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + log.Printf("console: port will be %d after a restart", b.Port) + writeJSON(w, map[string]any{ + "ok": true, + "port": b.Port, + "bind": b.Bind, + "applied": false, + "note": "Restart the pingping service to apply it — the tray icon can do that, and it re-points the firewall rule at the same time.", + }) +} + +// validateConsoleAddr checks the port and bind address that were given; zero +// and empty mean "unchanged". +func validateConsoleAddr(port int, bind string) error { + if port != 0 { + if err := validatePortValue(port); err != nil { + return err } - if b.Port != 0 { - if err := store.SetConsolePort(b.Port); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } + } + if bind != "" { + return validateBind(bind) + } + return nil +} + +func (a *webApp) storeConsoleAddr(port int, bind string) error { + if port != 0 { + if err := a.store.SetConsolePort(port); err != nil { + return err } - if b.Bind != "" { - if err := store.SetConsoleBind(b.Bind); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - log.Printf("console: bind address will be %s after a restart", b.Bind) + } + if bind != "" { + if err := a.store.SetConsoleBind(bind); err != nil { + return err } - log.Printf("console: port will be %d after a restart", b.Port) - writeJSON(w, map[string]any{ - "ok": true, - "port": b.Port, - "bind": b.Bind, - "applied": false, - "note": "Restart the pingping service to apply it — the tray icon can do that, and it re-points the firewall rule at the same time.", - }) - })) + log.Printf("console: bind address will be %s after a restart", bind) + } + return nil +} - // ---- read ---- +// ---- read ---- +func (a *webApp) registerInfo(mux *http.ServeMux) { // Health is what the notification-area icon polls. It is unauthenticated, // because the tray has no session and cannot get one — so it is restricted to // loopback and carries counts only. No hostnames: the list of what a machine @@ -475,47 +537,147 @@ func newMux(cfg *Config, store *Store, run *Runner) http.Handler { // hand these counts to anyone the proxy serves. The tray talks to the port // directly and never sends forwarding headers, so their presence means the // request came from somewhere else. - mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) { - if !isLoopback(r) || forwarded(r) { - http.NotFound(w, r) - return - } - targets := run.Targets() - down := 0 - since := time.Now().Add(-time.Hour).Unix() - for _, t := range targets { - if rec := store.Recent(t.Name, since); len(rec) > 0 && rec[len(rec)-1].R == 0 { - down++ - } + mux.HandleFunc("GET /api/health", a.handleHealth) + // The catalogue, one language at a time. Unauthenticated on purpose: the sign-in + // and first-run screens need it before anyone has a session, and it contains + // nothing but interface text. + mux.HandleFunc("GET /api/i18n", func(w http.ResponseWriter, r *http.Request) { + lang := normalizeLang(r.URL.Query().Get("lang")) + if lang == "" { + lang = acceptLanguage(r.Header.Get("Accept-Language")) } - // Both ports, so the tray can follow a change it did not make. It polls - // the effective one; if configured differs, a restart is pending and the - // tray knows where to look afterwards. - configured := store.ConsolePort() - if configured == 0 { - configured = portNum(cfg.Listen) + w.Header().Set("Cache-Control", "no-cache") + writeJSON(w, bundle(lang)) + }) + mux.HandleFunc("GET /api/version", a.handleVersion) + // The probe types this build can run and each type's own options, so the editor + // builds its type list and form from the server (the same endpoint fogping has). + mux.HandleFunc("GET /api/probe-types", a.guard(func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, probeTypes()) + })) + mux.HandleFunc("GET /api/targets", a.guard(a.handleTargets)) + mux.HandleFunc("GET /api/series", a.guard(a.handleSeries)) +} + +func (a *webApp) handleHealth(w http.ResponseWriter, r *http.Request) { + if !isLoopback(r) || forwarded(r) { + http.NotFound(w, r) + return + } + targets := a.run.Targets() + down := 0 + since := time.Now().Add(-time.Hour).Unix() + for _, t := range targets { + if rec := a.store.Recent(t.Name, since); len(rec) > 0 && rec[len(rec)-1].R == 0 { + down++ } - writeJSON(w, map[string]any{ - "version": version, - "needs_setup": store.NeedsSetup(), - "targets": len(targets), - "down": down, - "port": portNum(cfg.Listen), - "port_configured": configured, - }) + } + // Both ports, so the tray can follow a change it did not make. It polls + // the effective one; if configured differs, a restart is pending and the + // tray knows where to look afterwards. + configured := a.store.ConsolePort() + if configured == 0 { + configured = portNum(a.cfg.Listen) + } + writeJSON(w, map[string]any{ + "version": version, + "needs_setup": a.store.NeedsSetup(), + "targets": len(targets), + "down": down, + "port": portNum(a.cfg.Listen), + "port_configured": configured, }) +} - // The catalogue, one language at a time. Unauthenticated on purpose: the sign-in - // and first-run screens need it before anyone has a session, and it contains - // nothing but interface text. - // ---- brand ---- +func (a *webApp) handleVersion(w http.ResponseWriter, r *http.Request) { + // Anonymous callers get the version and nothing else: retention, whether a + // logo is set and whether setup is still pending describe the instance, and + // nothing before sign-in reads them (the console only loads once signed in, + // and the first-run redirect is decided server-side). + if !a.authed(r) { + writeJSON(w, map[string]any{"version": version}) + return + } + writeJSON(w, map[string]any{ + "version": version, + "retention_days": a.cfg.RetentionDays, + "hot_days": a.cfg.HotDays, // 原始样本保留天数,控制台据此判断对比段读原始层还是小时汇总 + "has_logo": a.hasLogo(), + "needs_setup": a.store.NeedsSetup(), + "authed": a.authed(r), + }) +} + +// targetItem is one row of GET /api/targets. +type targetItem struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Host string `json:"host"` + Port int `json:"port"` + Addr string `json:"addr"` + IntervalSec int `json:"interval_sec"` // effective + IntervalSet int `json:"interval_set"` // explicit override, 0 = from pace + Pace string `json:"pace"` + Options map[string]any `json:"options,omitempty"` + Down bool `json:"down"` + Last1h Stats `json:"last_1h"` + Last24h Stats `json:"last_24h"` +} +func (a *webApp) handleTargets(w http.ResponseWriter, r *http.Request) { + now := time.Now() + out := []targetItem{} + for _, t := range a.run.Targets() { + out = append(out, a.targetItem(t, now)) + } + writeJSON(w, out) +} + +func (a *webApp) targetItem(t TargetCfg, now time.Time) targetItem { + iv, _ := probeParams(t, a.cfg.Probe) + pace := t.Pace + if pace == "" { + pace = "normal" + } + rec := a.store.Recent(t.Name, now.Add(-time.Hour).Unix()) + down := len(rec) > 0 && rec[len(rec)-1].R == 0 + return targetItem{ + ID: t.ID, Name: t.Name, Type: t.Type, Host: t.Host, Port: t.Port, Addr: targetAddr(t), + IntervalSec: int(iv.Seconds()), IntervalSet: t.IntervalSec, Pace: pace, Options: t.Options, Down: down, + Last1h: calcStats(rec), + Last24h: calcStats(a.store.Recent(t.Name, now.Add(-24*time.Hour).Unix())), + } +} + +// handleSeries returns raw rounds for smoke. Supports either minutes=N (recent +// window) or from/to unix (arbitrary range). No thinning: every sample is +// returned as stored. +func (a *webApp) handleSeries(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + name := q.Get("target") + from, _ := strconv.ParseInt(q.Get("from"), 10, 64) + to, _ := strconv.ParseInt(q.Get("to"), 10, 64) + if from == 0 || to == 0 { + minutes, _ := strconv.Atoi(q.Get("minutes")) + if minutes <= 0 || minutes > 432000 { // up to 300 days + minutes = 360 + } + to = time.Now().Unix() + from = to - int64(minutes)*60 + } + writeJSON(w, a.store.ReadRange(r.Context(), name, from, to)) +} + +// ---- brand ---- + +func (a *webApp) registerBrand(mux *http.ServeMux) { // The logo is served from the database rather than as a static file so a // portable copy stays one directory. nosniff and an explicit Content-Type // matter here more than elsewhere: these bytes came from a user, and the // browser must not be free to decide they are something executable. - mux.HandleFunc("GET /api/brand/logo", guard(func(w http.ResponseWriter, r *http.Request) { - raw, ct, ok := store.Logo() + mux.HandleFunc("GET /api/brand/logo", a.guard(func(w http.ResponseWriter, r *http.Request) { + raw, ct, ok := a.store.Logo() if !ok { jsonErr(w, http.StatusNotFound, "no custom logo") return @@ -526,207 +688,123 @@ func newMux(cfg *Config, store *Store, run *Runner) http.Handler { w.Header().Set("Cache-Control", "no-cache") w.Write(raw) })) - - mux.HandleFunc("POST /api/brand/logo", admin(func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("POST /api/brand/logo", a.admin(func(w http.ResponseWriter, r *http.Request) { raw, err := io.ReadAll(io.LimitReader(r.Body, maxLogoBytes+1)) if err != nil { jsonErr(w, http.StatusBadRequest, "could not read the upload") return } - if err := store.SetLogo(raw); err != nil { + if err := a.store.SetLogo(raw); err != nil { jsonErr(w, http.StatusBadRequest, err.Error()) return } log.Printf("console: custom logo set (%d bytes)", len(raw)) writeJSON(w, map[string]bool{"ok": true}) })) - - mux.HandleFunc("DELETE /api/brand/logo", admin(func(w http.ResponseWriter, r *http.Request) { - if err := store.ClearLogo(); err != nil { + mux.HandleFunc("DELETE /api/brand/logo", a.admin(func(w http.ResponseWriter, r *http.Request) { + if err := a.store.ClearLogo(); err != nil { jsonErr(w, http.StatusInternalServerError, err.Error()) return } log.Printf("console: custom logo cleared") writeJSON(w, map[string]bool{"ok": true}) })) +} - mux.HandleFunc("GET /api/i18n", func(w http.ResponseWriter, r *http.Request) { - lang := normalizeLang(r.URL.Query().Get("lang")) - if lang == "" { - lang = acceptLanguage(r.Header.Get("Accept-Language")) - } - w.Header().Set("Cache-Control", "no-cache") - writeJSON(w, bundle(lang)) - }) - - mux.HandleFunc("GET /api/version", func(w http.ResponseWriter, r *http.Request) { - // Anonymous callers get the version and nothing else: retention, whether a - // logo is set and whether setup is still pending describe the instance, and - // nothing before sign-in reads them (the console only loads once signed in, - // and the first-run redirect is decided server-side). - if !authed(r) { - writeJSON(w, map[string]any{"version": version}) - return - } - writeJSON(w, map[string]any{ - "version": version, - "retention_days": cfg.RetentionDays, - "hot_days": cfg.HotDays, // 原始样本保留天数,控制台据此判断对比段读原始层还是小时汇总 - "has_logo": func() bool { _, _, ok := store.Logo(); return ok }(), - "needs_setup": store.NeedsSetup(), - "authed": authed(r), - }) - }) +// ---- target CRUD ---- +// Every write goes to the database first, then Runner.Reload picks it up, so a +// half-applied change cannot exist: either the row is there and probing, or it +// is not there at all. - // The probe types this build can run and each type's own options, so the editor - // builds its type list and form from the server (the same endpoint fogping has). - mux.HandleFunc("GET /api/probe-types", guard(func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, probeTypes()) +func (a *webApp) registerTargets(mux *http.ServeMux) { + mux.HandleFunc("POST /api/targets", a.admin(a.handleCreateTarget)) + // Export and import of the target list as a "netping-targets" file (see + // targetsio.go). Export is gated like GET /api/targets, so a viewer can take a + // copy of what they can already read; import changes what this host probes and + // is admin-only, like every other target write. + mux.HandleFunc("GET /api/targets/export", a.guard(func(w http.ResponseWriter, r *http.Request) { + serveTargetsExport(w, a.store, "pingping") })) - - mux.HandleFunc("GET /api/targets", guard(func(w http.ResponseWriter, r *http.Request) { - now := time.Now() - type item struct { - ID int64 `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Host string `json:"host"` - Port int `json:"port"` - Addr string `json:"addr"` - IntervalSec int `json:"interval_sec"` // effective - IntervalSet int `json:"interval_set"` // explicit override, 0 = from pace - Pace string `json:"pace"` - Options map[string]any `json:"options,omitempty"` - Down bool `json:"down"` - Last1h Stats `json:"last_1h"` - Last24h Stats `json:"last_24h"` - } - out := []item{} - for _, t := range run.Targets() { - iv, _ := probeParams(t, cfg.Probe) - pace := t.Pace - if pace == "" { - pace = "normal" - } - rec := store.Recent(t.Name, now.Add(-time.Hour).Unix()) - down := len(rec) > 0 && rec[len(rec)-1].R == 0 - out = append(out, item{ - ID: t.ID, Name: t.Name, Type: t.Type, Host: t.Host, Port: t.Port, Addr: targetAddr(t), - IntervalSec: int(iv.Seconds()), IntervalSet: t.IntervalSec, Pace: pace, Options: t.Options, Down: down, - Last1h: calcStats(rec), - Last24h: calcStats(store.Recent(t.Name, now.Add(-24*time.Hour).Unix())), - }) - } - writeJSON(w, out) + mux.HandleFunc("POST /api/targets/import", a.admin(func(w http.ResponseWriter, r *http.Request) { + serveTargetsImport(w, r, a.store, a.run) })) + mux.HandleFunc("PUT /api/targets/{id}", a.admin(a.handleUpdateTarget)) + mux.HandleFunc("DELETE /api/targets/{id}", a.admin(a.handleDeleteTarget)) +} - // raw rounds for smoke. Supports either minutes=N (recent window) or from/to unix - // (arbitrary range). No thinning: every sample is returned as stored. - mux.HandleFunc("GET /api/series", guard(func(w http.ResponseWriter, r *http.Request) { - q := r.URL.Query() - name := q.Get("target") - from, _ := strconv.ParseInt(q.Get("from"), 10, 64) - to, _ := strconv.ParseInt(q.Get("to"), 10, 64) - if from == 0 || to == 0 { - minutes, _ := strconv.Atoi(q.Get("minutes")) - if minutes <= 0 || minutes > 432000 { // up to 300 days - minutes = 360 - } - to = time.Now().Unix() - from = to - int64(minutes)*60 - } - writeJSON(w, store.ReadRange(r.Context(), name, from, to)) - })) +func targetID(w http.ResponseWriter, r *http.Request) (int64, bool) { + n, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil || n <= 0 { + jsonErr(w, http.StatusBadRequest, "bad id") + return 0, false + } + return n, true +} - // ---- target CRUD ---- - // Every write goes to the database first, then Runner.Reload picks it up, so a - // half-applied change cannot exist: either the row is there and probing, or it - // is not there at all. +func decodeTarget(w http.ResponseWriter, r *http.Request) (TargetCfg, bool) { + // Strict: an unknown field is a typo ("interval" for "interval_sec"), and + // accepting it would create the target with a setting the caller never + // asked for, with a 200 that says everything went fine. + var t TargetCfg + if !decodeJSONStrict(w, r, &t, targetFields) { + return t, false + } + if err := normalizeTarget(&t); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return t, false + } + return t, true +} - targetID := func(w http.ResponseWriter, r *http.Request) (int64, bool) { - n, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil || n <= 0 { - jsonErr(w, http.StatusBadRequest, "bad id") - return 0, false - } - return n, true - } - decodeTarget := func(w http.ResponseWriter, r *http.Request) (TargetCfg, bool) { - // Strict: an unknown field is a typo ("interval" for "interval_sec"), and - // accepting it would create the target with a setting the caller never - // asked for, with a 200 that says everything went fine. - var t TargetCfg - if !decodeJSONStrict(w, r, &t, targetFields) { - return t, false - } - if err := normalizeTarget(&t); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return t, false - } - return t, true - } - done := func(w http.ResponseWriter, t TargetCfg, err error, verb string) { - switch { - case errors.Is(err, errNameTaken), errors.Is(err, errNameDeleted): - jsonErr(w, http.StatusConflict, err.Error()) - case errors.Is(err, errNotFound): - jsonErr(w, http.StatusNotFound, err.Error()) - case err != nil: - log.Printf("target %s: %v", verb, err) - jsonErr(w, http.StatusInternalServerError, err.Error()) - default: - if err := run.Reload(); err != nil { - log.Printf("reload after %s: %v", verb, err) - } - log.Printf("console: target %s %q (%s)", verb, t.Name, targetAddr(t)) - writeJSON(w, t) - } +func (a *webApp) done(w http.ResponseWriter, t TargetCfg, err error, verb string) { + switch { + case errors.Is(err, errNameTaken), errors.Is(err, errNameDeleted): + jsonErr(w, http.StatusConflict, err.Error()) + case errors.Is(err, errNotFound): + jsonErr(w, http.StatusNotFound, err.Error()) + case err != nil: + log.Printf("target %s: %v", verb, err) + jsonErr(w, http.StatusInternalServerError, err.Error()) + default: + if err := a.run.Reload(); err != nil { + log.Printf("reload after %s: %v", verb, err) + } + log.Printf("console: target %s %q (%s)", verb, t.Name, targetAddr(t)) + writeJSON(w, t) } +} - mux.HandleFunc("POST /api/targets", admin(func(w http.ResponseWriter, r *http.Request) { - if t, ok := decodeTarget(w, r); ok { - t, err := store.CreateTarget(t) - done(w, t, err, "created") - } - })) - // Export and import of the target list as a "netping-targets" file (see - // targetsio.go). Export is gated like GET /api/targets, so a viewer can take a - // copy of what they can already read; import changes what this host probes and - // is admin-only, like every other target write. - mux.HandleFunc("GET /api/targets/export", guard(func(w http.ResponseWriter, r *http.Request) { - serveTargetsExport(w, store, "pingping") - })) - mux.HandleFunc("POST /api/targets/import", admin(func(w http.ResponseWriter, r *http.Request) { - serveTargetsImport(w, r, store, run) - })) - mux.HandleFunc("PUT /api/targets/{id}", admin(func(w http.ResponseWriter, r *http.Request) { - id, ok := targetID(w, r) - if !ok { - return - } - if t, ok := decodeTarget(w, r); ok { - t.ID = id - t, err := store.UpdateTarget(t) - done(w, t, err, "updated") - } - })) - mux.HandleFunc("DELETE /api/targets/{id}", admin(func(w http.ResponseWriter, r *http.Request) { - id, ok := targetID(w, r) - if !ok { - return - } - var t TargetCfg - for _, x := range run.Targets() { - if x.ID == id { - t = x - } - } - done(w, t, store.DeactivateTarget(id), "deleted") - })) +func (a *webApp) handleCreateTarget(w http.ResponseWriter, r *http.Request) { + if t, ok := decodeTarget(w, r); ok { + t, err := a.store.CreateTarget(t) + a.done(w, t, err, "created") + } +} - registerStats(mux, cfg.ZabbixToken, store, run) +func (a *webApp) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { + id, ok := targetID(w, r) + if !ok { + return + } + if t, ok := decodeTarget(w, r); ok { + t.ID = id + t, err := a.store.UpdateTarget(t) + a.done(w, t, err, "updated") + } +} - return securityHeaders(apiRules(mux)) +func (a *webApp) handleDeleteTarget(w http.ResponseWriter, r *http.Request) { + id, ok := targetID(w, r) + if !ok { + return + } + var t TargetCfg + for _, x := range a.run.Targets() { + if x.ID == id { + t = x + } + } + a.done(w, t, a.store.DeactivateTarget(id), "deleted") } func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {