From 65fd7ef8d614c49d70474e28fb844feb541d7179 Mon Sep 17 00:00:00 2001 From: githubflyideas <36397539+githubflyideas@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:28:41 +0900 Subject: [PATCH] Add OpenAPI spec, split newMux, Caps Lock hint --- .github/workflows/quality.yml | 28 ++ README.md | 4 + browser_server_test.go | 29 ++ docs/API.md | 3 + docs/openapi.yaml | 476 ++++++++++++++++++++++++++++ login_capslock.test.cjs | 73 +++++ openapi_test.go | 161 ++++++++++ package.json | 2 +- static/login.html | 16 +- web.go | 578 ++++++++++++++++++++-------------- 10 files changed, 1124 insertions(+), 246 deletions(-) create mode 100644 .github/workflows/quality.yml create mode 100644 browser_server_test.go create mode 100644 docs/openapi.yaml create mode 100644 login_capslock.test.cjs create mode 100644 openapi_test.go diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml new file mode 100644 index 0000000..7e0111e --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,28 @@ +name: quality + +# Keeps the router small and the OpenAPI spec valid. The spec-versus-routes +# test and the browser tests run in test.yml. +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' } + - name: OpenAPI lint + run: npx --yes @redocly/cli@2.82.0 lint docs/openapi.yaml diff --git a/README.md b/README.md index a638951..8c23bd6 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,10 @@ Web settings are stored in `targets/routing-options.json` and **override list-fi Off by default. `VRFPING_ZABBIX_TOKEN=<16+ characters> ./vrf-ping --zabbix user=admin passwd=...` (or `VRFPING_ZABBIX_TOKEN_FILE` / `--zabbix-token-file`) serves a read-only `GET /api/stats`: per target, the last five minutes' p50/p90/p99, loss, loss bursts and `probe_errors` (rounds that could not probe at all, such as a missing VRF). No hosts, VRFs, source addresses or raw samples. Use it with the [fogping Zabbix 7.0 template](https://github.com/githubflyideas/fogping/tree/main/zabbix/template_fogping/7.0): set `{$FOGPING.URL}` to `http://:8517`. Item ids derive from the target name, so a rename starts a new item. Without `--zabbix` nothing changes. `./vrf-ping --gen-token zabbix.token` makes a strong token in a file only you can read (it is never printed). +## HTTP API + +The web UI and the Zabbix template use one JSON API: [docs/API.md](docs/API.md) · OpenAPI 3.1: [docs/openapi.yaml](docs/openapi.yaml). + ## Data and upgrades `data/` contains daily JSONL files with a default retention of 300 days. Different VRF/source contexts have separate histories. Clearing both options returns to the target's default-context history. diff --git a/browser_server_test.go b/browser_server_test.go new file mode 100644 index 0000000..5653891 --- /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 login_capslock.test.cjs. It is skipped unless +// that test starts it, and stops when signalled (or after 5 minutes). +func TestBrowserServer(t *testing.T) { + if os.Getenv("BROWSER_TEST_SERVE") == "" { + t.Skip("started by login_capslock.test.cjs") + } + srv := httptest.NewServer(newMux(defaultConfig(), 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 47cbd39..13d7b55 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5,6 +5,9 @@ same rules hold in fogping and pingping, so a client written for one reads the others the same way. Targets themselves are not edited through the API: they come from `targets/*.list` (see the README). +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..7375f28 --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,476 @@ +openapi: 3.1.0 +info: + title: vrf-ping HTTP API + version: "1" + summary: The API the vrf-ping 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 `vrfping_session` cookie from `POST /api/login` + when vrf-ping was started with login users; without them, anyone may call + those endpoints. Session endpoints share five request slots; a request + that waits 30 seconds for one gets `503` with `Retry-After: 5`. + `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 vrf-ping 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: Version and configuration health. + - name: routing + description: Per-target VRF and source address. + - name: data + description: Targets and 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: "`vrfping_session`; HttpOnly, SameSite=Lax, 2 hours from issue." + 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. + security: [] + responses: + "200": + description: Version. + content: + application/json: + schema: + type: object + required: [version] + properties: + version: { type: string } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + /api/health: + get: + tags: [info] + operationId: getHealth + summary: Whether the target lists are applied in full. + responses: + "200": + description: Lines skipped at startup and the latest refused reload. + headers: + Cache-Control: + schema: { type: string, const: no-store } + content: + application/json: + schema: { $ref: "#/components/schemas/HealthReport" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "503": { $ref: "#/components/responses/Busy" } + /api/routing-options: + get: + tags: [routing] + operationId: getRoutingOptions + summary: A target's active and saved VRF and source address. + parameters: + - name: target + in: query + required: true + description: Target name. + schema: { type: string } + responses: + "200": + description: Routing as running, as saved, and whether a reload is pending. + headers: + Cache-Control: + schema: { type: string, const: no-store } + content: + application/json: + schema: + type: object + required: [editable, target, saved_target, pending_reload] + properties: + editable: { type: boolean, description: True when login users are configured. } + target: { $ref: "#/components/schemas/Target" } + saved_target: { $ref: "#/components/schemas/Target" } + pending_reload: { type: boolean } + "401": { $ref: "#/components/responses/Unauthorized" } + "404": { $ref: "#/components/responses/NotFound" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "500": { $ref: "#/components/responses/Internal" } + "503": { $ref: "#/components/responses/Busy" } + put: + tags: [routing] + operationId: putRoutingOptions + summary: Save a target's VRF and source address; applied by the next reload. + description: > + Needs login users to be configured, a browser `Origin` equal to this + host (and `Sec-Fetch-Site: same-origin` when sent), and a JSON body. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name, vrf, source_address] + properties: + name: { type: string, minLength: 1 } + vrf: { type: string, description: Empty for the default table. } + source_address: { type: string, description: Empty for automatic. } + responses: + "200": + description: Saved. + headers: + Cache-Control: + schema: { type: string, const: no-store } + content: + application/json: + schema: + type: object + required: [saved, pending_reload, target] + properties: + saved: { type: boolean, const: true } + pending_reload: { type: boolean, const: true } + target: { $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" } + "413": { $ref: "#/components/responses/TooLarge" } + "415": { $ref: "#/components/responses/UnsupportedMediaType" } + "500": { $ref: "#/components/responses/Internal" } + "503": { $ref: "#/components/responses/Busy" } + /api/targets: + get: + tags: [data] + operationId: listTargets + summary: Every target with its last-hour and last-day summary, routing and latest probe error. + responses: + "200": + description: Targets; `null` when none has history yet. + content: + application/json: + schema: + type: [array, "null"] + items: { $ref: "#/components/schemas/TargetItem" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "503": { $ref: "#/components/responses/Busy" } + /api/series: + get: + tags: [data] + operationId: getSeries + summary: Every stored round for one target in a window. + 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: Rounds, oldest first; `null` when there are none. + content: + application/json: + schema: + type: [array, "null"] + items: { $ref: "#/components/schemas/Round" } + "401": { $ref: "#/components/responses/Unauthorized" } + "405": { $ref: "#/components/responses/MethodNotAllowed" } + "503": { $ref: "#/components/responses/Busy" } + /api/stats: + get: + tags: [data] + operationId: getStats + summary: Per-target summary of the last 5 minutes, for Zabbix. + description: Registered only when vrf-ping 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: vrfping_session + bearer: + type: http + scheme: bearer + description: The read-only Zabbix token; accepted by `GET /api/stats` only. + 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: No login users configured, or not a same-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" } + 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" } + Busy: + description: All request slots stayed busy for 30 seconds. + headers: + Retry-After: + schema: { type: integer, const: 5 } + 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 } + HealthReport: + type: object + required: [ok] + properties: + ok: { type: boolean } + skipped_at_startup: { type: array, items: { type: string } } + reload_error: { type: string } + reload_error_since: { type: integer, format: int64, description: Unix seconds. } + Target: + type: object + required: [name, type, host, port, pace, interval_sec] + properties: + vrf: { type: string } + source_address: { type: string } + name: { type: string } + type: { type: string, description: "`icmp`, `tcp` or `http`." } + 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: [name, type, host, interval_sec, pace, down, vrf, source_address, last_1h, last_24h] + properties: + name: { type: string } + type: { type: string } + host: { type: string, description: "`host:port` for tcp." } + interval_sec: { type: integer } + pace: { type: string } + down: { type: boolean } + vrf: { type: string } + source_address: { type: string } + error: { type: string, description: Why the latest round could not probe. } + last_1h: { $ref: "#/components/schemas/Stats" } + last_24h: { $ref: "#/components/schemas/Stats" } + 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. } + error: { type: string, description: Why the round could not probe at all. } + 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/login_capslock.test.cjs b/login_capslock.test.cjs new file mode 100644 index 0000000..7052cf4 --- /dev/null +++ b/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: 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: __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/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/package.json b/package.json index 1296e4c..78c99df 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vrf-ping-browser-tests", "private": true, "scripts": { - "test": "node --test routing_browser.test.cjs" + "test": "node --test routing_browser.test.cjs login_capslock.test.cjs" }, "devDependencies": { "playwright": "1.62.1" diff --git a/static/login.html b/static/login.html index 7a4628e..f8e0a56 100644 --- a/static/login.html +++ b/static/login.html @@ -33,6 +33,7 @@ border-radius:6px; padding:11px; cursor:pointer; transition:background .12s; } button:hover { background:color-mix(in srgb, var(--amber) 12%, transparent); } .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="newsprint"] { --bg:#efe9dc; --panel:#f8f4ea; --line:#d8cfb8; --ctl:#898374; @@ -57,7 +58,8 @@

