From a7c9e0d955999a0b810df863e3dde5ac708947e4 Mon Sep 17 00:00:00 2001 From: githubflyideas <36397539+githubflyideas@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:16:43 +0900 Subject: [PATCH 1/2] Add OpenAPI spec, split newMux, Caps Lock hint --- .github/workflows/quality.yml | 37 ++ README.md | 1 + browser/.gitignore | 1 + browser/login_capslock.test.cjs | 73 ++++ browser/package-lock.json | 60 ++++ browser/package.json | 10 + browser_server_test.go | 29 ++ docs/API.md | 3 + docs/openapi.yaml | 614 ++++++++++++++++++++++++++++++++ openapi_test.go | 161 +++++++++ static/login.html | 16 +- web.go | 555 ++++++++++++++++------------- 12 files changed, 1321 insertions(+), 239 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..f9df31e --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,37 @@ +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-file: go.mod } + - name: gocyclo (router stays small) + run: | + go install github.com/fzipp/gocyclo/cmd/gocyclo@v0.6.0 + gocyclo -over 15 web.go stats.go + - name: OpenAPI spec matches the routes + run: go test -count=1 -run 'TestOpenAPI|TestAPI' -v . + - 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 4dc80fd..e929bf1 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ Everything else lives in the **[full guide](docs/GUIDE.md)**: [reading the chart](docs/GUIDE.md#reading-the-chart) · [upgrading](docs/GUIDE.md#upgrading) · [troubleshooting](docs/GUIDE.md#troubleshooting) · +[HTTP API](docs/API.md) ([OpenAPI 3.1](docs/openapi.yaml)) · [build from source](docs/GUIDE.md#build-from-source) 🌐 [English / 中文 / Español / Français / Português / Deutsch / Русский / 日本語 / 한국어 / Bahasa Indonesia / Tiếng Việt / العربية / हिन्दी / বাংলা / اردو / Türkçe / ไทย](docs/LANGUAGES.md) 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..e5081a5 --- /dev/null +++ b/browser/login_capslock.test.cjs @@ -0,0 +1,73 @@ +// 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'); + +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'); + 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(), ''); + + 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..fd45d92 --- /dev/null +++ b/browser/package-lock.json @@ -0,0 +1,60 @@ +{ + "name": "fogping-browser-tests", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fogping-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..7defc00 --- /dev/null +++ b/browser/package.json @@ -0,0 +1,10 @@ +{ + "name": "fogping-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..d6a8f05 --- /dev/null +++ b/browser_server_test.go @@ -0,0 +1,29 @@ +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/") + } + srv := httptest.NewServer(newMux(&Config{}, nil, nil, map[string]string{"admin": "browser-test-password"})) + 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 1fde69b..b1b9577 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4,6 +4,9 @@ fogping's web UI and the Zabbix template talk to fogping through this API. The same rules hold in pingping 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..cad0253 --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,614 @@ +openapi: 3.1.0 +info: + title: fogping HTTP API + version: "1" + summary: The API the fogping web UI 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 `fogping_session` cookie from `POST /api/login` + when fogping was started with a login; without a login, anyone may call + those endpoints. `GET /api/stats` is the only endpoint that takes a bearer + token, and that token is read-only. + + `api_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 fogping instance serving this API (default port 8518). +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: targets + description: Read and change what is probed. + - name: data + description: Measurements. +security: + - session: [] +paths: + /: + get: + tags: [pages] + operationId: getIndex + summary: The web UI. + security: [] + responses: + "200": + description: The dashboard page. + content: + text/html: {} + "302": + description: Not signed in; redirects to `/login`. + headers: + Location: + schema: { type: string, const: /login } + "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 sign-in page. + content: + text/html: {} + "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/`). + security: [] + parameters: + - name: path + in: path + required: true + description: File path below `/static/`; may contain `/`. + schema: { type: string } + responses: + "200": + description: The file. + content: + "*/*": {} + "404": + description: No such file (plain text, not under `/api/`). + "405": + description: Wrong method (plain text; not under `/api/`). + /api/login: + post: + tags: [auth] + operationId: login + summary: Sign in and get the session cookie. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + user: { type: string } + pass: { type: string } + responses: + "200": + description: Signed in. + headers: + Set-Cookie: + description: "`fogping_session`; HttpOnly, SameSite=Lax, 7 days." + schema: { type: string } + content: + application/json: + schema: { $ref: "#/components/schemas/Ok" } + "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/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 (or no login configured) + also `retention_days`, `hot_days` and `editable`. + content: + application/json: + schema: + type: object + required: [version] + properties: + version: { type: string } + retention_days: { type: integer } + hot_days: { type: integer } + editable: { 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 (needs `--edit`). 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 (needs `--edit`). + 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 (needs `--edit`); 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 (needs `--edit`). + 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 93 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 fogping 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: fogping_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: Read-only instance (no `--edit`) or a cross-origin browser request. + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + NotFound: + description: No such target. + 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: The name is taken or belongs to a deleted target. + 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] + 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 spec (OPTIONS.md). } + 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, probe_errors] + properties: + rounds: { type: integer } + p50: { type: number } + p90: { type: number } + p99: { type: number } + loss_pct: { type: number } + bursts: { type: integer } + probe_errors: { 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 } + probe_error: { type: string, description: Why the latest round could not be measured. } + 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; 0 when the round could not be measured. } + 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. } + e: { type: string, description: Why the round could not be measured. } + 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, probe_errors] + 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] } + probe_errors: { type: integer } + StatsReport: + type: object + required: [window_sec, targets] + properties: + window_sec: { type: integer } + targets: { type: array, items: { $ref: "#/components/schemas/StatsTarget" } } diff --git a/openapi_test.go b/openapi_test.go new file mode 100644 index 0000000..5914e27 --- /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{StatsToken: "t"}, nil, 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 321eb3c..667121b 100644 --- a/static/login.html +++ b/static/login.html @@ -28,6 +28,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; @@ -44,7 +45,8 @@

fogping

Sign in to fogping

- + +

@@ -62,6 +64,18 @@

fogping

} else $('err').textContent = 'Wrong username or password'; } $('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') ? '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('keydown', e => { if (e.key === 'Enter') login(); }); diff --git a/web.go b/web.go index fa3ebee..23b6d23 100644 --- a/web.go +++ b/web.go @@ -64,47 +64,78 @@ func serveWeb(cfg *Config, store *Store, run *Runner, users map[string]string) e return http.ListenAndServe(cfg.Listen, newMux(cfg, store, run, users)) } +// webApp holds what the HTTP handlers share. newMux only wires routes; each +// area of the API registers its own, so no single function grows past a +// screenful. +type webApp struct { + cfg *Config + store *Store + run *Runner + users map[string]string + sess *sessions + throttle *loginThrottle +} + func newMux(cfg *Config, store *Store, run *Runner, users map[string]string) http.Handler { - sess := &sessions{m: map[string]time.Time{}} - throttle := newLoginThrottle() + return securityHeaders(apiRules(buildMux(cfg, store, run, users))) +} + +// 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, users map[string]string) *http.ServeMux { + a := &webApp{cfg: cfg, store: store, run: run, users: users, + sess: &sessions{m: map[string]time.Time{}}, throttle: newLoginThrottle()} mux := http.NewServeMux() + a.registerPages(mux) + a.registerAuth(mux) + a.registerInfo(mux) + a.registerTargets(mux) + mux.HandleFunc("GET /api/series", a.guard(a.handleSeries)) + registerStats(mux, cfg.StatsToken, store, run) + return mux +} - authed := func(r *http.Request) bool { - if len(users) == 0 { - return true - } - c, err := r.Cookie("fogping_session") - return err == nil && sess.valid(c.Value) +func (a *webApp) authed(r *http.Request) bool { + if len(a.users) == 0 { + return true } - 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) - } + c, err := r.Cookie("fogping_session") + return err == nil && a.sess.valid(c.Value) +} + +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 } - } - page := func(name string) http.HandlerFunc { - b, _ := staticFS.ReadFile("static/" + name) - csp := pageCSP(b) - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Content-Security-Policy", csp) - w.Write(b) + 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) } } +} + +// page serves one embedded HTML file with a CSP that allows its own inline +// scripts by hash. +func page(name string) http.HandlerFunc { + b, _ := staticFS.ReadFile("static/" + name) + csp := pageCSP(b) + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Content-Security-Policy", csp) + w.Write(b) + } +} +func (a *webApp) registerPages(mux *http.ServeMux) { index := page("index.html") // 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 !authed(r) { + if !a.authed(r) { http.Redirect(w, r, "/login", http.StatusFound) return } @@ -112,251 +143,299 @@ func newMux(cfg *Config, store *Store, run *Runner, users map[string]string) htt }) mux.HandleFunc("GET /login", page("login.html")) mux.Handle("GET /static/", http.FileServer(http.FS(staticFS))) +} +func (a *webApp) registerAuth(mux *http.ServeMux) { // login: constant-time compare, 1s delay on failure, and a per-address lockout // after repeated failures (see loginthrottle.go). - mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) { - // Before the throttle: this refuses a request that carries no credentials at - // all, so it must not take the address's one login slot (begin) or count as - // a guess. - if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" { - jsonErr(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json") - return - } - key := loginClientKey(r) - if wait, ok := throttle.begin(key); !ok { - w.Header().Set("Retry-After", retryAfter(wait)) - jsonErr(w, http.StatusTooManyRequests, "too many failed logins, try again later") - return - } - var body struct{ User, Pass string } - if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&body); err != nil { - var tooBig *http.MaxBytesError - if errors.As(err, &tooBig) { - throttle.fail(key) // release the slot taken by begin; junk of this size is abuse, so it counts - jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") - return - } - // Anything else unreadable falls through as an empty login and fails - // like a wrong password, so the throttle counts it. - } - want, ok := users[body.User] - if len(users) == 0 || !ok || - subtle.ConstantTimeCompare([]byte(body.Pass), []byte(want)) != 1 { - time.Sleep(loginFailDelay) - if lock := throttle.fail(key); lock > 0 { - log.Printf("web login failed for %q from %s; address locked for %v", body.User, r.RemoteAddr, lock) - } else { - log.Printf("web login failed for %q from %s", body.User, r.RemoteAddr) - } - jsonErr(w, http.StatusUnauthorized, "wrong username or password") + mux.HandleFunc("POST /api/login", a.handleLogin) + mux.HandleFunc("POST /api/logout", a.handleLogout) +} + +func (a *webApp) handleLogin(w http.ResponseWriter, r *http.Request) { + // Before the throttle: this refuses a request that carries no credentials at + // all, so it must not take the address's one login slot (begin) or count as + // a guess. + if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" { + jsonErr(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json") + return + } + key := loginClientKey(r) + if wait, ok := a.throttle.begin(key); !ok { + w.Header().Set("Retry-After", retryAfter(wait)) + jsonErr(w, http.StatusTooManyRequests, "too many failed logins, try again later") + return + } + var body struct{ User, Pass string } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&body); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + a.throttle.fail(key) // release the slot taken by begin; junk of this size is abuse, so it counts + jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") return } - throttle.success(key) - http.SetCookie(w, &http.Cookie{Name: "fogping_session", Value: sess.issue(), - Path: "/", HttpOnly: true, MaxAge: 7 * 24 * 3600, SameSite: http.SameSiteLaxMode}) - writeJSON(w, map[string]bool{"ok": true}) - }) - mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) { - if c, err := r.Cookie("fogping_session"); err == nil { - sess.revoke(c.Value) // otherwise the token stays valid until it expires - } - http.SetCookie(w, &http.Cookie{Name: "fogping_session", Value: "", Path: "/", MaxAge: -1}) - writeJSON(w, map[string]bool{"ok": true}) - }) + // Anything else unreadable falls through as an empty login and fails + // like a wrong password, so the throttle counts it. + } + if !a.checkPassword(body.User, body.Pass) { + a.loginFailed(w, r, key, body.User) + return + } + a.throttle.success(key) + http.SetCookie(w, &http.Cookie{Name: "fogping_session", Value: a.sess.issue(), + Path: "/", HttpOnly: true, MaxAge: 7 * 24 * 3600, SameSite: http.SameSiteLaxMode}) + writeJSON(w, map[string]bool{"ok": true}) +} + +func (a *webApp) checkPassword(user, pass string) bool { + want, ok := a.users[user] + return len(a.users) != 0 && ok && + subtle.ConstantTimeCompare([]byte(pass), []byte(want)) == 1 +} +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("web login failed for %q from %s; address locked for %v", user, r.RemoteAddr, lock) + } else { + log.Printf("web login failed for %q from %s", user, r.RemoteAddr) + } + jsonErr(w, http.StatusUnauthorized, "wrong username or password") +} + +func (a *webApp) handleLogout(w http.ResponseWriter, r *http.Request) { + if c, err := r.Cookie("fogping_session"); err == nil { + a.sess.revoke(c.Value) // otherwise the token stays valid until it expires + } + http.SetCookie(w, &http.Cookie{Name: "fogping_session", Value: "", Path: "/", MaxAge: -1}) + writeJSON(w, map[string]bool{"ok": true}) +} + +func (a *webApp) registerInfo(mux *http.ServeMux) { // version is public (it is in every release download anyway); the instance's // settings are not, once a login is configured. mux.HandleFunc("GET /api/version", func(w http.ResponseWriter, r *http.Request) { - if !authed(r) { + if !a.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, // raw-sample days: the compare overlay asks for hourly rows beyond this - "editable": cfg.Editable}) + writeJSON(w, map[string]any{"version": version, "retention_days": a.cfg.RetentionDays, + "hot_days": a.cfg.HotDays, // raw-sample days: the compare overlay asks for hourly rows beyond this + "editable": a.cfg.Editable}) }) - - mux.HandleFunc("GET /api/probe-types", guard(func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/probe-types", a.guard(func(w http.ResponseWriter, r *http.Request) { writeJSON(w, probeTypes()) })) +} - 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"` - ProbeError string `json:"probe_error,omitempty"` // why the latest round could not be measured - 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: the last measured round got no reply. A round that could not be - // measured says nothing about the target; it is reported as probe_error. - down, probeErr := false, "" - for i := len(rec) - 1; i >= 0; i-- { - if rec[i].S == 0 { - if i == len(rec)-1 { - probeErr = rec[i].E - } - continue - } - down = rec[i].R == 0 - break - } - 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, ProbeError: probeErr, - Last1h: calcStats(rec), - Last24h: calcStats(store.Recent(t.Name, now.Add(-24*time.Hour).Unix())), - }) - } - writeJSON(w, out) - })) +// 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"` + ProbeError string `json:"probe_error,omitempty"` // why the latest round could not be measured + Last1h Stats `json:"last_1h"` + Last24h Stats `json:"last_24h"` +} - // Target CRUD. Always routed so a read-only instance answers with a reason - // instead of a bare 405; every write goes DB first, then Runner.Reload. - write := func(h func(w http.ResponseWriter, r *http.Request, id int64)) http.HandlerFunc { - return guard(func(w http.ResponseWriter, r *http.Request) { - if !cfg.Editable { - jsonErr(w, http.StatusForbidden, "read-only: restart fogping with --edit to change targets") - return - } - if !sameOrigin(r) { - jsonErr(w, http.StatusForbidden, "cross-origin request refused") - return - } - var id int64 - if v := r.PathValue("id"); v != "" { - n, err := strconv.ParseInt(v, 10, 64) - if err != nil || n <= 0 { - jsonErr(w, http.StatusBadRequest, "bad id") - return - } - id = n +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, probeErr := latestState(rec) + 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, ProbeError: probeErr, + Last1h: calcStats(rec), + Last24h: calcStats(a.store.Recent(t.Name, now.Add(-24*time.Hour).Unix())), + } +} + +// latestState: down means the last measured round got no reply. A round that +// could not be measured says nothing about the target; it is reported as +// probe_error. +func latestState(rec []Round) (down bool, probeErr string) { + for i := len(rec) - 1; i >= 0; i-- { + if rec[i].S == 0 { + if i == len(rec)-1 { + probeErr = rec[i].E } - h(w, r, id) - }) + continue + } + return rec[i].R == 0, probeErr } - decode := func(w http.ResponseWriter, r *http.Request) (TargetCfg, bool) { - var t TargetCfg - // JSON content type forces a CORS preflight on cross-site requests, which we - // never answer — so a form on another site can't drive these endpoints. - if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" { - jsonErr(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json") - return t, false + return false, probeErr +} + +// write gates every target change. Always routed so a read-only instance +// answers with a reason instead of a bare 405; every write goes DB first, then +// Runner.Reload. +func (a *webApp) write(h func(w http.ResponseWriter, r *http.Request, id int64)) http.HandlerFunc { + return a.guard(func(w http.ResponseWriter, r *http.Request) { + if !a.cfg.Editable { + jsonErr(w, http.StatusForbidden, "read-only: restart fogping with --edit to change targets") + return } - // Unknown fields are refused: a typo such as "interval" for "interval_sec" - // would otherwise create the target with a setting nobody asked for. - dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)) - dec.DisallowUnknownFields() - if err := dec.Decode(&t); err != nil { - var tooBig *http.MaxBytesError - if errors.As(err, &tooBig) { - jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") - return t, false - } - msg := "bad JSON: " + err.Error() - if f, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok { - msg = "unknown field " + f + "; accepted fields: id, name, type, host, port, pace, interval_sec, options" - } - jsonErr(w, http.StatusBadRequest, msg) - return t, false + if !sameOrigin(r) { + jsonErr(w, http.StatusForbidden, "cross-origin request refused") + return } - if err := normalizeTarget(&t); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return t, false + id, ok := pathID(w, r) + if !ok { + return } - return t, true + h(w, r, id) + }) +} + +// pathID reads the optional {id} path value; 0 when the route has none. +func pathID(w http.ResponseWriter, r *http.Request) (int64, bool) { + v := r.PathValue("id") + if v == "" { + return 0, 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("web: target %s %q (%s)", verb, t.Name, targetAddr(t)) - writeJSON(w, t) - } + n, err := strconv.ParseInt(v, 10, 64) + if err != nil || n <= 0 { + jsonErr(w, http.StatusBadRequest, "bad id") + return 0, false + } + return n, true +} + +func decodeTarget(w http.ResponseWriter, r *http.Request) (TargetCfg, bool) { + var t TargetCfg + // JSON content type forces a CORS preflight on cross-site requests, which we + // never answer — so a form on another site can't drive these endpoints. + if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" { + jsonErr(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json") + return t, false + } + // Unknown fields are refused: a typo such as "interval" for "interval_sec" + // would otherwise create the target with a setting nobody asked for. + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)) + dec.DisallowUnknownFields() + if err := dec.Decode(&t); err != nil { + badTargetJSON(w, err) + return t, false + } + if err := normalizeTarget(&t); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return t, false + } + return t, true +} + +func badTargetJSON(w http.ResponseWriter, err error) { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") + return } - mux.HandleFunc("POST /api/targets", write(func(w http.ResponseWriter, r *http.Request, _ int64) { - if t, ok := decode(w, r); ok { - t, err := store.CreateTarget(t) - done(w, t, err, "created") + msg := "bad JSON: " + err.Error() + if f, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok { + msg = "unknown field " + f + "; accepted fields: id, name, type, host, port, pace, interval_sec, options" + } + jsonErr(w, http.StatusBadRequest, msg) +} + +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("web: target %s %q (%s)", verb, t.Name, targetAddr(t)) + writeJSON(w, t) + } +} + +func (a *webApp) registerTargets(mux *http.ServeMux) { + mux.HandleFunc("GET /api/targets", a.guard(a.handleTargets)) + mux.HandleFunc("POST /api/targets", a.write(a.createTarget)) // Export and import of the target list as a "netping-targets" file (see // targetsio.go). Export is gated like GET /api/targets — the file says nothing // that list does not — so it works on a read-only instance too. Import changes // what this host probes, so it takes the same gate as every other write: // --edit, a session when users are configured, and a same-origin request. - mux.HandleFunc("GET /api/targets/export", guard(func(w http.ResponseWriter, r *http.Request) { - serveTargetsExport(w, store, "fogping") + mux.HandleFunc("GET /api/targets/export", a.guard(func(w http.ResponseWriter, r *http.Request) { + serveTargetsExport(w, a.store, "fogping") })) - mux.HandleFunc("POST /api/targets/import", write(func(w http.ResponseWriter, r *http.Request, _ int64) { - serveTargetsImport(w, r, store, run) - })) - mux.HandleFunc("PUT /api/targets/{id}", write(func(w http.ResponseWriter, r *http.Request, id int64) { - if t, ok := decode(w, r); ok { - t.ID = id - t, err := store.UpdateTarget(t) - done(w, t, err, "updated") - } - })) - mux.HandleFunc("DELETE /api/targets/{id}", write(func(w http.ResponseWriter, r *http.Request, id int64) { - var t TargetCfg - for _, x := range run.Targets() { - if x.ID == id { - t = x - } - } - done(w, t, store.DeactivateTarget(id), "deleted") + mux.HandleFunc("POST /api/targets/import", a.write(func(w http.ResponseWriter, r *http.Request, _ int64) { + serveTargetsImport(w, r, a.store, a.run) })) + mux.HandleFunc("PUT /api/targets/{id}", a.write(a.updateTarget)) + mux.HandleFunc("DELETE /api/targets/{id}", a.write(a.deleteTarget)) +} - // 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 > maxDays*1440 { // up to 93 days - minutes = 360 - } - to = time.Now().Unix() - from = to - int64(minutes)*60 - } - writeJSON(w, store.ReadRange(r.Context(), name, from, to)) - })) +func (a *webApp) createTarget(w http.ResponseWriter, r *http.Request, _ int64) { + if t, ok := decodeTarget(w, r); ok { + t, err := a.store.CreateTarget(t) + a.done(w, t, err, "created") + } +} - registerStats(mux, cfg.StatsToken, store, run) +func (a *webApp) updateTarget(w http.ResponseWriter, r *http.Request, id int64) { + 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) deleteTarget(w http.ResponseWriter, r *http.Request, id int64) { + var t TargetCfg + for _, x := range a.run.Targets() { + if x.ID == id { + t = x + } + } + a.done(w, t, a.store.DeactivateTarget(id), "deleted") +} + +// handleSeries returns raw rounds. 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 > maxDays*1440 { // up to 93 days + minutes = 360 + } + to = time.Now().Unix() + from = to - int64(minutes)*60 + } + writeJSON(w, a.store.ReadRange(r.Context(), name, from, to)) } // sameOrigin rejects browser requests whose Origin doesn't match the Host they were From eb056d81ade41f972caed94dd2171289d5e5bb91 Mon Sep 17 00:00:00 2001 From: githubflyideas <36397539+githubflyideas@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:28:32 +0900 Subject: [PATCH 2/2] OpenAPI: name the drift test's file --- docs/openapi.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/openapi.yaml b/docs/openapi.yaml index cad0253..82d26b3 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -14,7 +14,7 @@ info: those endpoints. `GET /api/stats` is the only endpoint that takes a bearer token, and that token is read-only. - `api_test.go` (`TestOpenAPIMatchesRoutes`) fails when this file and the + `openapi_test.go` (`TestOpenAPIMatchesRoutes`) fails when this file and the routes the code registers differ. license: name: Apache-2.0