Compare commits

..
Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 d58e3e2653 chore(lint): re-enable staticcheck and unused
ci / lint (pull_request) Successful in 6m32s
ci / test (pull_request) Successful in 12m59s
ci / image (pull_request) Successful in 6m29s
ci / build (pull_request) Successful in 11m31s
golangci-lint v2.15.0 ships a honnef.co/go/tools that analyzes the Go 1.27
standard library without panicking. Fix what they found: dead helpers, an
unused constant, error strings starting with a product name, the usage
error, and two negations simplified by De Morgan.

Closes #43

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 07:12:20 +01:00
Sebi 1ad68e2e87 Merge pull request 'feat: verified sign-up and several organizations per account' (#118) from feat/verified-signup into main
ci / image (push) Successful in 7m35s
ci / lint (push) Successful in 10m12s
ci / test (push) Successful in 12m36s
ci / build (push) Successful in 14m25s
Reviewed-on: #118
2026-11-22 21:01:47 +00:00
Sebastian UnterschützandClaude Opus 5.5 87b2f2a256 feat: verified sign-up and several organizations per account
ci / build (pull_request) Successful in 5m46s
ci / test (pull_request) Successful in 12m32s
ci / image (pull_request) Successful in 3m59s
ci / lint (pull_request) Successful in 14m9s
New accounts confirm their email address before signing in: sign-up
mails a link valid for 24 hours, and its page confirms only when the
visitor presses the button, so mail scanners opening links do not sign
in. Confirming signs the account in; unconfirmed accounts are told so
only after giving the right password, can ask for a new link, and are
deleted after a week. UPTIME_SIGNUP_VERIFY requires confirmation always
in the cloud edition and self-hosted wherever mail can be sent; without
a mail server, sign-up that needs it stays closed.

One account per mailbox: users.email_key drops +suffixes, and dots for
Gmail, and is unique, including for accounts created through
invitations and SSO, which count as confirmed. A client address (IPv6:
its /64) may create UPTIME_SIGNUPS_PER_IP accounts a day, 2 by default;
refused sign-ups do not count.

Sign-up asks only for name, email and password. Accounts without an
organization are led to create one; signed-in users create further
organizations from the switcher, within the per-account limit, and
POST /api/v1/orgs does the same.

Closes #112
Closes #113

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:59:12 +01:00
Sebi d644312f25 Merge pull request 'feat: page long and truncated lists' (#117) from feat/paging into main
ci / image (push) Successful in 3m34s
ci / build (push) Successful in 8m35s
ci / test (push) Successful in 12m4s
ci / lint (push) Canceled after 15m35s
Reviewed-on: #117
2026-11-22 20:45:56 +00:00
Sebi a71fd6f5e1 Merge pull request 'feat: per-organization limits set by platform admins' (#115) from feat/org-limits into main
ci / image (push) Canceled after 52s
ci / lint (push) Canceled after 52s
ci / test (push) Canceled after 53s
ci / build (push) Canceled after 53s
Reviewed-on: #115
2026-11-22 20:44:54 +00:00
Sebastian UnterschützandClaude Opus 5.5 d7c5cd711e feat: page long and truncated lists
ci / lint (pull_request) Successful in 15m0s
ci / image (pull_request) Successful in 3m18s
ci / build (pull_request) Successful in 8m38s
ci / test (pull_request) Successful in 12m6s
Lists that were cut off by a fixed LIMIT, or could grow without bound,
are paged by keyset: the cursor holds the sort key and an ID, so pages
neither skip nor repeat items as others are added. The audit logs had a
timestamp-only cursor that could skip entries with equal times.

The API returns at most 100 items per list (limit takes up to 500) with
next_cursor and prev_cursor, passed back as after and before. The
console shows Newer/Older (or Previous/Next) links and To the start,
without JavaScript.

Paged: incidents (optionally of one monitor), a monitor's results and
evidence, a checker's results, the audit logs, members, maintenance
windows, firing Alertmanager alerts, the monitors API and the admin
lists of status pages and organizations, which move to their own admin
pages. A monitor's page shows its latest incidents and results and links
to all of them. The dashboard caps every group at 50 of its own monitors
with a link to a paged view of the group, and gains a search by name or
target. Lists filtered by permission after reading may show fewer items
on a page.

Closes #116

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:40:25 +01:00
Sebastian UnterschützandClaude Opus 5.5 98fb5d3a82 fix(datapolicy): read running TimescaleDB jobs
A running job reports -infinity as its next start, which failed the
storage overview and, intermittently, its test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:40:25 +01:00
Sebastian UnterschützandClaude Opus 5.5 e4ce619fbe feat: per-organization limits set by platform admins
ci / image (pull_request) Successful in 4m25s
ci / build (pull_request) Successful in 8m15s
ci / lint (pull_request) Successful in 12m8s
ci / test (pull_request) Successful in 8m51s
Admins set default limits for monitors (all types), status pages and
regions per monitor, whether an organization's own checker regions count
towards the region limit, and how many organizations an account may own,
and override them per organization or account. Defaults are not copied:
changing one applies at once to everyone without an override. 0 means
unlimited; self-hosted defaults are unlimited, the cloud allows three
organizations per account.

Creations count under a per-organization advisory lock, so concurrent
requests cannot overshoot. A lowered limit keeps everything that exists:
monitors already beyond the region limit stay editable but may not grow.
Organizations see their usage in their settings and GET /org/limits;
the admin panel lists organizations with owner, usage and limits next
to their suspend and delete actions. Empty numeric form fields marked
data-nullable are sent as null.

Refs #111

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:06:45 +01:00
Sebi c8c8727a78 Merge pull request 'feat: admins suspend or delete status pages, organizations and accounts' (#110) from feat/admin-moderation into main
ci / lint (push) Successful in 6m11s
ci / image (push) Successful in 6m51s
ci / build (push) Successful in 8m18s
ci / test (push) Successful in 8m27s
Reviewed-on: #110
2026-11-22 19:54:41 +00:00
Sebastian UnterschützandClaude Opus 5.5 90e74d091a feat: admins suspend or delete status pages, organizations and accounts
ci / image (pull_request) Successful in 3m20s
ci / build (pull_request) Successful in 8m34s
ci / test (pull_request) Successful in 11m41s
ci / lint (pull_request) Successful in 13m0s
The admin panel lists every published status page, and every suspended
page, organization or account, with the organization and owner behind
it, searchable by title, address, organization or email. Each can be
suspended with a reason, reinstated, or deleted.

A suspended page is not served; status page servers drop it when they
next ask. A suspended organization's monitors leave the schedule, its
pages go offline, heartbeat pings and Alertmanager webhooks are no
longer recorded, and its members and API tokens get 403 org_suspended;
the console explains why. Reinstating restarts heartbeat waits so they
do not fire at once. A suspended account is signed out everywhere and
can neither sign in nor use its tokens; only someone who knows the
password learns of the suspension. Platform admins cannot be suspended
or deleted. Account deletion shares its logic with the GDPR erasure,
including the refusal while the account owns shared organizations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 20:46:46 +01:00
Sebi b61162cd22 Merge pull request 'feat(statuspage): add nested status page groups and optional component details' (#109) from feat/statuspage-groups-and-details into main
ci / lint (push) Successful in 13m12s
ci / test (push) Successful in 8m21s
ci / build (push) Successful in 12m52s
ci / image (push) Successful in 4m29s
Reviewed-on: #109
2026-11-22 19:18:50 +00:00
Sebi cdbaf5c8ee Merge pull request 'feat(alerting): add quiet hours to alert groups' (#108) from feat/alert-group-quiet-hours into main
ci / lint (push) Canceled after 2m0s
ci / test (push) Canceled after 1m56s
ci / build (push) Canceled after 1m11s
ci / image (push) Canceled after 0s
Reviewed-on: #108
2026-11-22 19:16:47 +00:00
Sebastian Unterschütz db37060c70 fix(store): coalesce NULL avg_latency_ms in HourlyBuckets
ci / test (pull_request) Successful in 11m55s
ci / build (pull_request) Successful in 8m32s
ci / lint (pull_request) Successful in 5m45s
ci / image (pull_request) Successful in 6m27s
2026-11-22 20:13:46 +01:00
Sebastian Unterschütz 9b26b4150e feat(statuspage): add nested status page groups and optional component details
ci / image (pull_request) Successful in 4m23s
ci / lint (pull_request) Canceled after 6m9s
ci / test (pull_request) Canceled after 6m8s
ci / build (pull_request) Canceled after 6m7s
2026-11-22 20:07:30 +01:00
Sebastian Unterschütz 1c31003baf style(alerting): align quiet hours code and tests with Go style guide
ci / image (pull_request) Successful in 4m28s
ci / build (pull_request) Successful in 8m16s
ci / lint (pull_request) Successful in 12m11s
ci / test (pull_request) Successful in 15m40s
2026-11-22 19:43:17 +01:00
Sebastian Unterschütz ee3769f578 feat(alerting): add quiet hours to alert groups
ci / image (pull_request) Successful in 6m35s
ci / build (pull_request) Successful in 8m24s
ci / test (pull_request) Successful in 7m56s
ci / lint (pull_request) Successful in 11m55s
2026-11-22 19:18:23 +01:00
Sebi bf529a7711 Merge pull request 'feat(alerting): expand notification providers and add monitor alert groups' (#107) from feat/more-notification-providers into main
ci / test (push) Successful in 13m15s
ci / image (push) Successful in 4m37s
ci / build (push) Successful in 5m33s
ci / lint (push) Successful in 9m27s
2026-11-22 17:55:20 +00:00
Sebi 51538fe681 Merge pull request 'feat: private-address access per checker, check types per organization' (#106) from feat/checker-network into main
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
ci / lint (push) Canceled after 47s
2026-11-22 17:54:26 +00:00
Sebi 60a2021edd Merge pull request 'feat: Docker container checks' (#105) from feat/docker-check into main
ci / lint (push) Canceled after 29s
ci / test (push) Canceled after 0s
ci / image (push) Canceled after 0s
ci / build (push) Canceled after 0s
2026-11-22 17:53:55 +00:00
Sebi a78f93de31 Merge pull request 'feat: Steam and Minecraft game server checks' (#104) from feat/game-checks into main
ci / test (push) Canceled after 28s
ci / lint (push) Canceled after 28s
ci / build (push) Canceled after 15s
ci / image (push) Canceled after 14s
2026-11-22 17:53:23 +00:00
Sebi 10ac23582b Merge pull request 'feat: gRPC, SMTP, RADIUS and SNMP checks' (#103) from feat/protocol-checks into main
ci / test (push) Canceled after 0s
ci / lint (push) Canceled after 26s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 17:52:51 +00:00
Sebi aac6d2c26b Merge pull request 'feat: MQTT, Kafka and RabbitMQ checks' (#102) from feat/messaging-checks into main
ci / lint (push) Canceled after 0s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 17:52:22 +00:00
Sebi 3809c87880 Merge pull request 'feat: platform admins can switch off check types' (#101) from feat/check-type-toggle into main
ci / lint (push) Canceled after 3m11s
ci / test (push) Canceled after 2m42s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 17:48:21 +00:00
Sebi 74dde09689 feat: database checks (PostgreSQL, MySQL/MariaDB, SQL Server, MongoDB, Redis) (#100)
ci / test (push) Canceled after 2m54s
ci / lint (push) Canceled after 5m24s
ci / build (push) Canceled after 2m24s
ci / image (push) Canceled after 39s
2026-11-22 17:42:41 +00:00
Sebi 7defeade5a feat: 16 notification services (chat, push, paging, Apprise) (#99)
ci / lint (push) Canceled after 0s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 17:42:08 +00:00
Sebi 37d49e0033 feat(alertmanager): add Alertmanager as a monitor source (#98)
ci / lint (push) Canceled after 42s
ci / test (push) Canceled after 41s
ci / build (push) Canceled after 42s
ci / image (push) Canceled after 42s
2026-11-22 17:41:13 +00:00
Sebastian Unterschütz ef7e12a52d fix(alerting): refresh channel groups after webhook creation
ci / build (pull_request) Successful in 12m29s
ci / image (pull_request) Successful in 4m27s
ci / test (pull_request) Successful in 8m36s
ci / lint (pull_request) Successful in 12m51s
2026-11-22 18:30:46 +01:00
Sebastian Unterschütz 8544e5a585 feat(alerting): add monitor alert groups with default routing 2026-11-22 18:25:36 +01:00
Sebastian UnterschützandClaude Opus 5.5 52819e64bb feat(notify): the remaining notification services of Uptime Kuma
ci / image (pull_request) Successful in 4m24s
ci / build (pull_request) Successful in 5m6s
ci / lint (pull_request) Successful in 12m3s
ci / test (pull_request) Successful in 15m27s
Adds 93 services, bringing the total to 109 plus webhook and email:
chat and messengers (DingTalk, Feishu, LINE, Nextcloud Talk, Threema,
WhatsApp gateways, Nostr, Home Assistant, …), push (Bark, Gorush,
ServerChan, …), SMS and calls (Twilio, Plivo, 46elks, Alibaba Cloud,
Teltonika routers, …), email APIs (SendGrid, Brevo, Resend, Microsoft
Graph, …) and incident management (Grafana OnCall, Jira Service
Management, Splunk On-Call, Squadcast, SIGNL4, …). Customers bring
their own credentials; secrets are sealed like the others.

Services pair incidents by their ID where they can resolve alerts.
Signed requests (DingTalk, Nextcloud Talk, Alibaba Cloud) and replies
that report failures with status 200 are handled. Nostr messages are
sealed and gift-wrapped (NIP-17/59) with go-nostr, but sent over our own
WebSocket connections so relays go through the network guard. Messages
now carry the monitor's name, ID and target.

The channel form groups services, the i18n test derives provider keys
from the registry, and channel types may contain digits.

Refs #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:40:19 +01:00
Sebastian UnterschützandClaude Opus 5.5 465fda60dc feat: choose which checkers may check private addresses, check types per organization
ci / image (pull_request) Successful in 3m33s
ci / lint (pull_request) Successful in 6m25s
ci / test (pull_request) Successful in 11m34s
ci / build (pull_request) Successful in 11m54s
Whether platform checkers may check private addresses, including the
host's Docker socket, is now a platform setting; unset, it stays as
before: allowed self-hosted, forbidden in the cloud edition. Each of an
organization's checkers has its own switch, on by default, settable at
creation and toggled in the checker list. Both apply from the checker's
next poll.

Organizations choose in their settings which of the platform's check
types their members are offered; existing monitors keep running, and if
the platform later switches off everything an organization kept, it is
offered the platform's types again rather than none. Forms marked
data-autosave are sent when a field changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:18:22 +01:00
Sebastian UnterschützandClaude Opus 5.5 0b7f48a609 feat: Docker container checks
ci / build (pull_request) Successful in 5m21s
ci / image (pull_request) Successful in 6m43s
ci / lint (pull_request) Successful in 10m3s
ci / test (pull_request) Successful in 12m5s
A Docker monitor asks the Docker Engine API for a container's state: up
while it runs and its health check, if any, is not unhealthy; exited,
paused or missing containers are reported as such. The API is reached
over the checker host's Unix socket, allowed only on checkers that may
see private networks, or over plain TCP through the network guard. The
README lists all check types and notification services and explains
mounting the socket.

Closes #97

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:03:50 +01:00
Sebastian UnterschützandClaude Opus 5.5 36301ed146 feat: Steam and Minecraft game server checks
ci / test (pull_request) Successful in 17m9s
ci / lint (pull_request) Successful in 5m44s
ci / build (pull_request) Successful in 5m8s
ci / image (pull_request) Successful in 4m43s
Steam servers are asked for A2S_INFO like the server browser does,
answering the challenge newer servers send. Minecraft Java Edition gets
the server list ping, Bedrock Edition a RakNet unconnected ping. A
minimum of free slots can be required. The protocols are implemented
directly; tested against protocol-accurate test servers and once by
hand against public Java and Bedrock servers.

Closes #96

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:03:43 +01:00
Sebastian UnterschützandClaude Opus 5.5 8b30ab4e79 fix(check): redact secrets of any length without garbling messages
ci / build (pull_request) Successful in 11m57s
ci / test (pull_request) Successful in 7m28s
ci / image (pull_request) Successful in 4m28s
ci / lint (pull_request) Successful in 12m16s
Skipping secrets under four characters left short passwords readable
whenever a client repeated them. Secrets are now replaced wherever they
stand alone, as clients print them (password=pw, user:pw@host, 'pw'),
but not inside longer words, and their URL-encoded forms are replaced
too, which connection URLs in errors carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:03:37 +01:00
Sebastian UnterschützandClaude Opus 5.5 365152d164 feat: protocol monitors in the editor and API docs
ci / image (pull_request) Successful in 2m57s
ci / lint (pull_request) Canceled after 12m11s
ci / test (pull_request) Canceled after 12m0s
ci / build (pull_request) Successful in 8m16s
Editor fields and translations for gRPC, SMTP, RADIUS and SNMP; the
RADIUS secret and password and the SNMP community are sealed like other
monitor secrets.

Closes #95

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:51:23 +01:00
Sebastian UnterschützandClaude Opus 5.5 03f6e9137f feat(check): gRPC, SMTP, RADIUS and SNMP checks
gRPC asks the standard health service, optionally about one service.
SMTP waits for the greeting, says EHLO and, unless disabled, requires
STARTTLS or connects with implicit TLS. RADIUS sends an Access-Request
signed with a Message-Authenticator and tells a rejected login from a
wrong shared secret. SNMP v1/v2c reads one OID and compares its value
textually or numerically, hinting at the community when the agent stays
silent. All go through the network guard. Errors from dialing are no
longer passed through redaction, and secrets shorter than four
characters are left in messages instead of garbling them.

Refs #95

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:51:23 +01:00
Sebastian UnterschützandClaude Opus 5.5 302514dc35 feat: message broker monitors in the editor and API docs
ci / build (pull_request) Successful in 7m52s
ci / image (pull_request) Successful in 4m9s
ci / test (pull_request) Successful in 7m3s
ci / lint (pull_request) Successful in 5m36s
Adds editor fields and translations for MQTT, Kafka and RabbitMQ, and
documents DBConfig and BrokerConfig, which the API reference lacked.
Compose's checks profile and CI gain Kafka and RabbitMQ.

Closes #94

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:43:51 +01:00
Sebastian UnterschützandClaude Opus 5.5 8ca56635cd feat(check): MQTT, Kafka and RabbitMQ checks
MQTT signs in and, with a topic, waits for a message (retained ones
count) that may have to contain a text. Kafka fetches cluster metadata
from one or more brokers, checks that a topic exists with a leader for
every partition and can produce a message, with SASL PLAIN or SCRAM.
RabbitMQ signs in over AMQP, opens a channel and checks that a queue
exists. All connect through the network guard with optional TLS, and
the TLS modes and error redaction are now shared with the database
checks. Tested against an in-process MQTT broker and real Kafka and
RabbitMQ.

Refs #94

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:43:51 +01:00
Sebastian UnterschützandClaude Opus 5.5 fb03b28df7 feat: platform admins can switch off check types
ci / image (pull_request) Successful in 2m32s
ci / build (pull_request) Successful in 7m28s
ci / lint (pull_request) Successful in 8m54s
ci / test (pull_request) Successful in 13m7s
Types an installation cannot offer, such as Docker on shared cloud
checkers, can be switched off in the admin panel. They are not offered
in the editor or accepted by the API for new monitors or type changes;
existing monitors keep running and stay editable. The setting lives in
a new platform_settings table and reaches every replica at once through
the versioned cache. GET /api/v1/org/check-types lists what is offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:35:49 +01:00
Sebastian UnterschützandClaude Opus 5.5 5a644e4ae5 test(check): skip only the database checks whose server is missing
ci / build (pull_request) Successful in 10m12s
ci / test (pull_request) Successful in 9m54s
ci / image (pull_request) Successful in 2m35s
ci / lint (pull_request) Successful in 10m58s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:33:24 +01:00
Sebastian UnterschützandClaude Opus 5.5 d3cf9f48e1 feat: database monitors with sealed credentials
ci / image (pull_request) Successful in 2m38s
ci / build (pull_request) Successful in 7m5s
ci / lint (pull_request) Successful in 10m15s
ci / test (pull_request) Failing after 11m53s
Secret monitor settings such as database passwords are stored sealed,
bound to monitor type and field, never returned by the API, the console
or exports, kept when an edit leaves them empty, and opened only for the
checker's job. Monitor types are validated by the check package; the
database only checks their format. Compose gets a checks profile with
MariaDB, MongoDB and SQL Server, and CI tests against MariaDB and
MongoDB.

Closes #93

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:17:08 +01:00
Sebastian UnterschützandClaude Opus 5.5 a62ffb43de feat(check): PostgreSQL, MySQL/MariaDB, SQL Server, MongoDB and Redis checks
Each connects to host:port with the configured credentials and TLS mode,
signs in and runs a query (a ping for MongoDB and Redis), optionally
comparing the first value. Connections go through the network guard, and
errors never repeat the password. Tested against real servers.

Refs #93

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:17:08 +01:00
Sebastian UnterschützandClaude Opus 5.5 b01eefdbce feat: notification channels for chat, push and paging services
ci / image (pull_request) Successful in 3m1s
ci / build (pull_request) Successful in 8m47s
ci / test (pull_request) Successful in 6m17s
ci / lint (pull_request) Successful in 9m36s
Channels of the new types store their settings with secrets sealed and
bound to type and field, never return them, and keep them when an update
leaves them empty. Messages are rendered in the channel's language with
a link to the monitor. The channels page offers every service with its
fields.

Closes #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:07:24 +01:00
Sebastian UnterschützandClaude Opus 5.5 a0a67ec5f8 feat(notify): chat, push and paging providers
Slack, Discord, Microsoft Teams, Google Chat, Mattermost, Rocket.Chat,
Telegram, Matrix, ntfy, Gotify, Pushover, Pushbullet, Signal (signal-cli
REST API), PagerDuty and Opsgenie natively, and every service Apprise
supports through an Apprise API server. Each provider declares its
settings and how it sends; PagerDuty and Opsgenie pair trigger and
resolve by incident. Requests go through the network guard, and errors
name only the host, since URLs may carry tokens.

Refs #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:07:24 +01:00
Sebastian UnterschützandClaude Opus 5.5 b3e34613a3 feat: Alertmanager as a source for monitors
ci / test (pull_request) Successful in 8m32s
ci / image (pull_request) Successful in 2m59s
ci / build (pull_request) Successful in 4m9s
ci / lint (pull_request) Successful in 8m8s
Organizations create receiver URLs for Alertmanager's webhook (token in
the path or as bearer). A monitor of type alertmanager is down while an
alert matching all its label matchers fires, and goes through the usual
evaluation, so confirmations, maintenance, notifications and SLA apply.
Results are recorded when the state changes and once per interval;
alerts Alertmanager stops repeating end after the monitor's stale period,
so a lost resolve cannot hold it down. An overview lists firing alerts
with the monitors following them and creates a prefilled monitor for the
others.

Closes #91

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 15:59:56 +01:00
Sebastian UnterschützandClaude Opus 5.5 16dfba817e feat(store): store Alertmanager receivers and the alerts they deliver
Refs #91

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 15:59:56 +01:00
Sebastian UnterschützandClaude Opus 5.5 98bdb3c282 feat(check): alertmanager monitors with Prometheus label matchers
Refs #91

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 15:59:56 +01:00
Sebi 235bd7db42 Merge pull request 'feat: UptimeSebi wordmark' (#90) from feat/brand-name into main
ci / build (push) Successful in 10m29s
ci / image (push) Successful in 2m19s
ci / lint (push) Successful in 11m42s
ci / test (push) Successful in 13m3s
2026-11-22 14:49:38 +00:00
Sebi 421c8c9135 Merge pull request 'feat: logo, favicons and app icons' (#89) from feat/brand into main
ci / lint (push) Canceled after 22s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
ci / test (push) Canceled after 0s
2026-11-22 14:49:07 +00:00
Sebi dcb3bd8553 Merge pull request 'fix: navigation on legal pages' (#88) from fix/legal-navbar into main
ci / lint (push) Canceled after 22s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 14:48:39 +00:00
Sebi 4249d1690f Merge pull request 'feat: link the API documentation in the footer and at token creation' (#87) from feat/api-docs-links into main
ci / lint (push) Canceled after 18s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 14:48:08 +00:00
Sebi 6c4acfa9ef Merge pull request 'docs: README' (#86) from docs/readme into main
ci / lint (push) Canceled after 21s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-22 14:47:40 +00:00
Sebi 12c642bf49 Merge pull request 'feat: OpenAPI documentation with Swagger UI' (#85) from feat/api-docs into main
ci / lint (push) Canceled after 25s
ci / test (push) Canceled after 13s
ci / build (push) Canceled after 13s
ci / image (push) Canceled after 13s
2026-11-22 14:47:05 +00:00
Sebastian UnterschützandClaude Opus 5.5 01981826c8 feat(web): spell the product UptimeSebi and give the wordmark its weight
ci / image (pull_request) Successful in 4m36s
ci / lint (pull_request) Successful in 5m10s
ci / test (pull_request) Successful in 5m58s
ci / build (pull_request) Successful in 6m33s
The wordmark next to the logo is set in the sans face, semibold and at
body size instead of small monospace. Page titles, status page footers,
the web manifest, the API document, PDF exports, test emails and the
README use the name UptimeSebi; technical identifiers stay lowercase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 15:44:47 +01:00
Sebastian UnterschützandClaude Opus 5.5 c0914b1364 feat(web): logo, favicons and app icons
ci / image (pull_request) Successful in 4m48s
ci / lint (pull_request) Successful in 4m56s
ci / build (pull_request) Successful in 6m33s
ci / test (pull_request) Successful in 8m33s
The logo is a pulse that ends in the green status dot. It replaces the
plain wordmark in the console, sign-in, legal and API documentation
headers and marks status page footers. Every page links an SVG favicon
that follows the browser's light or dark scheme, a PNG fallback, an
Apple touch icon and a web manifest; the README shows the logo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 15:36:48 +01:00
Sebi 6dadb920d7 Merge pull request 'ci: lint, tests against TimescaleDB and Redis, binaries and image' (#81) from ci/pipeline into main
ci / build (push) Successful in 8m46s
ci / lint (push) Successful in 9m39s
ci / image (push) Successful in 3m23s
ci / test (push) Successful in 5m33s
Reviewed-on: #81
2026-11-22 12:51:29 +00:00
Sebastian UnterschützandClaude Opus 5.5 e458984dcb fix(web): keep the navigation on legal pages
ci / lint (pull_request) Successful in 8m15s
ci / test (pull_request) Successful in 9m38s
ci / build (pull_request) Successful in 3m48s
ci / image (pull_request) Successful in 4m36s
Signed-in users see the console navigation on the legal notice and
privacy policy; visitors get a header with sign-in and language choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 13:37:52 +01:00
Sebastian UnterschützandClaude Opus 5.5 e6be8f15d3 feat(web): link the API documentation in the footer and where tokens are created
ci / lint (pull_request) Successful in 9m12s
ci / build (pull_request) Successful in 3m46s
ci / image (pull_request) Successful in 4m39s
ci / test (pull_request) Successful in 8m25s
The footer now always shows, with the API link next to the legal
documents. Creating a token explains how to send it, before and right
after creation.

Refs #84

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 13:23:18 +01:00
199 changed files with 30092 additions and 3580 deletions

No files matched your search

+18
View File
@@ -13,6 +13,17 @@ UPTIME_PUBLIC_URL=http://localhost:8080
# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud.
UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
# Who may sign up: first-user (only the operator of a fresh installation),
# open or closed. New accounts confirm their email address before signing in:
# auto = always in the cloud edition, self-hosted only when UPTIME_SMTP_URL is
# set; required; off (self-hosted only). Sign-ups per client address (IPv6:
# per /64) in 24 hours, 0 = unlimited.
# UPTIME_SIGNUP=first-user
# UPTIME_SIGNUP_VERIFY=auto
# UPTIME_SIGNUPS_PER_IP=2
# Outgoing mail, for email channels and sign-up confirmation.
# UPTIME_SMTP_URL=smtp://user:pass@mail.example.com:587?from=uptime@example.com
# Checker and status page reach the API only. Create tokens with:
# api agent create --kind checker --region local --name dev
# api agent create --kind statuspage --name dev
@@ -22,6 +33,13 @@ UPTIME_API_URL=http://localhost:8080
# Integration tests (make test). The Redis database is flushed by the tests.
UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable
UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
# Database checks are also tested against these when set
# (docker compose --profile checks up -d --wait).
# UPTIME_TEST_MYSQL_ADDR=localhost:13306
# UPTIME_TEST_MONGO_ADDR=localhost:27018
# UPTIME_TEST_MSSQL_ADDR=localhost:11433
# UPTIME_TEST_RABBITMQ_ADDR=localhost:15672
# UPTIME_TEST_KAFKA_ADDR=localhost:19092
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8
+36 -1
View File
@@ -11,7 +11,7 @@ concurrency:
cancel-in-progress: true
env:
GOLANGCI_LINT_VERSION: v2.12.2
GOLANGCI_LINT_VERSION: v2.15.0
SQLC_VERSION: v1.31.1
jobs:
@@ -55,9 +55,44 @@ jobs:
POSTGRES_PASSWORD: postgres
redis:
image: redis:8-alpine
# Targets of the database checks; SQL Server is left to local runs,
# its image is too large for ephemeral runners.
mariadb:
image: mariadb:11
env:
MARIADB_ROOT_PASSWORD: checkpw
MARIADB_DATABASE: shop
options: --health-cmd "healthcheck.sh --connect" --health-interval 2s --health-retries 60
mongo:
image: mongo:8
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: checkpw
rabbitmq:
image: rabbitmq:4-alpine
env:
RABBITMQ_DEFAULT_USER: check
RABBITMQ_DEFAULT_PASS: checkpw
kafka:
image: apache/kafka-native:4.1.1
env:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
env:
UPTIME_TEST_DATABASE_URL: postgres://uptime:uptime@timescaledb:5432/uptime_test?sslmode=disable
UPTIME_TEST_REDIS_URL: redis://redis:6379/15
UPTIME_TEST_MYSQL_ADDR: mariadb:3306
UPTIME_TEST_MONGO_ADDR: mongo:27017
UPTIME_TEST_RABBITMQ_ADDR: rabbitmq:5672
UPTIME_TEST_KAFKA_ADDR: kafka:9092
steps:
- uses: actions/checkout@v7
# The runners are ephemeral and clone every action from GitHub, which
+2 -2
View File
@@ -4,8 +4,6 @@ run:
tests: true
linters:
# staticcheck and unused are left out until honnef.co/go/tools supports
# the Go 1.27 standard library; they panic during analysis otherwise.
default: none
enable:
- errcheck
@@ -17,6 +15,8 @@ linters:
- misspell
- unconvert
- usestdlibvars
- staticcheck
- unused
settings:
revive:
rules:
+23 -4
View File
@@ -1,8 +1,10 @@
# uptimesebi
<img src="docs/images/logo.svg" alt="" width="260">
# UptimeSebi
[![ci](https://git.zb-server.de/ZB-Server/uptimesebi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
uptimesebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while uptimesebi itself is not, and it can run entirely on your own infrastructure.
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
@@ -10,9 +12,9 @@ It is built for teams and hosting providers: organizations with members, roles a
**What it does**
- **Checks:** HTTP(S) with keyword, JSON APIs with conditions on values, Prometheus queries, TCP, TLS certificate expiry, DNS, ICMP, and heartbeats pinged by cron jobs.
- **Checks:** HTTP(S) with keyword, JSON APIs with conditions on values, Prometheus queries, TCP, TLS certificate expiry, DNS, ICMP; PostgreSQL, MySQL/MariaDB, SQL Server, MongoDB, Redis; MQTT, Kafka, RabbitMQ; gRPC health, SMTP, RADIUS, SNMP; Steam and Minecraft servers; Docker containers; heartbeats pinged by cron jobs, and Prometheus Alertmanager alerts. Credentials are stored encrypted. Platform admins can switch off types an installation cannot offer.
- **Multi-region:** checkers run per region, several per region for load and failover; any number of regions per monitor.
- **Alerting:** incidents with webhooks (signed) and email, confirmations, maintenance windows (one-off or recurring).
- **Alerting:** incidents with webhooks (signed), email and over 100 services: chat and messengers (Slack, Discord, Microsoft Teams, Telegram, Matrix, WhatsApp gateways, Nostr, …), push (ntfy, Gotify, Pushover, …), SMS and calls (Twilio, Plivo, …), email APIs (SendGrid, Microsoft 365, …) and incident management (PagerDuty, Opsgenie, Grafana OnCall, Jira Service Management, …), plus Apprise; customers bring their own credentials. Confirmations, maintenance windows (one-off or recurring).
- **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body).
- **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages.
- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, enforced 2FA, audit log.
@@ -75,10 +77,13 @@ docker run -d -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN
--entrypoint /usr/local/bin/checker uptimesebi
```
Docker monitors ask the Docker API of the checker's host. Mount its socket read-only (`-v /var/run/docker.sock:/var/run/docker.sock:ro`) into checkers that may see private networks; shared checkers never use a socket, and installations without one can switch the Docker type off in the admin panel.
All settings are environment variables; [`.env.example`](.env.example) lists them with explanations. In particular:
- `UPTIME_SECRET_KEYS` encrypts stored secrets. Generate one with `echo "k1:$(head -c32 /dev/urandom | base64)"` and keep it safe; rotate by prepending a new key.
- `UPTIME_PUBLIC_URL` is the address users reach the console at.
- `UPTIME_SIGNUP` (`first-user`, `open`, `closed`) decides who may sign up. New accounts confirm their email address before signing in (`UPTIME_SIGNUP_VERIFY`: always in the cloud edition, self-hosted when `UPTIME_SMTP_URL` is set); one account per mailbox, and at most `UPTIME_SIGNUPS_PER_IP` (default 2) a day per client address.
- `UPTIME_TRUSTED_PROXIES` must name your reverse proxy, or client addresses in the audit log and rate limits will be the proxy's.
- `UPTIME_RETENTION_*` set how long results, aggregates, audit entries and captured responses are kept.
@@ -102,6 +107,20 @@ curl -H "Authorization: Bearer ust_…" https://uptime.example.com/api/v1/org/mo
The interactive API documentation is at `/api/docs` of every installation, the OpenAPI 3.1 document at `/api/openapi.json`.
Alert groups bundle notification channels under **Settings → Notifications**. Assign one or
more groups in the monitor editor. Each organization has a default group, automatically
assigned to new monitors and new channels. Existing monitors and channels are migrated
to that group to preserve delivery. The default group can be renamed and its channels
changed, but cannot be deleted. A channel in multiple assigned groups receives each
incident event once. Selecting no groups disables notifications for that monitor. Each group
can also define recurring quiet hours (`quiet_hours`) in a chosen time zone to suppress its
notifications during those periods while incidents continue to be recorded.
The API exposes `/api/v1/org/alert-groups` for managing groups and `alert_group_ids`
on monitor requests and responses. Omit the field when creating a monitor to use the
default; omit it when updating to preserve assignments. Send `[]` to remove them all.
Deleting a custom group removes its assignments without assigning a fallback.
## Examples
Create a monitor that checks a website from two regions every minute:
+7 -2
View File
@@ -30,6 +30,11 @@ const usage = `usage:
region and agent manage platform resources shared by all organizations;
organizations manage their own in the console.`
// usageError reports a command line the binary does not understand.
type usageError struct{}
func (usageError) Error() string { return usage }
// admin runs operator commands. They act across all organizations, hence the
// system scope, and print to stdout for humans and scripts.
func admin(ctx context.Context, cfg config.API, args []string) error {
@@ -96,7 +101,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error {
return err
})
}
return errors.New(usage)
return usageError{}
}
func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
@@ -108,7 +113,7 @@ func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
return err
}
if *name == "" || (*kind == "checker") != (*region != "") {
return errors.New(usage)
return usageError{}
}
var tok string
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
+1 -1
View File
@@ -50,7 +50,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
return admin(ctx, cfg, args)
case "serve":
default:
return errors.New(usage)
return usageError{}
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
return err
}
level.Set(cfg.LogLevel)
if err := cfg.Common.Validate(); err != nil {
if err := cfg.Validate(); err != nil {
return err
}
ctx, stop := platform.SignalContext()
+1 -1
View File
@@ -43,7 +43,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
return err
}
level.Set(cfg.LogLevel)
if err := cfg.Common.Validate(); err != nil {
if err := cfg.Validate(); err != nil {
return err
}
ctx, stop := platform.SignalContext()
+58
View File
@@ -50,5 +50,63 @@ services:
<<: *sentinel
environment: {PORT: "26381"}
# Databases the database checks are tested against:
# docker compose --profile checks up -d --wait
mariadb:
image: mariadb:11
profiles: [checks]
environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop}
ports: ["13306:3306"]
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect"]
interval: 2s
retries: 60
mongo:
image: mongo:8
profiles: [checks]
environment: {MONGO_INITDB_ROOT_USERNAME: root, MONGO_INITDB_ROOT_PASSWORD: checkpw}
ports: ["27018:27017"]
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping: 1})"]
interval: 2s
retries: 60
mssql:
image: mcr.microsoft.com/mssql/server:2022-latest
profiles: [checks]
environment: {ACCEPT_EULA: "Y", MSSQL_SA_PASSWORD: "Check-pw-2026"}
ports: ["11433:1433"]
healthcheck:
test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -Q 'SELECT 1' || exit 1"]
interval: 3s
retries: 60
rabbitmq:
image: rabbitmq:4-alpine
profiles: [checks]
environment: {RABBITMQ_DEFAULT_USER: check, RABBITMQ_DEFAULT_PASS: checkpw}
ports: ["15672:5672"]
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
interval: 3s
retries: 60
kafka:
image: apache/kafka-native:4.1.1
profiles: [checks]
ports: ["19092:9092"]
environment:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:19092
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
volumes:
pgdata:
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 48" role="img" aria-label="UptimeSebi">
<style>
.ink { stroke: #1c1d1f; fill: #1c1d1f }
@media (prefers-color-scheme: dark) { .ink { stroke: #e6e3dc; fill: #e6e3dc } }
</style>
<path class="ink" d="M3 26h9l4-12 6 23 5-16 3 5h6" style="fill:none" stroke-width="5" stroke-linejoin="round" stroke-linecap="square"/>
<circle cx="42" cy="26" r="5.5" fill="#2f7d4f"/>
<text class="ink" x="58" y="34" stroke="none" font-family="IBM Plex Sans, ui-sans-serif, system-ui, sans-serif" font-weight="600" font-size="26" letter-spacing="-0.3">UptimeSebi</text>
</svg>

After

Width:  |  Height:  |  Size: 629 B

+41 -2
View File
@@ -6,28 +6,46 @@ require (
github.com/a-h/templ v0.3.1118
github.com/caarlos0/env/v11 v11.4.2
github.com/caddyserver/certmagic v0.25.6
github.com/coder/websocket v1.8.15
github.com/coreos/go-oidc/v3 v3.21.0
github.com/eclipse/paho.mqtt.golang v1.5.1
github.com/gin-gonic/gin v1.12.0
github.com/go-jose/go-jose/v4 v4.1.4
github.com/go-playground/validator/v10 v10.30.6
github.com/go-sql-driver/mysql v1.10.2
github.com/google/uuid v1.6.0
github.com/gosnmp/gosnmp v1.47.0
github.com/jackc/pgx/v5 v5.13.0
github.com/microsoft/go-mssqldb v1.12.0
github.com/mochi-mqtt/server/v2 v2.7.9
github.com/nbd-wtf/go-nostr v0.52.3
github.com/nicksnyder/go-i18n/v2 v2.7.0
github.com/pquerna/otp v1.5.0
github.com/pressly/goose/v3 v3.30.1
github.com/rabbitmq/amqp091-go v1.17.0
github.com/redis/go-redis/v9 v9.23.0
github.com/twmb/franz-go v1.22.3
github.com/twmb/franz-go/pkg/kmsg v1.15.1
github.com/yuin/goldmark v1.7.13
go.mongodb.org/mongo-driver/v2 v2.5.0
go.uber.org/zap v1.28.0
golang.org/x/crypto v0.59.0
golang.org/x/net v0.63.0
golang.org/x/oauth2 v0.38.0
golang.org/x/text v0.44.0
google.golang.org/grpc v1.85.0
layeh.com/radius v0.0.0-20231213012653-1006025d24f8
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 // indirect
github.com/a-h/parse v0.0.42 // indirect
github.com/andybalholm/brotli v1.3.0 // indirect
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect
github.com/btcsuite/btcd/btcutil v1.1.5 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
@@ -36,6 +54,8 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cli/browser v1.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
@@ -44,13 +64,19 @@ require (
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/libdns/libdns v1.1.1 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mfridman/interpolate v0.2.0 // indirect
@@ -60,22 +86,35 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/natefinch/atomic v1.0.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pierrec/lz4/v4 v4.1.33 // indirect
github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/rs/xid v1.4.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/shopspring/decimal v1.6.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.2.0 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
github.com/zeebo/blake3 v0.2.4 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap/exp v0.3.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 // indirect
golang.org/x/mod v0.43.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/tools v0.52.0 // indirect
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
tool github.com/a-h/templ/cmd/templ
+235 -2
View File
@@ -1,11 +1,28 @@
code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 h1:w3gDUJlJ0BfBsHH02DCBDwbkmMSXJqBj6nBOCo9iocY=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0/go.mod h1:7scl8mG/IFLVjJ9ef/ltdND2T1z0CkgVSaQoUxLvmeU=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0 h1:MaKvxE6D0KkjOg6Wd9M00iqP5PR0kUxCfiezes4JweM=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0/go.mod h1:i2h9fsTFKZorh8RdV2IcSUf/Qj98GlTkrTvUbX/s8as=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0/go.mod h1:ucUjca2JtSZboY8IoUqyQyuuXvwbMBVwFOm0vdQPNhA=
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 h1:0O6j18nQDoIff6/mtosT5LNU2WehEwp+LqfX6699oqY=
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1/go.mod h1:xdYAf5bjkOpsd3auA8riiJW4vneBubt9caavL7626jQ=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 h1:ClzzXMDDuUbWfNNZqGeYq4PnYOlwlOVIvSyNaIy0ykg=
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3/go.mod h1:we0YA5CsBbH5+/NUzC/AlMmxaDtWlXeNsqrwXjTzmzA=
github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ=
github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w=
github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI=
github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjPuCS4=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
@@ -14,6 +31,30 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M=
github.com/btcsuite/btcd v0.23.5-0.20231215221805-96c9fd8078fd/go.mod h1:nm3Bko6zh6bWP60UxwoT5LzdGJsQJaPo6HjduXq9p6A=
github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA=
github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
github.com/btcsuite/btcd/btcec/v2 v2.3.4 h1:3EJjcN70HCu/mwqlUsGK8GcNVyLVxFDlWurTXGPFfiQ=
github.com/btcsuite/btcd/btcec/v2 v2.3.4/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A=
github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE=
github.com/btcsuite/btcd/btcutil v1.1.5 h1:+wER79R5670vs/ZusMTF1yTcRYE5GUsFbdjdisflzM8=
github.com/btcsuite/btcd/btcutil v1.1.5/go.mod h1:PSZZ4UitpLBWzxGd5VGOrLnmOjtPP/a6HaFo12zMs00=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I=
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
@@ -34,15 +75,30 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw=
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
@@ -61,15 +117,42 @@ github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dm
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo=
github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4=
github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0=
github.com/go-sql-driver/mysql v1.10.2/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gosnmp/gosnmp v1.47.0 h1:nQ0H9erruu03QP0lviAJ6vB6iiIGE0R5u73MKFr6QPs=
github.com/gosnmp/gosnmp v1.47.0/go.mod h1:LWPVcDKeRsiioQGeITGTQha4mdlx9lgmRmXz6zGINQ4=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -78,10 +161,26 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg=
github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=
@@ -90,6 +189,8 @@ github.com/letsencrypt/pebble/v2 v2.10.1 h1:oKHx3lgN4e5Nno2LKTMrVx+b+NkDptkO9aDi
github.com/letsencrypt/pebble/v2 v2.10.1/go.mod h1:KtYhQ4YTjT5MtoCZ6RTCXlbrrz6cKyXROCuTpIUDJFY=
github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
@@ -98,8 +199,12 @@ github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
github.com/mholt/acmez/v3 v3.1.7 h1:XTqpuUcRdRoIBuDoI+M4mCnRnPTPN4rqH3Mb723Rg4U=
github.com/mholt/acmez/v3 v3.1.7/go.mod h1:Lwv6P/czh/AOq+c99tAzP68/VP92s+8y+hDs4FCgxvo=
github.com/microsoft/go-mssqldb v1.12.0 h1:Jwg/8jz2MKlFOYf4Oj7wMOQuTpCLrP4PIx0aINasMfw=
github.com/microsoft/go-mssqldb v1.12.0/go.mod h1:iYsISdcqI4Tf8x/JwwkHfBu5pxtSD6lSJB8tCrOoo6E=
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
github.com/mochi-mqtt/server/v2 v2.7.9 h1:y0g4vrSLAag7T07l2oCzOa/+nKVLoazKEWAArwqBNYI=
github.com/mochi-mqtt/server/v2 v2.7.9/go.mod h1:lZD3j35AVNqJL5cezlnSkuG05c0FCHSsfAKSPBOSbqc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -107,32 +212,58 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
github.com/nbd-wtf/go-nostr v0.52.3 h1:Xd87pXfJEJRXHpM+fLjQQln8dBNNaoPA10V7BbyP4KI=
github.com/nbd-wtf/go-nostr v0.52.3/go.mod h1:4avYoc9mDGZ9wHsvCOhHH9vPzKucCfuYBtJUSpHTfNk=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0=
github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pierrec/lz4/v4 v4.1.33 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014=
github.com/pierrec/lz4/v4 v4.1.33/go.mod h1:7SE9MC2STkNtL4PIwGhjmyVwvILaGI9/COYQNBhKM/c=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/rs/xid v1.4.0 h1:qd7wPTDkN6KQx2VmMBLrpHkiyQwgFXRnkOLacUiaSNY=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4=
github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
@@ -140,12 +271,33 @@ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/twmb/franz-go v1.22.3 h1:RHe35s34pKefMLyL+ZYJ6mQVtfFZz4zHDHVkTyACur0=
github.com/twmb/franz-go v1.22.3/go.mod h1:OhbFLkvp6GLcN5daC7I4Q2z0W/rFP16HG+gTbe9CDC4=
github.com/twmb/franz-go/pkg/kmsg v1.15.1 h1:3sj7ekbH33t73nsBcHS0wtp/PyMIViHLNItZrE8V9zM=
github.com/twmb/franz-go/pkg/kmsg v1.15.1/go.mod h1:sGkGxKexpRLBThFHJLjjywcyfkK09qB/g+X+wFWZQ/A=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
@@ -174,27 +326,108 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 h1:qr+tk4P56rtbVVAJDyAr5LAOiaD/XhZCoRTr4SfLxAk=
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
layeh.com/radius v0.0.0-20231213012653-1006025d24f8 h1:orYXpi6BJZdvgytfHH4ybOe4wHnLbbS71Cmd8mWdZjs=
layeh.com/radius v0.0.0-20231213012653-1006025d24f8/go.mod h1:QRf+8aRqXc019kHkpcs/CTgyWXFzf+bxlsyuo2nAl1o=
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+148 -20
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/url"
"slices"
"time"
)
@@ -33,19 +34,53 @@ type Day struct {
Uptime float64 `json:"uptime"`
}
// HourBucket is one hourly summary of a component's recent 24-hour history.
// Uptime is -1 when no checks were recorded during that hour.
type HourBucket struct {
Time time.Time `json:"time"`
Uptime float64 `json:"uptime"`
AvgLatencyMS int `json:"avg_latency_ms"`
}
// ComponentRegion is the public status of one monitoring region for a
// component. Error details and checker IDs stay private.
type ComponentRegion struct {
Name string `json:"name"`
Status string `json:"status"`
LatencyMS int `json:"latency_ms,omitempty"`
}
// ComponentDetails holds the public metrics shown on a component's detail page
// when the status page opts in via ShowDetails.
type ComponentDetails struct {
SLA24h float64 `json:"sla_24h"`
SLA7d float64 `json:"sla_7d"`
SLA30d float64 `json:"sla_30d"`
SLA90d float64 `json:"sla_90d"`
Hours []HourBucket `json:"hours,omitempty"`
Regions []ComponentRegion `json:"regions,omitempty"`
}
// Component is one monitor as the public sees it. Targets, check details
// and error messages stay private.
type Component struct {
Name string `json:"name"`
Status string `json:"status"`
Uptime float64 `json:"uptime"`
Days []Day `json:"days"`
// ID identifies the component on detail URLs when ShowDetails is enabled.
ID string `json:"id,omitempty"`
Name string `json:"name"`
Status string `json:"status"`
Uptime float64 `json:"uptime"`
Days []Day `json:"days"`
Details *ComponentDetails `json:"details,omitempty"`
}
// Section groups components under a heading; the first may be unnamed.
// Section groups components and nested child sections under a heading; a
// top-level section with an empty Name holds ungrouped components.
type Section struct {
Name string `json:"name"`
Status string `json:"status,omitempty"`
Total int `json:"total,omitempty"`
Components []Component `json:"components"`
Children []Section `json:"children,omitempty"`
}
// PageIncident is an incident of a listed component.
@@ -62,6 +97,7 @@ type PageSnapshot struct {
Description string `json:"description"`
Theme Theme `json:"theme"`
Status string `json:"status"`
ShowDetails bool `json:"show_details,omitempty"`
Sections []Section `json:"sections"`
Incidents []PageIncident `json:"incidents"`
GeneratedAt time.Time `json:"generated_at"`
@@ -87,9 +123,9 @@ type PageMaintenance struct {
Components []string `json:"components"`
}
// Summarize derives a page state from component states. Unknown components
// do not make a page look broken, and a single failed component is a partial
// problem: only when all fail is it an outage.
// Summarize derives a page or group state from component states. Unknown
// components do not make a page look broken, and a single failed component is
// a partial problem: only when all fail is it an outage.
func Summarize(states []string) string {
rank := map[string]int{PageOperational: 0, PageUnknown: 0, PageDegraded: 1, PageOutage: 2}
worst, allUnknown, allDown := PageOperational, true, len(states) > 0
@@ -109,8 +145,22 @@ func Summarize(states []string) string {
return worst
}
func summarizeWithMaintenance(states []string, hasMaintenance bool) string {
if len(states) == 0 {
if hasMaintenance {
return PageUnderMaintenance
}
return PageUnknown
}
status := Summarize(states)
if hasMaintenance && (status == PageOperational || status == PageUnknown) {
return PageUnderMaintenance
}
return status
}
// WithMaintenance returns s as of now: components under maintenance in
// progress show as such and the page state leaves them out.
// progress show as such and the page and group states reflect it.
func (s PageSnapshot) WithMaintenance(now time.Time) PageSnapshot {
affected := map[string]bool{}
for _, m := range s.Maintenance {
@@ -123,27 +173,105 @@ func (s PageSnapshot) WithMaintenance(now time.Time) PageSnapshot {
if len(affected) == 0 {
return s
}
sections := make([]Section, len(s.Sections))
var states []string
for i, sec := range s.Sections {
sections[i] = Section{Name: sec.Name, Components: make([]Component, len(sec.Components))}
for j, c := range sec.Components {
var allStates []string
var anyMaint bool
var apply func(src Section) (Section, []string, bool)
apply = func(src Section) (Section, []string, bool) {
dst := Section{
Name: src.Name,
Total: src.Total,
Components: make([]Component, len(src.Components)),
}
var subStates []string
subMaint := false
for i, c := range src.Components {
if affected[c.Name] {
c.Status = PageUnderMaintenance
subMaint = true
} else {
states = append(states, c.Status)
subStates = append(subStates, c.Status)
}
sections[i].Components[j] = c
dst.Components[i] = c
}
if len(src.Children) > 0 {
dst.Children = make([]Section, len(src.Children))
for i, child := range src.Children {
var childStates []string
var childMaint bool
dst.Children[i], childStates, childMaint = apply(child)
subStates = append(subStates, childStates...)
subMaint = subMaint || childMaint
}
}
if dst.Name != "" {
dst.Status = summarizeWithMaintenance(subStates, subMaint)
}
return dst, subStates, subMaint
}
sections := make([]Section, len(s.Sections))
for i, sec := range s.Sections {
var states []string
var maint bool
sections[i], states, maint = apply(sec)
allStates = append(allStates, states...)
anyMaint = anyMaint || maint
}
s.Sections = sections
s.Status = Summarize(states)
if len(states) == 0 || s.Status == PageOperational {
s.Status = PageUnderMaintenance
}
s.Status = summarizeWithMaintenance(allStates, anyMaint)
return s
}
// ComponentByID finds a component anywhere in s.Sections by its ID.
func (s PageSnapshot) ComponentByID(id string) (Component, bool) {
if id == "" {
return Component{}, false
}
var find func(secs []Section) (Component, bool)
find = func(secs []Section) (Component, bool) {
for _, sec := range secs {
for _, c := range sec.Components {
if c.ID == id {
return c, true
}
}
if c, ok := find(sec.Children); ok {
return c, true
}
}
return Component{}, false
}
return find(s.Sections)
}
// IncidentsForComponent returns incidents belonging to componentName.
func (s PageSnapshot) IncidentsForComponent(componentName string) []PageIncident {
var out []PageIncident
for _, inc := range s.Incidents {
if inc.Component == componentName {
out = append(out, inc)
}
}
return out
}
// MaintenanceForComponent splits planned maintenance affecting componentName
// into ongoing and upcoming occurrences at now.
func (s PageSnapshot) MaintenanceForComponent(componentName string, now time.Time) (ongoing, upcoming []PageMaintenance) {
for _, m := range s.Maintenance {
if !slices.Contains(m.Components, componentName) {
continue
}
switch {
case !now.Before(m.Start) && now.Before(m.End):
ongoing = append(ongoing, m)
case now.Before(m.Start):
upcoming = append(upcoming, m)
}
}
return ongoing, upcoming
}
// Ongoing returns occurrences in progress at now.
func (s PageSnapshot) Ongoing(now time.Time) []PageMaintenance {
var out []PageMaintenance
+3
View File
@@ -123,6 +123,9 @@ func (s *Server) resolvePrincipal(c *gin.Context) (*principal, int, string, erro
if err != nil {
return nil, 0, "", err
}
if p.Org.SuspendedAt != nil {
return nil, http.StatusForbidden, "org_suspended", nil
}
if code := policyViolation(p.Org, p.Grants.Owner, sess); code != "" {
return nil, http.StatusForbidden, code, nil
}
+8 -7
View File
@@ -14,6 +14,7 @@ import (
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
@@ -118,12 +119,6 @@ func regionOf(c *gin.Context) string {
return ""
}
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
func (s *Server) allowPrivate(a store.GetAgentByHashRow) bool {
// Operator checkers in the cloud share our network; customers must not
// reach it through them. Customer-run checkers and self-hosted
// installations check whatever their operator can reach.
return !s.cloud() || a.OrgID != nil
}
func (s *Server) agentHello(c *gin.Context) {
a := agentOf(c)
@@ -181,6 +176,7 @@ func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, ent
if err != nil {
return nil, nil, err
}
allowPrivate := s.allowPrivate(ctx, a)
byID := make(map[uuid.UUID]store.Monitor, len(rows))
for _, m := range rows {
byID[m.ID] = m
@@ -190,9 +186,14 @@ func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, ent
if !ok {
continue
}
cfg, err := s.openMonitorConfig(check.Type(m.Type), m.Config)
if err != nil {
s.log.ErrorContext(ctx, "opening monitor secrets failed", "monitor", m.ID, "error", err)
continue
}
jobs = append(jobs, agentapi.Job{
MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target,
TimeoutMS: int(m.TimeoutMs), Config: m.Config, AllowPrivate: s.allowPrivate(a),
TimeoutMS: int(m.TimeoutMs), Config: cfg, AllowPrivate: allowPrivate,
})
orgs[m.ID] = m.OrgID
}
+199
View File
@@ -0,0 +1,199 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
type alertGroupRequest struct {
Name string `json:"name" binding:"required,max=100"`
ChannelIDs []uuid.UUID `json:"channel_ids" binding:"max=200"`
// QuietHours suppresses notifications from this group during the given
// windows. Omitting it on update preserves existing quiet hours; an
// empty array clears them.
QuietHours []quietHourRequest `json:"quiet_hours" binding:"max=20"`
}
type alertGroupView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
IsDefault bool `json:"is_default"`
ChannelIDs []uuid.UUID `json:"channel_ids"`
QuietHours []quietHourView `json:"quiet_hours"`
}
var errInvalidAlertGroup = errors.New("api: invalid alert group")
var errInvalidChannel = errors.New("api: invalid notification channel")
func (s *Server) listAlertGroups(c *gin.Context) {
ctx := c.Request.Context()
out := []alertGroupView{}
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
rows, err := q.ListAlertGroups(ctx)
if err != nil {
return err
}
for _, row := range rows {
out = append(out, alertGroupView{
ID: row.ID, Name: row.Name, IsDefault: row.IsDefault,
ChannelIDs: row.ChannelIds, QuietHours: decodeQuietHours(row.QuietHours),
})
}
return nil
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"alert_groups": out})
}
func (s *Server) saveAlertGroup(c *gin.Context) {
var req alertGroupRequest
if !bind(c, &req) {
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
var id uuid.UUID
if c.Param("id") != "" {
var err error
id, err = uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
}
var quietRaw []byte
switch {
case req.QuietHours != nil:
qh, code := validateQuietHours(req.QuietHours)
if code != "" {
fail(c, http.StatusUnprocessableEntity, code)
return
}
var err error
quietRaw, err = json.Marshal(qh)
if err != nil {
internalError(c, err)
return
}
case c.Param("id") == "":
quietRaw = []byte("[]")
}
ctx := c.Request.Context()
p := current(c)
var row store.AlertGroup
// Stable ordering also avoids deadlocks when concurrent edits share channels.
slices.SortFunc(req.ChannelIDs, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
req.ChannelIDs = slices.Compact(req.ChannelIDs)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if c.Param("id") == "" {
row, err = q.CreateAlertGroup(ctx, store.CreateAlertGroupParams{OrgID: p.Org.ID, Name: req.Name, QuietHours: quietRaw})
} else {
row, err = q.UpdateAlertGroup(ctx, store.UpdateAlertGroupParams{ID: id, Name: req.Name, QuietHours: quietRaw})
}
if err != nil {
return err
}
if err := q.DeleteAlertGroupChannels(ctx, row.ID); err != nil {
return err
}
for _, ch := range req.ChannelIDs {
n, err := q.AddAlertGroupChannel(ctx, store.AddAlertGroupChannelParams{OrgID: p.Org.ID, GroupID: row.ID, ChannelID: ch})
if err != nil {
return err
}
if n != 1 {
return errInvalidChannel
}
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if errors.Is(err, errInvalidChannel) {
fail(c, http.StatusUnprocessableEntity, "invalid_channel")
return
}
if err != nil {
internalError(c, err)
return
}
status := http.StatusOK
if c.Param("id") == "" {
status = http.StatusCreated
}
if req.ChannelIDs == nil {
req.ChannelIDs = []uuid.UUID{}
}
c.JSON(status, alertGroupView{
ID: row.ID, Name: row.Name, IsDefault: row.IsDefault,
ChannelIDs: req.ChannelIDs, QuietHours: decodeQuietHours(row.QuietHours),
})
}
func (s *Server) deleteAlertGroup(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
n, err = q.DeleteAlertGroup(ctx, id)
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "alert_group_not_deletable")
return
}
c.Status(http.StatusNoContent)
}
// setMonitorAlertGroups preserves assignments when ids is omitted. On creation,
// the database assigns the default group; an explicit empty list opts out.
func setMonitorAlertGroups(ctx context.Context, q *store.Queries, m store.Monitor, ids []uuid.UUID) error {
if ids == nil {
return nil
}
if err := q.DeleteMonitorAlertGroups(ctx, m.ID); err != nil {
return err
}
seen := make(map[uuid.UUID]bool, len(ids))
for _, id := range ids {
if seen[id] {
continue
}
seen[id] = true
n, err := q.AddMonitorAlertGroup(ctx, store.AddMonitorAlertGroupParams{OrgID: m.OrgID, MonitorID: m.ID, GroupID: id})
if err != nil {
return err
}
if n != 1 {
return errInvalidAlertGroup
}
}
return nil
}
+299
View File
@@ -0,0 +1,299 @@
package api_test
import (
"net/http"
"slices"
"strings"
"testing"
)
func TestAlertGroups(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("ag")+".test", uniq("ag-"))
groups := func(b *browser) []any {
t.Helper()
st, body := b.do("GET", "/api/v1/org/alert-groups", nil)
if st != http.StatusOK {
t.Fatalf("list groups = %d %v", st, body)
}
return body["alert_groups"].([]any)
}
initial := groups(owner)
if len(initial) != 1 || initial[0].(map[string]any)["is_default"] != true {
t.Fatalf("initial groups = %v", initial)
}
defaultID := initial[0].(map[string]any)["id"].(string)
channel := func(b *browser, name string, enabled bool) string {
t.Helper()
st, body := b.do("POST", "/api/v1/org/channels", map[string]any{"name": name, "type": "webhook", "url": "https://example.test/hook", "enabled": enabled})
if st != http.StatusCreated {
t.Fatalf("create channel = %d %v", st, body)
}
return body["channel"].(map[string]any)["id"].(string)
}
selected := channel(owner, "Selected", true)
unselected := channel(owner, "Unselected", true)
disabled := channel(owner, "Disabled", false)
if got := groups(owner)[0].(map[string]any)["channel_ids"].([]any); len(got) != 3 {
t.Fatalf("default channels = %v", got)
}
group := func(name string, channels []string) string {
t.Helper()
st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": name, "channel_ids": channels})
if st != http.StatusCreated {
t.Fatalf("create group = %d %v", st, body)
}
return body["id"].(string)
}
a := group("Operations", []string{selected, selected, disabled})
b := group("Escalation", []string{selected})
monitor := map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600}
st, body := owner.do("POST", "/api/v1/org/monitors", monitor)
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
id := body["id"].(string)
token := body["target"].(string)
if got := body["alert_group_ids"].([]any); len(got) != 1 || got[0] != defaultID {
t.Fatalf("default monitor assignments = %v", got)
}
st, _, html := owner.page("/monitors/" + id + "/edit")
if st != http.StatusOK || !strings.Contains(html, `name="alert_group_ids"`) || !strings.Contains(html, "Operations") {
t.Fatalf("monitor editor = %d, lacks alert groups", st)
}
st, _, html = owner.page("/settings/channels")
if st != http.StatusOK || !strings.Contains(html, "/org/alert-groups/"+a) {
t.Fatalf("settings = %d, lacks alert group editor", st)
}
monitor["alert_group_ids"] = []string{a, b, a}
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
t.Fatalf("assign groups = %d %v", st, body)
}
delete(monitor, "alert_group_ids")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
t.Fatalf("preserve assignments = %d %v", st, body)
}
// Exercise actual incident transitions and their outbox, including recovery.
for _, suffix := range []string{"/fail", ""} {
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader(""))
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode)
}
}
count := func(ch string) int {
return e.count(t, `SELECT count(*) FROM notifications n JOIN incidents i ON i.id=n.incident_id WHERE i.monitor_id=$1 AND n.channel_id=$2`, id, ch)
}
if count(selected) != 2 || count(unselected) != 0 || count(disabled) != 0 {
t.Fatalf("deliveries selected/unselected/disabled = %d/%d/%d", count(selected), count(unselected), count(disabled))
}
other := e.browser(t)
other.signup("x@"+uniq("ag")+".test", uniq("agx-"))
foreignGroup := groups(other)[0].(map[string]any)["id"].(string)
foreignChannel := channel(other, "Foreign", true)
monitor["alert_group_ids"] = []string{foreignGroup}
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
expect(t, "foreign monitor assignment", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
expect(t, "foreign assignment on creation", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Changed", "channel_ids": []string{foreignChannel}})
expect(t, "foreign channel assignment", st, body, http.StatusUnprocessableEntity, "invalid_channel")
st, body = other.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Stolen"})
expect(t, "foreign group update", st, body, http.StatusNotFound, "not_found")
for _, g := range groups(owner) {
g := g.(map[string]any)
if g["id"] == a && (g["name"] != "Operations" || len(g["channel_ids"].([]any)) != 2) {
t.Fatalf("failed update changed group: %v", g)
}
}
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
monitors := body["monitors"].([]any)
if len(monitors) != 1 || len(monitors[0].(map[string]any)["alert_group_ids"].([]any)) != 2 {
t.Fatalf("failed assignment changed monitors: %v", monitors)
}
viewer := e.joinVia(t, owner.invite("v@"+uniq("ag")+".test", owner.roleID("viewer")))
st, body = viewer.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": "Forbidden"})
expect(t, "viewer creates group", st, body, http.StatusForbidden, "forbidden")
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+defaultID, nil)
expect(t, "protected default", st, body, http.StatusNotFound, "alert_group_not_deletable")
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+defaultID, map[string]any{"name": "Standard", "channel_ids": []string{selected}})
if st != http.StatusOK || body["is_default"] != true {
t.Fatalf("edit default = %d %v", st, body)
}
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+a, nil)
expect(t, "delete custom group", st, body, http.StatusNoContent, "")
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
assigned := body["monitors"].([]any)[0].(map[string]any)["alert_group_ids"].([]any)
if !slices.Equal(assigned, []any{b}) {
t.Fatalf("assignments after group deletion = %v", assigned)
}
monitor["alert_group_ids"] = []string{}
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 0 {
t.Fatalf("clear assignments = %d %v", st, body)
}
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+"/fail", "text/plain", strings.NewReader(""))
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK || count(selected) != 2 {
t.Fatalf("unassigned monitor queued notifications, status=%d count=%d", resp.StatusCode, count(selected))
}
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
if st != http.StatusCreated || len(body["alert_group_ids"].([]any)) != 0 {
t.Fatalf("explicit empty creation = %d %v", st, body)
}
}
func TestAlertGroupQuietHours(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("q@"+uniq("agq")+".test", uniq("agq-"))
channel := func(name string) string {
t.Helper()
req := map[string]any{
"name": name,
"type": "webhook",
"url": "https://example.test/hook",
"enabled": true,
}
st, body := owner.do("POST", "/api/v1/org/channels", req)
if st != http.StatusCreated {
t.Fatalf("POST /api/v1/org/channels = %d %v, want %d", st, body, http.StatusCreated)
}
return body["channel"].(map[string]any)["id"].(string)
}
quietCh := channel("QuietOnly")
sharedCh := channel("Shared")
activeCh := channel("ActiveOnly")
// Invalid quiet hours are rejected.
st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
"name": "BadTZ",
"channel_ids": []string{quietCh},
"quiet_hours": []map[string]any{{"start": "22:00", "end": "07:00", "time_zone": "Not/AZone"}},
})
expect(t, "invalid timezone", st, body, http.StatusUnprocessableEntity, "invalid_time_zone")
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
"name": "BadRange",
"channel_ids": []string{quietCh},
"quiet_hours": []map[string]any{{"start": "12:00", "end": "12:00", "time_zone": "UTC"}},
})
expect(t, "equal non-zero times", st, body, http.StatusUnprocessableEntity, "invalid_quiet_hours")
// Create a group that is muted 24/7 (00:00-00:00 every day) and an active group.
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
"name": "Muted",
"channel_ids": []string{quietCh, sharedCh},
"quiet_hours": []map[string]any{{"weekdays": []string{}, "start": "00:00", "end": "00:00", "time_zone": "UTC"}},
})
if st != http.StatusCreated {
t.Fatalf("create muted group = %d %v", st, body)
}
mutedGroup := body["id"].(string)
if qh := body["quiet_hours"].([]any); len(qh) != 1 {
t.Fatalf("quiet_hours = %v", qh)
}
// Updating without quiet_hours preserves existing quiet hours.
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{
"name": "Muted Renamed",
"channel_ids": []string{quietCh, sharedCh},
})
if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 1 {
t.Fatalf("preserve quiet_hours = %d %v", st, body)
}
// Settings page shows the quiet hours inputs and active badge.
st, _, html := owner.page("/settings/channels")
if st != http.StatusOK || !strings.Contains(html, `name="quiet_hours.0.start"`) || !strings.Contains(html, "Quiet hours active") {
t.Fatalf("settings page = %d, lacks quiet hours UI", st)
}
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
"name": "AlwaysOn",
"channel_ids": []string{activeCh, sharedCh},
"quiet_hours": []map[string]any{},
})
if st != http.StatusCreated {
t.Fatalf("create active group = %d %v", st, body)
}
activeGroup := body["id"].(string)
// Monitor assigned only to Muted: incident opens & resolves, 0 notifications sent.
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "SilentBackup", "type": "heartbeat", "interval_seconds": 3600,
"alert_group_ids": []string{mutedGroup},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
monID := body["id"].(string)
token := body["target"].(string)
ping := func(suffix string) {
t.Helper()
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader(""))
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode)
}
}
count := func(ch string) int {
const q = `SELECT count(*) FROM notifications n
JOIN incidents i ON i.id = n.incident_id
WHERE i.monitor_id = $1 AND n.channel_id = $2`
return e.count(t, q, monID, ch)
}
ping("/fail")
ping("")
if inc := e.count(t, `SELECT count(*) FROM incidents WHERE monitor_id=$1`, monID); inc != 1 {
t.Fatalf("incidents = %d, want 1", inc)
}
if q, s := count(quietCh), count(sharedCh); q != 0 || s != 0 {
t.Fatalf("muted notifications quiet/shared = %d/%d, want 0/0", q, s)
}
// Assign both Muted and AlwaysOn: only AlwaysOn's channels (activeCh + sharedCh) notify,
// while quietCh stays silent.
st, body = owner.do("PUT", "/api/v1/org/monitors/"+monID, map[string]any{
"name": "SilentBackup",
"type": "heartbeat",
"interval_seconds": 3600,
"alert_group_ids": []string{mutedGroup, activeGroup},
})
if st != http.StatusOK {
t.Fatalf("PUT /api/v1/org/monitors/%s = %d %v, want %d", monID, st, body, http.StatusOK)
}
ping("/fail")
ping("")
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 0 || a != 2 || s != 2 {
t.Fatalf("mixed deliveries quiet/active/shared = %d/%d/%d, want 0/2/2", q, a, s)
}
// Explicitly clearing quiet_hours re-enables notifications on quietCh.
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{
"name": "Muted Renamed",
"channel_ids": []string{quietCh, sharedCh},
"quiet_hours": []map[string]any{},
})
if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 0 {
t.Fatalf("clear quiet_hours = %d %v, want 200 with empty quiet_hours", st, body)
}
ping("/fail")
ping("")
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 2 || a != 4 || s != 4 {
t.Fatalf("after clearing quiet hours quiet/active/shared = %d/%d/%d, want 2/4/4", q, a, s)
}
}
+25 -2
View File
@@ -61,7 +61,8 @@ func (s *Server) evaluateResults(ctx context.Context, region string, results []a
}
// transition opens or resolves the monitor's incident and queues a
// notification for every enabled channel of the org, in one transaction.
// notification for every enabled channel assigned to the monitor, in one
// transaction.
func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error {
return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error {
var (
@@ -96,10 +97,25 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
if err != nil {
return err
}
channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID)
routes, err := q.MonitorAlertRoutes(ctx, m.ID)
if err != nil {
return err
}
quiet := map[uuid.UUID]bool{}
seen := map[uuid.UUID]bool{}
var channels []uuid.UUID
for _, r := range routes {
muted, ok := quiet[r.GroupID]
if !ok {
muted = isQuietRawAt(r.QuietHours, at)
quiet[r.GroupID] = muted
}
if muted || seen[r.ChannelID] {
continue
}
seen[r.ChannelID] = true
channels = append(channels, r.ChannelID)
}
for _, ch := range channels {
if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil {
return err
@@ -217,6 +233,13 @@ func (s *Server) send(ctx context.Context, typ string, config []byte, ev notify.
}
return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale))
}
if p, ok := notify.Lookup(typ); ok {
settings, locale, err := s.openProviderSettings(typ, config)
if err != nil {
return err
}
return p.Send(ctx, settings, s.messageFor(ev, locale), !s.cloud())
}
return fmt.Errorf("unknown channel type %q", typ)
}
+1 -1
View File
@@ -60,7 +60,7 @@ func (r *receiver) kinds() []string {
func TestAlerting(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) { c.SMTPURL = mail.URL() })
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
+462
View File
@@ -0,0 +1,462 @@
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"sort"
"strings"
"time"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Alertmanager feeds monitors: it sends its alerts to a receiver URL of an
// organization, and a monitor of type alertmanager is down while an alert
// matching its label matchers fires.
const (
alertmanagerRegion = "alertmanager"
// receiverTokenPrefix tells receiver tokens apart from API tokens.
receiverTokenPrefix = "uam_"
// maxAlertmanagerBody bounds one webhook; Alertmanager batches alerts
// per group, and its default limit is far lower.
maxAlertmanagerBody = 4 << 20
// keepAlerts outlasts the longest stale period a monitor may set.
keepAlerts = 31 * 24 * time.Hour
)
// alertmanagerWebhook is Alertmanager's webhook payload (version 4).
type alertmanagerWebhook struct {
Version string `json:"version"`
Status string `json:"status"`
Alerts []struct {
Status string `json:"status"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
StartsAt time.Time `json:"startsAt"`
GeneratorURL string `json:"generatorURL"`
Fingerprint string `json:"fingerprint"`
} `json:"alerts"`
}
func (s *Server) mountAlertmanager(r gin.IRouter) {
r.POST("/am", s.alertmanagerWebhook)
r.POST("/am/:token", s.alertmanagerWebhook)
}
// alertmanagerWebhook takes the receiver token from the path or, as
// Alertmanager's http_config can send it, as a bearer token.
func (s *Server) alertmanagerWebhook(c *gin.Context) {
tok := c.Param("token")
if tok == "" {
tok = bearerToken(c)
}
if !strings.HasPrefix(tok, receiverTokenPrefix) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
if !s.limit(c, "am:"+tok[:min(len(tok), 16)], 600, time.Minute) {
return
}
var payload alertmanagerWebhook
if err := json.NewDecoder(http.MaxBytesReader(c.Writer, c.Request.Body, maxAlertmanagerBody)).Decode(&payload); err != nil {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
var receiver store.AlertmanagerReceiverByHashRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if receiver, err = q.AlertmanagerReceiverByHash(ctx, HashToken(tok)); err != nil {
return err
}
for _, a := range payload.Alerts {
if a.Fingerprint == "" || len(a.Fingerprint) > 200 || (a.Status != "firing" && a.Status != "resolved") {
continue
}
labels, _ := json.Marshal(nonNil(a.Labels))
annotations, _ := json.Marshal(nonNil(a.Annotations))
if err := q.UpsertAlertmanagerAlert(ctx, store.UpsertAlertmanagerAlertParams{
OrgID: receiver.OrgID, Fingerprint: a.Fingerprint, ReceiverID: receiver.ID, Status: a.Status,
Labels: labels, Annotations: annotations, StartsAt: a.StartsAt, GeneratorUrl: truncate(a.GeneratorURL, 2000),
}); err != nil {
return err
}
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
if err != nil {
internalError(c, err)
return
}
// State changes show at once; unchanged monitors wait for their interval.
if err := s.CheckAlertmanagerMonitors(ctx, &receiver.OrgID, time.Now(), true); err != nil {
s.log.ErrorContext(ctx, "evaluating alertmanager monitors failed", "error", err)
}
c.Status(http.StatusNoContent)
}
func nonNil(m map[string]string) map[string]string {
if m == nil {
return map[string]string{}
}
return m
}
// firingAlert is an alert of the overview and of monitor evaluation.
type firingAlert struct {
Fingerprint string `json:"fingerprint"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
StartsAt time.Time `json:"starts_at"`
UpdatedAt time.Time `json:"updated_at"`
GeneratorURL string `json:"generator_url,omitempty"`
}
func loadFiringAlerts(ctx context.Context, q *store.Queries, org uuid.UUID, since time.Time) ([]firingAlert, error) {
rows, err := q.FiringAlerts(ctx, store.FiringAlertsParams{OrgID: org, UpdatedAt: since})
out := make([]firingAlert, 0, len(rows))
for _, r := range rows {
a := firingAlert{Fingerprint: r.Fingerprint, StartsAt: r.StartsAt, UpdatedAt: r.UpdatedAt, GeneratorURL: r.GeneratorUrl}
_ = json.Unmarshal(r.Labels, &a.Labels)
_ = json.Unmarshal(r.Annotations, &a.Annotations)
out = append(out, a)
}
return out, err
}
// alertSummary names an alert for result messages: alertname, the summary
// annotation if any.
func alertSummary(a firingAlert) string {
name := a.Labels["alertname"]
if name == "" {
name = a.Fingerprint
}
if sum := a.Annotations["summary"]; sum != "" {
return name + ": " + sum
}
return name
}
// CheckAlertmanagerMonitors records the state of alertmanager monitors, of
// org or of all organizations. On a webhook (changed) it records monitors
// whose state differs from their last result; otherwise it records those
// whose interval has passed, so charts and the SLA have results to show.
func (s *Server) CheckAlertmanagerMonitors(ctx context.Context, org *uuid.UUID, now time.Time, changed bool) error {
var (
monitors []store.AlertmanagerMonitorsRow
alerts = map[uuid.UUID][]firingAlert{}
latest = map[uuid.UUID]store.LatestResultForMonitorRow{}
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if monitors, err = q.AlertmanagerMonitors(ctx, org); err != nil {
return err
}
for _, m := range monitors {
if _, ok := alerts[m.OrgID]; !ok {
// Alerts older than the longest stale period are filtered
// per monitor below.
if alerts[m.OrgID], err = loadFiringAlerts(ctx, q, m.OrgID, now.Add(-30*24*time.Hour)); err != nil {
return err
}
}
if changed {
r, err := q.LatestResultForMonitor(ctx, store.LatestResultForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID})
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return err
}
if err == nil {
latest[m.ID] = r
}
}
}
return nil
})
if err != nil {
return err
}
for _, m := range monitors {
var cfg check.AlertmanagerConfig
_ = json.Unmarshal(m.Config, &cfg)
stale := now.Add(-time.Duration(max(cfg.StaleHours, 1)) * time.Hour)
var matching []string
for _, a := range alerts[m.OrgID] {
if a.UpdatedAt.After(stale) && cfg.Matches(a.Labels) {
matching = append(matching, alertSummary(a))
}
}
ok := len(matching) == 0
msg := ""
if !ok {
sort.Strings(matching)
msg = fmt.Sprintf("%d firing: %s", len(matching), strings.Join(matching, "; "))
}
if changed {
last, seen := latest[m.ID]
if seen && last.Ok == ok && last.Error == msg {
continue
}
} else if now.Sub(m.LastResult) < time.Duration(m.IntervalSeconds)*time.Second {
continue
}
if err := s.recordPassive(ctx, alertmanagerRegion, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, now); err != nil {
return err
}
}
return nil
}
type receiverView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"`
CreatedAt time.Time `json:"created_at"`
LastReceivedAt *time.Time `json:"last_received_at"`
}
type receiverRequest struct {
Name string `json:"name" binding:"required,max=100"`
}
func (s *Server) listReceivers(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
var rows []store.ListAlertmanagerReceiversRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListAlertmanagerReceivers(ctx)
return err
})
if err != nil {
internalError(c, err)
return
}
out := make([]receiverView, len(rows))
for i, r := range rows {
out[i] = receiverView{ID: r.ID, Name: r.Name, Prefix: r.Prefix, CreatedAt: r.CreatedAt, LastReceivedAt: r.LastReceivedAt}
}
c.JSON(http.StatusOK, gin.H{"receivers": out})
}
// createReceiver returns the webhook URL once; only its hash is kept.
func (s *Server) createReceiver(c *gin.Context) {
var req receiverRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
tok := receiverTokenPrefix + auth.RandomToken()
var row store.CreateAlertmanagerReceiverRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.CreateAlertmanagerReceiver(ctx, store.CreateAlertmanagerReceiverParams{
OrgID: p.Org.ID, Name: strings.TrimSpace(req.Name), TokenHash: HashToken(tok), Prefix: tok[:len(receiverTokenPrefix)+6],
})
return err
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{
"receiver": receiverView{ID: row.ID, Name: row.Name, Prefix: row.Prefix, CreatedAt: row.CreatedAt},
"url": s.alertmanagerURL(tok),
})
}
func (s *Server) alertmanagerURL(tok string) string {
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/am/" + tok
}
func (s *Server) deleteReceiver(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
p := current(c)
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
n, err = q.DeleteAlertmanagerReceiver(ctx, id)
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
// alertView is a firing alert with the monitors that follow it.
type alertView struct {
firingAlert
Monitors []alertMonitorRef `json:"monitors"`
}
type alertMonitorRef struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
}
// firingAlertViews lists the organization's firing alerts and which
// monitors they hold down, so alerts no monitor follows stand out.
// firingAlertViews reads a page of firing alerts, newest first, with the
// monitors they match.
func (s *Server) firingAlertViews(ctx context.Context, p *principal, pg pageReq) ([]alertView, pageInfo, error) {
now := time.Now()
var (
rows []store.FiringAlertsPageRow
monitors []store.AlertmanagerMonitorsRow
)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if rows, err = q.FiringAlertsPage(ctx, store.FiringAlertsPageParams{
OrgID: p.Org.ID, Since: now.Add(-time.Duration(check.DefaultStaleHours) * time.Hour),
AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
}); err != nil {
return err
}
monitors, err = q.AlertmanagerMonitors(ctx, &p.Org.ID)
return err
})
if err != nil {
return nil, pageInfo{}, err
}
rows, info := paginate(pg, rows, func(r store.FiringAlertsPageRow) cursor { return cursor{T: r.StartsAt, S: r.Fingerprint} })
alerts := make([]firingAlert, len(rows))
for i, r := range rows {
alerts[i] = firingAlert{Fingerprint: r.Fingerprint, StartsAt: r.StartsAt, UpdatedAt: r.UpdatedAt, GeneratorURL: r.GeneratorUrl}
_ = json.Unmarshal(r.Labels, &alerts[i].Labels)
_ = json.Unmarshal(r.Annotations, &alerts[i].Annotations)
}
out := make([]alertView, len(alerts))
for i, a := range alerts {
out[i] = alertView{firingAlert: a, Monitors: []alertMonitorRef{}}
for _, m := range monitors {
var cfg check.AlertmanagerConfig
_ = json.Unmarshal(m.Config, &cfg)
if cfg.Matches(a.Labels) {
out[i].Monitors = append(out[i].Monitors, alertMonitorRef{ID: m.ID, Name: m.Name})
}
}
}
return out, info, nil
}
func (s *Server) listFiringAlerts(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
out, info, err := s.firingAlertViews(c.Request.Context(), current(c), pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"alerts": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
// suggestedMatchers proposes matchers for a monitor following a: its
// alertname and the labels that usually tell services apart.
func suggestedMatchers(a firingAlert) []check.Matcher {
var out []check.Matcher
for _, l := range []string{"alertname", "service", "job", "namespace", "instance"} {
if v, ok := a.Labels[l]; ok && v != "" {
out = append(out, check.Matcher{Label: l, Op: "=", Value: v})
}
if len(out) == 3 {
break
}
}
return slices.Clip(out)
}
func (s *Server) alertmanagerPage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
alerts, info, err := s.firingAlertViews(ctx, p, pg)
if err != nil {
return nil, err
}
v := web.AlertmanagerView{CanManage: p.Grants.Can(authz.OrgManage), Pager: pager(c, info)}
for _, a := range alerts {
row := web.AlertRow{
Name: a.Labels["alertname"], Summary: a.Annotations["summary"],
Since: a.StartsAt.Local().Format("2006-01-02 15:04"), Labels: sortedLabels(a.Labels),
}
if row.Name == "" {
row.Name = a.Fingerprint
}
for _, m := range a.Monitors {
row.Monitors = append(row.Monitors, web.CheckerLink{URL: "/monitors/" + m.ID.String(), Label: m.Name})
}
q := url.Values{"type": {string(check.Alertmanager)}, "name": {row.Name}}
for _, m := range suggestedMatchers(a.firingAlert) {
q.Add("m", m.Label+"="+m.Value)
}
row.CreateURL = "/monitors/new?" + q.Encode()
v.Alerts = append(v.Alerts, row)
}
if v.CanManage {
var rows []store.ListAlertmanagerReceiversRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListAlertmanagerReceivers(ctx)
return err
})
if err != nil {
return nil, err
}
for _, r := range rows {
row := web.ReceiverRow{ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, Created: r.CreatedAt.Local().Format("2006-01-02"), LastSeen: "–"}
if r.LastReceivedAt != nil {
row.LastSeen = r.LastReceivedAt.Local().Format("2006-01-02 15:04")
}
v.Receivers = append(v.Receivers, row)
}
}
return web.AlertmanagerPage(page, me, v), nil
}
func sortedLabels(labels map[string]string) [][2]string {
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
slices.Sort(keys)
out := make([][2]string, len(keys))
for i, k := range keys {
out[i] = [2]string{k, labels[k]}
}
return out
}
+142
View File
@@ -0,0 +1,142 @@
package api_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func TestAlertmanagerMonitor(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("am")+".test", uniq("am-"))
st, body := owner.do("POST", "/api/v1/org/alertmanager/receivers", map[string]any{"name": "prod"})
if st != http.StatusCreated {
t.Fatalf("create receiver = %d %v", st, body)
}
hook := body["url"].(string)
token := hook[strings.LastIndex(hook, "/")+1:]
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Shop errors", "type": "alertmanager", "interval_seconds": 60,
"config": map[string]any{"matchers": []map[string]string{
{"label": "alertname", "op": "=", "value": "HighErrorRate"},
{"label": "severity", "op": "=~", "value": "critical|page"},
}},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
monitor := body["id"].(string)
send := func(url, auth string, alerts ...map[string]any) int {
t.Helper()
raw, _ := json.Marshal(map[string]any{"version": "4", "status": "firing", "alerts": alerts})
req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
if auth != "" {
req.Header.Set("Authorization", "Bearer "+auth)
}
resp, err := e.srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
return resp.StatusCode
}
alert := func(fp, status, name, severity, service string) map[string]any {
return map[string]any{
"status": status, "fingerprint": fp, "startsAt": time.Now().Add(-time.Minute),
"labels": map[string]string{"alertname": name, "severity": severity, "service": service},
"annotations": map[string]string{"summary": "Error rate above 5%"},
}
}
open := func() bool {
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
for _, i := range b["incidents"].([]any) {
if i.(map[string]any)["resolved_at"] == nil {
return true
}
}
return false
}
if st := send(e.srv.URL+"/am/uam_wrong", "", alert("a1", "firing", "HighErrorRate", "critical", "shop")); st != http.StatusUnauthorized {
t.Errorf("wrong token = %d, want 401", st)
}
if st := send(hook, "", alert("a1", "firing", "HighErrorRate", "critical", "shop"), alert("a2", "firing", "DiskFull", "warning", "db")); st != http.StatusNoContent {
t.Fatalf("webhook = %d", st)
}
if !open() {
t.Fatal("a matching firing alert opened no incident")
}
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
if !strings.Contains(mustJSON(list), "1 firing: HighErrorRate: Error rate above 5%") {
t.Errorf("result message missing: %s", mustJSON(list))
}
// The overview shows which alerts no monitor follows, with a way to add one.
_, alerts := owner.do("GET", "/api/v1/org/alertmanager/alerts", nil)
var followed, unfollowed int
for _, a := range alerts["alerts"].([]any) {
if len(a.(map[string]any)["monitors"].([]any)) > 0 {
followed++
} else {
unfollowed++
}
}
if followed != 1 || unfollowed != 1 {
t.Errorf("alerts followed/unfollowed = %d/%d, want 1/1", followed, unfollowed)
}
_, _, page := owner.page("/settings/alertmanager")
if !strings.Contains(page, "/monitors/new?") || !strings.Contains(page, "DiskFull") {
t.Error("the overview does not offer to create a monitor for DiskFull")
}
_, _, editor := owner.page("/monitors/new?type=alertmanager&name=DiskFull&m=alertname%3DDiskFull&m=service%3Ddb")
if !strings.Contains(editor, `value="DiskFull"`) || !strings.Contains(editor, `value="db"`) {
t.Error("the editor is not prefilled from the alert")
}
// Resolved, sent with the token as bearer.
if st := send(e.srv.URL+"/am", token, alert("a1", "resolved", "HighErrorRate", "critical", "shop")); st != http.StatusNoContent {
t.Fatalf("bearer webhook = %d", st)
}
if open() {
t.Fatal("the resolved alert did not resolve the incident")
}
// An alert Alertmanager stopped repeating ends after the stale period.
send(hook, "", alert("a3", "firing", "HighErrorRate", "page", "shop"))
if !open() {
t.Fatal("no incident for the second alert")
}
ctx := context.Background()
org := uuid.MustParse(owner.orgID())
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE alertmanager_alerts SET updated_at = now() - interval '25 hours' WHERE org_id = $1 AND fingerprint = 'a3'`, org)
return err
}); err != nil {
t.Fatal(err)
}
if err := e.api.CheckAlertmanagerMonitors(ctx, &org, time.Now(), true); err != nil {
t.Fatal(err)
}
if open() {
t.Error("a stale alert still holds the monitor down")
}
// Other organizations see none of it.
other := e.browser(t)
other.signup("x@"+uniq("am")+".test", uniq("amx-"))
if _, oa := other.do("GET", "/api/v1/org/alertmanager/alerts", nil); len(oa["alerts"].([]any)) != 0 {
t.Error("another organization sees the alerts")
}
_ = monitor
}
+113 -18
View File
@@ -12,13 +12,28 @@ import (
// sessionStarted is the answer of requests that sign in.
var sessionStarted = obj{"status": "", "csrf_token": ""}
// paged adds the cursors of a paged list to its response.
func paged(o obj) obj {
o["next_cursor"], o["prev_cursor"] = "", ""
return o
}
// endpoints documents every route under /api/v1, in the order the docs
// show them.
var endpoints = []endpoint{
// Account
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account and organization", public: true,
description: "Starts a session. Depending on the installation, sign-up is open, limited to the first user, or closed.",
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
req: signupRequest{}, resp: sessionStarted},
{method: "POST", path: "/api/v1/auth/verify", tag: "Account", summary: "Confirm an email address with the mailed token", public: true,
description: "Signs the account in. Tokens are valid for 24 hours and once; `410 verification_expired` otherwise.",
req: verifyRequest{}, resp: sessionStarted},
{method: "POST", path: "/api/v1/auth/verify/resend", tag: "Account", summary: "Mail a new confirmation link", public: true,
description: "Answers the same whether or not an unconfirmed account with that address exists.",
req: resendRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/orgs", tag: "Account", summary: "Create an organization", sessionOnly: true,
description: "The account owns it, and it becomes the active organization. Limited per account by the platform (`422 org_limit`).",
req: createOrgRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "slug": "", "redirect": ""}},
{method: "POST", path: "/api/v1/auth/login", tag: "Account", summary: "Sign in with email and password", public: true,
description: "Answers `{\"status\": \"totp_required\"}` when the account has two-factor authentication; continue with /auth/login/totp.",
req: loginRequest{}, resp: sessionStarted},
@@ -39,7 +54,7 @@ var endpoints = []endpoint{
{method: "POST", path: "/api/v1/me/totp/recovery-codes", tag: "Account", summary: "Replace the recovery codes", sessionOnly: true,
req: reauthRequest{}, resp: obj{"recovery_codes": []string{}}},
{method: "GET", path: "/api/v1/me/audit", tag: "Account", summary: "Sign-ins and security changes of the account",
resp: obj{"events": []auditEventView{}}},
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)",
description: "`?format=pdf` returns a PDF instead of JSON.", resp: accountExport{}},
{method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
@@ -54,23 +69,34 @@ var endpoints = []endpoint{
// Monitors
{method: "GET", path: "/api/v1/org/monitors", tag: "Monitors", summary: "List monitors with their latest results",
description: "Only monitors the caller may read; header values and heartbeat tokens only for those who may change the monitor.",
perm: "monitors.read", resp: obj{"monitors": []monitorView{}}},
description: "Paged by name. Only monitors the caller may read, so a page may hold fewer; header values and heartbeat tokens only for those who may change the monitor.",
perm: "monitors.read", resp: paged(obj{"monitors": []monitorView{}})},
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp or heartbeat; `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, HeartbeatConfig). Heartbeat monitors take neither target nor regions and return their `ping_url`.",
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
req: monitorRequest{}, resp: monitorView{}},
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
req: monitorRequest{}, resp: monitorView{}},
{method: "DELETE", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Delete a monitor and its history", perm: "monitors.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/monitors/:id/evidence", tag: "Monitors", summary: "What checkers saw: captured responses",
perm: "monitors.write", resp: obj{"evidence": []evidenceSummary{}}},
description: "Paged, newest first.", perm: "monitors.write", resp: paged(obj{"evidence": []evidenceSummary{}})},
{method: "GET", path: "/api/v1/org/monitors/:id/results", tag: "Monitors", summary: "A monitor's check results",
description: "Paged, newest first, back to the end of raw result retention.", resp: paged(obj{"results": []resultView{}})},
{method: "GET", path: "/api/v1/org/monitors/:id/evidence/:evidence", tag: "Monitors", summary: "One captured response",
description: "Redirect chain with headers, timing, certificate and the first 32 KiB of the body.",
perm: "monitors.write", resp: obj{"id": uuid.UUID{}, "region": "", "checker_id": uuid.UUID{}, "time": time.Time{}, "ok": false, "status_code": new(int32), "error": new(string), "evidence": check.Evidence{}}},
{method: "GET", path: "/api/v1/org/checkers/:id", tag: "Monitors", summary: "What a checker instance is doing",
description: "Platform checkers serve every organization; other organizations' work appears only as a count.",
description: "Platform checkers serve every organization; other organizations' work appears only as a count. `recent` is paged, newest first; a page may hold fewer results than `limit` when some belong to monitors you cannot read.",
resp: checkerActivity{}},
{method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage",
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, region_limit or platform_region_limit.",
resp: usageView{}},
{method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types this installation offers",
resp: obj{"types": []string{}}},
{method: "PUT", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Choose the monitor types offered to members",
description: "Out of the types the platform offers; types left out are not offered for new monitors or type changes, existing monitors keep running.",
perm: "org.manage", sessionOnly: true, req: checkTypesRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/groups", tag: "Monitors", summary: "List monitor groups", resp: obj{"groups": []groupView{}}},
{method: "POST", path: "/api/v1/org/groups", tag: "Monitors", summary: "Create a group", perm: "monitors.write",
req: groupRequest{}, status: http.StatusCreated, resp: groupView{}},
@@ -79,7 +105,7 @@ var endpoints = []endpoint{
{method: "DELETE", path: "/api/v1/org/groups/:id", tag: "Monitors", summary: "Delete a group; its content moves up", perm: "monitors.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/maintenance", tag: "Monitors", summary: "List maintenance windows", perm: "monitors.read",
resp: obj{"maintenance": []maintenanceView{}}},
description: "Paged, latest start first. Only windows the caller may read, so a page may hold fewer.", resp: paged(obj{"maintenance": []maintenanceView{}})},
{method: "POST", path: "/api/v1/org/maintenance", tag: "Monitors", summary: "Plan maintenance",
description: "During maintenance, failures open no incidents and send no notifications.",
perm: "monitors.write", req: maintenanceRequest{}, status: http.StatusCreated, resp: maintenanceView{}},
@@ -87,8 +113,18 @@ var endpoints = []endpoint{
req: maintenanceRequest{}, resp: maintenanceView{}},
{method: "DELETE", path: "/api/v1/org/maintenance/:id", tag: "Monitors", summary: "Delete maintenance", perm: "monitors.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/alertmanager/alerts", tag: "Monitors", summary: "Alerts Alertmanager reports as firing",
description: "Paged, newest first. With the alertmanager monitors each alert holds down; alerts no monitor follows have none.",
perm: "monitors.read", resp: paged(obj{"alerts": []alertView{}})},
{method: "GET", path: "/api/v1/org/alertmanager/receivers", tag: "Monitors", summary: "List Alertmanager receivers", perm: "org.manage",
resp: obj{"receivers": []receiverView{}}},
{method: "POST", path: "/api/v1/org/alertmanager/receivers", tag: "Monitors", summary: "Create a receiver URL for Alertmanager's webhook",
description: "The URL is returned only this once. Alertmanager may also send its token as `Authorization: Bearer` to `/am`.",
perm: "org.manage", sessionOnly: true, req: receiverRequest{}, status: http.StatusCreated, resp: obj{"receiver": receiverView{}, "url": ""}},
{method: "DELETE", path: "/api/v1/org/alertmanager/receivers/:id", tag: "Monitors", summary: "Delete a receiver", perm: "org.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/incidents", tag: "Monitors", summary: "List incidents", perm: "incidents.read",
resp: obj{"incidents": []incidentView{}}},
description: "Paged, newest first. `monitor_id` limits them to one monitor.", resp: paged(obj{"incidents": []incidentView{}})},
// Status pages
{method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}},
@@ -98,8 +134,18 @@ var endpoints = []endpoint{
req: statusPageRequest{}, resp: statusPageView{}},
{method: "DELETE", path: "/api/v1/org/statuspages/:id", tag: "Status pages", summary: "Delete a status page", perm: "statuspages.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "List status page groups", perm: "statuspages.read",
resp: obj{"groups": []pageGroupView{}}},
{method: "POST", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "Create a status page group", perm: "statuspages.write",
req: pageGroupRequest{}, status: http.StatusCreated, resp: pageGroupView{}},
{method: "PUT", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Rename, move or reorder a status page group", perm: "statuspages.write",
req: pageGroupRequest{}, resp: pageGroupView{}},
{method: "DELETE", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Delete a status page group", perm: "statuspages.write",
description: "Child groups and monitors move up to the deleted group's parent.", status: http.StatusNoContent},
{method: "POST", path: "/api/v1/org/statuspages/:id/groups/import", tag: "Status pages", summary: "Import monitor groups into a status page", perm: "statuspages.write",
description: "Copies the organization's monitor group tree for the page's monitors and maps them into the imported groups.", resp: obj{"groups": []pageGroupView{}}},
{method: "PUT", path: "/api/v1/org/statuspages/:id/monitors", tag: "Status pages", summary: "Set the monitors shown", perm: "statuspages.write",
req: pageMonitorsRequest{}, status: http.StatusNoContent},
description: "Assigns monitors to optional nested groups via `group_id`. Legacy `section` names are mapped to top-level groups.", req: pageMonitorsRequest{}, status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/org/statuspages/:id/domain", tag: "Status pages", summary: "Set a custom domain", perm: "statuspages.write",
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}},
{method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
@@ -108,11 +154,22 @@ var endpoints = []endpoint{
media: "text/html"},
// Alerting
{method: "GET", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "List alert groups and their channels", perm: "notifications.read",
resp: obj{"alert_groups": []alertGroupView{}}},
{method: "POST", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "Create an alert group", perm: "notifications.write",
description: "Optional `quiet_hours` suppress notifications from this group during recurring local time windows (`start`/`end` as `HH:MM`, `start > end` wraps overnight, `00:00`–`00:00` or `24:00` covers the full day, empty `weekdays` means every day).",
req: alertGroupRequest{}, status: http.StatusCreated, resp: alertGroupView{}},
{method: "PUT", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Update an alert group, its channels and quiet hours", perm: "notifications.write",
description: "Omitting `quiet_hours` preserves existing quiet hours; an empty array removes them.",
req: alertGroupRequest{}, resp: alertGroupView{}},
{method: "DELETE", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Delete an alert group", perm: "notifications.write",
description: "The default group cannot be deleted. Deleting other groups removes their monitor assignments; no fallback group is assigned.", status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read",
resp: obj{"channels": []channelView{}, "email_available": false}},
{method: "POST", path: "/api/v1/org/channels", tag: "Alerting", summary: "Create a channel",
description: "Webhook channels return their signing secret once.", perm: "notifications.write",
req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}},
description: "`type` is webhook (`url`), email (`to`, `locale`) or one of slack, discord, teams, googlechat, mattermost, rocketchat, telegram, matrix, ntfy, gotify, pushover, pushbullet, signal, pagerduty, opsgenie, apprise with their `settings`. Secret settings are stored encrypted and never returned; on update, leaving one empty keeps it. Webhook channels return their signing secret once. New channels join the default alert group.",
perm: "notifications.write",
req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}},
{method: "PUT", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Change a channel", perm: "notifications.write",
req: channelRequest{}, resp: obj{"channel": channelView{}, "signing_secret": ""}},
{method: "DELETE", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Delete a channel", perm: "notifications.write",
@@ -124,7 +181,7 @@ var endpoints = []endpoint{
{method: "PUT", path: "/api/v1/org/policy", tag: "Organization", summary: "Set sign-in and token policies", perm: "org.manage", sessionOnly: true,
req: policyRequest{}, resp: obj{"require_totp": false, "require_sso": false, "api_token_max_days": new(int32)}},
{method: "GET", path: "/api/v1/org/members", tag: "Organization", summary: "List members and their roles", perm: "members.read",
resp: obj{"members": []memberView{}}},
description: "Paged by email.", resp: paged(obj{"members": []memberView{}})},
{method: "DELETE", path: "/api/v1/org/members/:user", tag: "Organization", summary: "Remove a member", perm: "members.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "POST", path: "/api/v1/org/members/:user/roles", tag: "Organization", summary: "Assign a role, optionally limited to a group or status page",
@@ -169,6 +226,8 @@ var endpoints = []endpoint{
resp: obj{"agents": []agentView{}}},
{method: "POST", path: "/api/v1/org/agents", tag: "Organization", summary: "Create an agent token", perm: "org.manage", sessionOnly: true,
description: "The token is returned only this once.", req: agentRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "token": ""}},
{method: "PATCH", path: "/api/v1/org/agents/:id", tag: "Organization", summary: "Let a checker check private addresses or not",
description: "Applies from the checker's next poll.", perm: "org.manage", sessionOnly: true, req: agentUpdate{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/org/agents/:id", tag: "Organization", summary: "Revoke an agent", perm: "org.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/legal", tag: "Organization", summary: "Legal notice and privacy policy of the status pages", perm: "org.manage",
@@ -177,8 +236,7 @@ var endpoints = []endpoint{
description: "Markdown or a link; a link wins. Both empty removes the document.", perm: "org.manage",
req: legalRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/audit", tag: "Organization", summary: "The organization's audit log", perm: "audit.read",
description: "Newest first; pass `next_before` of the answer as `?before=` for older entries.",
resp: obj{"events": []auditEventView{}}},
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
{method: "GET", path: "/api/v1/org/export", tag: "Organization", summary: "Export the organization's data", perm: "org.manage", sessionOnly: true,
description: "`?format=pdf` returns a PDF instead of JSON.", resp: orgExport{}},
{method: "POST", path: "/api/v1/org/delete", tag: "Organization", summary: "Delete the organization with all its data", sessionOnly: true,
@@ -187,11 +245,48 @@ var endpoints = []endpoint{
// Platform
{method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin",
resp: obj{"events": []auditEventView{}}},
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
{method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin",
resp: obj{"documents": []legalView{}}},
{method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin",
req: legalRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Check types and whether they are offered", perm: "platform admin",
resp: obj{"types": []checkTypeView{}}},
{method: "PUT", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Choose the check types offered for new monitors",
description: "Types left out are switched off: not offered for new monitors or type changes; existing monitors keep running.",
perm: "platform admin", req: checkTypesRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Whether platform checkers may check private addresses", perm: "platform admin",
resp: checkerNetwork{}},
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/limits", tag: "Platform", summary: "Default limits of organizations and accounts", perm: "platform admin", resp: Limits{}},
{method: "PUT", path: "/api/v1/admin/limits", tag: "Platform", summary: "Set the default limits",
description: "0 means unlimited. Defaults apply at once to every organization and account without an override of its own. Lowering a limit below current usage keeps everything; only new monitors, status pages, regions or organizations are refused.",
perm: "platform admin", req: limitsRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/orgs", tag: "Platform", summary: "Organizations with usage, limits and owner",
description: "Paged, newest first. `q` searches name, slug and owner email.", perm: "platform admin", resp: paged(obj{"orgs": []adminOrg{}})},
{method: "PUT", path: "/api/v1/admin/orgs/:id/limits", tag: "Platform", summary: "Override an organization's limits",
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: orgLimitsView{}, status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/admin/users/:id/limits", tag: "Platform", summary: "Override how many organizations an account may own",
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: userLimitsRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/status-pages", tag: "Platform", summary: "Public and suspended status pages with organization and owner",
description: "Paged, newest first. `q` searches title, slug, domain, organization and owner email.",
perm: "platform admin", resp: paged(obj{"status_pages": []moderatedPage{}})},
{method: "PUT", path: "/api/v1/admin/status-pages/:id/suspension", tag: "Platform", summary: "Suspend or reinstate a status page",
description: "A suspended page is not served; status page servers drop it when they next ask for it.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/status-pages/:id", tag: "Platform", summary: "Delete a status page", perm: "platform admin", status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/admin/orgs/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an organization",
description: "A suspended organization's monitors are not checked, its status pages are not served, heartbeats and Alertmanager webhooks are refused, and its members and API tokens get 403 org_suspended.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/orgs/:id", tag: "Platform", summary: "Delete an organization with all its data", perm: "platform admin", status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/admin/users/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an account",
description: "A suspended account is signed out everywhere and can neither sign in nor use its API tokens. Platform admins cannot be suspended.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/users/:id", tag: "Platform", summary: "Delete an account",
description: "Organizations only the account belongs to are deleted with it; owning one shared with others gives 409 owns_shared_orgs. Platform admins cannot be deleted.",
perm: "platform admin", status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
resp: obj{"regions": []regionView{}}},
{method: "POST", path: "/api/v1/admin/regions", tag: "Platform", summary: "Create a platform region", perm: "platform admin",
+102 -81
View File
@@ -6,7 +6,6 @@ import (
"encoding/json"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
@@ -26,9 +25,15 @@ import (
// empty name marks a route deliberately not audited. A test fails for
// routes missing here, so new endpoints cannot slip past the log.
var auditActions = map[string]string{
"POST /api/v1/org/alert-groups": "alert_group.create",
"PUT /api/v1/org/alert-groups/:id": "alert_group.update",
"DELETE /api/v1/org/alert-groups/:id": "alert_group.delete",
"POST /api/v1/locale": "",
"POST /api/v1/markdown/preview": "",
"POST /api/v1/auth/signup": "account.signup",
"POST /api/v1/auth/verify": "account.verify",
"POST /api/v1/auth/verify/resend": "",
"POST /api/v1/orgs": "org.create",
"POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
@@ -42,50 +47,69 @@ var auditActions = map[string]string{
"POST /api/v1/invitations/:token/accept": "member.join",
"POST /api/v1/invitations/:token/signup": "member.join",
"PUT /api/v1/org/policy": "org.policy_update",
"POST /api/v1/org/monitors": "monitor.create",
"PUT /api/v1/org/monitors/:id": "monitor.update",
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
"POST /api/v1/org/maintenance": "maintenance.create",
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
"POST /api/v1/org/groups": "group.create",
"PUT /api/v1/org/groups/:id": "group.update",
"DELETE /api/v1/org/groups/:id": "group.delete",
"POST /api/v1/org/regions": "region.create",
"DELETE /api/v1/org/regions/:id": "region.delete",
"POST /api/v1/org/agents": "agent.create",
"DELETE /api/v1/org/agents/:id": "agent.delete",
"POST /api/v1/org/statuspages": "statuspage.create",
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
"POST /api/v1/org/channels": "channel.create",
"PUT /api/v1/org/channels/:id": "channel.update",
"DELETE /api/v1/org/channels/:id": "channel.delete",
"POST /api/v1/org/channels/:id/test": "channel.test",
"POST /api/v1/org/sso": "sso.create",
"PUT /api/v1/org/sso/:id": "sso.update",
"DELETE /api/v1/org/sso/:id": "sso.delete",
"DELETE /api/v1/org/members/:user": "member.remove",
"POST /api/v1/org/members/:user/roles": "member.role_assign",
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
"POST /api/v1/org/invitations": "invitation.create",
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
"POST /api/v1/org/roles": "role.create",
"PUT /api/v1/org/roles/:id": "role.update",
"DELETE /api/v1/org/roles/:id": "role.delete",
"POST /api/v1/org/tokens": "token.create",
"DELETE /api/v1/org/tokens/:id": "token.delete",
"PUT /api/v1/org/policy": "org.policy_update",
"POST /api/v1/org/monitors": "monitor.create",
"PUT /api/v1/org/monitors/:id": "monitor.update",
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
"POST /api/v1/org/maintenance": "maintenance.create",
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
"POST /api/v1/org/groups": "group.create",
"PUT /api/v1/org/groups/:id": "group.update",
"DELETE /api/v1/org/groups/:id": "group.delete",
"POST /api/v1/org/regions": "region.create",
"DELETE /api/v1/org/regions/:id": "region.delete",
"POST /api/v1/org/agents": "agent.create",
"DELETE /api/v1/org/agents/:id": "agent.delete",
"POST /api/v1/org/statuspages": "statuspage.create",
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
"POST /api/v1/org/channels": "channel.create",
"PUT /api/v1/org/channels/:id": "channel.update",
"DELETE /api/v1/org/channels/:id": "channel.delete",
"POST /api/v1/org/channels/:id/test": "channel.test",
"POST /api/v1/org/sso": "sso.create",
"PUT /api/v1/org/sso/:id": "sso.update",
"DELETE /api/v1/org/sso/:id": "sso.delete",
"DELETE /api/v1/org/members/:user": "member.remove",
"POST /api/v1/org/members/:user/roles": "member.role_assign",
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
"POST /api/v1/org/invitations": "invitation.create",
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
"POST /api/v1/org/roles": "role.create",
"PUT /api/v1/org/roles/:id": "role.update",
"DELETE /api/v1/org/roles/:id": "role.delete",
"POST /api/v1/org/tokens": "token.create",
"DELETE /api/v1/org/tokens/:id": "token.delete",
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
"PUT /api/v1/org/legal/:kind": "org.legal_update",
"POST /api/v1/admin/regions": "platform.region_create",
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
"POST /api/v1/admin/agents": "platform.agent_create",
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
"PUT /api/v1/org/legal/:kind": "org.legal_update",
"PUT /api/v1/admin/check-types": "platform.check_types_update",
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
"PUT /api/v1/admin/limits": "platform.limits_update",
"PUT /api/v1/admin/orgs/:id/limits": "platform.org_limits_update",
"PUT /api/v1/admin/users/:id/limits": "platform.user_limits_update",
"PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension",
"DELETE /api/v1/admin/status-pages/:id": "platform.status_page_delete",
"PUT /api/v1/admin/orgs/:id/suspension": "platform.org_suspension",
"DELETE /api/v1/admin/orgs/:id": "platform.org_delete",
"PUT /api/v1/admin/users/:id/suspension": "platform.user_suspension",
"DELETE /api/v1/admin/users/:id": "platform.user_delete",
"PUT /api/v1/org/check-types": "org.check_types_update",
"PATCH /api/v1/org/agents/:id": "agent.update",
"POST /api/v1/admin/regions": "platform.region_create",
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
"POST /api/v1/admin/agents": "platform.agent_create",
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
}
// Failed attempts of these actions are recorded too.
@@ -153,7 +177,7 @@ func (s *Server) audit() gin.HandlerFunc {
action := auditActions[c.Request.Method+" "+c.FullPath()]
status := c.Writer.Status()
if action == "" || c.GetBool(ctxAuditSkip) || (status >= 400 && !(auditFailures[action] && status < 500)) {
if action == "" || c.GetBool(ctxAuditSkip) || (status >= 400 && (!auditFailures[action] || status >= 500)) {
return
}
if status >= 400 {
@@ -260,23 +284,17 @@ func (s *Server) writeAudit(c *gin.Context, e store.InsertAuditEventParams, deta
}
}
const auditPageSize = 100
// auditQuery reads one page of entries; before pages back in time.
func (s *Server) auditQuery(ctx context.Context, scope tenant.Scope, p store.ListAuditEventsParams, before string) ([]store.ListAuditEventsRow, error) {
if t, err := time.Parse(time.RFC3339Nano, before); err == nil {
p.Before = &t
}
if p.MaxRows == 0 {
p.MaxRows = auditPageSize
}
// auditQuery reads a page of entries, newest first.
func (s *Server) auditQuery(ctx context.Context, scope tenant.Scope, p store.ListAuditEventsParams, pg pageReq) ([]store.ListAuditEventsRow, pageInfo, error) {
p.AfterT, p.AfterID, p.BeforeT, p.BeforeID, p.MaxRows = pg.afterT(), pg.afterID(), pg.beforeT(), pg.beforeID(), pg.fetch()
var rows []store.ListAuditEventsRow
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
var err error
rows, err = q.ListAuditEvents(ctx, p)
return err
})
return rows, err
rows, info := paginate(pg, rows, func(r store.ListAuditEventsRow) cursor { return cursor{T: r.Time, ID: r.ID} })
return rows, info, err
}
type auditEventView struct {
@@ -294,7 +312,7 @@ type auditEventView struct {
RequestID string `json:"request_id,omitempty"`
}
func auditJSON(c *gin.Context, rows []store.ListAuditEventsRow, err error) {
func auditJSON(c *gin.Context, rows []store.ListAuditEventsRow, info pageInfo, err error) {
if err != nil {
internalError(c, err)
return
@@ -307,28 +325,30 @@ func auditJSON(c *gin.Context, rows []store.ListAuditEventsRow, err error) {
IP: r.Ip, UserAgent: r.UserAgent, RequestID: r.RequestID,
}
}
resp := gin.H{"events": out}
if len(rows) == auditPageSize {
resp["next_before"] = rows[len(rows)-1].Time.Format(time.RFC3339Nano)
}
c.JSON(http.StatusOK, resp)
c.JSON(http.StatusOK, gin.H{"events": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func (s *Server) listOrgAudit(c *gin.Context) {
p := current(c)
rows, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, c.Query("before"))
auditJSON(c, rows, err)
if pg, ok := parsePage(c, apiPageSize); ok {
p := current(c)
rows, info, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, pg)
auditJSON(c, rows, info, err)
}
}
func (s *Server) listMyAudit(c *gin.Context) {
sess := auth.Current(c)
rows, err := s.auditQuery(c.Request.Context(), tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, c.Query("before"))
auditJSON(c, rows, err)
if pg, ok := parsePage(c, apiPageSize); ok {
sess := auth.Current(c)
rows, info, err := s.auditQuery(c.Request.Context(), tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, pg)
auditJSON(c, rows, info, err)
}
}
func (s *Server) listPlatformAudit(c *gin.Context) {
rows, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, c.Query("before"))
auditJSON(c, rows, err)
if pg, ok := parsePage(c, apiPageSize); ok {
rows, info, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, pg)
auditJSON(c, rows, info, err)
}
}
// auditEntries prepares rows for the console. Unknown actions, say from a
@@ -369,11 +389,15 @@ func auditEntries(c *gin.Context, rows []store.ListAuditEventsRow) []web.AuditEn
}
func (s *Server) auditView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
rows, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, c.Query("before"))
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
rows, info, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, pg)
if err != nil {
return nil, err
}
return web.AuditPage(page, me, "audit.title", "audit.intro", auditEntries(c, rows), nextAuditPage(c, rows)), nil
return web.AuditPage(page, me, "audit.title", "audit.intro", auditEntries(c, rows), pager(c, info)), nil
}
func (s *Server) adminAuditPage(c *gin.Context) {
@@ -381,17 +405,14 @@ func (s *Server) adminAuditPage(c *gin.Context) {
if !ok {
return
}
rows, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, c.Query("before"))
pg, ok := parsePage(c, consolePageSize)
if !ok {
return
}
rows, info, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, pg)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.AuditPage(s.pageFor(c, "audit.platform_title"), me, "audit.platform_title", "audit.platform_intro", auditEntries(c, rows), nextAuditPage(c, rows)))
}
func nextAuditPage(c *gin.Context, rows []store.ListAuditEventsRow) string {
if len(rows) < auditPageSize {
return ""
}
return c.Request.URL.Path + "?before=" + url.QueryEscape(rows[len(rows)-1].Time.Format(time.RFC3339Nano))
web.Render(c, http.StatusOK, web.AuditPage(s.pageFor(c, "audit.platform_title"), me, "audit.platform_title", "audit.platform_intro", auditEntries(c, rows), pager(c, info)))
}
+61 -11
View File
@@ -30,8 +30,11 @@ type signupRequest struct {
Email string `json:"email" binding:"required,email,max=320"`
Password string `json:"password" binding:"required,max=1024"`
DisplayName string `json:"display_name" binding:"max=200"`
OrgName string `json:"org_name" binding:"required,max=200"`
OrgSlug string `json:"org_slug" binding:"required,max=63"`
// OrgName and OrgSlug create a first organization at once, when no
// email confirmation is needed; otherwise the account creates one
// after confirming.
OrgName string `json:"org_name" binding:"max=200"`
OrgSlug string `json:"org_slug" binding:"max=63"`
}
func (s *Server) signup(c *gin.Context) {
@@ -50,6 +53,15 @@ func (s *Server) signup(c *gin.Context) {
fail(c, http.StatusForbidden, "signup_closed")
return
}
if left, err := s.signupsLeft(c); err != nil {
internalError(c, err)
return
} else if !left {
fail(c, http.StatusTooManyRequests, "signup_limit")
return
}
verify := s.verificationRequired()
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
@@ -63,20 +75,27 @@ func (s *Server) signup(c *gin.Context) {
var user store.User
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
var err error
user, err = q.CreateUser(ctx, store.CreateUserParams{
params := store.CreateUserParams{
Email: normalizeEmail(req.Email),
DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash,
Locale: ptr(i18n.Lang(ctx)),
})
EmailKey: ptr(emailKey(req.Email)),
}
if !verify {
params.EmailVerifiedAt = ptr(time.Now())
}
user, err = q.CreateUser(ctx, params)
if err != nil {
return err
}
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
return err
}
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
return err
if withOrg {
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
return err
}
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
return err
}
}
// Whoever sets up a self-hosted installation operates it.
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
@@ -85,7 +104,7 @@ func (s *Server) signup(c *gin.Context) {
return nil
})
switch {
case isUniqueViolation(err, "users_email_key"):
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
fail(c, http.StatusConflict, "email_taken")
return
case isUniqueViolation(err, "orgs_slug_key"):
@@ -98,10 +117,27 @@ func (s *Server) signup(c *gin.Context) {
internalError(c, err)
return
}
s.countSignup(c)
if verify {
auditActor(c, user.ID)
if err := s.sendVerification(ctx, user); err != nil {
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
fail(c, http.StatusBadGateway, "verification_mail_failed")
return
}
c.JSON(http.StatusOK, gin.H{"status": "verification_sent", "redirect": "/signup/sent"})
return
}
if !withOrg {
orgID = uuid.Nil
}
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: orgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
}
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
if s.signupClosedWithoutMail() {
return false, nil
}
switch s.cfg.Signup {
case config.SignupOpen:
return true, nil
@@ -155,10 +191,20 @@ func (s *Server) login(c *gin.Context) {
internalError(c, err)
return
}
if !ok || user.DisabledAt != nil {
if !ok {
invalidCredentials(c)
return
}
// Only someone who knows the password learns of the suspension or a
// missing confirmation.
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
if user.EmailVerifiedAt == nil {
fail(c, http.StatusForbidden, "email_unverified")
return
}
if rehash {
s.rehashPassword(ctx, user.ID, req.Password)
}
@@ -243,6 +289,10 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Metho
internalError(c, err)
return
}
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
var org uuid.UUID
if len(orgs) > 0 {
org = orgs[0].ID
+50 -6
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
@@ -22,11 +23,14 @@ import (
type channelRequest struct {
Name string `json:"name" binding:"required,max=100"`
Type string `json:"type" binding:"required,oneof=webhook email"`
Type string `json:"type" binding:"required,max=32"`
URL string `json:"url" binding:"max=2000"`
To []string `json:"to" binding:"max=20,dive,max=320"`
Locale string `json:"locale" binding:"max=10"`
Enabled *bool `json:"enabled"`
// Settings configure the other channel types, as listed by
// notify.Providers; secret settings left empty keep their value.
Settings map[string]string `json:"settings" binding:"max=20"`
}
type channelView struct {
@@ -37,6 +41,10 @@ type channelView struct {
URL string `json:"url,omitempty"`
To []string `json:"to,omitempty"`
Locale string `json:"locale,omitempty"`
// Settings and SecretsSet describe other channel types; secret values
// are never returned.
Settings map[string]string `json:"settings,omitempty"`
SecretsSet []string `json:"secrets_set,omitempty"`
}
func viewChannel(ch store.NotificationChannel) channelView {
@@ -50,6 +58,8 @@ func viewChannel(ch store.NotificationChannel) channelView {
var c emailConfig
_ = json.Unmarshal(ch.Config, &c)
v.To, v.Locale = c.To, c.Locale
default:
v.Settings, v.SecretsSet, v.Locale = providerView(ch.Config)
}
return v
}
@@ -109,6 +119,10 @@ func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []b
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
return config, "", ""
}
if p, ok := notify.Lookup(req.Type); ok {
config, code = s.providerSettings(p, req, previous)
return config, "", code
}
return nil, "", "invalid_input"
}
@@ -277,15 +291,45 @@ type incidentView struct {
Cause map[string]string `json:"cause"`
}
func (s *Server) listIncidents(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
// incidentPage reads a page of incidents, newest first, of one monitor
// if monitor is set.
func (s *Server) incidentPage(ctx context.Context, p *principal, pg pageReq, monitor *uuid.UUID) ([]store.ListIncidentsRow, pageInfo, error) {
var rows []store.ListIncidentsRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidents(ctx)
rows, err = q.ListIncidents(ctx, store.ListIncidentsParams{
MonitorID: monitor, AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.ListIncidentsRow) cursor { return cursor{T: r.StartedAt, ID: r.ID} })
return rows, info, err
}
// monitorFilter reads the optional monitor query parameter.
func monitorFilter(c *gin.Context, name string) (*uuid.UUID, bool) {
raw := c.Query(name)
if raw == "" {
return nil, true
}
id, err := uuid.Parse(raw)
if err != nil {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return nil, false
}
return &id, true
}
func (s *Server) listIncidents(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
monitor, ok := monitorFilter(c, "monitor_id")
if !ok {
return
}
rows, info, err := s.incidentPage(c.Request.Context(), current(c), pg, monitor)
if err != nil {
internalError(c, err)
return
@@ -295,5 +339,5 @@ func (s *Server) listIncidents(c *gin.Context) {
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt}
_ = json.Unmarshal(r.Cause, &out[i].Cause)
}
c.JSON(http.StatusOK, gin.H{"incidents": out})
c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
+117
View File
@@ -0,0 +1,117 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// Whether checkers may check private addresses: platform checkers follow
// a platform setting, organizations' checkers their own flag.
const settingPlatformPrivate = "platform_checkers_private"
// platformPrivate reports whether platform checkers may reach private
// addresses. Unset, they may on self-hosted installations only: in the
// cloud they share the operator's network.
func (s *Server) platformPrivate(ctx context.Context) bool {
v, err := s.checkerNet.get(ctx, s.rdb, func(ctx context.Context) (bool, error) {
allow := !s.cloud()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingPlatformPrivate)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &allow)
})
return allow, err
})
if err != nil {
s.log.WarnContext(ctx, "loading checker network setting failed", "error", err)
return false
}
return v
}
func (s *Server) allowPrivate(ctx context.Context, a store.GetAgentByHashRow) bool {
if a.OrgID != nil {
return a.AllowPrivate
}
return s.platformPrivate(ctx)
}
type checkerNetwork struct {
// AllowPrivate lets platform checkers check private addresses.
AllowPrivate bool `json:"allow_private"`
}
func (s *Server) adminGetCheckerNetwork(c *gin.Context) {
c.JSON(http.StatusOK, checkerNetwork{AllowPrivate: s.platformPrivate(c.Request.Context())})
}
func (s *Server) adminSetCheckerNetwork(c *gin.Context) {
var req checkerNetwork
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(req.AllowPrivate)
auditDetail(c, "allow_private", req.AllowPrivate)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingPlatformPrivate, Value: raw})
})
if err != nil {
internalError(c, err)
return
}
if err := s.checkerNet.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing checker network change failed", "error", err)
}
c.Status(http.StatusNoContent)
}
type agentUpdate struct {
AllowPrivate bool `json:"allow_private"`
}
// updateOrgAgent changes whether one of the organization's checkers may
// check private addresses; it applies from the checker's next poll.
func (s *Server) updateOrgAgent(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req agentUpdate
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
auditDetail(c, "allow_private", req.AllowPrivate)
var n int64
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
n, err = q.SetAgentAllowPrivate(ctx, store.SetAgentAllowPrivateParams{ID: id, OrgID: &p.Org.ID, AllowPrivate: req.AllowPrivate})
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
+171
View File
@@ -0,0 +1,171 @@
package api_test
import (
"context"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// latestOf returns the newest result of a monitor: ok and the error.
func latestOf(b *browser, id string) (bool, string, bool) {
_, list := b.do("GET", "/api/v1/org/monitors", nil)
for _, m := range list["monitors"].([]any) {
m := m.(map[string]any)
if m["id"] != id {
continue
}
if l := m["latest"].([]any); len(l) > 0 {
r := l[0].(map[string]any)
msg, _ := r["error"].(string)
return r["ok"] == true, msg, true
}
}
return false, "", false
}
func TestCheckerNetwork(t *testing.T) {
// In the cloud edition, platform checkers stay off private networks
// unless an admin allows it.
cloud := newEnvWith(t, func(c *config.API) { c.Edition, c.SignupVerify = config.EditionCloud, "off" })
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `DELETE FROM platform_settings WHERE key = 'platform_checkers_private'`)
return err
})
}
reset()
t.Cleanup(reset)
// A private service: the test's own loopback.
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = l.Close() })
go func() {
for {
conn, err := l.Accept()
if err != nil {
return
}
_ = conn.Close()
}
}()
tok, platformRegion := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("net")+".test", uniq("net-"))
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), owner.userIDSelf())
}); err != nil {
t.Fatal(err)
}
monitor := func(region string) string {
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Internal", "type": "tcp", "target": l.Addr().String(), "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
return body["id"].(string)
}
waitResult := func(id string, ok bool, what string) {
t.Helper()
waitFor(t, 20*time.Second, what, func() bool {
got, msg, seen := latestOf(owner, id)
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
})
}
admin := cloud.browser(t)
admin.signup("a@"+uniq("net")+".test", uniq("neta-"))
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
if _, body := admin.do("GET", "/api/v1/admin/checker-network", nil); body["allow_private"] != false {
t.Errorf("cloud default = %v", body)
}
// Self-hosted, platform checkers may by default; an admin can forbid it.
pm := monitor(platformRegion)
waitResult(pm, true, "platform checker reaching a private address")
if st, body := owner.do("PUT", "/api/v1/admin/checker-network", map[string]any{"allow_private": false}); st != http.StatusNoContent {
t.Fatalf("forbid = %d %v", st, body)
}
waitResult(pm, false, "platform checker refusing the private address once forbidden")
owner.do("DELETE", "/api/v1/org/monitors/"+pm, nil)
// An organization's checker can be kept off private networks.
_, region := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region["id"], "allow_private": false})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, agent)
}
e.startChecker(t, agent["token"].(string))
om := monitor(region["id"].(string))
waitResult(om, false, "org checker kept off private addresses")
_, agents := owner.do("GET", "/api/v1/org/agents", nil)
if raw := mustJSON(agents); !strings.Contains(raw, `"allow_private":false`) {
t.Errorf("agents = %s", raw)
}
if st, body := owner.do("PATCH", "/api/v1/org/agents/"+agent["id"].(string), map[string]any{"allow_private": true}); st != http.StatusNoContent {
t.Fatalf("patch agent = %d %v", st, body)
}
waitResult(om, true, "org checker reaching the private address once allowed")
// Other organizations cannot change it.
other := e.browser(t)
other.signup("x@"+uniq("net")+".test", uniq("netx-"))
st, body := other.do("PATCH", "/api/v1/org/agents/"+agent["id"].(string), map[string]any{"allow_private": false})
expect(t, "foreign agent", st, body, http.StatusNotFound, "not_found")
}
func TestOrgCheckTypes(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("oct")+".test", uniq("oct-"))
other := e.browser(t)
other.signup("x@"+uniq("oct")+".test", uniq("octx-"))
_, tcp := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Port", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
if st, body := owner.do("PUT", "/api/v1/org/check-types", map[string]any{"enabled": []string{"http", "dns"}}); st != http.StatusNoContent {
t.Fatalf("set = %d %v", st, body)
}
if _, body := owner.do("GET", "/api/v1/org/check-types", nil); mustJSON(body["types"]) != `["http","dns"]` {
t.Errorf("offered = %v", body["types"])
}
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
expect(t, "switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+tcp["id"].(string), map[string]any{"name": "Port 2", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
expect(t, "existing monitor of a switched-off type", st, body, http.StatusOK, "")
if _, _, page := owner.page("/monitors/new"); strings.Contains(page, `value="tcp"`) || !strings.Contains(page, `value="dns"`) {
t.Error("the editor offers types the organization switched off")
}
if _, _, page := owner.page("/settings/org"); !strings.Contains(page, `value="icmp"`) {
t.Error("the settings page lacks the check types")
}
st, body = owner.do("PUT", "/api/v1/org/check-types", map[string]any{"enabled": []string{}})
expect(t, "switching off everything", st, body, http.StatusUnprocessableEntity, "all_check_types_disabled")
// Other organizations keep everything.
if _, body := other.do("GET", "/api/v1/org/check-types", nil); !strings.Contains(mustJSON(body), `"icmp"`) {
t.Errorf("other organization offered %v", body["types"])
}
}
+47 -20
View File
@@ -104,20 +104,23 @@ func (s *Server) runningOn(ctx context.Context, instance uuid.UUID, now time.Tim
// Platform checkers work for every organization: only the viewer's own
// monitors are named, the rest is counted.
type checkerActivity struct {
ID uuid.UUID `json:"id"`
Agent string `json:"agent"`
Region string `json:"region"`
Platform bool `json:"platform"`
Release string `json:"release"`
StartedAt time.Time `json:"started_at"`
LastSeenAt time.Time `json:"last_seen_at"`
Live bool `json:"live"`
Queued int64 `json:"queued"`
Running []runningView `json:"running"`
OtherOrgs int `json:"running_for_others"`
LastHour checkerHourStats `json:"last_hour"`
Recent []recentByCheck `json:"recent"`
Siblings []uuid.UUID `json:"other_instances"`
ID uuid.UUID `json:"id"`
Agent string `json:"agent"`
Region string `json:"region"`
Platform bool `json:"platform"`
Release string `json:"release"`
StartedAt time.Time `json:"started_at"`
LastSeenAt time.Time `json:"last_seen_at"`
Live bool `json:"live"`
Queued int64 `json:"queued"`
Running []runningView `json:"running"`
OtherOrgs int `json:"running_for_others"`
LastHour checkerHourStats `json:"last_hour"`
Recent []recentByCheck `json:"recent"`
// NextCursor and PrevCursor page through Recent, newest first.
NextCursor string `json:"next_cursor,omitempty"`
PrevCursor string `json:"prev_cursor,omitempty"`
Siblings []uuid.UUID `json:"other_instances"`
regionID string
monitorName map[uuid.UUID]string
}
@@ -148,7 +151,7 @@ var errNoChecker = errors.New("api: checker not found")
// loadCheckerActivity gathers the activity of a checker instance visible to
// p: platform instances and those of p's organization.
func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance uuid.UUID) (checkerActivity, error) {
func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance uuid.UUID, pg pageReq) (checkerActivity, error) {
now := time.Now()
a := checkerActivity{ID: instance, Running: []runningView{}, Recent: []recentByCheck{}, Siblings: []uuid.UUID{}, monitorName: map[uuid.UUID]string{}}
t, err := s.loadGroupTree(ctx, p.scope())
@@ -194,7 +197,15 @@ func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance
return err
}
a.LastHour = checkerHourStats{Checks: stats.Total, Failed: stats.Failed, AvgLatencyMS: stats.AvgLatencyMs}
recent, err := q.ResultsByChecker(ctx, store.ResultsByCheckerParams{OrgID: p.Org.ID, CheckerID: instance})
recent, err := q.ResultsByChecker(ctx, store.ResultsByCheckerParams{
OrgID: p.Org.ID, CheckerID: instance, AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
})
// Pages are cut before filtering, so cursors follow every result
// and a page may show fewer than it read.
recent, info := paginate(pg, recent, func(r store.ResultsByCheckerRow) cursor {
return cursor{T: r.Time, S: r.MonitorID.String() + "|" + r.Region}
})
a.NextCursor, a.PrevCursor = info.Next, info.Prev
for _, r := range recent {
if readable[r.MonitorID] {
a.Recent = append(a.Recent, recentByCheck{
@@ -237,7 +248,11 @@ func (s *Server) getChecker(c *gin.Context) {
fail(c, http.StatusNotFound, "not_found")
return
}
a, err := s.loadCheckerActivity(c.Request.Context(), current(c), id)
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
a, err := s.loadCheckerActivity(c.Request.Context(), current(c), id, pg)
if errors.Is(err, errNoChecker) {
fail(c, http.StatusNotFound, "not_found")
return
@@ -254,7 +269,11 @@ func (s *Server) checkerPage(c *gin.Context, p *principal, page web.Page, me web
if err != nil {
return notFoundPage(c)
}
a, err := s.loadCheckerActivity(c.Request.Context(), p, id)
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
a, err := s.loadCheckerActivity(c.Request.Context(), p, id, pg)
if errors.Is(err, errNoChecker) {
return notFoundPage(c)
}
@@ -274,9 +293,15 @@ func (s *Server) checkerPage(c *gin.Context, p *principal, page web.Page, me web
MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor, For: now.Sub(r.Since).Round(time.Second).String(),
})
}
// Live while showing the latest results; paged back, with dates.
timeLayout := "15:04:05"
if pg.at() != nil {
timeLayout = "01-02 15:04:05"
}
v.Pager = pager(c, pageInfo{Next: a.NextCursor, Prev: a.PrevCursor})
for _, r := range a.Recent {
row := web.CheckerResult{
Time: r.Time.Local().Format("15:04:05"), MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor,
Time: r.Time.Local().Format(timeLayout), MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor,
OK: r.OK, Latency: "–", Detail: deref(r.Error),
}
if r.LatencyMS != nil {
@@ -290,7 +315,9 @@ func (s *Server) checkerPage(c *gin.Context, p *principal, page web.Page, me web
for _, sb := range a.Siblings {
v.Siblings = append(v.Siblings, web.CheckerLink{URL: "/checkers/" + sb.String(), Label: shortID(sb)})
}
page.RefreshSeconds = 5
if pg.at() == nil {
page.RefreshSeconds = 5
}
return web.CheckerPage(page, me, v), nil
}
+179
View File
@@ -0,0 +1,179 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// Platform admins can switch off check types the installation cannot
// offer, such as Docker on shared cloud checkers. Switched-off types are
// not offered for new monitors; existing ones keep running and stay
// editable.
const settingDisabledChecks = "disabled_check_types"
func (s *Server) disabledChecks(ctx context.Context) map[string]bool {
set, err := s.checkTypes.get(ctx, s.rdb, func(ctx context.Context) (map[string]bool, error) {
out := map[string]bool{}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingDisabledChecks)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
var list []string
_ = json.Unmarshal(raw, &list)
for _, t := range list {
out[t] = true
}
return nil
})
return out, err
})
if err != nil {
s.log.WarnContext(ctx, "loading disabled check types failed", "error", err)
}
return set
}
// offered reports whether org may create monitors of type t: neither the
// platform nor the organization switched it off.
func (s *Server) offered(ctx context.Context, org store.Org, t string) bool {
return slices.Contains(s.enabledCheckTypes(ctx, org, ""), t)
}
// enabledCheckTypes lists the types offered to org for new monitors, plus
// keep when a monitor of a switched-off type is being edited. The
// organization's choice is ignored if it would leave nothing, which can
// happen when the platform later switches off what it kept.
func (s *Server) enabledCheckTypes(ctx context.Context, org store.Org, keep string) []string {
off := s.disabledChecks(ctx)
var platform, out []string
for _, t := range check.Types {
if off[string(t)] && string(t) != keep {
continue
}
platform = append(platform, string(t))
if !slices.Contains(org.DisabledCheckTypes, string(t)) || string(t) == keep {
out = append(out, string(t))
}
}
if len(out) == 0 {
return platform
}
return out
}
type checkTypeView struct {
Type string `json:"type"`
Enabled bool `json:"enabled"`
}
func (s *Server) adminListCheckTypes(c *gin.Context) {
off := s.disabledChecks(c.Request.Context())
out := make([]checkTypeView, len(check.Types))
for i, t := range check.Types {
out[i] = checkTypeView{Type: string(t), Enabled: !off[string(t)]}
}
c.JSON(http.StatusOK, gin.H{"types": out})
}
type checkTypesRequest struct {
// Enabled lists the types to offer; all others are switched off.
Enabled []string `json:"enabled" binding:"max=100"`
}
func (s *Server) adminSetCheckTypes(c *gin.Context) {
var req checkTypesRequest
if !bind(c, &req) {
return
}
var disabled []string
for _, t := range check.Types {
if !slices.Contains(req.Enabled, string(t)) {
disabled = append(disabled, string(t))
}
}
for _, t := range req.Enabled {
if !slices.Contains(check.Types, check.Type(t)) {
fail(c, http.StatusUnprocessableEntity, "invalid_type")
return
}
}
if len(disabled) == len(check.Types) {
fail(c, http.StatusUnprocessableEntity, "all_check_types_disabled")
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(append([]string{}, disabled...))
auditDetail(c, "disabled", disabled)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingDisabledChecks, Value: raw})
})
if err != nil {
internalError(c, err)
return
}
if err := s.checkTypes.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing check type change failed", "error", err)
}
c.Status(http.StatusNoContent)
}
// orgCheckTypes tells API clients which monitor types they can create.
func (s *Server) orgCheckTypes(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"types": s.enabledCheckTypes(c.Request.Context(), current(c).Org, "")})
}
// orgSetCheckTypes chooses which of the platform's types the organization
// offers its members.
func (s *Server) orgSetCheckTypes(c *gin.Context) {
var req checkTypesRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
off := s.disabledChecks(ctx)
disabled := []string{}
enabled := 0
for _, t := range check.Types {
switch {
case slices.Contains(req.Enabled, string(t)):
enabled++
case !off[string(t)]:
disabled = append(disabled, string(t))
}
}
for _, t := range req.Enabled {
if !slices.Contains(check.Types, check.Type(t)) {
fail(c, http.StatusUnprocessableEntity, "invalid_type")
return
}
}
if enabled == 0 {
fail(c, http.StatusUnprocessableEntity, "all_check_types_disabled")
return
}
auditDetail(c, "disabled", disabled)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
return q.SetOrgDisabledCheckTypes(ctx, store.SetOrgDisabledCheckTypesParams{ID: p.Org.ID, DisabledCheckTypes: disabled})
})
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
+77
View File
@@ -0,0 +1,77 @@
package api_test
import (
"context"
"net/http"
"slices"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestCheckTypesCanBeSwitchedOff(t *testing.T) {
e := newEnv(t)
// A second replica, started first: starting it clears the Redis test
// database, sessions included.
other := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
admin := e.browser(t)
admin.signup("a@"+uniq("ct")+".test", uniq("ct-"))
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
all := make([]string, len(check.Types))
for i, ty := range check.Types {
all[i] = string(ty)
}
// The setting is platform-wide: reset it directly, whatever happens
// to sessions during the test.
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `DELETE FROM platform_settings WHERE key = 'disabled_check_types'`)
return err
})
}
reset()
t.Cleanup(reset)
// A heartbeat created while allowed stays editable afterwards.
_, hb := admin.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600})
_, tcp := admin.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Port", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
enabled := slices.DeleteFunc(slices.Clone(all), func(s string) bool { return s == "icmp" || s == "heartbeat" })
if st, body := admin.do("PUT", "/api/v1/admin/check-types", map[string]any{"enabled": enabled}); st != http.StatusNoContent {
t.Fatalf("switch off = %d %v", st, body)
}
if st, body := admin.do("PUT", "/api/v1/admin/check-types", map[string]any{"enabled": []string{}}); st != http.StatusUnprocessableEntity {
t.Errorf("switching off everything = %d %v", st, body)
}
// Another replica sees the change at once.
member := other.browser(t)
member.signup("m@"+uniq("ct")+".test", uniq("ctm-"))
_, types := member.do("GET", "/api/v1/org/check-types", nil)
if raw := mustJSON(types); strings.Contains(raw, `"icmp"`) || strings.Contains(raw, `"heartbeat"`) || !strings.Contains(raw, `"http"`) {
t.Errorf("offered types = %s", raw)
}
st, body := member.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
expect(t, "create switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
if _, _, page := member.page("/monitors/new"); strings.Contains(page, `value="icmp"`) || !strings.Contains(page, `value="http"`) {
t.Error("the editor still offers a switched-off type")
}
st, body = admin.do("PUT", "/api/v1/org/monitors/"+hb["id"].(string), map[string]any{"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200})
expect(t, "edit existing heartbeat", st, body, http.StatusOK, "")
st, body = admin.do("PUT", "/api/v1/org/monitors/"+tcp["id"].(string), map[string]any{"name": "Port", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
expect(t, "switch to a switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
if _, _, page := admin.page("/monitors/" + hb["id"].(string) + "/edit"); !strings.Contains(page, `value="heartbeat" selected`) {
t.Error("editing a monitor of a switched-off type does not keep its type")
}
}
+452 -49
View File
@@ -1,11 +1,13 @@
package api
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
@@ -21,6 +23,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
@@ -38,7 +41,9 @@ func (s *Server) registerConsole(r gin.IRouter) {
r.GET("/groups", s.orgPage("groups.title", "", s.groupsView))
r.GET("/settings", s.settingsIndex)
r.GET("/incidents", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentsView))
r.GET("/monitors/:id/results", s.orgPage("monitors.results_title", "", s.resultsView))
r.GET("/maintenance", s.orgPage("maintenance.title", "", s.maintenancePage))
r.GET("/settings/alertmanager", s.orgPage("alertmanager.title", authz.MonitorsRead, s.alertmanagerPage))
r.GET("/settings/channels", s.orgPage("channels.title", authz.NotificationsRead, s.channelsView))
r.GET("/statuspages", s.orgPage("pages.title", "", s.statusPagesView))
r.GET("/statuspages/:id", s.orgPage("pages.title", "", s.statusPageEditor))
@@ -58,6 +63,11 @@ func (s *Server) dashboard(c *gin.Context) {
internalError(c, err)
return
}
if len(me.Orgs) == 0 {
// New accounts start by creating an organization.
c.Redirect(http.StatusSeeOther, "/orgs/new")
return
}
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
if p != nil && me.Policy == "" {
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
@@ -67,6 +77,9 @@ func (s *Server) dashboard(c *gin.Context) {
}
v.Root = buildGroupNodes(data.tree, data.rows)
v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0
if !s.dashboardPage(c, &v, data) {
return
}
v.CanWrite = writableAnywhere(p, data.tree)
v.Range = data.rng.Key
var earliest time.Time
@@ -83,6 +96,105 @@ func (s *Server) dashboard(c *gin.Context) {
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
}
// groupMonitorsShown is how many of its own monitors a group shows on the
// dashboard before linking to all of them.
const groupMonitorsShown = 50
// ungrouped names the pseudo-group of monitors outside any group.
const ungrouped = "none"
func monitorKey(m web.MonitorRow) cursor {
id, _ := uuid.Parse(m.ID)
return cursor{S: strings.ToLower(m.Name), ID: id}
}
func sortMonitors(ms []web.MonitorRow) {
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
ka, kb := monitorKey(a), monitorKey(b)
if c := strings.Compare(ka.S, kb.S); c != 0 {
return c
}
return strings.Compare(a.ID, b.ID)
})
}
// dashboardPage narrows the dashboard to a search or one group, pages it
// and caps every group's own monitors. It reports false after answering
// with an error.
func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monitorData) bool {
pg, ok := parsePage(c, consolePageSize)
if !ok {
return false
}
link := func(group string) string {
q := url.Values{"group": {group}}
if r := c.Query("range"); r != "" {
q.Set("range", r)
}
return "/?" + q.Encode()
}
var capNode func(n *web.GroupNode)
capNode = func(n *web.GroupNode) {
sortMonitors(n.Monitors)
if len(n.Monitors) > groupMonitorsShown {
n.More = len(n.Monitors) - groupMonitorsShown
n.Monitors = n.Monitors[:groupMonitorsShown]
n.MoreURL = link(cmp.Or(n.ID, ungrouped))
}
for i := range n.Children {
capNode(&n.Children[i])
}
}
var info pageInfo
switch group := c.Query("group"); {
case strings.TrimSpace(c.Query("q")) != "":
v.Search = strings.TrimSpace(c.Query("q"))
needle := strings.ToLower(v.Search)
var hits []web.MonitorRow
for _, m := range data.rows {
if strings.Contains(strings.ToLower(m.Name), needle) || strings.Contains(strings.ToLower(m.Target), needle) {
hits = append(hits, m)
}
}
sortMonitors(hits)
v.Results, info = pageSlice(hits, pg, monitorKey)
case group != "":
var focus web.GroupNode
found := false
if group == ungrouped {
focus, found = web.GroupNode{Monitors: v.Root.Monitors}, true
v.Focus = i18n.T(c.Request.Context(), "monitors.ungrouped")
} else {
var find func(ns []web.GroupNode)
find = func(ns []web.GroupNode) {
for _, n := range ns {
if n.ID == group {
focus, found = n, true
return
}
find(n.Children)
}
}
find(v.Root.Children)
v.Focus = focus.Name
}
if !found {
c.Redirect(http.StatusSeeOther, "/")
return false
}
sortMonitors(focus.Monitors)
focus.Monitors, info = pageSlice(focus.Monitors, pg, monitorKey)
for i := range focus.Children {
capNode(&focus.Children[i])
}
v.Root = focus
default:
capNode(&v.Root)
}
v.Pager = pager(c, info)
return true
}
type monitorData struct {
// heartbeatLabel names the pseudo-region of heartbeat results.
heartbeatLabel string
@@ -269,7 +381,7 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
keys := idStrings(regionsOf[m.ID])
if check.Passive(check.Type(m.Type)) {
// The target of a heartbeat is its secret ping token.
row.Target, keys = "", []string{heartbeatRegion}
row.Target, keys = "", []string{passiveRegion(check.Type(m.Type))}
}
if m.GroupID != nil {
row.GroupID = m.GroupID.String()
@@ -364,8 +476,8 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
}
var (
daily []store.DailyBucketsRow
recent []store.RecentResultsRow
incidents []store.Incident
recent []store.ListResultsRow
incidents []store.ListIncidentsRow
)
now := time.Now()
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
@@ -373,10 +485,10 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
if daily, err = q.DailyBuckets(ctx, store.DailyBucketsParams{OrgID: p.Org.ID, MonitorID: id, Bucket: now.AddDate(0, 0, -90)}); err != nil {
return err
}
if recent, err = q.RecentResults(ctx, store.RecentResultsParams{OrgID: p.Org.ID, MonitorID: id, Time: now.Add(-24 * time.Hour)}); err != nil {
if recent, err = q.ListResults(ctx, store.ListResultsParams{OrgID: p.Org.ID, MonitorID: id, MaxRows: monitorResultsShown + 1}); err != nil {
return err
}
incidents, err = q.MonitorIncidents(ctx, id)
incidents, err = q.ListIncidents(ctx, store.ListIncidentsParams{MonitorID: &id, MaxRows: monitorIncidentsShown + 1})
return err
})
if err != nil {
@@ -401,50 +513,38 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
if u := web.Uptime(buckets); u >= 0 {
v.Uptime90 = web.Percent(u)
}
var evidenceOf map[string]string
if v.CanWrite {
if v.Evidence, evidenceOf, err = s.evidenceRows(ctx, p, d, m); err != nil {
if v.Evidence, err = s.evidenceRows(ctx, p, d, m); err != nil {
return nil, err
}
}
shown := recent[:min(len(recent), 50)]
var checkerIDs []uuid.UUID
for _, r := range shown {
if r.CheckerID != uuid.Nil && !slices.Contains(checkerIDs, r.CheckerID) {
checkerIDs = append(checkerIDs, r.CheckerID)
}
more := len(recent) > monitorResultsShown
if more {
recent = recent[:monitorResultsShown]
v.MoreResults = true
}
checkers, err := s.checkerLinks(ctx, p, checkerIDs)
if err != nil {
if v.Recent, err = s.resultRows(ctx, p, d, m, recent, v.CanWrite); err != nil {
return nil, err
}
for _, r := range shown {
row := web.ResultRow{Time: r.Time.Format("01-02 15:04:05"), Region: d.regionNameString(r.Region), OK: r.Ok, Latency: "–", Detail: deref(r.Error)}
row.Checker = checkers[r.CheckerID]
if row.Checker.Label == "" && r.CheckerID != uuid.Nil {
// Instances seen before names were recorded, or of a deleted
// agent.
row.Checker.Label = shortID(r.CheckerID)
for n, i := range incidents {
if n == monitorIncidentsShown {
v.MoreIncidents = true
break
}
row.EvidenceURL = evidenceOf[evidenceKey(r.Region, r.Time)]
if r.LatencyMs != nil {
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMs)
}
if r.StatusCode != nil && row.Detail == "" {
row.Detail = fmt.Sprint(*r.StatusCode)
}
v.Recent = append(v.Recent, row)
}
for _, i := range incidents {
v.Incidents = append(v.Incidents, d.incidentRow(i, m.Name))
v.Incidents = append(v.Incidents, d.incidentRow(store.Incident{
ID: i.ID, OrgID: i.OrgID, MonitorID: i.MonitorID, StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: i.Cause,
}, m.Name))
}
page.TitleID = "console.monitors.title"
return web.MonitorDetail(page, me, v), nil
}
func (d monitorData) regionNameString(id string) string {
if id == heartbeatRegion {
switch id {
case heartbeatRegion:
return d.heartbeatLabel
case alertmanagerRegion:
return "Alertmanager"
}
if u, err := uuid.Parse(id); err == nil {
return d.regionName(u)
@@ -505,6 +605,18 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
JSONExpect: "2xx", JSONVerify: true, Assertions: assertionRows(nil),
PromOp: ">=", PromThreshold: "1", PromMode: "all", PromVerify: true,
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
Matchers: matcherRows(nil), StaleHours: check.DefaultStaleHours,
}
// "Create monitor" on a firing alert opens this page prefilled.
if c.Param("id") == "" && c.Query("type") == string(check.Alertmanager) {
f.Type, f.Name, f.IntervalSeconds, f.Confirmations = string(check.Alertmanager), c.Query("name"), 60, 1
var ms []check.Matcher
for _, kv := range c.QueryArray("m") {
if l, v, ok := strings.Cut(kv, "="); ok {
ms = append(ms, check.Matcher{Label: l, Op: "=", Value: v})
}
}
f.Matchers = matcherRows(ms)
}
var (
regions []store.Region
@@ -516,6 +628,24 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
if regions, err = q.ListVisibleRegions(ctx); err != nil {
return err
}
groups, err := q.ListAlertGroups(ctx)
if err != nil {
return err
}
var selected []uuid.UUID
if idParam != "" {
id, err := uuid.Parse(idParam)
if err != nil {
return pgx.ErrNoRows
}
selected, err = q.MonitorAlertGroups(ctx, id)
if err != nil {
return err
}
}
for _, g := range groups {
f.AlertGroups = append(f.AlertGroups, web.AlertGroupOption{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault, Checked: slices.Contains(selected, g.ID) || (idParam == "" && g.IsDefault)})
}
if idParam == "" {
return nil
}
@@ -537,6 +667,10 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
if err != nil {
return nil, err
}
f.Types = s.enabledCheckTypes(ctx, p.Org, f.Type)
if !slices.Contains(f.Types, f.Type) {
f.Type = f.Types[0]
}
for i, r := range regions {
live, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
@@ -572,6 +706,7 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
// Defaults for the other types, in case the type is switched.
f.JSONExpect, f.JSONVerify, f.Assertions, f.GraceSeconds = "2xx", true, assertionRows(nil), check.DefaultHeartbeatGrace
f.PromOp, f.PromThreshold, f.PromMode, f.PromVerify = ">=", "1", "all", true
f.Matchers, f.StaleHours = matcherRows(nil), check.DefaultStaleHours
switch check.Type(m.Type) {
case check.HTTP:
var c check.HTTPConfig
@@ -598,6 +733,49 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
_ = json.Unmarshal(m.Config, &c)
f.PromQuery, f.PromOp, f.PromThreshold, f.PromMode = c.Query, c.Op, strconv.FormatFloat(c.Threshold, 'g', -1, 64), c.Mode
f.PromEmptyOK, f.PromVerify, f.Headers = c.EmptyOK, c.VerifyTLS, headerLines(c.Headers)
case check.Postgres, check.MySQL, check.MSSQL, check.MongoDB, check.Redis:
var c check.DBConfig
cfg, secrets := publicMonitorConfig(m.Config)
_ = json.Unmarshal(cfg, &c)
f.DB = web.DBForm{User: c.User, Database: c.Database, TLS: c.TLS, Query: c.Query, Expect: c.Expect, PasswordSet: slices.Contains(secrets, "password")}
case check.MQTT, check.Kafka, check.RabbitMQ:
var c check.BrokerConfig
cfg, secrets := publicMonitorConfig(m.Config)
_ = json.Unmarshal(cfg, &c)
f.Broker = web.BrokerForm{
User: c.User, TLS: c.TLS, Topic: c.Topic, Expect: c.Expect, Message: c.Message, SASL: c.SASL,
Vhost: c.Vhost, Queue: c.Queue, PasswordSet: slices.Contains(secrets, "password"),
}
case check.GRPC, check.SMTP, check.RADIUS, check.SNMP:
cfg, secrets := publicMonitorConfig(m.Config)
var (
g check.GRPCConfig
sm check.SMTPConfig
r check.RADIUSConfig
sn check.SNMPConfig
)
_ = json.Unmarshal(cfg, &g)
_ = json.Unmarshal(cfg, &sm)
_ = json.Unmarshal(cfg, &r)
_ = json.Unmarshal(cfg, &sn)
f.Proto = web.ProtocolForm{
Service: g.Service, TLS: g.TLS, ImplicitTLS: sm.ImplicitTLS,
User: r.User, NASIdentifier: r.NASIdentifier,
SecretSet: slices.Contains(secrets, "secret"), PasswordSet: slices.Contains(secrets, "password"), CommunitySet: slices.Contains(secrets, "community"),
Version: sn.Version, OID: sn.OID, Condition: sn.Condition, Value: sn.Value,
}
case check.Steam, check.Minecraft:
var c check.GameConfig
_ = json.Unmarshal(m.Config, &c)
f.Game = web.GameForm{Edition: c.Edition, MinFreeSlots: c.MinFreeSlots}
case check.Docker:
var c check.DockerConfig
_ = json.Unmarshal(m.Config, &c)
f.DockerHost = c.Host
case check.Alertmanager:
var c check.AlertmanagerConfig
_ = json.Unmarshal(m.Config, &c)
f.Matchers, f.StaleHours, f.Target = matcherRows(c.Matchers), c.StaleHours, ""
case check.Heartbeat:
var c check.HeartbeatConfig
_ = json.Unmarshal(m.Config, &c)
@@ -606,14 +784,117 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
}
}
func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.ListIncidentsRow
// monitorIncidentsShown is how many incidents a monitor's page lists
// before linking to all of them.
const monitorIncidentsShown = 10
// monitorResultsShown is how many results a monitor's page lists before
// linking to all of them.
const monitorResultsShown = 50
// resultPage reads a page of m's results, newest first.
func (s *Server) resultPage(ctx context.Context, p *principal, m store.Monitor, pg pageReq) ([]store.ListResultsRow, pageInfo, error) {
var rows []store.ListResultsRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidents(ctx)
rows, err = q.ListResults(ctx, store.ListResultsParams{
OrgID: p.Org.ID, MonitorID: m.ID, AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.ListResultsRow) cursor { return cursor{T: r.Time, S: r.Position} })
return rows, info, err
}
func (s *Server) resultsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
return notFoundPage(c)
}
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
ctx := c.Request.Context()
d, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
if err != nil {
return nil, err
}
m, ok := d.byID[id]
if !ok {
return notFoundPage(c)
}
rows, info, err := s.resultPage(ctx, p, m, pg)
if err != nil {
return nil, err
}
v := web.ResultsView{MonitorID: m.ID.String(), Monitor: m.Name, Pager: pager(c, info)}
if v.Rows, err = s.resultRows(ctx, p, d, m, rows, canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID)); err != nil {
return nil, err
}
return web.ResultsPage(page, me, v), nil
}
// resultRows renders check results of m, linking evidence if withEvidence.
func (s *Server) resultRows(ctx context.Context, p *principal, d monitorData, m store.Monitor, rows []store.ListResultsRow, withEvidence bool) ([]web.ResultRow, error) {
if len(rows) == 0 {
return nil, nil
}
var checkerIDs []uuid.UUID
for _, r := range rows {
if r.CheckerID != uuid.Nil && !slices.Contains(checkerIDs, r.CheckerID) {
checkerIDs = append(checkerIDs, r.CheckerID)
}
}
checkers, err := s.checkerLinks(ctx, p, checkerIDs)
if err != nil {
return nil, err
}
evidence := map[string]string{}
if withEvidence {
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
found, err := q.EvidenceBetween(ctx, store.EvidenceBetweenParams{MonitorID: m.ID, Since: rows[len(rows)-1].Time, Until: rows[0].Time})
for _, e := range found {
evidence[evidenceKey(e.Region, e.Time)] = "/monitors/" + m.ID.String() + "/evidence/" + e.ID.String()
}
return err
})
if err != nil {
return nil, err
}
}
out := make([]web.ResultRow, 0, len(rows))
for _, r := range rows {
row := web.ResultRow{Time: r.Time.Format("01-02 15:04:05"), Region: d.regionNameString(r.Region), OK: r.Ok, Latency: "–", Detail: deref(r.Error)}
row.Checker = checkers[r.CheckerID]
if row.Checker.Label == "" && r.CheckerID != uuid.Nil {
// Instances seen before names were recorded, or of a deleted
// agent.
row.Checker.Label = shortID(r.CheckerID)
}
row.EvidenceURL = evidence[evidenceKey(r.Region, r.Time)]
if r.LatencyMs != nil {
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMs)
}
if r.StatusCode != nil && row.Detail == "" {
row.Detail = fmt.Sprint(*r.StatusCode)
}
out = append(out, row)
}
return out, nil
}
func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
monitor, ok := monitorFilter(c, "monitor")
if !ok {
return nil, errAborted
}
rows, info, err := s.incidentPage(ctx, p, pg, monitor)
if err != nil {
return nil, err
}
@@ -621,13 +902,18 @@ func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me w
if err != nil {
return nil, err
}
out := make([]web.IncidentRow, len(rows))
v := web.IncidentsView{Rows: make([]web.IncidentRow, len(rows)), Pager: pager(c, info)}
for i, r := range rows {
out[i] = d.incidentRow(store.Incident{
v.Rows[i] = d.incidentRow(store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause,
}, r.MonitorName)
}
return web.IncidentsPage(page, me, out), nil
if monitor != nil {
if m, ok := d.byID[*monitor]; ok {
v.Monitor, v.MonitorID = m.Name, monitor.String()
}
}
return web.IncidentsPage(page, me, v), nil
}
func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
@@ -642,14 +928,72 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
return nil, err
}
v := web.ChannelsView{EmailAvailable: s.smtp != nil, CanWrite: p.Grants.Can(authz.NotificationsWrite), Languages: s.catalog.Supported()}
ctx2 := c.Request.Context()
for _, pr := range notify.Providers {
opt := web.ProviderOption{Type: pr.Type, Group: pr.Group}
if help := i18n.T(ctx2, "channels.help_"+pr.Type); help != "channels.help_"+pr.Type {
opt.Help = help
}
for _, f := range pr.Fields {
opt.Fields = append(opt.Fields, web.ProviderField{
Name: f.Name, Label: i18n.T(ctx2, "channels.field_"+f.Name), Required: f.Required, Secret: f.Secret,
Kind: f.Kind, Options: f.Options, Default: f.Default,
})
}
v.Providers = append(v.Providers, opt)
}
// By group, then by name; the first is preselected.
groupOrder := []string{"chat", "push", "sms", "email", "incident", "other"}
slices.SortStableFunc(v.Providers, func(a, b web.ProviderOption) int {
if d := slices.Index(groupOrder, a.Group) - slices.Index(groupOrder, b.Group); d != 0 {
return d
}
return strings.Compare(strings.ToLower(i18n.T(ctx2, "channels.type_"+a.Type)), strings.ToLower(i18n.T(ctx2, "channels.type_"+b.Type)))
})
for _, r := range rows {
cv := viewChannel(r)
target := cv.URL
if cv.Type == "email" {
target = strings.Join(cv.To, ", ")
}
// Other services show their first setting that is no secret, such
// as the chat, topic or server.
if p, ok := notify.Lookup(cv.Type); ok {
for _, f := range p.Fields {
if v, ok := cv.Settings[f.Name]; ok && !f.Secret {
target = v
break
}
}
}
v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled})
}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
groups, err := q.ListAlertGroups(ctx)
if err != nil {
return err
}
now := time.Now()
for _, g := range groups {
qh := decodeQuietHours(g.QuietHours)
row := web.AlertGroupRow{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault, QuietNow: isQuietAt(qh, now)}
for _, ch := range rows {
row.Channels = append(row.Channels, web.AlertGroupOption{ID: ch.ID.String(), Name: ch.Name, Checked: slices.Contains(g.ChannelIds, ch.ID)})
}
for _, w := range qh {
days := map[int]bool{}
for _, d := range w.Weekdays {
days[d] = true
}
row.QuietHours = append(row.QuietHours, web.AlertGroupQuietRow{Start: w.Start, End: w.End, TimeZone: w.TimeZone, Weekdays: days})
}
v.AlertGroups = append(v.AlertGroups, row)
}
return nil
})
if err != nil {
return nil, err
}
return web.ChannelsPage(page, me, v), nil
}
@@ -678,7 +1022,7 @@ func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me
}
v.Pages = append(v.Pages, web.PageRow{
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
URL: s.pageURL(r), Domain: deref(r.CustomDomain),
URL: s.pageURL(r), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
})
}
return web.StatusPagesPage(page, me, v), nil
@@ -691,9 +1035,11 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
}
ctx := c.Request.Context()
var (
row store.StatusPage
listed []store.StatusPageMonitorsRow
monitors []store.Monitor
row store.StatusPage
listed []store.StatusPageMonitorsRow
pageGroups []store.StatusPageGroup
orgGroups []store.MonitorGroup
monitors []store.Monitor
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
@@ -703,6 +1049,12 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if listed, err = q.StatusPageMonitors(ctx, id); err != nil {
return err
}
if pageGroups, err = q.ListStatusPageGroups(ctx, id); err != nil {
return err
}
if orgGroups, err = q.ListGroups(ctx); err != nil {
return err
}
monitors, err = q.ListMonitors(ctx)
return err
})
@@ -715,21 +1067,60 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
v := viewStatusPage(row)
e := web.PageEditor{
ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
Published: row.Published, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
Published: row.Published, ShowDetails: row.ShowComponentDetails,
Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason,
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
HasOrgGroups: len(orgGroups) > 0,
}
if v.DomainRecord != nil {
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
}
newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) {
var parentID string
if g.ParentID != nil {
parentID = g.ParentID.String()
}
e.Groups = append(e.Groups, web.PageGroupRow{
ID: g.ID.String(), Name: g.Name, ParentID: parentID, Position: int(g.Position), Depth: depth,
Label: strings.Repeat("— ", depth) + g.Name,
})
})
orgTree := newGroupTree(orgGroups)
groupPath := func(gid *uuid.UUID) string {
if gid == nil {
return ""
}
var parts []string
for cur := gid; cur != nil && len(parts) < 10; {
g, ok := orgTree.byID[*cur]
if !ok {
break
}
parts = append(parts, g.Name)
cur = g.ParentID
}
slices.Reverse(parts)
return strings.Join(parts, " / ")
}
// Listed monitors keep their order; the rest follow alphabetically.
seen := map[uuid.UUID]bool{}
for _, l := range listed {
seen[l.MonitorID] = true
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: l.MonitorID.String(), Name: l.MonitorName, Included: true, Section: l.Section, Label: l.Label})
var groupID string
if l.GroupID != nil {
groupID = l.GroupID.String()
}
e.Monitors = append(e.Monitors, web.PageMonitorOption{
ID: l.MonitorID.String(), Name: l.MonitorName, MonitorGroupPath: groupPath(l.MonitorGroupID),
Included: true, GroupID: groupID, Label: l.Label,
})
}
for _, m := range monitors {
if !seen[m.ID] {
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: m.ID.String(), Name: m.Name})
e.Monitors = append(e.Monitors, web.PageMonitorOption{
ID: m.ID.String(), Name: m.Name, MonitorGroupPath: groupPath(m.GroupID),
})
}
}
return web.StatusPageEditor(page, me, e), nil
@@ -926,7 +1317,7 @@ func maintenanceItems(ws []store.MaintenanceWindow, now time.Time) []web.Mainten
// detailPingURL shows the ping URL of a heartbeat monitor to those who may
// change the monitor; anyone holding it can report the job healthy.
func (s *Server) detailPingURL(p *principal, d monitorData, m store.Monitor) string {
if !check.Passive(check.Type(m.Type)) || !canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID) {
if check.Type(m.Type) != check.Heartbeat || !canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID) {
return ""
}
return s.pingURL(m.Target)
@@ -954,3 +1345,15 @@ func headerLines(h map[string]string) string {
}
return b.String()
}
// matcherRows pads matchers to the rows the form offers.
func matcherRows(ms []check.Matcher) []web.MatcherRow {
rows := make([]web.MatcherRow, max(len(ms)+2, 4))
for i := range rows {
rows[i].Op = "="
}
for i, m := range ms {
rows[i] = web.MatcherRow{Label: m.Label, Op: m.Op, Value: m.Value}
}
return rows
}
+104
View File
@@ -0,0 +1,104 @@
package api_test
import (
"context"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
func TestDatabaseMonitorSecrets(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
pg, _ := url.Parse(os.Getenv("UPTIME_TEST_DATABASE_URL"))
owner := e.browser(t)
owner.signup("o@"+uniq("db")+".test", uniq("db-"))
monitor := map[string]any{
"name": "Main DB", "type": "postgres", "target": pg.Host, "interval_seconds": 10, "timeout_ms": 5000, "confirmations": 1,
"regions": []string{region},
"config": map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"},
}
st, body := owner.do("POST", "/api/v1/org/monitors", monitor)
if st != http.StatusCreated {
t.Fatalf("create = %d %v", st, body)
}
id := body["id"].(string)
if _, hasPassword := body["config"].(map[string]any)["password"]; hasPassword || mustJSON(body["secrets_set"]) != `["password"]` {
t.Errorf("create answer exposes or misses the password: %s", mustJSON(body))
}
var stored string
_ = e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT config::text FROM monitors WHERE id = $1`, id).Scan(&stored)
})
if strings.Contains(stored, `"password"`) || !strings.Contains(stored, "sealed_password") {
t.Errorf("stored config = %s", stored)
}
latestOK := func() bool {
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
for _, m := range list["monitors"].([]any) {
if l := m.(map[string]any)["latest"].([]any); len(l) > 0 && l[0].(map[string]any)["ok"] == true {
return true
}
}
return false
}
waitFor(t, 15*time.Second, "the checker signing in with the sealed password", latestOK)
// Saving without the password keeps it.
monitor["config"] = map[string]any{"user": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"}
if st, body := owner.do("PUT", "/api/v1/org/monitors/"+id, monitor); st != http.StatusOK || mustJSON(body["secrets_set"]) != `["password"]` {
t.Fatalf("update without password = %d %v", st, body)
}
if _, _, page := owner.page("/monitors/" + id + "/edit"); strings.Contains(page, `value="uptime_test"`) == false || strings.Contains(page, "sealed_") {
t.Error("the editor lacks the settings or shows the sealed password")
}
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
_, _, export := owner.download("/api/v1/org/export?format=json")
for _, raw := range []string{mustJSON(list), string(export)} {
if strings.Contains(raw, "sealed_password") {
t.Error("a sealed password leaves the API")
}
}
}
func TestProtocolMonitorSecrets(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("proto")+".test", uniq("proto-"))
for _, tc := range []struct {
typ, target string
config map[string]any
secrets string
}{
{"radius", "radius.example.com:1812", map[string]any{"secret": "radius-shared-1", "user": "probe", "password": "radius-pw-1"}, `["password","secret"]`},
{"snmp", "switch.example.com:161", map[string]any{"community": "snmp-comm-1", "oid": "1.3.6.1.2.1.1.5.0"}, `["community"]`},
} {
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": tc.typ, "type": tc.typ, "target": tc.target, "interval_seconds": 60, "regions": []string{region}, "config": tc.config,
})
if st != http.StatusCreated || mustJSON(body["secrets_set"]) != tc.secrets {
t.Fatalf("create %s = %d %s", tc.typ, st, mustJSON(body))
}
_, _, page := owner.page("/monitors/" + body["id"].(string) + "/edit")
for _, v := range tc.config {
if s := v.(string); strings.Contains(s, "-1") && (strings.Contains(page, s) || strings.Contains(mustJSON(body), s)) {
t.Errorf("%s: secret %q leaves the server", tc.typ, s)
}
}
if !strings.Contains(page, `name="config.`) {
t.Errorf("%s: editor lacks the settings", tc.typ)
}
}
}
+55 -15
View File
@@ -131,22 +131,29 @@ func (s *Server) listEvidence(c *gin.Context) {
if !ok {
return
}
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
ctx := c.Request.Context()
var rows []store.ListEvidenceRow
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListEvidence(ctx, m.ID)
rows, err = q.ListEvidence(ctx, store.ListEvidenceParams{
MonitorID: m.ID, AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
return err
})
if err != nil {
internalError(c, err)
return
}
rows, info := paginate(pg, rows, func(r store.ListEvidenceRow) cursor { return cursor{T: r.Time, ID: r.ID} })
out := make([]evidenceSummary, len(rows))
for i, r := range rows {
out[i] = evidenceSummary{ID: r.ID, Region: r.Region, Time: r.Time, OK: r.Ok, StatusCode: r.StatusCode, Error: r.Error}
}
c.JSON(http.StatusOK, gin.H{"evidence": out})
c.JSON(http.StatusOK, gin.H{"evidence": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func (s *Server) loadEvidence(c *gin.Context, m store.Monitor) (store.CheckEvidence, check.Evidence, bool) {
@@ -295,32 +302,65 @@ func prettyBody(contentType, body string) string {
return buf.String()
}
// evidenceRows lists stored evidence of m for its page.
func (s *Server) evidenceRows(ctx context.Context, p *principal, d monitorData, m store.Monitor) ([]web.EvidenceRow, map[string]string, error) {
// evidenceShown is how much of a monitor's evidence its page lists.
const evidenceShown = 20
// evidenceRows lists the latest stored evidence of m for its page.
func (s *Server) evidenceRows(ctx context.Context, p *principal, d monitorData, m store.Monitor) ([]web.EvidenceRow, error) {
var rows []store.ListEvidenceRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListEvidence(ctx, m.ID)
rows, err = q.ListEvidence(ctx, store.ListEvidenceParams{MonitorID: m.ID, MaxRows: evidenceShown})
return err
})
byResult := map[string]string{}
out := make([]web.EvidenceRow, 0, min(len(rows), 20))
for i, r := range rows {
url := "/monitors/" + m.ID.String() + "/evidence/" + r.ID.String()
byResult[evidenceKey(r.Region, r.Time)] = url
if i >= 20 {
continue
}
out := make([]web.EvidenceRow, 0, len(rows))
for _, r := range rows {
detail := deref(r.Error)
if detail == "" && r.StatusCode != nil {
detail = strconv.Itoa(int(*r.StatusCode))
}
out = append(out, web.EvidenceRow{URL: url, Time: r.Time.Local().Format("01-02 15:04:05"), Region: d.regionNameString(r.Region), OK: r.Ok, Detail: detail})
out = append(out, web.EvidenceRow{
URL: "/monitors/" + m.ID.String() + "/evidence/" + r.ID.String(), Time: r.Time.Local().Format("01-02 15:04:05"),
Region: d.regionNameString(r.Region), OK: r.Ok, Detail: detail,
})
}
return out, byResult, err
return out, err
}
// evidenceKey matches evidence with the check result it belongs to.
func evidenceKey(region string, t time.Time) string {
return region + "@" + strconv.FormatInt(t.UnixMicro(), 10)
}
// resultView is one check result.
type resultView struct {
Time time.Time `json:"time"`
Region string `json:"region"`
CheckerID uuid.UUID `json:"checker_id"`
OK bool `json:"ok"`
LatencyMS *int32 `json:"latency_ms"`
StatusCode *int32 `json:"status_code,omitempty"`
Error *string `json:"error,omitempty"`
}
// listResults pages through a monitor's check results, newest first.
func (s *Server) listResults(c *gin.Context) {
m, _, ok := s.evidenceMonitor(c)
if !ok {
return
}
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
rows, info, err := s.resultPage(c.Request.Context(), current(c), m, pg)
if err != nil {
internalError(c, err)
return
}
out := make([]resultView, len(rows))
for i, r := range rows {
out[i] = resultView{r.Time, r.Region, r.CheckerID, r.Ok, r.LatencyMs, r.StatusCode, r.Error}
}
c.JSON(http.StatusOK, gin.H{"results": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
+79 -30
View File
@@ -208,6 +208,7 @@ func (s *Server) sendExport(c *gin.Context, format, name, title string, x any) {
}
type orgExport struct {
AlertGroups []alertGroupView `json:"alert_groups"`
GeneratedAt time.Time `json:"generated_at"`
Organization exportOrg `json:"organization"`
Members []exportMember `json:"members"`
@@ -255,6 +256,7 @@ type exportGroup struct {
}
type exportMonitor struct {
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
@@ -277,19 +279,22 @@ type exportChannel struct {
}
type exportStatusPage struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
Published bool `json:"published"`
CustomDomain *string `json:"custom_domain"`
Monitors []exportPageMember `json:"monitors"`
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
Published bool `json:"published"`
ShowComponentDetails bool `json:"show_component_details"`
CustomDomain *string `json:"custom_domain"`
Groups []pageGroupView `json:"groups"`
Monitors []exportPageMember `json:"monitors"`
}
type exportPageMember struct {
MonitorID uuid.UUID `json:"monitor_id"`
Section string `json:"section"`
Label string `json:"label"`
MonitorID uuid.UUID `json:"monitor_id"`
GroupID *uuid.UUID `json:"group_id"`
Section string `json:"section"`
Label string `json:"label"`
}
type exportSSO struct {
@@ -391,6 +396,25 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
x.Groups = append(x.Groups, exportGroup{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
}
alertGroups, err := q.ListAlertGroups(ctx)
if err != nil {
return err
}
x.AlertGroups = []alertGroupView{}
for _, g := range alertGroups {
x.AlertGroups = append(x.AlertGroups, alertGroupView{
ID: g.ID, Name: g.Name, IsDefault: g.IsDefault,
ChannelIDs: g.ChannelIds, QuietHours: decodeQuietHours(g.QuietHours),
})
}
alertAssignments, err := q.AllMonitorAlertGroups(ctx)
if err != nil {
return err
}
alertGroupsByMonitor := map[uuid.UUID][]uuid.UUID{}
for _, a := range alertAssignments {
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
}
regionRows, err := q.AllMonitorRegions(ctx)
if err != nil {
return err
@@ -408,7 +432,8 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
x.Monitors = append(x.Monitors, exportMonitor{
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
TimeoutMS: m.TimeoutMs, Confirmations: m.Confirmations, Enabled: m.Enabled, GroupID: m.GroupID,
Regions: orEmpty(regions[m.ID]), Config: rawJSON(m.Config), CreatedAt: m.CreatedAt,
AlertGroupIDs: orEmpty(alertGroupsByMonitor[m.ID]),
Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt,
})
}
@@ -427,17 +452,30 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
}
x.StatusPages = []exportStatusPage{}
for _, pg := range pages {
pgGroups, err := q.ListStatusPageGroups(ctx, pg.ID)
if err != nil {
return err
}
exportedGroups := []pageGroupView{}
newPageGroupTree(pgGroups).walk(func(g store.StatusPageGroup, _ int) {
exportedGroups = append(exportedGroups, pageGroupView{
ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position,
})
})
pm, err := q.StatusPageMonitors(ctx, pg.ID)
if err != nil {
return err
}
members := []exportPageMember{}
for _, m := range pm {
members = append(members, exportPageMember{MonitorID: m.MonitorID, Section: m.Section, Label: m.Label})
members = append(members, exportPageMember{
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
})
}
x.StatusPages = append(x.StatusPages, exportStatusPage{
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description, Published: pg.Published,
CustomDomain: pg.CustomDomain, Monitors: members,
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
})
}
@@ -571,8 +609,28 @@ func (s *Server) deleteAccount(c *gin.Context) {
fail(c, http.StatusForbidden, "confirmation_failed")
return
}
var shared []string
var orgsDeleted int
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.owns_shared_orgs"), "organizations": shared,
})
return
}
auth.ClearCookie(c)
// Kept as proof of erasure, without saying whose.
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
map[string]any{"organizations_deleted": orgsDeleted})
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
// eraseAccount deletes u with the organizations only u belongs to and
// ends u's sessions. If u owns organizations shared with others, nothing
// is deleted and their slugs are returned.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []string, orgsDeleted int, err error) {
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, u.ID)
if err != nil {
@@ -605,24 +663,13 @@ func (s *Server) deleteAccount(c *gin.Context) {
}
return nil
})
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.owns_shared_orgs"), "organizations": shared,
})
return
if err != nil || len(shared) > 0 {
return shared, 0, err
}
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
}
auth.ClearCookie(c)
// Kept as proof of erasure, without saying whose.
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
map[string]any{"organizations_deleted": orgsDeleted})
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
return nil, orgsDeleted, nil
}
type orgDeletionRequest struct {
@@ -672,3 +719,5 @@ func (s *Server) deleteOrg(c *gin.Context) {
map[string]any{"slug": p.Org.Slug, "name": p.Org.Name})
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
func first[A, B any](a A, _ B) A { return a }
+14
View File
@@ -90,6 +90,20 @@ func TestExports(t *testing.T) {
if st != http.StatusOK {
t.Fatalf("org export = %d", st)
}
var org map[string]any
if err := json.Unmarshal(raw, &org); err != nil {
t.Fatal(err)
}
groups := org["alert_groups"].([]any)
monitors := org["monitors"].([]any)
if len(groups) != 1 || len(monitors) != 1 {
t.Fatalf("export groups/monitors = %v/%v", groups, monitors)
}
group := groups[0].(map[string]any)
assigned := monitors[0].(map[string]any)["alert_group_ids"].([]any)
if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(group["quiet_hours"].([]any)) != 0 || len(assigned) != 1 || assigned[0] != group["id"] {
t.Fatalf("export lost alert routing: group=%v assignments=%v", group, assigned)
}
if !bytes.Contains(raw, []byte(`"Shop"`)) || !bytes.Contains(raw, []byte(`"Hook"`)) {
t.Errorf("org export lacks monitor or channel")
}
-3
View File
@@ -68,9 +68,6 @@ func (t groupTree) resources(group *uuid.UUID) []authz.Resource {
return out
}
// depth returns how many ancestors a group has.
func (t groupTree) depth(id uuid.UUID) int { return len(t.resources(&id)) - 1 }
// walk visits groups depth-first in name order.
func (t groupTree) walk(fn func(g store.MonitorGroup, depth int)) {
var visit func(ids []uuid.UUID, depth int)
+12 -3
View File
@@ -82,7 +82,13 @@ func (s *Server) ping(c *gin.Context) {
// recordHeartbeat stores a ping or a missed deadline and evaluates it like
// a checker result.
func (s *Server) recordHeartbeat(ctx context.Context, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
row := store.InsertCheckResultsParams{Time: at, OrgID: org, MonitorID: id, Region: heartbeatRegion, Ok: ok}
return s.recordPassive(ctx, heartbeatRegion, id, org, interval, confirmations, ok, msg, at)
}
// recordPassive stores a result reported to us instead of by a checker,
// under the pseudo-region of its kind, and evaluates it.
func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
row := store.InsertCheckResultsParams{Time: at, OrgID: org, MonitorID: id, Region: region, Ok: ok}
if msg != "" {
row.Error = ptr(truncateValid(msg, 500))
}
@@ -93,10 +99,10 @@ func (s *Server) recordHeartbeat(ctx context.Context, id, org uuid.UUID, interva
if err != nil {
return err
}
s.evaluateResults(ctx, heartbeatRegion,
s.evaluateResults(ctx, region,
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
map[uuid.UUID]store.MonitorsForResultsRow{id: {
ID: id, OrgID: org, IntervalSeconds: interval, Confirmations: confirmations, Regions: []string{heartbeatRegion},
ID: id, OrgID: org, IntervalSeconds: interval, Confirmations: confirmations, Regions: []string{region},
}})
return nil
}
@@ -123,6 +129,9 @@ func (s *Server) RunHeartbeats(ctx context.Context) {
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
}
if err := s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false); err != nil && ctx.Err() == nil {
s.log.ErrorContext(ctx, "checking alertmanager monitors failed", "error", err)
}
}
}
+10 -3
View File
@@ -47,7 +47,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
// tokens and incidents older than the daily aggregate.
func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
keep := s.cfg.Retention
var counts [6]int64
var counts [7]int64
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if keep.Housekeeping > 0 {
@@ -72,15 +72,22 @@ func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
return err
}
}
if _, err = q.PurgeAlertmanagerAlerts(ctx, now.Add(-keepAlerts)); err != nil {
return err
}
if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
return err
}
if keep.Daily > 0 {
before := now.Add(-keep.Daily)
counts[3], err = q.PurgeIncidents(ctx, &before)
}
return err
})
if err == nil && counts != [6]int64{} {
if err == nil && counts != [7]int64{} {
s.log.InfoContext(ctx, "housekeeping purged rows",
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5])
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5],
"unverified_accounts", counts[6])
}
return err
}
+4 -1
View File
@@ -279,13 +279,16 @@ func (s *Server) inviteSignup(c *gin.Context) {
}
var user store.User
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
// The organization invited this address, which stands in for
// confirming it.
user, err = q.CreateUser(ctx, store.CreateUserParams{
Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)),
EmailKey: ptr(emailKey(inv.Email)), EmailVerifiedAt: ptr(time.Now()),
})
return err
})
if isUniqueViolation(err, "users_email_key") {
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
fail(c, http.StatusConflict, "email_taken")
return
}
+11 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -174,7 +175,16 @@ func (s *Server) legalPage(c *gin.Context) {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), html))
var me *web.Me
if sess := auth.Current(c); sess != nil {
m, _, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return
}
me = &m
}
web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), me, html))
return
}
c.Status(http.StatusNotFound)
+7
View File
@@ -46,6 +46,13 @@ func TestLegalDocuments(t *testing.T) {
if st != http.StatusOK || !strings.Contains(html, "<h1>Impressum</h1>") || strings.Contains(html, "<script>alert") {
t.Errorf("GET /legal/imprint = %d, rendered %q", st, html)
}
if !strings.Contains(html, `href="/login"`) {
t.Error("the imprint offers visitors no way to sign in")
}
// Signed in, the imprint keeps the console navigation.
if _, _, html := admin.page("/legal/imprint"); !strings.Contains(html, `href="/monitors`) && !strings.Contains(html, `href="/incidents"`) {
t.Error("the imprint lacks the console navigation for signed-in users")
}
// Status pages fall back to the platform's documents.
owner := e.browser(t)
+418
View File
@@ -0,0 +1,418 @@
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Platform admins limit what organizations and accounts may create. The
// platform defaults apply to every organization without an override of its
// own, also after they change. 0 means unlimited.
const settingLimits = "limits"
// Limits are the limits in effect for an organization, or the platform
// defaults.
type Limits struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
RegionsPerMonitor int `json:"regions_per_monitor"`
// OwnRegionsCount makes the organization's own checker regions count
// towards RegionsPerMonitor; otherwise only platform regions do.
OwnRegionsCount bool `json:"own_regions_count"`
// OrgsPerAccount limits the organizations an account owns.
OrgsPerAccount int `json:"orgs_per_account"`
}
func (s *Server) defaultLimits() Limits {
if s.cloud() {
return Limits{OrgsPerAccount: 3}
}
return Limits{}
}
// platformLimits returns the platform defaults.
func (s *Server) platformLimits(ctx context.Context) Limits {
l, err := s.limits.get(ctx, s.rdb, func(ctx context.Context) (Limits, error) {
l := s.defaultLimits()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingLimits)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &l)
})
return l, err
})
if err != nil {
s.log.WarnContext(ctx, "loading limits failed", "error", err)
return s.defaultLimits()
}
return l
}
// orgLimits applies org's overrides to the platform defaults.
func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
l := s.platformLimits(ctx)
override := func(dst *int, v *int32) {
if v != nil {
*dst = int(*v)
}
}
override(&l.Monitors, org.LimitMonitors)
override(&l.StatusPages, org.LimitStatusPages)
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
if org.LimitOwnRegionsCount != nil {
l.OwnRegionsCount = *org.LimitOwnRegionsCount
}
return l
}
// limitError reports a reached limit from inside a transaction.
type limitError struct {
code string
max int
}
func (e limitError) Error() string { return fmt.Sprintf("api: %s (%d)", e.code, e.max) }
// failLimit answers err if it is a limitError and reports whether it was.
func failLimit(c *gin.Context, err error) bool {
var le limitError
if errors.As(err, &le) {
fail(c, http.StatusUnprocessableEntity, le.code, "Max", le.max)
return true
}
return false
}
// reserve locks org's usage and fails if count, from countFn, has reached
// max.
func reserve(ctx context.Context, q *store.Queries, org uuid.UUID, max int, code string, countFn func(context.Context, uuid.UUID) (int64, error)) error {
if max == 0 {
return nil
}
if err := q.LockOrgUsage(ctx, org); err != nil {
return err
}
n, err := countFn(ctx, org)
if err != nil {
return err
}
if n >= int64(max) {
return limitError{code, max}
}
return nil
}
// countedRegions counts the regions that count towards the limit.
func countedRegions(l Limits, regions []uuid.UUID, platform map[uuid.UUID]bool) int {
n := 0
for _, r := range regions {
if l.OwnRegionsCount || platform[r] {
n++
}
}
return n
}
// checkRegions fails if a monitor would use more counted regions than
// allowed. A monitor already beyond a lowered limit may keep its regions
// but not add any.
func checkRegions(l Limits, regions, previous []uuid.UUID, platform map[uuid.UUID]bool) error {
n := countedRegions(l, regions, platform)
if l.RegionsPerMonitor == 0 || n <= l.RegionsPerMonitor || n <= countedRegions(l, previous, platform) {
return nil
}
if l.OwnRegionsCount {
return limitError{"region_limit", l.RegionsPerMonitor}
}
return limitError{"platform_region_limit", l.RegionsPerMonitor}
}
type usageView struct {
Limits Limits `json:"limits"`
Usage struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
} `json:"usage"`
}
func (s *Server) orgUsage(ctx context.Context, p *principal) (usageView, error) {
v := usageView{Limits: s.orgLimits(ctx, p.Org)}
v.Limits.OrgsPerAccount = 0
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
m, err := q.CountMonitors(ctx, p.Org.ID)
if err != nil {
return err
}
pg, err := q.CountStatusPages(ctx, p.Org.ID)
v.Usage.Monitors, v.Usage.StatusPages = int(m), int(pg)
return err
})
return v, err
}
func (s *Server) getOrgLimits(c *gin.Context) {
v, err := s.orgUsage(c.Request.Context(), current(c))
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, v)
}
func (s *Server) adminGetLimits(c *gin.Context) {
c.JSON(http.StatusOK, s.platformLimits(c.Request.Context()))
}
type limitsRequest struct {
Monitors int `json:"monitors" binding:"min=0,max=1000000"`
StatusPages int `json:"status_pages" binding:"min=0,max=1000000"`
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
OwnRegionsCount bool `json:"own_regions_count"`
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
}
func (s *Server) adminSetLimits(c *gin.Context) {
var req limitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(Limits(req))
auditDetail(c, "limits", Limits(req))
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingLimits, Value: raw})
})
if err != nil {
internalError(c, err)
return
}
if err := s.limits.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing limit change failed", "error", err)
}
c.Status(http.StatusNoContent)
}
// optBool is a JSON boolean that may be null, and also accepts "true",
// "false" and "" from forms.
type optBool struct{ v *bool }
// UnmarshalJSON implements json.Unmarshaler.
func (o *optBool) UnmarshalJSON(b []byte) error {
switch strings.Trim(string(b), `"`) {
case "null", "":
o.v = nil
case "true":
t := true
o.v = &t
case "false":
f := false
o.v = &f
default:
return errors.New("not a boolean")
}
return nil
}
// MarshalJSON implements json.Marshaler.
func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
// orgLimitsRequest overrides limits for one organization; null follows the
// platform default.
type orgLimitsRequest struct {
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
OwnRegionsCount optBool `json:"own_regions_count"`
}
func (s *Server) adminSetOrgLimits(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req orgLimitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
auditDetail(c, "limits", req)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
})
auditDetail(c, "slug", row.Slug)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
type userLimitsRequest struct {
// Orgs limits the organizations the account owns; null follows the
// platform default.
Orgs *int32 `json:"orgs" binding:"omitempty,min=0,max=100000"`
}
func (s *Server) adminSetUserLimits(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req userLimitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
auditDetail(c, "orgs", req.Orgs)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SetUserOrgLimit(ctx, store.SetUserOrgLimitParams{ID: id, Orgs: req.Orgs})
auditDetail(c, "email", row.Email)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
// adminOrg is an organization in the admin list.
type adminOrg struct {
moderatedOrg
Created string `json:"created_at"`
Overrides orgLimitsView `json:"overrides"`
Limits Limits `json:"limits"`
Usage struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
} `json:"usage"`
Owner *adminOwner `json:"owner"`
}
type orgLimitsView struct {
Monitors *int32 `json:"monitors"`
StatusPages *int32 `json:"status_pages"`
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
OwnRegionsCount *bool `json:"own_regions_count"`
}
type adminOwner struct {
moderatedUser
// OrgLimit overrides the organizations the account may own.
OrgLimit *int32 `json:"org_limit"`
Orgs int `json:"orgs"`
}
func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]adminOrg, pageInfo, error) {
var rows []store.AdminListOrgsRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.AdminListOrgs(ctx, store.AdminListOrgsParams{
Search: truncate(strings.TrimSpace(search), 200), MaxRows: pg.fetch(),
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.AdminListOrgsRow) cursor { return cursor{T: r.CreatedAt, ID: r.ID} })
defaults := s.platformLimits(ctx)
out := make([]adminOrg, len(rows))
for i, r := range rows {
o := &out[i]
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
o.Created = r.CreatedAt.Format("2006-01-02")
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount}
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount})
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
if r.OwnerID != uuid.Nil {
o.Owner = &adminOwner{
moderatedUser: moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin},
OrgLimit: r.OwnerLimitOrgs, Orgs: int(r.OwnerOrgs),
}
if r.OwnerLimitOrgs != nil {
o.Limits.OrgsPerAccount = int(*r.OwnerLimitOrgs)
}
}
}
return out, info, err
}
func (s *Server) adminListOrgs(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
orgs, info, err := s.adminOrgs(c.Request.Context(), c.Query("q"), pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"orgs": orgs, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func webLimits(l Limits) web.LimitsView { return web.LimitsView(l) }
func optInt(v *int32) string {
if v == nil {
return ""
}
return strconv.Itoa(int(*v))
}
func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
ctx := c.Request.Context()
orgs, info, err := s.adminOrgs(ctx, c.Query("q"), pg)
v := web.OrgsView{
Search: strings.TrimSpace(c.Query("q")), Pager: pager(c, info), Next: c.Request.URL.RequestURI(),
Defaults: webLimits(s.platformLimits(ctx)),
}
state := func(at *time.Time, reason string) string {
switch {
case at == nil:
return ""
case reason == "":
return "-"
}
return reason
}
for _, o := range orgs {
row := web.OrgRow{
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor),
}
if o.Overrides.OwnRegionsCount != nil {
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
}
if o.Owner != nil {
row.Owner = &web.ModeratedTarget{ID: o.Owner.ID.String(), Name: o.Owner.Email, Suspended: state(o.Owner.SuspendedAt, o.Owner.Reason), Admin: o.Owner.Admin}
row.OwnerOrgs, row.OwnerOrgLimit = o.Owner.Orgs, optInt(o.Owner.OrgLimit)
}
v.Orgs = append(v.Orgs, row)
}
return v, err
}
+157
View File
@@ -0,0 +1,157 @@
package api_test
import (
"context"
"net/http"
"strings"
"sync"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestLimits(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
return err
})
}
reset()
t.Cleanup(reset)
admin := e.browser(t)
admin.signup("admin@"+uniq("lim")+".test", uniq("lim-admin-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
setDefaults := func(l map[string]any) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/limits", l); st != http.StatusNoContent {
t.Fatalf("set defaults = %d %v", st, body)
}
}
setDefaults(map[string]any{"monitors": 2, "status_pages": 1, "regions_per_monitor": 1, "own_regions_count": false, "orgs_per_account": 3})
_, p1 := e.platformChecker(t, uniq("eu-"))
_, p2 := e.platformChecker(t, uniq("us-"))
owner := e.browser(t)
orgSlug := uniq("lim-org-")
owner.signup("o@"+uniq("lim")+".test", orgSlug)
_, own := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
o1 := own["id"].(string)
monitor := func(regions ...string) (int, map[string]any) {
return owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": regions,
})
}
// Monitors, passive ones included.
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
t.Fatalf("heartbeat = %d %v", st, body)
}
if st, body := monitor(p1); st != http.StatusCreated {
t.Fatalf("second monitor = %d %v", st, body)
}
st, body := monitor(p1)
expect(t, "third monitor", st, body, http.StatusUnprocessableEntity, "monitor_limit")
if !strings.Contains(body["message"].(string), "2") {
t.Errorf("message lacks the limit: %v", body["message"])
}
_, usage := owner.do("GET", "/api/v1/org/limits", nil)
if raw := mustJSON(usage); !strings.Contains(raw, `"monitors":2`) || !strings.Contains(raw, `"usage":{"monitors":2,"status_pages":0}`) {
t.Errorf("org limits = %s", raw)
}
// An override lifts the monitor limit; own regions do not count.
_, orgs := admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
org := orgs["orgs"].([]any)[0].(map[string]any)
orgID := org["id"].(string)
setOrg := func(l map[string]any) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+orgID+"/limits", l); st != http.StatusNoContent {
t.Fatalf("set org limits = %d %v", st, body)
}
}
setOrg(map[string]any{"monitors": 10, "status_pages": nil, "regions_per_monitor": nil, "own_regions_count": nil})
st, body = monitor(p1, p2)
expect(t, "two platform regions", st, body, http.StatusUnprocessableEntity, "platform_region_limit")
st, mixed := monitor(p1, o1)
expect(t, "platform and own region", st, mixed, http.StatusCreated, "")
// Once own regions count, the existing monitor keeps both but may not
// grow, and new ones are refused.
setOrg(map[string]any{"monitors": 10, "own_regions_count": "true"})
st, body = monitor(p1, o1)
expect(t, "own region counted", st, body, http.StatusUnprocessableEntity, "region_limit")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, o1},
})
expect(t, "edit a monitor beyond a lowered limit", st, body, http.StatusOK, "")
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, p2, o1},
})
expect(t, "grow a monitor beyond the limit", st, body, http.StatusUnprocessableEntity, "region_limit")
// Status pages; concurrent creations cannot overshoot.
var wg sync.WaitGroup
var mu sync.Mutex
created := 0
for range 5 {
wg.Add(1)
go func() {
defer wg.Done()
st, _ := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("p-"), "title": "x"})
mu.Lock()
defer mu.Unlock()
if st == http.StatusCreated {
created++
}
}()
}
wg.Wait()
if created != 1 {
t.Errorf("%d status pages created under a limit of 1", created)
}
// Defaults change for every organization without an override, at once.
other := e.browser(t)
other.signup("x@"+uniq("lim")+".test", uniq("lim-x-"))
setDefaults(map[string]any{"monitors": 1})
if st, _ := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
t.Fatalf("first monitor = %d", st)
}
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
expect(t, "default lowered", st, body, http.StatusUnprocessableEntity, "monitor_limit")
setDefaults(map[string]any{"monitors": 0})
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
expect(t, "default unlimited", st, body, http.StatusCreated, "")
// Account limits and the admin list.
ownerID := org["owner"].(map[string]any)["id"].(string)
if st, body := admin.do("PUT", "/api/v1/admin/users/"+ownerID+"/limits", map[string]any{"orgs": 5}); st != http.StatusNoContent {
t.Fatalf("set user limit = %d %v", st, body)
}
_, orgs = admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
raw := mustJSON(orgs)
for _, want := range []string{`"org_limit":5`, `"orgs":1`, `"monitors":10`, `"own_regions_count":true`, `"usage":{"monitors":3,"status_pages":1}`} {
if !strings.Contains(raw, want) {
t.Errorf("admin org list lacks %s: %s", want, raw)
}
}
if st, _ := owner.do("GET", "/api/v1/admin/orgs", nil); st != http.StatusForbidden {
t.Errorf("non-admin org list = %d", st)
}
if _, _, html := admin.page("/admin/orgs?q=" + orgSlug); !strings.Contains(html, `id="orgs"`) || !strings.Contains(html, orgSlug) {
t.Error("the admin page lacks the organization list")
}
if _, _, html := owner.page("/settings/org"); !strings.Contains(html, "3 / 10") {
t.Error("the organization settings lack the usage")
}
}
+20 -7
View File
@@ -266,19 +266,24 @@ func (ms maintenanceScope) can(p *principal, perm authz.Permission, monitors, gr
return n == len(monitors)+len(groups)
}
func (s *Server) listMaintenanceViews(ctx context.Context, p *principal, ms maintenanceScope) ([]maintenanceView, error) {
// listMaintenanceViews reads a page of maintenance windows, latest start
// first, keeping those p may read: a page may hold fewer.
func (s *Server) listMaintenanceViews(ctx context.Context, p *principal, ms maintenanceScope, pg pageReq) ([]maintenanceView, pageInfo, error) {
var (
windows []store.MaintenanceWindow
targets []store.MaintenanceTarget
)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if windows, err = q.ListMaintenance(ctx); err != nil {
if windows, err = q.ListMaintenancePage(ctx, store.ListMaintenancePageParams{
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
}); err != nil {
return err
}
targets, err = q.ListMaintenanceTargets(ctx)
return err
})
windows, info := paginate(pg, windows, func(w store.MaintenanceWindow) cursor { return cursor{T: w.StartsAt, ID: w.ID} })
out := []maintenanceView{}
now := time.Now()
for _, w := range windows {
@@ -287,7 +292,7 @@ func (s *Server) listMaintenanceViews(ctx context.Context, p *principal, ms main
out = append(out, v)
}
}
return out, err
return out, info, err
}
func (s *Server) listMaintenance(c *gin.Context) {
@@ -298,12 +303,16 @@ func (s *Server) listMaintenance(c *gin.Context) {
internalError(c, err)
return
}
out, err := s.listMaintenanceViews(ctx, p, ms)
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
out, info, err := s.listMaintenanceViews(ctx, p, ms, pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"maintenance": out})
c.JSON(http.StatusOK, gin.H{"maintenance": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func (s *Server) saveMaintenance(c *gin.Context, id *uuid.UUID) {
@@ -519,11 +528,15 @@ func (s *Server) maintenancePage(c *gin.Context, p *principal, page web.Page, me
if err != nil {
return nil, err
}
windows, err := s.listMaintenanceViews(ctx, p, ms)
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
windows, info, err := s.listMaintenanceViews(ctx, p, ms, pg)
if err != nil {
return nil, err
}
v := web.MaintenanceView{Form: web.MaintenanceForm{Duration: 60, Recurrence: "none", Every: 1}}
v := web.MaintenanceView{Form: web.MaintenanceForm{Duration: 60, Recurrence: "none", Every: 1}, Pager: pager(c, info)}
ms.tree.walk(func(g store.MonitorGroup, depth int) {
if canInGroup(p, authz.MonitorsWrite, ms.tree, &g.ID) {
v.Groups = append(v.Groups, web.TargetOption{ID: g.ID.String(), Name: g.Name, Depth: depth})
+14 -5
View File
@@ -32,15 +32,20 @@ type memberView struct {
Assignments []assignmentView `json:"assignments"`
}
func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) {
// loadMembers reads a page of members by email.
func (s *Server) loadMembers(c *gin.Context, pg pageReq) ([]memberView, pageInfo, error) {
p := current(c)
ctx := c.Request.Context()
var out []memberView
var info pageInfo
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
members, err := q.ListOrgMembers(ctx, p.Org.ID)
members, err := q.ListOrgMembersPage(ctx, store.ListOrgMembersPageParams{
OrgID: p.Org.ID, AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
if err != nil {
return err
}
members, info = paginate(pg, members, func(m store.ListOrgMembersPageRow) cursor { return cursor{S: m.Email, ID: m.ID} })
assigns, err := q.ListAssignments(ctx, p.Org.ID)
if err != nil {
return err
@@ -64,16 +69,20 @@ func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) {
}
return nil
})
return out, err
return out, info, err
}
func (s *Server) listMembers(c *gin.Context) {
members, err := s.loadMembers(c)
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
members, info, err := s.loadMembers(c, pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"members": members})
c.JSON(http.StatusOK, gin.H{"members": members, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
// removeMember requires the actor to hold every permission the member holds
+311
View File
@@ -0,0 +1,311 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Platform admins moderate public status pages and the organizations and
// accounts behind them: suspending hides or stops them and can be undone,
// deleting cannot. Suspended pages leave status page servers when these
// next ask for them, within half a minute.
type moderatedPage struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Published bool `json:"published"`
Domain string `json:"custom_domain,omitempty"`
SuspendedAt *time.Time `json:"suspended_at"`
Reason string `json:"suspended_reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
Org moderatedOrg `json:"org"`
Owner *moderatedUser `json:"owner"`
}
type moderatedOrg struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
SuspendedAt *time.Time `json:"suspended_at"`
Reason string `json:"suspended_reason,omitempty"`
}
type moderatedUser struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
SuspendedAt *time.Time `json:"suspended_at"`
Reason string `json:"suspended_reason,omitempty"`
// Admin marks platform admins, who cannot be suspended or deleted.
Admin bool `json:"admin,omitempty"`
}
func (s *Server) moderatedPages(ctx context.Context, search string, pg pageReq) ([]moderatedPage, pageInfo, error) {
var rows []store.AdminListStatusPagesRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.AdminListStatusPages(ctx, store.AdminListStatusPagesParams{
Search: truncate(strings.TrimSpace(search), 200), MaxRows: pg.fetch(),
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.AdminListStatusPagesRow) cursor { return cursor{T: r.CreatedAt, ID: r.ID} })
out := make([]moderatedPage, len(rows))
for i, r := range rows {
p := &out[i]
p.ID, p.Slug, p.Title, p.Published, p.SuspendedAt, p.Reason, p.CreatedAt = r.ID, r.Slug, r.Title, r.Published, r.SuspendedAt, r.SuspendedReason, r.CreatedAt
if r.CustomDomain != nil && r.DomainVerifiedAt != nil {
p.Domain = *r.CustomDomain
}
p.Org = moderatedOrg{r.OrgID, r.OrgSlug, r.OrgName, r.OrgSuspendedAt, r.OrgSuspendedReason}
if r.OwnerID != uuid.Nil {
p.Owner = &moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin}
}
}
return out, info, err
}
func (s *Server) adminListStatusPages(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
pages, info, err := s.moderatedPages(c.Request.Context(), c.Query("q"), pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"status_pages": pages, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
type suspensionRequest struct {
Suspended bool `json:"suspended"`
Reason string `json:"reason" binding:"max=500"`
}
// suspension binds a suspension request and the target ID.
func suspension(c *gin.Context) (uuid.UUID, suspensionRequest, bool) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return uuid.Nil, suspensionRequest{}, false
}
var req suspensionRequest
if !bind(c, &req) {
return uuid.Nil, req, false
}
req.Reason = strings.TrimSpace(req.Reason)
auditDetail(c, "suspended", req.Suspended)
if req.Reason != "" {
auditDetail(c, "reason", req.Reason)
}
return id, req, true
}
// moderated finishes a moderation request: 404 for unknown targets.
func moderated(c *gin.Context, err error) bool {
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return false
}
if err != nil {
internalError(c, err)
return false
}
return true
}
func (s *Server) adminSuspendStatusPage(c *gin.Context) {
id, req, ok := suspension(c)
if !ok {
return
}
ctx := c.Request.Context()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SuspendStatusPage(ctx, store.SuspendStatusPageParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
auditDetail(c, "slug", row.Slug)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
func (s *Server) adminDeleteStatusPage(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ctx := c.Request.Context()
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
page, err := q.GetStatusPage(ctx, id)
if err != nil {
return err
}
auditDetail(c, "slug", page.Slug)
_, err = q.DeleteStatusPage(ctx, id)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
func (s *Server) adminSuspendOrg(c *gin.Context) {
id, req, ok := suspension(c)
if !ok {
return
}
ctx := c.Request.Context()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SuspendOrg(ctx, store.SuspendOrgParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
if err != nil {
return err
}
auditDetail(c, "slug", row.Slug)
if !req.Suspended {
return q.RestartHeartbeatWait(ctx, id)
}
return nil
})
if !moderated(c, err) {
return
}
// Monitors leave or rejoin the schedule with its next reconciliation.
c.Status(http.StatusNoContent)
}
func (s *Server) adminDeleteOrg(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ctx := c.Request.Context()
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
org, err := q.GetOrg(ctx, id)
if err != nil {
return err
}
auditDetail(c, "slug", org.Slug)
auditDetail(c, "name", org.Name)
return purgeOrg(ctx, q, id)
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
// moderatedUser loads the target account, refusing platform admins: they
// would otherwise lock each other, or themselves, out.
func (s *Server) moderatedUser(c *gin.Context) (store.User, bool) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return store.User{}, false
}
u, err := s.loadUser(c.Request.Context(), id)
if !moderated(c, err) {
return u, false
}
auditDetail(c, "email", u.Email)
if u.IsAdmin {
fail(c, http.StatusConflict, "target_is_admin")
return u, false
}
return u, true
}
func (s *Server) adminSuspendUser(c *gin.Context) {
id, req, ok := suspension(c)
if !ok {
return
}
u, ok := s.moderatedUser(c)
if !ok {
return
}
ctx := c.Request.Context()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.SuspendUser(ctx, store.SuspendUserParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
return err
})
if !moderated(c, err) {
return
}
if req.Suspended {
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
internalError(c, err)
return
}
}
c.Status(http.StatusNoContent)
}
func (s *Server) adminDeleteUser(c *gin.Context) {
u, ok := s.moderatedUser(c)
if !ok {
return
}
ctx := c.Request.Context()
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.user_owns_shared_orgs"), "organizations": shared,
})
return
}
auditDetail(c, "organizations_deleted", orgsDeleted)
c.Status(http.StatusNoContent)
}
func (s *Server) moderationView(c *gin.Context, pg pageReq) (web.ModerationView, error) {
pages, info, err := s.moderatedPages(c.Request.Context(), c.Query("q"), pg)
v := web.ModerationView{Search: strings.TrimSpace(c.Query("q")), Pager: pager(c, info), Next: c.Request.URL.RequestURI()}
state := func(at *time.Time, reason string) string {
switch {
case at == nil:
return ""
case reason == "":
return "-"
}
return reason
}
for _, p := range pages {
u := strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
if p.Domain != "" {
u = "https://" + p.Domain + "/"
}
mp := web.ModeratedPage{
ID: p.ID.String(), Title: p.Title, Slug: p.Slug, URL: u, Created: p.CreatedAt.Format(time.DateOnly),
Published: p.Published, Suspended: state(p.SuspendedAt, p.Reason),
Org: web.ModeratedTarget{ID: p.Org.ID.String(), Name: p.Org.Name, Detail: p.Org.Slug, Suspended: state(p.Org.SuspendedAt, p.Org.Reason)},
}
if p.Domain != "" {
mp.Slug = p.Domain
}
if p.Owner != nil {
mp.Owner = &web.ModeratedTarget{ID: p.Owner.ID.String(), Name: p.Owner.Email, Suspended: state(p.Owner.SuspendedAt, p.Owner.Reason), Admin: p.Owner.Admin}
}
v.Pages = append(v.Pages, mp)
}
return v, err
}
+195
View File
@@ -0,0 +1,195 @@
package api_test
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const testPassword = "correct horse battery"
func TestModeration(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("admin@"+uniq("mod")+".test", uniq("mod-admin-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
ownerEmail := "owner@" + uniq("mod") + ".test"
owner := e.browser(t)
owner.signup(ownerEmail, uniq("mod-org-"))
slug := uniq("acme-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "published": true})
_, draft := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("draft-"), "title": "Draft", "published": false})
_, hb := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600})
_, region := e.platformChecker(t, uniq("eu-"))
_, web := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Web", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
scheduled := func() bool {
var rows []store.ListEnabledMonitorsForScheduleRow
_ = tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
return err
})
for _, r := range rows {
if r.ID.String() == web["id"] {
return true
}
}
return false
}
_, tok := owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
api := &browser{t: t, base: owner.base, hc: e.srv.Client(), bearer: tok["token"].(string)}
sp := e.statuspageClient(t, nil)
served := func() bool {
_, err := sp.Page(ctx, "", slug)
if err != nil && !errors.Is(err, agentapi.ErrNotFound) {
t.Fatal(err)
}
return err == nil
}
// Pings of paused monitors are answered, so cron jobs do not fail, but
// not recorded.
recorded := func() bool {
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+hb["target"].(string), "text/plain", nil)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return resp.StatusCode == http.StatusOK && !strings.Contains(string(b), "paused")
}
// Only admins see the list; it holds published pages with their
// organization and owner, and search narrows it.
if st, _ := owner.do("GET", "/api/v1/admin/status-pages", nil); st != http.StatusForbidden {
t.Errorf("non-admin listing = %d", st)
}
_, list := admin.do("GET", "/api/v1/admin/status-pages?q="+slug, nil)
raw := mustJSON(list)
if !strings.Contains(raw, slug) || !strings.Contains(raw, ownerEmail) || strings.Contains(raw, draft["slug"].(string)) {
t.Fatalf("list = %s", raw)
}
pg := list["status_pages"].([]any)[0].(map[string]any)
orgID := pg["org"].(map[string]any)["id"].(string)
userID := pg["owner"].(map[string]any)["id"].(string)
if _, other := admin.do("GET", "/api/v1/admin/status-pages?q=no-such-page-"+slug, nil); len(other["status_pages"].([]any)) != 0 {
t.Error("search does not narrow the list")
}
if !served() {
t.Fatal("the page is not served before suspension")
}
// A suspended page goes offline and its organization learns why.
suspend := func(path string, on bool, reason string) {
t.Helper()
if st, body := admin.do("PUT", "/api/v1/admin/"+path+"/suspension", map[string]any{"suspended": on, "reason": reason}); st != http.StatusNoContent {
t.Fatalf("suspend %s = %d %v", path, st, body)
}
}
suspend("status-pages/"+page["id"].(string), true, "phishing")
if served() {
t.Error("a suspended page is served")
}
_, pages := owner.do("GET", "/api/v1/org/statuspages", nil)
if raw := mustJSON(pages); !strings.Contains(raw, `"suspended":true`) || !strings.Contains(raw, `"suspended_reason":"phishing"`) {
t.Errorf("the organization does not see the suspension: %s", raw)
}
if _, _, html := owner.page("/statuspages"); !strings.Contains(html, "suspended by the operator") {
t.Error("the page list does not mark the suspension")
}
suspend("status-pages/"+page["id"].(string), false, "")
if !served() {
t.Error("a reinstated page is not served")
}
// A suspended organization is locked out, checks and pages stop.
suspend("orgs/"+orgID, true, "unpaid")
st, body := owner.do("GET", "/api/v1/org/monitors", nil)
expect(t, "member of a suspended org", st, body, http.StatusForbidden, "org_suspended")
st, body = api.do("GET", "/api/v1/org/monitors", nil)
expect(t, "token of a suspended org", st, body, http.StatusForbidden, "org_suspended")
if served() {
t.Error("a suspended organization's page is served")
}
if recorded() {
t.Error("a heartbeat of a suspended org is recorded")
}
if scheduled() {
t.Error("monitors of a suspended org are scheduled")
}
if _, _, html := owner.page("/"); !strings.Contains(html, "The operator suspended this organization") || !strings.Contains(html, "unpaid") {
t.Error("the console does not explain the suspension")
}
suspend("orgs/"+orgID, false, "")
if st, _ := owner.do("GET", "/api/v1/org/monitors", nil); st != http.StatusOK || !scheduled() {
t.Errorf("member of a reinstated org = %d, scheduled = %v", st, scheduled())
}
if !recorded() {
t.Error("a heartbeat after reinstatement is not recorded")
}
// A suspended account is signed out and kept out, tokens included.
suspend("users/"+userID, true, "")
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("session of a suspended account = %d", st)
}
if st, _ := api.do("GET", "/api/v1/org/monitors", nil); st != http.StatusUnauthorized {
t.Errorf("token of a suspended account = %d", st)
}
fresh := e.browser(t)
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword})
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": "wrong password"}); st != http.StatusUnauthorized {
t.Error("a wrong password reveals the suspension")
}
suspend("users/"+userID, false, "")
if st, _ := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
t.Errorf("sign-in after reinstatement = %d", st)
}
// Admins are out of reach, also for themselves.
st, body = admin.do("PUT", "/api/v1/admin/users/"+admin.userIDSelf().String()+"/suspension", map[string]any{"suspended": true})
expect(t, "suspend an admin", st, body, http.StatusConflict, "target_is_admin")
st, body = admin.do("DELETE", "/api/v1/admin/users/"+admin.userIDSelf().String(), nil)
expect(t, "delete an admin", st, body, http.StatusConflict, "target_is_admin")
// An owner of a shared organization cannot be deleted before it.
fresh.do("POST", "/api/v1/me/org", map[string]any{"org_id": orgID})
e.joinVia(t, fresh.invite("m@"+uniq("mod")+".test", fresh.roleID("viewer")))
st, body = admin.do("DELETE", "/api/v1/admin/users/"+userID, nil)
expect(t, "delete the owner of a shared org", st, body, http.StatusConflict, "owns_shared_orgs")
// Deleting: page, organization, account.
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
t.Errorf("delete page = %d", st)
}
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNoContent {
t.Errorf("delete org = %d", st)
}
if st, body := admin.do("DELETE", "/api/v1/admin/users/"+userID, nil); st != http.StatusNoContent {
t.Errorf("delete account = %d %v", st, body)
}
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusUnauthorized {
t.Error("the deleted account can still sign in")
}
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNotFound {
t.Error("deleting a deleted org is not 404")
}
// The admin page shows the list.
if _, _, html := admin.page("/admin/status-pages"); !strings.Contains(html, `id="moderation"`) {
t.Error("the admin page lacks the status page list")
}
}
+126 -9
View File
@@ -34,8 +34,14 @@ type monitorRequest struct {
// Confirmations is how many failures in a row make a region count as
// down; 0 keeps the default of 2.
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
// platform marks the platform regions among those visible, filled by
// validateMonitor.
platform map[uuid.UUID]bool
// GroupID places the monitor in a group; nil keeps it at the top level.
GroupID *uuid.UUID `json:"group_id"`
// AlertGroupIDs defaults on creation and preserves assignments on update
// when omitted. An explicit empty list disables notifications.
AlertGroupIDs []uuid.UUID `json:"alert_group_ids" binding:"max=100"`
}
type latestView struct {
@@ -48,6 +54,7 @@ type latestView struct {
}
type monitorView struct {
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
@@ -62,20 +69,25 @@ type monitorView struct {
Latest []latestView `json:"latest"`
// PingURL is where heartbeat monitors are pinged.
PingURL string `json:"ping_url,omitempty"`
// SecretsSet names secret settings that are set; their values are
// never returned.
SecretsSet []string `json:"secrets_set,omitempty"`
}
// withPingURL adds the ping URL of heartbeat monitors.
func (s *Server) withPingURL(v monitorView) monitorView {
if check.Passive(check.Type(v.Type)) && v.Target != "" {
if check.Type(v.Type) == check.Heartbeat && v.Target != "" {
v.PingURL = s.pingURL(v.Target)
}
return v
}
func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView {
cfg, secrets := publicMonitorConfig(m.Config)
return monitorView{
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{},
TimeoutMS: m.TimeoutMs, Config: cfg, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{},
SecretsSet: secrets,
}
}
@@ -160,6 +172,10 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTre
internalError(c, err)
return false
}
req.platform = map[uuid.UUID]bool{}
for _, k := range known {
req.platform[k.ID] = k.OrgID == nil
}
for _, r := range req.Regions {
// Row-level security limits known to the org's own and the
// platform regions.
@@ -174,8 +190,13 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTre
// listMonitors returns the monitors the principal may read, org-wide or
// through a group assignment.
func (s *Server) listMonitors(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
p := current(c)
ctx := c.Request.Context()
var info pageInfo
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
@@ -183,10 +204,22 @@ func (s *Server) listMonitors(c *gin.Context) {
}
out := []monitorView{}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
monitors, err := q.ListMonitors(ctx)
monitors, err := q.ListMonitorsPage(ctx, store.ListMonitorsPageParams{
AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
if err != nil {
return err
}
// Paged before filtering by permission: a page may hold fewer.
monitors, info = paginate(pg, monitors, func(m store.Monitor) cursor { return cursor{S: m.Name, ID: m.ID} })
assignments, err := q.AllMonitorAlertGroups(ctx)
if err != nil {
return err
}
alertGroups := map[uuid.UUID][]uuid.UUID{}
for _, a := range assignments {
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
}
regions, err := q.AllMonitorRegions(ctx)
if err != nil {
return err
@@ -210,6 +243,10 @@ func (s *Server) listMonitors(c *gin.Context) {
continue
}
v := viewMonitor(m, byMonitor[m.ID])
v.AlertGroupIDs = alertGroups[m.ID]
if v.AlertGroupIDs == nil {
v.AlertGroupIDs = []uuid.UUID{}
}
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
v = redactMonitor(v)
}
@@ -225,7 +262,7 @@ func (s *Server) listMonitors(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"monitors": out})
c.JSON(http.StatusOK, gin.H{"monitors": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func (s *Server) createMonitor(c *gin.Context) {
@@ -243,11 +280,21 @@ func (s *Server) createMonitor(c *gin.Context) {
if !s.validateMonitor(c, &req, t) {
return
}
if check.Passive(check.Type(req.Type)) {
req.Target = newPingToken()
if !s.offered(ctx, p.Org, req.Type) {
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
return
}
req.Target = passiveTarget(check.Type(req.Type), req.Target)
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
limits := s.orgLimits(ctx, p.Org)
if err := checkRegions(limits, req.Regions, nil, req.platform); failLimit(c, err) {
return
}
var m store.Monitor
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if err := reserve(ctx, q, p.Org.ID, limits.Monitors, "monitor_limit", q.CountMonitors); err != nil {
return err
}
var err error
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
@@ -258,8 +305,22 @@ func (s *Server) createMonitor(c *gin.Context) {
if err != nil {
return err
}
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
return err
}
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
if err != nil {
return err
}
return setRegions(ctx, q, m, req.Regions)
})
if errors.Is(err, errInvalidAlertGroup) {
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
return
}
if failLimit(c, err) {
return
}
if err != nil {
internalError(c, err)
return
@@ -268,7 +329,9 @@ func (s *Server) createMonitor(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, s.withPingURL(viewMonitor(m, req.Regions)))
v := viewMonitor(m, req.Regions)
v.AlertGroupIDs = req.AlertGroupIDs
c.JSON(http.StatusCreated, s.withPingURL(v))
}
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []uuid.UUID) error {
@@ -340,11 +403,22 @@ func (s *Server) updateMonitor(c *gin.Context) {
if previous, err = q.MonitorRegions(ctx, id); err != nil {
return err
}
if old.Type != req.Type && !s.offered(ctx, p.Org, req.Type) {
return errCheckTypeDisabled
}
if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil {
return err
}
if old.Type == req.Type {
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, old.Config)
} else {
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
}
if check.Passive(check.Type(req.Type)) {
// The ping URL stays the same across edits.
req.Target = old.Target
if old.Type != req.Type {
req.Target = newPingToken()
req.Target = passiveTarget(check.Type(req.Type), "")
}
}
m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{
@@ -356,8 +430,26 @@ func (s *Server) updateMonitor(c *gin.Context) {
if err != nil {
return err
}
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
return err
}
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
if err != nil {
return err
}
return setRegions(ctx, q, m, req.Regions)
})
if errors.Is(err, errInvalidAlertGroup) {
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
return
}
if errors.Is(err, errCheckTypeDisabled) {
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
return
}
if failLimit(c, err) {
return
}
if errors.Is(err, pgx.ErrNoRows) || (err == nil && denied) {
fail(c, http.StatusNotFound, "not_found")
return
@@ -370,7 +462,9 @@ func (s *Server) updateMonitor(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusOK, s.withPingURL(viewMonitor(m, req.Regions)))
v := viewMonitor(m, req.Regions)
v.AlertGroupIDs = req.AlertGroupIDs
c.JSON(http.StatusOK, s.withPingURL(v))
}
func (s *Server) deleteMonitor(c *gin.Context) {
@@ -496,3 +590,26 @@ func redactMonitor(v monitorView) monitorView {
}
return v
}
// passiveTarget fills the target of monitors that are reported to us:
// heartbeats get their secret ping token; alertmanager monitors, matched by
// labels, a fixed placeholder.
func passiveTarget(t check.Type, target string) string {
switch t {
case check.Heartbeat:
return newPingToken()
case check.Alertmanager:
return alertmanagerRegion
}
return target
}
// passiveRegion is the pseudo-region results of passive monitors carry.
func passiveRegion(t check.Type) string {
if t == check.Alertmanager {
return alertmanagerRegion
}
return heartbeatRegion
}
var errCheckTypeDisabled = errors.New("api: check type switched off")
+98
View File
@@ -0,0 +1,98 @@
package api
import (
"encoding/base64"
"encoding/json"
"slices"
"strings"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
)
// Monitor settings listed by check.SecretFields, such as database
// passwords, are stored as "sealed_<field>": encrypted and bound to the
// monitor type and field. They are never returned; checkers get them in
// plain text with their jobs.
const sealedPrefix = "sealed_"
func monitorSecretAAD(t check.Type, field string) []byte {
return []byte("monitor:" + string(t) + ":" + field)
}
// sealMonitorConfig replaces secret settings in cfg by their sealed form.
// A secret left empty keeps its value from previous, so forms need not ask
// for passwords again.
func (s *Server) sealMonitorConfig(t check.Type, cfg, previous []byte) []byte {
fields := check.SecretFields(t)
if len(fields) == 0 {
return cfg
}
var m, old map[string]any
if json.Unmarshal(cfg, &m) != nil {
return cfg
}
_ = json.Unmarshal(previous, &old)
for _, f := range fields {
v, _ := m[f].(string)
delete(m, f)
switch {
case v != "":
m[sealedPrefix+f] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), monitorSecretAAD(t, f)))
case old[sealedPrefix+f] != nil:
m[sealedPrefix+f] = old[sealedPrefix+f]
}
}
out, _ := json.Marshal(m)
return out
}
// openMonitorConfig restores secret settings for a checker.
func (s *Server) openMonitorConfig(t check.Type, cfg []byte) ([]byte, error) {
fields := check.SecretFields(t)
if len(fields) == 0 {
return cfg, nil
}
var m map[string]any
if err := json.Unmarshal(cfg, &m); err != nil {
return nil, err
}
for _, f := range fields {
sealed, ok := m[sealedPrefix+f].(string)
delete(m, sealedPrefix+f)
if !ok {
continue
}
raw, err := base64.StdEncoding.DecodeString(sealed)
if err != nil {
return nil, err
}
plain, err := s.keys.Open(raw, monitorSecretAAD(t, f))
if err != nil {
return nil, err
}
m[f] = string(plain)
}
return json.Marshal(m)
}
// publicMonitorConfig drops sealed secrets from cfg and names those set.
func publicMonitorConfig(cfg []byte) ([]byte, []string) {
var m map[string]any
if json.Unmarshal(cfg, &m) != nil {
return cfg, nil
}
var set []string
for k := range m {
if f, ok := strings.CutPrefix(k, sealedPrefix); ok {
set = append(set, f)
delete(m, k)
}
}
if set == nil {
return cfg, nil
}
slices.Sort(set)
out, _ := json.Marshal(m)
return out, set
}
+6 -3
View File
@@ -236,7 +236,7 @@ func buildOpenAPI(publicURL string) map[string]any {
},
}
// Monitor settings travel as untyped config; their shapes per type.
for _, c := range []any{check.HTTPConfig{}, check.JSONConfig{}, check.PrometheusConfig{}, check.DNSConfig{}, check.TLSConfig{}, check.HeartbeatConfig{}} {
for _, c := range []any{check.HTTPConfig{}, check.JSONConfig{}, check.PrometheusConfig{}, check.DNSConfig{}, check.TLSConfig{}, check.DBConfig{}, check.BrokerConfig{}, check.GRPCConfig{}, check.SMTPConfig{}, check.RADIUSConfig{}, check.SNMPConfig{}, check.GameConfig{}, check.DockerConfig{}, check.HeartbeatConfig{}, check.AlertmanagerConfig{}} {
b.schema(reflect.TypeOf(c))
}
paths := map[string]map[string]any{}
@@ -301,12 +301,15 @@ func buildOpenAPI(publicURL string) map[string]any {
return map[string]any{
"openapi": "3.1.0",
"info": map[string]any{
"title": "uptimesebi API",
"title": "UptimeSebi API",
"version": buildinfo.Version,
"description": "Manage monitors, status pages, alerting and members of an organization.\n\n" +
"Authenticate with an API token as `Authorization: Bearer ust_…` (create one under Settings → API tokens; " +
"it never exceeds its owner's permissions), or use the browser session, which additionally needs the " +
"`" + auth.CSRFHeader + "` header on changes. Errors share one format with a stable `error` code.",
"`" + auth.CSRFHeader + "` header on changes. Errors share one format with a stable `error` code.\n\n" +
"Lists marked as paged return at most 100 items (`limit` takes up to 500) with `next_cursor` and " +
"`prev_cursor`; pass one as `after` or `before` to get the next or previous page. A missing cursor " +
"means the list ends there. Cursors are opaque and stay valid while items are added.",
"license": map[string]any{"name": "AGPL-3.0-only", "identifier": "AGPL-3.0-only"},
},
"servers": []any{map[string]any{"url": strings.TrimSuffix(publicURL, "/")}},
+22
View File
@@ -13,6 +13,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
func TestEveryRouteIsDocumented(t *testing.T) {
@@ -115,4 +116,25 @@ func TestAPIDocsServed(t *testing.T) {
if st, _, page := e.browser(t).page("/api/docs"); st != http.StatusOK || !strings.Contains(page, "swagger-ui-bundle.js") {
t.Errorf("/api/docs = %d", st)
}
// Every page carries the favicons, which ship in the embedded /static.
for _, path := range []string{"/brand/favicon.svg", "/brand/favicon-32.png", "/brand/apple-touch-icon.png", "/brand/site.webmanifest"} {
f, err := web.Static().Open(path)
if err != nil {
t.Errorf("static %s: %v", path, err)
continue
}
_ = f.Close()
}
if _, _, login := e.browser(t).page("/login"); !strings.Contains(login, `href="/static/brand/favicon.svg"`) {
t.Error("the login page lacks the favicon")
}
// Linked from every console page and where tokens are created.
if _, _, login := e.browser(t).page("/login"); !strings.Contains(login, `href="/api/docs"`) {
t.Error("the footer does not link the API documentation")
}
b := e.browser(t)
b.signup("d@"+uniq("ad")+".test", uniq("ad-"))
if _, _, tokens := b.page("/settings/tokens"); !strings.Contains(tokens, `href="/api/docs"`) || !strings.Contains(tokens, "Authorization: Bearer") {
t.Error("the token page does not explain usage with a link to the API documentation")
}
}
+106 -7
View File
@@ -16,6 +16,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
@@ -26,6 +27,10 @@ import (
func (s *Server) registerPages(r gin.IRouter) {
r.GET("/login", s.loginPage)
r.GET("/signup", s.signupPage)
r.GET("/signup/sent", s.signupSentPage)
r.GET("/verify", s.verifyPage)
r.GET("/verify/resend", s.resendPage)
r.GET("/orgs/new", s.newOrgPage)
r.GET("/invite/:token", s.invitePage)
s.registerConsole(r)
r.GET("/settings/security", s.securityPage)
@@ -38,6 +43,8 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/settings/audit", s.orgPage("audit.title", authz.AuditRead, s.auditView))
r.GET("/admin", s.adminPage)
r.GET("/admin/audit", s.adminAuditPage)
r.GET("/admin/status-pages", s.adminStatusPagesPage)
r.GET("/admin/orgs", s.adminOrgsPage)
r.GET("/admin/legal", s.adminLegalPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/legal/:kind", s.legalPage)
@@ -49,7 +56,7 @@ var flashErrors = map[ssoError]bool{
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
"totp_required_by_org": true, "sso_required_by_org": true,
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
}
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
@@ -102,6 +109,36 @@ func (s *Server) signupPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title")))
}
func (s *Server) signupSentPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.SignupSent(s.pageFor(c, "auth.verify.sent_title")))
}
// verifyPage confirms an address only when the visitor presses the
// button: mail scanners that open links must not sign in.
func (s *Server) verifyPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.Verify(s.pageFor(c, "auth.verify.title"), c.Query("token")))
}
func (s *Server) resendPage(c *gin.Context) {
web.Render(c, http.StatusOK, web.ResendVerification(s.pageFor(c, "auth.verify.resend_title")))
}
// newOrgPage lets a signed-in account create an organization: the first
// one after signing up, or another.
func (s *Server) newOrgPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login?next=/orgs/new")
return
}
me, _, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.NewOrgPage(s.pageFor(c, "orgs.new_title"), me))
}
// consoleMe loads the signed-in user and, if an organization is active,
// their permissions and policy state there. The principal is nil when the
// user has no active organization or is no longer a member.
@@ -133,6 +170,10 @@ func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *princip
if err != nil || !member {
return me, nil, err
}
if p.Org.SuspendedAt != nil {
me.OrgSuspended, me.SuspendedReason = true, p.Org.SuspendedReason
return me, nil, nil
}
for _, perm := range authz.All {
me.Can[string(perm)] = p.Grants.Can(perm)
}
@@ -213,7 +254,7 @@ func (s *Server) securityPage(c *gin.Context) {
return
}
}
rows, err := s.auditQuery(ctx, tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID, MaxRows: 20}, "")
rows, _, err := s.auditQuery(ctx, tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, pageReq{limit: 20})
if err != nil {
internalError(c, err)
return
@@ -276,8 +317,19 @@ func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me
return web.SSOSettingsPage(page, me, view), nil
}
func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
func (s *Server) orgSettingsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
v := web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}
u, err := s.orgUsage(c.Request.Context(), p)
if err != nil {
return nil, err
}
v.Usage = web.UsageView{Limits: webLimits(u.Limits), Monitors: u.Usage.Monitors, StatusPages: u.Usage.StatusPages}
off := s.disabledChecks(c.Request.Context())
for _, t := range check.Types {
if !off[string(t)] {
v.CheckTypes = append(v.CheckTypes, web.CheckTypeOption{Type: string(t), Enabled: !slices.Contains(p.Org.DisabledCheckTypes, string(t))})
}
}
if p.Org.ApiTokenMaxDays != nil {
v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays)
}
@@ -286,7 +338,11 @@ func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me
func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
c.Set(ctxPrincipal, p)
members, err := s.loadMembers(c)
pg, ok := parsePage(c, consolePageSize)
if !ok {
return nil, errAborted
}
members, info, err := s.loadMembers(c, pg)
if err != nil {
return nil, err
}
@@ -306,7 +362,7 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
if err != nil {
return nil, err
}
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage)}
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info)}
scopeNames, scopes, err := s.scopeOptions(ctx, p)
if err != nil {
return nil, err
@@ -490,7 +546,46 @@ func (s *Server) adminPage(c *gin.Context) {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats)))
off := s.disabledChecks(ctx)
var types []web.CheckTypeOption
for _, t := range check.Types {
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
}
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx))))
}
func (s *Server) adminStatusPagesPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
pg, ok := parsePage(c, consolePageSize)
if !ok {
return
}
v, err := s.moderationView(c, pg)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.AdminStatusPagesPage(s.pageFor(c, "moderation.title"), me, v))
}
func (s *Server) adminOrgsPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
pg, ok := parsePage(c, consolePageSize)
if !ok {
return
}
v, err := s.orgsView(c, pg)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.AdminOrgsPage(s.pageFor(c, "orgs.title"), me, v))
}
func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) {
@@ -512,7 +607,11 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
if a.LastSeenAt != nil {
seen = a.LastSeenAt.Format(time.DateTime)
}
v.Agents = append(v.Agents, web.Agent{ID: a.ID.String(), Kind: a.Kind, Name: a.Name, Region: deref(a.RegionName), Prefix: a.Prefix, LastSeen: seen})
wa := web.Agent{ID: a.ID.String(), Kind: a.Kind, Name: a.Name, Region: deref(a.RegionName), Prefix: a.Prefix, LastSeen: seen}
if a.Kind == "checker" && a.OrgID != nil {
wa.AllowPrivate = &a.AllowPrivate
}
v.Agents = append(v.Agents, wa)
}
return v, nil
}
+218
View File
@@ -0,0 +1,218 @@
package api
import (
"encoding/base64"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Lists are paged by keyset: a cursor holds the sort key of an item and
// its ID, so pages neither skip nor repeat items when others are added.
// after pages forward in the list's order, before backward.
const (
apiPageSize = 100
maxPageSize = 500
consolePageSize = 50
)
// cursor is the position of an item: a time or string sort key and a
// tie-breaking ID.
type cursor struct {
T time.Time `json:"t,omitzero"`
S string `json:"s,omitempty"`
ID uuid.UUID `json:"i,omitzero"`
}
func (c cursor) encode() string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func decodeCursor(s string) (*cursor, bool) {
if s == "" {
return nil, true
}
b, err := base64.RawURLEncoding.DecodeString(s)
var c cursor
if err != nil || json.Unmarshal(b, &c) != nil {
return nil, false
}
return &c, true
}
// pageReq is a requested page.
type pageReq struct {
after, before *cursor
limit int
}
// backward reports whether the page is read against the list's order.
func (p pageReq) backward() bool { return p.before != nil }
// fetch is how many rows to read: one more tells whether more follow.
func (p pageReq) fetch() int32 { return int32(p.limit + 1) }
// at is the cursor to read from, in reading direction.
func (p pageReq) at() *cursor {
if p.before != nil {
return p.before
}
return p.after
}
// Keys of the cursor for queries; nil when not paging from a position.
func (p pageReq) afterT() *time.Time { return timeOf(p.after) }
func (p pageReq) beforeT() *time.Time { return timeOf(p.before) }
func (p pageReq) afterS() *string { return strOf(p.after) }
func (p pageReq) beforeS() *string { return strOf(p.before) }
func (p pageReq) afterID() *uuid.UUID { return idOf(p.after) }
func (p pageReq) beforeID() *uuid.UUID { return idOf(p.before) }
func timeOf(c *cursor) *time.Time {
if c == nil {
return nil
}
return &c.T
}
func strOf(c *cursor) *string {
if c == nil {
return nil
}
return &c.S
}
func idOf(c *cursor) *uuid.UUID {
if c == nil {
return nil
}
return &c.ID
}
// parsePage reads after, before and limit, answering 422 when invalid.
func parsePage(c *gin.Context, def int) (pageReq, bool) {
p := pageReq{limit: def}
if l := c.Query("limit"); l != "" {
n, err := strconv.Atoi(l)
if err != nil || n < 1 || n > maxPageSize {
fail(c, http.StatusUnprocessableEntity, "invalid_limit", "Max", maxPageSize)
return p, false
}
p.limit = n
}
var okA, okB bool
p.after, okA = decodeCursor(c.Query("after"))
p.before, okB = decodeCursor(c.Query("before"))
if !okA || !okB || p.after != nil && p.before != nil {
fail(c, http.StatusUnprocessableEntity, "invalid_cursor")
return p, false
}
return p, true
}
// pageInfo holds the cursors of the neighbouring pages, empty at either
// end of the list.
type pageInfo struct {
Next string `json:"next_cursor,omitempty"`
Prev string `json:"prev_cursor,omitempty"`
}
// paginate trims rows read for p to one page in the list's order and
// works out the neighbouring pages.
func paginate[T any](p pageReq, rows []T, key func(T) cursor) ([]T, pageInfo) {
var info pageInfo
more := len(rows) > p.limit
if more {
rows = rows[:p.limit]
}
if p.backward() {
slices.Reverse(rows)
}
if len(rows) == 0 {
return rows, info
}
first, last := key(rows[0]).encode(), key(rows[len(rows)-1]).encode()
switch {
case p.backward():
info.Next = last
if more {
info.Prev = first
}
default:
if more {
info.Next = last
}
if p.after != nil {
info.Prev = first
}
}
return rows, info
}
// pager builds the console's page links from info, keeping the request's
// other query parameters.
func pager(c *gin.Context, info pageInfo) web.Pager {
link := func(key, cur string) string {
q := c.Request.URL.Query()
q.Del("after")
q.Del("before")
if key != "" {
q.Set(key, cur)
}
if len(q) == 0 {
return c.Request.URL.Path
}
return c.Request.URL.Path + "?" + q.Encode()
}
var pg web.Pager
if info.Next != "" {
pg.Next = link("after", info.Next)
}
if info.Prev != "" {
pg.Prev = link("before", info.Prev)
pg.First = link("", "")
}
return pg
}
// pageSlice pages through items held in memory the way the queries page
// through tables. items must be sorted ascending by key.
func pageSlice[T any](items []T, pg pageReq, key func(T) cursor) ([]T, pageInfo) {
cmp := func(a, b cursor) int {
if c := strings.Compare(a.S, b.S); c != 0 {
return c
}
if c := a.T.Compare(b.T); c != 0 {
return c
}
return strings.Compare(a.ID.String(), b.ID.String())
}
var read []T
if pg.backward() {
for i := len(items) - 1; i >= 0 && len(read) < int(pg.fetch()); i-- {
if cmp(key(items[i]), *pg.before) < 0 {
read = append(read, items[i])
}
}
} else {
for _, it := range items {
if len(read) == int(pg.fetch()) {
break
}
if pg.after == nil || cmp(key(it), *pg.after) > 0 {
read = append(read, it)
}
}
}
return paginate(pg, read, key)
}
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"slices"
"testing"
"github.com/google/uuid"
)
func TestPaginate(t *testing.T) {
// A list of 0..9 shown in order, read the way the queries do: from a
// cursor in reading direction, one row more than the page.
all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
key := func(i int) cursor { return cursor{S: string(rune('a' + i)), ID: uuid.Nil} }
read := func(p pageReq) []int {
var out []int
if p.backward() {
for i := len(all) - 1; i >= 0; i-- {
if key(all[i]).S < p.before.S {
out = append(out, all[i])
}
}
} else {
for _, v := range all {
if p.after == nil || key(v).S > p.after.S {
out = append(out, v)
}
}
}
return out[:min(len(out), int(p.fetch()))]
}
page := func(p pageReq) ([]int, pageInfo) { return paginate(p, read(p), key) }
first, info := page(pageReq{limit: 4})
if !slices.Equal(first, []int{0, 1, 2, 3}) || info.Prev != "" || info.Next == "" {
t.Fatalf("first = %v %+v", first, info)
}
next, _ := decodeCursor(info.Next)
second, info := page(pageReq{limit: 4, after: next})
if !slices.Equal(second, []int{4, 5, 6, 7}) || info.Prev == "" || info.Next == "" {
t.Fatalf("second = %v %+v", second, info)
}
n3, _ := decodeCursor(info.Next)
last, lastInfo := page(pageReq{limit: 4, after: n3})
if !slices.Equal(last, []int{8, 9}) || lastInfo.Next != "" || lastInfo.Prev == "" {
t.Fatalf("last = %v %+v", last, lastInfo)
}
// Back from the last page and from the second to the first.
prev, _ := decodeCursor(lastInfo.Prev)
back, backInfo := page(pageReq{limit: 4, before: prev})
if !slices.Equal(back, []int{4, 5, 6, 7}) || backInfo.Prev == "" || backInfo.Next == "" {
t.Fatalf("back = %v %+v", back, backInfo)
}
p2, _ := decodeCursor(backInfo.Prev)
start, startInfo := page(pageReq{limit: 4, before: p2})
if !slices.Equal(start, []int{0, 1, 2, 3}) || startInfo.Prev != "" || startInfo.Next == "" {
t.Fatalf("start = %v %+v", start, startInfo)
}
if _, ok := decodeCursor("not a cursor!"); ok {
t.Error("garbage cursor accepted")
}
}
func TestPageSlice(t *testing.T) {
items := []string{"a", "b", "c", "d", "e"}
key := func(s string) cursor { return cursor{S: s} }
first, info := pageSlice(items, pageReq{limit: 2}, key)
next, _ := decodeCursor(info.Next)
second, info2 := pageSlice(items, pageReq{limit: 2, after: next}, key)
prev, _ := decodeCursor(info2.Prev)
back, _ := pageSlice(items, pageReq{limit: 2, before: prev}, key)
if !slices.Equal(first, []string{"a", "b"}) || !slices.Equal(second, []string{"c", "d"}) || !slices.Equal(back, first) {
t.Errorf("first %v, second %v, back %v", first, second, back)
}
}
func TestEmailKey(t *testing.T) {
for in, want := range map[string]string{
"Max.Power+uptime@googlemail.com": "maxpower@gmail.com",
"max.power@gmail.com": "maxpower@gmail.com",
"a.b+c@example.com": "a.b@example.com",
"A.B@Example.com": "a.b@example.com",
} {
if got := emailKey(in); got != want {
t.Errorf("emailKey(%q) = %q, want %q", in, got, want)
}
}
if clientKey("2001:db8:1:2:aaaa::1") != clientKey("2001:db8:1:2:bbbb::9") || clientKey("2001:db8:1:3::1") == clientKey("2001:db8:1:2::1") {
t.Error("IPv6 clients are not grouped by /64")
}
if clientKey("203.0.113.7") != "203.0.113.7" {
t.Error("IPv4 clients are grouped")
}
}
+184
View File
@@ -0,0 +1,184 @@
package api_test
import (
"context"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
// pages follows next_cursor through a list and back through prev_cursor,
// returning the IDs in order both ways.
func pages(t *testing.T, b *browser, path, key string) (forward, backward []string) {
t.Helper()
sep := "?"
if strings.Contains(path, "?") {
sep = "&"
}
ids := func(body map[string]any) []string {
var out []string
for _, it := range body[key].([]any) {
out = append(out, it.(map[string]any)["id"].(string))
}
return out
}
var last map[string]any
cursor := ""
for range 20 {
q := path + sep + "limit=2"
if cursor != "" {
q += "&after=" + url.QueryEscape(cursor)
}
st, body := b.do("GET", q, nil)
if st != http.StatusOK {
t.Fatalf("GET %s = %d %v", q, st, body)
}
forward = append(forward, ids(body)...)
last = body
if cursor, _ = body["next_cursor"].(string); cursor == "" {
break
}
}
// Back from the last page to the first.
page := ids(last)
backward = append(page, backward...)
prev, _ := last["prev_cursor"].(string)
for prev != "" {
st, body := b.do("GET", path+sep+"limit=2&before="+url.QueryEscape(prev), nil)
if st != http.StatusOK {
t.Fatalf("before = %d %v", st, body)
}
backward = append(ids(body), backward...)
prev, _ = body["prev_cursor"].(string)
}
return forward, backward
}
func TestPaging(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("pg")+".test", uniq("pg-"))
var monitors []string
for _, name := range []string{"e", "a", "d", "b", "c"} {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": name, "type": "heartbeat", "interval_seconds": 3600})
monitors = append(monitors, m["id"].(string))
}
// Monitors page by name.
fwd, back := pages(t, owner, "/api/v1/org/monitors", "monitors")
if len(fwd) != 5 || !slices.Equal(fwd, back) {
t.Errorf("monitors forward %v, backward %v", fwd, back)
}
_, first := owner.do("GET", "/api/v1/org/monitors?limit=1", nil)
if first["monitors"].([]any)[0].(map[string]any)["name"] != "a" {
t.Errorf("monitors are not by name: %v", first["monitors"])
}
// Incidents with the same start time: none skipped or repeated.
started := time.Now().Add(-time.Hour).Truncate(time.Second)
if err := e.asSystem(t, func(tx pgx.Tx) error {
for _, m := range monitors {
if _, err := tx.Exec(context.Background(), `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at, cause)
SELECT org_id, id, $2::timestamptz, $2::timestamptz + interval '1 minute', '{}' FROM monitors WHERE id = $1`, m, started); err != nil {
return err
}
}
return nil
}); err != nil {
t.Fatal(err)
}
fwd, back = pages(t, owner, "/api/v1/org/incidents", "incidents")
if len(fwd) != 5 || !slices.Equal(fwd, back) {
t.Errorf("incidents forward %v, backward %v", fwd, back)
}
seen := map[string]bool{}
for _, id := range fwd {
if seen[id] {
t.Errorf("incident %s repeated", id)
}
seen[id] = true
}
fwd, _ = pages(t, owner, "/api/v1/org/incidents?monitor_id="+monitors[0], "incidents")
if len(fwd) != 1 {
t.Errorf("incidents of one monitor = %v", fwd)
}
// Invalid requests.
st, body := owner.do("GET", "/api/v1/org/incidents?after=nonsense!", nil)
expect(t, "bad cursor", st, body, http.StatusUnprocessableEntity, "invalid_cursor")
st, body = owner.do("GET", "/api/v1/org/incidents?limit=501", nil)
expect(t, "limit too large", st, body, http.StatusUnprocessableEntity, "invalid_limit")
// The console pages with links.
_, _, html := owner.page("/incidents?limit=2")
if !strings.Contains(html, `rel="next"`) || strings.Contains(html, `rel="prev"`) {
t.Error("the first console page lacks a next link or has a previous one")
}
if _, _, html := owner.page(nextLink(t, html)); !strings.Contains(html, `rel="prev"`) || !strings.Contains(html, "To the start") {
t.Error("a later console page lacks the way back")
}
}
var nextHref = regexp.MustCompile(`href="([^"]+)" rel="next"`)
// nextLink returns the console's link to the next page.
func nextLink(t *testing.T, html string) string {
t.Helper()
m := nextHref.FindStringSubmatch(html)
if m == nil {
t.Fatal("no next link")
}
return strings.ReplaceAll(m[1], "&amp;", "&")
}
// shown counts the monitors a dashboard page links to.
func shown(html string) int {
return strings.Count(html, `href="/monitors/`) - strings.Count(html, `href="/monitors/new"`)
}
func TestDashboardPaging(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("dash")+".test", uniq("dash-"))
_, g := owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "Fleet"})
group := g["id"].(string)
for i := range 55 {
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "node-" + strconv.Itoa(100+i), "type": "heartbeat", "interval_seconds": 3600, "group_id": group,
})
if st != http.StatusCreated {
t.Fatalf("create = %d %v", st, body)
}
}
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "loner", "type": "heartbeat", "interval_seconds": 3600})
_, _, html := owner.page("/")
if n := shown(html); n != 51 {
t.Errorf("dashboard shows %d monitors, want 50 of the group and the ungrouped one", n)
}
if !strings.Contains(html, "Show all 55") || !strings.Contains(html, "/?group="+group) {
t.Error("the group lacks its show-all link")
}
_, _, html = owner.page("/?group=" + group)
if n := shown(html); n != 50 || !strings.Contains(html, `rel="next"`) || !strings.Contains(html, "Fleet") {
t.Errorf("focused group shows %d monitors or lacks paging", n)
}
if _, _, page2 := owner.page(nextLink(t, html)); shown(page2) != 5 || !strings.Contains(page2, "node-154") {
t.Error("the second page of the group is wrong")
}
if _, _, html := owner.page("/?q=node-107"); shown(html) != 1 || !strings.Contains(html, "node-107") {
t.Error("search does not find the one monitor")
}
if _, _, html := owner.page("/?group=none"); !strings.Contains(html, "loner") || strings.Contains(html, "node-100") {
t.Error("the ungrouped view is wrong")
}
}
+158
View File
@@ -0,0 +1,158 @@
package api
import (
"encoding/base64"
"encoding/json"
"net/url"
"slices"
"strconv"
"strings"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
// providerConfig is stored for channels of notify.Providers. Secret
// settings are sealed, bound to the channel type and field, and never
// shown again.
type providerConfig struct {
Settings map[string]string `json:"settings"`
Sealed map[string]string `json:"sealed"`
Locale string `json:"locale"`
}
func secretAAD(typ, field string) []byte { return []byte("channel:" + typ + ":" + field) }
// providerSettings validates the settings of a provider channel. Secret
// fields left empty keep their previous value, so a form can be saved
// without asking for tokens again.
func (s *Server) providerSettings(p notify.Provider, req *channelRequest, previous []byte) ([]byte, string) {
var old providerConfig
if previous != nil {
_ = json.Unmarshal(previous, &old)
}
cfg := providerConfig{Settings: map[string]string{}, Sealed: map[string]string{}, Locale: req.Locale}
for _, f := range p.Fields {
v := strings.TrimSpace(req.Settings[f.Name])
if f.Secret {
if v == "" {
if sealed, ok := old.Sealed[f.Name]; ok {
cfg.Sealed[f.Name] = sealed
continue
}
if f.Required {
return nil, "invalid_channel_settings"
}
continue
}
} else if v == "" {
v = f.Default
}
if v == "" {
if f.Required {
return nil, "invalid_channel_settings"
}
continue
}
if len(v) > 2000 || !s.validSetting(f, v) {
return nil, "invalid_channel_settings"
}
if f.Secret {
cfg.Sealed[f.Name] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), secretAAD(p.Type, f.Name)))
} else {
cfg.Settings[f.Name] = v
}
}
if cfg.Locale == "" || !s.catalog.IsSupported(cfg.Locale) {
cfg.Locale = "en"
}
raw, _ := json.Marshal(cfg)
return raw, ""
}
func (s *Server) validSetting(f notify.Field, v string) bool {
switch f.Kind {
case "url":
u, err := url.Parse(v)
// Plain http only where services may live on private networks.
return err == nil && u.Host != "" && u.User == nil && (u.Scheme == "https" || (u.Scheme == "http" && !s.cloud()))
case "number":
_, err := strconv.Atoi(v)
return err == nil
case "select":
return slices.Contains(f.Options, v)
}
return !strings.ContainsAny(v, "\r\n")
}
// providerView shows the settings of a provider channel; secrets appear
// only as the names of fields that are set.
func providerView(raw []byte) (map[string]string, []string, string) {
var cfg providerConfig
_ = json.Unmarshal(raw, &cfg)
set := make([]string, 0, len(cfg.Sealed))
for k := range cfg.Sealed {
set = append(set, k)
}
slices.Sort(set)
if cfg.Settings == nil {
cfg.Settings = map[string]string{}
}
return cfg.Settings, set, cfg.Locale
}
// openProviderSettings returns all settings with secrets unsealed.
func (s *Server) openProviderSettings(typ string, raw []byte) (map[string]string, string, error) {
var cfg providerConfig
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, "", err
}
out := map[string]string{}
for k, v := range cfg.Settings {
out[k] = v
}
for k, v := range cfg.Sealed {
sealed, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return nil, "", err
}
plain, err := s.keys.Open(sealed, secretAAD(typ, k))
if err != nil {
return nil, "", err
}
out[k] = string(plain)
}
return out, cfg.Locale, nil
}
// messageFor renders an event for chat and push services in locale.
func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
l := s.catalog.Match(locale)
data := map[string]any{"Monitor": ev.Monitor.Name}
m := notify.Message{Event: ev.Kind, Key: ev.IncidentID, Monitor: ev.Monitor.Name, MonitorID: ev.Monitor.ID, Target: ev.Monitor.Target}
var lines []string
switch ev.Kind {
case notify.Opened:
m.Title = l.T("notify.title_opened", data)
for region, msg := range ev.Cause {
lines = append(lines, region+": "+msg)
}
slices.Sort(lines)
case notify.Resolved:
m.Title = l.T("notify.title_resolved", data)
if ev.ResolvedAt != nil {
lines = append(lines, l.T("notify.duration", map[string]any{"Duration": ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()}))
}
default:
m.Title = l.T("notify.title_test", data)
lines = append(lines, l.T("notify.test_body", nil))
}
if ev.Monitor.Target != "" && ev.Monitor.Type != "heartbeat" {
lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...)
}
m.Body = strings.Join(lines, "\n")
if ev.Monitor.ID != [16]byte{} {
m.URL = strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
}
return m
}
+115
View File
@@ -0,0 +1,115 @@
package api_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
func TestProvidersAreTranslated(t *testing.T) {
catalog, err := i18n.Load()
if err != nil {
t.Fatal(err)
}
for _, lang := range catalog.Supported() {
ctx := i18n.NewContext(context.Background(), catalog.Match(lang))
for _, p := range notify.Providers {
ids := []string{"channels.type_" + p.Type}
for _, f := range p.Fields {
ids = append(ids, "channels.field_"+f.Name)
}
for _, id := range ids {
if i18n.T(ctx, id) == id {
t.Errorf("%s: %s is not translated", lang, id)
}
}
}
}
}
func TestProviderChannel(t *testing.T) {
e := newEnv(t)
var mu sync.Mutex
var paths, bodies []string
telegram := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
mu.Unlock()
}))
defer telegram.Close()
owner := e.browser(t)
owner.signup("o@"+uniq("pr")+".test", uniq("pr-"))
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops chat", "type": "telegram", "settings": map[string]string{"chat_id": "-100"}})
expect(t, "missing bot token", st, body, http.StatusUnprocessableEntity, "invalid_channel_settings")
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "carrierpigeon"})
expect(t, "unknown type", st, body, http.StatusUnprocessableEntity, "invalid_input")
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{
"name": "Ops chat", "type": "telegram", "locale": "de",
"settings": map[string]string{"bot_token": "4711:very-secret", "chat_id": "-100123", "api_url": telegram.URL},
})
if st != http.StatusCreated {
t.Fatalf("create telegram channel = %d %v", st, body)
}
ch := body["channel"].(map[string]any)
id := ch["id"].(string)
if raw := mustJSON(body); strings.Contains(raw, "very-secret") || ch["settings"].(map[string]any)["chat_id"] != "-100123" ||
mustJSON(ch["secrets_set"]) != `["bot_token"]` {
t.Errorf("create answer = %s", raw)
}
var stored string
_ = e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT config::text FROM notification_channels WHERE id = $1`, id).Scan(&stored)
})
if strings.Contains(stored, "very-secret") {
t.Error("the bot token is stored in plain text")
}
if _, list := owner.do("GET", "/api/v1/org/channels", nil); strings.Contains(mustJSON(list), "very-secret") {
t.Error("the channel list shows the bot token")
}
if st, body := owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil); st != http.StatusNoContent {
t.Fatalf("test send = %d %v", st, body)
}
// Saving without the token keeps it.
st, body = owner.do("PUT", "/api/v1/org/channels/"+id, map[string]any{
"name": "Ops chat", "type": "telegram", "locale": "de",
"settings": map[string]string{"chat_id": "-100999", "api_url": telegram.URL},
})
if st != http.StatusOK {
t.Fatalf("update = %d %v", st, body)
}
owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil)
mu.Lock()
defer mu.Unlock()
if len(paths) != 2 || paths[0] != "/bot4711:very-secret/sendMessage" || paths[1] != paths[0] {
t.Errorf("telegram requests = %v", paths)
}
if !strings.Contains(bodies[0], "Test von UptimeSebi") || !strings.Contains(bodies[1], `"chat_id":"-100999"`) {
t.Errorf("telegram bodies = %v", bodies)
}
_, _, page := owner.page("/settings/channels")
if !strings.Contains(page, `name="settings.bot_token"`) || !strings.Contains(page, "-100999") {
t.Error("the channels page lacks the service form or the channel")
}
// Services are grouped, and every one has its settings form.
if !strings.Contains(page, `<optgroup label="SMS and calls">`) {
t.Error("the services are not grouped")
}
for _, p := range notify.Providers {
if !strings.Contains(page, `<fieldset data-type="`+p.Type+`"`) {
t.Errorf("the channels page lacks the form of %s", p.Type)
}
}
}
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"encoding/json"
"slices"
"strconv"
"strings"
"time"
)
// quietHourRequest is one recurring time window during which an alert group
// suppresses notifications.
type quietHourRequest struct {
// Weekdays are days of the week (0 = Sunday .. 6 = Saturday); empty
// means every day.
Weekdays flexInts `json:"weekdays" binding:"max=7"`
// Start and End are wall-clock times "HH:MM" in TimeZone. End may be
// "24:00"; Start > End wraps overnight into the next day, and
// "00:00" to "00:00" (or "24:00") covers the entire day.
Start string `json:"start" binding:"required,max=5"`
End string `json:"end" binding:"required,max=5"`
TimeZone string `json:"time_zone" binding:"required,max=64"`
}
// quietHourView is one normalized quiet window returned by the API and stored
// on an alert group.
type quietHourView struct {
Weekdays []int `json:"weekdays"`
Start string `json:"start"`
End string `json:"end"`
TimeZone string `json:"time_zone"`
}
// validateQuietHours validates and normalizes quiet windows, returning an
// error code on failure.
func validateQuietHours(in []quietHourRequest) ([]quietHourView, string) {
out := make([]quietHourView, 0, len(in))
for _, w := range in {
tz := strings.TrimSpace(w.TimeZone)
if tz == "" || tz == "Local" {
return nil, "invalid_time_zone"
}
if _, err := time.LoadLocation(tz); err != nil {
return nil, "invalid_time_zone"
}
start := strings.TrimSpace(w.Start)
end := strings.TrimSpace(w.End)
startMin, startOK := parseClockMinutes(start)
endMin, endOK := parseEndMinutes(end)
if !startOK || !endOK {
return nil, "invalid_quiet_hours"
}
// Identical non-zero times would be an empty window; 00:00-00:00
// (like 00:00-24:00) means the whole day.
if startMin == endMin && startMin != 0 {
return nil, "invalid_quiet_hours"
}
days := make([]int, 0, len(w.Weekdays))
for _, d := range w.Weekdays {
if d < 0 || d > 6 {
return nil, "invalid_quiet_hours"
}
days = append(days, d)
}
slices.Sort(days)
days = slices.Compact(days)
out = append(out, quietHourView{
Weekdays: days,
Start: start,
End: end,
TimeZone: tz,
})
}
return out, ""
}
// parseClockMinutes parses "HH:MM" (00:00..23:59) into minutes since midnight.
func parseClockMinutes(s string) (int, bool) {
if len(s) != 5 || s[2] != ':' {
return 0, false
}
hour, err := strconv.Atoi(s[:2])
if err != nil || hour < 0 || hour > 23 {
return 0, false
}
minute, err := strconv.Atoi(s[3:])
if err != nil || minute < 0 || minute > 59 {
return 0, false
}
return hour*60 + minute, true
}
// parseEndMinutes parses a window end time, accepting "24:00" in addition to
// 00:00..23:59.
func parseEndMinutes(s string) (int, bool) {
if s == "24:00" {
return 24 * 60, true
}
return parseClockMinutes(s)
}
// decodeQuietHours decodes stored JSONB quiet windows, always returning a
// non-nil slice so JSON responses serialize as [] rather than null.
func decodeQuietHours(raw []byte) []quietHourView {
if len(raw) == 0 {
return []quietHourView{}
}
var out []quietHourView
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
return []quietHourView{}
}
for i := range out {
if out[i].Weekdays == nil {
out[i].Weekdays = []int{}
}
}
return out
}
// contains reports whether t falls inside w in w's time zone.
func (w quietHourView) contains(t time.Time) bool {
startMin, startOK := parseClockMinutes(w.Start)
endMin, endOK := parseEndMinutes(w.End)
if !startOK || !endOK {
return false
}
local := t.In(loadLocation(w.TimeZone))
nowMin := local.Hour()*60 + local.Minute()
today := int(local.Weekday())
hasDay := func(d int) bool {
return len(w.Weekdays) == 0 || slices.Contains(w.Weekdays, d)
}
if startMin == 0 && (endMin == 0 || endMin == 24*60) {
return hasDay(today)
}
if startMin < endMin {
return hasDay(today) && nowMin >= startMin && nowMin < endMin
}
// Overnight window (Start > End), e.g. 22:00-07:00 or 18:00-00:00:
// covers [Start, 24:00) on matching days and [00:00, End) on the next day.
yesterday := (today + 6) % 7
return (hasDay(today) && nowMin >= startMin) || (hasDay(yesterday) && nowMin < endMin)
}
// isQuietAt reports whether any window in windows suppresses notifications at t.
func isQuietAt(windows []quietHourView, t time.Time) bool {
for _, w := range windows {
if w.contains(t) {
return true
}
}
return false
}
func isQuietRawAt(raw []byte, t time.Time) bool {
return isQuietAt(decodeQuietHours(raw), t)
}
+152
View File
@@ -0,0 +1,152 @@
package api
import (
"slices"
"testing"
"time"
)
func TestValidateQuietHours(t *testing.T) {
in := []quietHourRequest{
{Weekdays: flexInts{5, 1, 5, 3}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"},
{Weekdays: nil, Start: "00:00", End: "24:00", TimeZone: "UTC"},
{Weekdays: flexInts{0, 6}, Start: "00:00", End: "00:00", TimeZone: "UTC"},
}
got, code := validateQuietHours(in)
if code != "" {
t.Fatalf("validateQuietHours(%+v) error code = %q, want %q", in, code, "")
}
if len(got) != 3 {
t.Fatalf("len(validateQuietHours(...)) = %d, want 3", len(got))
}
if want := []int{1, 3, 5}; !slices.Equal(got[0].Weekdays, want) {
t.Errorf("got[0].Weekdays = %v, want %v", got[0].Weekdays, want)
}
if got[1].Weekdays == nil || len(got[1].Weekdays) != 0 {
t.Errorf("got[1].Weekdays = %#v, want non-nil empty []int{}", got[1].Weekdays)
}
invalid := []struct {
name string
req quietHourRequest
want string
}{
{
name: "empty time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: ""},
want: "invalid_time_zone",
},
{
name: "local time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Local"},
want: "invalid_time_zone",
},
{
name: "unknown time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Mars/Olympus"},
want: "invalid_time_zone",
},
{
name: "invalid start hour",
req: quietHourRequest{Start: "24:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "invalid end minute",
req: quietHourRequest{Start: "22:00", End: "24:01", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "short clock format",
req: quietHourRequest{Start: "9:00", End: "17:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "equal non-zero start and end",
req: quietHourRequest{Start: "12:00", End: "12:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "negative weekday",
req: quietHourRequest{Weekdays: flexInts{-1}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "weekday out of range",
req: quietHourRequest{Weekdays: flexInts{7}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
}
for _, tc := range invalid {
t.Run(tc.name, func(t *testing.T) {
_, got := validateQuietHours([]quietHourRequest{tc.req})
if got != tc.want {
t.Errorf("validateQuietHours(%+v) error code = %q, want %q", tc.req, got, tc.want)
}
})
}
}
func TestQuietHoursContains(t *testing.T) {
berlin, err := time.LoadLocation("Europe/Berlin")
if err != nil {
t.Fatalf("time.LoadLocation(%q) error = %v", "Europe/Berlin", err)
}
at := func(y int, m time.Month, d, hh, mm int, loc *time.Location) time.Time {
return time.Date(y, m, d, hh, mm, 0, 0, loc)
}
// 2026-11-23 is Monday, 2026-11-27 is Friday, 2026-11-28 is Saturday,
// and 2026-11-29 is Sunday.
daytime := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "09:00", End: "17:00", TimeZone: "Europe/Berlin"}
overnight := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"}
weekendZero := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "00:00", TimeZone: "Europe/Berlin"}
weekend24 := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "24:00", TimeZone: "Europe/Berlin"}
eveningEndZero := quietHourView{Weekdays: []int{5}, Start: "18:00", End: "00:00", TimeZone: "UTC"}
dailyNight := quietHourView{Weekdays: []int{}, Start: "23:00", End: "06:00", TimeZone: "Europe/Berlin"}
cases := []struct {
name string
window quietHourView
ts time.Time
want bool
}{
{name: "daytime before start", window: daytime, ts: at(2026, 11, 23, 8, 59, berlin), want: false},
{name: "daytime at start", window: daytime, ts: at(2026, 11, 23, 9, 0, berlin), want: true},
{name: "daytime inside", window: daytime, ts: at(2026, 11, 23, 16, 59, berlin), want: true},
{name: "daytime at end", window: daytime, ts: at(2026, 11, 23, 17, 0, berlin), want: false},
{name: "daytime wrong day", window: daytime, ts: at(2026, 11, 28, 12, 0, berlin), want: false},
{name: "overnight mon before", window: overnight, ts: at(2026, 11, 23, 21, 59, berlin), want: false},
{name: "overnight mon start", window: overnight, ts: at(2026, 11, 23, 22, 0, berlin), want: true},
{name: "overnight mon early from sun", window: overnight, ts: at(2026, 11, 23, 3, 0, berlin), want: false},
{name: "overnight tue early from mon", window: overnight, ts: at(2026, 11, 24, 6, 59, berlin), want: true},
{name: "overnight tue at end", window: overnight, ts: at(2026, 11, 24, 7, 0, berlin), want: false},
{name: "overnight sat early from fri", window: overnight, ts: at(2026, 11, 28, 3, 0, berlin), want: true},
{name: "overnight sat late", window: overnight, ts: at(2026, 11, 28, 23, 0, berlin), want: false},
{name: "overnight sun early", window: overnight, ts: at(2026, 11, 29, 3, 0, berlin), want: false},
{name: "weekend 00-00 sat", window: weekendZero, ts: at(2026, 11, 28, 0, 0, berlin), want: true},
{name: "weekend 00-00 sun late", window: weekendZero, ts: at(2026, 11, 29, 23, 59, berlin), want: true},
{name: "weekend 00-00 mon", window: weekendZero, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
{name: "weekend 00-24 sat", window: weekend24, ts: at(2026, 11, 28, 15, 0, berlin), want: true},
{name: "weekend 00-24 mon", window: weekend24, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
{name: "evening 18-00 fri inside", window: eveningEndZero, ts: at(2026, 11, 27, 23, 59, time.UTC), want: true},
{name: "evening 18-00 sat midnight", window: eveningEndZero, ts: at(2026, 11, 28, 0, 0, time.UTC), want: false},
// Winter (CET = UTC+1) vs summer (CEST = UTC+2) in Europe/Berlin.
{name: "daily winter 22:30 UTC is 23:30 CET", window: dailyNight, ts: at(2026, 1, 15, 22, 30, time.UTC), want: true},
{name: "daily winter 21:30 UTC is 22:30 CET", window: dailyNight, ts: at(2026, 1, 15, 21, 30, time.UTC), want: false},
{name: "daily summer 21:30 UTC is 23:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 21, 30, time.UTC), want: true},
{name: "daily summer 03:30 UTC is 05:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 3, 30, time.UTC), want: true},
{name: "daily summer 04:00 UTC is 06:00 CEST", window: dailyNight, ts: at(2026, 7, 15, 4, 0, time.UTC), want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := tc.window.contains(tc.ts); got != tc.want {
t.Errorf("contains(%s) = %t, want %t", tc.ts.Format(time.RFC3339), got, tc.want)
}
})
}
}
+13 -1
View File
@@ -151,6 +151,9 @@ type agentView struct {
Prefix string `json:"prefix"`
LastSeenAt *time.Time `json:"last_seen_at"`
Release string `json:"release,omitempty"`
// AllowPrivate tells whether an organization's checker may check
// private addresses; platform checkers follow the platform setting.
AllowPrivate *bool `json:"allow_private,omitempty"`
}
func (s *Server) listAgents(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
@@ -171,6 +174,9 @@ func (s *Server) listAgents(c *gin.Context, scope tenant.Scope, org *uuid.UUID)
ID: a.ID, Kind: a.Kind, Name: a.Name, RegionID: a.RegionID, RegionKey: deref(a.RegionKey),
RegionName: deref(a.RegionName), Prefix: a.Prefix, LastSeenAt: a.LastSeenAt, Release: deref(a.Release),
}
if a.Kind == "checker" && a.OrgID != nil {
out[i].AllowPrivate = &a.AllowPrivate
}
}
c.JSON(http.StatusOK, gin.H{"agents": out})
}
@@ -179,6 +185,9 @@ type agentRequest struct {
Kind string `json:"kind" binding:"required,oneof=checker statuspage"`
Name string `json:"name" binding:"required,max=100"`
RegionID *uuid.UUID `json:"region_id"`
// AllowPrivate lets an organization's checker check private
// addresses; it defaults to true.
AllowPrivate *bool `json:"allow_private"`
}
// createAgent creates an agent and returns its token, which is shown once.
@@ -193,6 +202,9 @@ func (s *Server) createAgent(c *gin.Context, scope tenant.Scope, org *uuid.UUID)
return
}
tok, params := NewAgentToken(org, req.Kind, req.Name, req.RegionID)
if req.AllowPrivate != nil && org != nil {
params.AllowPrivate = *req.AllowPrivate
}
ctx := c.Request.Context()
var row store.Agent
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
@@ -218,7 +230,7 @@ func NewAgentToken(org *uuid.UUID, kind, name string, region *uuid.UUID) (string
tok := AgentTokenPrefix + auth.RandomToken()
return tok, store.CreateAgentParams{
OrgID: org, Kind: kind, Name: name, RegionID: region,
TokenHash: HashToken(tok), Prefix: tok[:len(AgentTokenPrefix)+6],
TokenHash: HashToken(tok), Prefix: tok[:len(AgentTokenPrefix)+6], AllowPrivate: true,
}
}
+62 -14
View File
@@ -44,6 +44,13 @@ type Server struct {
eval *evaluate.Evaluator
smtp *notify.SMTP
legal *versioned[[]agentapi.LegalDoc]
// checkTypes caches the check types switched off platform-wide.
checkTypes *versioned[map[string]bool]
// checkerNet caches whether platform checkers may reach private
// addresses.
checkerNet *versioned[bool]
// limits caches the platform's default limits.
limits *versioned[Limits]
}
// Deps are the external resources a Server needs.
@@ -61,20 +68,23 @@ func New(cfg config.API, d Deps) *Server {
allowPrivate := cfg.SSOAllowPrivate()
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
return &Server{
eval: evaluate.New(d.Redis),
smtp: mail,
cfg: cfg,
log: d.Log,
db: d.DB,
rdb: d.Redis,
keys: d.Keys,
catalog: d.Catalog,
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
limiter: auth.NewLimiter(d.Redis),
totp: auth.NewTOTPVerifier(d.Redis),
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
eval: evaluate.New(d.Redis),
smtp: mail,
cfg: cfg,
log: d.Log,
db: d.DB,
rdb: d.Redis,
keys: d.Keys,
catalog: d.Catalog,
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
limiter: auth.NewLimiter(d.Redis),
totp: auth.NewTOTPVerifier(d.Redis),
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"),
}
}
@@ -85,6 +95,7 @@ func (s *Server) Mount(r gin.IRouter) {
// the session and CSRF middleware.
s.mountAgentAPI(r)
s.mountHeartbeats(r)
s.mountAlertmanager(r)
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit())
@@ -97,6 +108,9 @@ func (s *Server) Mount(r gin.IRouter) {
a := v1.Group("/auth")
a.POST("/signup", s.signup)
a.POST("/verify", s.verifyEmail)
a.POST("/verify/resend", s.resendVerification)
v1.POST("/orgs", auth.Require(), s.createOrg)
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
@@ -129,8 +143,16 @@ func (s *Server) Mount(r gin.IRouter) {
org.PUT("/monitors/:id", s.updateMonitor)
org.DELETE("/monitors/:id", s.deleteMonitor)
org.GET("/monitors/:id/evidence", s.listEvidence)
org.GET("/monitors/:id/results", s.listResults)
org.GET("/checkers/:id", s.getChecker)
org.GET("/monitors/:id/evidence/:evidence", s.getEvidence)
org.GET("/alertmanager/receivers", can(authz.OrgManage), s.listReceivers)
org.POST("/alertmanager/receivers", sessionOnly(), can(authz.OrgManage), s.createReceiver)
org.DELETE("/alertmanager/receivers/:id", sessionOnly(), can(authz.OrgManage), s.deleteReceiver)
org.GET("/alertmanager/alerts", can(authz.MonitorsRead), s.listFiringAlerts)
org.GET("/check-types", s.orgCheckTypes)
org.GET("/limits", s.getOrgLimits)
org.PUT("/check-types", sessionOnly(), can(authz.OrgManage), s.orgSetCheckTypes)
org.GET("/maintenance", s.listMaintenance)
org.POST("/maintenance", s.createMaintenance)
org.PUT("/maintenance/:id", s.updateMaintenance)
@@ -145,10 +167,27 @@ func (s *Server) Mount(r gin.IRouter) {
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
admin := v1.Group("/admin", s.requireAdmin())
admin.GET("/audit", s.listPlatformAudit)
admin.GET("/check-types", s.adminListCheckTypes)
admin.PUT("/check-types", s.adminSetCheckTypes)
admin.GET("/checker-network", s.adminGetCheckerNetwork)
admin.GET("/limits", s.adminGetLimits)
admin.PUT("/limits", s.adminSetLimits)
admin.GET("/orgs", s.adminListOrgs)
admin.PUT("/orgs/:id/limits", s.adminSetOrgLimits)
admin.PUT("/users/:id/limits", s.adminSetUserLimits)
admin.GET("/status-pages", s.adminListStatusPages)
admin.PUT("/status-pages/:id/suspension", s.adminSuspendStatusPage)
admin.DELETE("/status-pages/:id", s.adminDeleteStatusPage)
admin.PUT("/orgs/:id/suspension", s.adminSuspendOrg)
admin.DELETE("/orgs/:id", s.adminDeleteOrg)
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
admin.DELETE("/users/:id", s.adminDeleteUser)
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
admin.GET("/legal", s.adminListLegal)
admin.PUT("/legal/:kind", s.adminSaveLegal)
admin.GET("/regions", s.adminListRegions)
@@ -163,6 +202,11 @@ func (s *Server) Mount(r gin.IRouter) {
page := org.Group("/statuspages/:id")
page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
page.GET("/groups", canPage(authz.StatusPagesRead), s.listStatusPageGroups)
page.POST("/groups", canPage(authz.StatusPagesWrite), s.createStatusPageGroup)
page.PUT("/groups/:group_id", canPage(authz.StatusPagesWrite), s.updateStatusPageGroup)
page.DELETE("/groups/:group_id", canPage(authz.StatusPagesWrite), s.deleteStatusPageGroup)
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
@@ -171,6 +215,10 @@ func (s *Server) Mount(r gin.IRouter) {
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
org.POST("/alert-groups", can(authz.NotificationsWrite), s.saveAlertGroup)
org.PUT("/alert-groups/:id", can(authz.NotificationsWrite), s.saveAlertGroup)
org.DELETE("/alert-groups/:id", can(authz.NotificationsWrite), s.deleteAlertGroup)
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
+270
View File
@@ -0,0 +1,270 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// New accounts confirm their email address before signing in, through a
// link mailed to them. One mailbox holds one account, aliases included,
// and a client address may create only a few accounts a day.
const (
verifyTTL = 24 * time.Hour
// unverifiedKeep is how long an account waits for confirmation.
unverifiedKeep = 7 * 24 * time.Hour
)
// emailKey identifies the mailbox behind an address: +suffixes are dropped
// everywhere, and Gmail ignores dots and treats googlemail.com as gmail.com.
// The migration adding users.email_key computes the same.
func emailKey(email string) string {
local, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@")
if !ok {
return strings.ToLower(email)
}
local, _, _ = strings.Cut(local, "+")
if domain == "gmail.com" || domain == "googlemail.com" {
local, domain = strings.ReplaceAll(local, ".", ""), "gmail.com"
}
return local + "@" + domain
}
// clientKey groups client addresses for sign-up limits: IPv6 clients
// usually hold a whole /64.
func clientKey(ip string) string {
a := net.ParseIP(ip)
if a == nil || a.To4() != nil {
return ip
}
return a.Mask(net.CIDRMask(64, 128)).String() + "/64"
}
// verificationRequired reports whether new accounts confirm their email.
func (s *Server) verificationRequired() bool {
switch s.cfg.SignupVerify {
case "required":
return true
case "off":
return false
}
return s.cloud() || s.smtp != nil
}
// signupsLeft reports whether the client may create another account.
func (s *Server) signupsLeft(c *gin.Context) (bool, error) {
if s.cfg.SignupsPerIP == 0 {
return true, nil
}
n, err := s.rdb.Get(c.Request.Context(), "signups:"+clientKey(c.ClientIP())).Int()
if errors.Is(err, redis.Nil) {
return true, nil
}
return n < s.cfg.SignupsPerIP, err
}
// countSignup counts a created account against the client's daily limit.
func (s *Server) countSignup(c *gin.Context) {
if s.cfg.SignupsPerIP == 0 {
return
}
ctx := c.Request.Context()
key := "signups:" + clientKey(c.ClientIP())
pipe := s.rdb.TxPipeline()
pipe.Incr(ctx, key)
pipe.ExpireNX(ctx, key, 24*time.Hour)
if _, err := pipe.Exec(ctx); err != nil {
s.log.WarnContext(ctx, "counting sign-up failed", "error", err)
}
}
func verifyKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "verify:" + hex.EncodeToString(sum[:])
}
// sendVerification mails u a link that confirms their address.
func (s *Server) sendVerification(ctx context.Context, u store.User) error {
if s.smtp == nil {
return errors.New("api: no mail server to send verification")
}
token := auth.RandomToken()
if err := s.rdb.Set(ctx, verifyKey(token), u.ID.String(), verifyTTL).Err(); err != nil {
return err
}
l := s.catalog.Match(deref(u.Locale))
link := strings.TrimSuffix(s.cfg.PublicURL, "/") + "/verify?token=" + url.QueryEscape(token)
data := map[string]any{"Link": link, "Hours": int(verifyTTL.Hours())}
return s.smtp.Send(ctx, notify.Mail{
To: []string{u.Email}, Subject: l.T("email.verify.subject", data), Body: l.T("email.verify.body", data),
})
}
type verifyRequest struct {
Token string `json:"token" binding:"required,max=200"`
}
// verifyEmail confirms the address the token was mailed to and signs the
// account in: whoever holds the link controls the mailbox.
func (s *Server) verifyEmail(c *gin.Context) {
var req verifyRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
if !s.limit(c, "verify:ip:"+c.ClientIP(), 30, 15*time.Minute) {
return
}
raw, err := s.rdb.GetDel(ctx, verifyKey(req.Token)).Result()
id, perr := uuid.Parse(raw)
if errors.Is(err, redis.Nil) || perr != nil {
fail(c, http.StatusGone, "verification_expired")
return
}
if err != nil {
internalError(c, err)
return
}
var u store.User
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
u, err = q.MarkEmailVerified(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusGone, "verification_expired")
return
}
if err != nil {
internalError(c, err)
return
}
auditActor(c, u.ID)
if u.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
s.finishLogin(c, u.ID, auth.MethodPassword)
}
type resendRequest struct {
Email string `json:"email" binding:"required,email,max=320"`
}
// resendVerification mails a new link to an unconfirmed account. It
// answers the same whether or not such an account exists.
func (s *Server) resendVerification(c *gin.Context) {
var req resendRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
email := normalizeEmail(req.Email)
if !s.limit(c, "resend:ip:"+c.ClientIP(), 10, time.Hour) || !s.limit(c, "resend:email:"+email, 3, time.Hour) {
return
}
var u store.User
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
u, err = q.GetUserByEmail(ctx, email)
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
case err != nil:
internalError(c, err)
return
case u.EmailVerifiedAt == nil && u.DisabledAt == nil:
if err := s.sendVerification(ctx, u); err != nil {
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
}
}
c.Status(http.StatusNoContent)
}
type createOrgRequest struct {
Name string `json:"name" binding:"required,max=200"`
Slug string `json:"slug" binding:"required,max=63"`
}
// createOrg creates an organization owned by the signed-in account and
// makes it the active one.
func (s *Server) createOrg(c *gin.Context) {
var req createOrgRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
ctx := c.Request.Context()
u, err := s.loadUser(ctx, sess.UserID)
if err != nil {
internalError(c, err)
return
}
max := s.platformLimits(ctx).OrgsPerAccount
if u.LimitOrgs != nil {
max = int(*u.LimitOrgs)
}
orgID := uuid.New()
err = s.db.Tx(ctx, tenant.Org(orgID, sess.UserID), func(q *store.Queries) error {
if max > 0 {
// Serialize the account's creations to count them reliably.
if err := q.LockOrgUsage(ctx, u.ID); err != nil {
return err
}
n, err := q.CountOwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
if n >= int64(max) {
return limitError{"org_limit", max}
}
}
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(strings.TrimSpace(req.Slug)), Name: strings.TrimSpace(req.Name)}); err != nil {
return err
}
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: u.ID, IsOwner: true})
})
switch {
case failLimit(c, err):
return
case isUniqueViolation(err, "orgs_slug_key"):
fail(c, http.StatusConflict, "slug_taken")
return
case isCheckViolation(err):
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
return
case err != nil:
internalError(c, err)
return
}
auditOrg(c, orgID)
if err := s.sessions.SwitchOrg(ctx, sess, orgID); err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"id": orgID, "slug": strings.ToLower(strings.TrimSpace(req.Slug)), "redirect": "/"})
}
// signupClosedWithoutMail tells whether sign-up must wait for a mail
// server: accounts need confirming but no link could be sent.
func (s *Server) signupClosedWithoutMail() bool {
return s.verificationRequired() && s.smtp == nil
}
+138
View File
@@ -0,0 +1,138 @@
package api_test
import (
"context"
"net/http"
"regexp"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
var verifyLink = regexp.MustCompile(`/verify\?token=([A-Za-z0-9_\-]+)`)
func TestVerifiedSignup(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify, c.SignupsPerIP = mail.URL(), "auto", 2
})
// mailFor waits for the n-th mail and returns its confirmation token.
tokenOf := func(n int, to string) string {
t.Helper()
waitFor(t, 5*time.Second, "the confirmation mail", func() bool { return len(mail.Messages()) >= n })
msg := mail.Messages()[n-1]
if !strings.Contains(strings.Join(msg.To, ","), to) {
t.Fatalf("mail %d went to %v, want %s", n, msg.To, to)
}
m := verifyLink.FindStringSubmatch(msg.Data)
if m == nil {
t.Fatalf("mail lacks the link: %s", msg.Data)
}
return m[1]
}
box := uniq("max.power")
email := strings.ToUpper(box[:1]) + box[1:] + "+uptime@googlemail.com"
lower := strings.ToLower(email)
// Signing up mails a link instead of signing in.
b := e.browser(t)
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{"email": email, "password": testPassword, "display_name": "Max"})
if st != http.StatusOK || body["status"] != "verification_sent" {
t.Fatalf("signup = %d %v", st, body)
}
if st, _ := b.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("signed in before confirming: %d", st)
}
token := tokenOf(1, lower)
// Unconfirmed accounts cannot sign in; only the right password says why.
st, body = e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": testPassword})
expect(t, "sign-in before confirming", st, body, http.StatusForbidden, "email_unverified")
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "wrong password"}); st != http.StatusUnauthorized {
t.Error("a wrong password reveals the missing confirmation")
}
// The same mailbox under another address is refused.
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": strings.ReplaceAll(box, ".", "") + "@gmail.com", "password": testPassword})
expect(t, "alias of an existing account", st, body, http.StatusConflict, "email_taken")
// Resending answers alike for unknown addresses and mails only real ones.
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": "nobody@" + uniq("x") + ".test"}); st != http.StatusNoContent {
t.Errorf("resend for unknown = %d", st)
}
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": email}); st != http.StatusNoContent {
t.Errorf("resend = %d", st)
}
tokenOf(2, lower)
if n := len(mail.Messages()); n != 2 {
t.Errorf("%d mails, want 2", n)
}
// The link page asks before confirming; confirming signs in once.
if _, _, html := b.page("/verify?token=" + token); !strings.Contains(html, `name="token"`) {
t.Error("the link page lacks its form")
}
if st, body := b.do("POST", "/api/v1/auth/verify", map[string]any{"token": token}); st != http.StatusOK {
t.Fatalf("verify = %d %v", st, body)
}
st, body = e.browser(t).do("POST", "/api/v1/auth/verify", map[string]any{"token": token})
expect(t, "token used twice", st, body, http.StatusGone, "verification_expired")
// Without an organization, the console asks for one.
if got := b.visit("/"); got.Path != "/orgs/new" {
t.Errorf("dashboard leads to %s, want /orgs/new", got.Path)
}
slug := uniq("max-")
if st, body := b.do("POST", "/api/v1/orgs", map[string]any{"name": "Max Corp", "slug": slug}); st != http.StatusCreated {
t.Fatalf("create org = %d %v", st, body)
}
if got := b.visit("/"); got.Path != "/" {
t.Errorf("dashboard leads to %s after creating an organization", got.Path)
}
_, me := b.do("GET", "/api/v1/me", nil)
if !strings.Contains(mustJSON(me), slug) {
t.Errorf("me lacks the new organization: %v", me)
}
// The account limit on organizations.
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `UPDATE users SET limit_orgs = 1 WHERE email = $1`, lower)
return err
})
st, body = b.do("POST", "/api/v1/orgs", map[string]any{"name": "Second", "slug": uniq("max2-")})
expect(t, "second organization", st, body, http.StatusUnprocessableEntity, "org_limit")
// Two accounts per client address and day; refused sign-ups do not count.
if st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "two@" + uniq("x") + ".test", "password": testPassword}); st != http.StatusOK {
t.Fatalf("second account = %d %v", st, body)
}
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "three@" + uniq("x") + ".test", "password": testPassword})
expect(t, "third account", st, body, http.StatusTooManyRequests, "signup_limit")
// Unconfirmed accounts go after a week.
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(context.Background(), `UPDATE users SET created_at = now() - interval '8 days' WHERE email_verified_at IS NULL AND email LIKE 'two@%'`)
return err
})
if err := e.api.Housekeep(context.Background(), time.Now()); err != nil {
t.Fatal(err)
}
var left int
_ = e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE email LIKE 'two@%' AND created_at < now() - interval '7 days'`).Scan(&left)
})
if left != 0 {
t.Error("an unconfirmed account outlived its week")
}
}
func TestSignupNeedsMail(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.SignupVerify = "required" })
st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "a@" + uniq("x") + ".test", "password": testPassword})
expect(t, "sign-up without a mail server", st, body, http.StatusForbidden, "signup_closed")
}
+8 -1
View File
@@ -255,7 +255,7 @@ func (s *Server) ssoCallback(c *gin.Context) {
return
}
if user.DisabledAt != nil {
s.ssoAbort(c, uuid.Nil, "invalid_credentials")
s.ssoAbort(c, uuid.Nil, "account_suspended")
return
}
if old := auth.Current(c); old != nil {
@@ -319,10 +319,17 @@ func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl s
} else if !errors.Is(err, pgx.ErrNoRows) {
return err
}
// Another address of the same mailbox has an account.
if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken {
code = "sso_link_required"
return err
}
// The identity provider confirmed the address.
u, err := q.CreateUser(ctx, store.CreateUserParams{
Email: email,
DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
Locale: ptr(i18n.Lang(ctx)),
EmailKey: ptr(emailKey(email)), EmailVerifiedAt: ptr(time.Now()),
})
if err != nil {
return err
+402
View File
@@ -0,0 +1,402 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// pageGroupTree organizes one status page's nested groups in display order.
type pageGroupTree struct {
byID map[uuid.UUID]store.StatusPageGroup
children map[uuid.UUID][]uuid.UUID
roots []uuid.UUID
}
func newPageGroupTree(groups []store.StatusPageGroup) pageGroupTree {
t := pageGroupTree{
byID: make(map[uuid.UUID]store.StatusPageGroup, len(groups)),
children: map[uuid.UUID][]uuid.UUID{},
}
for _, g := range groups {
t.byID[g.ID] = g
}
for _, g := range groups {
if g.ParentID != nil {
if _, ok := t.byID[*g.ParentID]; ok {
t.children[*g.ParentID] = append(t.children[*g.ParentID], g.ID)
continue
}
}
t.roots = append(t.roots, g.ID)
}
return t
}
func (t pageGroupTree) walk(fn func(g store.StatusPageGroup, depth int)) {
var visit func(ids []uuid.UUID, depth int)
visit = func(ids []uuid.UUID, depth int) {
for _, id := range ids {
fn(t.byID[id], depth)
visit(t.children[id], depth+1)
}
}
visit(t.roots, 0)
}
type pageGroupView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
ParentID *uuid.UUID `json:"parent_id"`
Position int32 `json:"position"`
}
type pageGroupRequest struct {
Name string `json:"name" binding:"required,max=100"`
ParentID *uuid.UUID `json:"parent_id"`
Position int32 `json:"position"`
}
func pageGroupError(c *gin.Context, err error) bool {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return false
}
switch {
case pgErr.ConstraintName == "status_page_groups_cycle", pgErr.ConstraintName == "status_page_groups_check":
fail(c, http.StatusUnprocessableEntity, "group_cycle")
case pgErr.ConstraintName == "status_page_groups_depth":
fail(c, http.StatusUnprocessableEntity, "group_too_deep")
case pgErr.Code == "23503":
fail(c, http.StatusUnprocessableEntity, "invalid_group")
default:
return false
}
return true
}
func (s *Server) listStatusPageGroups(c *gin.Context) {
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var groups []store.StatusPageGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
var err error
groups, err = q.ListStatusPageGroups(ctx, pageID)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
out := make([]pageGroupView, 0, len(groups))
newPageGroupTree(groups).walk(func(g store.StatusPageGroup, _ int) {
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
})
c.JSON(http.StatusOK, gin.H{"groups": out})
}
func (s *Server) createStatusPageGroup(c *gin.Context) {
var req pageGroupRequest
if !bind(c, &req) {
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var g store.StatusPageGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
var err error
g, err = q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: p.Org.ID,
ParentID: req.ParentID,
Name: req.Name,
Position: req.Position,
})
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if pageGroupError(c, err) {
return
}
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
func (s *Server) updateStatusPageGroup(c *gin.Context) {
groupID, err := uuid.Parse(c.Param("group_id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req pageGroupRequest
if !bind(c, &req) {
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var g store.StatusPageGroup
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
g, err = q.UpdateStatusPageGroup(ctx, store.UpdateStatusPageGroupParams{
ID: groupID,
PageID: pageID,
Name: req.Name,
ParentID: req.ParentID,
Position: req.Position,
})
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if pageGroupError(c, err) {
return
}
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
// deleteStatusPageGroup moves child groups and monitors up to the deleted
// group's parent before removing the group.
func (s *Server) deleteStatusPageGroup(c *gin.Context) {
groupID, err := uuid.Parse(c.Param("group_id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
groups, err := q.ListStatusPageGroups(ctx, pageID)
if err != nil {
return err
}
target, ok := newPageGroupTree(groups).byID[groupID]
if !ok {
return pgx.ErrNoRows
}
if err := q.ReparentStatusPageGroupChildren(ctx, store.ReparentStatusPageGroupChildrenParams{
PageID: pageID, ParentID: &groupID, ParentID_2: target.ParentID,
}); err != nil {
return err
}
if err := q.ReparentStatusPageGroupMonitors(ctx, store.ReparentStatusPageGroupMonitorsParams{
PageID: pageID, GroupID: &groupID, GroupID_2: target.ParentID,
}); err != nil {
return err
}
n, err := q.DeleteStatusPageGroup(ctx, store.DeleteStatusPageGroupParams{ID: groupID, PageID: pageID})
if err != nil {
return err
}
if n == 0 {
return pgx.ErrNoRows
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// importStatusPageGroups copies the organization's monitor group hierarchy
// onto the status page and maps the page's monitors into those groups. When
// the page already lists monitors, only groups containing those monitors (and
// their ancestors) are imported; otherwise the full monitor group tree is
// copied as a starting layout.
func (s *Server) importStatusPageGroups(c *gin.Context) {
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var created []store.StatusPageGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
orgGroups, err := q.ListGroups(ctx)
if err != nil {
return err
}
listed, err := q.StatusPageMonitors(ctx, pageID)
if err != nil {
return err
}
tree := newGroupTree(orgGroups)
needed := map[uuid.UUID]bool{}
if len(listed) == 0 {
for id := range tree.byID {
needed[id] = true
}
} else {
for _, m := range listed {
for cur := m.MonitorGroupID; cur != nil; {
g, ok := tree.byID[*cur]
if !ok || needed[g.ID] {
break
}
needed[g.ID] = true
cur = g.ParentID
}
}
}
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
return err
}
mapped := map[uuid.UUID]store.StatusPageGroup{}
var createErr error
posByParent := map[uuid.UUID]int32{}
tree.walk(func(g store.MonitorGroup, _ int) {
if createErr != nil || !needed[g.ID] {
return
}
var parentKey uuid.UUID
var parentID *uuid.UUID
if g.ParentID != nil {
if parent, ok := mapped[*g.ParentID]; ok {
pid := parent.ID
parentID = &pid
parentKey = pid
}
}
pos := posByParent[parentKey]
posByParent[parentKey] = pos + 1
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: p.Org.ID,
ParentID: parentID,
Name: g.Name,
Position: pos,
})
if err != nil {
createErr = err
return
}
mapped[g.ID] = row
created = append(created, row)
})
if createErr != nil {
return createErr
}
for _, m := range listed {
var gid *uuid.UUID
section := ""
if m.MonitorGroupID != nil {
if g, ok := mapped[*m.MonitorGroupID]; ok {
id := g.ID
gid = &id
section = g.Name
}
}
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
}); err != nil {
return err
}
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
out := make([]pageGroupView, 0, len(created))
for _, g := range created {
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
c.JSON(http.StatusOK, gin.H{"groups": out})
}
// resolvePageMonitorGroup returns the status page group ID and section label
// for a component entry, creating a top-level group when a legacy caller passes
// only section.
func resolvePageMonitorGroup(
ctx context.Context,
q *store.Queries,
pageID, orgID uuid.UUID,
m pageMonitor,
groupsByID map[uuid.UUID]store.StatusPageGroup,
topByName map[string]store.StatusPageGroup,
nextPos *int32,
) (*uuid.UUID, string, error) {
if m.GroupID != nil {
if g, ok := groupsByID[*m.GroupID]; ok {
return m.GroupID, g.Name, nil
}
// Let the database foreign key reject unknown or foreign group IDs.
return m.GroupID, strings.TrimSpace(m.Section), nil
}
sec := strings.TrimSpace(m.Section)
if sec == "" {
return nil, "", nil
}
if g, ok := topByName[sec]; ok {
id := g.ID
return &id, g.Name, nil
}
g, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: orgID,
Name: sec,
Position: *nextPos,
})
if err != nil {
return nil, "", err
}
*nextPos++
groupsByID[g.ID] = g
topByName[sec] = g
id := g.ID
return &id, g.Name, nil
}
+228 -34
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"math"
"net"
"net/http"
"net/url"
@@ -17,6 +18,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
@@ -42,17 +44,25 @@ var (
// buildSnapshot computes what the public sees of page.
func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) {
snap := agentapi.PageSnapshot{
Slug: page.Slug, Title: page.Title, Description: page.Description,
Sections: []agentapi.Section{}, Incidents: []agentapi.PageIncident{}, GeneratedAt: time.Now(),
Slug: page.Slug,
Title: page.Title,
Description: page.Description,
ShowDetails: page.ShowComponentDetails,
Sections: []agentapi.Section{},
Incidents: []agentapi.PageIncident{},
GeneratedAt: time.Now(),
}
_ = json.Unmarshal(page.Theme, &snap.Theme)
var (
listed []store.StatusPageMonitorsRow
latest []store.LatestResultsRow
open []store.Incident
daily []store.DailyBucketsForMonitorsRow
incidents []store.Incident
planned map[uuid.UUID][]store.MaintenanceWindow
listed []store.StatusPageMonitorsRow
pageGroups []store.StatusPageGroup
latest []store.LatestResultsRow
open []store.Incident
daily []store.DailyBucketsForMonitorsRow
hourly []store.HourlyBucketsRow
regions []store.Region
incidents []store.Incident
planned map[uuid.UUID][]store.MaintenanceWindow
)
now := time.Now()
err := s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
@@ -60,6 +70,9 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
if listed, err = q.StatusPageMonitors(ctx, page.ID); err != nil {
return err
}
if pageGroups, err = q.ListStatusPageGroups(ctx, page.ID); err != nil {
return err
}
ids := make([]uuid.UUID, len(listed))
for i, m := range listed {
ids[i] = m.MonitorID
@@ -75,6 +88,16 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
}); err != nil {
return err
}
if page.ShowComponentDetails {
if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour),
}); err != nil {
return err
}
if regions, err = q.ListVisibleRegions(ctx); err != nil {
return err
}
}
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
return err
}
@@ -90,11 +113,13 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
}
failing := map[uuid.UUID]int{}
reported := map[uuid.UUID]int{}
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
for _, l := range latest {
reported[l.MonitorID]++
if !l.Ok {
failing[l.MonitorID]++
}
latestByMonitor[l.MonitorID] = append(latestByMonitor[l.MonitorID], l)
}
down := map[uuid.UUID]bool{}
for _, i := range open {
@@ -104,15 +129,34 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
for _, d := range daily {
days[d.MonitorID] = append(days[d.MonitorID], web.Bucket{Start: d.Bucket, Total: d.Total, OK: d.OkCount})
}
hourlyByMonitor := map[uuid.UUID][]web.Bucket{}
for _, h := range hourly {
hourlyByMonitor[h.MonitorID] = append(hourlyByMonitor[h.MonitorID], web.Bucket{
Start: h.Bucket, Total: h.Total, OK: h.OkCount, Latency: h.AvgLatencyMs,
})
}
regionNames := make(map[string]string, len(regions))
for _, r := range regions {
regionNames[r.ID.String()] = r.Name
}
names := map[uuid.UUID]string{}
var states []string
var ungrouped []agentapi.Component
byGroup := map[uuid.UUID][]agentapi.Component{}
for _, m := range listed {
name := m.Label
if name == "" {
name = m.MonitorName
}
names[m.MonitorID] = name
comp := agentapi.Component{Name: name, Uptime: web.Uptime(days[m.MonitorID]), Days: dayHistory(days[m.MonitorID], now)}
uptime90 := web.Uptime(days[m.MonitorID])
comp := agentapi.Component{
ID: m.MonitorID.String(),
Name: name,
Uptime: uptime90,
Days: dayHistory(days[m.MonitorID], now),
}
switch {
case down[m.MonitorID]:
comp.Status = agentapi.PageOutage
@@ -123,13 +167,27 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
default:
comp.Status = agentapi.PageOperational
}
if page.ShowComponentDetails {
comp.Details = buildComponentDetails(
days[m.MonitorID],
hourlyByMonitor[m.MonitorID],
latestByMonitor[m.MonitorID],
regionNames,
uptime90,
now,
)
}
states = append(states, comp.Status)
if n := len(snap.Sections); n == 0 || snap.Sections[n-1].Name != m.Section {
snap.Sections = append(snap.Sections, agentapi.Section{Name: m.Section})
if m.GroupID != nil {
byGroup[*m.GroupID] = append(byGroup[*m.GroupID], comp)
} else {
ungrouped = append(ungrouped, comp)
}
last := &snap.Sections[len(snap.Sections)-1]
last.Components = append(last.Components, comp)
}
if len(ungrouped) > 0 {
snap.Sections = append(snap.Sections, agentapi.Section{Name: "", Components: ungrouped})
}
snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...)
snap.Status = agentapi.Summarize(states)
snap.Maintenance = pageMaintenance(planned, names, now)
for _, i := range incidents {
@@ -138,6 +196,102 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
return snap, nil
}
// buildPageSections turns a status page's group tree and grouped components
// into recursive public sections, omitting subtrees with no components.
func buildPageSections(tree pageGroupTree, byGroup map[uuid.UUID][]agentapi.Component) []agentapi.Section {
var build func(id uuid.UUID) (agentapi.Section, []string)
build = func(id uuid.UUID) (agentapi.Section, []string) {
g := tree.byID[id]
sec := agentapi.Section{Name: g.Name, Components: byGroup[id]}
var states []string
for _, c := range sec.Components {
states = append(states, c.Status)
}
sec.Total = len(sec.Components)
for _, childID := range tree.children[id] {
childSec, childStates := build(childID)
if childSec.Total == 0 {
continue
}
sec.Children = append(sec.Children, childSec)
sec.Total += childSec.Total
states = append(states, childStates...)
}
if sec.Total > 0 {
sec.Status = agentapi.Summarize(states)
}
return sec, states
}
var out []agentapi.Section
for _, rootID := range tree.roots {
sec, _ := build(rootID)
if sec.Total > 0 {
out = append(out, sec)
}
}
return out
}
func buildComponentDetails(
daily []web.Bucket,
hourly []web.Bucket,
latest []store.LatestResultsRow,
regionNames map[string]string,
uptime90 float64,
now time.Time,
) *agentapi.ComponentDetails {
since7d := now.UTC().AddDate(0, 0, -7)
since30d := now.UTC().AddDate(0, 0, -30)
var d7, d30 []web.Bucket
for _, b := range daily {
if !b.Start.Before(since30d) {
d30 = append(d30, b)
}
if !b.Start.Before(since7d) {
d7 = append(d7, b)
}
}
byHour := make(map[int64]web.Bucket, len(hourly))
for _, b := range hourly {
byHour[web.AlignBucket(b.Start.UTC(), time.Hour).Unix()] = b
}
endHour := web.AlignBucket(now.UTC(), time.Hour)
hours := make([]agentapi.HourBucket, 24)
for i := range hours {
ts := endHour.Add(-time.Duration(23-i) * time.Hour)
hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1}
if b, ok := byHour[ts.Unix()]; ok && b.Total > 0 {
hours[i].Uptime = float64(b.OK) / float64(b.Total)
hours[i].AvgLatencyMS = int(math.Round(float64(b.Latency)))
}
}
regs := make([]agentapi.ComponentRegion, 0, len(latest))
for _, l := range latest {
name := regionNames[l.Region]
if name == "" {
name = l.Region
}
status := agentapi.PageOperational
if !l.Ok {
status = agentapi.PageOutage
}
var latency int
if l.LatencyMs != nil && *l.LatencyMs > 0 {
latency = int(*l.LatencyMs)
}
regs = append(regs, agentapi.ComponentRegion{Name: name, Status: status, LatencyMS: latency})
}
slices.SortFunc(regs, func(a, b agentapi.ComponentRegion) int { return strings.Compare(a.Name, b.Name) })
return &agentapi.ComponentDetails{
SLA24h: web.Uptime(hourly),
SLA7d: web.Uptime(d7),
SLA30d: web.Uptime(d30),
SLA90d: uptime90,
Hours: hours,
Regions: regs,
}
}
func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day {
byDay := map[string]web.Bucket{}
for _, b := range buckets {
@@ -192,11 +346,12 @@ func (s *Server) agentPage(c *gin.Context) {
}
type statusPageRequest struct {
Slug string `json:"slug" binding:"required,max=63"`
Title string `json:"title" binding:"required,max=200"`
Description string `json:"description" binding:"max=10000"`
Published bool `json:"published"`
Theme agentapi.Theme `json:"theme"`
Slug string `json:"slug" binding:"required,max=63"`
Title string `json:"title" binding:"required,max=200"`
Description string `json:"description" binding:"max=10000"`
Published bool `json:"published"`
ShowComponentDetails bool `json:"show_component_details"`
Theme agentapi.Theme `json:"theme"`
}
func (r *statusPageRequest) normalize() string {
@@ -226,16 +381,21 @@ func (r *statusPageRequest) normalize() string {
}
type statusPageView struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
Published bool `json:"published"`
Theme agentapi.Theme `json:"theme"`
CustomDomain *string `json:"custom_domain"`
DomainVerified bool `json:"domain_verified"`
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
Published bool `json:"published"`
ShowComponentDetails bool `json:"show_component_details"`
Theme agentapi.Theme `json:"theme"`
CustomDomain *string `json:"custom_domain"`
DomainVerified bool `json:"domain_verified"`
// DomainRecord is the TXT record that proves control of CustomDomain.
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
// Suspended is set when platform admins took the page offline; it is
// not served whatever Published says.
Suspended bool `json:"suspended,omitempty"`
SuspendedReason string `json:"suspended_reason,omitempty"`
}
type dnsRecord struct {
@@ -246,8 +406,10 @@ type dnsRecord struct {
func viewStatusPage(p store.StatusPage) statusPageView {
v := statusPageView{
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description, Published: p.Published,
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description,
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails,
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason,
}
_ = json.Unmarshal(p.Theme, &v.Theme)
if p.CustomDomain != nil {
@@ -310,13 +472,20 @@ func (s *Server) createStatusPage(c *gin.Context) {
theme, _ := json.Marshal(req.Theme)
var row store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if err := reserve(ctx, q, p.Org.ID, s.orgLimits(ctx, p.Org).StatusPages, "status_page_limit", q.CountStatusPages); err != nil {
return err
}
var err error
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
Published: req.Published, DomainToken: newDomainToken(), Theme: theme,
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails,
DomainToken: newDomainToken(), Theme: theme,
})
return err
})
if failLimit(c, err) {
return
}
if isUniqueViolation(err, "status_pages_slug_key") {
fail(c, http.StatusConflict, "slug_taken")
return
@@ -351,7 +520,8 @@ func (s *Server) updateStatusPage(c *gin.Context) {
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description, Published: req.Published, Theme: theme,
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description,
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Theme: theme,
})
return err
})
@@ -389,9 +559,10 @@ func (s *Server) deleteStatusPage(c *gin.Context) {
}
type pageMonitor struct {
MonitorID uuid.UUID `json:"monitor_id" binding:"required"`
Section string `json:"section" binding:"max=100"`
Label string `json:"label" binding:"max=200"`
MonitorID uuid.UUID `json:"monitor_id" binding:"required"`
GroupID *uuid.UUID `json:"group_id"`
Section string `json:"section" binding:"max=100"`
Label string `json:"label" binding:"max=200"`
}
type pageMonitorsRequest struct {
@@ -412,13 +583,33 @@ func (s *Server) setPageMonitors(c *gin.Context) {
if _, err := q.GetStatusPage(ctx, id); err != nil {
return err
}
existingGroups, err := q.ListStatusPageGroups(ctx, id)
if err != nil {
return err
}
groupsByID := make(map[uuid.UUID]store.StatusPageGroup, len(existingGroups))
topByName := map[string]store.StatusPageGroup{}
var nextPos int32
for _, g := range existingGroups {
groupsByID[g.ID] = g
if g.ParentID == nil {
topByName[g.Name] = g
if g.Position >= nextPos {
nextPos = g.Position + 1
}
}
}
if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
return err
}
for i, m := range req.Monitors {
err := q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{
groupID, section, err := resolvePageMonitorGroup(ctx, q, id, p.Org.ID, m, groupsByID, topByName, &nextPos)
if err != nil {
return err
}
err = q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{
PageID: id, MonitorID: m.MonitorID, OrgID: p.Org.ID,
Section: strings.TrimSpace(m.Section), Label: strings.TrimSpace(m.Label), Position: int32(i),
Section: section, GroupID: groupID, Label: strings.TrimSpace(m.Label), Position: int32(i),
})
if err != nil {
return err
@@ -426,9 +617,12 @@ func (s *Server) setPageMonitors(c *gin.Context) {
}
return nil
})
var pgErr *pgconn.PgError
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case errors.As(err, &pgErr) && pgErr.Code == "23503" && strings.Contains(pgErr.ConstraintName, "group_id"):
fail(c, http.StatusUnprocessableEntity, "invalid_group")
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
// Unknown monitors, monitors of other orgs and duplicates.
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
+229
View File
@@ -213,3 +213,232 @@ func verifyDomain(t *testing.T, owner *browser, pageID string, record map[string
st, body := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil)
expect(t, "verify domain", st, body, http.StatusNoContent, "")
}
func TestStatusPageGroupsAndDetails(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer down.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("spg")+".test", uniq("spg-"))
// Create monitor groups to test importing the hierarchy later.
st, mgRoot := owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "Core"})
if st != http.StatusCreated {
t.Fatalf("create monitor root group = %d %v, want 201", st, mgRoot)
}
st, mgChild := owner.do("POST", "/api/v1/org/groups", map[string]any{
"name": "Edge",
"parent_id": mgRoot["id"],
})
if st != http.StatusCreated {
t.Fatalf("create monitor child group = %d %v, want 201", st, mgChild)
}
newMonitor := func(name, target string, groupID any) string {
t.Helper()
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": name,
"type": "http",
"target": target,
"interval_seconds": 60,
"confirmations": 1,
"regions": []string{region},
"group_id": groupID,
})
if st != http.StatusCreated {
t.Fatalf("create monitor %q = %d %v, want 201", name, st, body)
}
return body["id"].(string)
}
webID := newMonitor("web", up.URL, mgChild["id"])
apiID := newMonitor("api", down.URL, mgRoot["id"])
// Heartbeat monitors record NULL latency_ms; ensure HourlyBuckets handles them
// cleanly when show_component_details is enabled.
st, hbBody := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "nightly-job",
"type": "heartbeat",
"interval_seconds": 3600,
})
if st != http.StatusCreated {
t.Fatalf("create heartbeat monitor = %d %v, want 201", st, hbBody)
}
hbResp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+hbBody["target"].(string), "text/plain", strings.NewReader(""))
if err != nil {
t.Fatalf("ping heartbeat error = %v", err)
}
_ = hbResp.Body.Close()
slug := uniq("nested-")
st, pageBody := owner.do("POST", "/api/v1/org/statuspages", map[string]any{
"slug": slug,
"title": "Nested Status",
"published": true,
"show_component_details": false,
})
if st != http.StatusCreated {
t.Fatalf("create status page = %d %v, want 201", st, pageBody)
}
pageID := pageBody["id"].(string)
// Nested status page groups CRUD + cycle & depth validation.
st, gParent := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
"name": "Platform",
"position": 0,
})
if st != http.StatusCreated {
t.Fatalf("create page parent group = %d %v, want 201", st, gParent)
}
parentID := gParent["id"].(string)
st, gChild := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
"name": "Public Services",
"parent_id": parentID,
"position": 0,
})
if st != http.StatusCreated {
t.Fatalf("create page child group = %d %v, want 201", st, gChild)
}
childID := gChild["id"].(string)
// Cycle rejection.
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/groups/"+parentID, map[string]any{
"name": "Platform",
"parent_id": childID,
})
expect(t, "group cycle", st, body, http.StatusUnprocessableEntity, "group_cycle")
// Assign monitors into nested groups.
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{
"monitors": []map[string]any{
{"monitor_id": webID, "group_id": childID, "label": "Website"},
{"monitor_id": apiID, "group_id": parentID, "label": "API"},
},
})
expect(t, "assign grouped monitors", st, body, http.StatusNoContent, "")
waitFor(t, 10*time.Second, "incident for failing monitor", func() bool {
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
return len(b["incidents"].([]any)) == 1
})
platform := e.statuspageClient(t, nil)
snap, err := platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page() error = %v", err)
}
if snap.ShowDetails {
t.Fatalf("snap.ShowDetails = true, want false")
}
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Platform" ||
snap.Sections[0].Total != 2 || snap.Sections[0].Status != agentapi.PageDegraded ||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Public Services" ||
snap.Sections[0].Children[0].Status != agentapi.PageOperational {
t.Fatalf("nested sections = %+v, want Platform(degraded,2) -> Public Services(operational,1)", snap.Sections)
}
if snap.Sections[0].Components[0].Details != nil {
t.Errorf("component Details populated when show_component_details=false")
}
// Enable show_component_details and verify snapshot details & privacy.
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{
"slug": slug,
"title": "Nested Status",
"published": true,
"show_component_details": true,
})
if st != http.StatusOK || body["show_component_details"] != true {
t.Fatalf("enable show_component_details = %d %v, want 200 with true", st, body)
}
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(with details) error = %v", err)
}
if !snap.ShowDetails {
t.Fatalf("snap.ShowDetails = false, want true")
}
comp, ok := snap.ComponentByID(apiID)
if !ok || comp.Details == nil {
t.Fatalf("ComponentByID(%s) = (%+v, %t), want component with Details", apiID, comp, ok)
}
if len(comp.Details.Hours) != 24 || len(comp.Details.Regions) != 1 {
t.Errorf("component details hours/regions = %d/%d, want 24/1", len(comp.Details.Hours), len(comp.Details.Regions))
}
raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status", "HTTP 500"} {
if strings.Contains(string(raw), secret) {
t.Errorf("snapshot with details leaks %q", secret)
}
}
// Verify live status page server renders component detail page.
cat, _ := i18n.Load()
spSrv, err := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
if err != nil {
t.Fatalf("statuspage.New() error = %v", err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
spSrv.Mount(router)
req := httptest.NewRequest(http.MethodGet, "/"+slug+"/components/"+apiID, nil)
req.Host = "status.test"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "API") || !strings.Contains(rec.Body.String(), "Last 24 hours") {
t.Errorf("GET detail page = %d, want 200 with component details", rec.Code)
}
// Static export has no broken /components/ links and embeds inline details.
resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export")
if err != nil {
t.Fatalf("export request error = %v", err)
}
exported, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK || strings.Contains(string(exported), "/components/") || !strings.Contains(string(exported), "Show details") {
t.Errorf("export status = %d, want inline details without /components/ links", resp.StatusCode)
}
// Delete child group: monitor moves up to parent group.
st, body = owner.do("DELETE", "/api/v1/org/statuspages/"+pageID+"/groups/"+childID, nil)
expect(t, "delete child group", st, body, http.StatusNoContent, "")
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(after delete) error = %v", err)
}
if len(snap.Sections) != 1 || len(snap.Sections[0].Components) != 2 || len(snap.Sections[0].Children) != 0 {
t.Errorf("after deleting child group, sections = %+v, want 2 monitors under Platform", snap.Sections)
}
// Import monitor groups copies Core -> Edge and re-assigns monitors.
st, imported := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups/import", nil)
if st != http.StatusOK || len(imported["groups"].([]any)) != 2 {
t.Fatalf("import groups = %d %v, want 200 with 2 groups", st, imported)
}
snap, err = platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page(after import) error = %v", err)
}
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Core" ||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Edge" {
t.Errorf("imported sections = %+v, want Core -> Edge", snap.Sections)
}
// Console editor shows new controls.
st, _, html := owner.page("/statuspages/" + pageID)
for _, want := range []string{`name="show_component_details"`, `/groups/import`, `data-field="group_id"`} {
if st != http.StatusOK || !strings.Contains(html, want) {
t.Errorf("editor HTML = %d, missing %q", st, want)
}
}
}
+10
View File
@@ -79,6 +79,16 @@ func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, in
if err != nil {
return nil, 0, "", err
}
if p.Org.SuspendedAt != nil {
return nil, http.StatusForbidden, "org_suspended", nil
}
// Tokens act for their creator and stop with the creator's account.
if u, err := s.loadUser(ctx, row.UserID); err != nil || u.DisabledAt != nil {
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return nil, 0, "", err
}
return nil, http.StatusUnauthorized, "unauthenticated", nil
}
p.UserID, p.TokenID = row.UserID, row.ID
p.Grants = p.Grants.Restrict(authz.NewSet(row.Permissions...))
return p, 0, "", nil
+99
View File
@@ -0,0 +1,99 @@
package check
import (
"context"
"encoding/json"
"regexp"
"slices"
)
// AlertmanagerConfig configures a monitor fed by Alertmanager: it is down
// while an alert matching every matcher fires.
type AlertmanagerConfig struct {
Matchers []Matcher `json:"matchers"`
// StaleHours ends a firing alert that Alertmanager has not repeated for
// this long, so a lost "resolved" message cannot keep a monitor down
// forever. It must exceed Alertmanager's repeat_interval (4h by default).
StaleHours int `json:"stale_hours"`
}
// Matcher compares one label the way Prometheus and Alertmanager do:
// = and != compare text, =~ and !~ match a fully anchored regular
// expression. A missing label counts as empty.
type Matcher struct {
Label string `json:"label"`
Op string `json:"op"`
Value string `json:"value"`
}
// DefaultStaleHours applies when no stale period is set.
const DefaultStaleHours = 24
var (
labelName = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
matcherOps = []string{"=", "!=", "=~", "!~"}
)
type alertmanagerCheck struct{}
func (alertmanagerCheck) validate(_ string, config json.RawMessage) (json.RawMessage, error) {
c, err := decode[AlertmanagerConfig](config)
if err != nil {
return nil, err
}
// Forms send empty rows for unused matcher slots.
c.Matchers = slices.DeleteFunc(c.Matchers, func(m Matcher) bool { return m.Label == "" })
if len(c.Matchers) == 0 || len(c.Matchers) > 20 {
return nil, invalid("invalid_matchers")
}
for _, m := range c.Matchers {
if !labelName.MatchString(m.Label) || !slices.Contains(matcherOps, m.Op) || len(m.Value) > 500 {
return nil, invalid("invalid_matchers")
}
if _, err := m.compile(); err != nil {
return nil, invalid("invalid_matchers")
}
}
if c.StaleHours == 0 {
c.StaleHours = DefaultStaleHours
}
if c.StaleHours < 1 || c.StaleHours > 24*30 {
return nil, invalid("invalid_stale_hours")
}
return encode(c), nil
}
func (alertmanagerCheck) run(context.Context, Spec) Outcome {
return Outcome{Error: "alertmanager monitors are not run by checkers"}
}
func (m Matcher) compile() (*regexp.Regexp, error) {
if m.Op != "=~" && m.Op != "!~" {
return nil, nil
}
return regexp.Compile("^(?:" + m.Value + ")$")
}
// Matches reports whether labels satisfy every matcher of c.
func (c AlertmanagerConfig) Matches(labels map[string]string) bool {
for _, m := range c.Matchers {
v := labels[m.Label]
var ok bool
switch m.Op {
case "=":
ok = v == m.Value
case "!=":
ok = v != m.Value
default:
re, err := m.compile()
if err != nil {
return false
}
ok = re.MatchString(v) == (m.Op == "=~")
}
if !ok {
return false
}
}
return true
}
+48
View File
@@ -0,0 +1,48 @@
package check
import (
"encoding/json"
"testing"
)
func TestAlertmanagerMatchers(t *testing.T) {
c := AlertmanagerConfig{Matchers: []Matcher{
{Label: "service", Op: "=", Value: "shop"},
{Label: "severity", Op: "=~", Value: "critical|page"},
{Label: "env", Op: "!=", Value: "staging"},
{Label: "team", Op: "!~", Value: "infra.*"},
}}
for _, tc := range []struct {
labels map[string]string
want bool
}{
{map[string]string{"service": "shop", "severity": "critical"}, true},
{map[string]string{"service": "shop", "severity": "page", "env": "prod", "team": "web"}, true},
{map[string]string{"service": "shop", "severity": "warning"}, false},
{map[string]string{"service": "shop", "severity": "critical-ish"}, false}, // anchored
{map[string]string{"service": "shop", "severity": "critical", "env": "staging"}, false},
{map[string]string{"service": "shop", "severity": "critical", "team": "infra-db"}, false},
{map[string]string{"severity": "critical"}, false},
} {
if got := c.Matches(tc.labels); got != tc.want {
t.Errorf("Matches(%v) = %t, want %t", tc.labels, got, tc.want)
}
}
}
func TestAlertmanagerValidate(t *testing.T) {
cfg, err := Validate(Alertmanager, "", json.RawMessage(`{"matchers":[{"label":"alertname","op":"=","value":"Down"},{"label":"","op":"=","value":""}]}`))
if err != nil {
t.Fatal(err)
}
var c AlertmanagerConfig
_ = json.Unmarshal(cfg, &c)
if len(c.Matchers) != 1 || c.StaleHours != DefaultStaleHours {
t.Errorf("normalized = %+v", c)
}
for _, bad := range []string{`{"matchers":[]}`, `{"matchers":[{"label":"1x","op":"=","value":"a"}]}`, `{"matchers":[{"label":"a","op":"=~","value":"("}]}`, `{"matchers":[{"label":"a","op":"~","value":"a"}]}`} {
if _, err := Validate(Alertmanager, "", json.RawMessage(bad)); err == nil {
t.Errorf("Validate(%s) accepted", bad)
}
}
}
+23 -5
View File
@@ -29,13 +29,15 @@ const (
// Heartbeat monitors are pinged by the monitored job; no checker runs
// them.
Heartbeat Type = "heartbeat"
// Alertmanager monitors follow alerts that Alertmanager sends us.
Alertmanager Type = "alertmanager"
)
// Types lists every check type.
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Heartbeat}
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, GRPC, SMTP, RADIUS, SNMP, Steam, Minecraft, Docker, Heartbeat, Alertmanager}
// Passive reports whether t is reported to us rather than run by checkers.
func Passive(t Type) bool { return t == Heartbeat }
func Passive(t Type) bool { return t == Heartbeat || t == Alertmanager }
// Spec is everything needed to run one check.
type Spec struct {
@@ -93,9 +95,25 @@ var impls = map[Type]impl{
DNS: dnsCheck{},
TLS: tlsCheck{},
JSON: jsonCheck{},
Prometheus: prometheusCheck{},
Heartbeat: heartbeatCheck{},
JSON: jsonCheck{},
Prometheus: prometheusCheck{},
Postgres: dbCheck{Postgres},
MySQL: dbCheck{MySQL},
MSSQL: dbCheck{MSSQL},
MongoDB: dbCheck{MongoDB},
Redis: dbCheck{Redis},
MQTT: brokerCheck{MQTT},
Kafka: brokerCheck{Kafka},
RabbitMQ: brokerCheck{RabbitMQ},
GRPC: grpcCheck{},
SMTP: smtpCheck{},
RADIUS: radiusCheck{},
SNMP: snmpCheck{},
Steam: gameCheck{Steam},
Minecraft: gameCheck{Minecraft},
Docker: dockerCheck{},
Heartbeat: heartbeatCheck{},
Alertmanager: alertmanagerCheck{},
}
// Validate checks target and config for type t and returns the normalized
+1 -1
View File
@@ -126,7 +126,7 @@ func TestValidate(t *testing.T) {
{TCP, "x.test:0", `{}`, "invalid_target"},
{DNS, "x.test", `{"record":"SRV"}`, "invalid_record"},
{TLS, "x.test:443", `{"min_days_valid":-1}`, "invalid_config"},
{"smtp", "x.test", `{}`, "invalid_type"},
{"gopher", "x.test", `{}`, "invalid_type"},
}
for _, tt := range tests {
_, err := Validate(tt.typ, tt.target, json.RawMessage(tt.config))
+307
View File
@@ -0,0 +1,307 @@
package check
import (
"context"
"crypto/tls"
"database/sql"
"encoding/json"
"fmt"
"net"
"net/url"
"strconv"
"sync"
"time"
"github.com/go-sql-driver/mysql"
"github.com/jackc/pgx/v5"
mssql "github.com/microsoft/go-mssqldb"
"github.com/microsoft/go-mssqldb/msdsn"
"github.com/redis/go-redis/v9"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Database checks connect to host:port with the configured credentials and
// run a query. Every connection goes through the network guard.
const (
Postgres Type = "postgres"
MySQL Type = "mysql"
MSSQL Type = "mssql"
MongoDB Type = "mongodb"
Redis Type = "redis"
)
// DBConfig configures database checks. Password is a secret: the API
// stores it sealed and hands it only to checkers.
type DBConfig struct {
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
Database string `json:"database,omitempty"`
// TLS is "disable", "require" (encrypt without verifying) or "verify".
TLS string `json:"tls"`
// Query runs after connecting; it must succeed. Empty uses a ping.
// Not used for MongoDB and Redis.
Query string `json:"query,omitempty"`
// Expect, when set, must equal the first column of the first row.
Expect string `json:"expect,omitempty"`
}
// SecretFields lists the settings of t the API stores sealed.
func SecretFields(t Type) []string {
switch t {
case Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ:
return []string{"password"}
case RADIUS:
return []string{"password", "secret"}
case SNMP:
return []string{"community"}
}
return nil
}
type dbCheck struct{ typ Type }
func (d dbCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
host, port, err := net.SplitHostPort(target)
if n, perr := strconv.Atoi(port); err != nil || host == "" || perr != nil || n < 1 || n > 65535 {
return nil, invalid("invalid_target")
}
c := DBConfig{TLS: "require"}
if err := json.Unmarshal(config, &c); err != nil {
return nil, invalid("invalid_config")
}
if c.TLS == "" {
c.TLS = "require"
}
if !validTLSMode(c.TLS) {
return nil, invalid("invalid_config")
}
if len(c.User) > 200 || len(c.Password) > 500 || len(c.Database) > 200 || len(c.Query) > 2000 || len(c.Expect) > 500 {
return nil, invalid("invalid_config")
}
if (d.typ == MongoDB || d.typ == Redis) && (c.Query != "" || c.Expect != "") {
return nil, invalid("invalid_config")
}
if d.typ == Redis && c.Database != "" {
if n, err := strconv.Atoi(c.Database); err != nil || n < 0 || n > 15 {
return nil, invalid("invalid_config")
}
}
return encode(c), nil
}
func (d dbCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[DBConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
dialer := netguard.Dialer(s.AllowPrivate, s.Timeout)
tlsConfig := tlsFor(c.TLS, s.Target)
var got string
switch d.typ {
case Postgres:
got, err = queryPostgres(ctx, s.Target, c, dialer, tlsConfig)
case MySQL:
got, err = queryMySQL(ctx, s.Target, c, s.AllowPrivate, tlsConfig)
case MSSQL:
got, err = queryMSSQL(ctx, s.Target, c, dialer)
case MongoDB:
err = pingMongo(ctx, s.Target, c, dialer, tlsConfig)
case Redis:
err = pingRedis(ctx, s.Target, c, dialer, tlsConfig)
}
if err != nil {
return Outcome{Error: redact(err, c.Password)}
}
if c.Expect != "" && got != c.Expect {
return Outcome{Error: fmt.Sprintf("query returned %q, expected %q", truncate(got, 100), truncate(c.Expect, 100))}
}
return Outcome{OK: true}
}
func queryPostgres(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) (string, error) {
u := url.URL{Scheme: "postgres", Host: target, Path: "/" + c.Database}
if c.User != "" {
u.User = url.UserPassword(c.User, c.Password)
}
cfg, err := pgx.ParseConfig(u.String())
if err != nil {
return "", err
}
cfg.TLSConfig = tlsConfig
cfg.Fallbacks = nil
cfg.DialFunc = d.DialContext
conn, err := pgx.ConnectConfig(ctx, cfg)
if err != nil {
return "", err
}
defer func() { _ = conn.Close(context.WithoutCancel(ctx)) }()
q := c.Query
if q == "" {
q = "SELECT 1"
}
rows, err := conn.Query(ctx, q)
if err != nil {
return "", err
}
defer rows.Close()
var first string
if rows.Next() {
if vals, err := rows.Values(); err == nil && len(vals) > 0 {
first = fmt.Sprint(vals[0])
}
}
return first, rows.Err()
}
var registerMySQLDial sync.Once
// mysqlNetwork names a dial function registered with the MySQL driver,
// which only accepts dialers by name.
func mysqlNetwork(allowPrivate bool) string {
registerMySQLDial.Do(func() {
for _, private := range []bool{false, true} {
d := netguard.Dialer(private, 0)
mysql.RegisterDialContext(mysqlNetworkName(private), func(ctx context.Context, addr string) (net.Conn, error) {
return d.DialContext(ctx, "tcp", addr)
})
}
})
return mysqlNetworkName(allowPrivate)
}
func mysqlNetworkName(private bool) string {
if private {
return "guard-private"
}
return "guard-public"
}
var mysqlTLS sync.Map
func queryMySQL(ctx context.Context, target string, c DBConfig, allowPrivate bool, tlsConfig *tls.Config) (string, error) {
cfg := mysql.NewConfig()
cfg.User, cfg.Passwd, cfg.DBName = c.User, c.Password, c.Database
cfg.Net, cfg.Addr = mysqlNetwork(allowPrivate), target
if tlsConfig != nil {
// The driver takes TLS settings by registered name.
name := "uptimesebi-" + strconv.FormatBool(tlsConfig.InsecureSkipVerify) + "-" + tlsConfig.ServerName
if _, done := mysqlTLS.LoadOrStore(name, true); !done {
if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil {
return "", err
}
}
cfg.TLSConfig = name
}
connector, err := mysql.NewConnector(cfg)
if err != nil {
return "", err
}
return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1")
}
func queryMSSQL(ctx context.Context, target string, c DBConfig, d *net.Dialer) (string, error) {
host, port, _ := net.SplitHostPort(target)
q := url.Values{"database": {c.Database}}
switch c.TLS {
case "disable":
q.Set("encrypt", "disable")
case "require":
q.Set("encrypt", "true")
q.Set("TrustServerCertificate", "true")
default:
q.Set("encrypt", "true")
}
u := url.URL{Scheme: "sqlserver", User: url.UserPassword(c.User, c.Password), Host: net.JoinHostPort(host, port), RawQuery: q.Encode()}
cfg, err := msdsn.Parse(u.String())
if err != nil {
return "", err
}
connector := mssql.NewConnectorConfig(cfg)
connector.Dialer = dialer{d}
return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1")
}
// dialer adapts net.Dialer to the SQL Server driver's interface.
type dialer struct{ d *net.Dialer }
// DialContext implements the driver's Dialer.
func (d dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
return d.d.DialContext(ctx, network, addr)
}
func querySQL(ctx context.Context, db *sql.DB, c DBConfig, ping string) (string, error) {
defer func() { _ = db.Close() }()
db.SetMaxOpenConns(1)
q := c.Query
if q == "" {
q = ping
}
rows, err := db.QueryContext(ctx, q)
if err != nil {
return "", err
}
defer func() { _ = rows.Close() }()
var first sql.NullString
if rows.Next() {
cols, _ := rows.Columns()
dest := make([]any, len(cols))
for i := range dest {
dest[i] = new(any)
}
if len(cols) > 0 {
dest[0] = &first
}
if err := rows.Scan(dest...); err != nil {
return "", err
}
}
return first.String, rows.Err()
}
func pingMongo(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error {
opts := options.Client().SetHosts([]string{target}).SetDialer(d).SetTLSConfig(tlsConfig).
SetDirect(true).SetServerSelectionTimeout(timeoutOf(ctx)).SetConnectTimeout(timeoutOf(ctx))
if c.User != "" {
cred := options.Credential{Username: c.User, Password: c.Password}
if c.Database != "" {
cred.AuthSource = c.Database
}
opts.SetAuth(cred)
}
client, err := mongo.Connect(opts)
if err != nil {
return err
}
defer func() { _ = client.Disconnect(context.WithoutCancel(ctx)) }()
return client.Ping(ctx, readpref.Primary())
}
func pingRedis(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error {
db, _ := strconv.Atoi(c.Database)
client := redis.NewClient(&redis.Options{
Addr: target, Username: c.User, Password: c.Password, DB: db,
Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := d.DialContext(ctx, network, addr)
if err != nil || tlsConfig == nil {
return conn, err
}
return tls.Client(conn, tlsConfig), nil
},
MaxRetries: -1, PoolSize: 1, DisableIdentity: true,
})
defer func() { _ = client.Close() }()
return client.Ping(ctx).Err()
}
// timeoutOf is the time left until ctx's deadline, for drivers that take a
// timeout instead of a context.
func timeoutOf(ctx context.Context) time.Duration {
if dl, ok := ctx.Deadline(); ok {
return max(time.Until(dl), time.Millisecond)
}
return 10 * time.Second
}
+132
View File
@@ -0,0 +1,132 @@
package check
import (
"context"
"encoding/json"
"net/url"
"os"
"strings"
"testing"
"time"
)
// dbTarget returns the address of a test database or skips.
func dbTarget(t *testing.T, env string) string {
t.Helper()
v := os.Getenv(env)
if v == "" {
t.Skip(env + " is not set")
}
return v
}
func runDB(t *testing.T, typ Type, target string, cfg map[string]any, allowPrivate bool) Outcome {
t.Helper()
raw, _ := json.Marshal(cfg)
c, err := Validate(typ, target, raw)
if err != nil {
t.Fatalf("Validate(%s) = %v", raw, err)
}
timeout := 15 * time.Second
if !allowPrivate {
// MongoDB retries a refused server until the timeout.
timeout = 3 * time.Second
}
return Run(context.Background(), Spec{Type: typ, Target: target, Timeout: timeout, Config: c, AllowPrivate: allowPrivate})
}
func TestDatabaseChecks(t *testing.T) {
pgTarget := func(t *testing.T) string {
u, err := url.Parse(os.Getenv("UPTIME_TEST_DATABASE_URL"))
if err != nil || u.Host == "" {
t.Skip("UPTIME_TEST_DATABASE_URL is not set")
}
return u.Host
}
redisTarget := func(t *testing.T) string {
u, err := url.Parse(os.Getenv("UPTIME_TEST_REDIS_URL"))
if err != nil || u.Host == "" {
t.Skip("UPTIME_TEST_REDIS_URL is not set")
}
return u.Host
}
tests := []struct {
name string
typ Type
target func(*testing.T) string
good map[string]any
bad map[string]any
}{
{"postgres", Postgres, pgTarget,
map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"},
map[string]any{"user": "uptime", "password": "wrong-pw-123", "database": "uptime_test", "tls": "disable"}},
{"mariadb", MySQL, func(t *testing.T) string { return dbTarget(t, "UPTIME_TEST_MYSQL_ADDR") },
map[string]any{"user": "root", "password": "checkpw", "database": "shop", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"},
map[string]any{"user": "root", "password": "wrong-pw-123", "tls": "disable"}},
{"mssql", MSSQL, func(t *testing.T) string { return dbTarget(t, "UPTIME_TEST_MSSQL_ADDR") },
map[string]any{"user": "sa", "password": "Check-pw-2026", "database": "master", "tls": "require", "query": "SELECT 41 + 1", "expect": "42"},
map[string]any{"user": "sa", "password": "wrong-pw-123", "tls": "require"}},
{"mongodb", MongoDB, func(t *testing.T) string { return dbTarget(t, "UPTIME_TEST_MONGO_ADDR") },
map[string]any{"user": "root", "password": "checkpw", "database": "admin", "tls": "disable"},
map[string]any{"user": "root", "password": "wrong-pw-123", "database": "admin", "tls": "disable"}},
{"redis", Redis, redisTarget,
map[string]any{"database": "15", "tls": "disable"},
map[string]any{"user": "nobody", "password": "wrong-pw-123", "tls": "disable"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
target := tc.target(t)
if o := runDB(t, tc.typ, target, tc.good, true); !o.OK {
t.Fatalf("good credentials: %+v", o)
}
o := runDB(t, tc.typ, target, tc.bad, true)
if o.OK {
t.Fatal("wrong password accepted")
}
if strings.Contains(o.Error, "wrong-pw-123") {
t.Errorf("error repeats the password: %s", o.Error)
}
// Shared checkers must not reach private networks.
if o := runDB(t, tc.typ, target, tc.good, false); o.OK || !strings.Contains(o.Error, "non-public") && !strings.Contains(o.Error, "timeout") {
t.Errorf("private address reached without permission: %+v", o)
}
})
}
t.Run("unexpected result", func(t *testing.T) {
o := runDB(t, Postgres, pgTarget(t), map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 'degraded'", "expect": "ok"}, true)
if o.OK || !strings.Contains(o.Error, `"degraded"`) {
t.Errorf("Run() = %+v", o)
}
})
}
func TestDatabaseValidate(t *testing.T) {
for _, tc := range []struct {
typ Type
target string
cfg string
}{
{Postgres, "db.example.com", `{}`},
{Postgres, "db.example.com:99999", `{}`},
{Postgres, "db.example.com:5432", `{"tls":"maybe"}`},
{Redis, "cache:6379", `{"query":"INFO"}`},
{Redis, "cache:6379", `{"database":"16"}`},
} {
if _, err := Validate(tc.typ, tc.target, json.RawMessage(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg)
}
}
if got := SecretFields(MySQL); len(got) != 1 || got[0] != "password" {
t.Errorf("SecretFields(mysql) = %v", got)
}
}
// runShort runs a check whose failure ends in a timeout with a short one.
func runShort(t *testing.T, typ Type, target, cfg string) Outcome {
t.Helper()
c, err := Validate(typ, target, json.RawMessage(cfg))
if err != nil {
t.Fatalf("Validate(%s) = %v", cfg, err)
}
return Run(context.Background(), Spec{Type: typ, Target: target, Timeout: 3 * time.Second, Config: c, AllowPrivate: true})
}
+124
View File
@@ -0,0 +1,124 @@
package check
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Docker checks a container through the Docker Engine API.
const Docker Type = "docker"
// DefaultDockerHost is the checker's own Docker socket.
const DefaultDockerHost = "unix:///var/run/docker.sock"
// DockerConfig configures a container check; the target is the container
// name or ID.
type DockerConfig struct {
// Host is a Unix socket ("unix:///var/run/docker.sock") or a plain
// TCP endpoint ("tcp://docker.internal:2375").
Host string `json:"host"`
}
var containerName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$`)
type dockerCheck struct{}
func (dockerCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !containerName.MatchString(target) {
return nil, invalid("invalid_target")
}
c := DockerConfig{Host: DefaultDockerHost}
if err := json.Unmarshal(config, &c); err != nil {
return nil, invalid("invalid_config")
}
if c.Host == "" {
c.Host = DefaultDockerHost
}
u, err := url.Parse(c.Host)
switch {
case err != nil:
return nil, invalid("invalid_config")
case u.Scheme == "unix" && u.Host == "" && strings.HasPrefix(u.Path, "/") && len(u.Path) < 200:
case u.Scheme == "tcp" && validHostPort(u.Host) && (u.Path == "" || u.Path == "/"):
default:
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (dockerCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[DockerConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
u, err := url.Parse(c.Host)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
var dial func(ctx context.Context, _, _ string) (net.Conn, error)
if u.Scheme == "unix" {
// The socket controls the checker's own host; shared checkers
// may not use it.
if !s.AllowPrivate {
return Outcome{Error: "this checker does not allow Docker sockets"}
}
dial = func(ctx context.Context, _, _ string) (net.Conn, error) { return d.DialContext(ctx, "unix", u.Path) }
} else {
dial = func(ctx context.Context, _, _ string) (net.Conn, error) { return d.DialContext(ctx, "tcp", u.Host) }
}
client := &http.Client{Transport: &http.Transport{DialContext: dial, DisableKeepAlives: true}}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker/containers/"+url.PathEscape(s.Target)+"/json", nil)
resp, err := client.Do(req)
if err != nil {
var op *net.OpError
if errors.As(err, &op) {
return Outcome{Error: describeNetErr(op)}
}
return Outcome{Error: truncate(err.Error(), 300)}
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
switch {
case resp.StatusCode == http.StatusNotFound:
return Outcome{Error: "no container named " + s.Target}
case resp.StatusCode != http.StatusOK:
var e struct {
Message string `json:"message"`
}
_ = json.Unmarshal(body, &e)
return Outcome{Error: fmt.Sprintf("Docker API answered %d %s", resp.StatusCode, truncate(e.Message, 200))}
}
var info struct {
State struct {
Status string `json:"Status"`
ExitCode int `json:"ExitCode"`
Health *struct {
Status string `json:"Status"`
} `json:"Health"`
} `json:"State"`
}
if err := json.Unmarshal(body, &info); err != nil {
return Outcome{Error: "not a Docker API answer"}
}
st := info.State
switch {
case st.Status == "exited":
return Outcome{Error: fmt.Sprintf("container exited with code %d", st.ExitCode)}
case st.Status != "running":
return Outcome{Error: "container is " + st.Status}
case st.Health != nil && st.Health.Status == "unhealthy":
return Outcome{Error: "container is unhealthy"}
}
return Outcome{OK: true}
}
+90
View File
@@ -0,0 +1,90 @@
package check
import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
)
// dockerAPI serves container states like the Docker Engine API, on a Unix
// socket and on TCP.
func dockerAPI(t *testing.T) (socket, tcp string) {
states := map[string]any{
"web": map[string]any{"Status": "running"},
"api": map[string]any{"Status": "running", "Health": map[string]any{"Status": "healthy"}},
"worker": map[string]any{"Status": "running", "Health": map[string]any{"Status": "unhealthy"}},
"migrate": map[string]any{"Status": "exited", "ExitCode": 3},
"paused-1": map[string]any{"Status": "paused"},
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/containers/"), "/json")
st, ok := states[name]
if !ok {
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "No such container: " + name})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"Name": "/" + name, "State": st})
})
socket = filepath.Join(t.TempDir(), "docker.sock")
l, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewUnstartedServer(h)
srv.Listener = l
srv.Start()
t.Cleanup(srv.Close)
ts := httptest.NewServer(h)
t.Cleanup(ts.Close)
return socket, strings.TrimPrefix(ts.URL, "http://")
}
func TestDockerCheck(t *testing.T) {
socket, tcp := dockerAPI(t)
for _, host := range []string{"unix://" + socket, "tcp://" + tcp} {
cfg := `{"host":"` + host + `"}`
for target, want := range map[string]string{
"web": "",
"api": "",
"worker": "container is unhealthy",
"migrate": "container exited with code 3",
"paused-1": "container is paused",
"gone": "no container named gone",
} {
o := runShort(t, Docker, target, cfg)
if want == "" && !o.OK || want != "" && (o.OK || o.Error != want) {
t.Errorf("%s %s: %+v, want %q", host, target, o, want)
}
}
}
// Shared checkers may use neither their socket nor private addresses.
for _, host := range []string{"unix://" + socket, "tcp://" + tcp} {
c, _ := Validate(Docker, "web", []byte(`{"host":"`+host+`"}`))
if o := Run(t.Context(), Spec{Type: Docker, Target: "web", Timeout: 2 * time.Second, Config: c}); o.OK {
t.Errorf("%s reached by a shared checker", host)
}
}
}
func TestDockerValidate(t *testing.T) {
got, err := Validate(Docker, "web", []byte(`{}`))
if err != nil || string(got) != `{"host":"unix:///var/run/docker.sock"}` {
t.Errorf("default = %s, %v", got, err)
}
for _, tc := range []struct{ target, cfg string }{
{"../etc", `{}`},
{"web", `{"host":"http://docker:2375"}`},
{"web", `{"host":"tcp://docker"}`},
{"web", `{"host":"unix://relative.sock"}`},
} {
if _, err := Validate(Docker, tc.target, []byte(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s) accepted", tc.target, tc.cfg)
}
}
}
+253
View File
@@ -0,0 +1,253 @@
package check
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Game server checks query a server the way game clients list it.
const (
Steam Type = "steam"
Minecraft Type = "minecraft"
)
// GameConfig configures game server checks.
type GameConfig struct {
// Edition is "java" or "bedrock" for Minecraft.
Edition string `json:"edition,omitempty"`
// MinFreeSlots fails the check when fewer player slots are free.
MinFreeSlots int `json:"min_free_slots,omitempty"`
}
type gameCheck struct{ typ Type }
func (g gameCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !validHostPort(target) {
return nil, invalid("invalid_target")
}
var c GameConfig
if err := json.Unmarshal(config, &c); err != nil || c.MinFreeSlots < 0 || c.MinFreeSlots > 10000 {
return nil, invalid("invalid_config")
}
switch {
case g.typ == Minecraft && c.Edition == "":
c.Edition = "java"
case g.typ == Minecraft && c.Edition != "java" && c.Edition != "bedrock",
g.typ == Steam && c.Edition != "":
return nil, invalid("invalid_config")
}
return encode(c), nil
}
// gameStatus is what a server tells about itself.
type gameStatus struct {
Name string
Players, Max int
}
func (g gameCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[GameConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
var st gameStatus
switch {
case g.typ == Steam:
st, err = queryA2S(ctx, d, s.Target)
case c.Edition == "bedrock":
st, err = pingBedrock(ctx, d, s.Target)
default:
st, err = pingJava(ctx, d, s.Target)
}
var op *net.OpError
switch {
case errors.As(err, &op) && op.Timeout(), errors.Is(err, context.DeadlineExceeded):
return Outcome{Error: "no answer from the game server"}
case errors.As(err, &op):
return Outcome{Error: describeNetErr(err)}
case err != nil:
return Outcome{Error: truncate(err.Error(), 300)}
}
if free := st.Max - st.Players; c.MinFreeSlots > 0 && free < c.MinFreeSlots {
return Outcome{Error: fmt.Sprintf("%d of %d slots taken", st.Players, st.Max)}
}
return Outcome{OK: true}
}
// udpExchange sends req and returns the first answer.
func udpExchange(ctx context.Context, conn net.Conn, req []byte) ([]byte, error) {
if _, err := conn.Write(req); err != nil {
return nil, err
}
buf := make([]byte, 1500)
n, err := conn.Read(buf)
if err != nil {
return nil, err
}
return buf[:n], ctx.Err()
}
func deadlineConn(ctx context.Context, d *net.Dialer, network, target string) (net.Conn, error) {
conn, err := d.DialContext(ctx, network, target)
if err != nil {
return nil, err
}
if dl, ok := ctx.Deadline(); ok {
// Leave time to report a silent server before the check's deadline.
_ = conn.SetDeadline(time.Now().Add(time.Until(dl) * 4 / 5))
}
return conn, nil
}
var a2sInfo = append([]byte{0xFF, 0xFF, 0xFF, 0xFF, 'T'}, "Source Engine Query\x00"...)
// queryA2S asks a Steam server for A2S_INFO, answering a challenge if the
// server sends one.
func queryA2S(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
conn, err := deadlineConn(ctx, d, "udp", target)
if err != nil {
return gameStatus{}, err
}
defer func() { _ = conn.Close() }()
resp, err := udpExchange(ctx, conn, a2sInfo)
if err != nil {
return gameStatus{}, err
}
if len(resp) == 9 && resp[4] == 'A' {
resp, err = udpExchange(ctx, conn, append(append([]byte{}, a2sInfo...), resp[5:9]...))
if err != nil {
return gameStatus{}, err
}
}
if len(resp) < 6 || !bytes.Equal(resp[:4], []byte{0xFF, 0xFF, 0xFF, 0xFF}) || resp[4] != 'I' {
return gameStatus{}, errors.New("not a Steam server query answer")
}
r := bytes.NewReader(resp[6:])
cstr := func() string {
var b strings.Builder
for {
c, err := r.ReadByte()
if err != nil || c == 0 {
return b.String()
}
b.WriteByte(c)
}
}
name := cstr()
_, _, _ = cstr(), cstr(), cstr() // map, folder, game
var rest struct {
ID uint16
Players, Max uint8
}
if err := binary.Read(r, binary.LittleEndian, &rest); err != nil {
return gameStatus{}, errors.New("truncated Steam server answer")
}
return gameStatus{Name: name, Players: int(rest.Players), Max: int(rest.Max)}, nil
}
// pingJava does the Minecraft Java Edition server list ping.
func pingJava(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
conn, err := deadlineConn(ctx, d, "tcp", target)
if err != nil {
return gameStatus{}, err
}
defer func() { _ = conn.Close() }()
host, port, _ := net.SplitHostPort(target)
p, _ := strconv.Atoi(port)
var hs bytes.Buffer
hs.WriteByte(0x00)
hs.Write(binary.AppendUvarint(nil, 767)) // protocol version; servers answer any
hs.Write(binary.AppendUvarint(nil, uint64(len(host))))
hs.WriteString(host)
_ = binary.Write(&hs, binary.BigEndian, uint16(p))
hs.WriteByte(0x01) // next state: status
var out []byte
out = binary.AppendUvarint(out, uint64(hs.Len()))
out = append(out, hs.Bytes()...)
out = append(out, 0x01, 0x00) // status request
if _, err := conn.Write(out); err != nil {
return gameStatus{}, err
}
r := bufio.NewReader(conn)
length, err := binary.ReadUvarint(r)
if err != nil {
return gameStatus{}, err
}
// The packet ID is checked first: another protocol's greeting would
// otherwise leave us waiting for the rest of an imagined packet.
if id, err := r.ReadByte(); err != nil || id != 0x00 || length < 2 || length > 1<<20 {
return gameStatus{}, errors.New("not a Minecraft server")
}
packet := make([]byte, length-1)
if _, err := io.ReadFull(r, packet); err != nil {
return gameStatus{}, err
}
pr := bytes.NewReader(packet)
n, err := binary.ReadUvarint(pr)
if err != nil || n > uint64(pr.Len()) {
return gameStatus{}, errors.New("not a Minecraft server")
}
var status struct {
Players struct {
Max int `json:"max"`
Online int `json:"online"`
} `json:"players"`
Description json.RawMessage `json:"description"`
}
if err := json.NewDecoder(io.LimitReader(pr, int64(n))).Decode(&status); err != nil {
return gameStatus{}, errors.New("not a Minecraft server")
}
return gameStatus{Players: status.Players.Online, Max: status.Players.Max}, nil
}
var raknetMagic = []byte{0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78}
// pingBedrock sends a RakNet unconnected ping, which Bedrock servers
// answer with their MOTD line.
func pingBedrock(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
conn, err := deadlineConn(ctx, d, "udp", target)
if err != nil {
return gameStatus{}, err
}
defer func() { _ = conn.Close() }()
req := []byte{0x01}
req = binary.BigEndian.AppendUint64(req, uint64(time.Now().UnixMilli()))
req = append(req, raknetMagic...)
guid := make([]byte, 8)
_, _ = rand.Read(guid)
req = append(req, guid...)
resp, err := udpExchange(ctx, conn, req)
if err != nil {
return gameStatus{}, err
}
// 0x1C, time (8), server GUID (8), magic (16), length (2), MOTD.
if len(resp) < 35 || resp[0] != 0x1C || !bytes.Equal(resp[17:33], raknetMagic) {
return gameStatus{}, errors.New("not a Minecraft Bedrock server")
}
motd := resp[35:]
if n := int(binary.BigEndian.Uint16(resp[33:35])); n < len(motd) {
motd = motd[:n]
}
// MCPE;name;protocol;version;online;max;...
f := strings.Split(string(motd), ";")
if len(f) < 6 {
return gameStatus{}, errors.New("not a Minecraft Bedrock server")
}
online, _ := strconv.Atoi(f[4])
maxPlayers, _ := strconv.Atoi(f[5])
return gameStatus{Name: f[1], Players: online, Max: maxPlayers}, nil
}
+136
View File
@@ -0,0 +1,136 @@
package check
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"io"
"net"
"testing"
)
func udpServer(t *testing.T, answer func(req []byte) []byte) string {
t.Helper()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pc.Close() })
go func() {
buf := make([]byte, 1500)
for {
n, addr, err := pc.ReadFrom(buf)
if err != nil {
return
}
if out := answer(append([]byte{}, buf[:n]...)); out != nil {
_, _ = pc.WriteTo(out, addr)
}
}
}()
return pc.LocalAddr().String()
}
// steamServer answers A2S_INFO after a challenge, like current servers.
func steamServer(t *testing.T, players, maxPlayers byte) string {
challenge := []byte{0x11, 0x22, 0x33, 0x44}
return udpServer(t, func(req []byte) []byte {
if !bytes.HasPrefix(req, a2sInfo) {
return nil
}
if !bytes.Equal(req[len(a2sInfo):], challenge) {
return append([]byte{0xFF, 0xFF, 0xFF, 0xFF, 'A'}, challenge...)
}
out := []byte{0xFF, 0xFF, 0xFF, 0xFF, 'I', 17}
for _, s := range []string{"Test Server", "de_dust2", "csgo", "Counter-Strike"} {
out = append(append(out, s...), 0)
}
out = binary.LittleEndian.AppendUint16(out, 730)
return append(out, players, maxPlayers, 0, 'd', 'l', 0, 1)
})
}
func javaServer(t *testing.T, online, maxPlayers int) string {
l := listen(t)
go func() {
for {
conn, err := l.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = conn.Close() }()
r := bufio.NewReader(conn)
for range 2 { // handshake, status request
n, err := binary.ReadUvarint(r)
if err != nil {
return
}
if _, err := io.CopyN(io.Discard, r, int64(n)); err != nil {
return
}
}
status, _ := json.Marshal(map[string]any{
"version": map[string]any{"name": "1.21.4", "protocol": 769},
"players": map[string]any{"max": maxPlayers, "online": online},
"description": map[string]any{"text": "A Minecraft Server"},
})
body := append([]byte{0x00}, binary.AppendUvarint(nil, uint64(len(status)))...)
body = append(body, status...)
_, _ = conn.Write(append(binary.AppendUvarint(nil, uint64(len(body))), body...))
}()
}
}()
return l.Addr().String()
}
func bedrockServer(t *testing.T) string {
return udpServer(t, func(req []byte) []byte {
if len(req) < 25 || req[0] != 0x01 || !bytes.Equal(req[9:25], raknetMagic) {
return nil
}
motd := "MCPE;Dedicated Server;766;1.21.50;3;10;1234;Bedrock level;Survival;1;19132;19133;"
out := append([]byte{0x1C}, req[1:9]...)
out = binary.BigEndian.AppendUint64(out, 42)
out = append(out, raknetMagic...)
out = binary.BigEndian.AppendUint16(out, uint16(len(motd)))
return append(out, motd...)
})
}
func TestGameChecks(t *testing.T) {
expectOutcomes(t, Steam, steamServer(t, 3, 24), map[string]string{
`{}`: "",
`{"min_free_slots":21}`: "",
`{"min_free_slots":22}`: "3 of 24 slots taken",
})
expectOutcomes(t, Minecraft, javaServer(t, 19, 20), map[string]string{
`{}`: "",
`{"edition":"java","min_free_slots":2}`: "19 of 20 slots taken",
})
expectOutcomes(t, Minecraft, bedrockServer(t), map[string]string{
`{"edition":"bedrock"}`: "",
`{"edition":"bedrock","min_free_slots":8}`: "3 of 10 slots taken",
})
// A port that answers nothing, and one speaking another protocol.
silent := udpServer(t, func([]byte) []byte { return nil })
expectOutcomes(t, Steam, silent, map[string]string{`{}`: "no answer from the game server"})
expectOutcomes(t, Minecraft, steamServer(t, 0, 1), map[string]string{`{"edition":"bedrock"}`: "no answer"})
expectOutcomes(t, Minecraft, smtpServer(t, nil), map[string]string{`{}`: "not a Minecraft server"})
}
func TestGameValidate(t *testing.T) {
for _, tc := range []struct {
typ Type
cfg string
}{
{Minecraft, `{"edition":"pocket"}`},
{Steam, `{"edition":"java"}`},
{Steam, `{"min_free_slots":-1}`},
} {
if _, err := Validate(tc.typ, "game.example.com:27015", []byte(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s) accepted", tc.typ, tc.cfg)
}
}
}
+301
View File
@@ -0,0 +1,301 @@
package check
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"strings"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/pkg/kmsg"
"github.com/twmb/franz-go/pkg/sasl"
"github.com/twmb/franz-go/pkg/sasl/plain"
"github.com/twmb/franz-go/pkg/sasl/scram"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Message broker checks sign in to the broker; optionally they look at a
// topic or queue.
const (
MQTT Type = "mqtt"
Kafka Type = "kafka"
RabbitMQ Type = "rabbitmq"
)
// BrokerConfig configures message broker checks. Password is a secret.
type BrokerConfig struct {
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
// TLS is "disable", "require" (encrypt without verifying) or "verify".
TLS string `json:"tls"`
// Topic is, for MQTT, subscribed to: a message must arrive (retained
// messages count) and contain Expect if set. For Kafka it must exist
// with a leader for every partition.
Topic string `json:"topic,omitempty"`
Expect string `json:"expect,omitempty"`
// Message is produced to the Kafka topic when set.
Message string `json:"message,omitempty"`
// SASL is the Kafka mechanism: "plain", "scram-sha-256" or
// "scram-sha-512"; used when User is set.
SASL string `json:"sasl,omitempty"`
// Vhost and Queue are for RabbitMQ; the queue must exist.
Vhost string `json:"vhost,omitempty"`
Queue string `json:"queue,omitempty"`
}
type brokerCheck struct{ typ Type }
func (b brokerCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
targets := strings.Split(target, ",")
if len(targets) > 1 && b.typ != Kafka || len(targets) > 5 {
return nil, invalid("invalid_target")
}
for _, t := range targets {
if !validHostPort(strings.TrimSpace(t)) {
return nil, invalid("invalid_target")
}
}
c := BrokerConfig{TLS: "disable"}
if err := json.Unmarshal(config, &c); err != nil {
return nil, invalid("invalid_config")
}
if c.TLS == "" {
c.TLS = "disable"
}
if !validTLSMode(c.TLS) || len(c.User) > 200 || len(c.Password) > 500 || len(c.Topic) > 250 ||
len(c.Expect) > 500 || len(c.Message) > 1000 || len(c.Vhost) > 200 || len(c.Queue) > 250 {
return nil, invalid("invalid_config")
}
only := func(ok bool, fields ...string) bool {
for _, f := range fields {
if f != "" && !ok {
return false
}
}
return true
}
valid := only(b.typ == MQTT || b.typ == Kafka, c.Topic) &&
only(b.typ == MQTT, c.Expect) &&
only(b.typ == Kafka, c.Message, c.SASL) &&
only(b.typ == RabbitMQ, c.Vhost, c.Queue)
if !valid || c.Expect != "" && c.Topic == "" || c.Message != "" && c.Topic == "" {
return nil, invalid("invalid_config")
}
if b.typ == MQTT && strings.ContainsAny(c.Topic, "+#") {
return nil, invalid("invalid_config")
}
if b.typ == Kafka && c.User != "" {
if c.SASL == "" {
c.SASL = "plain"
}
if c.SASL != "plain" && c.SASL != "scram-sha-256" && c.SASL != "scram-sha-512" {
return nil, invalid("invalid_config")
}
}
return encode(c), nil
}
func (b brokerCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[BrokerConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
dial := func(ctx context.Context, addr string) (net.Conn, error) {
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil || c.TLS == "disable" {
return conn, err
}
tc := tls.Client(conn, tlsFor(c.TLS, addr))
if err := tc.HandshakeContext(ctx); err != nil {
_ = conn.Close()
return nil, err
}
return tc, nil
}
switch b.typ {
case MQTT:
err = checkMQTT(ctx, s.Target, c, dial)
case Kafka:
err = checkKafka(ctx, s.Target, c, dial)
case RabbitMQ:
err = checkRabbitMQ(ctx, s.Target, c, dial)
}
if err != nil {
return Outcome{Error: redact(err, c.Password)}
}
return Outcome{OK: true}
}
type dialFunc func(ctx context.Context, addr string) (net.Conn, error)
func checkMQTT(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error {
id := make([]byte, 6)
_, _ = rand.Read(id)
opts := mqtt.NewClientOptions().AddBroker("tcp://" + target).
SetClientID("uptimesebi-" + hex.EncodeToString(id)).
SetUsername(c.User).SetPassword(c.Password).
SetCleanSession(true).SetAutoReconnect(false).SetConnectRetry(false).
SetConnectTimeout(timeoutOf(ctx)).
SetCustomOpenConnectionFn(func(uri *url.URL, _ mqtt.ClientOptions) (net.Conn, error) {
return dial(ctx, uri.Host)
})
client := mqtt.NewClient(opts)
if err := wait(ctx, client.Connect()); err != nil {
return err
}
defer client.Disconnect(0)
if c.Topic == "" {
return nil
}
got := make(chan string, 16)
sub := client.Subscribe(c.Topic, 0, func(_ mqtt.Client, m mqtt.Message) {
select {
case got <- string(m.Payload()):
default:
}
})
if err := wait(ctx, sub); err != nil {
return err
}
// Stop waiting before the check's deadline, so the result says what
// was missing instead of a bare timeout.
ctx, cancel := context.WithTimeout(ctx, timeoutOf(ctx)*4/5)
defer cancel()
var last string
for {
select {
case msg := <-got:
if c.Expect == "" || strings.Contains(msg, c.Expect) {
return nil
}
last = msg
case <-ctx.Done():
if last != "" {
return fmt.Errorf("message %q does not contain %q", truncate(last, 100), truncate(c.Expect, 100))
}
return fmt.Errorf("no message on %s", c.Topic)
}
}
}
// wait waits for an MQTT operation until ctx ends.
func wait(ctx context.Context, t mqtt.Token) error {
select {
case <-t.Done():
return t.Error()
case <-ctx.Done():
return errors.New("broker did not answer in time")
}
}
func checkKafka(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error {
seeds := strings.Split(target, ",")
for i := range seeds {
seeds[i] = strings.TrimSpace(seeds[i])
}
opts := []kgo.Opt{
kgo.SeedBrokers(seeds...),
kgo.Dialer(func(ctx context.Context, _, host string) (net.Conn, error) { return dial(ctx, host) }),
kgo.RequestRetries(0),
kgo.ProducerLinger(0),
kgo.RecordDeliveryTimeout(timeoutOf(ctx)),
}
if c.User != "" {
var m sasl.Mechanism
switch c.SASL {
case "scram-sha-256":
m = scram.Auth{User: c.User, Pass: c.Password}.AsSha256Mechanism()
case "scram-sha-512":
m = scram.Auth{User: c.User, Pass: c.Password}.AsSha512Mechanism()
default:
m = plain.Auth{User: c.User, Pass: c.Password}.AsMechanism()
}
opts = append(opts, kgo.SASL(m))
}
client, err := kgo.NewClient(opts...)
if err != nil {
return err
}
defer client.Close()
req := kmsg.NewPtrMetadataRequest()
if c.Topic != "" {
t := kmsg.NewMetadataRequestTopic()
t.Topic = kmsg.StringPtr(c.Topic)
req.Topics = append(req.Topics, t)
}
resp, err := req.RequestWith(ctx, client)
if err != nil {
return err
}
if len(resp.Brokers) == 0 {
return errors.New("cluster reports no brokers")
}
if c.Topic == "" {
return nil
}
if len(resp.Topics) == 0 {
return fmt.Errorf("topic %s not found", c.Topic)
}
topic := resp.Topics[0]
if err := kerr.ErrorForCode(topic.ErrorCode); err != nil {
return fmt.Errorf("topic %s: %w", c.Topic, err)
}
for _, p := range topic.Partitions {
if p.Leader < 0 {
return fmt.Errorf("topic %s: partition %d has no leader", c.Topic, p.Partition)
}
}
if c.Message != "" {
rec := &kgo.Record{Topic: c.Topic, Value: []byte(c.Message), Timestamp: time.Now()}
if err := client.ProduceSync(ctx, rec).FirstErr(); err != nil {
return fmt.Errorf("producing to %s: %w", c.Topic, err)
}
}
return nil
}
func checkRabbitMQ(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error {
vhost := c.Vhost
if vhost == "" {
vhost = "/"
}
user, password := c.User, c.Password
if user == "" {
user, password = "guest", "guest"
}
// TLS is done by dial, so the URL always names plain AMQP.
conn, err := amqp.DialConfig("amqp://"+target+"/", amqp.Config{
SASL: []amqp.Authentication{&amqp.PlainAuth{Username: user, Password: password}},
Vhost: vhost,
Heartbeat: 10 * time.Second,
Dial: func(_, addr string) (net.Conn, error) { return dial(ctx, addr) },
})
if err != nil {
return err
}
defer func() { _ = conn.Close() }()
ch, err := conn.Channel()
if err != nil {
return err
}
defer func() { _ = ch.Close() }()
if c.Queue != "" {
if _, err := ch.QueueDeclarePassive(c.Queue, false, false, false, false, nil); err != nil {
return fmt.Errorf("queue %s: %w", c.Queue, err)
}
}
return nil
}
+158
View File
@@ -0,0 +1,158 @@
package check
import (
"context"
"errors"
"io"
"log/slog"
"net"
"strings"
"testing"
mqttserver "github.com/mochi-mqtt/server/v2"
"github.com/mochi-mqtt/server/v2/hooks/auth"
"github.com/mochi-mqtt/server/v2/listeners"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/pkg/kmsg"
)
// mqttBroker starts an in-process broker that accepts check/checkpw and
// holds a retained status message.
func mqttBroker(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := l.Addr().String()
_ = l.Close()
srv := mqttserver.New(&mqttserver.Options{InlineClient: true, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
ledger := &auth.Ledger{
Auth: auth.AuthRules{{Username: "check", Password: "checkpw", Allow: true}},
ACL: auth.ACLRules{{Filters: auth.Filters{"#": auth.ReadWrite}}},
}
if err := srv.AddHook(new(auth.Hook), &auth.Options{Ledger: ledger}); err != nil {
t.Fatal(err)
}
if err := srv.AddListener(listeners.NewTCP(listeners.Config{ID: "t", Address: addr})); err != nil {
t.Fatal(err)
}
if err := srv.Serve(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = srv.Close() })
if err := srv.Publish("plant/pump", []byte(`{"state":"running"}`), true, 0); err != nil {
t.Fatal(err)
}
return addr
}
func TestBrokerChecks(t *testing.T) {
tests := []struct {
name string
typ Type
target func(*testing.T) string
good []map[string]any
bad map[string]any
// fails are working credentials with a failing condition.
fails map[string]string
}{
{"mqtt", MQTT, mqttBroker,
[]map[string]any{
{"user": "check", "password": "checkpw"},
{"user": "check", "password": "checkpw", "topic": "plant/pump", "expect": "running"},
},
map[string]any{"user": "check", "password": "wrong-pw-123"},
map[string]string{
`{"user":"check","password":"checkpw","topic":"plant/pump","expect":"stopped"}`: `does not contain "stopped"`,
`{"user":"check","password":"checkpw","topic":"plant/silent"}`: "no message on plant/silent",
}},
{"rabbitmq", RabbitMQ, func(t *testing.T) string { return dbTarget(t, "UPTIME_TEST_RABBITMQ_ADDR") },
[]map[string]any{{"user": "check", "password": "checkpw"}},
map[string]any{"user": "check", "password": "wrong-pw-123"},
map[string]string{
`{"user":"check","password":"checkpw","queue":"no-such-queue"}`: "queue no-such-queue",
`{"user":"check","password":"checkpw","vhost":"nope"}`: "vhost nope not found",
}},
{"kafka", Kafka, kafkaWithTopic,
[]map[string]any{
{},
{"topic": "uptimesebi-check", "message": "probe"},
{"topic": "uptimesebi-check"},
},
nil,
map[string]string{
`{"topic":"no-such-topic-for-sure"}`: "no-such-topic-for-sure",
}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
target := tc.target(t)
for _, cfg := range tc.good {
if o := runDB(t, tc.typ, target, cfg, true); !o.OK {
t.Errorf("%v: %+v", cfg, o)
}
}
if tc.bad != nil {
o := runDB(t, tc.typ, target, tc.bad, true)
if o.OK || strings.Contains(o.Error, "wrong-pw-123") {
t.Errorf("wrong password: %+v", o)
}
}
for cfg, want := range tc.fails {
o := runShort(t, tc.typ, target, cfg)
if o.OK || !strings.Contains(o.Error, want) {
t.Errorf("%s: %+v, want error containing %q", cfg, o, want)
}
}
if o := runDB(t, tc.typ, target, tc.good[0], false); o.OK || !strings.Contains(o.Error, "non-public") && !strings.Contains(o.Error, "timeout") && !strings.Contains(o.Error, "in time") {
t.Errorf("private address reached without permission: %+v", o)
}
})
}
}
// kafkaWithTopic returns the test Kafka with the topic uptimesebi-check.
func kafkaWithTopic(t *testing.T) string {
addr := dbTarget(t, "UPTIME_TEST_KAFKA_ADDR")
client, err := kgo.NewClient(kgo.SeedBrokers(addr))
if err != nil {
t.Fatal(err)
}
defer client.Close()
req := kmsg.NewPtrCreateTopicsRequest()
topic := kmsg.NewCreateTopicsRequestTopic()
topic.Topic, topic.NumPartitions, topic.ReplicationFactor = "uptimesebi-check", 1, 1
req.Topics = append(req.Topics, topic)
resp, err := req.RequestWith(context.Background(), client)
if err != nil {
t.Fatal(err)
}
if err := kerr.ErrorForCode(resp.Topics[0].ErrorCode); err != nil && !errors.Is(err, kerr.TopicAlreadyExists) {
t.Fatal(err)
}
return addr
}
func TestBrokerValidate(t *testing.T) {
for _, tc := range []struct {
typ Type
target, cfg string
}{
{MQTT, "a:1883,b:1883", `{}`},
{MQTT, "broker:1883", `{"topic":"plant/#"}`},
{MQTT, "broker:1883", `{"expect":"ok"}`},
{MQTT, "broker:1883", `{"queue":"q"}`},
{Kafka, "a:9092", `{"user":"u","sasl":"gssapi"}`},
{Kafka, "a:9092", `{"message":"m"}`},
{RabbitMQ, "mq:5672", `{"topic":"t"}`},
} {
if _, err := Validate(tc.typ, tc.target, []byte(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg)
}
}
if _, err := Validate(Kafka, "a:9092, b:9092", []byte(`{"user":"u","password":"p"}`)); err != nil {
t.Errorf("Kafka with two brokers: %v", err)
}
}
+346
View File
@@ -0,0 +1,346 @@
package check
import (
"context"
"crypto/hmac"
"crypto/md5" //nolint:gosec // RADIUS defines Message-Authenticator as HMAC-MD5
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"math/big"
"net"
"net/smtp"
"regexp"
"strconv"
"strings"
"github.com/gosnmp/gosnmp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"layeh.com/radius"
"layeh.com/radius/rfc2865"
"layeh.com/radius/rfc2869"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Protocol checks speak a service's own protocol beyond a TCP connect.
const (
GRPC Type = "grpc"
SMTP Type = "smtp"
RADIUS Type = "radius"
SNMP Type = "snmp"
)
// GRPCConfig configures a check against the standard gRPC health service.
type GRPCConfig struct {
// Service is asked about; empty asks about the server as a whole.
Service string `json:"service,omitempty"`
TLS string `json:"tls"`
}
type grpcCheck struct{}
func (grpcCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !validHostPort(target) {
return nil, invalid("invalid_target")
}
c := GRPCConfig{TLS: "verify"}
if err := json.Unmarshal(config, &c); err != nil || !validTLSMode(c.TLS) || len(c.Service) > 200 {
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (grpcCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[GRPCConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
creds := insecure.NewCredentials()
if c.TLS != "disable" {
creds = credentials.NewTLS(tlsFor(c.TLS, s.Target))
}
conn, err := grpc.NewClient("passthrough:///"+s.Target,
grpc.WithTransportCredentials(creds),
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return d.DialContext(ctx, "tcp", addr)
}))
if err != nil {
return Outcome{Error: truncate(err.Error(), 300)}
}
defer func() { _ = conn.Close() }()
resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: c.Service})
if err != nil {
return Outcome{Error: truncate(err.Error(), 300)}
}
if st := resp.GetStatus(); st != healthpb.HealthCheckResponse_SERVING {
return Outcome{Error: "health status " + st.String()}
}
return Outcome{OK: true}
}
// SMTPConfig configures a mail server check.
type SMTPConfig struct {
// TLS "disable" only greets; otherwise STARTTLS must succeed, or, with
// ImplicitTLS (port 465), the connection starts encrypted.
TLS string `json:"tls"`
ImplicitTLS bool `json:"implicit_tls,omitempty"`
}
type smtpCheck struct{}
func (smtpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !validHostPort(target) {
return nil, invalid("invalid_target")
}
c := SMTPConfig{TLS: "verify"}
if err := json.Unmarshal(config, &c); err != nil || !validTLSMode(c.TLS) || c.ImplicitTLS && c.TLS == "disable" {
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (smtpCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[SMTPConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
conn, err := netguard.Dialer(s.AllowPrivate, s.Timeout).DialContext(ctx, "tcp", s.Target)
if err != nil {
return Outcome{Error: describeNetErr(err)}
}
defer func() { _ = conn.Close() }()
if dl, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(dl)
}
if c.ImplicitTLS {
tc := tls.Client(conn, tlsFor(c.TLS, s.Target))
if err := tc.HandshakeContext(ctx); err != nil {
return Outcome{Error: truncate(err.Error(), 300)}
}
conn = tc
}
host, _, _ := net.SplitHostPort(s.Target)
client, err := smtp.NewClient(conn, host)
if err != nil {
return Outcome{Error: "greeting: " + truncate(err.Error(), 300)}
}
if err := client.Hello("uptimesebi"); err != nil {
return Outcome{Error: "EHLO: " + truncate(err.Error(), 300)}
}
if c.TLS != "disable" && !c.ImplicitTLS {
if ok, _ := client.Extension("STARTTLS"); !ok {
return Outcome{Error: "server does not offer STARTTLS"}
}
if err := client.StartTLS(tlsFor(c.TLS, s.Target)); err != nil {
return Outcome{Error: "STARTTLS: " + truncate(err.Error(), 300)}
}
}
_ = client.Quit()
return Outcome{OK: true}
}
// RADIUSConfig configures an authentication check. Secret and Password
// are secrets.
type RADIUSConfig struct {
Secret string `json:"secret,omitempty"`
User string `json:"user"`
Password string `json:"password,omitempty"`
NASIdentifier string `json:"nas_identifier,omitempty"`
}
type radiusCheck struct{}
func (radiusCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !validHostPort(target) {
return nil, invalid("invalid_target")
}
var c RADIUSConfig
if err := json.Unmarshal(config, &c); err != nil || c.User == "" || len(c.User) > 200 ||
len(c.Secret) > 200 || len(c.Password) > 128 || len(c.NASIdentifier) > 200 {
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (radiusCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[RADIUSConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
if c.Secret == "" {
return Outcome{Error: "no shared secret configured"}
}
p := radius.New(radius.CodeAccessRequest, []byte(c.Secret))
_ = rfc2865.UserName_SetString(p, c.User)
_ = rfc2865.UserPassword_SetString(p, c.Password)
nas := c.NASIdentifier
if nas == "" {
nas = "uptimesebi"
}
_ = rfc2865.NASIdentifier_SetString(p, nas)
if err := signRADIUS(p); err != nil {
return Outcome{Error: err.Error()}
}
client := radius.Client{Dialer: *netguard.Dialer(s.AllowPrivate, s.Timeout), Retry: timeoutOf(ctx) / 3, MaxPacketErrors: 1}
resp, err := client.Exchange(ctx, p, s.Target)
switch {
case errors.Is(err, context.DeadlineExceeded):
return Outcome{Error: "no answer from the server"}
case err != nil:
var nonAuth *radius.NonAuthenticResponseError
if errors.As(err, &nonAuth) {
return Outcome{Error: "answer not signed with the shared secret"}
}
return Outcome{Error: redact(err, c.Secret, c.Password)}
}
switch resp.Code {
case radius.CodeAccessAccept, radius.CodeAccessChallenge:
return Outcome{OK: true}
case radius.CodeAccessReject:
msg := "access rejected"
if reply := rfc2865.ReplyMessage_GetString(resp); reply != "" {
msg += ": " + truncate(reply, 200)
}
return Outcome{Error: msg}
}
return Outcome{Error: "unexpected answer " + resp.Code.String()}
}
// signRADIUS adds a Message-Authenticator, which servers protecting
// against BlastRADIUS require.
func signRADIUS(p *radius.Packet) error {
if err := rfc2869.MessageAuthenticator_Set(p, make([]byte, md5.Size)); err != nil {
return err
}
raw, err := p.Encode()
if err != nil {
return err
}
mac := hmac.New(md5.New, p.Secret)
mac.Write(raw)
return rfc2869.MessageAuthenticator_Set(p, mac.Sum(nil))
}
// SNMPConfig configures a check reading one OID. Community is a secret.
type SNMPConfig struct {
// Version is "1" or "2c".
Version string `json:"version"`
Community string `json:"community,omitempty"`
OID string `json:"oid"`
// Condition compares the value with Value: "" (any value), "eq", "ne",
// "contains", or numerically "gt", "ge", "lt", "le".
Condition string `json:"condition,omitempty"`
Value string `json:"value,omitempty"`
}
var oidPattern = regexp.MustCompile(`^\.?[0-9]+(\.[0-9]+){1,127}$`)
type snmpCheck struct{}
func (snmpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !validHostPort(target) {
return nil, invalid("invalid_target")
}
c := SNMPConfig{Version: "2c"}
if err := json.Unmarshal(config, &c); err != nil || !oidPattern.MatchString(c.OID) || len(c.Community) > 200 || len(c.Value) > 500 {
return nil, invalid("invalid_config")
}
if c.Version != "1" && c.Version != "2c" {
return nil, invalid("invalid_config")
}
switch c.Condition {
case "":
c.Value = ""
case "eq", "ne", "contains":
case "gt", "ge", "lt", "le":
if _, ok := new(big.Float).SetString(c.Value); !ok {
return nil, invalid("invalid_config")
}
default:
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (snmpCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[SNMPConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
host, port, _ := net.SplitHostPort(s.Target)
p, _ := strconv.Atoi(port)
g := &gosnmp.GoSNMP{
Target: host, Port: uint16(p), Transport: "udp", Community: c.Community, Version: gosnmp.Version2c,
// Give up before the check's deadline to say why.
Timeout: timeoutOf(ctx) * 4 / 5, Retries: 0, Context: ctx, MaxOids: 1,
Control: netguard.Dialer(s.AllowPrivate, s.Timeout).Control,
}
if c.Community == "" {
g.Community = "public"
}
if c.Version == "1" {
g.Version = gosnmp.Version1
}
if err := g.Connect(); err != nil {
return Outcome{Error: describeNetErr(err)}
}
defer func() { _ = g.Conn.Close() }()
resp, err := g.Get([]string{c.OID})
if err != nil && strings.Contains(err.Error(), "timeout") {
// Agents silently drop requests with a wrong community.
return Outcome{Error: "no answer from the agent; is the community or version right?"}
}
if err != nil {
return Outcome{Error: redact(err, c.Community)}
}
if resp.Error != gosnmp.NoError {
return Outcome{Error: "agent answered " + resp.Error.String()}
}
if len(resp.Variables) == 0 {
return Outcome{Error: "agent returned no value"}
}
v := resp.Variables[0]
var got string
switch v.Type {
case gosnmp.NoSuchObject, gosnmp.NoSuchInstance, gosnmp.EndOfMibView, gosnmp.Null:
return Outcome{Error: c.OID + " does not exist on the agent"}
case gosnmp.OctetString:
b, _ := v.Value.([]byte)
got = string(b)
default:
got = fmt.Sprint(v.Value)
if n := gosnmp.ToBigInt(v.Value); n != nil && v.Type != gosnmp.ObjectIdentifier && v.Type != gosnmp.IPAddress {
got = n.String()
}
}
if !snmpMatches(c.Condition, got, c.Value) {
return Outcome{Error: fmt.Sprintf("value %q does not satisfy %s %q", truncate(got, 100), c.Condition, truncate(c.Value, 100))}
}
return Outcome{OK: true}
}
func snmpMatches(cond, got, want string) bool {
switch cond {
case "eq":
return got == want
case "ne":
return got != want
case "contains":
return strings.Contains(got, want)
case "gt", "ge", "lt", "le":
a, ok1 := new(big.Float).SetString(strings.TrimSpace(got))
b, ok2 := new(big.Float).SetString(want)
if !ok1 || !ok2 {
return false
}
r := a.Cmp(b)
return cond == "gt" && r > 0 || cond == "ge" && r >= 0 || cond == "lt" && r < 0 || cond == "le" && r <= 0
}
return true
}
+280
View File
@@ -0,0 +1,280 @@
package check
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"net"
"strings"
"testing"
"time"
"github.com/gosnmp/gosnmp"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"layeh.com/radius"
"layeh.com/radius/rfc2865"
)
func listen(t *testing.T) net.Listener {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = l.Close() })
return l
}
func selfSigned(t *testing.T) tls.Certificate {
t.Helper()
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "mail.test"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}
func expectOutcomes(t *testing.T, typ Type, target string, cases map[string]string) {
t.Helper()
for cfg, want := range cases {
o := runShort(t, typ, target, cfg)
switch {
case want == "" && !o.OK:
t.Errorf("%s %s: %+v", typ, cfg, o)
case want != "" && (o.OK || !strings.Contains(o.Error, want)):
t.Errorf("%s %s: %+v, want error containing %q", typ, cfg, o, want)
}
}
}
func TestGRPCCheck(t *testing.T) {
l := listen(t)
srv := grpc.NewServer()
hs := health.NewServer()
hs.SetServingStatus("shop", healthpb.HealthCheckResponse_SERVING)
hs.SetServingStatus("billing", healthpb.HealthCheckResponse_NOT_SERVING)
healthpb.RegisterHealthServer(srv, hs)
go func() { _ = srv.Serve(l) }()
t.Cleanup(srv.Stop)
expectOutcomes(t, GRPC, l.Addr().String(), map[string]string{
`{"tls":"disable"}`: "",
`{"tls":"disable","service":"shop"}`: "",
`{"tls":"disable","service":"billing"}`: "NOT_SERVING",
`{"tls":"disable","service":"unknown"}`: "NotFound",
`{"tls":"require","service":"shop"}`: "Unavailable",
})
}
// smtpServer answers like a mail server, offering STARTTLS if cert is set.
func smtpServer(t *testing.T, cert *tls.Certificate) string {
l := listen(t)
go func() {
for {
conn, err := l.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer func() { _ = conn.Close() }()
r := bufio.NewReader(conn)
write := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) }
write("220 mail.test ESMTP")
encrypted := false
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
switch cmd := strings.ToUpper(strings.Fields(line + " x")[0]); {
case cmd == "EHLO" && cert != nil && !encrypted:
write("250-mail.test")
write("250 STARTTLS")
case cmd == "EHLO":
write("250 mail.test")
case cmd == "STARTTLS":
write("220 go ahead")
tc := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{*cert}})
if tc.Handshake() != nil {
return
}
conn, r, encrypted = tc, bufio.NewReader(tc), true
case cmd == "QUIT":
write("221 bye")
return
default:
write("250 ok")
}
}
}(conn)
}
}()
return l.Addr().String()
}
func TestSMTPCheck(t *testing.T) {
cert := selfSigned(t)
expectOutcomes(t, SMTP, smtpServer(t, &cert), map[string]string{
`{"tls":"disable"}`: "",
`{"tls":"require"}`: "",
`{"tls":"verify"}`: "certificate",
})
expectOutcomes(t, SMTP, smtpServer(t, nil), map[string]string{
`{"tls":"disable"}`: "",
`{"tls":"require"}`: "does not offer STARTTLS",
})
// Implicit TLS (SMTPS).
l := listen(t)
tl := tls.NewListener(l, &tls.Config{Certificates: []tls.Certificate{cert}})
go func() {
for {
conn, err := tl.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = conn.Close() }()
_, _ = conn.Write([]byte("220 mail.test\r\n"))
r := bufio.NewReader(conn)
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
_, _ = conn.Write([]byte("250 ok\r\n"))
if strings.HasPrefix(line, "QUIT") {
return
}
}
}()
}
}()
expectOutcomes(t, SMTP, l.Addr().String(), map[string]string{`{"tls":"require","implicit_tls":true}`: ""})
}
func TestRADIUSCheck(t *testing.T) {
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := radius.PacketServer{
SecretSource: radius.StaticSecretSource([]byte("shared-s3cret")),
Handler: radius.HandlerFunc(func(w radius.ResponseWriter, r *radius.Request) {
code := radius.CodeAccessReject
if rfc2865.UserName_GetString(r.Packet) == "probe" && rfc2865.UserPassword_GetString(r.Packet) == "probe-pw" {
code = radius.CodeAccessAccept
}
resp := r.Response(code)
if code == radius.CodeAccessReject {
_ = rfc2865.ReplyMessage_SetString(resp, "bad credentials")
}
_ = w.Write(resp)
}),
}
go func() { _ = srv.Serve(pc) }()
t.Cleanup(func() { _ = pc.Close() })
expectOutcomes(t, RADIUS, pc.LocalAddr().String(), map[string]string{
`{"secret":"shared-s3cret","user":"probe","password":"probe-pw"}`: "",
`{"secret":"shared-s3cret","user":"probe","password":"wrong-pw-123"}`: "access rejected: bad credentials",
`{"secret":"wrong-secret","user":"probe","password":"probe-pw"}`: "not signed with the shared secret",
})
}
// snmpAgent answers GET requests with community s3cret.
func snmpAgent(t *testing.T) string {
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pc.Close() })
values := map[string]gosnmp.SnmpPDU{
".1.3.6.1.2.1.1.5.0": {Type: gosnmp.OctetString, Value: []byte("core-sw-1")},
".1.3.6.1.2.1.2.1.0": {Type: gosnmp.Integer, Value: 48},
}
go func() {
buf := make([]byte, 65535)
for {
n, addr, err := pc.ReadFrom(buf)
if err != nil {
return
}
req, err := (&gosnmp.GoSNMP{}).SnmpDecodePacket(buf[:n])
if err != nil || req.Community != "s3cret" || len(req.Variables) == 0 {
continue
}
name := req.Variables[0].Name
v, ok := values[name]
if !ok {
v = gosnmp.SnmpPDU{Type: gosnmp.NoSuchObject}
}
v.Name = name
resp := &gosnmp.SnmpPacket{Version: req.Version, Community: req.Community, PDUType: gosnmp.GetResponse, RequestID: req.RequestID, Variables: []gosnmp.SnmpPDU{v}}
out, err := resp.MarshalMsg()
if err == nil {
_, _ = pc.WriteTo(out, addr)
}
}
}()
return pc.LocalAddr().String()
}
func TestSNMPCheck(t *testing.T) {
expectOutcomes(t, SNMP, snmpAgent(t), map[string]string{
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0"}`: "",
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0","condition":"eq","value":"core-sw-1"}`: "",
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0","condition":"contains","value":"sw"}`: "",
`{"community":"s3cret","oid":"1.3.6.1.2.1.2.1.0","condition":"ge","value":"48"}`: "",
`{"community":"s3cret","oid":"1.3.6.1.2.1.2.1.0","condition":"lt","value":"10"}`: `value "48" does not satisfy lt "10"`,
`{"community":"s3cret","oid":"1.3.6.1.2.1.99.0"}`: "does not exist",
`{"community":"wrong-community","oid":"1.3.6.1.2.1.1.5.0"}`: "is the community or version right",
})
}
func TestProtocolValidate(t *testing.T) {
for _, tc := range []struct {
typ Type
target, cfg string
}{
{GRPC, "api", `{}`},
{SMTP, "mail:25", `{"tls":"disable","implicit_tls":true}`},
{RADIUS, "radius:1812", `{}`},
{SNMP, "switch:161", `{"oid":"system.name"}`},
{SNMP, "switch:161", `{"oid":"1.3.6","version":"3"}`},
{SNMP, "switch:161", `{"oid":"1.3.6","condition":"gt","value":"many"}`},
} {
if _, err := Validate(tc.typ, tc.target, []byte(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg)
}
}
}
func TestProtocolChecksStayOffPrivateNetworks(t *testing.T) {
for typ, cfg := range map[Type]string{
GRPC: `{"tls":"disable"}`,
SMTP: `{"tls":"disable"}`,
RADIUS: `{"secret":"s","user":"u","password":"p"}`,
SNMP: `{"oid":"1.3.6.1.2.1.1.5.0"}`,
} {
c, err := Validate(typ, "127.0.0.1:9", []byte(cfg))
if err != nil {
t.Fatal(err)
}
o := Run(t.Context(), Spec{Type: typ, Target: "127.0.0.1:9", Timeout: 2 * time.Second, Config: c})
if o.OK || !strings.Contains(o.Error, "non-public") {
t.Errorf("%s: %+v", typ, o)
}
}
}
+75
View File
@@ -0,0 +1,75 @@
package check
import (
"crypto/tls"
"errors"
"net"
"net/url"
"strings"
"unicode"
"unicode/utf8"
)
// TLS modes of services with optional encryption: "require" encrypts
// without verifying the certificate, "verify" also verifies it.
func validTLSMode(m string) bool { return m == "disable" || m == "require" || m == "verify" }
// tlsFor returns the client TLS settings for mode, or nil for "disable".
func tlsFor(mode, target string) *tls.Config {
if mode == "disable" {
return nil
}
host, _, _ := net.SplitHostPort(target)
return &tls.Config{ServerName: host, InsecureSkipVerify: mode == "require"} //nolint:gosec // "require" encrypts without verifying, as chosen per monitor
}
// redact shortens err for customers and removes secrets some clients
// repeat in their errors, also in URL-encoded form.
func redact(err error, secrets ...string) string {
var op *net.OpError
if errors.As(err, &op) && op.Op == "dial" {
return describeNetErr(err)
}
msg := err.Error()
for _, s := range secrets {
if s == "" {
continue
}
for _, v := range []string{s, url.QueryEscape(s), url.PathEscape(s)} {
msg = replaceStandalone(msg, v, "***")
}
}
return truncate(msg, 300)
}
// replaceStandalone replaces occurrences of s in msg that are not part of
// a longer word. Clients print secrets as values ("password=pw",
// "user:pw@host", "'pw'"), so this hides secrets of any length without
// tearing apart words that merely contain them.
func replaceStandalone(msg, s, with string) string {
var b strings.Builder
done, from := 0, 0
for {
i := strings.Index(msg[from:], s)
if i < 0 {
b.WriteString(msg[done:])
return b.String()
}
i += from
before, _ := utf8.DecodeLastRuneInString(msg[:i])
after, _ := utf8.DecodeRuneInString(msg[i+len(s):])
if isWordRune(before) || isWordRune(after) {
_, n := utf8.DecodeRuneInString(msg[i:])
from = i + n
continue
}
b.WriteString(msg[done:i])
b.WriteString(with)
done = i + len(s)
from = done
}
}
func isWordRune(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}
+33
View File
@@ -0,0 +1,33 @@
package check
import (
"errors"
"testing"
)
func TestRedact(t *testing.T) {
tests := []struct {
msg string
secrets []string
want string
}{
// Short secrets are hidden where they stand alone ...
{`failed to connect: password=pw user=app`, []string{"pw"}, `failed to connect: password=*** user=app`},
{`dial postgres://app:x@db:5432/shop`, []string{"x"}, `dial postgres://app:***@db:5432/shop`},
{`auth failed for 'ab'`, []string{"ab"}, `auth failed for '***'`},
// ... without tearing apart words that contain them.
{`destination resolves to a non-public address`, []string{"s"}, `destination resolves to a non-public address`},
{`access denied for user probe`, []string{"p", "e"}, `access denied for user probe`},
// Long secrets and secrets with symbols, also URL-encoded.
{`login "Sup3r-Secret!" rejected`, []string{"Sup3r-Secret!"}, `login "***" rejected`},
{`dial mongodb://root:p%40ss%2Fw@db/admin`, []string{"p@ss/w"}, `dial mongodb://root:***@db/admin`},
{`dial amqp://u:a+b@mq/`, []string{"a b"}, `dial amqp://u:***@mq/`},
{`token=abc abc_def xabc abc`, []string{"abc"}, `token=*** abc_def xabc ***`},
{`umlaut ä and äb`, []string{"ä"}, `umlaut *** and äb`},
}
for _, tc := range tests {
if got := redact(errors.New(tc.msg), tc.secrets...); got != tc.want {
t.Errorf("redact(%q, %q)\n got %q\nwant %q", tc.msg, tc.secrets, got, tc.want)
}
}
}
+22 -3
View File
@@ -74,9 +74,16 @@ const (
type API struct {
Common
Storage
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
// SignupVerify is "auto", "required" or "off": whether new accounts
// confirm their email address before signing in. Auto requires it in
// the cloud edition and wherever mail can be sent.
SignupVerify string `env:"UPTIME_SIGNUP_VERIFY" envDefault:"auto"`
// SignupsPerIP limits sign-ups per client address (IPv6: per /64) in
// 24 hours; 0 means unlimited.
SignupsPerIP int `env:"UPTIME_SIGNUPS_PER_IP" envDefault:"2"`
SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"`
SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"`
// PublicURL is the externally reachable base URL, used for SSO callbacks.
@@ -137,6 +144,18 @@ func (a API) Validate() error {
default:
return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup)
}
switch a.SignupVerify {
case "auto", "required":
case "off":
if a.Edition == EditionCloud {
return fmt.Errorf("config: UPTIME_SIGNUP_VERIFY=off is not allowed in the cloud edition")
}
default:
return fmt.Errorf("config: UPTIME_SIGNUP_VERIFY must be auto, required or off")
}
if a.SignupsPerIP < 0 {
return fmt.Errorf("config: UPTIME_SIGNUPS_PER_IP must not be negative")
}
switch a.SSOPrivateNetworks {
case "auto", "true", "false":
default:
+3 -1
View File
@@ -88,7 +88,9 @@ func Collect(ctx context.Context, pool *pgxpool.Pool) (Stats, error) {
rows, err = pool.Query(ctx, `
SELECT j.job_id, j.proc_name, coalesce(j.hypertable_name, ''), coalesce(st.last_run_status, ''),
st.last_run_started_at, st.next_start, coalesce(st.total_failures, 0)
-- A running job reports -infinity as its next start.
nullif(nullif(st.last_run_started_at, '-infinity'), 'infinity'),
nullif(nullif(st.next_start, '-infinity'), 'infinity'), coalesce(st.total_failures, 0)
FROM timescaledb_information.jobs j
LEFT JOIN timescaledb_information.job_stats st USING (job_id)
WHERE j.proc_name LIKE 'policy_%' AND j.proc_name <> 'policy_telemetry'
+44 -15
View File
@@ -12,6 +12,7 @@ import (
"testing"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
func catalogKeys(t *testing.T) map[string]map[string]bool {
@@ -151,21 +152,49 @@ func TestEveryMailEventHasTexts(t *testing.T) {
func TestDynamicFamilies(t *testing.T) {
en := catalogKeys(t)["en"]
families := map[string][]string{
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "heartbeat"},
"channels.type_": {"webhook", "email"},
"agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"page.component.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"storage.level_": {"raw", "1h", "1d"},
"legal.": {"imprint", "privacy"},
"monitors.op_": {"eq", "ne", "gt", "ge", "lt", "le", "contains", "exists", "absent"},
"evidence.stage_": {"dns", "connect", "tls", "response", "body"},
"evidence.phase_": {"dns", "connect", "tls", "wait", "download"},
"weekday.": {"0", "1", "2", "3", "4", "5", "6"},
"md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"},
"maintenance.recurrence_": {"none", "daily", "weekly", "monthly"},
"storage.job_": {"compression", "retention", "refresh_continuous_aggregate", "job_stat_history_retention"},
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "postgres", "mysql", "mssql", "mongodb", "redis", "mqtt", "kafka", "rabbitmq", "grpc", "smtp", "radius", "snmp", "steam", "minecraft", "docker", "heartbeat", "alertmanager"},
"agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"page.component.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"storage.level_": {"raw", "1h", "1d"},
"legal.": {"imprint", "privacy"},
"monitors.op_": {"eq", "ne", "gt", "ge", "lt", "le", "contains", "exists", "absent"},
"evidence.stage_": {"dns", "connect", "tls", "response", "body"},
"evidence.phase_": {"dns", "connect", "tls", "wait", "download"},
"monitors.db_database_": {"postgres", "mysql", "mssql", "mongodb", "redis"},
"monitors.broker_hint_": {"mqtt", "kafka", "rabbitmq"},
"monitors.snmp_cond_": {"any", "eq", "ne", "contains", "gt", "ge", "lt", "le"},
"monitors.minecraft_": {"java", "bedrock", "hint", "edition"},
"monitors.db_tls_": {"require", "verify", "disable"},
"moderation.target_": {"page", "org", "owner"},
"moderation.delete_": {"page", "org", "owner"},
"moderation.delete_confirm_": {"page", "org", "owner"},
"limits.own_": {"true", "false"},
"pager.": {"newer", "older", "previous", "next", "later", "earlier"},
"weekday.": {"0", "1", "2", "3", "4", "5", "6"},
"md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"},
"maintenance.recurrence_": {"none", "daily", "weekly", "monthly"},
"storage.job_": {"compression", "retention", "refresh_continuous_aggregate", "job_stat_history_retention"},
}
// Notification services name their type, group and settings.
families["channels.type_"] = []string{"webhook", "email"}
seenGroup, seenField := map[string]bool{}, map[string]bool{}
for _, p := range notify.Providers {
families["channels.type_"] = append(families["channels.type_"], p.Type)
if !seenGroup[p.Group] {
seenGroup[p.Group] = true
families["channels.group_"] = append(families["channels.group_"], p.Group)
}
for _, f := range p.Fields {
if !seenField[f.Name] {
seenField[f.Name] = true
families["channels.field_"] = append(families["channels.field_"], f.Name)
}
}
if en["channels.help_"+p.Type] {
families["channels.help_"] = append(families["channels.help_"], p.Type)
}
}
for prefix, values := range families {
for _, v := range values {
+523 -4
View File
@@ -1,6 +1,14 @@
{
"admin.check_types": "Check-Typen",
"admin.check_types_intro": "Schalte Typen ab, die diese Installation nicht anbieten kann, etwa Docker auf geteilten Cloud-Checkern oder ICMP ohne die nötigen Rechte. Sie verschwinden für neue Monitore; bestehende laufen weiter.",
"admin.checker_network": "Checker-Netzwerk",
"admin.intro": "Hier angelegte Regionen, Checker und Statuspage-Server stehen allen Organisationen zur Verfügung. Organisationen legen ihre eigenen unter Regionen & Checker an.",
"admin.platform_private": "Plattform-Checker dürfen private Adressen prüfen",
"admin.platform_private_hint": "Private, Loopback-, Link-Local- und CGNAT-Adressen sowie der Docker-Socket des Checker-Hosts. Ausgeschaltet lassen, wo Plattform-Checker im selben Netz wie die eigene Infrastruktur laufen, etwa bei einem gehosteten Dienst; eigene Checker der Organisationen haben ihren eigenen Schalter.",
"admin.title": "Plattform-Verwaltung",
"agents.allow_private": "Darf private Adressen prüfen",
"agents.allow_private_hint": "Nur für Checker. Ausschalten, wenn der Checker in einem Netz läuft, in das Monitore nicht hineinschauen sollen.",
"agents.allow_private_short": "private Adressen",
"agents.create": "Agent anlegen",
"agents.kind": "Art",
"agents.kind_checker": "Checker",
@@ -10,6 +18,35 @@
"agents.region": "Region",
"agents.revoke_confirm": "Diesen Agent widerrufen? Seine Instanzen hören sofort auf zu arbeiten.",
"agents.token_now": "Kopiere den Token jetzt und setze ihn als UPTIME_AGENT_TOKEN. Er wird nicht erneut angezeigt. Beliebig viele Instanzen können ihn teilen.",
"alert_groups.create": "Gruppe erstellen",
"alert_groups.default": "Standardgruppe",
"alert_groups.delete_confirm": "Diese Alertgruppe löschen? Ihre Monitore benachrichtigen diese Kanäle dann nur noch, wenn eine andere zugeordnete Gruppe sie enthält.",
"alert_groups.intro": "Bündele Benachrichtigungskanäle und ordne die Gruppen Monitoren zu. Neue Monitore und Kanäle werden automatisch der Standardgruppe zugeordnet. Kanäle in mehreren Gruppen erhalten jeden Alert nur einmal.",
"alert_groups.monitor_hint": "Wähle die Gruppen, die Alerts erhalten sollen. Ohne Auswahl werden für diesen Monitor keine Benachrichtigungen verschickt.",
"alert_groups.new": "Neue Alertgruppe",
"alert_groups.no_channels": "Erstelle unten einen Benachrichtigungskanal, um Alerts zu erhalten.",
"alert_groups.quiet_active": "Ruhezeit aktiv",
"alert_groups.quiet_add": "Ruhezeit hinzufügen",
"alert_groups.quiet_end": "Bis",
"alert_groups.quiet_hint": "Unterdrückt Benachrichtigungen dieser Gruppe in diesen Zeiträumen (Vorfälle werden weiter aufgezeichnet). Ohne Wochentagsauswahl gilt der Zeitraum täglich; 00:00 bis 00:00 gilt ganztägig.",
"alert_groups.quiet_remove": "Entfernen",
"alert_groups.quiet_start": "Von",
"alert_groups.quiet_title": "Ruhezeiten",
"alert_groups.save": "Gruppe speichern",
"alert_groups.title": "Alertgruppen",
"alertmanager.config_hint": "Trage sie als Webhook-Empfänger in die alertmanager.yml ein; send_resolved ist nötig, damit Monitore wieder hochgehen.",
"alertmanager.copy_now": "Kopiere die URL jetzt, sie wird nicht erneut angezeigt. Sie enthält ein Geheimnis.",
"alertmanager.create_monitor": "Monitor anlegen",
"alertmanager.create_receiver": "Empfänger anlegen",
"alertmanager.delete_confirm": "Diesen Empfänger löschen? Alertmanager kann dann über seine URL keine Alerts mehr schicken.",
"alertmanager.firing": "Feuernde Alerts",
"alertmanager.intro": "Lass Alertmanager seine Alerts hierher schicken. Monitore vom Typ Alertmanager sind ausgefallen, solange ein passender Alert feuert, mit Vorfällen, Benachrichtigungen und SLA wie jeder andere Monitor.",
"alertmanager.last_received": "letzter Alert: {{.Time}}",
"alertmanager.no_alerts": "Kein Alert feuert.",
"alertmanager.receivers": "Empfänger",
"alertmanager.since": "seit {{.Time}}",
"alertmanager.title": "Alertmanager",
"apidocs.footer": "API",
"apidocs.hint": "„Try it out“ nutzt deine aktuelle Sitzung.",
"apidocs.title": "API-Dokumentation",
"app.network_error": "Verbindung fehlgeschlagen.",
@@ -19,8 +56,15 @@
"audit.action.account.signup": "Konto erstellt",
"audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert",
"audit.action.account.totp_enable": "Zwei-Faktor-Authentifizierung aktiviert",
"audit.action.account.verify": "E-Mail-Adresse bestätigt",
"audit.action.agent.create": "Agent erstellt",
"audit.action.agent.delete": "Agent widerrufen",
"audit.action.agent.update": "Agent geändert",
"audit.action.alert_group.create": "Alertgruppe erstellt",
"audit.action.alert_group.delete": "Alertgruppe gelöscht",
"audit.action.alert_group.update": "Alertgruppe geändert",
"audit.action.alertmanager.receiver_create": "Alertmanager-Empfänger angelegt",
"audit.action.alertmanager.receiver_delete": "Alertmanager-Empfänger gelöscht",
"audit.action.auth.login": "Angemeldet",
"audit.action.auth.login_failed": "Anmeldung fehlgeschlagen",
"audit.action.auth.login_sso": "Mit SSO angemeldet",
@@ -44,15 +88,28 @@
"audit.action.monitor.create": "Monitor erstellt",
"audit.action.monitor.delete": "Monitor gelöscht",
"audit.action.monitor.update": "Monitor geändert",
"audit.action.org.check_types_update": "Check-Typen geändert",
"audit.action.org.create": "Organisation angelegt",
"audit.action.org.delete": "Organisation gelöscht",
"audit.action.org.export": "Daten der Organisation exportiert",
"audit.action.org.legal_update": "Rechtstext geändert",
"audit.action.org.policy_update": "Sicherheitsrichtlinie geändert",
"audit.action.platform.agent_create": "Plattform-Agent erstellt",
"audit.action.platform.agent_delete": "Plattform-Agent widerrufen",
"audit.action.platform.check_types_update": "Check-Typen geändert",
"audit.action.platform.checker_network_update": "Checker-Netzwerk geändert",
"audit.action.platform.legal_update": "Rechtstext der Plattform geändert",
"audit.action.platform.limits_update": "Standard-Limits geändert",
"audit.action.platform.org_delete": "Organisation durch Admin gelöscht",
"audit.action.platform.org_limits_update": "Limits einer Organisation geändert",
"audit.action.platform.org_suspension": "Organisation gesperrt oder entsperrt",
"audit.action.platform.region_create": "Plattform-Region erstellt",
"audit.action.platform.region_delete": "Plattform-Region gelöscht",
"audit.action.platform.status_page_delete": "Statusseite durch Admin gelöscht",
"audit.action.platform.status_page_suspension": "Statusseite gesperrt oder entsperrt",
"audit.action.platform.user_delete": "Account durch Admin gelöscht",
"audit.action.platform.user_limits_update": "Limits eines Accounts geändert",
"audit.action.platform.user_suspension": "Account gesperrt oder entsperrt",
"audit.action.region.create": "Region erstellt",
"audit.action.region.delete": "Region gelöscht",
"audit.action.role.create": "Rolle erstellt",
@@ -65,6 +122,10 @@
"audit.action.statuspage.delete": "Statusseite gelöscht",
"audit.action.statuspage.domain_update": "Eigene Domain geändert",
"audit.action.statuspage.domain_verify": "Eigene Domain verifiziert",
"audit.action.statuspage.group_create": "Statusseiten-Gruppe erstellt",
"audit.action.statuspage.group_delete": "Statusseiten-Gruppe gelöscht",
"audit.action.statuspage.group_update": "Statusseiten-Gruppe geändert",
"audit.action.statuspage.groups_import": "Statusseiten-Gruppen aus Monitor-Gruppen übernommen",
"audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert",
"audit.action.statuspage.update": "Statusseite geändert",
"audit.action.token.create": "API-Token erstellt",
@@ -72,7 +133,6 @@
"audit.deleted_user": "Gelöschter Benutzer",
"audit.empty": "Noch keine Einträge.",
"audit.intro": "Änderungen in dieser Organisation: wer wann was getan hat und von welcher Adresse. Einträge lassen sich nicht bearbeiten.",
"audit.older": "Ältere Einträge",
"audit.platform_intro": "Änderungen an Plattform-Regionen und -Agents sowie Anmeldeversuche für unbekannte Konten.",
"audit.platform_title": "Plattform-Audit-Log",
"audit.title": "Audit-Log",
@@ -95,19 +155,279 @@
"auth.sso.heading": "Single Sign-on",
"auth.sso.org_placeholder": "Kurzname der Organisation",
"auth.sso.submit": "Weiter",
"auth.verify.intro": "Drücke den Knopf, um deine E-Mail-Adresse zu bestätigen und dich anzumelden.",
"auth.verify.resend_intro": "Wenn ein unbestätigtes Konto diese Adresse nutzt, schicken wir ihm einen neuen Link.",
"auth.verify.resend_link": "Bestätigungs-E-Mail erneut senden",
"auth.verify.resend_submit": "Link senden",
"auth.verify.resend_title": "Neuer Bestätigungslink",
"auth.verify.sent": "Wir haben dir einen Link geschickt, mit dem du deine E-Mail-Adresse bestätigst. Er ist 24 Stunden gültig.",
"auth.verify.sent_hint": "Nichts angekommen? Schau im Spam-Ordner nach oder fordere einen neuen Link an.",
"auth.verify.sent_title": "Schau in dein Postfach",
"auth.verify.submit": "Bestätigen und anmelden",
"auth.verify.title": "E-Mail-Adresse bestätigen",
"channels.create": "Kanal anlegen",
"channels.created": "Webhook erstellt. Er ist bereits in der Standardgruppe. Kopiere den Signaturschlüssel, bevor du fortfährst.",
"channels.delete_confirm": "Diesen Kanal löschen?",
"channels.intro": "Jeder aktive Kanal wird benachrichtigt, wenn ein Monitor in allen seinen Regionen ausfällt und wenn er sich erholt.",
"channels.field_access_key": "Zugriffsschlüssel",
"channels.field_access_key_id": "AccessKey-ID",
"channels.field_access_key_secret": "AccessKey-Secret",
"channels.field_access_token": "Zugriffstoken",
"channels.field_account_sid": "Account-SID",
"channels.field_action_group_id": "Aktionsgruppen-ID",
"channels.field_answer_url": "Answer-URL (für Anrufe)",
"channels.field_api_key": "API-Schlüssel",
"channels.field_api_token": "API-Token",
"channels.field_api_url": "API-URL",
"channels.field_api_version": "API-Version",
"channels.field_app_token": "Anwendungs-Token",
"channels.field_auth_id": "Auth-ID",
"channels.field_auth_token": "Auth-Token",
"channels.field_bcc_email": "BCC (durch Komma getrennt)",
"channels.field_bot_id": "Bot-ID",
"channels.field_bot_key": "Bot-Schlüssel",
"channels.field_bot_secret": "Bot-Geheimnis",
"channels.field_bot_token": "Bot-Token",
"channels.field_cc_email": "CC (durch Komma getrennt)",
"channels.field_channel": "Kanal",
"channels.field_channel_id": "Kanal-ID",
"channels.field_chat_id": "Chat-ID",
"channels.field_chat_ids": "Chat-IDs (durch Komma getrennt)",
"channels.field_client_id": "Client-ID",
"channels.field_client_key": "Client-Schlüssel",
"channels.field_client_secret": "Client-Secret",
"channels.field_cloud_id": "Cloud-ID",
"channels.field_config_key": "Konfigurationsschlüssel",
"channels.field_consumer_key": "Consumer-Key",
"channels.field_consumer_secret": "Consumer-Secret",
"channels.field_conversation_token": "Unterhaltungs-Token",
"channels.field_device": "Gerät",
"channels.field_device_id": "Geräte-ID",
"channels.field_device_token": "Geräte-Token",
"channels.field_email": "Konto-E-Mail",
"channels.field_endpoint_url": "Endpunkt-URL",
"channels.field_environment": "Umgebung",
"channels.field_from_email": "Absenderadresse",
"channels.field_from_name": "Absendername",
"channels.field_gateway": "Gateway-Typ",
"channels.field_gateway_id": "Gateway-ID (Absender)",
"channels.field_gateway_secret": "Gateway-Secret",
"channels.field_group": "Gruppe",
"channels.field_group_ids": "Gruppen-IDs (durch Komma getrennt)",
"channels.field_hash_key": "Hash-Schlüssel",
"channels.field_homeserver_url": "Homeserver-URL",
"channels.field_instance": "Instanz",
"channels.field_integration_key": "Integrationsschlüssel oder Push-URL",
"channels.field_integration_url": "Integrations-URL",
"channels.field_line_number": "Leitungsnummer",
"channels.field_mailbox": "Absender-Postfach",
"channels.field_mentioned_mobiles": "Handynummern erwähnen (durch Komma getrennt)",
"channels.field_message_type": "Nachrichtentyp",
"channels.field_messaging_profile_id": "Messaging-Profil-ID",
"channels.field_messaging_service_sid": "Messaging-Service-SID",
"channels.field_modem": "Modem-ID",
"channels.field_number": "Absendernummer",
"channels.field_originator_type": "Absendertyp",
"channels.field_password": "Passwort",
"channels.field_peer_id": "Peer-ID",
"channels.field_phone_number": "Telefonnummer",
"channels.field_phone_numbers": "Telefonnummern (durch Komma getrennt)",
"channels.field_platform": "Plattform",
"channels.field_priority": "Priorität",
"channels.field_publish_url": "Publish-URL",
"channels.field_push_key": "Push-Schlüssel",
"channels.field_receiver_id": "Empfänger-ID",
"channels.field_recipient": "Empfänger",
"channels.field_recipient_type": "Empfängertyp",
"channels.field_recipients": "Empfänger (durch Komma getrennt)",
"channels.field_region": "Region",
"channels.field_relays": "Relays (wss://, durch Komma getrennt)",
"channels.field_rest_url": "REST-Endpunkt-URL (mit Routing-Key)",
"channels.field_room_id": "Raum-ID",
"channels.field_routing_key": "Integrationsschlüssel",
"channels.field_send_key": "SendKey",
"channels.field_sender": "Absender",
"channels.field_sender_nsec": "Privater Absenderschlüssel (nsec)",
"channels.field_server_url": "Server-URL",
"channels.field_service": "Notify-Service (Standard: notify)",
"channels.field_session": "Session",
"channels.field_severity": "Schweregrad",
"channels.field_sign_name": "Signaturname",
"channels.field_sign_secret": "Signatur-Secret",
"channels.field_sms_type": "SMS-Typ",
"channels.field_sound": "Ton",
"channels.field_spt": "SPT-Tokens (durch Komma getrennt)",
"channels.field_subject": "Betreff (Standard: Titel des Vorfalls)",
"channels.field_target": "Ziel",
"channels.field_target_id": "Geräte- oder Benutzer-ID",
"channels.field_template_code": "Vorlagencode",
"channels.field_template_id": "Vorlagen-ID",
"channels.field_template_key": "Vorlagenschlüssel",
"channels.field_tenant_id": "Mandanten-ID",
"channels.field_thread_id": "Themen-ID (Forum-Gruppen)",
"channels.field_to_email": "Empfänger (durch Komma getrennt)",
"channels.field_token": "Token",
"channels.field_topic": "Topic",
"channels.field_trigger_id": "Trigger-ID",
"channels.field_urgency": "Dringlichkeit",
"channels.field_urls": "Apprise-URLs",
"channels.field_user_id": "Benutzer-ID",
"channels.field_user_key": "Benutzer-Schlüssel",
"channels.field_username": "Benutzername",
"channels.field_variable_id": "Variablen-ID",
"channels.field_webhook_url": "Webhook-URL",
"channels.field_workspace_id": "Workspace-ID",
"channels.group_chat": "Chat und Messenger",
"channels.group_email": "E-Mail-Dienste",
"channels.group_incident": "Incident-Management",
"channels.group_other": "Weitere",
"channels.group_push": "Push",
"channels.group_sms": "SMS und Anrufe",
"channels.help_aliyunsms": "Die Vorlage erhält die Parameter name, time, status und msg.",
"channels.help_apprise": "Erreicht über 100 Dienste über einen Apprise-API-Server: gib Apprise-URLs oder den Schlüssel einer dort gespeicherten Konfiguration an.",
"channels.help_bark": "Der Endpunkt enthält deinen Geräteschlüssel, z. B. https://api.day.app/KEY.",
"channels.help_callmebot": "Die URL, die CallMeBot dir geschickt hat, mit Telefonnummer und API-Key.",
"channels.help_dingtalk": "Die Webhook-URL des Roboters; das Signatur-Secret angeben, wenn der Roboter „Zusatzsignatur“ nutzt.",
"channels.help_freemobile": "Schreibt dem Telefon des Free-Mobile-Kontos; dort „Notifications par SMS“ aktivieren.",
"channels.help_googlesheets": "Die URL einer Google-Apps-Script-Web-App, die die gesendeten Felder als Zeile anhängt.",
"channels.help_homeassistant": "Nutzt einen langlebigen Zugriffstoken. Der Service ist der Teil nach notify., z. B. mobile_app_phone; persistent_notification zeigt sie in Home Assistant an.",
"channels.help_keep": "Nutzt die Uptime-Kuma-Integration von Keep.",
"channels.help_microsoftgraph": "Braucht eine App-Registrierung in Microsoft Entra mit der Anwendungsberechtigung Mail.Send; gesendet wird als das Postfach.",
"channels.help_nostr": "Sendet eine verschlüsselte Privatnachricht (NIP-17) vom Absenderschlüssel an jede npub über die Relays.",
"channels.help_opsgenie": "Der Alert wird geschlossen, wenn der Vorfall behoben ist.",
"channels.help_opsimate": "Nutzt die Uptime-Kuma-Integration von OpsiMate.",
"channels.help_pagerduty": "Nutze den Integrationsschlüssel einer Events-API-v2-Integration; die Behebung schließt den PagerDuty-Vorfall.",
"channels.help_pinglet": "Nutzt das Uptime-Kuma-Format von Pinglet.",
"channels.help_plivo": "Für Anrufe muss die Answer-URL Plivo-XML liefern; die Nachricht kommt als Parameter message.",
"channels.help_signal": "Braucht einen signal-cli-REST-API-Server (bbernhard/signal-cli-rest-api) mit registrierter Nummer.",
"channels.help_smsir": "sms.ir versendet Verify-Vorlagen; die Vorlage braucht einen Parameter uptkumaalert, der Monitor und Zustand erhält.",
"channels.help_splunk": "Der REST-Endpunkt aus der REST-Integration von Splunk On-Call, mit dem Routing-Key am Ende.",
"channels.help_teams": "Nutze die URL eines Teams-Workflows „Bei Empfang einer Webhookanforderung in einem Kanal posten“.",
"channels.help_telegram": "Lege mit @BotFather einen Bot an; die Chat-ID einer Gruppe beginnt mit -100.",
"channels.intro": "Aktivierte Kanäle erhalten Ausfall- und Entwarnungsmeldungen von Monitoren, die ihren Alertgruppen zugeordnet sind.",
"channels.language": "Sprache",
"channels.manage_groups": "Schlüssel kopiert — Alertgruppen verwalten",
"channels.new_email": "Neuer E-Mail-Kanal",
"channels.new_service": "Weitere Dienste",
"channels.new_webhook": "Neuer Webhook",
"channels.optional": "optional",
"channels.secret_now": "Signatur-Secret: Prüfe damit den Header X-Uptimesebi-Signature. Es wird nicht erneut angezeigt.",
"channels.service": "Dienst",
"channels.service_intro": "Chat-, Push- und Alarmierungsdienste. Tokens und Schlüssel werden verschlüsselt gespeichert und nie wieder angezeigt.",
"channels.test": "Test senden",
"channels.test_ok": "Testbenachrichtigung zugestellt.",
"channels.title": "Benachrichtigungen",
"channels.to": "Empfänger",
"channels.type_alerta": "Alerta",
"channels.type_alertnow": "AlertNow",
"channels.type_aliyunsms": "Alibaba Cloud SMS",
"channels.type_amootsms": "Amoot SMS",
"channels.type_apprise": "Apprise",
"channels.type_bale": "Bale",
"channels.type_bark": "Bark",
"channels.type_bearsms": "BearSMS",
"channels.type_bitrix": "Bitrix24",
"channels.type_brevo": "Brevo",
"channels.type_callmebot": "CallMeBot",
"channels.type_cellsynt": "Cellsynt",
"channels.type_clicksend": "ClickSend SMS",
"channels.type_clickup": "ClickUp Chat",
"channels.type_dingtalk": "DingTalk",
"channels.type_discord": "Discord",
"channels.type_egosms": "EgoSMS",
"channels.type_elks46": "46elks",
"channels.type_email": "E-Mail",
"channels.type_evolution": "Evolution API (WhatsApp)",
"channels.type_feishu": "Feishu / Lark",
"channels.type_flashduty": "Flashduty",
"channels.type_flowtriq": "Flowtriq",
"channels.type_fluxer": "Fluxer",
"channels.type_freemobile": "Free Mobile",
"channels.type_goalert": "GoAlert",
"channels.type_googlechat": "Google Chat",
"channels.type_googlesheets": "Google Sheets",
"channels.type_gorush": "Gorush",
"channels.type_gotify": "Gotify",
"channels.type_grafanaoncall": "Grafana OnCall",
"channels.type_gtxmessaging": "GTX Messaging",
"channels.type_halopsa": "HaloPSA",
"channels.type_heiioncall": "Heii On-Call",
"channels.type_homeassistant": "Home Assistant",
"channels.type_indigo": "Indigo",
"channels.type_jsm": "Jira Service Management",
"channels.type_keep": "Keep",
"channels.type_kook": "KOOK",
"channels.type_line": "LINE Messaging API",
"channels.type_lunasea": "LunaSea",
"channels.type_matrix": "Matrix",
"channels.type_mattermost": "Mattermost",
"channels.type_max": "MAX",
"channels.type_messenger360": "360messenger (WhatsApp)",
"channels.type_microsoftgraph": "Microsoft 365 (Graph)",
"channels.type_milky": "Milky (QQ)",
"channels.type_nextcloudtalk": "Nextcloud Talk",
"channels.type_nostr": "Nostr",
"channels.type_notifery": "Notifery",
"channels.type_notifyapp": "NotifyApp",
"channels.type_ntfy": "ntfy",
"channels.type_octopush": "Octopush",
"channels.type_onebot": "OneBot (QQ)",
"channels.type_onechat": "OneChat",
"channels.type_onesender": "OneSender (WhatsApp)",
"channels.type_ooredoo": "Ooredoo Maldives",
"channels.type_openwa": "OpenWA (WhatsApp)",
"channels.type_opsgenie": "Opsgenie",
"channels.type_opsimate": "OpsiMate",
"channels.type_pagerduty": "PagerDuty",
"channels.type_pagertree": "PagerTree",
"channels.type_pinglet": "Pinglet",
"channels.type_plivo": "Plivo",
"channels.type_promosms": "PromoSMS",
"channels.type_pumble": "Pumble",
"channels.type_pushbullet": "Pushbullet",
"channels.type_pushdeer": "PushDeer",
"channels.type_pushover": "Pushover",
"channels.type_pushplus": "PushPlus",
"channels.type_pushy": "Pushy",
"channels.type_resend": "Resend",
"channels.type_rocketchat": "Rocket.Chat",
"channels.type_sendgrid": "SendGrid",
"channels.type_serverchan": "ServerChan",
"channels.type_serwersms": "SerwerSMS.pl",
"channels.type_sevenio": "seven",
"channels.type_signal": "Signal",
"channels.type_signalgrid": "Signalgrid",
"channels.type_signl4": "SIGNL4",
"channels.type_slack": "Slack",
"channels.type_smsc": "SMSC",
"channels.type_smseagle": "SMSEagle",
"channels.type_smsgateway": "SMS Gateway for Android",
"channels.type_smsir": "sms.ir",
"channels.type_smsmanager": "SmsManager",
"channels.type_smspartner": "SMS Partner",
"channels.type_smsplanet": "SMSPlanet",
"channels.type_splunk": "Splunk On-Call (VictorOps)",
"channels.type_spugpush": "Spug Push",
"channels.type_squadcast": "Squadcast",
"channels.type_stackfield": "Stackfield",
"channels.type_teams": "Microsoft Teams",
"channels.type_techulus": "Techulus Push",
"channels.type_telegram": "Telegram",
"channels.type_telnyx": "Telnyx",
"channels.type_teltonika": "Teltonika router",
"channels.type_threema": "Threema",
"channels.type_trigv": "Trigv",
"channels.type_turbosmtp": "turboSMTP",
"channels.type_twilio": "Twilio",
"channels.type_vk": "VK",
"channels.type_vkteams": "VK Teams",
"channels.type_waha": "WAHA (WhatsApp)",
"channels.type_webhook": "Webhook",
"channels.type_wecom": "WeCom (WeChat Work)",
"channels.type_whapi": "Whapi (WhatsApp)",
"channels.type_wpush": "WPush",
"channels.type_wxpusher": "WxPusher",
"channels.type_yunzhijia": "Yunzhijia",
"channels.type_zohocliq": "Zoho Cliq",
"channels.url": "Webhook-URL",
"checkers.avg_latency": "Mittlere Latenz",
"checkers.for": "seit {{.Duration}}",
@@ -148,35 +468,48 @@
"console.nav.settings": "Einstellungen",
"console.nav.sso": "SSO",
"console.nav.tokens": "API-Tokens",
"console.org_suspended": "Der Betreiber hat diese Organisation gesperrt: Ihre Monitore werden nicht geprüft und ihre Statusseiten sind offline.",
"console.sso_required_action": "Mit SSO anmelden",
"console.suspended_reason": "Grund: {{.Reason}}",
"console.totp_missing_action": "Jetzt einrichten",
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.",
"email.opened.subject": "[DOWN] {{.Monitor}}",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
"email.resolved.subject": "[UP] {{.Monitor}}",
"email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.",
"email.test.subject": "Testbenachrichtigung von uptimesebi",
"email.test.subject": "Testbenachrichtigung von UptimeSebi",
"email.verify.body": "Hallo,\n\nbitte bestätige deine E-Mail-Adresse, um die Registrierung abzuschließen:\n\n{{.Link}}\n\nDer Link ist {{.Hours}} Stunden gültig. Wenn du dich nicht registriert hast, ignoriere diese E-Mail; das Konto wird nach einer Woche gelöscht.",
"email.verify.subject": "Bestätige deine E-Mail-Adresse für UptimeSebi",
"error.account_suspended": "Dieser Account ist gesperrt. Wende dich an den Betreiber.",
"error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.",
"error.alert_group_not_deletable": "Die Gruppe existiert nicht oder ist die geschützte Standardgruppe.",
"error.all_check_types_disabled": "Lass mindestens einen Check-Typ eingeschaltet.",
"error.already_assigned": "Das Mitglied hat diese Rolle bereits.",
"error.already_member": "Diese Person ist bereits Mitglied.",
"error.channel_test_failed": "Die Testbenachrichtigung konnte nicht zugestellt werden.",
"error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.",
"error.check_type_disabled": "Dieser Check-Typ ist für diese Organisation oder Installation abgeschaltet.",
"error.confirmation_failed": "Die Bestätigung stimmt nicht.",
"error.domain_not_verified": "Der TXT-Eintrag wurde noch nicht gefunden. DNS-Änderungen brauchen manchmal etwas Zeit.",
"error.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
"error.email_unverified": "Bestätige zuerst deine E-Mail-Adresse; wir haben dir einen Link geschickt. Einen neuen kannst du unten anfordern.",
"error.forbidden": "Dafür fehlt dir die Berechtigung.",
"error.group_cycle": "Eine Gruppe kann nicht in sich selbst oder eine ihrer Untergruppen verschoben werden.",
"error.group_too_deep": "Gruppen lassen sich höchstens acht Ebenen tief verschachteln.",
"error.internal": "Interner Fehler.",
"error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.",
"error.invalid_assertion_op": "Unbekannter Operator.",
"error.invalid_assertion_path": "Ein Pfad ist ungültig. Nutze durch Punkte getrennte Schlüssel und [n] für Array-Elemente.",
"error.invalid_assertion_value": "Vergleiche mit <, >, ≤ und ≥ brauchen eine Zahl.",
"error.invalid_assertions": "Lege 1 bis 10 Bedingungen an.",
"error.invalid_channel": "Ein Benachrichtigungskanal existiert nicht in dieser Organisation.",
"error.invalid_channel_settings": "Fülle die Pflichtfelder aus; Adressen müssen https-URLs sein.",
"error.invalid_code": "Code ungültig.",
"error.invalid_config": "Die Check-Einstellungen sind ungültig.",
"error.invalid_credentials": "E-Mail oder Passwort falsch.",
"error.invalid_cursor": "Dieser Seitenlink ist ungültig; beginne bei der ersten Seite.",
"error.invalid_domain": "Eine der Domains ist ungültig.",
"error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.",
"error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.",
@@ -187,17 +520,21 @@
"error.invalid_interval": "Das Intervall muss mindestens {{.Min}} Sekunden und höchstens einen Tag betragen.",
"error.invalid_json_body": "Der Request-Body ist kein gültiges JSON.",
"error.invalid_legal_url": "Der Link muss eine http- oder https-URL sein.",
"error.invalid_limit": "limit muss zwischen 1 und {{.Max}} liegen.",
"error.invalid_maintenance_duration": "Die Dauer muss zwischen 1 Minute und 30 Tagen liegen.",
"error.invalid_maintenance_time": "Prüfe Beginn, Wochentage und letzten Tag.",
"error.invalid_matchers": "Lege 1 bis 20 Label-Matcher mit gültigen Label-Namen und regulären Ausdrücken an.",
"error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.",
"error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.",
"error.invalid_permissions": "Mindestens eine Berechtigung auswählen.",
"error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.",
"error.invalid_quiet_hours": "Prüfe Startzeit, Endzeit und Wochentage der Ruhezeiten.",
"error.invalid_record": "Nicht unterstützter DNS-Record-Typ.",
"error.invalid_region": "Unbekannte Region.",
"error.invalid_region_key": "Regions-Schlüssel haben 1–40 Zeichen: a–z, 0–9 und Bindestrich.",
"error.invalid_resolver": "Der Resolver muss als host:port angegeben werden.",
"error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.",
"error.invalid_stale_hours": "Die Verfallszeit muss zwischen 1 Stunde und 30 Tagen liegen.",
"error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.",
"error.invalid_theme": "Die Theme-Einstellungen sind ungültig: Akzent als #rrggbb, Logo als https-URL, CSS ohne \"</\".",
"error.invalid_time_zone": "Unbekannte Zeitzone. Nutze einen Namen wie Europe/Berlin.",
@@ -211,25 +548,31 @@
"error.maintenance_overlaps": "Die Wartung würde länger dauern als der Abstand bis zur Wiederholung.",
"error.maintenance_without_targets": "Wähle mindestens einen Monitor oder eine Gruppe.",
"error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
"error.monitor_limit": "Deine Organisation hat ihr Limit von {{.Max}} Monitoren erreicht.",
"error.no_domain": "Lege zuerst eine eigene Domain fest.",
"error.no_password": "Konto ohne Passwort.",
"error.not_found": "Nicht gefunden.",
"error.org_limit": "Dein Konto darf höchstens {{.Max}} Organisationen besitzen.",
"error.org_not_found": "Organisation nicht gefunden.",
"error.org_suspended": "Der Betreiber hat diese Organisation gesperrt.",
"error.owner_cannot_be_removed": "Der Owner kann nicht entfernt werden.",
"error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.",
"error.owns_shared_orgs": "Du besitzt Organisationen mit weiteren Mitgliedern. Übergib oder lösche sie zuerst.",
"error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
"error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.",
"error.platform_region_limit": "Ein Monitor darf aus höchstens {{.Max}} Plattform-Regionen geprüft werden; eigene Checker-Regionen zählen nicht.",
"error.policy_would_lock_you_out": "Deine aktuelle Anmeldung erfüllt diese Richtlinie nicht. Erfülle sie zuerst und aktiviere sie dann.",
"error.rate_limited": "Zu viele Versuche, bitte später erneut.",
"error.region_in_use": "Die Region wird noch von Monitoren oder Agents genutzt.",
"error.region_key_taken": "Eine Region mit diesem Schlüssel gibt es bereits.",
"error.region_limit": "Ein Monitor darf aus höchstens {{.Max}} Regionen geprüft werden.",
"error.role_built_in": "Eingebaute Rollen können nicht geändert werden.",
"error.role_in_use": "Die Rolle ist noch Mitgliedern zugewiesen.",
"error.role_name_taken": "Eine Rolle mit diesem Namen gibt es bereits.",
"error.role_not_found": "Rolle nicht gefunden.",
"error.session_required": "Diese Aktion ist für API-Tokens nicht verfügbar.",
"error.signup_closed": "Registrierung ist deaktiviert.",
"error.signup_limit": "Aus deinem Netz wurden heute zu viele Konten angelegt. Versuche es morgen wieder.",
"error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
"error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.",
"error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.",
@@ -244,6 +587,8 @@
"error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.",
"error.sso_required_by_org": "Diese Organisation verlangt die Anmeldung über ihren SSO-Provider.",
"error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.",
"error.status_page_limit": "Deine Organisation hat ihr Limit von {{.Max}} Statusseiten erreicht.",
"error.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.",
"error.token_lifetime_exceeds_policy": {
"one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.",
"other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen."
@@ -253,6 +598,9 @@
"error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
"error.unauthenticated": "Anmeldung erforderlich.",
"error.unsupported_locale": "Sprache wird nicht unterstützt.",
"error.user_owns_shared_orgs": "Dem Account gehören Organisationen mit weiteren Mitgliedern. Lösche diese zuerst oder übertrage sie.",
"error.verification_expired": "Dieser Bestätigungslink ist ungültig oder abgelaufen. Fordere einen neuen an.",
"error.verification_mail_failed": "Dein Konto wurde angelegt, aber die Bestätigungs-E-Mail konnte nicht gesendet werden. Fordere später einen neuen Link an.",
"evidence.body": "Antwort-Body",
"evidence.body_binary": "Binärer Inhalt, nicht gespeichert.",
"evidence.body_empty": "Leer.",
@@ -403,7 +751,10 @@
"groups.none": "– oberste Ebene –",
"groups.parent": "In Gruppe",
"groups.title": "Monitor-Gruppen",
"incidents.all": "Alle Vorfälle",
"incidents.all_of_monitor": "Alle Vorfälle dieses Monitors",
"incidents.none": "Bisher keine Incidents.",
"incidents.of_monitor": "Vorfälle von",
"incidents.ongoing": "laufend",
"incidents.resolved": "behoben",
"incidents.title": "Incidents",
@@ -423,6 +774,20 @@
"legal.platform_title": "Impressum & Datenschutz der Plattform",
"legal.privacy": "Datenschutz",
"legal.url": "Link auf eine bestehende Seite",
"limits.default": "Standard: {{.Value}}",
"limits.intro": "Gelten für jede Organisation und jeden Account ohne eigenen Wert, auch wenn du sie später änderst. 0 heißt unbegrenzt. Ein gesenktes Limit lässt alles Bestehende stehen; nur neue Monitore, Statusseiten, Regionen oder Organisationen werden abgelehnt.",
"limits.monitors": "Monitore",
"limits.org_title": "Kontingent",
"limits.orgs_per_account": "Organisationen pro Account",
"limits.own_false": "zählen nicht",
"limits.own_regions_count": "Eigene Checker-Regionen zählen zum Regionen-Limit",
"limits.own_regions_count_hint": "Aus: Organisationen dürfen beliebig viele eigene Regionen nutzen; begrenzt werden nur Plattform-Regionen.",
"limits.own_regions_free": "Eigene Checker-Regionen zählen nicht zum Regionen-Limit.",
"limits.own_true": "zählen",
"limits.regions_per_monitor": "Regionen pro Monitor",
"limits.status_pages": "Statusseiten",
"limits.title": "Standard-Limits",
"limits.unlimited": "unbegrenzt",
"maintenance.delete_confirm": "Dieses Wartungsfenster samt Wiederholungen löschen?",
"maintenance.edit": "Wartung bearbeiten",
"maintenance.empty": "Keine Wartung geplant.",
@@ -496,25 +861,84 @@
"members.scope_org": "gesamte Organisation",
"members.title": "Mitglieder",
"members.unassign": "Rolle entfernen",
"moderation.actions": "Sperren oder löschen …",
"moderation.created": "Erstellt",
"moderation.delete_confirm_org": "Organisation {{.Name}} mit allen Monitoren, Ergebnissen und Statusseiten endgültig löschen?",
"moderation.delete_confirm_owner": "Account {{.Name}} endgültig löschen? Organisationen, in denen nur er Mitglied ist, werden mitgelöscht.",
"moderation.delete_confirm_page": "Statusseite {{.Name}} endgültig löschen?",
"moderation.delete_org": "Organisation löschen",
"moderation.delete_owner": "Account löschen",
"moderation.delete_page": "Statusseite löschen",
"moderation.intro": "Alle veröffentlichten Statusseiten und alle gesperrten Seiten, Organisationen und Accounts, jeweils mit Organisation und Inhaber. Sperren lässt sich rückgängig machen und zeigt der Organisation den Grund; Löschen ist endgültig.",
"moderation.none": "Keine Statusseite gefunden.",
"moderation.org": "Organisation",
"moderation.owner": "Inhaber",
"moderation.owner_is_admin": "Der Inhaber ist Plattform-Admin und kann hier nicht gesperrt oder gelöscht werden.",
"moderation.page": "Statusseite",
"moderation.reason": "Grund (optional)",
"moderation.reinstate": "Entsperren",
"moderation.search": "Titel, Adresse, Organisation oder E-Mail",
"moderation.search_button": "Suchen",
"moderation.suspend": "Sperren",
"moderation.suspended": "Gesperrt",
"moderation.target_org": "Organisation",
"moderation.target_owner": "Inhaber-Account",
"moderation.target_page": "Statusseite",
"moderation.title": "Öffentliche Statusseiten",
"monitors.alertmanager_hint": "Ausgefallen, solange ein Alert feuert, der alle Matcher erfüllt. Alerts kommen über einen Empfänger:",
"monitors.all": "Alle Monitore",
"monitors.all_results": "Alle Ergebnisse",
"monitors.assertion_op": "Operator",
"monitors.assertion_path": "Pfad",
"monitors.assertion_value": "Wert",
"monitors.assertions": "Bedingungen",
"monitors.assertions_hint": "Alle müssen erfüllt sein. Pfade wie status.database oder checks[0].state; leere Zeilen werden ignoriert.",
"monitors.broker_expect": "Nachricht muss enthalten (optional)",
"monitors.broker_hint_kafka": "Ziel sind ein oder mehrere Broker als host:port. Fragt die Cluster-Metadaten ab; mit Topic muss es existieren und jede Partition einen Leader haben.",
"monitors.broker_hint_mqtt": "Ziel ist host:port (meist 1883, mit TLS 8883). Meldet sich an; mit Topic muss innerhalb des Timeouts eine Nachricht ankommen (Retained-Nachrichten zählen).",
"monitors.broker_hint_rabbitmq": "Ziel ist host:port des AMQP-Ports (meist 5672, mit TLS 5671). Meldet sich an und öffnet einen Kanal; mit Queue muss sie existieren.",
"monitors.broker_message": "Diese Nachricht ins Topic schreiben (optional)",
"monitors.broker_queue": "Queue (optional)",
"monitors.broker_sasl": "SASL-Verfahren (mit Benutzer)",
"monitors.broker_topic_kafka": "Topic (optional)",
"monitors.broker_topic_mqtt": "Topic (optional)",
"monitors.broker_user": "Benutzer (optional)",
"monitors.broker_vhost": "Virtueller Host",
"monitors.by_region": "Nach Region",
"monitors.by_region_hint": "Anteil erfolgreicher Checks aus jeder Region. Die SLA sinkt nur, wenn alle Regionen gleichzeitig ausfallen.",
"monitors.confirmations": "Fehlschläge bis zum Alarm",
"monitors.confirmations_hint": "Aufeinanderfolgende Fehlschläge pro Region. Alarm gibt es erst, wenn alle gewählten Regionen ausfallen.",
"monitors.db_database_mongodb": "Authentifizierungs-Datenbank",
"monitors.db_database_mssql": "Datenbank",
"monitors.db_database_mysql": "Datenbank",
"monitors.db_database_postgres": "Datenbank",
"monitors.db_database_redis": "Datenbanknummer (0–15)",
"monitors.db_expect": "Erwarteter erster Wert (optional)",
"monitors.db_hint": "Ziel ist host:port. Verbindet sich, meldet sich an und führt die Abfrage aus; das Passwort wird verschlüsselt gespeichert und nur an Checker übergeben.",
"monitors.db_password": "Passwort",
"monitors.db_query": "Abfrage (optional)",
"monitors.db_tls": "Verschlüsselung",
"monitors.db_tls_disable": "Keine",
"monitors.db_tls_require": "TLS, Zertifikat ungeprüft",
"monitors.db_tls_verify": "TLS mit geprüftem Zertifikat",
"monitors.db_user": "Benutzer",
"monitors.db_user_redis": "Benutzer (ACL, optional)",
"monitors.delete": "Monitor löschen",
"monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?",
"monitors.dns_expect": "Erwartete Antwort (optional)",
"monitors.dns_record": "Record-Typ",
"monitors.dns_resolver": "Resolver (host:port, optional)",
"monitors.docker_hint": "Ziel ist der Container-Name oder die ID. Erreichbar, solange der Container läuft und nicht unhealthy ist. Der Socket ist der Host des Checkers und funktioniert nur auf Checkern, die private Netze erreichen dürfen.",
"monitors.docker_host": "Docker-Host (unix://-Socket oder tcp://host:2375)",
"monitors.edit": "Monitor bearbeiten",
"monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)",
"monitors.follow_redirects": "Weiterleitungen folgen",
"monitors.game_min_free_slots": "Mindestens freie Plätze",
"monitors.game_min_free_slots_hint": "0 prüft nur, ob der Server antwortet.",
"monitors.grace": "Toleranz (Sekunden)",
"monitors.grace_hint": "Wie spät ein Ping sein darf, für Jobs, die manchmal länger laufen.",
"monitors.grpc_hint": "Ziel ist host:port. Fragt den Standard-Health-Service von gRPC (grpc.health.v1); die Antwort muss SERVING sein.",
"monitors.grpc_service": "Service (optional, leer = ganzer Server)",
"monitors.headers": "Request-Header",
"monitors.headers_hint": "Einer pro Zeile, „Name: Wert“. Nur Mitglieder, die den Monitor bearbeiten dürfen, sehen die Werte.",
"monitors.heartbeat_hint": "Dein Job ruft bei jedem Lauf eine geheime URL auf. Kommt innerhalb von Intervall plus Toleranz kein Aufruf, gilt der Monitor als ausgefallen. Die URL wird nach dem Speichern angezeigt.",
@@ -526,8 +950,17 @@
"monitors.keyword_absent": "Fehler, wenn das Keyword vorkommt",
"monitors.last_90d": "Letzte 90 Tage",
"monitors.latency": "Durchschnittliche Latenz",
"monitors.matcher_label": "Label",
"monitors.matchers": "Label-Matcher",
"monitors.matchers_hint": "Wie in Prometheus: = und != vergleichen, =~ und !~ prüfen einen regulären Ausdruck gegen den ganzen Wert.",
"monitors.method": "Methode",
"monitors.minecraft_bedrock": "Bedrock Edition",
"monitors.minecraft_edition": "Edition",
"monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.",
"monitors.minecraft_java": "Java Edition",
"monitors.new": "Neuer Monitor",
"monitors.no_match": "Kein Monitor gefunden.",
"monitors.no_results": "Noch keine Ergebnisse.",
"monitors.op_absent": "fehlt",
"monitors.op_contains": "enthält",
"monitors.op_eq": "gleich",
@@ -547,30 +980,79 @@
"monitors.prom_mode_any": "Eine Serie mit erfüllter Bedingung genügt",
"monitors.prom_query": "PromQL-Abfrage",
"monitors.prom_threshold": "Schwellwert",
"monitors.radius_hint": "Ziel ist host:port (meist 1812). Sendet einen Access-Request mit diesen Zugangsdaten; Access-Accept gilt als erreichbar.",
"monitors.radius_nas": "NAS-Identifier (optional)",
"monitors.radius_secret": "Gemeinsames Geheimnis",
"monitors.range": "Zeitraum",
"monitors.range_not_enough": "Für weniger als die Hälfte dieses Zeitraums liegen bisher Daten vor.",
"monitors.range_note": "SLA und Balken: letzte {{.Range}}",
"monitors.recent": "Letzte Checks",
"monitors.regions": "Regionen",
"monitors.regions_hint": "Geprüft von einem zufälligen Checker jeder gewählten Region. Deine eigenen Regionen stehen oben.",
"monitors.results_title": "Prüfergebnisse",
"monitors.search": "Nach Name oder Ziel suchen",
"monitors.secret_unchanged": "unverändert",
"monitors.show_all": "Alle {{.Count}} anzeigen",
"monitors.sla": "SLA",
"monitors.sla_table": "SLA nach Zeitraum",
"monitors.smtp_hint": "Ziel ist host:port (25, 587 oder 465). Wartet auf die Begrüßung und sendet EHLO; mit Verschlüsselung muss STARTTLS gelingen.",
"monitors.smtp_implicit_tls": "Von Anfang an verschlüsselt (SMTPS, Port 465)",
"monitors.snmp_community": "Community (leer = public)",
"monitors.snmp_cond_any": "beliebiger Wert",
"monitors.snmp_cond_contains": "enthält",
"monitors.snmp_cond_eq": "gleich",
"monitors.snmp_cond_ge": "mindestens",
"monitors.snmp_cond_gt": "größer als",
"monitors.snmp_cond_le": "höchstens",
"monitors.snmp_cond_lt": "kleiner als",
"monitors.snmp_cond_ne": "ungleich",
"monitors.snmp_condition": "Bedingung",
"monitors.snmp_hint": "Ziel ist host:port (meist 161). Liest eine OID per SNMP v1 oder v2c und kann ihren Wert vergleichen.",
"monitors.snmp_oid": "OID",
"monitors.snmp_value": "Wert",
"monitors.snmp_version": "Version",
"monitors.stale_hours": "Verfällt nach (Stunden)",
"monitors.stale_hours_hint": "Ein feuernder Alert, den Alertmanager nicht mehr wiederholt, gilt nach dieser Zeit als beendet. Halte sie über repeat_interval.",
"monitors.steam_hint": "Ziel ist host:port des Query-Ports (meist der Spielport, z. B. 27015). Fragt den Server wie der Steam-Serverbrowser nach seinen Infos (A2S); funktioniert für Source- und die meisten Steam-Spiele.",
"monitors.target": "Ziel",
"monitors.target_hint": "URL für HTTP, host:port für TCP und TLS, Hostname für DNS und ICMP.",
"monitors.target_hint": "URL für HTTP, host:port für TCP, TLS, Datenbanken, Broker (Kafka: mehrere, durch Komma getrennt) und Spieleserver, Hostname für DNS und ICMP, Container-Name für Docker.",
"monitors.timeout": "Timeout (ms)",
"monitors.tls_min_days": "Mindestens Tage bis Ablauf",
"monitors.tls_server_name": "Servername (optional)",
"monitors.type": "Check-Typ",
"monitors.type_alertmanager": "Alertmanager",
"monitors.type_dns": "DNS",
"monitors.type_docker": "Docker-Container",
"monitors.type_grpc": "gRPC",
"monitors.type_heartbeat": "Heartbeat",
"monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)",
"monitors.type_json": "JSON-API",
"monitors.type_kafka": "Kafka",
"monitors.type_minecraft": "Minecraft-Server",
"monitors.type_mongodb": "MongoDB",
"monitors.type_mqtt": "MQTT",
"monitors.type_mssql": "Microsoft SQL Server",
"monitors.type_mysql": "MySQL / MariaDB",
"monitors.type_postgres": "PostgreSQL",
"monitors.type_prometheus": "Prometheus",
"monitors.type_rabbitmq": "RabbitMQ",
"monitors.type_radius": "RADIUS",
"monitors.type_redis": "Redis",
"monitors.type_smtp": "SMTP",
"monitors.type_snmp": "SNMP",
"monitors.type_steam": "Steam-Spieleserver",
"monitors.type_tcp": "TCP-Port",
"monitors.type_tls": "TLS-Zertifikat",
"monitors.ungrouped": "Ohne Gruppe",
"monitors.uptime_chart": "Uptime pro Zeitraum",
"monitors.verify_tls": "TLS-Zertifikat prüfen",
"notify.duration": "Ausgefallen für {{.Duration}}",
"notify.test_body": "Wenn du das lesen kannst, funktioniert der Kanal.",
"notify.title_opened": "{{.Monitor}} ist ausgefallen",
"notify.title_resolved": "{{.Monitor}} ist wieder erreichbar",
"notify.title_test": "Test von UptimeSebi",
"org.check_types_intro": "Monitor-Typen, die den Mitgliedern dieser Organisation angeboten werden, aus denen, die diese Installation anbietet. Bestehende Monitore eines abgeschalteten Typs laufen weiter.",
"org.policy": "Anmelderichtlinie",
"org.require_sso": "SSO verlangen",
"org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.",
@@ -580,6 +1062,18 @@
"org.token_max_days": "Maximale Gültigkeit von API-Tokens (Tage)",
"org.token_max_days_hint": "Neue Tokens müssen innerhalb dieses Zeitraums ablaufen. Beim Speichern werden bestehende Tokens gekürzt, die länger gelten würden. Leer lassen für keine Begrenzung.",
"org.token_max_days_none": "unbegrenzt",
"orgs.create": "Organisation anlegen",
"orgs.first_intro": "Dein Konto ist eingerichtet. Lege eine Organisation für deine Monitore und Statusseiten an.",
"orgs.intro": "Alle Organisationen mit Inhaber, Nutzung und Limits. Ein leeres Limit folgt dem Standard.",
"orgs.invited_hint": "Wurdest du in eine Organisation eingeladen? Öffne stattdessen den Link aus der Einladung.",
"orgs.limits": "Limits dieser Organisation",
"orgs.manage": "Limits, sperren oder löschen …",
"orgs.new_intro": "Du bist Inhaber und kannst andere einladen.",
"orgs.new_title": "Neue Organisation",
"orgs.none": "Keine Organisation gefunden.",
"orgs.owner_orgs": "Organisationen, die der Inhaber besitzen darf (besitzt {{.Count}})",
"orgs.search": "Name, Kürzel oder E-Mail des Inhabers",
"orgs.title": "Organisationen",
"page.component.degraded": "Eingeschränkt",
"page.component.maintenance": "Wartung",
"page.component.operational": "In Betrieb",
@@ -589,6 +1083,9 @@
"one": "vor {{.Count}} Tag",
"other": "vor {{.Count}} Tagen"
},
"page.details_expand": "Details anzeigen",
"page.details_last_24h": "Letzte 24 Stunden",
"page.details_latency_summary": "Ø {{.Avg}} · Max {{.Max}}",
"page.incidents": "Letzte Vorfälle",
"page.maintenance_ongoing": "Laufende Wartung",
"page.maintenance_upcoming": "Geplante Wartung",
@@ -601,6 +1098,14 @@
"page.status.unknown": "Status derzeit nicht verfügbar",
"page.today": "Heute",
"page.updated": "Aktualisiert {{.Time}}",
"pager.earlier": "Frühere",
"pager.first": "Zum Anfang",
"pager.label": "Seiten",
"pager.later": "Spätere",
"pager.newer": "Neuere",
"pager.next": "Weiter",
"pager.older": "Ältere",
"pager.previous": "Zurück",
"pages.accent": "Akzentfarbe (#rrggbb)",
"pages.components": "Monitore auf dieser Seite",
"pages.create": "Statuspage anlegen",
@@ -615,15 +1120,27 @@
"pages.domain_verified": "Domain geprüft.",
"pages.draft": "Entwurf",
"pages.export": "Als HTML exportieren",
"pages.group": "Gruppe",
"pages.group_position": "Reihenfolge",
"pages.groups": "Gruppen",
"pages.groups_import": "Aus Monitor-Gruppen übernehmen",
"pages.groups_import_confirm": "Die Gruppen dieser Statusseite durch die Monitor-Gruppenstruktur der Organisation ersetzen?",
"pages.groups_imported": "Gruppen aus den Monitor-Gruppen übernommen.",
"pages.groups_intro": "Ordne Komponenten in einklappbare, verschachtelte Gruppen – genau wie auf der Monitore-Seite.",
"pages.intro": "Öffentliche Seiten mit dem Zustand ausgewählter Monitore. Jede Seite kann eine eigene Domain nutzen oder als einzelne HTML-Datei exportiert werden.",
"pages.label": "Öffentlicher Name",
"pages.logo": "Logo-URL (https)",
"pages.no_group": "Ohne Gruppe",
"pages.open": "Öffnen",
"pages.page_title": "Titel",
"pages.published": "Veröffentlicht",
"pages.section": "Abschnitt",
"pages.settings": "Einstellungen",
"pages.show_details": "Monitor-Details beim Anklicken anzeigen",
"pages.show_details_hint": "Erlaubt Besuchern eine Detailansicht mit 24h-Verlauf, Latenz, SLA und Regionen-Status. Ziele, Fehlermeldungen und Zugangsdaten bleiben immer privat.",
"pages.slug": "Kurzname (URL)",
"pages.suspended": "vom Betreiber gesperrt",
"pages.suspended_notice": "Der Betreiber hat diese Statusseite gesperrt; sie bleibt offline, bis er sie wieder freigibt.",
"pages.theme": "Theme",
"pages.title": "Statuspages",
"pages.value": "Wert",
@@ -688,6 +1205,7 @@
"security.totp.inactive": "nicht eingerichtet",
"security.totp.qr_alt": "QR-Code für die Authenticator-App",
"security.totp.start": "Einrichten",
"settings.alertmanager": "Prometheus-Alerts als Monitore empfangen.",
"settings.apidocs": "Alle Endpunkte mit ihren Feldern, im OpenAPI-Format.",
"settings.audit": "Wer wann was geändert hat.",
"settings.channels": "Webhooks und E-Mail für Incidents",
@@ -772,6 +1290,7 @@
},
"tokens.revoke_confirm": "Diesen Token widerrufen? Anfragen damit schlagen sofort fehl.",
"tokens.title": "API-Tokens",
"tokens.usage": "Sende den Token bei jeder Anfrage mit:",
"weekday.0": "So",
"weekday.1": "Mo",
"weekday.2": "Di",
+523 -4
View File
@@ -1,6 +1,14 @@
{
"admin.check_types": "Check types",
"admin.check_types_intro": "Switch off types this installation cannot offer, such as Docker on shared cloud checkers or ICMP without the needed privileges. They disappear for new monitors; existing monitors keep running.",
"admin.checker_network": "Checker network",
"admin.intro": "Regions, checkers and status page servers created here are shared by every organization. Organizations add their own under Regions & checkers.",
"admin.platform_private": "Platform checkers may check private addresses",
"admin.platform_private_hint": "Private, loopback, link-local and CGNAT addresses, and the checker host's Docker socket. Leave off where platform checkers share a network with your own infrastructure, as in a hosted service; organizations' own checkers have their own switch.",
"admin.title": "Platform administration",
"agents.allow_private": "May check private addresses",
"agents.allow_private_hint": "Checkers only. Switch off if the checker runs in a network monitors must not look into.",
"agents.allow_private_short": "private addresses",
"agents.create": "Create agent",
"agents.kind": "Kind",
"agents.kind_checker": "Checker",
@@ -10,6 +18,35 @@
"agents.region": "Region",
"agents.revoke_confirm": "Revoke this agent? Its instances stop working immediately.",
"agents.token_now": "Copy the token now and set it as UPTIME_AGENT_TOKEN. It will not be shown again. Any number of instances may share it.",
"alert_groups.create": "Create group",
"alert_groups.default": "Default group",
"alert_groups.delete_confirm": "Delete this alert group? Its monitors will no longer notify its channels unless another assigned group includes them.",
"alert_groups.intro": "Bundle notification channels and assign groups to monitors. New monitors and channels are automatically assigned to the default group. Channels shared by several groups receive each alert only once.",
"alert_groups.monitor_hint": "Select the groups that should receive alerts. No selection disables notifications for this monitor.",
"alert_groups.new": "New alert group",
"alert_groups.no_channels": "Create a notification channel below to receive alerts.",
"alert_groups.quiet_active": "Quiet hours active",
"alert_groups.quiet_add": "Add quiet period",
"alert_groups.quiet_end": "Until",
"alert_groups.quiet_hint": "Suppress notifications from this group during these times (incidents are still recorded). Leave weekdays unchecked for every day; 00:00 to 00:00 covers the whole day.",
"alert_groups.quiet_remove": "Remove",
"alert_groups.quiet_start": "From",
"alert_groups.quiet_title": "Quiet hours",
"alert_groups.save": "Save group",
"alert_groups.title": "Alert groups",
"alertmanager.config_hint": "Add it to alertmanager.yml as a webhook receiver; send_resolved is needed so monitors recover.",
"alertmanager.copy_now": "Copy the URL now; it is not shown again. It contains a secret.",
"alertmanager.create_monitor": "Create monitor",
"alertmanager.create_receiver": "Create receiver",
"alertmanager.delete_confirm": "Delete this receiver? Alertmanager can no longer send alerts with its URL.",
"alertmanager.firing": "Firing alerts",
"alertmanager.intro": "Let Alertmanager send its alerts here. Monitors of type Alertmanager are down while a matching alert fires, with incidents, notifications and SLA like any other monitor.",
"alertmanager.last_received": "last alert: {{.Time}}",
"alertmanager.no_alerts": "No alert is firing.",
"alertmanager.receivers": "Receivers",
"alertmanager.since": "since {{.Time}}",
"alertmanager.title": "Alertmanager",
"apidocs.footer": "API",
"apidocs.hint": "\"Try it out\" uses your current session.",
"apidocs.title": "API documentation",
"app.network_error": "Connection failed.",
@@ -19,8 +56,15 @@
"audit.action.account.signup": "Account created",
"audit.action.account.totp_disable": "Two-factor authentication disabled",
"audit.action.account.totp_enable": "Two-factor authentication enabled",
"audit.action.account.verify": "Email address confirmed",
"audit.action.agent.create": "Agent created",
"audit.action.agent.delete": "Agent revoked",
"audit.action.agent.update": "Agent changed",
"audit.action.alert_group.create": "Alert group created",
"audit.action.alert_group.delete": "Alert group deleted",
"audit.action.alert_group.update": "Alert group changed",
"audit.action.alertmanager.receiver_create": "Alertmanager receiver created",
"audit.action.alertmanager.receiver_delete": "Alertmanager receiver deleted",
"audit.action.auth.login": "Signed in",
"audit.action.auth.login_failed": "Sign-in failed",
"audit.action.auth.login_sso": "Signed in with SSO",
@@ -44,15 +88,28 @@
"audit.action.monitor.create": "Monitor created",
"audit.action.monitor.delete": "Monitor deleted",
"audit.action.monitor.update": "Monitor changed",
"audit.action.org.check_types_update": "Check types changed",
"audit.action.org.create": "Organization created",
"audit.action.org.delete": "Organization deleted",
"audit.action.org.export": "Organization data exported",
"audit.action.org.legal_update": "Legal document changed",
"audit.action.org.policy_update": "Security policy changed",
"audit.action.platform.agent_create": "Platform agent created",
"audit.action.platform.agent_delete": "Platform agent revoked",
"audit.action.platform.check_types_update": "Check types changed",
"audit.action.platform.checker_network_update": "Checker network changed",
"audit.action.platform.legal_update": "Platform legal document changed",
"audit.action.platform.limits_update": "Default limits changed",
"audit.action.platform.org_delete": "Organization deleted by admin",
"audit.action.platform.org_limits_update": "Organization limits changed",
"audit.action.platform.org_suspension": "Organization suspended or reinstated",
"audit.action.platform.region_create": "Platform region created",
"audit.action.platform.region_delete": "Platform region deleted",
"audit.action.platform.status_page_delete": "Status page deleted by admin",
"audit.action.platform.status_page_suspension": "Status page suspended or reinstated",
"audit.action.platform.user_delete": "Account deleted by admin",
"audit.action.platform.user_limits_update": "Account limits changed",
"audit.action.platform.user_suspension": "Account suspended or reinstated",
"audit.action.region.create": "Region created",
"audit.action.region.delete": "Region deleted",
"audit.action.role.create": "Role created",
@@ -65,6 +122,10 @@
"audit.action.statuspage.delete": "Status page deleted",
"audit.action.statuspage.domain_update": "Custom domain changed",
"audit.action.statuspage.domain_verify": "Custom domain verified",
"audit.action.statuspage.group_create": "Status page group created",
"audit.action.statuspage.group_delete": "Status page group deleted",
"audit.action.statuspage.group_update": "Status page group changed",
"audit.action.statuspage.groups_import": "Status page groups imported from monitor groups",
"audit.action.statuspage.monitors_update": "Status page monitors changed",
"audit.action.statuspage.update": "Status page changed",
"audit.action.token.create": "API token created",
@@ -72,7 +133,6 @@
"audit.deleted_user": "Deleted user",
"audit.empty": "No entries yet.",
"audit.intro": "Changes in this organization: who did what and when, from which address. Entries cannot be edited.",
"audit.older": "Older entries",
"audit.platform_intro": "Changes to platform regions and agents, and sign-in attempts for unknown accounts.",
"audit.platform_title": "Platform audit log",
"audit.title": "Audit log",
@@ -95,19 +155,279 @@
"auth.sso.heading": "Single sign-on",
"auth.sso.org_placeholder": "Organization short name",
"auth.sso.submit": "Continue",
"auth.verify.intro": "Press the button to confirm your email address and sign in.",
"auth.verify.resend_intro": "If an unconfirmed account uses this address, we send it a new link.",
"auth.verify.resend_link": "Resend the confirmation email",
"auth.verify.resend_submit": "Send link",
"auth.verify.resend_title": "New confirmation link",
"auth.verify.sent": "We sent you a link to confirm your email address. It is valid for 24 hours.",
"auth.verify.sent_hint": "Nothing arrived? Look in your spam folder, or ask for a new link.",
"auth.verify.sent_title": "Check your inbox",
"auth.verify.submit": "Confirm and sign in",
"auth.verify.title": "Confirm your email address",
"channels.create": "Create channel",
"channels.created": "Webhook created. It is already in the default alert group. Copy the signing secret before continuing.",
"channels.delete_confirm": "Delete this channel?",
"channels.intro": "Every enabled channel is notified when a monitor goes down in all of its regions and when it recovers.",
"channels.field_access_key": "Access key",
"channels.field_access_key_id": "AccessKey ID",
"channels.field_access_key_secret": "AccessKey secret",
"channels.field_access_token": "Access token",
"channels.field_account_sid": "Account SID",
"channels.field_action_group_id": "Action group ID",
"channels.field_answer_url": "Answer URL (for calls)",
"channels.field_api_key": "API key",
"channels.field_api_token": "API token",
"channels.field_api_url": "API URL",
"channels.field_api_version": "API version",
"channels.field_app_token": "Application token",
"channels.field_auth_id": "Auth ID",
"channels.field_auth_token": "Auth token",
"channels.field_bcc_email": "BCC (comma-separated)",
"channels.field_bot_id": "Bot ID",
"channels.field_bot_key": "Bot key",
"channels.field_bot_secret": "Bot secret",
"channels.field_bot_token": "Bot token",
"channels.field_cc_email": "CC (comma-separated)",
"channels.field_channel": "Channel",
"channels.field_channel_id": "Channel ID",
"channels.field_chat_id": "Chat ID",
"channels.field_chat_ids": "Chat IDs (comma-separated)",
"channels.field_client_id": "Client ID",
"channels.field_client_key": "Client key",
"channels.field_client_secret": "Client secret",
"channels.field_cloud_id": "Cloud ID",
"channels.field_config_key": "Configuration key",
"channels.field_consumer_key": "Consumer key",
"channels.field_consumer_secret": "Consumer secret",
"channels.field_conversation_token": "Conversation token",
"channels.field_device": "Device",
"channels.field_device_id": "Device ID",
"channels.field_device_token": "Device token",
"channels.field_email": "Account email",
"channels.field_endpoint_url": "Endpoint URL",
"channels.field_environment": "Environment",
"channels.field_from_email": "Sender address",
"channels.field_from_name": "Sender name",
"channels.field_gateway": "Gateway type",
"channels.field_gateway_id": "Gateway ID (sender)",
"channels.field_gateway_secret": "Gateway secret",
"channels.field_group": "Group",
"channels.field_group_ids": "Group IDs (comma-separated)",
"channels.field_hash_key": "Hash key",
"channels.field_homeserver_url": "Homeserver URL",
"channels.field_instance": "Instance",
"channels.field_integration_key": "Integration key or push URL",
"channels.field_integration_url": "Integration URL",
"channels.field_line_number": "Line number",
"channels.field_mailbox": "Sending mailbox",
"channels.field_mentioned_mobiles": "Mention mobiles (comma-separated)",
"channels.field_message_type": "Message type",
"channels.field_messaging_profile_id": "Messaging profile ID",
"channels.field_messaging_service_sid": "Messaging service SID",
"channels.field_modem": "Modem ID",
"channels.field_number": "Sender number",
"channels.field_originator_type": "Sender type",
"channels.field_password": "Password",
"channels.field_peer_id": "Peer ID",
"channels.field_phone_number": "Phone number",
"channels.field_phone_numbers": "Phone numbers (comma-separated)",
"channels.field_platform": "Platform",
"channels.field_priority": "Priority",
"channels.field_publish_url": "Publish URL",
"channels.field_push_key": "Push key",
"channels.field_receiver_id": "Receiver ID",
"channels.field_recipient": "Recipient",
"channels.field_recipient_type": "Recipient type",
"channels.field_recipients": "Recipients (comma-separated)",
"channels.field_region": "Region",
"channels.field_relays": "Relays (wss://, comma-separated)",
"channels.field_rest_url": "REST endpoint URL (with routing key)",
"channels.field_room_id": "Room ID",
"channels.field_routing_key": "Integration key",
"channels.field_send_key": "SendKey",
"channels.field_sender": "Sender",
"channels.field_sender_nsec": "Sender private key (nsec)",
"channels.field_server_url": "Server URL",
"channels.field_service": "Notify service (default: notify)",
"channels.field_session": "Session",
"channels.field_severity": "Severity",
"channels.field_sign_name": "Signature name",
"channels.field_sign_secret": "Signing secret",
"channels.field_sms_type": "SMS type",
"channels.field_sound": "Sound",
"channels.field_spt": "SPT tokens (comma-separated)",
"channels.field_subject": "Subject (default: incident title)",
"channels.field_target": "Target",
"channels.field_target_id": "Device or user ID",
"channels.field_template_code": "Template code",
"channels.field_template_id": "Template ID",
"channels.field_template_key": "Template key",
"channels.field_tenant_id": "Tenant ID",
"channels.field_thread_id": "Topic ID (forum groups)",
"channels.field_to_email": "Recipients (comma-separated)",
"channels.field_token": "Token",
"channels.field_topic": "Topic",
"channels.field_trigger_id": "Trigger ID",
"channels.field_urgency": "Urgency",
"channels.field_urls": "Apprise URLs",
"channels.field_user_id": "User ID",
"channels.field_user_key": "User key",
"channels.field_username": "Username",
"channels.field_variable_id": "Variable ID",
"channels.field_webhook_url": "Webhook URL",
"channels.field_workspace_id": "Workspace ID",
"channels.group_chat": "Chat and messengers",
"channels.group_email": "Email services",
"channels.group_incident": "Incident management",
"channels.group_other": "More",
"channels.group_push": "Push",
"channels.group_sms": "SMS and calls",
"channels.help_aliyunsms": "The template receives the parameters name, time, status and msg.",
"channels.help_apprise": "Reaches over 100 services through an Apprise API server: give Apprise URLs or the key of a configuration stored there.",
"channels.help_bark": "The endpoint includes your device key, e.g. https://api.day.app/KEY.",
"channels.help_callmebot": "The URL CallMeBot sent you, with phone number and API key.",
"channels.help_dingtalk": "The robot's webhook URL; add the signing secret if the robot uses \"additional signature\".",
"channels.help_freemobile": "Texts the phone of the Free Mobile account; enable \"Notifications par SMS\" in its options.",
"channels.help_googlesheets": "The URL of a Google Apps Script web app that appends the posted fields as a row.",
"channels.help_homeassistant": "Uses a long-lived access token. The service is the part after notify., e.g. mobile_app_phone; persistent_notification shows it in Home Assistant.",
"channels.help_keep": "Uses Keep's Uptime Kuma integration.",
"channels.help_microsoftgraph": "Needs an app registration in Microsoft Entra with the Mail.Send application permission; mail is sent as the mailbox.",
"channels.help_nostr": "Sends an encrypted private message (NIP-17) from the sender key to each npub through the relays.",
"channels.help_opsgenie": "The alert closes when the incident is resolved.",
"channels.help_opsimate": "Uses OpsiMate's Uptime Kuma integration.",
"channels.help_pagerduty": "Use the integration key of an Events API v2 integration; resolving closes the PagerDuty incident.",
"channels.help_pinglet": "Uses Pinglet's Uptime Kuma format.",
"channels.help_plivo": "For calls, the answer URL must return Plivo XML; the message is passed as the message parameter.",
"channels.help_signal": "Needs a signal-cli REST API server (bbernhard/signal-cli-rest-api) with a registered number.",
"channels.help_smsir": "sms.ir sends verify templates; the template needs a parameter named uptkumaalert, which gets the monitor and its state.",
"channels.help_splunk": "The REST endpoint from Splunk On-Call's REST integration, ending in the routing key.",
"channels.help_teams": "Use the URL of a Teams workflow \"Post to a channel when a webhook request is received\".",
"channels.help_telegram": "Create a bot with @BotFather; the chat ID of a group starts with -100.",
"channels.intro": "Enabled channels receive outage and recovery alerts from monitors assigned to their alert groups.",
"channels.language": "Language",
"channels.manage_groups": "Secret copied — manage alert groups",
"channels.new_email": "New email channel",
"channels.new_service": "Other services",
"channels.new_webhook": "New webhook",
"channels.optional": "optional",
"channels.secret_now": "Signing secret: verify the X-Uptimesebi-Signature header with it. It will not be shown again.",
"channels.service": "Service",
"channels.service_intro": "Chat, push and paging services. Tokens and keys are stored encrypted and never shown again.",
"channels.test": "Send test",
"channels.test_ok": "Test notification delivered.",
"channels.title": "Notifications",
"channels.to": "Recipients",
"channels.type_alerta": "Alerta",
"channels.type_alertnow": "AlertNow",
"channels.type_aliyunsms": "Alibaba Cloud SMS",
"channels.type_amootsms": "Amoot SMS",
"channels.type_apprise": "Apprise",
"channels.type_bale": "Bale",
"channels.type_bark": "Bark",
"channels.type_bearsms": "BearSMS",
"channels.type_bitrix": "Bitrix24",
"channels.type_brevo": "Brevo",
"channels.type_callmebot": "CallMeBot",
"channels.type_cellsynt": "Cellsynt",
"channels.type_clicksend": "ClickSend SMS",
"channels.type_clickup": "ClickUp Chat",
"channels.type_dingtalk": "DingTalk",
"channels.type_discord": "Discord",
"channels.type_egosms": "EgoSMS",
"channels.type_elks46": "46elks",
"channels.type_email": "Email",
"channels.type_evolution": "Evolution API (WhatsApp)",
"channels.type_feishu": "Feishu / Lark",
"channels.type_flashduty": "Flashduty",
"channels.type_flowtriq": "Flowtriq",
"channels.type_fluxer": "Fluxer",
"channels.type_freemobile": "Free Mobile",
"channels.type_goalert": "GoAlert",
"channels.type_googlechat": "Google Chat",
"channels.type_googlesheets": "Google Sheets",
"channels.type_gorush": "Gorush",
"channels.type_gotify": "Gotify",
"channels.type_grafanaoncall": "Grafana OnCall",
"channels.type_gtxmessaging": "GTX Messaging",
"channels.type_halopsa": "HaloPSA",
"channels.type_heiioncall": "Heii On-Call",
"channels.type_homeassistant": "Home Assistant",
"channels.type_indigo": "Indigo",
"channels.type_jsm": "Jira Service Management",
"channels.type_keep": "Keep",
"channels.type_kook": "KOOK",
"channels.type_line": "LINE Messaging API",
"channels.type_lunasea": "LunaSea",
"channels.type_matrix": "Matrix",
"channels.type_mattermost": "Mattermost",
"channels.type_max": "MAX",
"channels.type_messenger360": "360messenger (WhatsApp)",
"channels.type_microsoftgraph": "Microsoft 365 (Graph)",
"channels.type_milky": "Milky (QQ)",
"channels.type_nextcloudtalk": "Nextcloud Talk",
"channels.type_nostr": "Nostr",
"channels.type_notifery": "Notifery",
"channels.type_notifyapp": "NotifyApp",
"channels.type_ntfy": "ntfy",
"channels.type_octopush": "Octopush",
"channels.type_onebot": "OneBot (QQ)",
"channels.type_onechat": "OneChat",
"channels.type_onesender": "OneSender (WhatsApp)",
"channels.type_ooredoo": "Ooredoo Maldives",
"channels.type_openwa": "OpenWA (WhatsApp)",
"channels.type_opsgenie": "Opsgenie",
"channels.type_opsimate": "OpsiMate",
"channels.type_pagerduty": "PagerDuty",
"channels.type_pagertree": "PagerTree",
"channels.type_pinglet": "Pinglet",
"channels.type_plivo": "Plivo",
"channels.type_promosms": "PromoSMS",
"channels.type_pumble": "Pumble",
"channels.type_pushbullet": "Pushbullet",
"channels.type_pushdeer": "PushDeer",
"channels.type_pushover": "Pushover",
"channels.type_pushplus": "PushPlus",
"channels.type_pushy": "Pushy",
"channels.type_resend": "Resend",
"channels.type_rocketchat": "Rocket.Chat",
"channels.type_sendgrid": "SendGrid",
"channels.type_serverchan": "ServerChan",
"channels.type_serwersms": "SerwerSMS.pl",
"channels.type_sevenio": "seven",
"channels.type_signal": "Signal",
"channels.type_signalgrid": "Signalgrid",
"channels.type_signl4": "SIGNL4",
"channels.type_slack": "Slack",
"channels.type_smsc": "SMSC",
"channels.type_smseagle": "SMSEagle",
"channels.type_smsgateway": "SMS Gateway for Android",
"channels.type_smsir": "sms.ir",
"channels.type_smsmanager": "SmsManager",
"channels.type_smspartner": "SMS Partner",
"channels.type_smsplanet": "SMSPlanet",
"channels.type_splunk": "Splunk On-Call (VictorOps)",
"channels.type_spugpush": "Spug Push",
"channels.type_squadcast": "Squadcast",
"channels.type_stackfield": "Stackfield",
"channels.type_teams": "Microsoft Teams",
"channels.type_techulus": "Techulus Push",
"channels.type_telegram": "Telegram",
"channels.type_telnyx": "Telnyx",
"channels.type_teltonika": "Teltonika router",
"channels.type_threema": "Threema",
"channels.type_trigv": "Trigv",
"channels.type_turbosmtp": "turboSMTP",
"channels.type_twilio": "Twilio",
"channels.type_vk": "VK",
"channels.type_vkteams": "VK Teams",
"channels.type_waha": "WAHA (WhatsApp)",
"channels.type_webhook": "Webhook",
"channels.type_wecom": "WeCom (WeChat Work)",
"channels.type_whapi": "Whapi (WhatsApp)",
"channels.type_wpush": "WPush",
"channels.type_wxpusher": "WxPusher",
"channels.type_yunzhijia": "Yunzhijia",
"channels.type_zohocliq": "Zoho Cliq",
"channels.url": "Webhook URL",
"checkers.avg_latency": "Average latency",
"checkers.for": "for {{.Duration}}",
@@ -148,35 +468,48 @@
"console.nav.settings": "Settings",
"console.nav.sso": "SSO",
"console.nav.tokens": "API tokens",
"console.org_suspended": "The operator suspended this organization: its monitors are not checked and its status pages are offline.",
"console.sso_required_action": "Sign in with SSO",
"console.suspended_reason": "Reason: {{.Reason}}",
"console.totp_missing_action": "Set up now",
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.",
"email.opened.subject": "[DOWN] {{.Monitor}}",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
"email.resolved.subject": "[UP] {{.Monitor}}",
"email.test.body": "This is a test. If you can read it, the channel works.",
"email.test.subject": "Test notification from uptimesebi",
"email.test.subject": "Test notification from UptimeSebi",
"email.verify.body": "Hello,\n\nplease confirm your email address to finish signing up:\n\n{{.Link}}\n\nThe link is valid for {{.Hours}} hours. If you did not sign up, ignore this email; the account is deleted after a week.",
"email.verify.subject": "Confirm your email address for UptimeSebi",
"error.account_suspended": "This account is suspended. Contact the operator.",
"error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.",
"error.alert_group_not_deletable": "The group does not exist or is the protected default group.",
"error.all_check_types_disabled": "Leave at least one check type on.",
"error.already_assigned": "The member already has this role.",
"error.already_member": "This person is already a member.",
"error.channel_test_failed": "The test notification could not be delivered.",
"error.channel_type_immutable": "The type of a channel cannot be changed.",
"error.check_type_disabled": "This check type is switched off for this organization or installation.",
"error.confirmation_failed": "The confirmation does not match.",
"error.domain_not_verified": "The TXT record was not found yet. DNS changes can take a while to appear.",
"error.domain_taken": "This domain is already used by another status page.",
"error.email_not_configured": "Email is not available on this server.",
"error.email_taken": "This email address is already registered.",
"error.email_unverified": "Confirm your email address first; we mailed you a link. You can ask for a new one below.",
"error.forbidden": "You are not allowed to do this.",
"error.group_cycle": "A group cannot be placed inside itself or one of its subgroups.",
"error.group_too_deep": "Groups can be nested at most eight levels deep.",
"error.internal": "Internal error.",
"error.invalid_alert_group": "An alert group does not exist in this organization.",
"error.invalid_assertion_op": "Unknown condition operator.",
"error.invalid_assertion_path": "A condition path is invalid. Use keys separated by dots and [n] for array elements.",
"error.invalid_assertion_value": "Comparisons with <, >, ≤ and ≥ need a number.",
"error.invalid_assertions": "Add between 1 and 10 conditions.",
"error.invalid_channel": "A notification channel does not exist in this organization.",
"error.invalid_channel_settings": "Fill in the required fields; addresses must be https URLs.",
"error.invalid_code": "Invalid code.",
"error.invalid_config": "The check settings are not valid.",
"error.invalid_credentials": "Wrong email or password.",
"error.invalid_cursor": "This page link is invalid; start from the first page.",
"error.invalid_domain": "One of the domains is not valid.",
"error.invalid_email": "Please enter a valid email address.",
"error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.",
@@ -187,17 +520,21 @@
"error.invalid_interval": "The interval must be at least {{.Min}} seconds and at most one day.",
"error.invalid_json_body": "The request body is not valid JSON.",
"error.invalid_legal_url": "The link must be an http or https URL.",
"error.invalid_limit": "limit must be between 1 and {{.Max}}.",
"error.invalid_maintenance_duration": "The duration must be between 1 minute and 30 days.",
"error.invalid_maintenance_time": "Check start, weekdays and last day.",
"error.invalid_matchers": "Add 1 to 20 label matchers with valid label names and regular expressions.",
"error.invalid_method": "Only GET and HEAD requests are supported.",
"error.invalid_monitor": "One of the monitors does not exist or is listed twice.",
"error.invalid_permissions": "Choose at least one permission.",
"error.invalid_query": "Enter a PromQL query of at most 2000 characters.",
"error.invalid_quiet_hours": "Check start time, end time and weekdays of the quiet hours.",
"error.invalid_record": "Unsupported DNS record type.",
"error.invalid_region": "Unknown region.",
"error.invalid_region_key": "Region keys use 1–40 characters: a–z, 0–9 and hyphen.",
"error.invalid_resolver": "The resolver must be given as host:port.",
"error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.",
"error.invalid_stale_hours": "The stale period must be between 1 hour and 30 days.",
"error.invalid_target": "The target is not valid for this check type.",
"error.invalid_theme": "The theme settings are not valid: accent as #rrggbb, logo as https URL, CSS without \"</\".",
"error.invalid_time_zone": "Unknown time zone. Use a name like Europe/Berlin.",
@@ -211,25 +548,31 @@
"error.maintenance_overlaps": "The maintenance would last longer than the time until it repeats.",
"error.maintenance_without_targets": "Choose at least one monitor or group.",
"error.mfa_expired": "Sign-in expired, please start again.",
"error.monitor_limit": "Your organization has reached its limit of {{.Max}} monitors.",
"error.no_domain": "Set a custom domain first.",
"error.no_password": "This account has no password.",
"error.not_found": "Not found.",
"error.org_limit": "Your account may own at most {{.Max}} organizations.",
"error.org_not_found": "Organization not found.",
"error.org_suspended": "The operator suspended this organization.",
"error.owner_cannot_be_removed": "The owner cannot be removed.",
"error.owner_has_all_permissions": "The owner already has every permission.",
"error.owns_shared_orgs": "You own organizations with other members. Hand them over or delete them first.",
"error.password_too_short": "The password needs at least {{.Min}} characters.",
"error.permission_escalation": "You cannot grant permissions you do not hold yourself.",
"error.platform_region_limit": "A monitor may be checked from at most {{.Max}} platform regions; your own checker regions do not count.",
"error.policy_would_lock_you_out": "Your current sign-in does not meet this policy. Meet it first, then turn it on.",
"error.rate_limited": "Too many attempts, please try again later.",
"error.region_in_use": "The region is still used by monitors or agents.",
"error.region_key_taken": "A region with this key already exists.",
"error.region_limit": "A monitor may be checked from at most {{.Max}} regions.",
"error.role_built_in": "Built-in roles cannot be changed.",
"error.role_in_use": "The role is still assigned to members.",
"error.role_name_taken": "A role with this name already exists.",
"error.role_not_found": "Role not found.",
"error.session_required": "This action is not available to API tokens.",
"error.signup_closed": "Sign-up is disabled.",
"error.signup_limit": "Too many accounts were created from your network today. Try again tomorrow.",
"error.slug_taken": "This short name is already taken.",
"error.sso_denied": "Sign-in was cancelled at the identity provider.",
"error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.",
@@ -244,6 +587,8 @@
"error.sso_provider_error": "The identity provider could not complete the sign-in.",
"error.sso_required_by_org": "This organization requires signing in through its SSO provider.",
"error.sso_unavailable": "Single sign-on is not available for this organization.",
"error.status_page_limit": "Your organization has reached its limit of {{.Max}} status pages.",
"error.target_is_admin": "Platform admins cannot be suspended or deleted here.",
"error.token_lifetime_exceeds_policy": {
"one": "Tokens in this organization must expire within {{.Count}} day.",
"other": "Tokens in this organization must expire within {{.Count}} days."
@@ -253,6 +598,9 @@
"error.totp_setup_expired": "Setup expired, please start again.",
"error.unauthenticated": "Authentication required.",
"error.unsupported_locale": "Unsupported language.",
"error.user_owns_shared_orgs": "The account owns organizations with other members. Delete those or hand them over first.",
"error.verification_expired": "This confirmation link is invalid or expired. Ask for a new one.",
"error.verification_mail_failed": "Your account was created, but the confirmation email could not be sent. Ask for a new link in a while.",
"evidence.body": "Response body",
"evidence.body_binary": "Binary content, not stored.",
"evidence.body_empty": "Empty.",
@@ -403,7 +751,10 @@
"groups.none": "– top level –",
"groups.parent": "Inside group",
"groups.title": "Monitor groups",
"incidents.all": "All incidents",
"incidents.all_of_monitor": "All incidents of this monitor",
"incidents.none": "No incidents so far.",
"incidents.of_monitor": "Incidents of",
"incidents.ongoing": "ongoing",
"incidents.resolved": "resolved",
"incidents.title": "Incidents",
@@ -423,6 +774,20 @@
"legal.platform_title": "Platform legal notice & privacy",
"legal.privacy": "Privacy policy",
"legal.url": "Link to an existing page",
"limits.default": "default: {{.Value}}",
"limits.intro": "Apply to every organization and account without an override of its own, also when you change them later. 0 means unlimited. Lowering a limit keeps everything that exists; only new monitors, status pages, regions or organizations are refused.",
"limits.monitors": "Monitors",
"limits.org_title": "Usage",
"limits.orgs_per_account": "Organizations per account",
"limits.own_false": "do not count",
"limits.own_regions_count": "Own checker regions count towards the region limit",
"limits.own_regions_count_hint": "Off: organizations may add as many of their own regions as they like; only platform regions are limited.",
"limits.own_regions_free": "Your own checker regions do not count towards the region limit.",
"limits.own_true": "count",
"limits.regions_per_monitor": "Regions per monitor",
"limits.status_pages": "Status pages",
"limits.title": "Default limits",
"limits.unlimited": "unlimited",
"maintenance.delete_confirm": "Delete this maintenance window and all its repeats?",
"maintenance.edit": "Edit maintenance",
"maintenance.empty": "No maintenance planned.",
@@ -496,25 +861,84 @@
"members.scope_org": "whole organization",
"members.title": "Members",
"members.unassign": "Remove role",
"moderation.actions": "Suspend or delete …",
"moderation.created": "Created",
"moderation.delete_confirm_org": "Delete the organization {{.Name}} with all its monitors, results and status pages for good?",
"moderation.delete_confirm_owner": "Delete the account {{.Name}} for good? Organizations only it belongs to go with it.",
"moderation.delete_confirm_page": "Delete the status page {{.Name}} for good?",
"moderation.delete_org": "Delete organization",
"moderation.delete_owner": "Delete account",
"moderation.delete_page": "Delete status page",
"moderation.intro": "Every published status page, and every page, organization or account that is suspended, with the organization and its owner behind it. Suspending can be undone and shows the reason to the organization; deleting cannot be undone.",
"moderation.none": "No status page matches.",
"moderation.org": "Organization",
"moderation.owner": "Owner",
"moderation.owner_is_admin": "The owner is a platform admin and cannot be suspended or deleted here.",
"moderation.page": "Status page",
"moderation.reason": "Reason (optional)",
"moderation.reinstate": "Reinstate",
"moderation.search": "Title, address, organization or email",
"moderation.search_button": "Search",
"moderation.suspend": "Suspend",
"moderation.suspended": "Suspended",
"moderation.target_org": "Organization",
"moderation.target_owner": "Owner account",
"moderation.target_page": "Status page",
"moderation.title": "Public status pages",
"monitors.alertmanager_hint": "Down while an alert matching all matchers fires. Alerts arrive through a receiver:",
"monitors.all": "All monitors",
"monitors.all_results": "All results",
"monitors.assertion_op": "Operator",
"monitors.assertion_path": "Path",
"monitors.assertion_value": "Value",
"monitors.assertions": "Conditions",
"monitors.assertions_hint": "All must hold. Paths like status.database or checks[0].state; empty rows are ignored.",
"monitors.broker_expect": "Message must contain (optional)",
"monitors.broker_hint_kafka": "Target is one or more brokers as host:port. Fetches the cluster metadata; with a topic, it must exist and every partition must have a leader.",
"monitors.broker_hint_mqtt": "Target is host:port (usually 1883, 8883 with TLS). Signs in; with a topic, a message must arrive within the timeout (retained messages count).",
"monitors.broker_hint_rabbitmq": "Target is host:port of the AMQP port (usually 5672, 5671 with TLS). Signs in and opens a channel; with a queue, it must exist.",
"monitors.broker_message": "Produce this message to the topic (optional)",
"monitors.broker_queue": "Queue (optional)",
"monitors.broker_sasl": "SASL mechanism (with user)",
"monitors.broker_topic_kafka": "Topic (optional)",
"monitors.broker_topic_mqtt": "Topic (optional)",
"monitors.broker_user": "User (optional)",
"monitors.broker_vhost": "Virtual host",
"monitors.by_region": "By region",
"monitors.by_region_hint": "Share of successful checks from each region. The SLA only drops when all regions fail at the same time.",
"monitors.confirmations": "Failures before alerting",
"monitors.confirmations_hint": "Consecutive failures per region. An alert needs every selected region to fail.",
"monitors.db_database_mongodb": "Authentication database",
"monitors.db_database_mssql": "Database",
"monitors.db_database_mysql": "Database",
"monitors.db_database_postgres": "Database",
"monitors.db_database_redis": "Database number (0–15)",
"monitors.db_expect": "Expected first value (optional)",
"monitors.db_hint": "Target is host:port. Connects, signs in and runs the query; the password is stored encrypted and only handed to checkers.",
"monitors.db_password": "Password",
"monitors.db_query": "Query (optional)",
"monitors.db_tls": "Encryption",
"monitors.db_tls_disable": "None",
"monitors.db_tls_require": "TLS, certificate not verified",
"monitors.db_tls_verify": "TLS with verified certificate",
"monitors.db_user": "User",
"monitors.db_user_redis": "User (ACL, optional)",
"monitors.delete": "Delete monitor",
"monitors.delete_confirm": "Delete this monitor and its history?",
"monitors.dns_expect": "Expected answer (optional)",
"monitors.dns_record": "Record type",
"monitors.dns_resolver": "Resolver (host:port, optional)",
"monitors.docker_hint": "Target is the container name or ID. Up while the container runs and is not unhealthy. The socket is the checker's own host and only works on checkers allowed to reach private networks.",
"monitors.docker_host": "Docker host (unix:// socket or tcp://host:2375)",
"monitors.edit": "Edit monitor",
"monitors.expect_status": "Expected status (e.g. 2xx, 301)",
"monitors.follow_redirects": "Follow redirects",
"monitors.game_min_free_slots": "Minimum free slots",
"monitors.game_min_free_slots_hint": "0 only checks that the server answers.",
"monitors.grace": "Grace period (seconds)",
"monitors.grace_hint": "How late a ping may be, for jobs that sometimes run longer.",
"monitors.grpc_hint": "Target is host:port. Asks the standard gRPC health service (grpc.health.v1); the answer must be SERVING.",
"monitors.grpc_service": "Service (optional, empty = whole server)",
"monitors.headers": "Request headers",
"monitors.headers_hint": "One per line, \"Name: value\". Only members who may edit the monitor see the values.",
"monitors.heartbeat_hint": "Your job calls a secret URL each time it runs. If no call arrives within the interval plus the grace period, the monitor is down. The URL is shown after saving.",
@@ -526,8 +950,17 @@
"monitors.keyword_absent": "Fail if the keyword is present",
"monitors.last_90d": "Last 90 days",
"monitors.latency": "Average latency",
"monitors.matcher_label": "Label",
"monitors.matchers": "Label matchers",
"monitors.matchers_hint": "As in Prometheus: = and != compare, =~ and !~ match a regular expression against the whole value.",
"monitors.method": "Method",
"monitors.minecraft_bedrock": "Bedrock Edition",
"monitors.minecraft_edition": "Edition",
"monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.",
"monitors.minecraft_java": "Java Edition",
"monitors.new": "New monitor",
"monitors.no_match": "No monitor matches.",
"monitors.no_results": "No results yet.",
"monitors.op_absent": "is absent",
"monitors.op_contains": "contains",
"monitors.op_eq": "equals",
@@ -547,30 +980,79 @@
"monitors.prom_mode_any": "One series meeting the condition is enough",
"monitors.prom_query": "PromQL query",
"monitors.prom_threshold": "Threshold",
"monitors.radius_hint": "Target is host:port (usually 1812). Sends an Access-Request with these credentials; Access-Accept counts as up.",
"monitors.radius_nas": "NAS identifier (optional)",
"monitors.radius_secret": "Shared secret",
"monitors.range": "Time range",
"monitors.range_not_enough": "Less than half of this period is covered by data yet.",
"monitors.range_note": "SLA and bars: last {{.Range}}",
"monitors.recent": "Recent checks",
"monitors.regions": "Regions",
"monitors.regions_hint": "Checked from a random checker in each selected region. Your own regions are listed first.",
"monitors.results_title": "Check results",
"monitors.search": "Search by name or target",
"monitors.secret_unchanged": "unchanged",
"monitors.show_all": "Show all {{.Count}}",
"monitors.sla": "SLA",
"monitors.sla_table": "SLA by period",
"monitors.smtp_hint": "Target is host:port (25, 587 or 465). Waits for the greeting and says EHLO; with encryption, STARTTLS must succeed.",
"monitors.smtp_implicit_tls": "Encrypted from the start (SMTPS, port 465)",
"monitors.snmp_community": "Community (empty = public)",
"monitors.snmp_cond_any": "any value",
"monitors.snmp_cond_contains": "contains",
"monitors.snmp_cond_eq": "equals",
"monitors.snmp_cond_ge": "at least",
"monitors.snmp_cond_gt": "greater than",
"monitors.snmp_cond_le": "at most",
"monitors.snmp_cond_lt": "less than",
"monitors.snmp_cond_ne": "not equal",
"monitors.snmp_condition": "Condition",
"monitors.snmp_hint": "Target is host:port (usually 161). Reads one OID over SNMP v1 or v2c and can compare its value.",
"monitors.snmp_oid": "OID",
"monitors.snmp_value": "Value",
"monitors.snmp_version": "Version",
"monitors.stale_hours": "Stale after (hours)",
"monitors.stale_hours_hint": "A firing alert Alertmanager stops repeating counts as over after this time. Keep it above repeat_interval.",
"monitors.steam_hint": "Target is host:port of the query port (usually the game port, e.g. 27015). Asks the server for its info like the Steam server browser (A2S); works for Source and most Steam games.",
"monitors.target": "Target",
"monitors.target_hint": "URL for HTTP, host:port for TCP and TLS, host name for DNS and ICMP.",
"monitors.target_hint": "URL for HTTP, host:port for TCP, TLS, databases, brokers (Kafka: several, comma-separated) and game servers, host name for DNS and ICMP, container name for Docker.",
"monitors.timeout": "Timeout (ms)",
"monitors.tls_min_days": "Minimum days until expiry",
"monitors.tls_server_name": "Server name (optional)",
"monitors.type": "Check type",
"monitors.type_alertmanager": "Alertmanager",
"monitors.type_dns": "DNS",
"monitors.type_docker": "Docker container",
"monitors.type_grpc": "gRPC",
"monitors.type_heartbeat": "Heartbeat",
"monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)",
"monitors.type_json": "JSON API",
"monitors.type_kafka": "Kafka",
"monitors.type_minecraft": "Minecraft server",
"monitors.type_mongodb": "MongoDB",
"monitors.type_mqtt": "MQTT",
"monitors.type_mssql": "Microsoft SQL Server",
"monitors.type_mysql": "MySQL / MariaDB",
"monitors.type_postgres": "PostgreSQL",
"monitors.type_prometheus": "Prometheus",
"monitors.type_rabbitmq": "RabbitMQ",
"monitors.type_radius": "RADIUS",
"monitors.type_redis": "Redis",
"monitors.type_smtp": "SMTP",
"monitors.type_snmp": "SNMP",
"monitors.type_steam": "Steam game server",
"monitors.type_tcp": "TCP port",
"monitors.type_tls": "TLS certificate",
"monitors.ungrouped": "Without group",
"monitors.uptime_chart": "Uptime per period",
"monitors.verify_tls": "Verify TLS certificate",
"notify.duration": "Down for {{.Duration}}",
"notify.test_body": "If you can read this, the channel works.",
"notify.title_opened": "{{.Monitor}} is down",
"notify.title_resolved": "{{.Monitor}} is up again",
"notify.title_test": "Test from UptimeSebi",
"org.check_types_intro": "Monitor types offered to the members of this organization, out of those this installation offers. Existing monitors of a switched-off type keep running.",
"org.policy": "Sign-in policy",
"org.require_sso": "Require SSO",
"org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.",
@@ -580,6 +1062,18 @@
"org.token_max_days": "Maximum API token lifetime (days)",
"org.token_max_days_hint": "New tokens must expire within this period. Saving shortens existing tokens that would outlive it. Leave empty for no limit.",
"org.token_max_days_none": "unlimited",
"orgs.create": "Create organization",
"orgs.first_intro": "Your account is ready. Create an organization for your monitors and status pages.",
"orgs.intro": "All organizations with their owner, usage and limits. Leave a limit empty to follow the default.",
"orgs.invited_hint": "Were you invited to an organization? Open the link from the invitation instead.",
"orgs.limits": "Limits of this organization",
"orgs.manage": "Limits, suspend or delete …",
"orgs.new_intro": "You will own it and can invite others.",
"orgs.new_title": "New organization",
"orgs.none": "No organization matches.",
"orgs.owner_orgs": "Organizations the owner may own (owns {{.Count}})",
"orgs.search": "Name, slug or owner email",
"orgs.title": "Organizations",
"page.component.degraded": "Degraded",
"page.component.maintenance": "Maintenance",
"page.component.operational": "Operational",
@@ -589,6 +1083,9 @@
"one": "{{.Count}} day ago",
"other": "{{.Count}} days ago"
},
"page.details_expand": "Show details",
"page.details_last_24h": "Last 24 hours",
"page.details_latency_summary": "avg {{.Avg}} · max {{.Max}}",
"page.incidents": "Recent incidents",
"page.maintenance_ongoing": "Maintenance in progress",
"page.maintenance_upcoming": "Planned maintenance",
@@ -601,6 +1098,14 @@
"page.status.unknown": "Status currently unavailable",
"page.today": "Today",
"page.updated": "Updated {{.Time}}",
"pager.earlier": "Earlier",
"pager.first": "To the start",
"pager.label": "Pages",
"pager.later": "Later",
"pager.newer": "Newer",
"pager.next": "Next",
"pager.older": "Older",
"pager.previous": "Previous",
"pages.accent": "Accent color (#rrggbb)",
"pages.components": "Monitors on this page",
"pages.create": "Create status page",
@@ -615,15 +1120,27 @@
"pages.domain_verified": "Domain verified.",
"pages.draft": "draft",
"pages.export": "Export as HTML",
"pages.group": "Group",
"pages.group_position": "Order",
"pages.groups": "Groups",
"pages.groups_import": "Import from monitor groups",
"pages.groups_import_confirm": "Replace this status page's groups with the organization's monitor group tree?",
"pages.groups_imported": "Groups imported from monitor groups.",
"pages.groups_intro": "Organize components into collapsible nested groups, just like on the monitors page.",
"pages.intro": "Public pages showing the state of selected monitors. Each page can use its own domain or be exported as a single HTML file.",
"pages.label": "Public name",
"pages.logo": "Logo URL (https)",
"pages.no_group": "No group",
"pages.open": "Open",
"pages.page_title": "Title",
"pages.published": "Published",
"pages.section": "Section",
"pages.settings": "Settings",
"pages.show_details": "Show component details on click",
"pages.show_details_hint": "Lets visitors open a detail view with 24h history, latency, SLA and region status. Targets, errors and credentials always stay private.",
"pages.slug": "Short name (URL)",
"pages.suspended": "suspended by the operator",
"pages.suspended_notice": "The operator suspended this status page; it is offline until they reinstate it.",
"pages.theme": "Theme",
"pages.title": "Status pages",
"pages.value": "Value",
@@ -688,6 +1205,7 @@
"security.totp.inactive": "not set up",
"security.totp.qr_alt": "QR code for your authenticator app",
"security.totp.start": "Set up",
"settings.alertmanager": "Receive Prometheus alerts as monitors.",
"settings.apidocs": "Every endpoint with its fields, in OpenAPI format.",
"settings.audit": "Who changed what and when.",
"settings.channels": "Webhooks and email for incidents",
@@ -772,6 +1290,7 @@
},
"tokens.revoke_confirm": "Revoke this token? Requests using it fail immediately.",
"tokens.title": "API tokens",
"tokens.usage": "Send the token with every request:",
"weekday.0": "Sun",
"weekday.1": "Mon",
"weekday.2": "Tue",
+72
View File
@@ -0,0 +1,72 @@
package migrations
import (
"context"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func TestAlertGroupsBackfill(t *testing.T) {
dsn := os.Getenv("UPTIME_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("UPTIME_TEST_DATABASE_URL not set")
}
ctx := context.Background()
if _, err := Up(ctx, dsn); err != nil {
t.Fatal(err)
}
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.Begin(ctx)
if err != nil {
t.Fatal(err)
}
// Exercise both directions inside a transaction; existing test data and
// goose's migration history remain unchanged after rollback.
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil {
t.Fatal(err)
}
raw, err := files.ReadFile("sql/00039_alert_groups.sql")
if err != nil {
t.Fatal(err)
}
up, down, ok := strings.Cut(string(raw), "-- +goose Down")
if !ok {
t.Fatal("missing down migration")
}
if _, err := tx.Exec(ctx, down); err != nil {
t.Fatalf("down: %v", err)
}
orgID := uuid.New()
if _, err := tx.Exec(ctx, `INSERT INTO orgs (id,slug,name) VALUES ($1,$2,'Existing organization')`, orgID, "migration-"+orgID.String()); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, `INSERT INTO monitors (org_id,name,type,target,interval_seconds,timeout_ms) VALUES ($1,'Existing monitor','tcp','example.test:443',60,1000)`, orgID); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, `INSERT INTO notification_channels (org_id,name,type,config) VALUES ($1,'Existing channel','webhook','{}')`, orgID); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, up); err != nil {
t.Fatalf("up: %v", err)
}
var groups, monitors, channels int
err = tx.QueryRow(ctx, `SELECT
(SELECT count(*) FROM alert_groups WHERE org_id=$1 AND is_default),
(SELECT count(*) FROM monitor_alert_groups WHERE org_id=$1),
(SELECT count(*) FROM alert_group_channels WHERE org_id=$1)`, orgID).Scan(&groups, &monitors, &channels)
if err != nil {
t.Fatal(err)
}
if groups != 1 || monitors != 1 || channels != 1 {
t.Fatalf("backfilled groups/monitors/channels = %d/%d/%d, want 1/1/1", groups, monitors, channels)
}
}
@@ -0,0 +1,50 @@
-- +goose Up
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat', 'alertmanager'));
-- Endpoints Alertmanager sends its webhooks to; the token is kept hashed
-- like API tokens.
CREATE TABLE alertmanager_receivers (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
token_hash bytea NOT NULL UNIQUE,
prefix text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
last_received_at timestamptz
);
-- The latest state of every alert received, by Alertmanager's fingerprint.
CREATE TABLE alertmanager_alerts (
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
fingerprint text NOT NULL CHECK (length(fingerprint) BETWEEN 1 AND 200),
receiver_id uuid NOT NULL REFERENCES alertmanager_receivers (id) ON DELETE CASCADE,
status text NOT NULL CHECK (status IN ('firing', 'resolved')),
labels jsonb NOT NULL,
annotations jsonb NOT NULL,
starts_at timestamptz NOT NULL,
generator_url text NOT NULL DEFAULT '',
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (org_id, fingerprint)
);
CREATE INDEX alertmanager_alerts_firing_idx ON alertmanager_alerts (org_id) WHERE status = 'firing';
ALTER TABLE alertmanager_receivers ENABLE ROW LEVEL SECURITY;
ALTER TABLE alertmanager_receivers FORCE ROW LEVEL SECURITY;
CREATE POLICY alertmanager_receivers_tenant ON alertmanager_receivers FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE alertmanager_alerts ENABLE ROW LEVEL SECURITY;
ALTER TABLE alertmanager_alerts FORCE ROW LEVEL SECURITY;
CREATE POLICY alertmanager_alerts_tenant ON alertmanager_alerts FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- +goose Down
DROP TABLE alertmanager_alerts;
DROP TABLE alertmanager_receivers;
DELETE FROM monitors WHERE type = 'alertmanager';
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat'));
@@ -0,0 +1,10 @@
-- +goose Up
-- Channel types follow notify.Providers; the application validates them
-- and their settings, secrets of which are sealed in config.
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type ~ '^[a-z]{2,32}$');
-- +goose Down
DELETE FROM notification_channels WHERE type NOT IN ('webhook', 'email');
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type IN ('webhook', 'email'));
@@ -0,0 +1,11 @@
-- +goose Up
-- Monitor types follow the check package, which validates them with their
-- settings; listing them here as well meant a migration per new type.
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check CHECK (type ~ '^[a-z]{2,32}$');
-- +goose Down
DELETE FROM monitors WHERE type NOT IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat', 'alertmanager');
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat', 'alertmanager'));
@@ -0,0 +1,17 @@
-- +goose Up
-- Settings of the whole installation, changed by platform admins.
CREATE TABLE platform_settings (
key text PRIMARY KEY,
value jsonb NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE platform_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE platform_settings FORCE ROW LEVEL SECURITY;
-- Every organization may read them; they say what the installation offers.
CREATE POLICY platform_settings_read ON platform_settings FOR SELECT USING (true);
CREATE POLICY platform_settings_write ON platform_settings FOR ALL
USING (app_scope_system()) WITH CHECK (app_scope_system());
-- +goose Down
DROP TABLE platform_settings;
@@ -0,0 +1,13 @@
-- +goose Up
-- Whether an organization's checker may check private addresses. Platform
-- checkers follow the platform setting instead.
ALTER TABLE agents ADD COLUMN allow_private boolean NOT NULL DEFAULT true;
-- Check types an organization does not want offered, on top of those
-- switched off platform-wide.
ALTER TABLE orgs ADD COLUMN disabled_check_types text[] NOT NULL DEFAULT '{}'
CHECK (cardinality(disabled_check_types) <= 100);
-- +goose Down
ALTER TABLE orgs DROP COLUMN disabled_check_types;
ALTER TABLE agents DROP COLUMN allow_private;
@@ -0,0 +1,9 @@
-- +goose Up
-- Some services are named with digits, such as 46elks.
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type ~ '^[a-z0-9]{2,32}$');
-- +goose Down
DELETE FROM notification_channels WHERE type !~ '^[a-z]{2,32}$';
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_type_check;
ALTER TABLE notification_channels ADD CONSTRAINT notification_channels_type_check CHECK (type ~ '^[a-z]{2,32}$');
@@ -0,0 +1,78 @@
-- +goose Up
CREATE TABLE alert_groups (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
is_default boolean NOT NULL DEFAULT false,
UNIQUE (id, org_id)
);
CREATE UNIQUE INDEX alert_groups_default_idx ON alert_groups (org_id) WHERE is_default;
ALTER TABLE notification_channels ADD UNIQUE (id, org_id);
CREATE TABLE alert_group_channels (
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
group_id uuid NOT NULL,
channel_id uuid NOT NULL,
PRIMARY KEY (group_id, channel_id),
FOREIGN KEY (group_id, org_id) REFERENCES alert_groups (id, org_id) ON DELETE CASCADE,
FOREIGN KEY (channel_id, org_id) REFERENCES notification_channels (id, org_id) ON DELETE CASCADE
);
CREATE TABLE monitor_alert_groups (
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
monitor_id uuid NOT NULL,
group_id uuid NOT NULL,
PRIMARY KEY (monitor_id, group_id),
FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE,
FOREIGN KEY (group_id, org_id) REFERENCES alert_groups (id, org_id) ON DELETE CASCADE
);
CREATE INDEX monitor_alert_groups_group_idx ON monitor_alert_groups (group_id);
CREATE INDEX alert_group_channels_channel_idx ON alert_group_channels (channel_id);
INSERT INTO alert_groups (org_id, name, is_default) SELECT id, 'Default', true FROM orgs;
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT c.org_id, g.id, c.id FROM notification_channels c JOIN alert_groups g ON g.org_id = c.org_id AND g.is_default;
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT m.org_id, m.id, g.id FROM monitors m JOIN alert_groups g ON g.org_id = m.org_id AND g.is_default;
-- Defaults apply to every creation path, including CLI and imports.
-- +goose StatementBegin
CREATE FUNCTION alert_groups_defaults() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_TABLE_NAME = 'orgs' THEN
INSERT INTO alert_groups (org_id, name, is_default) VALUES (NEW.id, 'Default', true);
ELSIF TG_TABLE_NAME = 'monitors' THEN
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT NEW.org_id, NEW.id, id FROM alert_groups WHERE org_id = NEW.org_id AND is_default;
ELSE
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT NEW.org_id, id, NEW.id FROM alert_groups WHERE org_id = NEW.org_id AND is_default;
END IF;
RETURN NEW;
END
$$;
-- +goose StatementEnd
CREATE TRIGGER org_alert_group AFTER INSERT ON orgs FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
CREATE TRIGGER monitor_alert_group AFTER INSERT ON monitors FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
CREATE TRIGGER channel_alert_group AFTER INSERT ON notification_channels FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
ALTER TABLE alert_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE alert_groups FORCE ROW LEVEL SECURITY;
CREATE POLICY alert_groups_tenant ON alert_groups FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE alert_group_channels ENABLE ROW LEVEL SECURITY;
ALTER TABLE alert_group_channels FORCE ROW LEVEL SECURITY;
CREATE POLICY alert_group_channels_tenant ON alert_group_channels FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE monitor_alert_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE monitor_alert_groups FORCE ROW LEVEL SECURITY;
CREATE POLICY monitor_alert_groups_tenant ON monitor_alert_groups FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- +goose Down
DROP TRIGGER channel_alert_group ON notification_channels;
DROP TRIGGER monitor_alert_group ON monitors;
DROP TRIGGER org_alert_group ON orgs;
DROP FUNCTION alert_groups_defaults();
DROP TABLE monitor_alert_groups;
DROP TABLE alert_group_channels;
DROP TABLE alert_groups;
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_id_org_id_key;
@@ -0,0 +1,6 @@
-- +goose Up
ALTER TABLE alert_groups ADD COLUMN quiet_hours jsonb NOT NULL DEFAULT '[]'::jsonb
CHECK (jsonb_typeof(quiet_hours) = 'array');
-- +goose Down
ALTER TABLE alert_groups DROP COLUMN quiet_hours;
@@ -0,0 +1,96 @@
-- +goose Up
ALTER TABLE status_pages
ADD COLUMN show_component_details boolean NOT NULL DEFAULT false;
CREATE TABLE status_page_groups (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
page_id uuid NOT NULL,
org_id uuid NOT NULL,
parent_id uuid,
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
position integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (id, page_id, org_id),
CHECK (parent_id IS DISTINCT FROM id),
FOREIGN KEY (page_id, org_id) REFERENCES status_pages (id, org_id) ON DELETE CASCADE,
FOREIGN KEY (parent_id, page_id, org_id) REFERENCES status_page_groups (id, page_id, org_id) ON DELETE SET NULL (parent_id)
);
CREATE INDEX status_page_groups_page_idx ON status_page_groups (page_id, position, name);
CREATE INDEX status_page_groups_parent_idx ON status_page_groups (parent_id);
-- +goose StatementBegin
-- Rejects cycles and nesting deeper than eight levels within a status page.
CREATE FUNCTION status_page_groups_tree_check() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
depth integer;
BEGIN
IF NEW.parent_id IS NULL THEN
RETURN NEW;
END IF;
WITH RECURSIVE up AS (
SELECT id, parent_id, 1 AS depth FROM status_page_groups WHERE id = NEW.parent_id
UNION ALL
SELECT g.id, g.parent_id, up.depth + 1 FROM status_page_groups g JOIN up ON g.id = up.parent_id
WHERE up.depth < 20
)
SELECT max(up.depth) INTO depth FROM up;
IF EXISTS (
WITH RECURSIVE up AS (
SELECT id, parent_id FROM status_page_groups WHERE id = NEW.parent_id
UNION
SELECT g.id, g.parent_id FROM status_page_groups g JOIN up ON g.id = up.parent_id
)
SELECT 1 FROM up WHERE id = NEW.id
) THEN
RAISE EXCEPTION 'status page group cycle' USING ERRCODE = 'check_violation', CONSTRAINT = 'status_page_groups_cycle';
END IF;
IF depth >= 8 THEN
RAISE EXCEPTION 'status page groups nested too deeply' USING ERRCODE = 'check_violation', CONSTRAINT = 'status_page_groups_depth';
END IF;
RETURN NEW;
END
$$;
-- +goose StatementEnd
CREATE TRIGGER status_page_groups_tree BEFORE INSERT OR UPDATE OF parent_id ON status_page_groups
FOR EACH ROW EXECUTE FUNCTION status_page_groups_tree_check();
ALTER TABLE status_page_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE status_page_groups FORCE ROW LEVEL SECURITY;
CREATE POLICY status_page_groups_tenant ON status_page_groups FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE status_page_monitors ADD COLUMN group_id uuid;
ALTER TABLE status_page_monitors
ADD FOREIGN KEY (group_id, page_id, org_id) REFERENCES status_page_groups (id, page_id, org_id) ON DELETE SET NULL (group_id);
CREATE INDEX status_page_monitors_group_idx ON status_page_monitors (group_id);
WITH existing_sections AS (
SELECT page_id, org_id, section, min(position) AS first_pos
FROM status_page_monitors
WHERE section <> ''
GROUP BY page_id, org_id, section
)
INSERT INTO status_page_groups (page_id, org_id, name, position)
SELECT page_id, org_id, section,
(row_number() OVER (PARTITION BY page_id ORDER BY first_pos, section) - 1)::integer
FROM existing_sections;
UPDATE status_page_monitors spm
SET group_id = g.id
FROM status_page_groups g
WHERE g.page_id = spm.page_id
AND g.org_id = spm.org_id
AND g.parent_id IS NULL
AND g.name = spm.section
AND spm.section <> '';
-- +goose Down
ALTER TABLE status_page_monitors DROP COLUMN group_id;
DROP TABLE status_page_groups;
DROP FUNCTION status_page_groups_tree_check();
ALTER TABLE status_pages DROP COLUMN show_component_details;
@@ -0,0 +1,16 @@
-- +goose Up
-- Platform admins suspend status pages, organizations and accounts, for
-- instance over abuse. Suspension hides or stops them without deleting
-- anything; users.disabled_at already marks suspended accounts.
ALTER TABLE status_pages ADD COLUMN suspended_at timestamptz;
ALTER TABLE status_pages ADD COLUMN suspended_reason text NOT NULL DEFAULT '' CHECK (length(suspended_reason) <= 500);
ALTER TABLE orgs ADD COLUMN suspended_at timestamptz;
ALTER TABLE orgs ADD COLUMN suspended_reason text NOT NULL DEFAULT '' CHECK (length(suspended_reason) <= 500);
ALTER TABLE users ADD COLUMN disabled_reason text NOT NULL DEFAULT '' CHECK (length(disabled_reason) <= 500);
-- +goose Down
ALTER TABLE users DROP COLUMN disabled_reason;
ALTER TABLE orgs DROP COLUMN suspended_reason;
ALTER TABLE orgs DROP COLUMN suspended_at;
ALTER TABLE status_pages DROP COLUMN suspended_reason;
ALTER TABLE status_pages DROP COLUMN suspended_at;
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more