vrf-ping

Sign in to vrf-ping

- + +

@@ -75,6 +77,18 @@

vrf-ping

} 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 7681950..dff8eb6 100644 --- a/web.go +++ b/web.go @@ -110,50 +110,77 @@ func serveWeb(cfg *Config, store *Store, users map[string]string) error { return http.ListenAndServe(cfg.Listen, newMux(cfg, store, users)) } +// webApp holds what the HTTP handlers share. newMux only wires routes; each +// area registers its own, so no single function grows past a screenful. +type webApp struct { + cfg *Config + store *Store + users map[string]string + sess *sessions + throttle *loginThrottle + limit func(http.HandlerFunc) http.HandlerFunc +} + func newMux(cfg *Config, store *Store, users map[string]string) http.Handler { - sess := newSessions() - throttle := newLoginThrottle() - limit := limiter(maxInflight, queueWait) + return securityHeaders(apiRules(buildMux(cfg, store, 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, users map[string]string) *http.ServeMux { + a := &webApp{cfg: cfg, store: store, users: users, sess: newSessions(), + throttle: newLoginThrottle(), limit: limiter(maxInflight, queueWait)} mux := http.NewServeMux() + a.registerPages(mux) + a.registerAuth(mux) + a.registerData(mux) + registerStats(mux, cfg.ZabbixToken, cfg, store) + return mux +} - authed := func(r *http.Request) bool { - if len(users) == 0 { - return true - } - c, err := r.Cookie(sessionCookie) - 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) { // before the limiter: unauthenticated requests never hold a slot - jsonErr(w, http.StatusUnauthorized, "sign in first") - return - } - limit(func(w http.ResponseWriter, r *http.Request) { - 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) - } - })(w, r) + c, err := r.Cookie(sessionCookie) + 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) { // before the limiter: unauthenticated requests never hold a slot + jsonErr(w, http.StatusUnauthorized, "sign in first") + return } + a.limit(func(w http.ResponseWriter, r *http.Request) { + 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) + } + })(w, r) } - 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) - } +} + +// 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) } - index := page("index.html") +} +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 } @@ -161,244 +188,307 @@ func newMux(cfg *Config, store *Store, users map[string]string) http.Handler { }) 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 from %s; address locked for %v", r.RemoteAddr, lock) - } else { - log.Printf("web login failed from %s", r.RemoteAddr) - } - jsonErr(w, http.StatusUnauthorized, "wrong username or password") - return - } - throttle.success(key) - http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: sess.issue(), - Path: "/", HttpOnly: true, MaxAge: int(sessionTTL.Seconds()), SameSite: http.SameSiteLaxMode}) - writeJSON(w, map[string]bool{"ok": true}) - }) + mux.HandleFunc("POST /api/login", a.handleLogin) mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) { if c, err := r.Cookie(sessionCookie); err == nil { - sess.revoke(c.Value) // otherwise the token stays valid until it expires + a.sess.revoke(c.Value) // otherwise the token stays valid until it expires } http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: "", Path: "/", MaxAge: -1}) writeJSON(w, map[string]bool{"ok": true}) }) +} + +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 + } + // 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) + return + } + a.throttle.success(key) + http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: a.sess.issue(), + Path: "/", HttpOnly: true, MaxAge: int(sessionTTL.Seconds()), 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 string) { + time.Sleep(loginFailDelay) + if lock := a.throttle.fail(key); lock > 0 { + log.Printf("web login failed from %s; address locked for %v", r.RemoteAddr, lock) + } else { + log.Printf("web login failed from %s", r.RemoteAddr) + } + jsonErr(w, http.StatusUnauthorized, "wrong username or password") +} + +func (a *webApp) registerData(mux *http.ServeMux) { mux.HandleFunc("GET /api/version", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]string{"version": version}) }) - // health: whether the target lists are applied in full. Same gate as the data: // the messages quote list lines, which name the hosts this machine watches. - mux.HandleFunc("GET /api/health", guard(func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/health", a.guard(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") - writeJSON(w, cfg.Health.report()) + writeJSON(w, a.cfg.Health.report()) })) + mux.HandleFunc("GET /api/routing-options", a.guard(a.getRoutingOptions)) + mux.HandleFunc("PUT /api/routing-options", a.guard(a.putRoutingOptions)) + mux.HandleFunc("GET /api/targets", a.guard(a.handleTargets)) + mux.HandleFunc("GET /api/series", a.guard(a.handleSeries)) +} - routingOptions := func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - if r.Method == http.MethodGet { - name := r.URL.Query().Get("target") - for _, target := range cfg.TargetList() { - if target.Name == name { - routingOptionsMu.Lock() - options, err := readRoutingOptions(cfg.TargetsDir) - routingOptionsMu.Unlock() - if err != nil { - jsonErr(w, http.StatusInternalServerError, "cannot read routing options") - return - } - saved := target - if option, ok := options[name]; ok { - saved.VRF, saved.SourceAddress = option.VRF, option.SourceAddress - } - pending := saved.VRF != target.VRF || saved.SourceAddress != target.SourceAddress - writeJSON(w, map[string]any{"editable": len(users) > 0, "target": target, "saved_target": saved, "pending_reload": pending}) - return - } - } - jsonErr(w, http.StatusNotFound, "target not found") - return - } - if len(users) == 0 { - jsonErr(w, http.StatusForbidden, "Routing is read-only: configure login users to edit.") +// getRoutingOptions answers one target's routing as running and as saved for +// the next reload. +func (a *webApp) getRoutingOptions(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + name := r.URL.Query().Get("target") + for _, target := range a.cfg.TargetList() { + if target.Name == name { + a.writeRoutingTarget(w, target) return } - // Require an explicit browser same-origin signal. Do not trust forwarded - // headers supplied by clients; the browser Origin must match this host. - origin, err := url.Parse(r.Header.Get("Origin")) - scheme := "http" - if r.TLS != nil { - scheme = "https" - } - if err != nil || origin.Scheme != scheme || origin.Host != r.Host || origin.User != nil || origin.Path != "" || origin.RawQuery != "" || origin.Fragment != "" { - jsonErr(w, http.StatusForbidden, "same-origin request required") - return - } - if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" { - jsonErr(w, http.StatusForbidden, "same-origin request required") - return - } - media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) - if err != nil || media != "application/json" { - jsonErr(w, http.StatusUnsupportedMediaType, "application/json required") - return - } - var body struct { - Name string `json:"name"` - VRF *string `json:"vrf"` - SourceAddress *string `json:"source_address"` - } - if err := decodeRoutingJSON(http.MaxBytesReader(w, r.Body, 8192), &body); err != nil || body.Name == "" || body.VRF == nil || body.SourceAddress == nil { - var tooBig *http.MaxBytesError - if errors.As(err, &tooBig) { - jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") - return - } - jsonErr(w, http.StatusBadRequest, "expected name, vrf and source_address JSON fields") - return - } - routingOptionsMu.Lock() - defer routingOptionsMu.Unlock() - targets := cfg.TargetList() - found := -1 - for i := range targets { - if targets[i].Name == body.Name { - found = i - break - } - } - if found < 0 { - jsonErr(w, http.StatusNotFound, "target not found") - return - } - options, err := readRoutingOptions(cfg.TargetsDir) - if err != nil { - jsonErr(w, http.StatusInternalServerError, "cannot read routing options") - return - } - // The running snapshot can lag earlier saves. Validate the complete - // pending overlay, not just the requested change on that stale snapshot. - for i := range targets { - if option, ok := options[targets[i].Name]; ok { - targets[i].VRF = option.VRF - targets[i].SourceAddress = option.SourceAddress - } - } - targets[found].VRF = *body.VRF - targets[found].SourceAddress = *body.SourceAddress - candidate := &Config{Targets: targets, Probe: cfg.Probe} - if err := validateTargets(candidate); err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - options[body.Name] = routingOption{VRF: *body.VRF, SourceAddress: *body.SourceAddress} - if err := writeRoutingOptions(cfg.TargetsDir, options); err != nil { - jsonErr(w, http.StatusInternalServerError, "cannot persist routing options") - return - } - // The existing reload loop owns probe replacement, not this handler. - writeJSON(w, map[string]any{"saved": true, "pending_reload": true, "target": targets[found]}) - } - // One handler, bound to exactly the two methods it serves. - mux.HandleFunc("GET /api/routing-options", guard(routingOptions)) - mux.HandleFunc("PUT /api/routing-options", guard(routingOptions)) - - mux.HandleFunc("GET /api/targets", guard(func(w http.ResponseWriter, r *http.Request) { - now := time.Now() - type item struct { - Name string `json:"name"` - Type string `json:"type"` - Host string `json:"host"` - IntervalSec int `json:"interval_sec"` - Pace string `json:"pace"` - Down bool `json:"down"` - VRF string `json:"vrf"` - SourceAddress string `json:"source_address"` - Error string `json:"error,omitempty"` - Last1h Stats `json:"last_1h"` - Last24h Stats `json:"last_24h"` - } - byName := map[string]TargetCfg{} - for _, t := range cfg.TargetList() { - byName[t.Name] = t + } + jsonErr(w, http.StatusNotFound, "target not found") +} + +func (a *webApp) writeRoutingTarget(w http.ResponseWriter, target TargetCfg) { + routingOptionsMu.Lock() + options, err := readRoutingOptions(a.cfg.TargetsDir) + routingOptionsMu.Unlock() + if err != nil { + jsonErr(w, http.StatusInternalServerError, "cannot read routing options") + return + } + saved := target + if option, ok := options[target.Name]; ok { + saved.VRF, saved.SourceAddress = option.VRF, option.SourceAddress + } + pending := saved.VRF != target.VRF || saved.SourceAddress != target.SourceAddress + writeJSON(w, map[string]any{"editable": len(a.users) > 0, "target": target, "saved_target": saved, "pending_reload": pending}) +} + +// routingBody is what PUT /api/routing-options accepts. +type routingBody struct { + Name string `json:"name"` + VRF *string `json:"vrf"` + SourceAddress *string `json:"source_address"` +} + +// putRoutingOptions saves one target's routing for the next reload. +func (a *webApp) putRoutingOptions(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if len(a.users) == 0 { + jsonErr(w, http.StatusForbidden, "Routing is read-only: configure login users to edit.") + return + } + if !routingRequestAllowed(w, r) { + return + } + body, ok := decodeRoutingBody(w, r) + if !ok { + return + } + routingOptionsMu.Lock() + defer routingOptionsMu.Unlock() + a.saveRoutingOption(w, body) +} + +// routingRequestAllowed requires an explicit browser same-origin signal and a +// JSON body. Do not trust forwarded headers supplied by clients; the browser +// Origin must match this host. +func routingRequestAllowed(w http.ResponseWriter, r *http.Request) bool { + if !strictSameOrigin(r) { + jsonErr(w, http.StatusForbidden, "same-origin request required") + return false + } + if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" { + jsonErr(w, http.StatusForbidden, "same-origin request required") + return false + } + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || media != "application/json" { + jsonErr(w, http.StatusUnsupportedMediaType, "application/json required") + return false + } + return true +} + +// strictSameOrigin: the Origin header must be exactly this request's scheme +// and host, with nothing else in it. +func strictSameOrigin(r *http.Request) bool { + origin, err := url.Parse(r.Header.Get("Origin")) + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + return err == nil && origin.Scheme == scheme && origin.Host == r.Host && origin.User == nil && + origin.Path == "" && origin.RawQuery == "" && origin.Fragment == "" +} + +func decodeRoutingBody(w http.ResponseWriter, r *http.Request) (routingBody, bool) { + var body routingBody + if err := decodeRoutingJSON(http.MaxBytesReader(w, r.Body, 8192), &body); err != nil || body.Name == "" || body.VRF == nil || body.SourceAddress == nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + jsonErr(w, http.StatusRequestEntityTooLarge, "request body is too large") + return body, false } - var out []item - for _, name := range store.Names() { - t := byName[name] - iv, _ := probeParams(t, cfg.Probe) - pace := t.Pace - if pace == "" { - pace = "normal" - } - rec := store.Recent(name, now.Add(-time.Hour).Unix()) - down := len(rec) > 0 && rec[len(rec)-1].S > 0 && rec[len(rec)-1].R == 0 && rec[len(rec)-1].Error == "" - probeError := "" - if len(rec) > 0 { - probeError = rec[len(rec)-1].Error - } - out = append(out, item{ - Name: name, Type: t.Type, Host: targetAddr(t), - VRF: t.VRF, SourceAddress: t.SourceAddress, Error: probeError, - IntervalSec: int(iv.Seconds()), Pace: pace, Down: down, - Last1h: calcStats(rec), - Last24h: calcStats(store.Recent(name, now.Add(-24*time.Hour).Unix())), - }) + jsonErr(w, http.StatusBadRequest, "expected name, vrf and source_address JSON fields") + return body, false + } + return body, true +} + +// saveRoutingOption validates and stores one change. The caller holds +// routingOptionsMu. +func (a *webApp) saveRoutingOption(w http.ResponseWriter, body routingBody) { + targets := a.cfg.TargetList() + found := targetIndex(targets, body.Name) + if found < 0 { + jsonErr(w, http.StatusNotFound, "target not found") + return + } + options, err := readRoutingOptions(a.cfg.TargetsDir) + if err != nil { + jsonErr(w, http.StatusInternalServerError, "cannot read routing options") + return + } + // The running snapshot can lag earlier saves. Validate the complete + // pending overlay, not just the requested change on that stale snapshot. + applyRoutingOptions(targets, options) + targets[found].VRF = *body.VRF + targets[found].SourceAddress = *body.SourceAddress + candidate := &Config{Targets: targets, Probe: a.cfg.Probe} + if err := validateTargets(candidate); err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + options[body.Name] = routingOption{VRF: *body.VRF, SourceAddress: *body.SourceAddress} + if err := writeRoutingOptions(a.cfg.TargetsDir, options); err != nil { + jsonErr(w, http.StatusInternalServerError, "cannot persist routing options") + return + } + // The existing reload loop owns probe replacement, not this handler. + writeJSON(w, map[string]any{"saved": true, "pending_reload": true, "target": targets[found]}) +} + +func targetIndex(targets []TargetCfg, name string) int { + for i := range targets { + if targets[i].Name == name { + return i } - writeJSON(w, out) - })) + } + return -1 +} - // 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 +func applyRoutingOptions(targets []TargetCfg, options map[string]routingOption) { + for i := range targets { + if option, ok := options[targets[i].Name]; ok { + targets[i].VRF = option.VRF + targets[i].SourceAddress = option.SourceAddress } - writeJSON(w, store.ReadRange(r.Context(), name, from, to)) - })) + } +} - registerStats(mux, cfg.ZabbixToken, cfg, store) +// targetItem is one row of GET /api/targets. +type targetItem struct { + Name string `json:"name"` + Type string `json:"type"` + Host string `json:"host"` + IntervalSec int `json:"interval_sec"` + Pace string `json:"pace"` + Down bool `json:"down"` + VRF string `json:"vrf"` + SourceAddress string `json:"source_address"` + Error string `json:"error,omitempty"` + Last1h Stats `json:"last_1h"` + Last24h Stats `json:"last_24h"` +} - return securityHeaders(apiRules(mux)) +func (a *webApp) handleTargets(w http.ResponseWriter, r *http.Request) { + now := time.Now() + byName := map[string]TargetCfg{} + for _, t := range a.cfg.TargetList() { + byName[t.Name] = t + } + var out []targetItem + for _, name := range a.store.Names() { + out = append(out, a.targetItem(name, byName[name], now)) + } + writeJSON(w, out) +} + +func (a *webApp) targetItem(name string, t TargetCfg, now time.Time) targetItem { + iv, _ := probeParams(t, a.cfg.Probe) + pace := t.Pace + if pace == "" { + pace = "normal" + } + rec := a.store.Recent(name, now.Add(-time.Hour).Unix()) + down := len(rec) > 0 && rec[len(rec)-1].S > 0 && rec[len(rec)-1].R == 0 && rec[len(rec)-1].Error == "" + probeError := "" + if len(rec) > 0 { + probeError = rec[len(rec)-1].Error + } + return targetItem{ + Name: name, Type: t.Type, Host: targetAddr(t), + VRF: t.VRF, SourceAddress: t.SourceAddress, Error: probeError, + IntervalSec: int(iv.Seconds()), Pace: pace, Down: down, + Last1h: calcStats(rec), + Last24h: calcStats(a.store.Recent(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)) } func targetAddr(t TargetCfg) string {