Compare commits

..
56 Commits
Author SHA1 Message Date
Sebi 12e6de77aa Merge pull request 'feat: support tickets between accounts and platform admins' (#148) from feat/support-tickets into main
ci / lint (push) Successful in 10m3s
ci / test (push) Successful in 13m50s
ci / build (push) Successful in 16m48s
ci / image (push) Successful in 4m2s
2026-11-24 17:04:36 +00:00
Sebastian UnterschützandClaude Opus 5.5 f3d402705e feat: support tickets between accounts and platform admins
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 7m0s
ci / test (pull_request) Successful in 12m1s
ci / build (pull_request) Successful in 18m14s
ci / image (pull_request) Successful in 5m9s
ci / build (push) Skipped
ci / image (push) Skipped
Accounts open tickets under Support and admins answer them under Admin →
Support tickets.

- A ticket is open while it waits for the admins and answered while it
  waits for the account. Either side can close or reopen it, and a reply
  reopens it.
- The admins are mailed about new tickets and replies, and the account
  about answers.
- A ticket can name the active organization and point at a monitor,
  notification channel, alert group, status page or incident in it.
  Each must be something the account can read.
- Next to the conversation, admins see the account at a glance: state,
  sign-in, organizations with their limits and usage, and open tickets.
- Admins switch support off and limit how many tickets an account has
  open at once.
- Suspended accounts and those yet to accept the terms reach support too;
  a suspended account opens one ticket.
- Tickets are part of the account export and are deleted with the
  account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 18:01:50 +01:00
Sebi 9fc3c6b050 Merge pull request 'feat(web): fit the console and status pages to phones and tablets' (#147) from feat/responsive into main
ci / lint (push) Successful in 6m29s
ci / test (push) Successful in 11m57s
ci / build (push) Canceled after 17m4s
ci / image (push) Canceled after 0s
2026-11-24 16:35:25 +00:00
Sebastian UnterschützandClaude Opus 5.5 670dde40b6 feat(web): fit the console and status pages to phones and tablets
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 6m4s
ci / test (pull_request) Successful in 11m52s
ci / build (pull_request) Successful in 17m48s
ci / image (pull_request) Successful in 5m28s
ci / build (push) Skipped
ci / image (push) Skipped
- The console header folds its navigation into a menu below 1024px.
- Pages use narrower gutters on phones.
- Monitor rows keep name and uptime in place on narrow screens.
- Toolbars and the range switch wrap.
- Tables scroll sideways instead of squeezing their columns.
- Form fields keep 16px text on touch screens so iOS does not zoom in.
- The status page footer wraps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 17:09:50 +01:00
Sebi 442b45b974 Merge pull request 'feat(statuspage): show the open incident's status next to its component' (#146) from feat/component-incident-status into main
ci / test (push) Successful in 9m43s
ci / lint (push) Successful in 10m25s
release / release (push) Successful in 11m48s
ci / image (push) Successful in 5m18s
ci / build (push) Successful in 18m40s
2026-11-24 06:11:19 +00:00
Sebastian UnterschützandClaude Opus 5.5 316bdeb223 feat(statuspage): show the open incident's status next to its component
ci / lint (push) Skipped
ci / test (push) Skipped
ci / test (pull_request) Successful in 13m1s
ci / lint (pull_request) Successful in 10m19s
ci / image (pull_request) Successful in 4m54s
ci / build (pull_request) Successful in 16m3s
ci / build (push) Skipped
ci / image (push) Skipped
The component list names the status of the component's newest unresolved
incident the organization gave one, built-in or own with its color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 07:09:50 +01:00
Sebi 45123ff93a Merge pull request 'feat(console): set an incident's status right in the incident list' (#145) from feat/incident-quick-status into main
ci / lint (push) Successful in 9m43s
ci / test (push) Successful in 9m44s
ci / image (push) Successful in 4m39s
ci / build (push) Successful in 20m6s
2026-11-23 22:59:33 +00:00
Sebi 6a60ee746e Merge pull request 'feat: own incident statuses with a color; incidents before maintenance' (#144) from feat/incident-statuses into main
ci / lint (push) Canceled after 19s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-23 22:59:03 +00:00
Sebi 3bf84e8c27 Merge pull request 'feat: incident updates with a status, public or internal' (#143) from feat/incident-updates into main
ci / lint (push) Canceled after 17s
ci / test (push) Canceled after 17s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-23 22:58:30 +00:00
Sebastian UnterschützandClaude Opus 5.5 437b6e934f feat(console): set an incident's status right in the incident list
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (pull_request) Successful in 15m32s
ci / test (pull_request) Successful in 12m58s
ci / image (pull_request) Successful in 4m29s
ci / lint (pull_request) Successful in 12m19s
ci / build (push) Skipped
ci / image (push) Skipped
Each row of the incident list offers "Set status" to those who may write
the monitor's incidents: a status (built-in or own, the next one
preselected), an optional message and whether it shows on status pages.
An update may now just change the status, without a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 23:57:05 +01:00
Sebastian UnterschützandClaude Opus 5.5 2409a919c3 feat: own incident statuses with a color; incidents before maintenance
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 9m38s
ci / build (pull_request) Successful in 16m36s
ci / image (pull_request) Successful in 3m37s
ci / test (pull_request) Successful in 14m21s
ci / build (push) Skipped
ci / image (push) Skipped
Organizations add statuses of their own, with a name and a color, next
to the built-in ones (Settings, incident statuses; API under
/org/incident-statuses, managed with org.manage). Updates pick them by
ID; the console and status pages show them in their color. Renaming or
recoloring carries into the history; a status in use cannot be deleted
(409 status_in_use). API responses give status "custom" with status_id,
status_name and status_color.

Status pages now list recent incidents before planned maintenance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 23:49:58 +01:00
Sebastian UnterschützandClaude Opus 5.5 43a04e99b1 feat: incident updates with a status, public or internal
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 6m54s
ci / test (pull_request) Successful in 12m15s
ci / image (pull_request) Successful in 4m23s
ci / build (pull_request) Successful in 11m0s
ci / build (push) Skipped
ci / image (push) Skipped
Outages open and close with their monitor; now people can say what is
going on. An incident gets an optional title and updates, each with a
status (investigating, identified, monitoring, resolved) and a Markdown
message, shown on status pages or kept as an internal note. The incident
shows the latest update's status, resolved once its monitor recovered.

The console lists title and status and has a page per incident with its
timeline (outage, updates, recovery) and, for incidents.write in the
monitor's group, forms to post updates and set the title. Status pages
show title, status and public updates. API: GET/PATCH
/org/incidents/:id, POST and DELETE /org/incidents/:id/updates; the
incident list carries title and status; the organization export
includes the updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 23:38:07 +01:00
Sebi 6f0cf59406 Merge pull request 'feat: several owners per organization, and handing ownership over' (#142) from feat/owners into main
ci / lint (push) Successful in 11m58s
ci / test (push) Successful in 13m34s
ci / build (push) Successful in 11m30s
ci / image (push) Successful in 5m29s
2026-11-23 21:40:35 +00:00
Sebi 91326356bc Merge pull request 'feat: terms of service and versioned consent; data rights for every account' (#141) from feat/terms into main
ci / test (push) Canceled after 19s
ci / lint (push) Canceled after 19s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-23 21:40:00 +00:00
Sebastian UnterschützandClaude Opus 5.5 db3ff19983 feat: several owners per organization, and handing ownership over
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (pull_request) Successful in 15m40s
ci / image (pull_request) Successful in 4m26s
ci / lint (pull_request) Successful in 9m19s
ci / test (pull_request) Successful in 9m25s
ci / build (push) Skipped
ci / image (push) Skipped
An organization may now have several owners; the unique index allowing
only one is gone. Owners make members owners or take it back, their own
included, through PUT /api/v1/org/members/:user/owner; handing an
organization over is making someone else owner and stepping down. The
last owner cannot step down, and changes serialize on a per-organization
lock so two owners stepping down at once cannot leave none. A former
owner without roles keeps working as Admin. Owners still cannot be
removed while they are owners.

Deleting an account now takes along only the organizations it is the
last owner of, counted under the same lock; it just leaves those with
further owners. The members page offers "Make owner", "Remove as owner"
and "Step down as owner" to owners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 22:38:04 +01:00
Sebastian UnterschützandClaude Opus 5.5 8d7c1f856c feat: terms of service and versioned consent; data rights for every account
ci / test (push) Skipped
ci / lint (pull_request) Successful in 9m21s
ci / lint (push) Skipped
ci / image (pull_request) Successful in 4m36s
ci / test (pull_request) Successful in 13m53s
ci / build (pull_request) Successful in 11m22s
ci / build (push) Skipped
ci / image (push) Skipped
Terms of service join the legal notice and privacy policy, for the
platform only. Every account accepts the platform's privacy policy and
terms: on sign-up (also through an invitation) by ticking a box for the
versions shown, and after a sign-in through a provider right away. When
an admin saves a material change with "everyone has to accept again",
the document gets a new version and each account is asked at its next
request; corrections ask nobody. Acceptances are kept per version with
their time, as proof, and are part of the data export.

Until an account accepted, and while it is suspended, it can read the
documents, export its data, delete itself and sign out, nothing else:
pages lead to /consent or /account/suspended, other API calls answer 403
consent_required or account_suspended. Suspended accounts therefore sign
in again, by password or provider; their API tokens stay blocked.

Deleting an account deletes the organizations it owns, monitors and all,
also when they have other members (each organization has one owner); it
no longer refuses. The account settings name those organizations first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 22:26:20 +01:00
Sebi 61fdfa830a Merge pull request 'feat(deploy): Docker Compose setup for one host' (#140) from feat/compose into main
ci / lint (push) Successful in 7m3s
ci / test (push) Successful in 14m40s
ci / build (push) Successful in 11m39s
ci / image (push) Successful in 5m20s
2026-11-23 20:54:01 +00:00
Sebastian UnterschützandClaude Opus 5.5 fc8c01b9a4 feat(deploy): Docker Compose setup for one host
ci / lint (push) Skipped
ci / test (push) Skipped
ci / test (pull_request) Successful in 12m37s
ci / build (pull_request) Successful in 15m44s
ci / image (pull_request) Successful in 4m34s
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 12m24s
deploy/compose runs the console and API with a migration step before it
starts, and through COMPOSE_PROFILES optionally a bundled TimescaleDB and
Redis (leave them out to use your own by URL), a checker and a status
page server. Only the public URL and the secret keys are mandatory, so
every combination of profiles starts; containers run read-only without
capabilities. The API gains a health command for the image's
HEALTHCHECK, as checker and status page server have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 21:50:37 +01:00
Sebi b05afc8c79 Merge pull request 'feat(deploy): Helm chart' (#139) from feat/helm into main
ci / test (push) Successful in 9m18s
ci / lint (push) Successful in 12m5s
ci / build (push) Canceled after 3m29s
ci / image (push) Canceled after 0s
2026-11-23 20:38:09 +00:00
Sebastian UnterschützandClaude Opus 5.5 d2b669ae71 feat(deploy): optional bundled Redis in the Helm chart
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 10m22s
ci / test (pull_request) Successful in 15m16s
ci / build (pull_request) Successful in 15m27s
ci / image (pull_request) Successful in 4m43s
ci / build (push) Skipped
ci / image (push) Skipped
redis.bundled.enabled adds a single Redis for trying UptimeSebi out, like
the bundled TimescaleDB: password generated and kept, append-only file on
a volume so sessions and schedules survive restarts, read-only root
filesystem, kept with its volume on uninstall and adopted by a reinstall.
Your own Redis, directly or through Sentinel, stays the way for
production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 21:21:41 +01:00
Sebastian UnterschützandClaude Opus 5.5 a9de8b8d75 feat(deploy): Helm chart
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Canceled after 5m11s
ci / test (pull_request) Canceled after 5m11s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
ci / build (push) Skipped
ci / image (push) Skipped
deploy/helm/uptimesebi runs the console and API (Deployment, Service,
PodDisruptionBudget, Ingress) and optionally an in-cluster checker and
status page servers. PostgreSQL and Redis are your own: by URL, from an
existing secret, or Redis through Sentinel; Redis is not bundled. For
trying it out, a single TimescaleDB can be bundled; its volume and
password survive an uninstall and are picked up again by a reinstall.

Migrations run as a pre-install/pre-upgrade hook with its own short-lived
copy of the secrets; with the bundled database, which does not exist
before the install, as an init container (runs serialize on the
migration lock). Pods run as 65532 with a read-only root filesystem, no
capabilities and RuntimeDefault seccomp; checkers get the safe ping
sysctl. Missing settings fail rendering with a message.

CI lints and renders the chart in several configurations; releases
package it with the release version, sign it with the checksums and push
it to the Gitea Helm registry.

Closes #35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 21:16:21 +01:00
Sebi ac0d212a01 Merge pull request 'fix(ci): build and push only after lint and tests pass' (#138) from fix/ci-order into main
ci / lint (push) Successful in 9m23s
ci / test (push) Successful in 14m58s
ci / build (push) Successful in 16m15s
ci / image (push) Successful in 4m43s
2026-11-23 19:58:50 +00:00
Sebastian UnterschützandClaude Opus 5.5 4acea46736 fix(ci): build and push only after lint and tests pass
ci / lint (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 12m8s
ci / test (pull_request) Successful in 12m14s
ci / build (pull_request) Successful in 11m42s
ci / image (pull_request) Successful in 4m32s
ci / build (push) Skipped
ci / image (push) Skipped
The build job, and so the image job after it, now needs lint and test:
a failing test no longer lets CI go on to push images from main.

TestBackgroundRefresh failed on CI now and then with "TempDir RemoveAll
cleanup: directory not empty": a refresh started by a visit updates the
cache before writing the snapshot to disk, so the test could end and
remove the directory mid-write. Visit-triggered refreshes are tracked,
and the test harness waits for them before its directory is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 19:55:42 +01:00
Sebi d99a19250b Merge pull request 'ci: release only tags on main' (#137) from ci/release-guard into main
ci / lint (push) Successful in 7m27s
ci / test (push) Failing after 14m14s
ci / build (push) Successful in 22m27s
ci / image (push) Successful in 4m17s
2026-11-23 18:37:26 +00:00
Sebi 6816ff9ba8 Merge pull request 'feat(console): install instructions for new agents, outdated agents' (#136) from feat/agent-console into main
ci / test (push) Canceled after 14s
ci / lint (push) Canceled after 16s
ci / build (push) Canceled after 15s
ci / image (push) Canceled after 0s
2026-11-23 18:36:55 +00:00
Sebi 8d9a52d97d Merge pull request 'feat(agents): one-line install and Compose files for agents' (#135) from feat/agent-install into main
ci / lint (push) Canceled after 8m9s
ci / test (push) Canceled after 7m56s
ci / build (push) Canceled after 6m41s
ci / image (push) Canceled after 0s
2026-11-23 18:28:20 +00:00
Sebi 134e6e5436 Merge pull request 'feat(agents): self-updating agent image variant' (#134) from feat/autoupdate 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-23 18:27:32 +00:00
Sebi 841e61751e Merge pull request 'feat(release): sign checksums and publish an SBOM' (#132) from feat/release-signing into main
ci / lint (push) Canceled after 32s
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-23 18:26:49 +00:00
Sebastian UnterschützandClaude Opus 5.5 f278b66efb ci: release only tags on main
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (pull_request) Successful in 9m7s
ci / image (pull_request) Successful in 5m17s
ci / lint (pull_request) Successful in 7m13s
ci / test (pull_request) Successful in 12m58s
ci / build (push) Skipped
ci / image (push) Skipped
Only code that reached main through a protected merge is released, the
release workflow included: a tag on any other commit, such as one with a
changed workflow, publishes nothing. Together with the tag protection
that leaves v* tags to the Owners team.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 19:22:55 +01:00
Sebastian UnterschützandClaude Opus 5.5 e281bcd604 feat(console): install instructions for new agents, outdated agents
ci / build (pull_request) Successful in 11m14s
ci / lint (pull_request) Successful in 14m23s
ci / image (pull_request) Successful in 3m58s
ci / test (pull_request) Successful in 18m0s
Creating a checker or status page server now shows how to install it
next to the one-time token: the one-liner of the platform's install
script and the Compose files with .env, with the token and kind filled
in, and a switch between the self-updating and the plain image. Agents
behind the platform's release are marked outdated in the organization's
and the admin's agent lists, which also show each agent's release and
the platform's.

Closes #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 19:14:20 +01:00
Sebastian UnterschützandClaude Opus 5.5 0c382f814c feat(agents): one-line install and Compose files for agents
ci / build (pull_request) Successful in 11m3s
ci / lint (pull_request) Successful in 10m38s
ci / image (pull_request) Successful in 4m40s
ci / test (pull_request) Successful in 17m29s
The API serves /install.sh with its public address and agent image
filled in. The POSIX sh script checks for Linux on a supported CPU,
Docker and Compose, writes /opt/uptimesebi/<kind>[-<name>]/compose.yaml
and a .env readable only by its owner, starts the agent and waits until
it is healthy. Options cover status page hosts with Let's Encrypt, the
plain image for manual updates, the Docker socket for checkers and
several agents per host; running it again changes the settings.

The Compose files in deploy/agent are configured through .env alone, so
they also work without the script. Images follow the platform's channel
(latest, beta or edge). CI shellchecks the rendered script.

Closes #130

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 19:07:02 +01:00
Sebastian UnterschützandClaude Opus 5.5 a35dadd8f6 feat(agents): self-updating agent image variant
ci / image (pull_request) Successful in 4m40s
ci / lint (pull_request) Successful in 12m17s
ci / test (pull_request) Successful in 9m12s
ci / build (pull_request) Successful in 16m25s
The -autoupdate variant of the checker and status page images adds a
launcher layer. The launcher runs the agent as a child process and keeps
it on the platform's release: GET /agent/v1/update names the API's own
release and the agent image for it, the launcher downloads the binary
for its platform from the registry, accepts it only when the index is
signed with a release key for exactly that version, swaps the agent
gracefully and rolls back when the new release does not become ready or
crashes right after starting. Agents never get ahead of the API, and
installations on unreleased builds are not followed.

CI pushes both variants and signs each index with RELEASE_SIGNING_KEY
(minisign signature in a sha256-<digest>.minisig image next to it). The
image builder moves to internal/agentimage; the API image job takes the
build job's version so the API reports the release its agents are tagged
with. Agents gain a version command.

Closes #129
Closes #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 18:57:48 +01:00
Sebastian Unterschütz 431048e244 Merge remote-tracking branch 'origin/feat/release-signing' into feat/autoupdate
# Conflicts:
#	README.md
2026-11-23 18:40:16 +01:00
Sebastian UnterschützandClaude Opus 5.5 a9f94fc492 feat(agents): multi-arch checker and status page images on scratch
ci / image (pull_request) Successful in 7m15s
ci / test (pull_request) Successful in 9m5s
ci / lint (pull_request) Successful in 14m17s
ci / build (pull_request) Successful in 15m59s
uptimesebi-checker and uptimesebi-statuspage for linux/amd64, arm64,
arm/v7 and arm/v6, from a Raspberry Pi Zero to servers. tools/image
assembles them from the cross-compiled binaries without Docker or
emulation: one layer on an empty base with the binary, a data volume
owned by the unprivileged user and a HEALTHCHECK running the new
`checker health` / `statuspage health` commands. The binaries embed time
zone data and fallback CA roots, so no base image ever needs updating.
CI pushes them with the same channel tags as the main image; releases
carry tarballs for all four platforms.

Refs #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 18:33:42 +01:00
Sebastian UnterschützandClaude Opus 5.5 b1ca8eb19f feat(release): sign checksums and publish an SBOM
ci / image (pull_request) Successful in 4m1s
ci / build (pull_request) Successful in 8m59s
ci / lint (pull_request) Successful in 10m34s
ci / test (pull_request) Successful in 12m29s
Releases carry SHA256SUMS signed in the minisign format (prehashed
Ed25519, the release tag as trusted comment) and an SPDX SBOM of the Go
modules and the npm packages the frontend build bundles. internal/signing
signs and verifies; the release keys are committed in release.pub and
compiled in, so the self-updating agents can check their downloads.
Without the RELEASE_SIGNING_KEY secret a release is published unsigned
with a warning.

Closes #34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 18:20:05 +01:00
Sebi d2d6bf9f44 Merge pull request 'chore(deps): update go module directive to v1.27.4' (#120) from renovate/go-toolchain into main
ci / test (push) Successful in 9m17s
ci / lint (push) Successful in 13m16s
ci / image (push) Successful in 7m26s
ci / build (push) Successful in 12m39s
2026-11-23 17:15:03 +00:00
Sebi e17e7aab41 Merge pull request 'chore(deps): pin dependencies' (#119) from renovate/pin-dependencies into main
ci / test (push) Canceled after 2m3s
ci / lint (push) Canceled after 2m15s
ci / build (push) Canceled after 2m3s
ci / image (push) Canceled after 2m4s
2026-11-23 17:12:48 +00:00
Sebi 607ff43a1c Merge branch 'main' into renovate/go-toolchain
ci / image (pull_request) Successful in 3m48s
ci / build (pull_request) Successful in 8m41s
ci / lint (pull_request) Successful in 10m3s
ci / test (pull_request) Successful in 16m41s
2026-11-23 16:50:53 +00:00
Sebi 4a0099afe2 Merge branch 'main' into renovate/pin-dependencies
ci / image (pull_request) Successful in 4m53s
ci / test (pull_request) Successful in 9m14s
ci / build (pull_request) Successful in 8m48s
ci / lint (pull_request) Successful in 14m57s
2026-11-23 16:50:28 +00:00
Sebi b82ed264f9 Merge pull request 'test: merge declaration flagged by staticcheck' (#127) from fix/lint-platform-sso into main
ci / test (push) Successful in 9m15s
ci / lint (push) Successful in 13m18s
ci / image (push) Successful in 6m50s
ci / build (push) Successful in 8m38s
2026-11-23 16:49:47 +00:00
Sebastian UnterschützandClaude Opus 5.5 ef759826b7 test: merge declaration flagged by staticcheck
ci / image (pull_request) Successful in 3m32s
ci / build (pull_request) Successful in 8m52s
ci / lint (pull_request) Successful in 11m59s
ci / test (pull_request) Successful in 12m9s
#123 was built before staticcheck came back in #125.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 17:36:47 +01:00
Sebi aa8c392784 Merge branch 'main' into renovate/go-toolchain
ci / lint (pull_request) Failing after 7m0s
renovate/stability-days Updates have met minimum release age requirement
ci / build (pull_request) Successful in 8m51s
ci / test (pull_request) Successful in 9m28s
ci / image (pull_request) Successful in 3m46s
2026-11-23 16:23:35 +00:00
Sebi 866e4c2313 chore(deps): pin dependencies
ci / image (pull_request) Successful in 5m10s
ci / test (pull_request) Successful in 18m16s
ci / build (pull_request) Successful in 9m5s
renovate/stability-days Updates have not met minimum release age requirement
ci / lint (pull_request) Failing after 10m22s
2026-11-23 16:21:49 +00:00
Sebi 5beb9f6451 Merge pull request 'chore(deps): update apache/kafka-native docker tag to v4.4.0' (#122) from renovate/apache-kafka-native-4.x into main
ci / test (push) Successful in 18m2s
ci / lint (push) Failing after 15m25s
ci / build (push) Successful in 5m57s
ci / image (push) Successful in 4m6s
2026-11-23 16:18:03 +00:00
Sebi 26d75de428 Merge pull request 'fix(deps): update module github.com/yuin/goldmark to v1.8.7' (#124) from renovate/github.com-yuin-goldmark-1.x 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-23 16:17:33 +00:00
Sebi a15dc0a2ff Merge pull request 'fix(deps): update module github.com/go-jose/go-jose/v4 to v4.1.9' (#121) from renovate/github.com-go-jose-go-jose-v4-4.x into main
ci / lint (push) Canceled after 24s
ci / test (push) Canceled after 18s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-23 16:17:03 +00:00
Sebi 29b9e1ce2b Merge pull request 'feat: sign up and sign in with platform identity providers' (#123) from feat/platform-sso into main
ci / lint (push) Canceled after 22s
ci / test (push) Canceled after 17s
ci / build (push) Canceled after 17s
ci / image (push) Canceled after 16s
2026-11-23 16:16:30 +00:00
Sebi b05f3dbdb0 Merge pull request 'ci: release automation from Conventional Commits' (#126) from feat/release into main
ci / lint (push) Canceled after 30s
ci / test (push) Canceled after 18s
ci / build (push) Canceled after 17s
ci / image (push) Canceled after 18s
2026-11-23 16:15:55 +00:00
Sebi 4097139e0b Merge pull request 'chore(lint): re-enable staticcheck and unused' (#125) from chore/staticcheck into main
ci / test (push) Successful in 14m21s
ci / lint (push) Successful in 9m59s
ci / image (push) Successful in 3m14s
ci / build (push) Successful in 11m43s
Reviewed-on: #125
2026-11-23 06:17:30 +00:00
Sebastian UnterschützandClaude Opus 5.5 68a7827475 ci: release automation from Conventional Commits
ci / image (pull_request) Successful in 3m39s
ci / build (pull_request) Successful in 5m34s
ci / lint (pull_request) Successful in 9m41s
ci / test (pull_request) Successful in 16m7s
tools/release derives the next version from the commits since the last
stable release and renders the changelog. `make release` tags it on main,
CHANNEL=beta a numbered prerelease of the coming version; pushing the tag
runs the release workflow, which publishes the release with its notes,
Linux binaries and checksums. Images get channel tags: edge for main, beta
for prereleases, latest, stable and X.Y for releases.

Closes #33

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 07:17:02 +01:00
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 ccc97eb406 fix(deps): update module github.com/yuin/goldmark to v1.8.7
renovate/stability-days Updates have met minimum release age requirement
ci / image (pull_request) Successful in 4m22s
ci / test (pull_request) Successful in 8m29s
ci / build (pull_request) Successful in 10m53s
ci / lint (pull_request) Successful in 11m10s
2026-11-23 01:14:44 +00:00
Sebastian UnterschützandClaude Opus 5.5 fe5c4fb24c feat: sign up and sign in with platform identity providers
ci / image (pull_request) Successful in 6m20s
ci / test (pull_request) Successful in 11m46s
ci / build (pull_request) Successful in 5m13s
ci / lint (pull_request) Successful in 5m45s
Platform admins register identity providers for the whole installation:
any OpenID Connect provider, checked by discovery, and GitHub or GitHub
Enterprise through OAuth, which reads the primary email GitHub verified.
Sign-in pages offer them; the sign-up page offers those open to sign-up,
also where email sign-up is closed for lack of a mail server.

Accounts are reached only through identities stored by subject. A new
identity signs up only with an email the provider confirmed, within the
per-address limit and sign-up mode, and never takes over an existing
account, including through an alias of its address: its owner links
the provider in the security settings. The account's TOTP still applies
after the provider. Unlinking refuses to remove the last way to sign in,
and removing a provider refuses while accounts depend on it.

The test browser takes the CSRF token from pages, as the console does.

Closes #114

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 01:26:14 +01:00
Sebi 77498934fc chore(deps): update apache/kafka-native docker tag to v4.4.0
ci / test (pull_request) Successful in 17m23s
renovate/stability-days Updates have met minimum release age requirement
ci / lint (pull_request) Successful in 14m45s
ci / image (pull_request) Successful in 7m11s
ci / build (pull_request) Successful in 9m0s
2026-11-23 00:15:48 +00:00
Sebi 8a035825f2 fix(deps): update module github.com/go-jose/go-jose/v4 to v4.1.9
ci / image (pull_request) Successful in 4m59s
renovate/stability-days Updates have met minimum release age requirement
ci / lint (pull_request) Successful in 5m39s
ci / build (pull_request) Successful in 4m58s
ci / test (pull_request) Successful in 12m44s
2026-11-23 00:15:26 +00:00
Sebi 06fd36c2a4 chore(deps): update go module directive to v1.27.4
renovate/stability-days Updates have met minimum release age requirement
ci / image (pull_request) Successful in 5m9s
ci / lint (pull_request) Failing after 5m51s
ci / build (pull_request) Successful in 14m53s
ci / test (pull_request) Successful in 20m12s
2026-11-22 23:13:33 +00:00
156 changed files with 21168 additions and 3063 deletions

No files matched your search

+4
View File
@@ -57,6 +57,10 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
# What checkers saw of HTTP responses. # What checkers saw of HTTP responses.
# UPTIME_RETENTION_EVIDENCE=720h # UPTIME_RETENTION_EVIDENCE=720h
# Image agents are installed and self-updated from (-checker or -statuspage
# is appended); set it to a mirror if agents cannot reach the default.
# UPTIME_AGENT_IMAGE=git.zb-server.de/zb-server/uptimesebi
# Status page server: hosts serving pages by slug; enable TLS for custom domains. # Status page server: hosts serving pages by slug; enable TLS for custom domains.
UPTIME_STATUSPAGE_URL=http://localhost:8082 UPTIME_STATUSPAGE_URL=http://localhost:8082
UPTIME_STATUSPAGE_HOSTS=localhost UPTIME_STATUSPAGE_HOSTS=localhost
+86 -14
View File
@@ -11,8 +11,9 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
env: env:
GOLANGCI_LINT_VERSION: v2.12.2 GOLANGCI_LINT_VERSION: v2.15.0
SQLC_VERSION: v1.31.1 SQLC_VERSION: v1.31.1
HELM_VERSION: v3.19.0
jobs: jobs:
lint: lint:
@@ -38,13 +39,34 @@ jobs:
sqlc generate sqlc generate
git diff --exit-code -- '*.go' git diff --exit-code -- '*.go'
- name: gofmt - name: gofmt
run: test -z "$(gofmt -l internal cmd)" || { gofmt -l internal cmd; exit 1; } run: test -z "$(gofmt -l internal cmd tools deploy)" || { gofmt -l internal cmd tools deploy; exit 1; }
- name: go vet - name: go vet
run: go vet ./... run: go vet ./...
- name: golangci-lint - name: golangci-lint
run: | run: |
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION} go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION}
"$(go env GOPATH)/bin/golangci-lint" run ./... "$(go env GOPATH)/bin/golangci-lint" run ./...
- name: Helm chart
run: |
curl -fsSL "https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz" | tar -xz -C /usr/local/bin --strip-components=1 linux-amd64/helm
chart=deploy/helm/uptimesebi
base="--set publicURL=https://uptime.example.com --set redis.url=redis://redis:6379/0 --set secretKeys.value=k1:test"
helm lint --strict "$chart" $base --set database.url=postgres://u:p@db/uptime
# Every combination renders; missing settings fail with a message.
helm template t "$chart" $base --set database.url=postgres://u:p@db/uptime >/dev/null
helm template t "$chart" $base --set database.bundled.enabled=true --set ingress.enabled=true --set ingress.tls.enabled=true \
--set checker.enabled=true --set checker.token=usa_x --set statuspage.enabled=true --set statuspage.token=usa_y \
--set 'statuspage.hosts={status.example.com}' --set statuspage.ingress.enabled=true \
--set redis.sentinel.master=m --set 'redis.sentinel.addrs={s1:26379}' --set redis.sentinel.password=p >/dev/null
helm template t "$chart" --set publicURL=https://uptime.example.com --set secretKeys.value=k1:test \
--set database.bundled.enabled=true --set redis.bundled.enabled=true --set redis.bundled.persistence.enabled=false >/dev/null
if helm template t "$chart" $base >/dev/null 2>&1; then echo "rendered without a database" >&2; exit 1; fi
# The install script the API serves must stay POSIX sh for Alpine,
# Debian and Raspberry Pi OS; the test renders and checks it.
- name: shellcheck
run: |
command -v shellcheck >/dev/null || { apt-get update -qq && apt-get install -y -qq shellcheck; }
go test -count=1 -run 'TestScript|TestInstall' -v ./deploy/agent/ | grep -v '^=== RUN'
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -58,7 +80,7 @@ jobs:
# Targets of the database checks; SQL Server is left to local runs, # Targets of the database checks; SQL Server is left to local runs,
# its image is too large for ephemeral runners. # its image is too large for ephemeral runners.
mariadb: mariadb:
image: mariadb:11 image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
env: env:
MARIADB_ROOT_PASSWORD: checkpw MARIADB_ROOT_PASSWORD: checkpw
MARIADB_DATABASE: shop MARIADB_DATABASE: shop
@@ -74,7 +96,7 @@ jobs:
RABBITMQ_DEFAULT_USER: check RABBITMQ_DEFAULT_USER: check
RABBITMQ_DEFAULT_PASS: checkpw RABBITMQ_DEFAULT_PASS: checkpw
kafka: kafka:
image: apache/kafka-native:4.1.1@sha256:b8faca36f5385f90e46861ea0b2f532ebed86e9b2868b717c75a67f6fda0c7ce image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
env: env:
KAFKA_NODE_ID: 1 KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller KAFKA_PROCESS_ROLES: broker,controller
@@ -116,7 +138,12 @@ jobs:
run: go test -p 1 -count=1 ./... run: go test -p 1 -count=1 ./...
build: build:
# Nothing is built or pushed from code that fails lint or tests; the
# image job waits for this one.
needs: [lint, test]
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs:
version: ${{ steps.binaries.outputs.version }}
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
# The runners are ephemeral and clone every action from GitHub, which # The runners are ephemeral and clone every action from GitHub, which
@@ -131,12 +158,47 @@ jobs:
- name: Build frontend - name: Build frontend
run: npm ci --no-audit --no-fund && npm run build run: npm ci --no-audit --no-fund && npm run build
- name: Build binaries - name: Build binaries
id: binaries
run: | run: |
for platform in linux/amd64 linux/arm64; do set -eu
CGO_ENABLED=0 GOOS=${platform%/*} GOARCH=${platform#*/} \ pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo
go build -trimpath -ldflags "-s -w" -o "dist/${platform%/*}_${platform#*/}/" ./cmd/... case "$GITHUB_REF" in
refs/tags/v*) version="$GITHUB_REF_NAME" ;;
*) version="$(git log -1 --format=%cd --date=format:%Y%m%d%H%M%S)-$(git rev-parse --short=12 HEAD)" ;;
esac
echo "VERSION=$version" >> "$GITHUB_ENV"
echo "version=$version" >> "$GITHUB_OUTPUT"
for platform in linux/amd64 linux/arm64 linux/arm/v7 linux/arm/v6; do
IFS=/ read -r os arch variant <<< "$platform"
CGO_ENABLED=0 GOOS=$os GOARCH=$arch GOARM=${variant#v} go build -trimpath \
-ldflags "-s -w -X $pkg.Version=$version -X $pkg.Commit=$(git rev-parse --short=12 HEAD)" \
-o "dist/$(echo "$platform" | tr / _)/" ./cmd/...
done
ls -lR dist
# Checker and status page images for every platform, plain and
# self-updating, assembled from the binaries above without Docker;
# pushed like the main image and signed for the self-updating agents.
- name: Agent images
env:
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
run: |
set -eu
host="${GITHUB_SERVER_URL#*://}"
owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')"
flags="-version $VERSION -commit $GITHUB_SHA -ref $GITHUB_REF -created $(git log -1 --format=%ct) -source $GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
case "$GITHUB_SERVER_URL" in http://*) flags="$flags -insecure" ;; esac
case "$GITHUB_REF" in
refs/heads/main|refs/tags/v*)
if [ -n "${PACKAGE_TOKEN:-}" ]; then flags="$flags -push"; else echo "PACKAGE_TOKEN is not set; building without pushing."; fi ;;
esac
export REGISTRY_USER="$GITHUB_ACTOR" REGISTRY_PASSWORD="${PACKAGE_TOKEN:-}"
go build -o image ./tools/image
for variant in "" -autoupdate; do
./image -name checker -repo "$host/$owner/uptimesebi-checker" -port 8081/tcp $variant $flags
./image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \
-env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $variant $flags
done done
ls -R dist
image: image:
# Kaniko runs rootless from docker:cli, the same way as the other # Kaniko runs rootless from docker:cli, the same way as the other
@@ -144,6 +206,9 @@ jobs:
# CLI, and Kaniko's own image lacks what the runner needs to keep a job # CLI, and Kaniko's own image lacks what the runner needs to keep a job
# container alive. Images are pushed only from main and tags, and only # container alive. Images are pushed only from main and tags, and only
# once the PACKAGE_TOKEN secret (write:package) exists. # once the PACKAGE_TOKEN secret (write:package) exists.
# The build job's version, so the API reports the release its agent
# images are tagged with.
needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d
@@ -155,22 +220,29 @@ jobs:
env: env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
VERSION: ${{ needs.build.outputs.version }}
run: | run: |
set -eu set -eu
REGISTRY="${GITHUB_SERVER_URL#*://}" REGISTRY="${GITHUB_SERVER_URL#*://}"
IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')" IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')"
SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)" SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)"
case "$GITHUB_REF" in TAG="$VERSION"
refs/tags/v*) TAG="$GITHUB_REF_NAME" ;;
*) TAG="$(date -u +%Y%m%d%H%M%S)-$SHORT" ;;
esac
PUSH="--no-push" PUSH="--no-push"
DEST="--destination ${IMAGE}:${TAG}" DEST="--destination ${IMAGE}:${TAG#v}"
# Channels: edge follows main, beta the newest prerelease, latest
# and stable the newest release, X.Y its newest patch.
case "$GITHUB_REF" in
refs/heads/main) CHANNELS="edge" ;;
refs/tags/v*-beta.*) CHANNELS="beta" ;;
refs/tags/v*)
MINOR="$(printf '%s' "${TAG#v}" | cut -d. -f1-2)"
CHANNELS="latest stable $MINOR" ;;
esac
case "$GITHUB_REF" in case "$GITHUB_REF" in
refs/heads/main|refs/tags/v*) refs/heads/main|refs/tags/v*)
if [ -n "${PACKAGE_TOKEN:-}" ]; then if [ -n "${PACKAGE_TOKEN:-}" ]; then
PUSH="" PUSH=""
[ "$GITHUB_REF" = refs/heads/main ] && DEST="$DEST --destination ${IMAGE}:latest" for c in $CHANNELS; do DEST="$DEST --destination ${IMAGE}:$c"; done
else else
echo "PACKAGE_TOKEN is not set; building without pushing." echo "PACKAGE_TOKEN is not set; building without pushing."
fi ;; fi ;;
+97
View File
@@ -0,0 +1,97 @@
name: release
# Runs for release tags, which `make release` creates. Only the Owners team
# may push v* tags (tag protection), and only tags on main are released.
# The image of a tag is built by the ci workflow.
on:
push:
tags: ["v*"]
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
# The notes need the history back to the previous release.
fetch-depth: 0
- name: Install Go
run: |
v="$(awk '/^go /{print $2}' go.mod)"
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz
echo /usr/local/go/bin >> "$GITHUB_PATH"
- name: Check tag
run: |
go run ./tools/release check "$GITHUB_REF_NAME"
# Only code that reached main through a protected merge is
# released, this workflow included: a tag on any other commit,
# e.g. one with a changed workflow, publishes nothing.
git fetch -q origin main
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
echo "::error::$GITHUB_REF_NAME does not point to a commit on main; not releasing."
exit 1
fi
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
- name: Package Helm chart
run: |
curl -fsSL "https://get.helm.sh/helm-v3.19.0-linux-amd64.tar.gz" | tar -xz -C /usr/local/bin --strip-components=1 linux-amd64/helm
# Chart and app version follow the release; image tags drop the v.
helm package deploy/helm/uptimesebi --version "${GITHUB_REF_NAME#v}" --app-version "${GITHUB_REF_NAME#v}" -d dist
- name: Build binaries
run: |
set -eu
pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo
commit="$(git rev-parse --short=12 HEAD)"
for platform in linux/amd64 linux/arm64 linux/arm/v7 linux/arm/v6; do
IFS=/ read -r os arch variant <<< "$platform"
dir="uptimesebi_${GITHUB_REF_NAME#v}_${os}_${arch}${variant}"
CGO_ENABLED=0 GOOS=$os GOARCH=$arch GOARM=${variant#v} go build -trimpath \
-ldflags "-s -w -X $pkg.Version=$GITHUB_REF_NAME -X $pkg.Commit=$commit" \
-o "dist/$dir/" ./cmd/...
cp LICENSE README.md .env.example "dist/$dir/"
tar -C dist -czf "dist/$dir.tar.gz" "$dir"
done
go run ./tools/release sbom "$GITHUB_REF_NAME" dist/uptimesebi_*_linux_amd64/{api,checker,statuspage} > dist/sbom.spdx.json
(cd dist && sha256sum ./*.tar.gz ./*.tgz ./sbom.spdx.json | sed 's| \./| |' > SHA256SUMS)
cat dist/SHA256SUMS
- name: Sign checksums
env:
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
run: |
if [ -z "$RELEASE_SIGNING_KEY" ]; then
echo "::warning::RELEASE_SIGNING_KEY is not set; the release is not signed."
exit 0
fi
go run ./tools/release sign dist/SHA256SUMS "$GITHUB_REF_NAME"
go run ./tools/release verify dist/SHA256SUMS
- name: Publish release
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
set -eu
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY"
if curl -fsS -o /dev/null -H "Authorization: token $TOKEN" "$api/releases/tags/$GITHUB_REF_NAME"; then
echo "Release $GITHUB_REF_NAME exists already; delete it to publish again." >&2
exit 1
fi
go run ./tools/release notes -json "$GITHUB_REF_NAME" > release.json
id="$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
--data-binary @release.json "$api/releases" | grep -o '"id":[0-9]*' | head -n1 | cut -d: -f2)"
for f in dist/*.tar.gz dist/*.tgz dist/sbom.spdx.json dist/SHA256SUMS dist/SHA256SUMS.minisig; do
[ -f "$f" ] || continue
curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")"
done
# helm repo add uptimesebi <server>/api/packages/<owner>/helm
- name: Publish Helm chart
env:
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
run: |
if [ -z "$PACKAGE_TOKEN" ]; then
echo "::warning::PACKAGE_TOKEN is not set; the chart is only attached to the release."
exit 0
fi
owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')"
curl -fsS --user "$GITHUB_ACTOR:$PACKAGE_TOKEN" -X POST --upload-file dist/uptimesebi-*.tgz \
"$GITHUB_SERVER_URL/api/packages/$owner/helm/api/charts"
+2 -2
View File
@@ -4,8 +4,6 @@ run:
tests: true tests: true
linters: 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 default: none
enable: enable:
- errcheck - errcheck
@@ -17,6 +15,8 @@ linters:
- misspell - misspell
- unconvert - unconvert
- usestdlibvars - usestdlibvars
- staticcheck
- unused
settings: settings:
revive: revive:
rules: rules:
+1 -1
View File
@@ -1,4 +1,4 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1@sha256:572cebbc2b15e6f84c077742952674889cb63cd5e9b80abdffcbe587b6f19183
FROM node:24-alpine AS web FROM node:24-alpine AS web
WORKDIR /src WORKDIR /src
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
+14 -1
View File
@@ -3,7 +3,7 @@ COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
PKG := git.zb-server.de/ZB-Server/uptimesebi PKG := git.zb-server.de/ZB-Server/uptimesebi
LDFLAGS := -s -w -X $(PKG)/internal/buildinfo.Version=$(VERSION) -X $(PKG)/internal/buildinfo.Commit=$(COMMIT) LDFLAGS := -s -w -X $(PKG)/internal/buildinfo.Version=$(VERSION) -X $(PKG)/internal/buildinfo.Commit=$(COMMIT)
.PHONY: generate web build test lint dev-up dev-up-sentinel dev-down migrate image .PHONY: generate web build test lint release dev-up dev-up-sentinel dev-down migrate image
generate: generate:
sqlc generate sqlc generate
@@ -22,6 +22,19 @@ test:
lint: lint:
golangci-lint run golangci-lint run
# Tags the next release from the Conventional Commits since the last one;
# pushing the tag publishes it. CHANNEL=beta tags a prerelease.
CHANNEL ?= stable
release:
@test "$$(git rev-parse --abbrev-ref HEAD)" = main || { echo "release from main" >&2; exit 1; }
@git diff --quiet HEAD || { echo "commit or stash your changes first" >&2; exit 1; }
@git fetch -q --tags origin main
@test "$$(git rev-parse HEAD)" = "$$(git rev-parse origin/main)" || { echo "main is not origin/main" >&2; exit 1; }
@tag="$$(go run ./tools/release next $(CHANNEL))" && \
git tag -a "$$tag" -m "$$tag" && \
go run ./tools/release notes "$$tag" && \
echo "Tagged $$tag. Publish it with: git push origin $$tag"
dev-up: dev-up:
docker compose up -d --wait docker compose up -d --wait
+68 -4
View File
@@ -16,9 +16,10 @@ It is built for teams and hosting providers: organizations with members, roles a
- **Multi-region:** checkers run per region, several per region for load and failover; any number of regions per monitor. - **Multi-region:** checkers run per region, several per region for load and failover; any number of regions per monitor.
- **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). - **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). - **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body).
- **Incident communication:** give an outage a title and post updates with a status (investigating, identified, monitoring, resolved), public on status pages or as internal notes.
- **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages. - **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. - **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, sign-up and sign-in with providers such as Google, Microsoft or GitHub, enforced 2FA, audit log.
- **Privacy:** GDPR data export (JSON, PDF) and deletion, configurable retention, no telemetry. - **Privacy:** GDPR data export (JSON, PDF) and deletion, also for suspended accounts; legal notice, privacy policy and terms of service, with versioned consent on sign-up and again after material changes; configurable retention, no telemetry.
- **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation. - **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation.
## Installation ## Installation
@@ -67,7 +68,24 @@ UPTIME_STATUSPAGE_CACHE_DIR=./.statuspage-cache go run ./cmd/statuspage
### Run in production ### Run in production
One image contains all three commands; `api` is the default entrypoint. One image contains all three commands; `api` is the default entrypoint. Images are published as `git.zb-server.de/zb-server/uptimesebi:<tag>`; pick a channel:
| Tag | Follows |
| --- | --- |
| `latest`, `stable` | the newest release |
| `1.4` | the newest patch release of 1.4 |
| `1.4.2` | exactly that release |
| `beta` | the newest prerelease (`1.5.0-beta.N`) |
| `edge` | every commit on `main` |
Each [release](https://git.zb-server.de/ZB-Server/uptimesebi/releases) also carries Linux binaries (amd64, arm64, armv7, armv6), the changelog, an SPDX SBOM (`sbom.spdx.json`: Go modules and bundled npm packages) and checksums signed with [minisign](https://jedisct1.github.io/minisign/). Verify a download with:
```sh
minisign -Vm SHA256SUMS -P RWRrmAkTu/xZg/o8QCsko5rUujqW/N165cj+dyEcp5CDXPTE2jKbLkyA
sha256sum -c --ignore-missing SHA256SUMS
```
The trusted comment names the release, so a signature cannot be passed off for another one. Or build the image yourself:
```sh ```sh
docker build -t uptimesebi . docker build -t uptimesebi .
@@ -77,6 +95,25 @@ docker run -d -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN
--entrypoint /usr/local/bin/checker uptimesebi --entrypoint /usr/local/bin/checker uptimesebi
``` ```
Checkers and status page servers also come as small images of their own, `uptimesebi-checker` and `uptimesebi-statuspage` (same tags), for Linux on amd64, arm64, arm/v7 and arm/v6, so they run on anything from a Raspberry Pi Zero to a server; `docker pull` picks the right one. They contain only the binary, run as an unprivileged user and keep their data in the volume `/var/lib/uptimesebi`:
```sh
docker run -d --restart unless-stopped -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN=usa_… \
git.zb-server.de/zb-server/uptimesebi-checker:latest
```
The quickest way onto a Linux host with Docker is the install script your platform serves, with its address filled in. It checks the host, writes `/opt/uptimesebi/<kind>/compose.yaml` and `.env` (the token readable only by root) and starts the agent:
```sh
curl -fsSL https://uptime.example.com/install.sh | sudo sh -s -- checker --token usa_…
curl -fsSL https://uptime.example.com/install.sh | sudo sh -s -- statuspage --token usa_… \
--host status.example.com --tls --email ops@example.com
```
`--help` lists the options: `--manual-updates` for the plain image, `--docker-socket` for checkers answering Docker monitors, `--name` for several agents on one host. To set it up yourself, take the Compose files in [`deploy/agent`](deploy/agent) and put `UPTIME_API_URL` and `UPTIME_AGENT_TOKEN` in a `.env` next to them.
To keep agents up to date without touching them, use the `-autoupdate` variant of the image (`uptimesebi-checker:latest-autoupdate`). Its launcher runs the agent and follows the release your platform runs: it asks the API every 15 minutes, downloads the new agent from the registry for its platform, accepts it only with a valid release signature, swaps the agent gracefully and rolls back if the new one does not become ready. Agents thus never get ahead of the API. The variant is a choice of image, not a setting; the plain image contains no update code. Agents of an installation running an unreleased build stay as they are. Set `UPTIME_AGENT_IMAGE` on the API if agents pull from a mirror.
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. 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: All settings are environment variables; [`.env.example`](.env.example) lists them with explanations. In particular:
@@ -87,6 +124,33 @@ All settings are environment variables; [`.env.example`](.env.example) lists the
- `UPTIME_TRUSTED_PROXIES` must name your reverse proxy, or client addresses in the audit log and rate limits will be the proxy's. - `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. - `UPTIME_RETENTION_*` set how long results, aggregates, audit entries and captured responses are kept.
### Docker Compose
[`deploy/compose`](deploy/compose) runs everything on one host: the console and API, a migration step before it starts, and optionally TimescaleDB, Redis, a checker and a status page server, each chosen through `COMPOSE_PROFILES` in `.env`:
```sh
cp .env.example .env && chmod 600 .env # fill in UPTIME_PUBLIC_URL, UPTIME_SECRET_KEYS and the passwords
docker compose up -d
```
Leave `db` and `redis` out of the profiles and set `UPTIME_DATABASE_URL` and `UPTIME_REDIS_URL` to use your own. The checker and status page server need a token, created with `docker compose exec api api agent create …` (the comments in `.env.example` show how). Containers run with a read-only root filesystem and without capabilities.
### Kubernetes
The Helm chart in [`deploy/helm/uptimesebi`](deploy/helm/uptimesebi) runs the console and API, and optionally a checker and status page servers in the cluster. Bring your own PostgreSQL with TimescaleDB and your own Redis (directly or through Sentinel). Each release publishes the chart:
```sh
helm repo add uptimesebi https://git.zb-server.de/api/packages/zb-server/helm
helm install uptime uptimesebi/uptimesebi -n uptime --create-namespace \
--set publicURL=https://uptime.example.com \
--set database.url='postgres://uptime:…@db:5432/uptime?sslmode=require' \
--set redis.url='redis://:…@redis:6379/0' \
--set secretKeys.value="k1:$(head -c32 /dev/urandom | base64)" \
--set ingress.enabled=true --set ingress.tls.enabled=true
```
Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too.
Run as many API, checker and status page instances as you need; they share no local state. The supported setups are: Run as many API, checker and status page instances as you need; they share no local state. The supported setups are:
| Mode | Console and API | Checkers | Status pages | | Mode | Console and API | Checkers | Status pages |
@@ -156,7 +220,7 @@ make lint
The tests run against the `uptime_test` database and Redis database 15 from [`.env.example`](.env.example). CI runs lint, tests, builds and the image for every pull request ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)). The tests run against the `uptime_test` database and Redis database 15 from [`.env.example`](.env.example). CI runs lint, tests, builds and the image for every pull request ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)).
Commits follow [Conventional Commits](https://www.conventionalcommits.org/). Code comments, commits and issues are in English; the interface is translated (English and German, `internal/i18n/locales`). Commits follow [Conventional Commits](https://www.conventionalcommits.org/), which decide the version: `make release` tags the next one on `main` (breaking changes move the major version, before 1.0 the minor one; `feat` the minor, `fix` and `perf` the patch version), `make release CHANNEL=beta` the next prerelease. Pushing the tag publishes the release with its changelog ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)), signed with the key in the `RELEASE_SIGNING_KEY` secret. To rotate it, create a key with `go run ./tools/release keygen <file>`, add the printed public key to [`internal/signing/release.pub`](internal/signing/release.pub) (keep the old one, so self-updating agents can update across the change) and replace the secret. Code comments, commits and issues are in English; the interface is translated (English and German, `internal/i18n/locales`).
## License ## License
+8 -2
View File
@@ -21,6 +21,7 @@ import (
const usage = `usage: const usage = `usage:
api [serve] api [serve]
api migrate up|down|status api migrate up|down|status
api health
api admin grant|revoke <email> api admin grant|revoke <email>
api region add <key> [name] api region add <key> [name]
api agent create --kind checker|statuspage [--region <key>] --name <name> api agent create --kind checker|statuspage [--region <key>] --name <name>
@@ -30,6 +31,11 @@ const usage = `usage:
region and agent manage platform resources shared by all organizations; region and agent manage platform resources shared by all organizations;
organizations manage their own in the console.` 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 // admin runs operator commands. They act across all organizations, hence the
// system scope, and print to stdout for humans and scripts. // system scope, and print to stdout for humans and scripts.
func admin(ctx context.Context, cfg config.API, args []string) error { func admin(ctx context.Context, cfg config.API, args []string) error {
@@ -96,7 +102,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error {
return err return err
}) })
} }
return errors.New(usage) return usageError{}
} }
func createAgent(ctx context.Context, db *tenant.DB, args []string) error { func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
@@ -108,7 +114,7 @@ func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
return err return err
} }
if *name == "" || (*kind == "checker") != (*region != "") { if *name == "" || (*kind == "checker") != (*region != "") {
return errors.New(usage) return usageError{}
} }
var tok string var tok string
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
+4 -1
View File
@@ -48,9 +48,12 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
return migrate(ctx, log, cfg, args[1:]) return migrate(ctx, log, cfg, args[1:])
case "admin", "agent", "region": case "admin", "agent", "region":
return admin(ctx, cfg, args) return admin(ctx, cfg, args)
case "health":
// The image has no shell; Docker's HEALTHCHECK runs this.
return platform.ProbeLocal(ctx, cfg.Listen, "/healthz")
case "serve": case "serve":
default: default:
return errors.New(usage) return usageError{}
} }
} }
+22 -1
View File
@@ -5,6 +5,7 @@
package main package main
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
@@ -20,6 +21,17 @@ import (
) )
func main() { func main() {
if len(os.Args) == 2 && os.Args[1] == "version" {
fmt.Println(buildinfo.Version)
return
}
if len(os.Args) == 2 && os.Args[1] == "health" {
if err := health(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log, level := platform.NewLogger("checker") log, level := platform.NewLogger("checker")
// Route the standard log package and dependencies through the same handler. // Route the standard log package and dependencies through the same handler.
slog.SetDefault(log) slog.SetDefault(log)
@@ -35,7 +47,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
return err return err
} }
level.Set(cfg.LogLevel) level.Set(cfg.LogLevel)
if err := cfg.Common.Validate(); err != nil { if err := cfg.Validate(); err != nil {
return err return err
} }
ctx, stop := platform.SignalContext() ctx, stop := platform.SignalContext()
@@ -68,3 +80,12 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
} }
return errors.Join(runErr, <-serveErr) return errors.Join(runErr, <-serveErr)
} }
// health probes the running checker in this container.
func health() error {
cfg, err := config.Load[config.Checker]()
if err != nil {
return err
}
return platform.ProbeLocal(context.Background(), cfg.HealthListen, "/healthz")
}
+94
View File
@@ -0,0 +1,94 @@
// Command launcher is the entrypoint of the self-updating agent images. It
// runs the agent named by UPTIME_LAUNCHER_AGENT and keeps it on the
// release the platform runs, with signed downloads and rollback.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentimage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/launcher"
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
func main() {
log, level := platform.NewLogger("launcher")
slog.SetDefault(log)
if err := run(log, level); err != nil {
log.Error("exit", "error", err)
os.Exit(1)
}
}
// settings are what the launcher needs from the agent's configuration.
type settings struct {
common config.Common
agent config.Agent
listen string
}
func load(agent string) (settings, error) {
switch agent {
case "checker":
c, err := config.Load[config.Checker]()
return settings{c.Common, c.Agent, c.HealthListen}, err
case "statuspage":
c, err := config.Load[config.StatusPage]()
return settings{c.Common, c.Agent, c.Listen}, err
}
return settings{}, fmt.Errorf("UPTIME_LAUNCHER_AGENT is %q, not checker or statuspage", agent)
}
func run(log *slog.Logger, level *slog.LevelVar) error {
agent := os.Getenv("UPTIME_LAUNCHER_AGENT")
s, err := load(agent)
if err != nil {
return err
}
level.Set(s.common.LogLevel)
ctx, stop := platform.SignalContext()
defer stop()
bundled := filepath.Join(agentimage.BinDir, agent)
current, err := launcher.BinaryVersion(bundled)
if err != nil {
return err
}
client := agentapi.NewClient(s.agent.APIURL, s.agent.Token, uuid.New(), current)
platformOf := launcher.Platform()
l := launcher.New(launcher.Config{
Agent: agent,
Bundled: bundled,
Dir: filepath.Join(agentimage.DataDir, "launcher"),
Interval: 15 * time.Minute,
ReadyWait: 2 * time.Minute,
StopTimeout: s.common.ShutdownTimeout + 10*time.Second,
RetryAfter: 6 * time.Hour,
Log: log.With("agent", agent, "platform", platformOf.String()),
Updates: client.Update,
Fetch: func(ctx context.Context, u agentapi.Update) ([]byte, error) {
return agentimage.Fetch(ctx, u.Image, agent, u.Version, platformOf, signing.ReleaseKeys())
},
Start: launcher.StartProcess,
Ready: func(ctx context.Context) error {
return platform.ProbeLocal(ctx, s.listen, "/readyz")
},
Version: launcher.BinaryVersion,
})
err = l.Run(ctx)
if errors.Is(ctx.Err(), context.Canceled) {
return nil
}
return err
}
+21 -1
View File
@@ -28,6 +28,17 @@ import (
) )
func main() { func main() {
if len(os.Args) == 2 && os.Args[1] == "version" {
fmt.Println(buildinfo.Version)
return
}
if len(os.Args) == 2 && os.Args[1] == "health" {
if err := health(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log, level := platform.NewLogger("statuspage") log, level := platform.NewLogger("statuspage")
// Route the standard log package and dependencies through the same handler. // Route the standard log package and dependencies through the same handler.
slog.SetDefault(log) slog.SetDefault(log)
@@ -43,7 +54,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
return err return err
} }
level.Set(cfg.LogLevel) level.Set(cfg.LogLevel)
if err := cfg.Common.Validate(); err != nil { if err := cfg.Validate(); err != nil {
return err return err
} }
ctx, stop := platform.SignalContext() ctx, stop := platform.SignalContext()
@@ -168,3 +179,12 @@ func resolveCacheDir(dir string) (string, error) {
} }
return filepath.Join(base, "uptimesebi-statuspage"), nil return filepath.Join(base, "uptimesebi-statuspage"), nil
} }
// health probes the running statuspage in this container.
func health() error {
cfg, err := config.Load[config.StatusPage]()
if err != nil {
return err
}
return platform.ProbeLocal(context.Background(), cfg.Listen, "/healthz")
}
+2 -2
View File
@@ -53,7 +53,7 @@ services:
# Databases the database checks are tested against: # Databases the database checks are tested against:
# docker compose --profile checks up -d --wait # docker compose --profile checks up -d --wait
mariadb: mariadb:
image: mariadb:11 image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
profiles: [checks] profiles: [checks]
environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop} environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop}
ports: ["13306:3306"] ports: ["13306:3306"]
@@ -93,7 +93,7 @@ services:
retries: 60 retries: 60
kafka: kafka:
image: apache/kafka-native:4.1.1@sha256:b8faca36f5385f90e46861ea0b2f532ebed86e9b2868b717c75a67f6fda0c7ce image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
profiles: [checks] profiles: [checks]
ports: ["19092:9092"] ports: ["19092:9092"]
environment: environment:
+78
View File
@@ -0,0 +1,78 @@
// Package agent holds the Docker Compose files of the agents and the
// script that installs them, which the API serves at /install.sh.
package agent
import (
"bytes"
"embed"
"fmt"
"net/url"
"regexp"
"strings"
"text/template"
)
//go:embed compose.checker.yaml compose.statuspage.yaml compose.docker-socket.yaml install.sh.tmpl
var files embed.FS
// Compose returns the Compose file of an agent kind (checker, statuspage)
// or of the docker-socket addition.
func Compose(name string) ([]byte, error) {
return files.ReadFile("compose." + name + ".yaml")
}
// Install is what the platform fills into the install script.
type Install struct {
// APIURL is the platform's public address.
APIURL string
// Image is the image name; -checker or -statuspage is appended.
Image string
// Tag is the channel the platform runs: latest, beta or edge.
Tag string
}
var (
safeImage = regexp.MustCompile(`^[a-z0-9.:/_-]+$`)
stable = regexp.MustCompile(`^v\d+\.\d+\.\d+$`)
beta = regexp.MustCompile(`^v\d+\.\d+\.\d+-beta\.\d+$`)
)
// Script renders the install script.
func Script(in Install) ([]byte, error) {
u, err := url.Parse(in.APIURL)
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || strings.ContainsAny(in.APIURL, "'\n") {
return nil, fmt.Errorf("agent: %q is not a usable platform address", in.APIURL)
}
if !safeImage.MatchString(in.Image) || !safeImage.MatchString(in.Tag) {
return nil, fmt.Errorf("agent: unusable image %q or tag %q", in.Image, in.Tag)
}
tmpl, err := template.ParseFS(files, "install.sh.tmpl")
if err != nil {
return nil, err
}
data := map[string]string{"APIURL": strings.TrimSuffix(in.APIURL, "/"), "Image": in.Image, "Tag": in.Tag}
for key, name := range map[string]string{"Checker": "checker", "StatusPage": "statuspage", "DockerSocket": "docker-socket"} {
c, err := Compose(name)
if err != nil {
return nil, err
}
data[key] = string(c)
}
var b bytes.Buffer
if err := tmpl.Execute(&b, data); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Channel is the image tag that follows a platform release: latest for
// releases, beta for prereleases, edge for everything else.
func Channel(version string) string {
switch {
case stable.MatchString(version):
return "latest"
case beta.MatchString(version):
return "beta"
}
return "edge"
}
+196
View File
@@ -0,0 +1,196 @@
package agent
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// fakeDocker answers like Docker with Compose for the install script and
// logs every call.
const fakeDocker = `#!/bin/sh
echo "$*" >> "$FAKE_LOG"
case "$*" in
"compose ps -q"*) echo c0ffee ;;
inspect*) echo healthy ;;
esac
exit 0
`
type installRun struct {
dir, log, out string
err error
}
func runInstall(t *testing.T, script []byte, env []string, args ...string) installRun {
t.Helper()
tmp := t.TempDir()
bin := filepath.Join(tmp, "bin")
if err := os.Mkdir(bin, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(fakeDocker), 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(tmp, "install.sh")
if err := os.WriteFile(path, script, 0o755); err != nil {
t.Fatal(err)
}
r := installRun{dir: filepath.Join(tmp, "agent"), log: filepath.Join(tmp, "docker.log")}
// bash --posix is close to dash and busybox; the script must stay POSIX.
cmd := exec.Command("bash", append([]string{"--posix", path}, append(args, "--dir", r.dir)...)...)
cmd.Env = append([]string{"PATH=" + bin + ":/usr/bin:/bin", "FAKE_LOG=" + r.log}, env...)
out, err := cmd.CombinedOutput()
r.out, r.err = string(out), err
return r
}
func read(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func script(t *testing.T) []byte {
t.Helper()
s, err := Script(Install{APIURL: "https://uptime.example.com/", Image: "git.example.com/acme/uptimesebi", Tag: "latest"})
if err != nil {
t.Fatal(err)
}
return s
}
func TestInstallChecker(t *testing.T) {
r := runInstall(t, script(t), nil, "checker", "--token", "usa_secret")
if r.err != nil {
t.Fatalf("install failed: %v\n%s", r.err, r.out)
}
checker, _ := Compose("checker")
if got := read(t, filepath.Join(r.dir, "compose.yaml")); got != string(checker) {
t.Errorf("compose.yaml = %q", got)
}
env := read(t, filepath.Join(r.dir, ".env"))
for _, want := range []string{
"UPTIME_API_URL=https://uptime.example.com\n", "UPTIME_AGENT_TOKEN=usa_secret\n",
"UPTIME_AGENT_IMAGE=git.example.com/acme/uptimesebi\n", "UPTIME_AGENT_TAG=latest-autoupdate\n",
} {
if !strings.Contains(env, want) {
t.Errorf(".env lacks %q:\n%s", want, env)
}
}
if st, _ := os.Stat(filepath.Join(r.dir, ".env")); st.Mode().Perm() != 0o600 {
t.Errorf(".env mode = %v", st.Mode().Perm())
}
if log := read(t, r.log); !strings.Contains(log, "compose pull") || !strings.Contains(log, "compose up -d") {
t.Errorf("docker calls:\n%s", log)
}
if !strings.Contains(r.out, "updates itself") {
t.Errorf("output:\n%s", r.out)
}
}
func TestInstallStatusPage(t *testing.T) {
r := runInstall(t, script(t), []string{"UPTIME_AGENT_TOKEN=usa_fromenv"}, "statuspage",
"--host", "status.example.com", "--host", "status.example.org", "--tls", "--email", "ops@example.com",
"--manual-updates", "--http-port", "8080", "--no-start")
if r.err != nil {
t.Fatalf("install failed: %v\n%s", r.err, r.out)
}
env := read(t, filepath.Join(r.dir, ".env"))
for _, want := range []string{
"UPTIME_AGENT_TOKEN=usa_fromenv\n", "UPTIME_AGENT_TAG=latest\n",
"UPTIME_STATUSPAGE_HOSTS=status.example.com,status.example.org\n", "UPTIME_STATUSPAGE_TLS=true\n",
"UPTIME_STATUSPAGE_TLS_LISTEN=:8443\n", "UPTIME_ACME_EMAIL=ops@example.com\n", "UPTIME_HTTP_PORT=8080\n",
} {
if !strings.Contains(env, want) {
t.Errorf(".env lacks %q:\n%s", want, env)
}
}
if log, _ := os.ReadFile(r.log); strings.Contains(string(log), "compose up") {
t.Error("--no-start started the agent")
}
// Running it again keeps the old settings as a backup.
again := runInstall(t, script(t), nil, "statuspage", "--token", "usa_new", "--no-start")
if again.err != nil {
t.Fatal(again.out)
}
}
func TestInstallSocket(t *testing.T) {
if _, err := os.Stat("/var/run/docker.sock"); err != nil {
t.Skip("no Docker socket on this host")
}
r := runInstall(t, script(t), nil, "checker", "--token", "usa_x", "--docker-socket", "--no-start")
if r.err != nil {
t.Fatalf("install failed: %v\n%s", r.err, r.out)
}
socket, _ := Compose("docker-socket")
if read(t, filepath.Join(r.dir, "compose.override.yaml")) != string(socket) || !strings.Contains(read(t, filepath.Join(r.dir, ".env")), "DOCKER_GID=") {
t.Error("the Docker socket is not set up")
}
}
func TestInstallRefuses(t *testing.T) {
for name, args := range map[string][]string{
"no token": {"checker"},
"user token": {"checker", "--token", "ust_abc"},
"unknown kind": {"database", "--token", "usa_x"},
"unknown option": {"checker", "--token", "usa_x", "--force"},
"tls without host": {"statuspage", "--token", "usa_x", "--tls", "--email", "a@b.c"},
"host for a checker": {"checker", "--token", "usa_x", "--host", "x.example.com"},
"socket for pages": {"statuspage", "--token", "usa_x", "--docker-socket"},
"bad name": {"checker", "--token", "usa_x", "--name", "../etc"},
} {
r := runInstall(t, script(t), nil, args...)
if r.err == nil {
t.Errorf("%s: installed:\n%s", name, r.out)
}
if _, err := os.Stat(r.dir); err == nil {
t.Errorf("%s: wrote files", name)
}
}
}
func TestScript(t *testing.T) {
for _, bad := range []Install{
{APIURL: "ftp://x", Image: "a", Tag: "latest"},
{APIURL: "https://x.example/'$(reboot)'", Image: "a", Tag: "latest"},
{APIURL: "https://x.example", Image: "a b", Tag: "latest"},
{APIURL: "https://x.example", Image: "a", Tag: "$(id)"},
} {
if _, err := Script(bad); err == nil {
t.Errorf("Script(%+v) accepted", bad)
}
}
path := filepath.Join(t.TempDir(), "install.sh")
if err := os.WriteFile(path, script(t), 0o644); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("bash", "--posix", "-n", path).CombinedOutput(); err != nil {
t.Fatalf("syntax: %v %s", err, out)
}
// shellcheck runs in CI; locally only when installed.
sc, err := exec.LookPath("shellcheck")
if err != nil {
t.Skip("shellcheck is not installed")
}
if out, err := exec.Command(sc, "--shell=sh", path).CombinedOutput(); err != nil {
t.Errorf("shellcheck:\n%s", out)
}
}
func TestChannel(t *testing.T) {
for v, want := range map[string]string{
"v1.4.2": "latest", "v1.5.0-beta.2": "beta", "20261123180000-abc": "edge", "dev": "edge", "v1.4": "edge",
} {
if got := Channel(v); got != want {
t.Errorf("Channel(%s) = %s, want %s", v, got, want)
}
}
}
+18
View File
@@ -0,0 +1,18 @@
# UptimeSebi checker. Settings are in .env next to this file; start with
# `docker compose up -d`. UPTIME_AGENT_TAG picks the image: latest-autoupdate
# follows the platform's release by itself, latest (or a version) does not.
services:
checker:
image: ${UPTIME_AGENT_IMAGE:-git.zb-server.de/zb-server/uptimesebi}-checker:${UPTIME_AGENT_TAG:-latest-autoupdate}
restart: unless-stopped
env_file: .env
volumes:
- data:/var/lib/uptimesebi
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
volumes:
data:
+9
View File
@@ -0,0 +1,9 @@
# Lets the checker answer Docker monitors from this host's Docker API. Use it
# only for checkers that may see this host: the socket is read-only, but it
# still reveals everything running here. DOCKER_GID is the socket's group.
services:
checker:
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
group_add:
- "${DOCKER_GID:?set DOCKER_GID to the group of /var/run/docker.sock}"
+23
View File
@@ -0,0 +1,23 @@
# UptimeSebi status page server. Settings are in .env next to this file;
# start with `docker compose up -d`. UPTIME_AGENT_TAG picks the image:
# latest-autoupdate follows the platform's release by itself, latest (or a
# version) does not.
services:
statuspage:
image: ${UPTIME_AGENT_IMAGE:-git.zb-server.de/zb-server/uptimesebi}-statuspage:${UPTIME_AGENT_TAG:-latest-autoupdate}
restart: unless-stopped
env_file: .env
ports:
# HTTP; with TLS it answers ACME challenges and redirects to HTTPS.
- "${UPTIME_HTTP_PORT:-80}:8082"
- "${UPTIME_HTTPS_PORT:-443}:8443"
volumes:
- data:/var/lib/uptimesebi
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
volumes:
data:
+182
View File
@@ -0,0 +1,182 @@
#!/bin/sh
# Installs an UptimeSebi checker or status page server with Docker Compose.
# Served by the platform at /install.sh, with its address filled in:
#
# curl -fsSL {{.APIURL}}/install.sh | sudo sh -s -- checker --token usa_...
# curl -fsSL {{.APIURL}}/install.sh | sudo sh -s -- statuspage --token usa_... \
# --host status.example.com --tls --email ops@example.com
#
# The token may also come from UPTIME_AGENT_TOKEN. Run it again to change
# the settings; data is kept.
set -eu
API_URL='{{.APIURL}}'
IMAGE='{{.Image}}'
TAG='{{.Tag}}'
usage() {
cat <<'USAGE'
usage: install.sh checker|statuspage --token TOKEN [options]
--token TOKEN agent token from the console (or UPTIME_AGENT_TOKEN)
--name NAME installation name, for several on one host (default: the kind)
--dir DIR where to keep compose.yaml and .env (default: /opt/uptimesebi/KIND[-NAME])
--manual-updates use the plain image; update with docker compose pull && docker compose up -d
--docker-socket checker: answer Docker monitors from this host's Docker API
--host HOST status page: host name serving pages by slug (repeatable)
--tls status page: HTTPS with certificates from Let's Encrypt
--email EMAIL status page: contact address for Let's Encrypt
--http-port PORT status page: host port for HTTP (default 80)
--https-port PORT status page: host port for HTTPS (default 443)
--no-start write the files but do not start
USAGE
}
fail() {
echo "install.sh: $*" >&2
exit 1
}
kind=${1:-}
case $kind in
checker | statuspage) shift ;;
-h | --help) usage; exit 0 ;;
*) usage >&2; exit 2 ;;
esac
token=${UPTIME_AGENT_TOKEN:-}
name=''
dir=''
autoupdate=1
socket=0
hosts=''
tls=0
email=''
http_port=80
https_port=443
start=1
while [ $# -gt 0 ]; do
case $1 in
--token) token=${2:?--token needs a value}; shift 2 ;;
--name) name=${2:?--name needs a value}; shift 2 ;;
--dir) dir=${2:?--dir needs a value}; shift 2 ;;
--manual-updates) autoupdate=0; shift ;;
--docker-socket) socket=1; shift ;;
--host) hosts=${hosts:+$hosts,}${2:?--host needs a value}; shift 2 ;;
--tls) tls=1; shift ;;
--email) email=${2:?--email needs a value}; shift 2 ;;
--http-port) http_port=${2:?--http-port needs a value}; shift 2 ;;
--https-port) https_port=${2:?--https-port needs a value}; shift 2 ;;
--no-start) start=0; shift ;;
-h | --help) usage; exit 0 ;;
*) fail "unknown option $1 (see --help)" ;;
esac
done
case $token in
usa_*) ;;
'') fail "the agent token is missing: --token usa_... (create one in the console)" ;;
*) fail "that is not an agent token; agent tokens start with usa_" ;;
esac
case $name in
*[!a-z0-9-]*) fail "--name may contain only a-z, 0-9 and -" ;;
esac
if [ "$kind" = checker ] && { [ -n "$hosts" ] || [ "$tls" = 1 ]; }; then
fail "--host and --tls are for status pages"
fi
if [ "$kind" = statuspage ] && [ "$socket" = 1 ]; then
fail "--docker-socket is for checkers"
fi
if [ "$tls" = 1 ] && { [ -z "$hosts" ] || [ -z "$email" ]; }; then
fail "--tls needs --host and --email"
fi
# Linux on x86-64, 64-bit ARM, ARMv7 or ARMv6 (Raspberry Pi Zero and 1).
[ "$(uname -s)" = Linux ] || fail "UptimeSebi agents run on Linux only"
case $(uname -m) in
x86_64 | amd64 | aarch64 | arm64 | armv7l | armv6l) ;;
*) fail "no image for $(uname -m); supported are x86_64, aarch64, armv7l and armv6l" ;;
esac
command -v docker >/dev/null 2>&1 || fail "Docker is not installed; see https://docs.docker.com/engine/install/"
docker compose version >/dev/null 2>&1 || fail "the Docker Compose plugin is missing; see https://docs.docker.com/compose/install/linux/"
docker info >/dev/null 2>&1 || fail "cannot reach Docker; run as root (sudo) or as a member of the docker group"
dir=${dir:-/opt/uptimesebi/$kind${name:+-$name}}
mkdir -p "$dir" 2>/dev/null || fail "cannot create $dir; run with sudo"
cd "$dir"
tag=$TAG
[ "$autoupdate" = 1 ] && tag=$tag-autoupdate
compose_checker() {
cat <<'COMPOSE'
{{.Checker}}COMPOSE
}
compose_statuspage() {
cat <<'COMPOSE'
{{.StatusPage}}COMPOSE
}
compose_socket() {
cat <<'COMPOSE'
{{.DockerSocket}}COMPOSE
}
"compose_$kind" >compose.yaml
rm -f compose.override.yaml
if [ "$socket" = 1 ]; then
[ -S /var/run/docker.sock ] || fail "/var/run/docker.sock does not exist"
compose_socket >compose.override.yaml
fi
[ -f .env ] && cp -p .env .env.bak
umask 077
{
echo "# Written by install.sh. Run it again or edit this file, then: docker compose up -d"
echo "UPTIME_API_URL=$API_URL"
echo "UPTIME_AGENT_TOKEN=$token"
echo "UPTIME_AGENT_IMAGE=$IMAGE"
echo "UPTIME_AGENT_TAG=$tag"
if [ "$socket" = 1 ]; then
echo "DOCKER_GID=$(stat -c %g /var/run/docker.sock)"
fi
if [ "$kind" = statuspage ]; then
echo "UPTIME_STATUSPAGE_HOSTS=${hosts:-localhost}"
echo "UPTIME_HTTP_PORT=$http_port"
echo "UPTIME_HTTPS_PORT=$https_port"
if [ "$tls" = 1 ]; then
echo "UPTIME_STATUSPAGE_TLS=true"
echo "UPTIME_STATUSPAGE_TLS_LISTEN=:8443"
echo "UPTIME_ACME_EMAIL=$email"
fi
fi
} >.env
echo "Wrote $dir/compose.yaml and $dir/.env."
if [ "$start" = 0 ]; then
echo "Start it with: cd $dir && docker compose up -d"
exit 0
fi
docker compose pull --quiet
docker compose up -d --remove-orphans
container=$(docker compose ps -q "$kind")
printf 'Waiting for the %s to become healthy' "$kind"
i=0
while [ $i -lt 60 ]; do
status=$(docker inspect --format '{{"{{"}}.State.Health.Status{{"}}"}}' "$container" 2>/dev/null || echo unknown)
[ "$status" = healthy ] && break
printf .
sleep 3
i=$((i + 1))
done
echo
if [ "$status" != healthy ]; then
docker compose logs --tail 30 "$kind" >&2 || true
fail "the $kind did not become healthy; see the log above and: cd $dir && docker compose logs"
fi
echo "The $kind is running. It appears as connected in the console."
if [ "$autoupdate" = 1 ]; then
echo "It updates itself to the platform's release."
else
echo "Update it with: cd $dir && docker compose pull && docker compose up -d"
fi
echo "Logs: cd $dir && docker compose logs -f Remove: cd $dir && docker compose down -v"
+40
View File
@@ -0,0 +1,40 @@
# Settings for compose.yaml; copy to .env (chmod 600) and fill in.
# Parts to run: db and redis bundle TimescaleDB and Redis, checker and
# statuspage add a checker and a status page server on this host.
COMPOSE_PROFILES=db,redis
# Image and channel: latest (releases), beta, edge (main), or a version.
UPTIME_TAG=latest
# UPTIME_IMAGE=git.zb-server.de/zb-server/uptimesebi
# Address users reach the console at.
UPTIME_PUBLIC_URL=http://localhost:8080
UPTIME_PORT=8080
# Encrypts stored secrets; generate with: echo "k1:$(head -c32 /dev/urandom | base64)"
UPTIME_SECRET_KEYS=
# first-user, open or closed.
UPTIME_SIGNUP=first-user
# UPTIME_SMTP_URL=smtp://user:pass@host:587?from=alerts@example.com
# Address of a reverse proxy in front, e.g. 172.16.0.0/12 for one in Docker.
# UPTIME_TRUSTED_PROXIES=
# Bundled database and Redis (profiles db and redis); generate with:
# head -c24 /dev/urandom | base64 | tr -d '/+='
POSTGRES_PASSWORD=
REDIS_PASSWORD=
# Or your own; then drop db and redis from COMPOSE_PROFILES.
# UPTIME_DATABASE_URL=postgres://uptime:...@db.example.com:5432/uptime?sslmode=require
# UPTIME_REDIS_URL=redis://:...@redis.example.com:6379/0
# Checker on this host (profile checker); token from:
# docker compose exec api api region add <key> <name>
# docker compose exec api api agent create --kind checker --region <key> --name <name>
# UPTIME_CHECKER_TOKEN=
# Status page server on this host (profile statuspage); token from:
# docker compose exec api api agent create --kind statuspage --name <name>
# UPTIME_STATUSPAGE_TOKEN=
# UPTIME_STATUSPAGE_HOSTS=status.example.com
# UPTIME_STATUSPAGE_PORT=8082
# UPTIME_STATUSPAGE_URL=https://status.example.com
+142
View File
@@ -0,0 +1,142 @@
# UptimeSebi on one host with Docker Compose. Copy .env.example to .env,
# fill it in and run: docker compose up -d
#
# COMPOSE_PROFILES in .env picks the parts: db and redis bundle TimescaleDB
# and Redis (leave them out and set UPTIME_DATABASE_URL / UPTIME_REDIS_URL
# to use your own), checker and statuspage add a checker and a status page
# server on this host. To switch a part off again, take it out of
# COMPOSE_PROFILES and remove its container: docker compose rm -sf checker
x-image: &image ${UPTIME_IMAGE:-git.zb-server.de/zb-server/uptimesebi}:${UPTIME_TAG:-latest}
x-platform: &platform
UPTIME_PUBLIC_URL: ${UPTIME_PUBLIC_URL:?set UPTIME_PUBLIC_URL in .env}
UPTIME_SECRET_KEYS: ${UPTIME_SECRET_KEYS:?set UPTIME_SECRET_KEYS in .env}
UPTIME_DATABASE_URL: ${UPTIME_DATABASE_URL:-postgres://uptime:${POSTGRES_PASSWORD:-}@db:5432/uptime?sslmode=disable}
UPTIME_REDIS_URL: ${UPTIME_REDIS_URL:-redis://:${REDIS_PASSWORD:-}@redis:6379/0}
UPTIME_SIGNUP: ${UPTIME_SIGNUP:-first-user}
UPTIME_SMTP_URL: ${UPTIME_SMTP_URL:-}
UPTIME_STATUSPAGE_URL: ${UPTIME_STATUSPAGE_URL:-}
UPTIME_TRUSTED_PROXIES: ${UPTIME_TRUSTED_PROXIES:-}
UPTIME_AGENT_IMAGE: ${UPTIME_IMAGE:-git.zb-server.de/zb-server/uptimesebi}
UPTIME_LOG_LEVEL: ${UPTIME_LOG_LEVEL:-info}
x-logging: &logging
driver: json-file
options:
max-size: 10m
max-file: "3"
x-hardening: &hardening
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs: [/tmp]
services:
db:
profiles: [db]
image: timescale/timescaledb:2.30.1-pg16
restart: unless-stopped
environment:
POSTGRES_USER: uptime
POSTGRES_DB: uptime
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-}
volumes:
- db:/var/lib/postgresql/data
healthcheck:
test: [CMD, pg_isready, -U, uptime, -d, uptime]
interval: 5s
timeout: 5s
retries: 30
logging: *logging
redis:
profiles: [redis]
image: redis:8-alpine
restart: unless-stopped
command: [redis-server, --requirepass, "${REDIS_PASSWORD:-}", --appendonly, "yes", --save, ""]
environment:
REDISCLI_AUTH: ${REDIS_PASSWORD:-}
volumes:
- redis:/data
healthcheck:
test: [CMD, redis-cli, ping]
interval: 5s
timeout: 5s
retries: 30
logging: *logging
# Applies the schema before the API starts, on every docker compose up.
migrate:
image: *image
command: [migrate, up]
restart: "no"
environment: *platform
depends_on:
db:
condition: service_healthy
required: false
<<: *hardening
logging: *logging
api:
image: *image
restart: unless-stopped
environment: *platform
ports:
- "${UPTIME_PORT:-8080}:8080"
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_healthy
required: false
healthcheck:
test: [CMD, /usr/local/bin/api, health]
interval: 30s
timeout: 5s
start_period: 20s
<<: *hardening
logging: *logging
# Create its token first, then set UPTIME_CHECKER_TOKEN:
# docker compose exec api api region add <key> <name>
# docker compose exec api api agent create --kind checker --region <key> --name <name>
checker:
profiles: [checker]
image: ${UPTIME_IMAGE:-git.zb-server.de/zb-server/uptimesebi}-checker:${UPTIME_TAG:-latest}
restart: unless-stopped
environment:
UPTIME_API_URL: http://api:8080
UPTIME_AGENT_TOKEN: ${UPTIME_CHECKER_TOKEN:-}
UPTIME_LOG_LEVEL: ${UPTIME_LOG_LEVEL:-info}
depends_on:
api:
condition: service_healthy
<<: *hardening
logging: *logging
# Create its token first, then set UPTIME_STATUSPAGE_TOKEN:
# docker compose exec api api agent create --kind statuspage --name <name>
statuspage:
profiles: [statuspage]
image: ${UPTIME_IMAGE:-git.zb-server.de/zb-server/uptimesebi}-statuspage:${UPTIME_TAG:-latest}
restart: unless-stopped
environment:
UPTIME_API_URL: http://api:8080
UPTIME_AGENT_TOKEN: ${UPTIME_STATUSPAGE_TOKEN:-}
UPTIME_STATUSPAGE_HOSTS: ${UPTIME_STATUSPAGE_HOSTS:-localhost}
UPTIME_TRUSTED_PROXIES: ${UPTIME_TRUSTED_PROXIES:-}
UPTIME_LOG_LEVEL: ${UPTIME_LOG_LEVEL:-info}
ports:
- "${UPTIME_STATUSPAGE_PORT:-8082}:8082"
volumes:
- statuspage:/var/lib/uptimesebi
depends_on:
api:
condition: service_healthy
<<: *hardening
logging: *logging
volumes:
db:
redis:
statuspage:
+5
View File
@@ -0,0 +1,5 @@
.DS_Store
*.swp
*.bak
*.tmp
ci/
+15
View File
@@ -0,0 +1,15 @@
apiVersion: v2
name: uptimesebi
description: Uptime monitoring with checkers in many regions and public status pages.
type: application
# The release workflow sets both versions from the release tag.
version: 0.0.0-dev
appVersion: edge
home: https://git.zb-server.de/ZB-Server/uptimesebi
sources:
- https://git.zb-server.de/ZB-Server/uptimesebi
keywords:
- monitoring
- uptime
- status-page
kubeVersion: ">=1.27.0-0"
@@ -0,0 +1,18 @@
UptimeSebi {{ include "uptimesebi.tag" . }} is being rolled out.
Console: {{ .Values.publicURL }}
{{- if not .Values.ingress.enabled }}
No ingress is enabled; try it with:
kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "uptimesebi.fullname" . }}-api {{ .Values.api.service.port }}
{{- end }}
{{- if eq .Values.signup "first-user" }}
The first account to sign up becomes the administrator.
{{- end }}
Checkers and status page servers outside the cluster: create them in the
console (Settings -> Regions) and install them with the command shown there.
{{- if or .Values.database.bundled.enabled .Values.redis.bundled.enabled }}
The bundled {{ if .Values.database.bundled.enabled }}database{{ end }}{{ if and .Values.database.bundled.enabled .Values.redis.bundled.enabled }} and {{ end }}{{ if .Values.redis.bundled.enabled }}Redis{{ end }} are meant for trying UptimeSebi out: no backups
and no high availability. Their volumes and passwords are kept on uninstall.
{{- end }}
@@ -0,0 +1,172 @@
{{/* Names and labels. */}}
{{- define "uptimesebi.name" -}}
{{- .Chart.Name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- define "uptimesebi.fullname" -}}
{{- if contains .Chart.Name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- define "uptimesebi.labels" -}}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
app.kubernetes.io/name: {{ include "uptimesebi.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/version: {{ include "uptimesebi.tag" . | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}
{{/* selector labels of one component: include with (list . "api"). */}}
{{- define "uptimesebi.selector" -}}
{{- $root := index . 0 -}}
app.kubernetes.io/name: {{ include "uptimesebi.name" $root }}
app.kubernetes.io/instance: {{ $root.Release.Name }}
app.kubernetes.io/component: {{ index . 1 }}
{{- end -}}
{{- define "uptimesebi.tag" -}}
{{- .Values.image.tag | default .Chart.AppVersion -}}
{{- end -}}
{{/* image of a component: include with (list . "" | "-checker" | "-statuspage"). */}}
{{- define "uptimesebi.image" -}}
{{- $root := index . 0 -}}
{{- printf "%s%s:%s" $root.Values.image.repository (index . 1) (include "uptimesebi.tag" $root) -}}
{{- end -}}
{{- define "uptimesebi.secretName" -}}
{{- include "uptimesebi.fullname" . }}
{{- end -}}
{{- define "uptimesebi.apiURL" -}}
{{- printf "http://%s-api:%d" (include "uptimesebi.fullname" .) (int .Values.api.service.port) -}}
{{- end -}}
{{- define "uptimesebi.publicHost" -}}
{{- .Values.ingress.host | default (urlParse (required "publicURL is required, e.g. https://uptime.example.com" .Values.publicURL)).host -}}
{{- end -}}
{{/*
secretEnv renders an env var from a value or an existing secret: include
with (list $secret "UPTIME_X" .Values.x.existingSecret .Values.x.existingSecretKey "x-key"),
where $secret is the chart's secret holding values under the last argument.
*/}}
{{- define "uptimesebi.secretEnv" -}}
- name: {{ index . 1 }}
valueFrom:
secretKeyRef:
{{- if index . 2 }}
name: {{ index . 2 }}
key: {{ index . 3 }}
{{- else }}
name: {{ index . 0 }}
key: {{ index . 4 }}
{{- end }}
{{- end -}}
{{/* secretData is what the chart's secrets hold, as YAML. */}}
{{- define "uptimesebi.secretData" -}}
{{- $data := dict -}}
{{- if and .Values.secretKeys.value (not .Values.secretKeys.existingSecret) }}{{ $_ := set $data "secret-keys" .Values.secretKeys.value }}{{ end -}}
{{- if and .Values.database.url (not .Values.database.existingSecret) (not .Values.database.bundled.enabled) }}{{ $_ := set $data "database-url" .Values.database.url }}{{ end -}}
{{- if and .Values.redis.url (not .Values.redis.existingSecret) (not .Values.redis.bundled.enabled) }}{{ $_ := set $data "redis-url" .Values.redis.url }}{{ end -}}
{{- if and .Values.redis.sentinel.password (not .Values.redis.sentinel.existingSecret) }}{{ $_ := set $data "redis-sentinel-password" .Values.redis.sentinel.password }}{{ end -}}
{{- if and .Values.smtp.url (not .Values.smtp.existingSecret) }}{{ $_ := set $data "smtp-url" .Values.smtp.url }}{{ end -}}
{{- if and .Values.checker.token (not .Values.checker.existingSecret) }}{{ $_ := set $data "checker-token" .Values.checker.token }}{{ end -}}
{{- if and .Values.statuspage.token (not .Values.statuspage.existingSecret) }}{{ $_ := set $data "statuspage-token" .Values.statuspage.token }}{{ end -}}
{{- if $data }}{{ toYaml $data }}{{ end -}}
{{- end -}}
{{/* databaseSet tells whether a database is configured. */}}
{{- define "uptimesebi.databaseSet" -}}
{{- if or .Values.database.url .Values.database.existingSecret .Values.database.bundled.enabled -}}true{{- end -}}
{{- end -}}
{{/*
Environment of the API and the migrations: include with (list . $secret),
$secret being the chart secret to read values from.
*/}}
{{- define "uptimesebi.platformEnv" -}}
{{- $secret := index . 1 -}}
{{- with index . 0 -}}
- name: UPTIME_EDITION
value: {{ .Values.edition | quote }}
- name: UPTIME_LOG_LEVEL
value: {{ .Values.logLevel | quote }}
- name: UPTIME_PUBLIC_URL
value: {{ required "publicURL is required, e.g. https://uptime.example.com" .Values.publicURL | trimSuffix "/" | quote }}
- name: UPTIME_SIGNUP
value: {{ .Values.signup | quote }}
- name: UPTIME_AGENT_IMAGE
value: {{ .Values.image.repository | quote }}
{{- with .Values.trustedProxies }}
- name: UPTIME_TRUSTED_PROXIES
value: {{ join "," . | quote }}
{{- end }}
{{- with .Values.statusPageURL }}
- name: UPTIME_STATUSPAGE_URL
value: {{ . | quote }}
{{- end }}
{{- if not (include "uptimesebi.databaseSet" .) }}
{{- fail "set database.url, database.existingSecret or database.bundled.enabled" }}
{{- end }}
{{- if .Values.database.bundled.enabled }}
- name: UPTIME_DB_PASSWORD
valueFrom:
secretKeyRef:
name: {{ include "uptimesebi.fullname" . }}-db
key: password
- name: UPTIME_DATABASE_URL
value: {{ printf "postgres://uptime:$(UPTIME_DB_PASSWORD)@%s-db:5432/uptime?sslmode=disable" (include "uptimesebi.fullname" .) | quote }}
{{- else }}
{{ include "uptimesebi.secretEnv" (list $secret "UPTIME_DATABASE_URL" .Values.database.existingSecret .Values.database.existingSecretKey "database-url") }}
{{- end }}
{{- if .Values.redis.bundled.enabled }}
- name: UPTIME_REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: {{ include "uptimesebi.fullname" . }}-redis
key: password
- name: UPTIME_REDIS_URL
value: {{ printf "redis://:$(UPTIME_REDIS_PASSWORD)@%s-redis:6379/0" (include "uptimesebi.fullname" .) | quote }}
{{- else if .Values.redis.sentinel.master }}
- name: UPTIME_REDIS_SENTINEL_MASTER
value: {{ .Values.redis.sentinel.master | quote }}
- name: UPTIME_REDIS_SENTINEL_ADDRS
value: {{ required "redis.sentinel.addrs is required with redis.sentinel.master" .Values.redis.sentinel.addrs | join "," | quote }}
{{- with .Values.redis.sentinel.username }}
- name: UPTIME_REDIS_SENTINEL_USERNAME
value: {{ . | quote }}
{{- end }}
{{- if or .Values.redis.sentinel.password .Values.redis.sentinel.existingSecret }}
{{ include "uptimesebi.secretEnv" (list $secret "UPTIME_REDIS_SENTINEL_PASSWORD" .Values.redis.sentinel.existingSecret .Values.redis.sentinel.existingSecretKey "redis-sentinel-password") }}
{{- end }}
{{- else if or .Values.redis.url .Values.redis.existingSecret }}
{{ include "uptimesebi.secretEnv" (list $secret "UPTIME_REDIS_URL" .Values.redis.existingSecret .Values.redis.existingSecretKey "redis-url") }}
{{- else }}
{{- fail "set redis.url, redis.existingSecret, redis.sentinel.master or redis.bundled.enabled" }}
{{- end }}
{{- if or .Values.secretKeys.value .Values.secretKeys.existingSecret }}
{{ include "uptimesebi.secretEnv" (list $secret "UPTIME_SECRET_KEYS" .Values.secretKeys.existingSecret .Values.secretKeys.existingSecretKey "secret-keys") }}
{{- else }}
{{- fail "set secretKeys.value or secretKeys.existingSecret, e.g. k1:$(head -c32 /dev/urandom | base64)" }}
{{- end }}
{{- if or .Values.smtp.url .Values.smtp.existingSecret }}
{{ include "uptimesebi.secretEnv" (list $secret "UPTIME_SMTP_URL" .Values.smtp.existingSecret .Values.smtp.existingSecretKey "smtp-url") }}
{{- end }}
{{- with .Values.extraEnv }}
{{ toYaml . }}
{{- end }}
{{- end -}}
{{- end -}}
{{/* Volumes every pod gets: the root filesystem is read-only. */}}
{{- define "uptimesebi.tmpVolume" -}}
- name: tmp
emptyDir:
medium: Memory
sizeLimit: 64Mi
{{- end -}}
+120
View File
@@ -0,0 +1,120 @@
{{- $secret := include "uptimesebi.secretName" . }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "uptimesebi.fullname" . }}-api
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: api
spec:
replicas: {{ .Values.api.replicas }}
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "api") | nindent 8 }}
annotations:
# Roll the pods when values in the chart's secret change.
checksum/secret: {{ include "uptimesebi.secretData" . | sha256sum }}
{{- with .Values.api.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
automountServiceAccountToken: false
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
{{- if and .Values.migrations.enabled .Values.database.bundled.enabled }}
initContainers:
# With the bundled database the migrations cannot run as a hook
# before the install; concurrent runs serialize on a lock.
- name: migrate
image: {{ include "uptimesebi.image" (list . "") }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args: [migrate, up]
env:
{{- include "uptimesebi.platformEnv" (list . $secret) | nindent 12 }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
resources:
{{- toYaml .Values.migrations.resources | nindent 12 }}
volumeMounts:
- name: tmp
mountPath: /tmp
{{- end }}
containers:
- name: api
image: {{ include "uptimesebi.image" (list . "") }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args: [serve]
env:
{{- include "uptimesebi.platformEnv" (list . $secret) | nindent 12 }}
ports:
- name: http
containerPort: 8080
startupProbe:
httpGet: {path: /healthz, port: http}
periodSeconds: 2
failureThreshold: 60
livenessProbe:
httpGet: {path: /healthz, port: http}
periodSeconds: 10
readinessProbe:
httpGet: {path: /readyz, port: http}
periodSeconds: 5
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
resources:
{{- toYaml .Values.api.resources | nindent 12 }}
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
{{- include "uptimesebi.tmpVolume" . | nindent 8 }}
{{- with .Values.api.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.api.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.api.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ include "uptimesebi.fullname" . }}-api
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: api
spec:
type: {{ .Values.api.service.type }}
selector:
{{- include "uptimesebi.selector" (list . "api") | nindent 4 }}
ports:
- name: http
port: {{ .Values.api.service.port }}
targetPort: http
{{- if and .Values.api.podDisruptionBudget.enabled (gt (int .Values.api.replicas) 1) }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include "uptimesebi.fullname" . }}-api
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
spec:
minAvailable: {{ .Values.api.podDisruptionBudget.minAvailable }}
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
{{- end }}
@@ -0,0 +1,87 @@
{{- if .Values.checker.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "uptimesebi.fullname" . }}-checker
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: checker
spec:
replicas: {{ .Values.checker.replicas }}
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "checker") | nindent 6 }}
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "checker") | nindent 8 }}
annotations:
checksum/secret: {{ include "uptimesebi.secretData" . | sha256sum }}
{{- with .Values.checker.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
automountServiceAccountToken: false
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
{{- if .Values.checker.pingSysctl }}
sysctls:
# A safe sysctl: unprivileged ICMP sockets for ping monitors.
- name: net.ipv4.ping_group_range
value: "0 2147483647"
{{- end }}
# Checks may take a while; the checker hands its queue back on SIGTERM.
terminationGracePeriodSeconds: 40
containers:
- name: checker
image: {{ include "uptimesebi.image" (list . "-checker") }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
env:
- name: UPTIME_API_URL
value: {{ .Values.checker.apiURL | default (include "uptimesebi.apiURL" .) | quote }}
{{- if not (or .Values.checker.token .Values.checker.existingSecret) }}
{{- fail "checker.enabled needs checker.token or checker.existingSecret (see values.yaml)" }}
{{- end }}
{{- include "uptimesebi.secretEnv" (list (include "uptimesebi.secretName" .) "UPTIME_AGENT_TOKEN" .Values.checker.existingSecret .Values.checker.existingSecretKey "checker-token") | nindent 12 }}
- name: UPTIME_CHECKER_CONCURRENCY
value: {{ .Values.checker.concurrency | quote }}
- name: UPTIME_LOG_LEVEL
value: {{ .Values.logLevel | quote }}
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
ports:
- name: health
containerPort: 8081
livenessProbe:
httpGet: {path: /healthz, port: health}
periodSeconds: 10
readinessProbe:
httpGet: {path: /readyz, port: health}
periodSeconds: 10
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
resources:
{{- toYaml .Values.checker.resources | nindent 12 }}
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
{{- include "uptimesebi.tmpVolume" . | nindent 8 }}
{{- with .Values.checker.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.checker.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.checker.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
@@ -0,0 +1,114 @@
{{- if .Values.database.bundled.enabled }}
{{- $name := printf "%s-db" (include "uptimesebi.fullname" .) }}
{{- $existing := lookup "v1" "Secret" .Release.Namespace $name }}
{{- $password := .Values.database.bundled.password }}
{{- if and (not $password) $existing }}{{ $password = index $existing.data "password" | b64dec }}{{ end }}
{{- if not $password }}{{ $password = randAlphaNum 32 }}{{ end }}
apiVersion: v1
kind: Secret
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: db
annotations:
# Uninstalling keeps the password, which the kept volume still needs.
helm.sh/resource-policy: keep
type: Opaque
stringData:
password: {{ $password | quote }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: db
spec:
clusterIP: None
selector:
{{- include "uptimesebi.selector" (list . "db") | nindent 4 }}
ports:
- name: postgres
port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: db
spec:
serviceName: {{ $name }}
replicas: 1
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "db") | nindent 6 }}
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "db") | nindent 8 }}
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 70
runAsGroup: 70
fsGroup: 70
seccompProfile:
type: RuntimeDefault
containers:
- name: timescaledb
image: {{ printf "%s:%s" .Values.database.bundled.image.repository .Values.database.bundled.image.tag }}
env:
- name: POSTGRES_USER
value: uptime
- name: POSTGRES_DB
value: uptime
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: {{ $name }}
key: password
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- name: postgres
containerPort: 5432
readinessProbe:
exec:
command: [pg_isready, -U, uptime, -d, uptime]
periodSeconds: 5
livenessProbe:
exec:
command: [pg_isready, -U, uptime, -d, uptime]
periodSeconds: 20
failureThreshold: 6
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
resources:
{{- toYaml .Values.database.bundled.resources | nindent 12 }}
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
- name: run
mountPath: /var/run/postgresql
volumes:
- name: run
emptyDir: {}
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ReadWriteOnce]
{{- with .Values.database.bundled.persistence.storageClass }}
storageClassName: {{ . }}
{{- end }}
resources:
requests:
storage: {{ .Values.database.bundled.persistence.size }}
{{- end }}
@@ -0,0 +1,32 @@
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "uptimesebi.fullname" . }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
{{- if .Values.ingress.tls.enabled }}
tls:
- hosts: [{{ include "uptimesebi.publicHost" . | quote }}]
secretName: {{ .Values.ingress.tls.secretName | default (printf "%s-tls" (include "uptimesebi.fullname" .)) }}
{{- end }}
rules:
- host: {{ include "uptimesebi.publicHost" . | quote }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: {{ include "uptimesebi.fullname" . }}-api
port:
name: http
{{- end }}
@@ -0,0 +1,72 @@
{{- if and .Values.migrations.enabled (not .Values.database.bundled.enabled) }}
{{- $secret := printf "%s-migrate" (include "uptimesebi.fullname" .) }}
{{- with include "uptimesebi.secretData" . }}
# The hook runs before the release's resources exist, so it brings its own
# copy of the secrets and removes it afterwards.
apiVersion: v1
kind: Secret
metadata:
name: {{ $secret }}
labels:
{{- include "uptimesebi.labels" $ | nindent 4 }}
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "-10"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
type: Opaque
stringData:
{{- . | nindent 2 }}
---
{{- end }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "uptimesebi.fullname" . }}-migrate
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: migrate
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "0"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
backoffLimit: {{ .Values.migrations.backoffLimit }}
activeDeadlineSeconds: 900
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "migrate") | nindent 8 }}
spec:
restartPolicy: Never
automountServiceAccountToken: false
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: migrate
image: {{ include "uptimesebi.image" (list . "") }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args: [migrate, up]
env:
{{- include "uptimesebi.platformEnv" (list . $secret) | nindent 12 }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
resources:
{{- toYaml .Values.migrations.resources | nindent 12 }}
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
{{- include "uptimesebi.tmpVolume" . | nindent 8 }}
{{- with .Values.api.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.api.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
+122
View File
@@ -0,0 +1,122 @@
{{- if .Values.redis.bundled.enabled }}
{{- $name := printf "%s-redis" (include "uptimesebi.fullname" .) }}
{{- $existing := lookup "v1" "Secret" .Release.Namespace $name }}
{{- $password := .Values.redis.bundled.password }}
{{- if and (not $password) $existing }}{{ $password = index $existing.data "password" | b64dec }}{{ end }}
{{- if not $password }}{{ $password = randAlphaNum 32 }}{{ end }}
apiVersion: v1
kind: Secret
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: redis
annotations:
# Uninstalling keeps the password along with the kept volume.
helm.sh/resource-policy: keep
type: Opaque
stringData:
password: {{ $password | quote }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: redis
spec:
selector:
{{- include "uptimesebi.selector" (list . "redis") | nindent 4 }}
ports:
- name: redis
port: 6379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: redis
spec:
serviceName: {{ $name }}
replicas: 1
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "redis") | nindent 6 }}
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "redis") | nindent 8 }}
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 999
runAsGroup: 999
fsGroup: 999
seccompProfile:
type: RuntimeDefault
containers:
- name: redis
image: {{ printf "%s:%s" .Values.redis.bundled.image.repository .Values.redis.bundled.image.tag }}
command: [redis-server]
args:
- --requirepass
- $(REDIS_PASSWORD)
- --appendonly
- {{ ternary "yes" "no" .Values.redis.bundled.persistence.enabled | quote }}
- --save
- ""
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: {{ $name }}
key: password
- name: REDISCLI_AUTH
valueFrom:
secretKeyRef:
name: {{ $name }}
key: password
ports:
- name: redis
containerPort: 6379
readinessProbe:
exec:
command: [redis-cli, ping]
periodSeconds: 5
livenessProbe:
tcpSocket:
port: redis
periodSeconds: 20
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: [ALL]
resources:
{{- toYaml .Values.redis.bundled.resources | nindent 12 }}
volumeMounts:
- name: data
mountPath: /data
{{- if not .Values.redis.bundled.persistence.enabled }}
volumes:
- name: data
emptyDir: {}
{{- end }}
{{- if .Values.redis.bundled.persistence.enabled }}
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ReadWriteOnce]
{{- with .Values.redis.bundled.persistence.storageClass }}
storageClassName: {{ . }}
{{- end }}
resources:
requests:
storage: {{ .Values.redis.bundled.persistence.size }}
{{- end }}
{{- end }}
@@ -0,0 +1,11 @@
{{- with include "uptimesebi.secretData" . }}
apiVersion: v1
kind: Secret
metadata:
name: {{ include "uptimesebi.secretName" $ }}
labels:
{{- include "uptimesebi.labels" $ | nindent 4 }}
type: Opaque
stringData:
{{- . | nindent 2 }}
{{- end }}
@@ -0,0 +1,156 @@
{{- if .Values.statuspage.enabled }}
{{- $name := printf "%s-statuspage" (include "uptimesebi.fullname" .) }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: statuspage
spec:
replicas: {{ .Values.statuspage.replicas }}
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
template:
metadata:
labels:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 8 }}
annotations:
checksum/secret: {{ include "uptimesebi.secretData" . | sha256sum }}
{{- with .Values.statuspage.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
automountServiceAccountToken: false
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: statuspage
image: {{ include "uptimesebi.image" (list . "-statuspage") }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
env:
- name: UPTIME_API_URL
value: {{ .Values.statuspage.apiURL | default (include "uptimesebi.apiURL" .) | quote }}
{{- if not (or .Values.statuspage.token .Values.statuspage.existingSecret) }}
{{- fail "statuspage.enabled needs statuspage.token or statuspage.existingSecret (see values.yaml)" }}
{{- end }}
{{- include "uptimesebi.secretEnv" (list (include "uptimesebi.secretName" .) "UPTIME_AGENT_TOKEN" .Values.statuspage.existingSecret .Values.statuspage.existingSecretKey "statuspage-token") | nindent 12 }}
- name: UPTIME_STATUSPAGE_HOSTS
value: {{ required "statuspage.hosts needs at least one host name" .Values.statuspage.hosts | join "," | quote }}
- name: UPTIME_STATUSPAGE_CACHE_DIR
value: /var/lib/uptimesebi
- name: UPTIME_TRUSTED_PROXIES
value: {{ join "," .Values.trustedProxies | quote }}
- name: UPTIME_LOG_LEVEL
value: {{ .Values.logLevel | quote }}
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
ports:
- name: http
containerPort: 8082
livenessProbe:
httpGet: {path: /healthz, port: http}
periodSeconds: 10
readinessProbe:
httpGet: {path: /readyz, port: http}
periodSeconds: 5
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
resources:
{{- toYaml .Values.statuspage.resources | nindent 12 }}
volumeMounts:
- name: tmp
mountPath: /tmp
# Snapshots keep pages up while the API is away; rebuilt on start.
- name: cache
mountPath: /var/lib/uptimesebi
volumes:
{{- include "uptimesebi.tmpVolume" . | nindent 8 }}
- name: cache
emptyDir:
sizeLimit: 256Mi
{{- with .Values.statuspage.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.statuspage.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.statuspage.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: statuspage
spec:
type: {{ .Values.statuspage.service.type }}
selector:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 4 }}
ports:
- name: http
port: {{ .Values.statuspage.service.port }}
targetPort: http
{{- if and .Values.statuspage.podDisruptionBudget.enabled (gt (int .Values.statuspage.replicas) 1) }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
spec:
minAvailable: {{ .Values.statuspage.podDisruptionBudget.minAvailable }}
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
{{- end }}
{{- if .Values.statuspage.ingress.enabled }}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.statuspage.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.statuspage.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
{{- if .Values.statuspage.ingress.tls.enabled }}
tls:
- hosts:
{{- toYaml .Values.statuspage.hosts | nindent 8 }}
secretName: {{ .Values.statuspage.ingress.tls.secretName | default (printf "%s-tls" $name) }}
{{- end }}
rules:
{{- range .Values.statuspage.hosts }}
- host: {{ . | quote }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: {{ $name }}
port:
name: http
{{- end }}
{{- end }}
{{- end }}
+227
View File
@@ -0,0 +1,227 @@
# Default values for UptimeSebi. Only publicURL, the database, Redis and
# secretKeys have to be set; everything else has working defaults.
image:
# The API image; checkers and status page servers use <repository>-checker
# and <repository>-statuspage with the same tag.
repository: git.zb-server.de/zb-server/uptimesebi
# Defaults to the chart's appVersion.
tag: ""
pullPolicy: IfNotPresent
imagePullSecrets: []
# -- Platform --
# Address users reach the console at, e.g. https://uptime.example.com.
# Used for links in mails, SSO callbacks and the agent install script.
publicURL: ""
# selfhosted or cloud.
edition: selfhosted
logLevel: info
# Who may sign up: first-user, open or closed.
signup: first-user
# Reverse proxies whose X-Forwarded-For is believed, e.g. the pod network of
# the ingress controller. Client addresses feed rate limits and the audit
# log; without this they are the ingress controller's.
trustedProxies: []
# Where the platform's status page servers are reachable.
statusPageURL: ""
# Further environment variables for every component, e.g. UPTIME_RETENTION_*.
extraEnv: []
# - name: UPTIME_RETENTION_RAW
# value: 720h
# Encrypts stored secrets (UPTIME_SECRET_KEYS): "k1:<32 random bytes, base64>",
# e.g. echo "k1:$(head -c32 /dev/urandom | base64)". Keep it safe; rotate by
# prepending a new key. Or name a secret that holds it.
secretKeys:
value: ""
existingSecret: ""
existingSecretKey: secret-keys
# Outgoing mail, e.g. smtp://user:pass@host:587?from=alerts@example.com.
smtp:
url: ""
existingSecret: ""
existingSecretKey: smtp-url
# -- PostgreSQL with TimescaleDB --
database:
# postgres://user:password@host:5432/uptime?sslmode=require. The user needs
# to create the timescaledb and citext extensions on the first migration.
url: ""
existingSecret: ""
existingSecretKey: database-url
# A single TimescaleDB in the cluster, for trying UptimeSebi out. Without
# backups or high availability: for production use your own database.
bundled:
enabled: false
image:
repository: timescale/timescaledb
tag: 2.30.1-pg16
# Generated on install if empty, then kept.
password: ""
persistence:
size: 10Gi
storageClass: ""
resources: {}
# -- Redis --
# Point to your own Redis, directly or through Sentinel, or bundle one.
redis:
# redis://:password@host:6379/0 or rediss:// for TLS.
url: ""
existingSecret: ""
existingSecretKey: redis-url
sentinel:
master: ""
addrs: []
username: ""
password: ""
existingSecret: ""
existingSecretKey: redis-sentinel-password
# A single Redis in the cluster, for trying UptimeSebi out. Without high
# availability: for production use your own Redis.
bundled:
enabled: false
image:
repository: redis
tag: 8-alpine
# Generated on install if empty, then kept; letters and digits only,
# it goes into a URL.
password: ""
# Sessions, schedules and rate limits survive restarts on a volume;
# without one a restart signs everyone out.
persistence:
enabled: true
size: 1Gi
storageClass: ""
resources: {}
# -- Migrations --
migrations:
# Run "api migrate up" as a hook before every install and upgrade. With
# the bundled database, which does not exist before the install, they run
# as an init container of the API instead.
enabled: true
backoffLimit: 3
resources: {}
# -- Console and API --
api:
replicas: 2
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 512Mi
podDisruptionBudget:
enabled: true
minAvailable: 1
service:
type: ClusterIP
port: 8080
# The API image is built for amd64 only; checkers and status page servers
# run on arm64 and 32-bit ARM too. Also used by the migration job.
nodeSelector:
kubernetes.io/arch: amd64
tolerations: []
affinity: {}
podAnnotations: {}
ingress:
enabled: false
className: ""
annotations: {}
# Defaults to the host of publicURL.
host: ""
tls:
enabled: false
# Secret with the certificate, e.g. made by cert-manager.
secretName: ""
# -- Checker --
# A checker in the cluster, for checks from the cluster's region. Create
# its region and token first:
# kubectl exec deploy/<release>-uptimesebi-api -- api region add <key> <name>
# kubectl exec deploy/<release>-uptimesebi-api -- api agent create --kind checker --region <key> --name <name>
checker:
enabled: false
replicas: 1
token: ""
existingSecret: ""
existingSecretKey: checker-token
# Defaults to the API service inside the cluster.
apiURL: ""
concurrency: 64
# Lets the checker send pings without privileges.
pingSysctl: true
resources:
requests:
cpu: 50m
memory: 64Mi
limits:
memory: 512Mi
nodeSelector: {}
tolerations: []
affinity: {}
podAnnotations: {}
# -- Status page server --
# Serves public status pages. Create its token first:
# kubectl exec deploy/<release>-uptimesebi-api -- api agent create --kind statuspage --name <name>
statuspage:
enabled: false
replicas: 2
token: ""
existingSecret: ""
existingSecretKey: statuspage-token
# Defaults to the API service inside the cluster.
apiURL: ""
# Host names serving pages by slug, e.g. status.example.com.
hosts: []
service:
type: ClusterIP
port: 80
ingress:
enabled: false
className: ""
annotations: {}
tls:
enabled: false
secretName: ""
resources:
requests:
cpu: 50m
memory: 64Mi
limits:
memory: 256Mi
podDisruptionBudget:
enabled: true
minAvailable: 1
nodeSelector: {}
tolerations: []
affinity: {}
podAnnotations: {}
# Pod and container security for all components; the images run as user
# 65532 without a shell.
podSecurityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
fsGroup: 65532
seccompProfile:
type: RuntimeDefault
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: [ALL]
+11 -3
View File
@@ -1,6 +1,6 @@
module git.zb-server.de/ZB-Server/uptimesebi module git.zb-server.de/ZB-Server/uptimesebi
go 1.27.1 go 1.27.4
require ( require (
github.com/a-h/templ v0.3.1118 github.com/a-h/templ v0.3.1118
@@ -10,9 +10,10 @@ require (
github.com/coreos/go-oidc/v3 v3.21.0 github.com/coreos/go-oidc/v3 v3.21.0
github.com/eclipse/paho.mqtt.golang v1.5.1 github.com/eclipse/paho.mqtt.golang v1.5.1
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/go-jose/go-jose/v4 v4.1.4 github.com/go-jose/go-jose/v4 v4.1.9
github.com/go-playground/validator/v10 v10.30.6 github.com/go-playground/validator/v10 v10.30.6
github.com/go-sql-driver/mysql v1.10.2 github.com/go-sql-driver/mysql v1.10.2
github.com/google/go-containerregistry v0.22.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gosnmp/gosnmp v1.47.0 github.com/gosnmp/gosnmp v1.47.0
github.com/jackc/pgx/v5 v5.13.0 github.com/jackc/pgx/v5 v5.13.0
@@ -26,10 +27,11 @@ require (
github.com/redis/go-redis/v9 v9.23.0 github.com/redis/go-redis/v9 v9.23.0
github.com/twmb/franz-go v1.22.3 github.com/twmb/franz-go v1.22.3
github.com/twmb/franz-go/pkg/kmsg v1.15.1 github.com/twmb/franz-go/pkg/kmsg v1.15.1
github.com/yuin/goldmark v1.7.13 github.com/yuin/goldmark v1.8.7
go.mongodb.org/mongo-driver/v2 v2.5.0 go.mongodb.org/mongo-driver/v2 v2.5.0
go.uber.org/zap v1.28.0 go.uber.org/zap v1.28.0
golang.org/x/crypto v0.59.0 golang.org/x/crypto v0.59.0
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259
golang.org/x/net v0.63.0 golang.org/x/net v0.63.0
golang.org/x/oauth2 v0.38.0 golang.org/x/oauth2 v0.38.0
golang.org/x/text v0.44.0 golang.org/x/text v0.44.0
@@ -56,6 +58,8 @@ require (
github.com/cloudwego/base64x v0.1.6 // indirect github.com/cloudwego/base64x v0.1.6 // indirect
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/docker/cli v29.7.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.3 // indirect
github.com/fatih/color v1.19.0 // indirect github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect
@@ -85,6 +89,8 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/natefinch/atomic v1.0.1 // indirect github.com/natefinch/atomic v1.0.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pierrec/lz4/v4 v4.1.33 // indirect github.com/pierrec/lz4/v4 v4.1.33 // indirect
github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect
@@ -93,6 +99,7 @@ require (
github.com/rs/xid v1.4.0 // indirect github.com/rs/xid v1.4.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/shopspring/decimal v1.6.0 // indirect github.com/shopspring/decimal v1.6.0 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect
@@ -115,6 +122,7 @@ require (
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
google.golang.org/protobuf v1.36.12 // indirect google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools/v3 v3.5.2 // indirect
) )
tool github.com/a-h/templ/cmd/templ tool github.com/a-h/templ/cmd/templ
+20 -4
View File
@@ -90,6 +90,10 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeC
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= 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/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/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
github.com/docker/cli v29.7.2+incompatible h1:dlkwallR8XqfeVnA2ELEhdwvb4lsSwuB4IgsG8Q9cLY=
github.com/docker/cli v29.7.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8=
github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= 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/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/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw=
@@ -107,8 +111,8 @@ github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-jose/go-jose/v4 v4.1.9/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
@@ -144,6 +148,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 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 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-containerregistry v0.22.1 h1:RZuuSYhTvlDvtsK+NkutoCZ//C0X2ebLK8X8l3ULs84=
github.com/google/go-containerregistry v0.22.1/go.mod h1:bJR35SK8XgisYmhg/FMQ/5RK0S/XrOAqLBV5/LR2XE0=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 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 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -227,6 +233,10 @@ github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 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.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= 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/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 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014=
@@ -258,6 +268,8 @@ github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJ
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= 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 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4=
github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 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.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.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -298,8 +310,8 @@ github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3i
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= 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/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.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
@@ -333,6 +345,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= 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 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259 h1:wXcJiWf6AuFE+YJzfySrqJW1+yko6kcV2W+fg4n6WGk=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 h1:qr+tk4P56rtbVVAJDyAr5LAOiaD/XhZCoRTr4SfLxAk= 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/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.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -426,6 +440,8 @@ 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.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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
layeh.com/radius v0.0.0-20231213012653-1006025d24f8 h1:orYXpi6BJZdvgytfHH4ybOe4wHnLbbS71Cmd8mWdZjs= 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= 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 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
+18
View File
@@ -180,6 +180,24 @@ func (c *Client) Report(ctx context.Context, results []Result) error {
return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil) return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil)
} }
// Update tells a self-updating agent which release to run.
type Update struct {
// Version is the platform's release; agents follow it.
Version string `json:"version"`
// Image is the agent image of that release, e.g.
// git.example.com/owner/uptimesebi-checker:1.4.2. Empty when the
// platform runs an unreleased build, which agents do not follow.
Image string `json:"image,omitempty"`
}
// Update asks which release the agent should run. It does not count as a
// sign of life of an instance.
func (c *Client) Update(ctx context.Context) (Update, error) {
var u Update
err := c.do(ctx, http.MethodGet, "/update", nil, &u)
return u, err
}
// Release hands this instance's queued jobs back for other instances and // Release hands this instance's queued jobs back for other instances and
// deregisters it. Call it during graceful shutdown. // deregisters it. Call it during graceful shutdown.
func (c *Client) Release(ctx context.Context) error { func (c *Client) Release(ctx context.Context) error {
+36
View File
@@ -88,6 +88,26 @@ type PageIncident struct {
Component string `json:"component"` Component string `json:"component"`
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"` ResolvedAt *time.Time `json:"resolved_at,omitempty"`
// Title names the incident; empty shows the component.
Title string `json:"title,omitempty"`
// Status is investigating, identified, monitoring or resolved, or
// custom with StatusName and StatusColor; empty while nobody said
// anything.
Status string `json:"status,omitempty"`
StatusName string `json:"status_name,omitempty"`
StatusColor string `json:"status_color,omitempty"`
// Updates are the public updates, newest first.
Updates []PageIncidentUpdate `json:"updates,omitempty"`
}
// PageIncidentUpdate is what the organization told about an incident.
type PageIncidentUpdate struct {
Status string `json:"status"`
StatusName string `json:"status_name,omitempty"`
StatusColor string `json:"status_color,omitempty"`
// Message is Markdown.
Message string `json:"message"`
At time.Time `json:"at"`
} }
// PageSnapshot is everything needed to render a status page. // PageSnapshot is everything needed to render a status page.
@@ -255,6 +275,22 @@ func (s PageSnapshot) IncidentsForComponent(componentName string) []PageIncident
return out return out
} }
// OpenIncidentStatus returns the newest unresolved incident of
// componentName the organization gave a status, if any.
func (s PageSnapshot) OpenIncidentStatus(componentName string) (PageIncident, bool) {
var found PageIncident
ok := false
for _, inc := range s.Incidents {
if inc.Component != componentName || inc.ResolvedAt != nil || inc.Status == "" {
continue
}
if !ok || inc.StartedAt.After(found.StartedAt) {
found, ok = inc, true
}
}
return found, ok
}
// MaintenanceForComponent splits planned maintenance affecting componentName // MaintenanceForComponent splits planned maintenance affecting componentName
// into ongoing and upcoming occurrences at now. // into ongoing and upcoming occurrences at now.
func (s PageSnapshot) MaintenanceForComponent(componentName string, now time.Time) (ongoing, upcoming []PageMaintenance) { func (s PageSnapshot) MaintenanceForComponent(componentName string, now time.Time) (ongoing, upcoming []PageMaintenance) {
+292
View File
@@ -0,0 +1,292 @@
// Package agentimage builds, signs and reads the images of the agents
// (checker and status page server): one layer on an empty base per
// platform, combined into an OCI index, built from cross-compiled binaries
// without Docker. The autoupdate variant adds a layer with the launcher.
package agentimage
import (
"archive/tar"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/empty"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/tarball"
"github.com/google/go-containerregistry/pkg/v1/types"
)
// Platform is a Linux target and the directory its binaries are built in.
type Platform struct {
Dir string
v1.Platform
}
// Platforms are the targets: x86 servers, 64-bit ARM (Raspberry Pi 3/4/5
// on a 64-bit OS, ARM servers), 32-bit Raspberry Pi OS and the Raspberry
// Pi Zero and 1.
var Platforms = []Platform{
{"linux_amd64", v1.Platform{OS: "linux", Architecture: "amd64"}},
{"linux_arm64", v1.Platform{OS: "linux", Architecture: "arm64"}},
{"linux_arm_v7", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v7"}},
{"linux_arm_v6", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"}},
}
// Nonroot is the user the agents run as, the same ID as distroless'
// nonroot so volumes carry over.
const Nonroot = 65532
// DataDir holds the status page cache and the launcher's releases.
const DataDir = "/var/lib/uptimesebi"
// BinDir is where the binaries are in the image.
const BinDir = "/usr/local/bin"
// Options describe the images of one agent.
type Options struct {
// Name is the binary: checker or statuspage.
Name string
// Dist holds one directory per platform (Platform.Dir) with the
// binaries.
Dist string
Version, Commit, Source string
Env, Ports []string
Created time.Time
// Launcher adds the launcher layer for the autoupdate variant.
Launcher bool
}
// Build assembles the index of all platforms.
func Build(o Options) (v1.ImageIndex, error) {
idx := mutate.IndexMediaType(empty.Index, types.OCIImageIndex)
for _, p := range Platforms {
img, err := image(o, p)
if err != nil {
return nil, err
}
pl := p.Platform
idx = mutate.AppendManifests(idx, mutate.IndexAddendum{Add: img, Descriptor: v1.Descriptor{Platform: &pl}})
}
return idx, nil
}
func image(o Options, p Platform) (v1.Image, error) {
agent, err := os.ReadFile(filepath.Join(o.Dist, p.Dir, o.Name))
if err != nil {
return nil, fmt.Errorf("agentimage: %w", err)
}
rootLayer, err := rootfs(o.Name, agent, o.Created)
if err != nil {
return nil, err
}
img, err := appendLayer(emptyImage(), rootLayer, v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi agentimage", Comment: o.Name + " " + o.Version})
if err != nil {
return nil, err
}
if o.Launcher {
launcher, err := os.ReadFile(filepath.Join(o.Dist, p.Dir, "launcher"))
if err != nil {
return nil, fmt.Errorf("agentimage: %w", err)
}
raw, err := launcherLayer(launcher, o.Created)
if err != nil {
return nil, err
}
if img, err = appendLayer(img, raw, v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi agentimage", Comment: "launcher " + o.Version}); err != nil {
return nil, err
}
}
cf, err := img.ConfigFile()
if err != nil {
return nil, err
}
cf = cf.DeepCopy()
cf.OS, cf.Architecture, cf.Variant = p.OS, p.Architecture, p.Variant
cf.Created = v1.Time{Time: o.Created}
agentPath := BinDir + "/" + o.Name
entry := []string{agentPath}
env := append([]string{"HOME=" + DataDir}, o.Env...)
if o.Launcher {
entry = []string{BinDir + "/launcher"}
env = append(env, "UPTIME_LAUNCHER_AGENT="+o.Name)
}
cf.Config = v1.Config{
Entrypoint: entry,
User: fmt.Sprintf("%d:%d", Nonroot, Nonroot),
WorkingDir: DataDir,
Env: env,
Volumes: map[string]struct{}{DataDir: {}},
Healthcheck: &v1.HealthConfig{
Test: []string{"CMD", agentPath, "health"},
Interval: 30 * time.Second, Timeout: 5 * time.Second, StartPeriod: 20 * time.Second, Retries: 3,
},
Labels: labels(o),
}
if len(o.Ports) > 0 {
cf.Config.ExposedPorts = map[string]struct{}{}
for _, port := range o.Ports {
cf.Config.ExposedPorts[port] = struct{}{}
}
}
return mutate.ConfigFile(img, cf)
}
func labels(o Options) map[string]string {
l := map[string]string{
"org.opencontainers.image.title": "uptimesebi-" + o.Name,
"org.opencontainers.image.version": o.Version,
"org.opencontainers.image.licenses": "AGPL-3.0-only",
}
if o.Commit != "" {
l["org.opencontainers.image.revision"] = o.Commit
}
if o.Source != "" {
l["org.opencontainers.image.source"] = o.Source
}
return l
}
type tarEntry struct {
path string
mode int64
uid int
data []byte
dir bool
}
func writeTar(entries []tarEntry, mtime time.Time) ([]byte, error) {
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
for _, e := range entries {
h := &tar.Header{Name: e.path, Mode: e.mode, Uid: e.uid, Gid: e.uid, ModTime: mtime, Format: tar.FormatPAX}
if e.dir {
h.Typeflag, h.Name = tar.TypeDir, e.path+"/"
} else {
h.Typeflag, h.Size = tar.TypeReg, int64(len(e.data))
}
if err := tw.WriteHeader(h); err != nil {
return nil, err
}
if _, err := tw.Write(e.data); err != nil {
return nil, err
}
}
if err := tw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// rootfs is the agent layer: the binary, a data directory owned by the
// agent's user and a temporary directory.
func rootfs(binName string, bin []byte, mtime time.Time) ([]byte, error) {
bindir := strings.TrimPrefix(BinDir, "/")
return writeTar([]tarEntry{
{path: "tmp", mode: 0o1777, dir: true},
{path: "usr", mode: 0o755, dir: true}, {path: "usr/local", mode: 0o755, dir: true}, {path: bindir, mode: 0o755, dir: true},
{path: "var", mode: 0o755, dir: true}, {path: "var/lib", mode: 0o755, dir: true},
{path: strings.TrimPrefix(DataDir, "/"), mode: 0o700, uid: Nonroot, dir: true},
{path: bindir + "/" + binName, mode: 0o755, data: bin},
}, mtime)
}
func launcherLayer(bin []byte, mtime time.Time) ([]byte, error) {
return writeTar([]tarEntry{{path: strings.TrimPrefix(BinDir, "/") + "/launcher", mode: 0o755, data: bin}}, mtime)
}
var releaseTag = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-beta\.\d+)?$`)
// ChannelTags are the tags an image gets: edge and its build version from
// main, beta from prereleases, latest, stable, X.Y and X.Y.Z from releases.
// Other refs (pull requests, branches) publish nothing. A variant suffix
// is appended to every tag.
//
// The first tag is the image of exactly this version, the one the
// platform names to self-updating agents.
func ChannelTags(ref, version, suffix string) []string {
var tags []string
switch {
case ref == "refs/heads/main":
tags = []string{strings.TrimPrefix(version, "v"), "edge"}
case strings.HasPrefix(ref, "refs/tags/"):
m := releaseTag.FindStringSubmatch(strings.TrimPrefix(ref, "refs/tags/"))
switch {
case m == nil:
return nil
case m[4] != "":
tags = []string{strings.TrimPrefix(m[0], "v"), "beta"}
default:
tags = []string{strings.TrimPrefix(m[0], "v"), m[1] + "." + m[2], "stable", "latest"}
}
default:
return nil
}
if suffix != "" {
for i := range tags {
tags[i] += "-" + suffix
}
}
return tags
}
// Credentials log in to the registry; empty means anonymous.
type Credentials struct{ User, Password string }
func remoteOptions(ctx context.Context, login Credentials) []remote.Option {
opts := []remote.Option{remote.WithContext(ctx)}
if login.User != "" {
opts = append(opts, remote.WithAuth(&authn.Basic{Username: login.User, Password: login.Password}))
}
return opts
}
// Publish pushes the index under its first tag and adds the others.
func Publish(ctx context.Context, idx v1.ImageIndex, repo string, tags []string, login Credentials, nameOpts ...name.Option) error {
opts := remoteOptions(ctx, login)
for i, t := range tags {
tag, err := name.NewTag(repo+":"+t, nameOpts...)
if err != nil {
return err
}
if i == 0 {
err = remote.WriteIndex(tag, idx, opts...)
} else {
err = remote.Tag(tag, idx, opts...)
}
if err != nil {
return fmt.Errorf("agentimage: push %s: %w", tag, err)
}
}
return nil
}
var timeZero = time.Unix(0, 0).UTC()
func emptyImage() v1.Image {
img := mutate.MediaType(empty.Image, types.OCIManifestSchema1)
return mutate.ConfigMediaType(img, types.OCIConfigJSON)
}
func appendLayer(img v1.Image, raw []byte, history v1.History) (v1.Image, error) {
layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(raw)), nil
}, tarball.WithMediaType(types.OCILayer))
if err != nil {
return nil, err
}
return mutate.Append(img, mutate.Addendum{Layer: layer, History: history, MediaType: types.OCILayer})
}
func singleLayer(raw []byte) (v1.Image, error) {
return appendLayer(emptyImage(), raw, v1.History{Created: v1.Time{Time: timeZero}})
}
+198
View File
@@ -0,0 +1,198 @@
package agentimage
import (
"context"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/registry"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
func fakeDist(t *testing.T, version string, bins ...string) string {
t.Helper()
dist := t.TempDir()
for _, p := range Platforms {
if err := os.MkdirAll(filepath.Join(dist, p.Dir), 0o755); err != nil {
t.Fatal(err)
}
for _, b := range bins {
if err := os.WriteFile(filepath.Join(dist, p.Dir, b), []byte(b+" "+version+" for "+p.Dir), 0o755); err != nil {
t.Fatal(err)
}
}
}
return dist
}
func TestBuild(t *testing.T) {
o := Options{
Name: "statuspage", Dist: fakeDist(t, "v1.2.3", "statuspage", "launcher"), Version: "v1.2.3", Commit: "abc123",
Env: []string{"UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi"}, Ports: []string{"8082/tcp"},
Created: time.Unix(1700000000, 0).UTC(),
}
for _, launcher := range []bool{false, true} {
o.Launcher = launcher
idx, err := Build(o)
if err != nil {
t.Fatal(err)
}
m, err := idx.IndexManifest()
if err != nil {
t.Fatal(err)
}
if len(m.Manifests) != len(Platforms) {
t.Fatalf("index has %d manifests", len(m.Manifests))
}
for i, desc := range m.Manifests {
want := Platforms[i]
if desc.Platform == nil || !desc.Platform.Equals(want.Platform) {
t.Errorf("manifest %d platform = %v, want %v", i, desc.Platform, want.Platform)
}
img, err := idx.Image(desc.Digest)
if err != nil {
t.Fatal(err)
}
cf, err := img.ConfigFile()
if err != nil {
t.Fatal(err)
}
entry := []string{"/usr/local/bin/statuspage"}
if launcher {
entry = []string{"/usr/local/bin/launcher"}
}
if cf.Architecture != want.Architecture || cf.Variant != want.Variant || cf.Config.User != "65532:65532" ||
!slices.Equal(cf.Config.Entrypoint, entry) ||
!slices.Equal(cf.Config.Healthcheck.Test, []string{"CMD", "/usr/local/bin/statuspage", "health"}) ||
!slices.Contains(cf.Config.Env, "UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi") ||
slices.Contains(cf.Config.Env, "UPTIME_LAUNCHER_AGENT=statuspage") != launcher ||
cf.Config.Labels["org.opencontainers.image.version"] != "v1.2.3" {
t.Errorf("%s launcher=%v config = %+v", want.Dir, launcher, cf.Config)
}
bin, err := ReadFile(img, "usr/local/bin/statuspage", 1<<20)
if err != nil || string(bin) != "statuspage v1.2.3 for "+want.Dir {
t.Errorf("%s binary = %q, %v", want.Dir, bin, err)
}
_, err = ReadFile(img, "usr/local/bin/launcher", 1<<20)
if (err == nil) != launcher {
t.Errorf("launcher=%v but launcher file err = %v", launcher, err)
}
}
}
// The same input gives the same image.
o.Launcher = false
a, _ := Build(o)
b, _ := Build(o)
d1, _ := a.Digest()
d2, _ := b.Digest()
if d1 != d2 {
t.Errorf("rebuild changed the digest: %s, %s", d1, d2)
}
o.Dist = t.TempDir()
if _, err := Build(o); err == nil {
t.Error("built without binaries")
}
}
func TestChannelTags(t *testing.T) {
for _, c := range []struct {
ref, suffix string
want []string
}{
{"refs/heads/main", "", []string{"20261123180000-0123456789ab", "edge"}},
{"refs/tags/v1.4.2", "", []string{"1.4.2", "1.4", "stable", "latest"}},
{"refs/tags/v1.5.0-beta.3", "", []string{"1.5.0-beta.3", "beta"}},
{"refs/tags/v1.4.2", "autoupdate", []string{"1.4.2-autoupdate", "1.4-autoupdate", "stable-autoupdate", "latest-autoupdate"}},
{"refs/tags/nightly", "", nil},
{"refs/pull/7/merge", "", nil},
{"refs/heads/feature", "", nil},
} {
if got := ChannelTags(c.ref, "20261123180000-0123456789ab", c.suffix); !slices.Equal(got, c.want) {
t.Errorf("%s %s: tags = %v, want %v", c.ref, c.suffix, got, c.want)
}
}
}
// publishSigned builds and pushes a checker release to the registry.
func publishSigned(t *testing.T, host, version string, key signing.PrivateKey) v1.Hash {
t.Helper()
repo := host + "/zb/uptimesebi-checker"
idx, err := Build(Options{Name: "checker", Dist: fakeDist(t, version, "checker"), Version: version})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
tags := ChannelTags("refs/tags/"+version, version, "")
if err := Publish(ctx, idx, repo, tags, Credentials{}); err != nil {
t.Fatal(err)
}
if err := Sign(ctx, idx, repo, "checker", version, key, Credentials{}); err != nil {
t.Fatal(err)
}
d, _ := idx.Digest()
return d
}
func TestSignFetch(t *testing.T) {
reg := httptest.NewServer(registry.New())
defer reg.Close()
host := strings.TrimPrefix(reg.URL, "http://")
repo := host + "/zb/uptimesebi-checker"
key, _ := signing.GenerateKey()
keys := []signing.PublicKey{key.Public()}
ctx := context.Background()
piZero := v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"}
digest := publishSigned(t, host, "v1.0.0", key)
for _, tag := range []string{"1.0.0", "latest"} {
ref, _ := name.NewTag(repo + ":" + tag)
if desc, err := remote.Get(ref); err != nil || desc.Digest != digest {
t.Errorf("%s = %v, %v", tag, desc, err)
}
}
bin, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys)
if err != nil || string(bin) != "checker v1.0.0 for linux_arm_v6" {
t.Fatalf("Fetch = %q, %v", bin, err)
}
if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.1", piZero, keys); err == nil || !strings.Contains(err.Error(), "signed as") {
t.Errorf("an old release passed off as a new version: %v", err)
}
other, _ := signing.GenerateKey()
if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, []signing.PublicKey{other.Public()}); err == nil {
t.Error("accepted a signature by an unknown key")
}
if _, err := Fetch(ctx, repo+":1.0.0", "statuspage", "v1.0.0", piZero, keys); err == nil {
t.Error("the checker's signature passed for the status page")
}
if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", v1.Platform{OS: "linux", Architecture: "riscv64"}, keys); err == nil {
t.Error("fetched for a platform without image")
}
// An attacker who can push moves the tag to an image signed by no one.
evil, _ := Build(Options{Name: "checker", Dist: fakeDist(t, "evil", "checker"), Version: "v1.0.0"})
if err := Publish(ctx, evil, repo, []string{"1.0.0"}, Credentials{}); err != nil {
t.Fatal(err)
}
if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys); err == nil || !strings.Contains(err.Error(), "no signature") {
t.Errorf("unsigned image accepted: %v", err)
}
// ...or signs it with a key of their own.
if err := Sign(ctx, evil, repo, "checker", "v1.0.0", other, Credentials{}); err != nil {
t.Fatal(err)
}
if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys); err == nil {
t.Error("image signed by a foreign key accepted")
}
}
+154
View File
@@ -0,0 +1,154 @@
package agentimage
import (
"archive/tar"
"context"
"errors"
"fmt"
"io"
"strings"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
// An image's signature is a minisign signature of Message, with the
// version as trusted comment, stored as a small image under SignatureTag
// next to it, as cosign does. The message names the agent but not the
// registry, so mirrors keep the signature valid.
// Message is what the signature of an agent's image index covers.
func Message(agent string, digest v1.Hash) []byte {
return []byte("uptimesebi-" + agent + "@" + digest.String() + "\n")
}
// SignatureTag is the tag holding the signature of the index digest.
func SignatureTag(digest v1.Hash) string {
return digest.Algorithm + "-" + digest.Hex + ".minisig"
}
const signatureFile = "signature.minisig"
// Sign pushes the signature of idx, published as the agent's image in
// repo at version.
func Sign(ctx context.Context, idx v1.ImageIndex, repo, agent, version string, key signing.PrivateKey, login Credentials, nameOpts ...name.Option) error {
digest, err := idx.Digest()
if err != nil {
return err
}
sig, err := signing.Sign(key, Message(agent, digest), version)
if err != nil {
return err
}
img, err := fileImage(signatureFile, sig)
if err != nil {
return err
}
tag, err := name.NewTag(repo+":"+SignatureTag(digest), nameOpts...)
if err != nil {
return err
}
return remote.Write(tag, img, remoteOptions(ctx, login)...)
}
func fileImage(path string, data []byte) (v1.Image, error) {
raw, err := writeTar([]tarEntry{{path: path, mode: 0o644, data: data}}, timeZero)
if err != nil {
return nil, err
}
return singleLayer(raw)
}
// Fetch resolves ref, checks that the index is signed by one of keys for
// version and returns the agent binary for platform.
func Fetch(ctx context.Context, ref, agent, version string, platform v1.Platform, keys []signing.PublicKey, nameOpts ...name.Option) ([]byte, error) {
r, err := name.ParseReference(ref, nameOpts...)
if err != nil {
return nil, err
}
opts := remoteOptions(ctx, Credentials{})
desc, err := remote.Get(r, opts...)
if err != nil {
return nil, fmt.Errorf("agentimage: %s: %w", ref, err)
}
// Everything below is read by digest, which the client verifies.
pinned := r.Context().Digest(desc.Digest.String())
sigImg, err := remote.Image(r.Context().Tag(SignatureTag(desc.Digest)), opts...)
if err != nil {
return nil, fmt.Errorf("agentimage: no signature for %s: %w", pinned, err)
}
sig, err := ReadFile(sigImg, signatureFile, 4096)
if err != nil {
return nil, err
}
signed, err := signing.Verify(keys, Message(agent, desc.Digest), sig)
if err != nil {
return nil, fmt.Errorf("agentimage: %s: %w", pinned, err)
}
if signed != version {
return nil, fmt.Errorf("agentimage: %s is signed as %q, not %q", pinned, signed, version)
}
idx, err := remote.Index(pinned, opts...)
if err != nil {
return nil, err
}
m, err := idx.IndexManifest()
if err != nil {
return nil, err
}
for _, d := range m.Manifests {
if d.Platform == nil || !d.Platform.Equals(platform) {
continue
}
img, err := idx.Image(d.Digest)
if err != nil {
return nil, err
}
return ReadFile(img, strings.TrimPrefix(BinDir, "/")+"/"+agent, 512<<20)
}
return nil, fmt.Errorf("agentimage: %s has no image for %s", pinned, platform)
}
// ReadFile returns a file of an image's layers, up to max bytes.
func ReadFile(img v1.Image, path string, max int64) ([]byte, error) {
layers, err := img.Layers()
if err != nil {
return nil, err
}
for i := len(layers) - 1; i >= 0; i-- {
data, found, err := fileInLayer(layers[i], path, max)
if err != nil || found {
return data, err
}
}
return nil, fmt.Errorf("agentimage: %s is not in the image", path)
}
func fileInLayer(l v1.Layer, path string, max int64) ([]byte, bool, error) {
rc, err := l.Uncompressed()
if err != nil {
return nil, false, err
}
defer func() { _ = rc.Close() }()
tr := tar.NewReader(rc)
for {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
if strings.TrimPrefix(h.Name, "./") != path || h.Typeflag != tar.TypeReg {
continue
}
if h.Size > max {
return nil, true, fmt.Errorf("agentimage: %s is larger than %d bytes", path, max)
}
data, err := io.ReadAll(io.LimitReader(tr, max))
return data, true, err
}
}
+55
View File
@@ -5,6 +5,7 @@ import (
"errors" "errors"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
@@ -13,12 +14,15 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
agentdeploy "git.zb-server.de/ZB-Server/uptimesebi/deploy/agent"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check" "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/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule" "git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store" "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/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
) )
// AgentTokenPrefix marks agent tokens, distinct from user API tokens. // AgentTokenPrefix marks agent tokens, distinct from user API tokens.
@@ -34,6 +38,7 @@ const (
func (s *Server) mountAgentAPI(r gin.IRouter) { func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth()) g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello) g.GET("/hello", s.agentHello)
g.GET("/update", s.agentUpdate)
sp := g.Group("", requireAgentKind("statuspage")) sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage) sp.GET("/pages", s.agentPage)
sp.GET("/storage", s.storageGet) sp.GET("/storage", s.storageGet)
@@ -76,6 +81,11 @@ func (s *Server) agentAuth() gin.HandlerFunc {
if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil { if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil {
return err return err
} }
// The launcher of a self-updating agent asks for updates with
// an instance of its own; only the agent itself is a sign of life.
if strings.HasSuffix(c.FullPath(), "/agent/v1/update") {
return nil
}
if err := q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release}); err != nil { if err := q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release}); err != nil {
return err return err
} }
@@ -128,6 +138,51 @@ func (s *Server) agentHello(c *gin.Context) {
}) })
} }
// agentUpdate names the release self-updating agents run: the platform's
// own, so agents never get ahead of the API. Unreleased builds ("dev")
// are not followed.
func (s *Server) agentUpdate(c *gin.Context) {
u := agentapi.Update{Version: buildinfo.Version}
if buildinfo.Version != "dev" {
u.Image = s.cfg.AgentImage + "-" + agentOf(c).Kind + ":" + strings.TrimPrefix(buildinfo.Version, "v")
}
c.JSON(http.StatusOK, u)
}
// installView is what the console shows to install a new agent.
func (s *Server) installView() web.InstallView {
v := web.InstallView{
ScriptURL: strings.TrimSuffix(s.cfg.PublicURL, "/") + "/install.sh",
APIURL: strings.TrimSuffix(s.cfg.PublicURL, "/"),
Image: s.cfg.AgentImage,
Channel: agentdeploy.Channel(buildinfo.Version),
Compose: map[string]string{},
}
if buildinfo.Version != "dev" {
v.Release = buildinfo.Version
}
for _, kind := range []string{"checker", "statuspage"} {
if c, err := agentdeploy.Compose(kind); err == nil {
v.Compose[kind] = string(c)
}
}
return v
}
// installScript serves the script that installs a checker or status page
// server with Docker Compose, pointed at this platform.
func (s *Server) installScript(c *gin.Context) {
script, err := agentdeploy.Script(agentdeploy.Install{
APIURL: s.cfg.PublicURL, Image: s.cfg.AgentImage, Tag: agentdeploy.Channel(buildinfo.Version),
})
if err != nil {
internalError(c, err)
return
}
c.Header("Cache-Control", "no-store")
c.Data(http.StatusOK, "text/x-shellscript; charset=utf-8", script)
}
func (s *Server) agentJobs(c *gin.Context) { func (s *Server) agentJobs(c *gin.Context) {
var req agentapi.JobsRequest var req agentapi.JobsRequest
if !bind(c, &req) { if !bind(c, &req) {
+63 -3
View File
@@ -41,6 +41,8 @@ var endpoints = []endpoint{
req: secondFactorRequest{}, resp: sessionStarted}, req: secondFactorRequest{}, resp: sessionStarted},
{method: "POST", path: "/api/v1/auth/logout", tag: "Account", summary: "Sign out", sessionOnly: true, status: http.StatusNoContent}, {method: "POST", path: "/api/v1/auth/logout", tag: "Account", summary: "Sign out", sessionOnly: true, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/me", tag: "Account", summary: "The signed-in user and their organizations", resp: meView{}}, {method: "GET", path: "/api/v1/me", tag: "Account", summary: "The signed-in user and their organizations", resp: meView{}},
{method: "DELETE", path: "/api/v1/me/identities/:provider", tag: "Account", summary: "Unlink a platform identity provider from the account", sessionOnly: true,
description: "Refused with `409 last_sign_in` when it is the account's only way to sign in.", status: http.StatusNoContent},
{method: "POST", path: "/api/v1/me/org", tag: "Account", summary: "Switch the active organization", sessionOnly: true, {method: "POST", path: "/api/v1/me/org", tag: "Account", summary: "Switch the active organization", sessionOnly: true,
req: switchOrgRequest{}, status: http.StatusNoContent}, req: switchOrgRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/locale", tag: "Account", summary: "Set the interface language", public: true, {method: "POST", path: "/api/v1/locale", tag: "Account", summary: "Set the interface language", public: true,
@@ -58,8 +60,22 @@ var endpoints = []endpoint{
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)", {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{}}, 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, {method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
description: "Refused with `owns_shared_orgs` while the user owns organizations with other members. Organizations only the user belongs to are deleted with the account.", description: "Organizations the user is the last owner of are deleted with the account, with all their monitors, even when they have other members; organizations with further owners are left. Open to suspended accounts and to those that have not accepted the terms.",
req: deletionRequest{}, resp: obj{"status": ""}}, req: deletionRequest{}, resp: obj{"status": ""}},
{method: "POST", path: "/api/v1/consent", tag: "Account", summary: "Accept the platform's privacy policy and terms", sessionOnly: true,
description: "`versions` are the versions shown, e.g. `privacy:12,terms:14`; `409 consent_outdated` when a document changed meanwhile. Until an account accepted the current versions, other requests of its sessions get `403 consent_required`.",
req: consentRequest{}, resp: obj{"redirect": ""}},
{method: "GET", path: "/api/v1/support/tickets", tag: "Support", summary: "The account's support tickets", sessionOnly: true,
description: "Newest activity first. Open to suspended accounts and to those that have not accepted the terms.", resp: obj{"tickets": []supportTicketView{}}},
{method: "POST", path: "/api/v1/support/tickets", tag: "Support", summary: "Ask the platform's admins for help", sessionOnly: true,
description: "`message` is Markdown; the admins are mailed. `attach_org` names the active organization; `monitor_id`, `channel_id`, `alert_group_id`, `status_page_id` and `incident_id` point at things in it the account can read, and name it too. `409 too_many_tickets` beyond the platform's limit of open tickets per account, `409 suspended_ticket_limit` for a second ticket of a suspended account; `403 support_disabled` while the admins switched support off.",
req: supportTicketRequest{}, resp: supportTicketView{}, status: http.StatusCreated},
{method: "GET", path: "/api/v1/support/tickets/:id", tag: "Support", summary: "A support ticket with its messages", sessionOnly: true,
resp: supportTicketView{}},
{method: "POST", path: "/api/v1/support/tickets/:id/messages", tag: "Support", summary: "Reply to a support ticket", sessionOnly: true,
description: "Moves the ticket to `open`, also out of `closed`.", req: supportMessageRequest{}, resp: obj{"status": ""}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/support/tickets/:id/status", tag: "Support", summary: "Close or reopen a support ticket", sessionOnly: true,
description: "`status` is `closed` or `open`.", req: supportStatusRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it", {method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it",
req: previewRequest{}, resp: obj{"html": ""}}, req: previewRequest{}, resp: obj{"html": ""}},
{method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true, {method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true,
@@ -125,6 +141,24 @@ var endpoints = []endpoint{
status: http.StatusNoContent}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/incidents", tag: "Monitors", summary: "List incidents", perm: "incidents.read", {method: "GET", path: "/api/v1/org/incidents", tag: "Monitors", summary: "List incidents", perm: "incidents.read",
description: "Paged, newest first. `monitor_id` limits them to one monitor.", resp: paged(obj{"incidents": []incidentView{}})}, description: "Paged, newest first. `monitor_id` limits them to one monitor.", resp: paged(obj{"incidents": []incidentView{}})},
{method: "GET", path: "/api/v1/org/incidents/:id", tag: "Monitors", summary: "An incident with its updates", perm: "incidents.read",
description: "`status` is `resolved` once the monitor recovered, otherwise the status of the latest update (`investigating`, `identified`, `monitoring`, `resolved`), empty before the first. Updates newest first, internal notes included.",
resp: incidentDetailView{}},
{method: "PATCH", path: "/api/v1/org/incidents/:id", tag: "Monitors", summary: "Name an incident", perm: "incidents.write",
description: "The title status pages show; empty shows the monitor's name.", req: incidentTitleRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/org/incidents/:id/updates", tag: "Monitors", summary: "Post an update with a status", perm: "incidents.write",
description: "`status` is a built-in status or the `id` of one of the organization's own. `message` is Markdown and may be empty to just change the status. `public` (default true) shows it on status pages; false keeps it an internal note. The update's status becomes the incident's.",
req: incidentUpdateRequest{}, resp: incidentUpdateView{}, status: http.StatusCreated},
{method: "DELETE", path: "/api/v1/org/incidents/:id/updates/:update", tag: "Monitors", summary: "Delete an update", perm: "incidents.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/incident-statuses", tag: "Monitors", summary: "List the organization's own incident statuses", perm: "incidents.read",
resp: obj{"statuses": []incidentStatusView{}}},
{method: "POST", path: "/api/v1/org/incident-statuses", tag: "Monitors", summary: "Add an incident status with a color", perm: "org.manage",
description: "`color` is `#rrggbb`. Updates use it by its `id` as `status`.", req: incidentStatusRequest{}, resp: incidentStatusView{}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/org/incident-statuses/:id", tag: "Monitors", summary: "Rename or recolor an incident status", perm: "org.manage",
description: "Applies to the history of incidents that used it too.", req: incidentStatusRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/org/incident-statuses/:id", tag: "Monitors", summary: "Delete an unused incident status", perm: "org.manage",
description: "`409 status_in_use` while updates use it.", status: http.StatusNoContent},
// Status pages // Status pages
{method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}}, {method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}},
@@ -184,6 +218,10 @@ var endpoints = []endpoint{
description: "Paged by email.", resp: paged(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, {method: "DELETE", path: "/api/v1/org/members/:user", tag: "Organization", summary: "Remove a member", perm: "members.manage", sessionOnly: true,
status: http.StatusNoContent}, status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/org/members/:user/owner", tag: "Organization", summary: "Make a member an owner, or step down", sessionOnly: true,
perm: "owner",
description: "Only owners decide. `{\"owner\": false}` on oneself steps down; handing over is making someone else owner first. The last owner cannot step down (`409 last_owner`). A former owner without roles becomes Admin.",
req: ownerRequest{}, 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", {method: "POST", path: "/api/v1/org/members/:user/roles", tag: "Organization", summary: "Assign a role, optionally limited to a group or status page",
description: "Nobody can grant permissions they do not hold.", perm: "members.manage", sessionOnly: true, description: "Nobody can grant permissions they do not hold.", perm: "members.manage", sessionOnly: true,
req: assignRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}}}, req: assignRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}}},
@@ -246,6 +284,18 @@ var endpoints = []endpoint{
// Platform // Platform
{method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin", {method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin",
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})}, description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
{method: "GET", path: "/api/v1/admin/support/settings", tag: "Platform", summary: "How the platform runs support tickets", perm: "platform admin",
resp: supportSettings{}},
{method: "PUT", path: "/api/v1/admin/support/settings", tag: "Platform", summary: "Switch support tickets on or off and limit open tickets per account", perm: "platform admin",
description: "`max_open_tickets` of 0 means unlimited.", req: supportSettings{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/support/tickets", tag: "Platform", summary: "Support tickets of every account", perm: "platform admin",
description: "`?status=open` (default), `answered`, `closed` or `all`; the latest 200, those waiting for the admins first.", resp: obj{"tickets": []supportTicketView{}}},
{method: "GET", path: "/api/v1/admin/support/tickets/:id", tag: "Platform", summary: "A support ticket with its messages", perm: "platform admin",
resp: supportTicketView{}},
{method: "POST", path: "/api/v1/admin/support/tickets/:id/messages", tag: "Platform", summary: "Answer a support ticket", perm: "platform admin",
description: "Moves the ticket to `answered` and mails the account.", req: supportMessageRequest{}, resp: obj{"status": ""}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/admin/support/tickets/:id/status", tag: "Platform", summary: "Set a support ticket's status", perm: "platform admin",
req: supportStatusRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin", {method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin",
resp: obj{"documents": []legalView{}}}, resp: obj{"documents": []legalView{}}},
{method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin", {method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin",
@@ -260,6 +310,16 @@ var endpoints = []endpoint{
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not", {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.", 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}, perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
resp: obj{"providers": []idpView{}, "callback_url": ""}},
{method: "POST", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Add an identity provider",
description: "`kind` oidc takes the issuer, which is checked by discovery; github takes the GitHub server (empty for github.com). Accounts are linked by subject, never by email: an existing account with the provider's email is not taken over.",
perm: "platform admin", req: idpRequest{}, status: http.StatusCreated, resp: idpView{}},
{method: "PUT", path: "/api/v1/admin/identity-providers/:id", tag: "Platform", summary: "Change an identity provider",
description: "An empty client secret keeps the stored one; the kind cannot change.", perm: "platform admin", req: idpRequest{}, resp: idpView{}},
{method: "DELETE", path: "/api/v1/admin/identity-providers/:id", tag: "Platform", summary: "Remove an identity provider",
description: "Refused with `409 idp_in_use` while accounts can sign in only through it; disable it instead.", perm: "platform admin", 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: "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", {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.", 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.",
@@ -282,10 +342,10 @@ var endpoints = []endpoint{
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent}, 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: "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", {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.", description: "A suspended account is signed out everywhere and cannot use its API tokens; signing in again only lets it export or delete its data. Platform admins cannot be suspended.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent}, perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/users/:id", tag: "Platform", summary: "Delete an account", {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.", description: "Organizations the account is the last owner of are deleted with it. Platform admins cannot be deleted.",
perm: "platform admin", status: http.StatusNoContent}, perm: "platform admin", status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin", {method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
resp: obj{"regions": []regionView{}}}, resp: obj{"regions": []regionView{}}},
+19 -1
View File
@@ -37,6 +37,20 @@ var auditActions = map[string]string{
"POST /api/v1/auth/login": "auth.login", "POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login", "POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout", "POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/consent": "account.consent",
"POST /api/v1/support/tickets": "support.create",
"POST /api/v1/support/tickets/:id/messages": "support.reply",
"PUT /api/v1/support/tickets/:id/status": "support.status",
"POST /api/v1/admin/support/tickets/:id/messages": "support.answer",
"PUT /api/v1/admin/support/tickets/:id/status": "support.status",
"PUT /api/v1/admin/support/settings": "support.settings",
"PUT /api/v1/org/members/:user/owner": "member.owner",
"PATCH /api/v1/org/incidents/:id": "incident.title",
"POST /api/v1/org/incidents/:id/updates": "incident.update",
"DELETE /api/v1/org/incidents/:id/updates/:update": "incident.update_delete",
"POST /api/v1/org/incident-statuses": "incident_status.create",
"PUT /api/v1/org/incident-statuses/:id": "incident_status.update",
"DELETE /api/v1/org/incident-statuses/:id": "incident_status.delete",
"POST /api/v1/me/org": "", "POST /api/v1/me/org": "",
"POST /api/v1/me/totp/setup": "", "POST /api/v1/me/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable", "POST /api/v1/me/totp/enable": "account.totp_enable",
@@ -96,6 +110,10 @@ var auditActions = map[string]string{
"PUT /api/v1/admin/check-types": "platform.check_types_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/checker-network": "platform.checker_network_update",
"PUT /api/v1/admin/limits": "platform.limits_update", "PUT /api/v1/admin/limits": "platform.limits_update",
"POST /api/v1/admin/identity-providers": "platform.idp_create",
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
"DELETE /api/v1/admin/identity-providers/:id": "platform.idp_delete",
"DELETE /api/v1/me/identities/:provider": "account.identity_unlink",
"PUT /api/v1/admin/orgs/:id/limits": "platform.org_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/users/:id/limits": "platform.user_limits_update",
"PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension", "PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension",
@@ -177,7 +195,7 @@ func (s *Server) audit() gin.HandlerFunc {
action := auditActions[c.Request.Method+" "+c.FullPath()] action := auditActions[c.Request.Method+" "+c.FullPath()]
status := c.Writer.Status() 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 return
} }
if status >= 400 { if status >= 400 {
+16 -10
View File
@@ -35,6 +35,10 @@ type signupRequest struct {
// after confirming. // after confirming.
OrgName string `json:"org_name" binding:"max=200"` OrgName string `json:"org_name" binding:"max=200"`
OrgSlug string `json:"org_slug" binding:"max=63"` OrgSlug string `json:"org_slug" binding:"max=63"`
// Consent accepts the platform's privacy policy and terms in the
// versions the form showed (ConsentVersions, "privacy:12,terms:14").
Consent bool `json:"consent"`
ConsentVersions string `json:"consent_versions" binding:"max=200"`
} }
func (s *Server) signup(c *gin.Context) { func (s *Server) signup(c *gin.Context) {
@@ -60,6 +64,10 @@ func (s *Server) signup(c *gin.Context) {
fail(c, http.StatusTooManyRequests, "signup_limit") fail(c, http.StatusTooManyRequests, "signup_limit")
return return
} }
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
verify := s.verificationRequired() verify := s.verificationRequired()
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != "" withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
hash, err := auth.HashPassword(req.Password) hash, err := auth.HashPassword(req.Password)
@@ -103,6 +111,11 @@ func (s *Server) signup(c *gin.Context) {
} }
return nil return nil
}) })
if err == nil {
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
return recordConsent(ctx, q, user.ID, consent)
})
}
switch { switch {
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"): case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
fail(c, http.StatusConflict, "email_taken") fail(c, http.StatusConflict, "email_taken")
@@ -195,12 +208,9 @@ func (s *Server) login(c *gin.Context) {
invalidCredentials(c) invalidCredentials(c)
return return
} }
// Only someone who knows the password learns of the suspension or a // Only someone who knows the password learns of a missing
// missing confirmation. // confirmation. Suspended accounts sign in, but only to export or
if user.DisabledAt != nil { // delete their data.
fail(c, http.StatusForbidden, "account_suspended")
return
}
if user.EmailVerifiedAt == nil { if user.EmailVerifiedAt == nil {
fail(c, http.StatusForbidden, "email_unverified") fail(c, http.StatusForbidden, "email_unverified")
return return
@@ -289,10 +299,6 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Metho
internalError(c, err) internalError(c, err)
return return
} }
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
var org uuid.UUID var org uuid.UUID
if len(orgs) > 0 { if len(orgs) > 0 {
org = orgs[0].ID org = orgs[0].ID
+18 -2
View File
@@ -289,6 +289,10 @@ type incidentView struct {
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"` ResolvedAt *time.Time `json:"resolved_at"`
Cause map[string]string `json:"cause"` Cause map[string]string `json:"cause"`
Title string `json:"title"`
// The status is resolved once the monitor recovered, otherwise the
// status of the latest update, empty before the first.
statusFields
} }
// incidentPage reads a page of incidents, newest first, of one monitor // incidentPage reads a page of incidents, newest first, of one monitor
@@ -329,14 +333,26 @@ func (s *Server) listIncidents(c *gin.Context) {
if !ok { if !ok {
return return
} }
rows, info, err := s.incidentPage(c.Request.Context(), current(c), pg, monitor) ctx := c.Request.Context()
rows, info, err := s.incidentPage(ctx, current(c), pg, monitor)
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
} }
var statuses customStatuses
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
statuses, err = loadCustomStatuses(ctx, q)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]incidentView, len(rows)) out := make([]incidentView, len(rows))
for i, r := range rows { for i, r := range rows {
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt} out[i] = incidentView{
ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt,
Title: r.Title, statusFields: toStatusFields(statuses.of(store.Incident{ResolvedAt: r.ResolvedAt, Status: r.Status, StatusID: r.StatusID}), r.StatusID),
}
_ = json.Unmarshal(r.Cause, &out[i].Cause) _ = json.Unmarshal(r.Cause, &out[i].Cause)
} }
c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev}) c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
+52
View File
@@ -3,9 +3,11 @@ package api_test
import ( import (
"context" "context"
"errors" "errors"
"io"
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time" "time"
@@ -13,7 +15,9 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/api" "git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker" "git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
"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/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
) )
@@ -191,6 +195,54 @@ func TestAgentAuth(t *testing.T) {
} }
} }
func TestAgentUpdate(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.AgentImage = "mirror.example/acme/uptimesebi" })
tok, _ := e.platformChecker(t, uniq("up-"))
ctx := context.Background()
instance := uuid.New()
client := agentapi.NewClient(e.srv.URL, tok, instance, "v1.0.0").WithHTTPClient(e.srv.Client())
u, err := client.Update(ctx)
if err != nil || u.Version != "dev" || u.Image != "" {
t.Errorf("unreleased platform: Update = %+v, %v", u, err)
}
old := buildinfo.Version
buildinfo.Version = "v1.4.2"
t.Cleanup(func() { buildinfo.Version = old })
u, err = client.Update(ctx)
if err != nil || u.Version != "v1.4.2" || u.Image != "mirror.example/acme/uptimesebi-checker:1.4.2" {
t.Errorf("Update = %+v, %v", u, err)
}
// The launcher asking is not an instance of the agent.
if n := e.count(t, `SELECT count(*) FROM agent_instances WHERE id = $1`, instance); n != 0 {
t.Errorf("the update check registered an instance")
}
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Update(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Update(wrong token) = %v", err)
}
}
func TestInstallScript(t *testing.T) {
e := newEnvWith(t, func(c *config.API) {
c.PublicURL = "https://uptime.example.com"
c.AgentImage = "mirror.example/acme/uptimesebi"
})
resp, err := e.srv.Client().Get(e.srv.URL + "/install.sh")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/x-shellscript") {
t.Fatalf("GET /install.sh = %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
}
for _, want := range []string{"#!/bin/sh", "API_URL='https://uptime.example.com'", "IMAGE='mirror.example/acme/uptimesebi'", "TAG='edge'"} {
if !strings.Contains(string(body), want) {
t.Errorf("the script lacks %q", want)
}
}
}
func (b *browser) orgID() string { func (b *browser) orgID() string {
b.t.Helper() b.t.Helper()
_, me := b.do("GET", "/api/v1/me", nil) _, me := b.do("GET", "/api/v1/me", nil)
+362
View File
@@ -0,0 +1,362 @@
package api
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"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"
)
// Every account accepts the platform's privacy policy and terms in their
// current version: on sign-up, and otherwise right after signing in, again
// whenever a document asks for it. Until then, and while an account is
// suspended, it can only read the documents, export its data, delete
// itself and sign out.
// requiredConsent returns the current version of each document accounts
// accept; empty when the platform has none.
func (s *Server) requiredConsent(ctx context.Context) (map[string]int64, error) {
return s.consent.get(ctx, s.rdb, func(ctx context.Context) (map[string]int64, error) {
out := map[string]int64{}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
rows, err := q.RequiredLegalVersions(ctx)
for _, r := range rows {
out[r.Kind] = r.Version
}
return err
})
return out, err
})
}
// consentVersions encodes versions for a form, e.g. "privacy:12,terms:14".
func consentVersions(v map[string]int64) string {
var parts []string
for _, kind := range web.ConsentKinds {
if n, ok := v[kind]; ok {
parts = append(parts, kind+":"+strconv.FormatInt(n, 10))
}
}
return strings.Join(parts, ",")
}
func parseConsentVersions(s string) map[string]int64 {
out := map[string]int64{}
for part := range strings.SplitSeq(s, ",") {
kind, n, ok := strings.Cut(strings.TrimSpace(part), ":")
if v, err := strconv.ParseInt(n, 10, 64); ok && err == nil {
out[kind] = v
}
}
return out
}
// errConsentOutdated reports an acceptance of versions that are no longer
// current: a document changed while the form was open.
var errConsentOutdated = errors.New("api: consent for outdated documents")
// checkConsent verifies that accepted covers exactly the documents
// required right now.
func checkConsent(required, accepted map[string]int64) error {
for kind, v := range required {
if accepted[kind] != v {
return errConsentOutdated
}
}
return nil
}
func recordConsent(ctx context.Context, q *store.Queries, user uuid.UUID, versions map[string]int64) error {
for kind, v := range versions {
if err := q.AcceptLegal(ctx, store.AcceptLegalParams{UserID: user, Kind: kind, Version: v}); err != nil {
return err
}
}
return nil
}
// access is what an account may do in the console.
type access struct {
suspended bool
reason string
// missing are the documents still to accept, with their versions.
missing map[string]int64
}
func (a access) restricted() bool { return a.suspended || len(a.missing) > 0 }
func (s *Server) accessOf(ctx context.Context, user uuid.UUID) (access, error) {
required, err := s.requiredConsent(ctx)
if err != nil {
return access{}, err
}
var a access
err = s.db.Tx(ctx, tenant.User(user), func(q *store.Queries) error {
u, err := q.GetUser(ctx, user)
if err != nil {
return err
}
if u.DisabledAt != nil {
a.suspended, a.reason = true, u.DisabledReason
}
if len(required) == 0 {
return nil
}
accepted, err := q.AcceptedLegalVersions(ctx, user)
if err != nil {
return err
}
for kind, v := range required {
if !slices.ContainsFunc(accepted, func(r store.AcceptedLegalVersionsRow) bool { return r.Kind == kind && r.Version == v }) {
if a.missing == nil {
a.missing = map[string]int64{}
}
a.missing[kind] = v
}
}
return nil
})
return a, err
}
// restrictedPaths stay open to accounts that are suspended or have yet to
// accept the documents, support included: a suspended account may want to
// ask why. Admins keep editing the documents, which they may be publishing
// one after the other; the handlers still check they are.
var restrictedPaths = []string{
"/consent", "/account/suspended", "/legal/",
"/api/v1/auth/", "/api/v1/consent", "/api/v1/me/export", "/api/v1/me/delete", "/api/v1/locale",
"/support", "/support/", "/api/v1/support/",
"/admin/legal", "/api/v1/admin/legal/",
}
func allowedRestricted(path string) bool {
return slices.ContainsFunc(restrictedPaths, func(p string) bool {
return path == p || (strings.HasSuffix(p, "/") && strings.HasPrefix(path, p))
})
}
// accountGate keeps restricted accounts on the consent or suspension page.
func (s *Server) accountGate() gin.HandlerFunc {
return func(c *gin.Context) {
sess := auth.Current(c)
path := c.Request.URL.Path
if sess == nil || allowedRestricted(path) {
c.Next()
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
switch {
case err != nil:
internalError(c, err)
c.Abort()
return
case !a.restricted():
c.Next()
return
}
if strings.HasPrefix(path, "/api/") {
code := "consent_required"
if a.suspended {
code = "account_suspended"
}
fail(c, http.StatusForbidden, code)
c.Abort()
return
}
target := "/account/suspended"
if !a.suspended {
target = "/consent?next=" + url.QueryEscape(c.Request.URL.RequestURI())
}
c.Redirect(http.StatusSeeOther, target)
c.Abort()
}
}
// localNext keeps a redirect target on this site.
func localNext(next string) string {
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") {
return "/"
}
return next
}
type consentRequest struct {
// Versions are the documents accepted, as shown: "privacy:12,terms:14".
Versions string `json:"versions" binding:"max=200"`
Next string `json:"next" binding:"max=2000"`
}
// acceptConsent records that the signed-in account accepts the current
// documents.
func (s *Server) acceptConsent(c *gin.Context) {
var req consentRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
if sess == nil {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
required, err := s.requiredConsent(ctx)
if err != nil {
internalError(c, err)
return
}
accepted := parseConsentVersions(req.Versions)
if err := checkConsent(required, accepted); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return
}
auditDetail(c, "versions", consentVersions(required))
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return recordConsent(ctx, q, sess.UserID, required)
}); err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"redirect": localNext(req.Next)})
}
// consentDocs lists the documents of versions with their links.
func (s *Server) consentDocs(ctx context.Context, versions map[string]int64) []web.LegalLink {
var docs []web.LegalLink
for _, l := range web.LegalLinks(s.platformLegalDocs(ctx), "/legal/") {
if _, ok := versions[l.Kind]; ok {
docs = append(docs, l)
}
}
return docs
}
// restrictedMe is the account data the consent and suspension pages show,
// with the organizations its deletion would take along.
func (s *Server) restrictedMe(c *gin.Context, sess *auth.Session) (web.Me, error) {
m, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
return web.Me{}, err
}
me := toWebMe(m)
me.Support = s.supportSettings(c.Request.Context()).Enabled
me.DeletesOrgs, err = s.lastOwnedOrgs(c.Request.Context(), sess.UserID)
return me, err
}
func (s *Server) consentPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
next := localNext(c.Query("next"))
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if a.suspended {
c.Redirect(http.StatusSeeOther, "/account/suspended")
return
}
if len(a.missing) == 0 {
c.Redirect(http.StatusSeeOther, next)
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.ConsentPage(s.pageFor(c, "consent.title"), me,
s.consentDocs(c.Request.Context(), a.missing), consentVersions(required), next))
}
func (s *Server) suspendedPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if !a.suspended {
c.Redirect(http.StatusSeeOther, "/")
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.SuspendedPage(s.pageFor(c, "suspended.title"), me, a.reason))
}
// signupConsent checks the consent given on a sign-up form and returns the
// versions to record.
func (s *Server) signupConsent(c *gin.Context, given bool, versions string) (map[string]int64, bool) {
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return nil, false
}
if len(required) == 0 {
return nil, true
}
if !given {
fail(c, http.StatusUnprocessableEntity, "consent_required")
return nil, false
}
if err := checkConsent(required, parseConsentVersions(versions)); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return nil, false
}
return required, true
}
// signupConsentView is what sign-up forms show: the documents to accept
// and their versions.
func (s *Server) signupConsentView(ctx context.Context) (web.SignupConsent, error) {
required, err := s.requiredConsent(ctx)
if err != nil || len(required) == 0 {
return web.SignupConsent{}, err
}
return web.SignupConsent{Docs: s.consentDocs(ctx, required), Versions: consentVersions(required)}, nil
}
// lastOwnedOrgs names the organizations user is the last owner of, which
// deleting the account deletes too.
func (s *Server) lastOwnedOrgs(ctx context.Context, user uuid.UUID) ([]string, error) {
var out []string
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, user)
for _, o := range owned {
if o.Owners == 1 {
out = append(out, fmt.Sprintf("%s (%s)", o.Name, o.Slug))
}
}
return err
})
return out, err
}
+193
View File
@@ -0,0 +1,193 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestConsent(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("cs")+".test", uniq("cs-"))
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)
}
earlier := e.browser(t)
earlier.signup("e@"+uniq("cs")+".test", uniq("cs-"))
t.Cleanup(func() { clearPlatformLegal(admin) })
for kind, text := range map[string]string{"privacy": "# Datenschutz", "terms": "# AGB"} {
if st, body := admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{"markdown": text}); st != http.StatusNoContent {
t.Fatalf("set %s = %d %v", kind, st, body)
}
}
admin.acceptConsent()
if _, _, html := e.browser(t).page("/login"); !strings.Contains(html, `href="/legal/terms"`) {
t.Error("the footer lacks the terms")
}
if st, body := admin.do("PUT", "/api/v1/org/legal/terms", map[string]any{"markdown": "x"}); st != http.StatusNotFound {
t.Errorf("organization sets terms = %d %v, want 404", st, body)
}
// Signing up needs the box ticked for the versions shown.
visitor := e.browser(t)
_, _, form := visitor.page("/signup")
versions := consentShown(form)
if !strings.Contains(versions, "privacy:") || !strings.Contains(versions, "terms:") || !strings.Contains(form, `name="consent" required`) {
t.Fatalf("sign-up form lacks the consent box: versions %q", versions)
}
signup := func(consent bool, versions string) (int, map[string]any) {
return e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{
"email": uniq("n") + "@example.test", "password": password, "consent": consent, "consent_versions": versions,
})
}
st, body := signup(false, versions)
expect(t, "sign up without consent", st, body, http.StatusUnprocessableEntity, "consent_required")
st, body = signup(true, "privacy:1,terms:1")
expect(t, "sign up with outdated versions", st, body, http.StatusConflict, "consent_outdated")
email := uniq("n") + "@example.test"
fresh := e.browser(t)
if st, body := fresh.do("POST", "/api/v1/auth/signup", map[string]any{
"email": email, "password": password, "consent": true, "consent_versions": versions,
}); st != http.StatusOK {
t.Fatalf("sign up with consent = %d %v", st, body)
}
freshID := fresh.userIDSelf()
if n := e.count(t, `SELECT count(*) FROM legal_acceptances WHERE user_id = $1`, freshID); n != 2 {
t.Errorf("recorded %d acceptances, want 2", n)
}
if got := fresh.visit("/"); got.Path == "/consent" {
t.Error("an account that accepted on sign-up is asked again")
}
// Accounts from before have to accept first; until then they can read
// the documents, take their data along and sign out.
if got := earlier.visit("/"); got.Path != "/consent" || got.Query().Get("next") != "/" {
t.Errorf("console before consent landed on %s", got)
}
st, body = earlier.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API before consent", st, body, http.StatusForbidden, "consent_required")
for _, path := range []string{"/legal/terms", "/api/v1/me/export"} {
if st, _, _ := earlier.page(path); st != http.StatusOK {
t.Errorf("GET %s before consent = %d", path, st)
}
}
_, _, page := earlier.page("/consent")
if !strings.Contains(page, "Delete account") || !strings.Contains(page, `href="/legal/terms"`) {
t.Error("the consent page offers no way out or lacks the documents")
}
st, body = earlier.do("POST", "/api/v1/consent", map[string]any{"versions": "terms:1", "next": "/"})
expect(t, "accept outdated versions", st, body, http.StatusConflict, "consent_outdated")
if st, body := earlier.do("POST", "/api/v1/consent", map[string]any{"versions": consentShown(page), "next": "//evil.example"}); st != http.StatusOK || body["redirect"] != "/" {
t.Errorf("accept = %d %v, want a local redirect", st, body)
}
if st, _ := earlier.do("GET", "/api/v1/org/monitors", nil); st != http.StatusOK {
t.Errorf("API after consent = %d", st)
}
// A correction asks nobody again; a new version asks everyone.
admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "# AGB\n\nTippfehler behoben"})
if got := earlier.visit("/"); got.Path == "/consent" {
t.Error("a correction asked for consent again")
}
admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "# AGB v2", "new_version": true})
if got := earlier.visit("/"); got.Path != "/consent" {
t.Errorf("a new version of the terms was not put before the account: %s", got)
}
if _, _, page := earlier.page("/consent"); !strings.Contains(page, `href="/legal/terms"`) || strings.Contains(page, `<li><a href="/legal/privacy"`) {
t.Error("the consent page should list only the changed terms")
}
earlier.acceptConsent()
admin.acceptConsent()
// An account created through a sign-in provider is asked right after
// its first sign-in.
idp := ssotest.New(t)
st, provider := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
"kind": "oidc", "name": "IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
"allow_signup": true, "enabled": true,
})
if st != http.StatusCreated {
t.Fatalf("create provider = %d %v", st, provider)
}
t.Cleanup(func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_identity_providers WHERE id = $1`, provider["id"])
return err
})
})
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("sso") + "@example.test", EmailVerified: true})
viaSSO := e.browser(t)
if got := viaSSO.visit("/login/sso/" + provider["id"].(string)); got.Path != "/consent" {
t.Errorf("SSO sign-up landed on %s, want the consent page", got)
}
viaSSO.acceptConsent()
if got := viaSSO.visit("/"); got.Path != "/orgs/new" {
t.Errorf("after consenting the new SSO account landed on %s, want /orgs/new", got)
}
}
func TestSuspendedAccount(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("su")+".test", uniq("su-"))
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)
}
email := "s@" + uniq("su") + ".test"
user := e.browser(t)
user.signup(email, uniq("su-"))
userID := user.userIDSelf()
org := uuid.MustParse(user.orgID())
user.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
_, tok := user.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
if st, body := admin.do("PUT", "/api/v1/admin/users/"+userID.String()+"/suspension", map[string]any{"suspended": true, "reason": "Unpaid invoice"}); st != http.StatusNoContent {
t.Fatalf("suspend = %d %v", st, body)
}
api := &browser{t: t, base: user.base, hc: e.srv.Client(), bearer: tok["token"].(string)}
if st, _ := api.do("GET", "/api/v1/org/monitors", nil); st != http.StatusUnauthorized {
t.Errorf("API token of a suspended account = %d, want 401", st)
}
// It signs in again, but only to take its data along or delete itself.
back := e.browser(t)
if st, body := back.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": password}); st != http.StatusOK {
t.Fatalf("suspended account signs in = %d %v", st, body)
}
if got := back.visit("/"); got.Path != "/account/suspended" {
t.Errorf("console of a suspended account landed on %s", got)
}
_, _, page := back.page("/account/suspended")
if !strings.Contains(page, "Unpaid invoice") || !strings.Contains(page, "Delete account") || !strings.Contains(page, "You are the last owner of these organizations") {
t.Error("the suspension page lacks the reason or the way out")
}
st, body := back.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, _, _ := back.page("/api/v1/me/export"); st != http.StatusOK {
t.Errorf("export of a suspended account = %d", st)
}
if st, body := back.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("suspended account deletes itself = %d %v", st, body)
}
for q, arg := range map[string]any{`SELECT count(*) FROM users WHERE id = $1`: userID, `SELECT count(*) FROM orgs WHERE id = $1`: org, `SELECT count(*) FROM monitors WHERE org_id = $1`: org} {
if n := e.count(t, q, arg); n != 0 {
t.Errorf("%s = %d after deletion", q, n)
}
}
}
+15 -3
View File
@@ -212,6 +212,8 @@ type monitorData struct {
// firstRegion the same per region. // firstRegion the same per region.
first map[uuid.UUID]time.Time first map[uuid.UUID]time.Time
firstRegion map[uuid.UUID]map[string]time.Time firstRegion map[uuid.UUID]map[string]time.Time
// statuses are the organization's own incident statuses.
statuses customStatuses
} }
// loadFirstData finds when monitors and their regions first reported. The // loadFirstData finds when monitors and their regions first reported. The
@@ -333,6 +335,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil { if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil {
return err return err
} }
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err
}
ids := make([]uuid.UUID, len(monitors)) ids := make([]uuid.UUID, len(monitors))
for i, m := range monitors { for i, m := range monitors {
ids[i] = m.ID ids[i] = m.ID
@@ -533,6 +538,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
} }
v.Incidents = append(v.Incidents, d.incidentRow(store.Incident{ 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, ID: i.ID, OrgID: i.OrgID, MonitorID: i.MonitorID, StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: i.Cause,
Title: i.Title, Status: i.Status, StatusID: i.StatusID,
}, m.Name)) }, m.Name))
} }
page.TitleID = "console.monitors.title" page.TitleID = "console.monitors.title"
@@ -556,6 +562,7 @@ func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentR
row := web.IncidentRow{ row := web.IncidentRow{
ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor, ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor,
Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil, Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil,
Title: i.Title, Status: d.statuses.of(i),
} }
end := time.Now() end := time.Now()
if i.ResolvedAt != nil { if i.ResolvedAt != nil {
@@ -902,11 +909,16 @@ func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me w
if err != nil { if err != nil {
return nil, err return nil, err
} }
v := web.IncidentsView{Rows: make([]web.IncidentRow, len(rows)), Pager: pager(c, info)} v := web.IncidentsView{Rows: make([]web.IncidentRow, len(rows)), Pager: pager(c, info), Custom: d.statuses.list()}
for i, r := range rows { for i, r := range rows {
v.Rows[i] = d.incidentRow(store.Incident{ inc := store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause, ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause,
}, r.MonitorName) Title: r.Title, Status: r.Status, StatusID: r.StatusID,
}
v.Rows[i] = d.incidentRow(inc, r.MonitorName)
// Whoever may write the monitor's incidents sets the status here.
v.Rows[i].CanWrite = canInGroup(p, authz.IncidentsWrite, d.tree, d.byID[r.MonitorID].GroupID)
v.Rows[i].NextStatus = nextIncidentStatus(inc)
} }
if monitor != nil { if monitor != nil {
if m, ok := d.byID[*monitor]; ok { if m, ok := d.byID[*monitor]; ok {
+8 -1
View File
@@ -5,12 +5,16 @@ import (
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"regexp"
"strings" "strings"
"testing" "testing"
"time" "time"
) )
// page fetches path and returns the final status, path and body. var csrfMeta = regexp.MustCompile(`<meta name="csrf-token" content="([^"]+)"`)
// page fetches path and returns the final status, path and body. Like the
// console's script, it takes the CSRF token from the page.
func (b *browser) page(path string) (int, string, string) { func (b *browser) page(path string) (int, string, string) {
b.t.Helper() b.t.Helper()
resp, err := b.hc.Get(b.base + path) resp, err := b.hc.Get(b.base + path)
@@ -19,6 +23,9 @@ func (b *browser) page(path string) (int, string, string) {
} }
defer func() { _ = resp.Body.Close() }() defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
if m := csrfMeta.FindSubmatch(body); m != nil {
b.csrf = string(m[1])
}
return resp.StatusCode, resp.Request.URL.Path, string(body) return resp.StatusCode, resp.Request.URL.Path, string(body)
} }
+89 -23
View File
@@ -31,9 +31,32 @@ type accountExport struct {
Organizations []exportMembership `json:"organizations"` Organizations []exportMembership `json:"organizations"`
Identities []exportIdentity `json:"sso_identities"` Identities []exportIdentity `json:"sso_identities"`
Tokens []exportToken `json:"api_tokens"` Tokens []exportToken `json:"api_tokens"`
Consents []exportConsent `json:"consents"`
Support []exportTicket `json:"support_tickets"`
Activity []exportActivity `json:"activity"` Activity []exportActivity `json:"activity"`
} }
type exportTicket struct {
Subject string `json:"subject"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
Messages []exportTicketMessage `json:"messages"`
}
// exportTicketMessage leaves out which admin answered: that is about them.
type exportTicketMessage struct {
Time time.Time `json:"time"`
FromStaff bool `json:"from_staff"`
Body string `json:"body"`
}
// exportConsent is an accepted version of the privacy policy or terms.
type exportConsent struct {
Kind string `json:"kind"`
Version int64 `json:"version"`
AcceptedAt time.Time `json:"accepted_at"`
}
type exportAccount struct { type exportAccount struct {
ID uuid.UUID `json:"id"` ID uuid.UUID `json:"id"`
Email string `json:"email"` Email string `json:"email"`
@@ -133,6 +156,14 @@ func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (acco
if err != nil { if err != nil {
return err return err
} }
consents, err := q.LegalAcceptances(ctx, u.ID)
if err != nil {
return err
}
x.Consents = []exportConsent{}
for _, r := range consents {
x.Consents = append(x.Consents, exportConsent{Kind: r.Kind, Version: r.Version, AcceptedAt: r.AcceptedAt})
}
x.Tokens = []exportToken{} x.Tokens = []exportToken{}
for _, t := range toks { for _, t := range toks {
x.Tokens = append(x.Tokens, exportToken{ x.Tokens = append(x.Tokens, exportToken{
@@ -140,6 +171,22 @@ func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (acco
ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt, ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt,
}) })
} }
tickets, err := q.ListUserSupportTickets(ctx, userID)
if err != nil {
return err
}
x.Support = []exportTicket{}
for _, t := range tickets {
msgs, err := q.SupportMessages(ctx, t.ID)
if err != nil {
return err
}
et := exportTicket{Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, Messages: []exportTicketMessage{}}
for _, m := range msgs {
et.Messages = append(et.Messages, exportTicketMessage{Time: m.CreatedAt, FromStaff: m.FromStaff, Body: m.Body})
}
x.Support = append(x.Support, et)
}
events, err := q.UserAuditEvents(ctx, &userID) events, err := q.UserAuditEvents(ctx, &userID)
if err != nil { if err != nil {
return err return err
@@ -321,6 +368,16 @@ type exportIncident struct {
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"` ResolvedAt *time.Time `json:"resolved_at"`
Cause json.RawMessage `json:"cause"` Cause json.RawMessage `json:"cause"`
Title string `json:"title"`
Status *string `json:"status"`
Updates []exportUpdate `json:"updates"`
}
type exportUpdate struct {
Status string `json:"status"`
Message string `json:"message"`
Public bool `json:"public"`
CreatedAt time.Time `json:"created_at"`
} }
type exportAuditEntry struct { type exportAuditEntry struct {
@@ -502,10 +559,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
if err != nil { if err != nil {
return err return err
} }
updates, err := q.OrgIncidentUpdatesExport(ctx, org)
if err != nil {
return err
}
updatesOf := map[uuid.UUID][]exportUpdate{}
for _, u := range updates {
updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], exportUpdate{Status: u.Status, Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt})
}
x.Incidents = []exportIncident{} x.Incidents = []exportIncident{}
for _, i := range incidents { for _, i := range incidents {
x.Incidents = append(x.Incidents, exportIncident{ID: i.ID, MonitorID: i.MonitorID, Monitor: i.Monitor, x.Incidents = append(x.Incidents, exportIncident{ID: i.ID, MonitorID: i.MonitorID, Monitor: i.Monitor,
StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause)}) StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause),
Title: i.Title, Status: i.Status, Updates: orEmpty(updatesOf[i.ID])})
} }
audit, err := q.OrgAuditExport(ctx, org) audit, err := q.OrgAuditExport(ctx, org)
@@ -586,9 +652,12 @@ func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
return err return err
} }
// deleteAccount erases the signed-in user (Art. 17). Organizations only the // deleteAccount erases the signed-in user (Art. 17). Organizations the
// user belongs to go with the account; an organization shared with others // user is the last owner of go with the account, monitors and all, even
// must be handed over or deleted first, so nobody loses access to it. // when they have other members: nobody would be left to run them. The user
// just leaves organizations with further owners.
// Suspended accounts and those that have not accepted the terms may do
// this too.
func (s *Server) deleteAccount(c *gin.Context) { func (s *Server) deleteAccount(c *gin.Context) {
var req deletionRequest var req deletionRequest
if !bind(c, &req) { if !bind(c, &req) {
@@ -609,17 +678,11 @@ func (s *Server) deleteAccount(c *gin.Context) {
fail(c, http.StatusForbidden, "confirmation_failed") fail(c, http.StatusForbidden, "confirmation_failed")
return return
} }
shared, orgsDeleted, err := s.eraseAccount(ctx, u) orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return 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) auth.ClearCookie(c)
// Kept as proof of erasure, without saying whose. // Kept as proof of erasure, without saying whose.
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK}, s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
@@ -627,24 +690,27 @@ func (s *Server) deleteAccount(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "deleted"}) c.JSON(http.StatusOK, gin.H{"status": "deleted"})
} }
// eraseAccount deletes u with the organizations only u belongs to and // eraseAccount deletes u with the organizations u is the last owner of and
// ends u's sessions. If u owns organizations shared with others, nothing // ends u's sessions; u leaves the others.
// is deleted and their slugs are returned. func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted int, err error) {
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 { err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, u.ID) owned, err := q.OwnedOrgs(ctx, u.ID)
if err != nil { if err != nil {
return err return err
} }
for _, o := range owned { for _, o := range owned {
if o.Members > 1 { if err := q.LockOrgOwners(ctx, o.ID); err != nil {
shared = append(shared, o.Slug) return err
} }
// Counted again under the lock: another owner may be stepping
// down right now.
n, err := q.CountOwners(ctx, o.ID)
if err != nil {
return err
} }
if len(shared) > 0 { if n > 1 {
return nil continue
} }
for _, o := range owned {
if err := purgeOrg(ctx, q, o.ID); err != nil { if err := purgeOrg(ctx, q, o.ID); err != nil {
return err return err
} }
@@ -663,13 +729,13 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []strin
} }
return nil return nil
}) })
if err != nil || len(shared) > 0 { if err != nil {
return shared, 0, err return 0, err
} }
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil { if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err) s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
} }
return nil, orgsDeleted, nil return orgsDeleted, nil
} }
type orgDeletionRequest struct { type orgDeletionRequest struct {
+20 -4
View File
@@ -228,10 +228,6 @@ func TestDeleteAccount(t *testing.T) {
memberID := member.userIDSelf() memberID := member.userIDSelf()
member.do("POST", "/api/v1/org/groups", map[string]any{"name": "By member"}) member.do("POST", "/api/v1/org/groups", map[string]any{"name": "By member"})
// An owner of a shared organization must hand it over first.
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusConflict || body["error"] != "owns_shared_orgs" {
t.Errorf("owner of shared org deletes account = %d %v, want 409", st, body)
}
if st, _ := member.do("POST", "/api/v1/me/delete", map[string]any{"password": "wrong password"}); st != http.StatusForbidden { if st, _ := member.do("POST", "/api/v1/me/delete", map[string]any{"password": "wrong password"}); st != http.StatusForbidden {
t.Errorf("wrong password = %d, want 403", st) t.Errorf("wrong password = %d, want 403", st)
} }
@@ -273,4 +269,24 @@ func TestDeleteAccount(t *testing.T) {
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, soloOrg) != 0 { if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, soloOrg) != 0 {
t.Error("sole owner's organization survived") t.Error("sole owner's organization survived")
} }
// The owner takes the organization along, monitors and all, even when
// others still belong to it; the security page says so first.
org := uuid.MustParse(owner.orgID())
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
other := e.joinVia(t, owner.invite("x@"+uniq("da")+".test", owner.roleID("viewer")))
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "You are the last owner of these organizations") {
t.Error("the security page does not warn that the organization goes with the account")
}
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("last owner deletes account = %d %v", st, body)
}
for _, q := range []string{`SELECT count(*) FROM orgs WHERE id = $1`, `SELECT count(*) FROM monitors WHERE org_id = $1`} {
if n := e.count(t, q, org); n != 0 {
t.Errorf("%s = %d after the last owner left", q, n)
}
}
if st, me := other.do("GET", "/api/v1/me", nil); st != http.StatusOK || len(me["orgs"].([]any)) != 0 {
t.Errorf("remaining member = %d %v, want an account without the organization", st, me)
}
} }
-3
View File
@@ -68,9 +68,6 @@ func (t groupTree) resources(group *uuid.UUID) []authz.Resource {
return out 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. // walk visits groups depth-first in name order.
func (t groupTree) walk(fn func(g store.MonitorGroup, depth int)) { func (t groupTree) walk(fn func(g store.MonitorGroup, depth int)) {
var visit func(ids []uuid.UUID, depth int) var visit func(ids []uuid.UUID, depth int)
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"net/http"
"regexp"
"strings"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// An organization's own incident statuses, next to the built-in ones.
var hexColor = regexp.MustCompile(`^#[0-9a-f]{6}$`)
type incidentStatusRequest struct {
Name string `json:"name" binding:"required,max=40"`
Color string `json:"color" binding:"required,max=7"`
}
type incidentStatusView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
}
// validStatusRequest normalizes req and reports whether it is usable.
func validStatusRequest(c *gin.Context, req *incidentStatusRequest) bool {
req.Name, req.Color = strings.TrimSpace(req.Name), strings.ToLower(strings.TrimSpace(req.Color))
if req.Name == "" || !hexColor.MatchString(req.Color) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return false
}
return true
}
func (s *Server) listIncidentStatuses(c *gin.Context) {
ctx := c.Request.Context()
var rows []store.IncidentStatus
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidentStatuses(ctx)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]incidentStatusView, len(rows))
for i, r := range rows {
out[i] = incidentStatusView{ID: r.ID, Name: r.Name, Color: r.Color}
}
c.JSON(http.StatusOK, gin.H{"statuses": out})
}
func (s *Server) createIncidentStatus(c *gin.Context) {
var req incidentStatusRequest
if !bind(c, &req) || !validStatusRequest(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
var row store.IncidentStatus
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.CreateIncidentStatus(ctx, store.CreateIncidentStatusParams{OrgID: p.Org.ID, Name: req.Name, Color: req.Color})
return err
})
if isUniqueViolation(err, "incident_statuses_org_id_name_key") {
fail(c, http.StatusConflict, "status_name_taken")
return
}
if err != nil {
internalError(c, err)
return
}
auditDetail(c, "name", req.Name)
c.JSON(http.StatusCreated, incidentStatusView{ID: row.ID, Name: row.Name, Color: row.Color})
}
// updateIncidentStatus renames or recolors a status, also in the history
// of incidents that used it.
func (s *Server) updateIncidentStatus(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req incidentStatusRequest
if !bind(c, &req) || !validStatusRequest(c, &req) {
return
}
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
n, err = q.UpdateIncidentStatus(ctx, store.UpdateIncidentStatusParams{ID: id, Name: req.Name, Color: req.Color})
return err
})
switch {
case isUniqueViolation(err, "incident_statuses_org_id_name_key"):
fail(c, http.StatusConflict, "status_name_taken")
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
auditDetail(c, "name", req.Name)
c.Status(http.StatusNoContent)
}
}
// deleteIncidentStatus removes a status nobody used yet; history keeps
// the ones in use.
func (s *Server) deleteIncidentStatus(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.DeleteIncidentStatus(ctx, id)
return err
})
switch {
case isForeignKeyViolation(err):
fail(c, http.StatusConflict, "status_in_use")
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
c.Status(http.StatusNoContent)
}
}
func (s *Server) incidentStatusesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.IncidentStatus
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidentStatuses(ctx)
return err
}); err != nil {
return nil, err
}
v := make([]web.CustomIncidentStatus, len(rows))
for i, r := range rows {
v[i] = web.CustomIncidentStatus{ID: r.ID.String(), Name: r.Name, Color: r.Color}
}
return web.IncidentStatusesPage(page, me, v, p.Grants.Can(authz.OrgManage)), nil
}
+375
View File
@@ -0,0 +1,375 @@
package api
import (
"context"
"errors"
"net/http"
"slices"
"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/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Incidents open and close with their monitor. People explain them with a
// title, a status and updates, public on status pages or internal notes.
// Statuses are the built-in ones or the organization's own, with a color.
// customStatuses are an organization's own statuses by ID.
type customStatuses map[uuid.UUID]store.IncidentStatus
func loadCustomStatuses(ctx context.Context, q *store.Queries) (customStatuses, error) {
rows, err := q.ListIncidentStatuses(ctx)
out := customStatuses{}
for _, r := range rows {
out[r.ID] = r
}
return out, err
}
// info describes a stored status: a built-in key, or custom with the
// status named by id.
func (cs customStatuses) info(key *string, id *uuid.UUID) web.IncidentStatusInfo {
if key == nil {
return web.IncidentStatusInfo{}
}
if *key == "custom" && id != nil {
st := cs[*id]
return web.IncidentStatusInfo{Key: "custom", Name: st.Name, Color: st.Color}
}
return web.IncidentStatusInfo{Key: *key}
}
// list returns the statuses for a form, by name.
func (cs customStatuses) list() []web.CustomIncidentStatus {
out := make([]web.CustomIncidentStatus, 0, len(cs))
for _, st := range cs {
out = append(out, web.CustomIncidentStatus{ID: st.ID.String(), Name: st.Name, Color: st.Color})
}
slices.SortFunc(out, func(a, b web.CustomIncidentStatus) int { return strings.Compare(a.Name, b.Name) })
return out
}
// of is what an incident shows: resolved once its monitor recovered,
// otherwise the status of its latest update, empty before one.
func (cs customStatuses) of(i store.Incident) web.IncidentStatusInfo {
if i.ResolvedAt != nil {
return web.IncidentStatusInfo{Key: "resolved"}
}
return cs.info(i.Status, i.StatusID)
}
// statusFields are a status in API responses.
type statusFields struct {
// Status is investigating, identified, monitoring, resolved or custom.
Status string `json:"status"`
// StatusID, StatusName and StatusColor describe a custom status.
StatusID *uuid.UUID `json:"status_id,omitempty"`
StatusName string `json:"status_name,omitempty"`
StatusColor string `json:"status_color,omitempty"`
}
func toStatusFields(info web.IncidentStatusInfo, id *uuid.UUID) statusFields {
f := statusFields{Status: info.Key}
if info.Key == "custom" {
f.StatusID, f.StatusName, f.StatusColor = id, info.Name, info.Color
}
return f
}
type incidentUpdateView struct {
ID uuid.UUID `json:"id"`
statusFields
Message string `json:"message"`
Public bool `json:"public"`
Author string `json:"author"`
CreatedAt time.Time `json:"created_at"`
}
type incidentDetailView struct {
ID uuid.UUID `json:"id"`
MonitorID uuid.UUID `json:"monitor_id"`
Monitor string `json:"monitor"`
Title string `json:"title"`
statusFields
StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"`
Updates []incidentUpdateView `json:"updates"`
}
// incidentData is an incident with its updates and the organization's
// statuses.
type incidentData struct {
inc store.GetIncidentRow
updates []store.ListIncidentUpdatesRow
statuses customStatuses
}
// loadIncident reads the incident of the request.
func (s *Server) loadIncident(c *gin.Context) (incidentData, bool) {
var d incidentData
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return d, false
}
ctx := c.Request.Context()
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
if d.inc, err = q.GetIncident(ctx, id); err != nil {
return err
}
if d.updates, err = q.ListIncidentUpdates(ctx, id); err != nil {
return err
}
d.statuses, err = loadCustomStatuses(ctx, q)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return d, false
}
if err != nil {
internalError(c, err)
return d, false
}
return d, true
}
func incidentOf(r store.GetIncidentRow) store.Incident {
return store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt,
Cause: r.Cause, Title: r.Title, Status: r.Status, StatusID: r.StatusID,
}
}
func (d incidentData) view() incidentDetailView {
inc := incidentOf(d.inc)
v := incidentDetailView{
ID: inc.ID, MonitorID: inc.MonitorID, Monitor: d.inc.MonitorName, Title: inc.Title,
statusFields: toStatusFields(d.statuses.of(inc), inc.StatusID), StartedAt: inc.StartedAt, ResolvedAt: inc.ResolvedAt,
Updates: []incidentUpdateView{},
}
for _, u := range d.updates {
v.Updates = append(v.Updates, incidentUpdateView{
ID: u.ID, statusFields: toStatusFields(d.statuses.info(&u.Status, u.StatusID), u.StatusID),
Message: u.Message, Public: u.Public, Author: u.AuthorName, CreatedAt: u.CreatedAt,
})
}
return v
}
func (s *Server) getIncident(c *gin.Context) {
if d, ok := s.loadIncident(c); ok {
c.JSON(http.StatusOK, d.view())
}
}
// mayWriteIncident checks incidents.write for the incident's monitor,
// which roles limited to monitor groups grant too.
func (s *Server) mayWriteIncident(c *gin.Context, inc store.GetIncidentRow) bool {
p := current(c)
t, err := s.loadGroupTree(c.Request.Context(), p.scope())
if err != nil {
internalError(c, err)
return false
}
if !canInGroup(p, authz.IncidentsWrite, t, inc.MonitorGroupID) {
fail(c, http.StatusForbidden, "forbidden")
return false
}
return true
}
type incidentTitleRequest struct {
Title string `json:"title" binding:"max=200"`
}
// setIncidentTitle names the incident, e.g. on status pages; empty shows
// the monitor's name.
func (s *Server) setIncidentTitle(c *gin.Context) {
var req incidentTitleRequest
if !bind(c, &req) {
return
}
d, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, d.inc) {
return
}
ctx := c.Request.Context()
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
_, err := q.SetIncidentTitle(ctx, store.SetIncidentTitleParams{ID: d.inc.ID, Title: strings.TrimSpace(req.Title)})
return err
}); err != nil {
internalError(c, err)
return
}
auditDetail(c, "incident_id", d.inc.ID.String())
c.Status(http.StatusNoContent)
}
type incidentUpdateRequest struct {
// Status is a built-in status or the ID of a custom one.
Status string `json:"status" binding:"required"`
// Message is Markdown; empty just changes the status.
Message string `json:"message" binding:"max=5000"`
// Public shows the update on status pages; otherwise it is an internal
// note. Defaults to public.
Public *bool `json:"public"`
}
// addIncidentUpdate tells what is going on: a status and, usually, a
// message.
func (s *Server) addIncidentUpdate(c *gin.Context) {
var req incidentUpdateRequest
if !bind(c, &req) {
return
}
req.Message = strings.TrimSpace(req.Message)
d, ok := s.loadIncident(c)
if !ok {
return
}
key, statusID := req.Status, (*uuid.UUID)(nil)
if id, err := uuid.Parse(req.Status); err == nil {
if _, ok := d.statuses[id]; !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
key, statusID = "custom", &id
}
if statusID == nil && !slices.Contains(web.IncidentStatuses, key) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
if !s.mayWriteIncident(c, d.inc) {
return
}
public := req.Public == nil || *req.Public
p := current(c)
var author *uuid.UUID
if p.Session != nil {
author = &p.UserID
}
ctx := c.Request.Context()
var u store.IncidentUpdate
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
u, err = q.AddIncidentUpdate(ctx, store.AddIncidentUpdateParams{
OrgID: p.Org.ID, IncidentID: d.inc.ID, Status: key, StatusID: statusID, Message: req.Message, Public: public, AuthorID: author,
})
if err != nil {
return err
}
return q.RefreshIncidentStatus(ctx, d.inc.ID)
}); err != nil {
internalError(c, err)
return
}
auditDetail(c, "incident_id", d.inc.ID.String())
auditDetail(c, "status", req.Status)
c.JSON(http.StatusCreated, incidentUpdateView{
ID: u.ID, statusFields: toStatusFields(d.statuses.info(&u.Status, u.StatusID), u.StatusID),
Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt,
})
}
func (s *Server) deleteIncidentUpdate(c *gin.Context) {
update, err := uuid.Parse(c.Param("update"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
d, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, d.inc) {
return
}
ctx := c.Request.Context()
var n int64
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
if n, err = q.DeleteIncidentUpdate(ctx, store.DeleteIncidentUpdateParams{ID: update, IncidentID: d.inc.ID}); err != nil || n == 0 {
return err
}
return q.RefreshIncidentStatus(ctx, d.inc.ID)
}); err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
auditDetail(c, "incident_id", d.inc.ID.String())
c.Status(http.StatusNoContent)
}
// incidentDetailView is the console page of one incident.
func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
c.Set(ctxPrincipal, p)
d, ok := s.loadIncident(c)
if !ok {
return nil, errAborted
}
ctx := c.Request.Context()
md, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
if err != nil {
return nil, err
}
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
return nil, err
}
inc := incidentOf(d.inc)
v := web.IncidentDetailView{
Row: md.incidentRow(inc, d.inc.MonitorName),
CanWrite: canInGroup(p, authz.IncidentsWrite, t, d.inc.MonitorGroupID),
}
// Newest first; the monitor's own events among the updates.
type entry struct {
at time.Time
e web.IncidentTimelineEntry
}
entries := []entry{{inc.StartedAt, web.IncidentTimelineEntry{Kind: "started"}}}
if inc.ResolvedAt != nil {
entries = append(entries, entry{*inc.ResolvedAt, web.IncidentTimelineEntry{Kind: "resolved"}})
}
for _, u := range d.updates {
html, err := web.RenderMarkdown(u.Message)
if err != nil {
return nil, err
}
entries = append(entries, entry{u.CreatedAt, web.IncidentTimelineEntry{
Kind: "update", ID: u.ID.String(), Status: d.statuses.info(&u.Status, u.StatusID), HTML: html,
Author: u.AuthorName, Public: u.Public,
}})
}
slices.SortStableFunc(entries, func(a, b entry) int { return b.at.Compare(a.at) })
for _, x := range entries {
x.e.At = x.at.UTC().Format(timeLayout)
v.Timeline = append(v.Timeline, x.e)
}
v.NextStatus = nextIncidentStatus(inc)
v.Custom = d.statuses.list()
return web.IncidentDetailPage(page, me, v), nil
}
// nextIncidentStatus suggests the status of the next update: one built-in
// step further, the same custom status, resolved at the end.
func nextIncidentStatus(inc store.Incident) string {
switch {
case inc.Status == nil:
return web.IncidentStatuses[0]
case *inc.Status == "custom" && inc.StatusID != nil:
return inc.StatusID.String()
}
i := slices.Index(web.IncidentStatuses, *inc.Status)
return web.IncidentStatuses[min(i+1, len(web.IncidentStatuses)-1)]
}
+202
View File
@@ -0,0 +1,202 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestIncidentUpdates(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
owner := e.browser(t)
owner.signup("o@"+uniq("iu")+".test", uniq("iu-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Login", "type": "heartbeat", "interval_seconds": 3600})
monitorID := m["id"].(string)
slug := uniq("iup-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme"})
pageID := page["id"].(string)
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme", "published": true})
if st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}}); st != http.StatusNoContent && st != http.StatusOK {
t.Fatalf("list monitor on page = %d %v", st, body)
}
var incident uuid.UUID
if err := e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, cause)
SELECT org_id, id, now() - interval '10 minutes', '{}' FROM monitors WHERE id = $1 RETURNING id`, monitorID).Scan(&incident)
}); err != nil {
t.Fatal(err)
}
base := "/api/v1/org/incidents/" + incident.String()
status := func() string {
_, body := owner.do("GET", base, nil)
s, _ := body["status"].(string)
return s
}
if s := status(); s != "" {
t.Errorf("status before any update = %q", s)
}
// Updates with a status, public or internal, and a title.
st, body := owner.do("POST", base+"/updates", map[string]any{"status": "panicking", "message": "x"})
expect(t, "invalid status", st, body, http.StatusUnprocessableEntity, "invalid_input")
if st, body := owner.do("POST", base+"/updates", map[string]any{"status": "investigating", "message": "We are **looking** into it."}); st != http.StatusCreated {
t.Fatalf("post update = %d %v", st, body)
}
if st, body := owner.do("PATCH", base, map[string]any{"title": "Sign-in is slow"}); st != http.StatusNoContent {
t.Fatalf("set title = %d %v", st, body)
}
_, note := owner.do("POST", base+"/updates", map[string]any{"status": "identified", "message": "DB failover, ask Bob", "public": false})
if s := status(); s != "identified" {
t.Errorf("status = %q, want the latest update's", s)
}
_, list := owner.do("GET", "/api/v1/org/incidents", nil)
if first := list["incidents"].([]any)[0].(map[string]any); first["title"] != "Sign-in is slow" || first["status"] != "identified" {
t.Errorf("incident list = %v", first)
}
// Status pages show the title, the status and only public updates.
snap, err := e.statuspageClient(t, nil).Page(ctx, "", slug)
if err != nil {
t.Fatal(err)
}
var shown agentapi.PageIncident
for _, i := range snap.Incidents {
if i.Component == "Login" {
shown = i
}
}
if shown.Title != "Sign-in is slow" || shown.Status != "identified" || len(shown.Updates) != 1 || !strings.Contains(shown.Updates[0].Message, "looking") {
t.Errorf("status page incident = %+v", shown)
}
// The console page tells the story, internal notes marked.
_, _, html := owner.page("/incidents/" + incident.String())
for _, want := range []string{"Sign-in is slow", "<strong>looking</strong>", "DB failover", ">internal<", "Post update", "Outage began"} {
if !strings.Contains(html, want) {
t.Errorf("incident page lacks %q", want)
}
}
// Readers read, writers write.
viewer := e.joinVia(t, owner.invite("v@"+uniq("iu")+".test", owner.roleID("viewer")))
if st, _ := viewer.do("GET", base, nil); st != http.StatusOK {
t.Errorf("viewer reads incident = %d", st)
}
st, body = viewer.do("POST", base+"/updates", map[string]any{"status": "monitoring", "message": "x"})
expect(t, "viewer posts update", st, body, http.StatusForbidden, "forbidden")
// The incident list sets the status right there, for writers only.
if _, _, html := owner.page("/incidents"); !strings.Contains(html, "Set status") || !strings.Contains(html, `data-api="/org/incidents/`+incident.String()+`/updates"`) {
t.Error("the incident list lacks the set-status button")
}
if _, _, html := viewer.page("/incidents"); strings.Contains(html, "Set status") {
t.Error("the viewer is offered setting the status")
}
if _, _, html := viewer.page("/incidents/" + incident.String()); strings.Contains(html, "Post update") {
t.Error("the viewer is offered the update form")
}
// A status change needs no message.
_, quick := owner.do("POST", base+"/updates", map[string]any{"status": "monitoring", "message": "", "public": true})
if quick["status"] != "monitoring" || status() != "monitoring" {
t.Errorf("status-only update = %v", quick)
}
owner.do("DELETE", base+"/updates/"+quick["id"].(string), nil)
// Deleting an update falls back to the previous status; the monitor
// recovering resolves the incident whatever was said.
if st, _ := owner.do("DELETE", base+"/updates/"+note["id"].(string), nil); st != http.StatusNoContent || status() != "investigating" {
t.Errorf("after deleting the latest update status = %q", status())
}
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE incidents SET resolved_at = $2 WHERE id = $1`, incident, time.Now())
return err
}); err != nil {
t.Fatal(err)
}
if s := status(); s != "resolved" {
t.Errorf("status after recovery = %q", s)
}
if st, _ := owner.do("GET", "/api/v1/org/incidents/"+uuid.NewString(), nil); st != http.StatusNotFound {
t.Errorf("unknown incident = %d", st)
}
}
func TestCustomIncidentStatuses(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
owner := e.browser(t)
owner.signup("o@"+uniq("cis")+".test", uniq("cis-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "heartbeat", "interval_seconds": 3600})
monitorID := m["id"].(string)
slug := uniq("cisp-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme"})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Acme", "published": true})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}})
var incident uuid.UUID
if err := e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, cause)
SELECT org_id, id, now() - interval '10 minutes', '{}' FROM monitors WHERE id = $1 RETURNING id`, monitorID).Scan(&incident)
}); err != nil {
t.Fatal(err)
}
for _, bad := range []map[string]any{{"name": "x", "color": "red"}, {"name": " ", "color": "#7c3aed"}} {
st, body := owner.do("POST", "/api/v1/org/incident-statuses", bad)
expect(t, "invalid status", st, body, http.StatusUnprocessableEntity, "invalid_input")
}
st, status := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Waiting for provider", "color": "#7C3AED"})
if st != http.StatusCreated || status["color"] != "#7c3aed" {
t.Fatalf("create status = %d %v", st, status)
}
id := status["id"].(string)
st, body := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Waiting for provider", "color": "#000000"})
expect(t, "duplicate name", st, body, http.StatusConflict, "status_name_taken")
viewer := e.joinVia(t, owner.invite("v@"+uniq("cis")+".test", owner.roleID("viewer")))
st, body = viewer.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Mine", "color": "#000000"})
expect(t, "viewer adds a status", st, body, http.StatusForbidden, "forbidden")
// Updates use it by its ID; it shows with name and color.
base := "/api/v1/org/incidents/" + incident.String()
if st, body := owner.do("POST", base+"/updates", map[string]any{"status": id, "message": "Provider is on it."}); st != http.StatusCreated || body["status_name"] != "Waiting for provider" {
t.Fatalf("update with own status = %d %v", st, body)
}
st, body = owner.do("POST", base+"/updates", map[string]any{"status": uuid.NewString(), "message": "x"})
expect(t, "update with an unknown status", st, body, http.StatusUnprocessableEntity, "invalid_input")
if _, inc := owner.do("GET", base, nil); inc["status"] != "custom" || inc["status_id"] != id || inc["status_color"] != "#7c3aed" {
t.Errorf("incident = %v", inc)
}
snap, err := e.statuspageClient(t, nil).Page(ctx, "", slug)
if err != nil {
t.Fatal(err)
}
if len(snap.Incidents) == 0 || snap.Incidents[0].StatusName != "Waiting for provider" || snap.Incidents[0].Updates[0].StatusColor != "#7c3aed" {
t.Errorf("status page incidents = %+v", snap.Incidents)
}
_, _, html := owner.page("/incidents/" + incident.String())
if !strings.Contains(html, "background-color:#7c3aed") || !strings.Contains(html, `<option value="`+id+`" selected`) {
t.Error("the incident page lacks the own status or does not preselect it")
}
if _, _, html := owner.page("/settings/incident-statuses"); !strings.Contains(html, "Waiting for provider") || !strings.Contains(html, "Investigating") {
t.Error("the settings page lacks the statuses")
}
// Renaming carries into the history; a status in use stays.
owner.do("PUT", "/api/v1/org/incident-statuses/"+id, map[string]any{"name": "Provider working", "color": "#0ea5e9"})
if _, inc := owner.do("GET", base, nil); inc["status_name"] != "Provider working" {
t.Errorf("after renaming = %v", inc["status_name"])
}
st, body = owner.do("DELETE", "/api/v1/org/incident-statuses/"+id, nil)
expect(t, "delete a status in use", st, body, http.StatusConflict, "status_in_use")
_, unused := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Unused", "color": "#111111"})
if st, _ := owner.do("DELETE", "/api/v1/org/incident-statuses/"+unused["id"].(string), nil); st != http.StatusNoContent {
t.Errorf("delete an unused status = %d", st)
}
}
+15
View File
@@ -246,6 +246,8 @@ func (s *Server) acceptInvitation(c *gin.Context) {
type inviteSignupRequest struct { type inviteSignupRequest struct {
DisplayName string `json:"display_name" binding:"max=200"` DisplayName string `json:"display_name" binding:"max=200"`
Password string `json:"password" binding:"required,max=1024"` Password string `json:"password" binding:"required,max=1024"`
Consent bool `json:"consent"`
ConsentVersions string `json:"consent_versions" binding:"max=200"`
} }
// inviteSignup creates an account for an invited address. It bypasses // inviteSignup creates an account for an invited address. It bypasses
@@ -268,6 +270,10 @@ func (s *Server) inviteSignup(c *gin.Context) {
fail(c, http.StatusGone, "invitation_invalid") fail(c, http.StatusGone, "invitation_invalid")
return return
} }
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
hash, err := auth.HashPassword(req.Password) hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) { if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength) fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
@@ -288,6 +294,11 @@ func (s *Server) inviteSignup(c *gin.Context) {
}) })
return err return err
}) })
if err == nil {
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
return recordConsent(ctx, q, user.ID, consent)
})
}
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") { if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
fail(c, http.StatusConflict, "email_taken") fail(c, http.StatusConflict, "email_taken")
return return
@@ -341,5 +352,9 @@ func (s *Server) invitePage(c *gin.Context) {
} }
} }
} }
if view.Consent, err = s.signupConsentView(ctx); err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view)) web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view))
} }
+34 -11
View File
@@ -51,11 +51,20 @@ func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc {
return docs return docs
} }
func validLegalKind(kind string) bool { return slices.Contains(web.LegalKinds, kind) } // legalKinds are the documents org (nil: the platform) can set.
func legalKinds(org *uuid.UUID) []string {
if org == nil {
return web.LegalKinds
}
return web.OrgLegalKinds
}
type legalRequest struct { type legalRequest struct {
URL string `json:"url" binding:"max=2000"` URL string `json:"url" binding:"max=2000"`
Markdown string `json:"markdown" binding:"max=100000"` Markdown string `json:"markdown" binding:"max=100000"`
// NewVersion asks every account to accept the platform's privacy
// policy or terms again.
NewVersion bool `json:"new_version"`
} }
// validLegalURL accepts absolute http and https URLs only, so a stored link // validLegalURL accepts absolute http and https URLs only, so a stored link
@@ -69,7 +78,7 @@ func validLegalURL(raw string) bool {
// nil for the platform. // nil for the platform.
func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool { func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool {
kind := c.Param("kind") kind := c.Param("kind")
if !validLegalKind(kind) { if !slices.Contains(legalKinds(org), kind) {
fail(c, http.StatusNotFound, "not_found") fail(c, http.StatusNotFound, "not_found")
return false return false
} }
@@ -83,12 +92,16 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b
return false return false
} }
auditDetail(c, "kind", kind) auditDetail(c, "kind", kind)
newVersion := req.NewVersion && org == nil && slices.Contains(web.ConsentKinds, kind)
if newVersion {
auditDetail(c, "new_version", "true")
}
ctx := c.Request.Context() ctx := c.Request.Context()
err := s.db.Tx(ctx, scope, func(q *store.Queries) error { err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
if req.URL == "" && req.Markdown == "" { if req.URL == "" && req.Markdown == "" {
return q.DeleteLegalDocument(ctx, store.DeleteLegalDocumentParams{OrgID: org, Kind: kind}) return q.DeleteLegalDocument(ctx, store.DeleteLegalDocumentParams{OrgID: org, Kind: kind})
} }
return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown}) return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown, NewVersion: newVersion})
}) })
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
@@ -100,8 +113,11 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b
func (s *Server) adminSaveLegal(c *gin.Context) { func (s *Server) adminSaveLegal(c *gin.Context) {
if s.saveLegal(c, tenant.System(), nil) { if s.saveLegal(c, tenant.System(), nil) {
if err := s.legal.bump(c.Request.Context(), s.rdb); err != nil { ctx := c.Request.Context()
s.log.ErrorContext(c.Request.Context(), "announcing legal document change failed", "error", err) for _, err := range []error{s.legal.bump(ctx, s.rdb), s.consent.bump(ctx, s.rdb)} {
if err != nil {
s.log.ErrorContext(ctx, "announcing legal document change failed", "error", err)
}
} }
} }
} }
@@ -115,6 +131,8 @@ type legalView struct {
Kind string `json:"kind"` Kind string `json:"kind"`
URL string `json:"url"` URL string `json:"url"`
Markdown string `json:"markdown"` Markdown string `json:"markdown"`
// Version changes whenever accounts have to accept the document again.
Version int64 `json:"version,omitempty"`
} }
// ownLegal returns the documents stored for org (nil: the platform), // ownLegal returns the documents stored for org (nil: the platform),
@@ -126,12 +144,15 @@ func (s *Server) ownLegal(ctx context.Context, scope tenant.Scope, org *uuid.UUI
rows, err = q.LegalDocuments(ctx, org) rows, err = q.LegalDocuments(ctx, org)
return err return err
}) })
out := make([]legalView, 0, len(web.LegalKinds)) out := make([]legalView, 0, len(legalKinds(org)))
for _, kind := range web.LegalKinds { for _, kind := range legalKinds(org) {
v := legalView{Kind: kind} v := legalView{Kind: kind}
for _, r := range rows { for _, r := range rows {
if r.Kind == kind && (r.OrgID == nil) == (org == nil) { if r.Kind == kind && (r.OrgID == nil) == (org == nil) {
v.URL, v.Markdown = r.Url, r.Markdown v.URL, v.Markdown = r.Url, r.Markdown
if org == nil && slices.Contains(web.ConsentKinds, kind) {
v.Version = r.Version
}
} }
} }
out = append(out, v) out = append(out, v)
@@ -190,10 +211,12 @@ func (s *Server) legalPage(c *gin.Context) {
c.Status(http.StatusNotFound) c.Status(http.StatusNotFound)
} }
func toLegalForms(docs []legalView) []web.LegalForm { // toLegalForms prepares the forms; the platform's privacy policy and terms
// can ask everyone to accept them again.
func toLegalForms(docs []legalView, platform bool) []web.LegalForm {
out := make([]web.LegalForm, len(docs)) out := make([]web.LegalForm, len(docs))
for i, d := range docs { for i, d := range docs {
out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown} out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown, Consent: platform && slices.Contains(web.ConsentKinds, d.Kind)}
} }
return out return out
} }
@@ -203,7 +226,7 @@ func (s *Server) orgLegalView(c *gin.Context, p *principal, page web.Page, me we
if err != nil { if err != nil {
return nil, err return nil, err
} }
return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs)), nil return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs, false)), nil
} }
func (s *Server) adminLegalPage(c *gin.Context) { func (s *Server) adminLegalPage(c *gin.Context) {
@@ -216,5 +239,5 @@ func (s *Server) adminLegalPage(c *gin.Context) {
internalError(c, err) internalError(c, err)
return return
} }
web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs))) web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs, true)))
} }
+15 -7
View File
@@ -21,11 +21,7 @@ func TestLegalDocuments(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { t.Cleanup(func() { clearPlatformLegal(admin) })
for _, kind := range []string{"imprint", "privacy"} {
admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{})
}
})
imprint := "# Impressum\n\nBetreiber GmbH <script>alert(1)</script>" imprint := "# Impressum\n\nBetreiber GmbH <script>alert(1)</script>"
st, body := admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": imprint}) st, body := admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": imprint})
@@ -34,7 +30,8 @@ func TestLegalDocuments(t *testing.T) {
expect(t, "javascript link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url") expect(t, "javascript link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "https://operator.example/privacy"}) st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "https://operator.example/privacy"})
expect(t, "admin sets privacy link", st, body, http.StatusNoContent, "") expect(t, "admin sets privacy link", st, body, http.StatusNoContent, "")
st, body = admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "x"}) admin.acceptConsent()
st, body = admin.do("PUT", "/api/v1/admin/legal/cookies", map[string]any{"markdown": "x"})
expect(t, "unknown kind", st, body, http.StatusNotFound, "not_found") expect(t, "unknown kind", st, body, http.StatusNotFound, "not_found")
// The console footer links them, also before signing in. // The console footer links them, also before signing in.
@@ -121,7 +118,7 @@ func TestLegalChangeReachesOtherReplicas(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) }) t.Cleanup(func() { clearPlatformLegal(admin) })
admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{})
visitor := b.browser(t) visitor := b.browser(t)
@@ -147,3 +144,14 @@ func TestMarkdownPreview(t *testing.T) {
t.Errorf("preview = %d %q", st, html) t.Errorf("preview = %d %q", st, html)
} }
} }
// clearPlatformLegal removes the platform's documents again, so other tests
// sign up without consent.
func clearPlatformLegal(admin *browser) {
admin.acceptConsent()
for _, kind := range []string{"imprint", "privacy", "terms"} {
if st, body := admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{}); st != http.StatusNoContent {
admin.t.Errorf("clearing platform %s = %d %v", kind, st, body)
}
}
}
+79
View File
@@ -3,6 +3,7 @@ package api
import ( import (
"errors" "errors"
"net/http" "net/http"
"slices"
"strings" "strings"
"time" "time"
@@ -495,3 +496,81 @@ func (s *Server) updatePolicy(c *gin.Context) {
} }
var errNoSSOProvider = errors.New("api: no enabled sso provider") var errNoSSOProvider = errors.New("api: no enabled sso provider")
// adminRole is the built-in Admin role.
var adminRole = uuid.MustParse("00000000-0000-0000-0000-00000000a001")
type ownerRequest struct {
Owner bool `json:"owner"`
}
// setOwner makes a member an owner or takes it back, the actor's own
// ownership included: handing an organization over is making someone else
// owner and stepping down. Only owners decide, and the last owner stays.
// A former owner without roles keeps working as Admin.
func (s *Server) setOwner(c *gin.Context) {
target, err := uuid.Parse(c.Param("user"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req ownerRequest
if !bind(c, &req) {
return
}
p := current(c)
if !p.Grants.Owner {
fail(c, http.StatusForbidden, "owner_only")
return
}
auditDetail(c, "user_id", target.String())
auditDetail(c, "owner", req.Owner)
ctx := c.Request.Context()
var code string
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if err := q.LockOrgOwners(ctx, p.Org.ID); err != nil {
return err
}
m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: p.Org.ID, UserID: target})
switch {
case errors.Is(err, pgx.ErrNoRows):
code = "not_found"
return nil
case err != nil:
return err
case m.IsOwner == req.Owner:
return nil
}
if !req.Owner {
n, err := q.CountOwners(ctx, p.Org.ID)
if err != nil {
return err
}
if n <= 1 {
code = "last_owner"
return nil
}
assigned, err := q.ListAssignments(ctx, p.Org.ID)
if err != nil {
return err
}
if !slices.ContainsFunc(assigned, func(a store.ListAssignmentsRow) bool { return a.UserID == target }) {
if _, err := q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: p.Org.ID, UserID: target, RoleID: adminRole}); err != nil {
return err
}
}
}
_, err = q.SetOwner(ctx, store.SetOwnerParams{OrgID: p.Org.ID, UserID: target, Owner: req.Owner})
return err
})
switch {
case err != nil:
internalError(c, err)
case code == "not_found":
fail(c, http.StatusNotFound, code)
case code != "":
fail(c, http.StatusConflict, code)
default:
c.Status(http.StatusNoContent)
}
}
+1 -8
View File
@@ -11,7 +11,6 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "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/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web" "git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -262,17 +261,11 @@ func (s *Server) adminDeleteUser(c *gin.Context) {
return return
} }
ctx := c.Request.Context() ctx := c.Request.Context()
shared, orgsDeleted, err := s.eraseAccount(ctx, u) orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return 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) auditDetail(c, "organizations_deleted", orgsDeleted)
c.Status(http.StatusNoContent) c.Status(http.StatusNoContent)
} }
+7 -9
View File
@@ -140,7 +140,8 @@ func TestModeration(t *testing.T) {
t.Error("a heartbeat after reinstatement is not recorded") t.Error("a heartbeat after reinstatement is not recorded")
} }
// A suspended account is signed out and kept out, tokens included. // A suspended account is signed out, its tokens stop working, and
// signing in again only lets it export or delete its data.
suspend("users/"+userID, true, "") suspend("users/"+userID, true, "")
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized { if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("session of a suspended account = %d", st) t.Errorf("session of a suspended account = %d", st)
@@ -149,8 +150,11 @@ func TestModeration(t *testing.T) {
t.Errorf("token of a suspended account = %d", st) t.Errorf("token of a suspended account = %d", st)
} }
fresh := e.browser(t) fresh := e.browser(t)
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}) if st, body := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended") t.Errorf("sign-in of a suspended account = %d %v", st, body)
}
st, body = fresh.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API 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 { 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") t.Error("a wrong password reveals the suspension")
} }
@@ -165,12 +169,6 @@ func TestModeration(t *testing.T) {
st, body = admin.do("DELETE", "/api/v1/admin/users/"+admin.userIDSelf().String(), nil) 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") 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. // Deleting: page, organization, account.
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() { if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
t.Errorf("delete page = %d", st) t.Errorf("delete page = %d", st)
+85
View File
@@ -0,0 +1,85 @@
package api_test
import (
"net/http"
"strings"
"testing"
"github.com/google/uuid"
)
func TestOwners(t *testing.T) {
e := newEnv(t)
first := e.browser(t)
first.signup("f@"+uniq("ow")+".test", uniq("ow-"))
org := uuid.MustParse(first.orgID())
firstID := first.userIDSelf()
second := e.joinVia(t, first.invite("s@"+uniq("ow")+".test", first.roleID("viewer")))
secondID := second.userIDSelf()
owner := func(b *browser, user uuid.UUID, on bool) (int, map[string]any) {
return b.do("PUT", "/api/v1/org/members/"+user.String()+"/owner", map[string]any{"owner": on})
}
isOwner := func(user uuid.UUID) bool {
return e.count(t, `SELECT count(*) FROM memberships WHERE org_id = $1 AND user_id = $2 AND is_owner`, org, user) == 1
}
// Only owners decide.
st, body := owner(second, secondID, true)
expect(t, "non-owner makes itself owner", st, body, http.StatusForbidden, "owner_only")
st, body = owner(first, firstID, false)
expect(t, "last owner steps down", st, body, http.StatusConflict, "last_owner")
if _, _, html := first.page("/settings/members"); !strings.Contains(html, "Make owner") || strings.Contains(html, "Step down as owner") {
t.Error("the members page offers the wrong owner actions to the only owner")
}
// Handing over: make someone else owner, then step down.
if st, body := owner(first, secondID, true); st != http.StatusNoContent || !isOwner(secondID) {
t.Fatalf("make owner = %d %v", st, body)
}
if st, _ := second.do("PUT", "/api/v1/org/legal/imprint", map[string]any{"markdown": "# Impressum"}); st != http.StatusNoContent {
t.Errorf("new owner manages the organization = %d", st)
}
if _, _, html := first.page("/settings/members"); !strings.Contains(html, "Step down as owner") || !strings.Contains(html, "Remove as owner") {
t.Error("with two owners the page offers neither stepping down nor removing")
}
st, body = first.do("DELETE", "/api/v1/org/members/"+secondID.String(), nil)
expect(t, "remove an owner", st, body, http.StatusForbidden, "owner_cannot_be_removed")
if st, body := owner(first, firstID, false); st != http.StatusNoContent || isOwner(firstID) {
t.Fatalf("step down = %d %v", st, body)
}
// The former owner keeps working as Admin.
if n := e.count(t, `SELECT count(*) FROM role_assignments WHERE org_id = $1 AND user_id = $2 AND role_id = '00000000-0000-0000-0000-00000000a001'`, org, firstID); n != 1 {
t.Errorf("former owner has %d admin assignments, want 1", n)
}
if st, _ := first.do("GET", "/api/v1/org/members", nil); st != http.StatusOK {
t.Errorf("former owner lists members = %d", st)
}
st, body = owner(first, firstID, true)
expect(t, "former owner takes ownership back", st, body, http.StatusForbidden, "owner_only")
st, body = owner(second, secondID, false)
expect(t, "the new last owner steps down", st, body, http.StatusConflict, "last_owner")
// Deleting an account leaves organizations with further owners and
// takes along those it is the last owner of.
if st, body := owner(second, firstID, true); st != http.StatusNoContent {
t.Fatalf("make owner again = %d %v", st, body)
}
if _, _, html := first.page("/settings/security"); strings.Contains(html, "last owner of these organizations") {
t.Error("an organization with another owner is announced as deleted")
}
if st, body := first.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("co-owner deletes account = %d %v", st, body)
}
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, org) != 1 || !isOwner(secondID) {
t.Fatal("the organization did not stay with its other owner")
}
if _, _, html := second.page("/settings/security"); !strings.Contains(html, "last owner of these organizations") {
t.Error("the last owner is not warned")
}
if st, body := second.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("last owner deletes account = %d %v", st, body)
}
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, org) != 0 {
t.Error("the organization survived its last owner")
}
}
+75 -10
View File
@@ -46,8 +46,16 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/admin/status-pages", s.adminStatusPagesPage) r.GET("/admin/status-pages", s.adminStatusPagesPage)
r.GET("/admin/orgs", s.adminOrgsPage) r.GET("/admin/orgs", s.adminOrgsPage)
r.GET("/admin/legal", s.adminLegalPage) r.GET("/admin/legal", s.adminLegalPage)
r.GET("/admin/support", s.adminSupportPage)
r.GET("/admin/support/:id", s.adminSupportTicketPage)
r.GET("/support", s.supportPage)
r.GET("/support/:id", s.supportTicketPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView)) r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/incidents/:id", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentDetailView))
r.GET("/settings/incident-statuses", s.orgPage("incident_statuses.title", authz.IncidentsRead, s.incidentStatusesView))
r.GET("/legal/:kind", s.legalPage) r.GET("/legal/:kind", s.legalPage)
r.GET("/consent", s.consentPage)
r.GET("/account/suspended", s.suspendedPage)
} }
// flashErrors lists the codes a redirect may ask a page to display. Anything // flashErrors lists the codes a redirect may ask a page to display. Anything
@@ -56,6 +64,7 @@ var flashErrors = map[ssoError]bool{
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true, "sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true, "sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true, "sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
"sso_email_unverified": true, "signup_limit": true,
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true, "totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
} }
@@ -88,25 +97,46 @@ func (s *Server) loginPage(c *gin.Context) {
c.Redirect(http.StatusSeeOther, next) c.Redirect(http.StatusSeeOther, next)
return return
} }
allowed, err := s.signupAllowed(c.Request.Context()) email, signupProviders, err := s.signupOptions(c.Request.Context())
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
} }
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next)) allowed := email || len(signupProviders) > 0
providers := s.platformButtons(c.Request.Context(), false)
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next, providers, c.Query("mfa") == "1"))
}
// signupOptions tells whether people may sign up with email, and which
// providers they may sign up through.
func (s *Server) signupOptions(ctx context.Context) (bool, []web.IDPButton, error) {
email, err := s.signupAllowed(ctx)
if err != nil {
return false, nil, err
}
mode, err := s.signupModeAllows(ctx)
if err != nil || !mode {
return email, nil, err
}
return email, s.platformButtons(ctx, true), nil
} }
func (s *Server) signupPage(c *gin.Context) { func (s *Server) signupPage(c *gin.Context) {
allowed, err := s.signupAllowed(c.Request.Context()) email, providers, err := s.signupOptions(c.Request.Context())
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
} }
if !allowed { if !email && len(providers) == 0 {
c.Redirect(http.StatusSeeOther, "/login") c.Redirect(http.StatusSeeOther, "/login")
return return
} }
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"))) consent, err := s.signupConsentView(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email, consent))
} }
func (s *Server) signupSentPage(c *gin.Context) { func (s *Server) signupSentPage(c *gin.Context) {
@@ -150,6 +180,7 @@ func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *princip
} }
me := toWebMe(m) me := toWebMe(m)
me.Can = map[string]bool{} me.Can = map[string]bool{}
me.Support = s.supportSettings(ctx).Enabled
if sess.OrgID == uuid.Nil { if sess.OrgID == uuid.Nil {
return me, nil, nil return me, nil, nil
} }
@@ -232,6 +263,10 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err) internalError(c, err)
return return
} }
if me.DeletesOrgs, err = s.lastOwnedOrgs(ctx, sess.UserID); err != nil {
internalError(c, err)
return
}
var ( var (
identities []web.Identity identities []web.Identity
canLink bool canLink bool
@@ -259,7 +294,29 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err) internalError(c, err)
return return
} }
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink, auditEntries(c, rows))) var platform web.PlatformIdentities
var linked []store.ListUserPlatformIdentitiesRow
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
linked, err = q.ListUserPlatformIdentities(ctx, sess.UserID)
return err
})
if err != nil {
internalError(c, err)
return
}
isLinked := map[string]bool{}
for _, l := range linked {
platform.Linked = append(platform.Linked, web.LinkedIdentity{ProviderID: l.ProviderID.String(), Name: l.ProviderName, Email: deref(l.Email)})
isLinked["/login/sso/"+l.ProviderID.String()] = true
}
for _, b := range s.platformButtons(ctx, false) {
if !isLinked[b.URL] {
b.URL += "?link=1"
platform.Available = append(platform.Available, b)
}
}
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink, auditEntries(c, rows), platform))
} }
func toWebRoles(rows []store.Role) []web.Role { func toWebRoles(rows []store.Role) []web.Role {
@@ -350,19 +407,26 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
var ( var (
roles []store.Role roles []store.Role
pending []store.ListPendingInvitationsRow pending []store.ListPendingInvitationsRow
owners int64
) )
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error var err error
if roles, err = q.ListRoles(ctx); err != nil { if roles, err = q.ListRoles(ctx); err != nil {
return err return err
} }
if owners, err = q.CountOwners(ctx, p.Org.ID); err != nil {
return err
}
pending, err = q.ListPendingInvitations(ctx) pending, err = q.ListPendingInvitations(ctx)
return err return err
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info)} v := web.MembersView{
CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info),
IsOwner: p.Grants.Owner, Self: p.UserID.String(), Owners: int(owners),
}
scopeNames, scopes, err := s.scopeOptions(ctx, p) scopeNames, scopes, err := s.scopeOptions(ctx, p)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -551,7 +615,7 @@ func (s *Server) adminPage(c *gin.Context) {
for _, t := range check.Types { for _, t := range check.Types {
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]}) 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)))) 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)), s.idpAdminView(ctx)))
} }
func (s *Server) adminStatusPagesPage(c *gin.Context) { func (s *Server) adminStatusPagesPage(c *gin.Context) {
@@ -589,7 +653,7 @@ func (s *Server) adminOrgsPage(c *gin.Context) {
} }
func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) { func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) {
v := web.RegionsView{APIBase: apiBase, Next: next} v := web.RegionsView{APIBase: apiBase, Next: next, Install: s.installView()}
never := i18n.T(ctx, "tokens.never") never := i18n.T(ctx, "tokens.never")
for _, r := range regions { for _, r := range regions {
n, err := s.sched.Instances(ctx, r.ID.String()) n, err := s.sched.Instances(ctx, r.ID.String())
@@ -607,7 +671,8 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
if a.LastSeenAt != nil { if a.LastSeenAt != nil {
seen = a.LastSeenAt.Format(time.DateTime) seen = a.LastSeenAt.Format(time.DateTime)
} }
wa := 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, Release: deref(a.Release)}
wa.Outdated = v.Install.Release != "" && wa.Release != "" && wa.Release != "dev" && wa.Release != v.Install.Release
if a.Kind == "checker" && a.OrgID != nil { if a.Kind == "checker" && a.OrgID != nil {
wa.AllowPrivate = &a.AllowPrivate wa.AllowPrivate = &a.AllowPrivate
} }
+5 -1
View File
@@ -26,7 +26,11 @@ func (b *browser) invite(email, roleID string) string {
func (e *env) joinVia(t *testing.T, tok string) *browser { func (e *env) joinVia(t *testing.T, tok string) *browser {
t.Helper() t.Helper()
b := e.browser(t) b := e.browser(t)
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{"password": password}) _, _, form := b.page("/invite/" + tok)
versions := consentShown(form)
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{
"password": password, "consent": versions != "", "consent_versions": versions,
})
if st != http.StatusOK { if st != http.StatusOK {
t.Fatalf("invite signup = %d %v, want 200", st, body) t.Fatalf("invite signup = %d %v, want 200", st, body)
} }
+572
View File
@@ -0,0 +1,572 @@
package api
import (
"context"
"encoding/json"
"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/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
"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 identity providers, such as Google or GitHub, let people sign
// up and sign in without a password. Accounts are reached only through
// identities stored by subject: an existing account with the provider's
// email is never taken over, its owner links the provider while signed in.
const githubServer = "https://github.com"
func (s *Server) platformIDP(row store.PlatformIdentityProvider) (sso.Provider, error) {
p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: []string{"openid", "email", "profile"}}
if row.Kind == sso.GitHub {
p.Kind = sso.GitHub
}
if row.ClientSecret != nil {
secret, err := s.keys.Open(row.ClientSecret, row.ID[:])
if err != nil {
return p, err
}
p.ClientSecret = string(secret)
}
return p, nil
}
func (s *Server) loadPlatformIDP(ctx context.Context, id uuid.UUID) (store.PlatformIdentityProvider, error) {
var row store.PlatformIdentityProvider
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
row, err = q.GetPlatformIDP(ctx, id)
return err
})
return row, err
}
// platformButtons lists the enabled providers for sign-in pages, only
// those open to sign-up if signup is set.
func (s *Server) platformButtons(ctx context.Context, signup bool) []web.IDPButton {
var rows []store.PlatformIdentityProvider
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
rows, err = q.ListPlatformIDPs(ctx)
return err
})
if err != nil {
s.log.WarnContext(ctx, "listing identity providers failed", "error", err)
return nil
}
var out []web.IDPButton
for _, r := range rows {
if r.Enabled && (!signup || r.AllowSignup) {
out = append(out, web.IDPButton{URL: "/login/sso/" + r.ID.String(), Name: r.Name, Kind: r.Kind})
}
}
return out
}
// platformSSOStart sends the browser to a platform provider, to sign in or,
// with ?link=1, to link it to the signed-in account.
func (s *Server) platformSSOStart(c *gin.Context) {
ctx := c.Request.Context()
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
return
}
var linkUser uuid.UUID
if c.Query("link") == "1" {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
linkUser = sess.UserID
}
id, err := uuid.Parse(c.Param("provider"))
if err != nil {
s.ssoAbort(c, linkUser, "sso_unavailable")
return
}
row, err := s.loadPlatformIDP(ctx, id)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
s.ssoAbort(c, linkUser, "sso_unavailable")
return
}
if err != nil {
internalError(c, err)
return
}
p, err := s.platformIDP(row)
if err != nil {
internalError(c, err)
return
}
flow := sso.NewFlow(auth.RandomToken)
authURL, err := s.sso.AuthURL(ctx, p, flow)
if err != nil {
s.log.WarnContext(ctx, "sso discovery failed", "provider", row.ID, "error", err)
s.ssoAbort(c, linkUser, "sso_provider_error")
return
}
state, _ := json.Marshal(ssoFlow{Provider: row.ID, Platform: true, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser})
if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil {
internalError(c, err)
return
}
setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds()))
c.Redirect(http.StatusFound, authURL)
}
// platformCallback finishes a platform provider's flow: linking, signing
// in through a stored identity, or signing up.
func (s *Server) platformCallback(c *gin.Context, f ssoFlow, state string) {
ctx := c.Request.Context()
row, err := s.loadPlatformIDP(ctx, f.Provider)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
s.ssoAbort(c, f.LinkUser, "sso_unavailable")
return
}
if err != nil {
internalError(c, err)
return
}
p, err := s.platformIDP(row)
if err != nil {
internalError(c, err)
return
}
claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code"))
if err != nil {
s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err)
s.ssoAbort(c, f.LinkUser, "sso_provider_error")
return
}
if f.LinkUser != uuid.Nil {
s.platformLink(c, row, f.LinkUser, claims)
return
}
userID, code, err := s.platformResolve(c, row, claims)
if err != nil {
internalError(c, err)
return
}
if code != "" {
s.ssoAbort(c, uuid.Nil, code)
return
}
user, err := s.loadUser(ctx, userID)
if err != nil {
internalError(c, err)
return
}
// Suspended accounts sign in too, but only to export or delete their
// data (accountGate).
// The account's second factor still applies; the provider replaces
// only the password.
if user.TotpSecret != nil {
token := auth.RandomToken()
if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil {
internalError(c, err)
return
}
setCookie(c, mfaCookie, token, int(mfaTTL.Seconds()))
c.Redirect(http.StatusSeeOther, "/login?mfa=1")
return
}
var orgs []store.ListUserOrgsRow
err = s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
orgs, err = q.ListUserOrgs(ctx, userID)
return err
})
if err != nil {
internalError(c, err)
return
}
var org uuid.UUID
if len(orgs) > 0 {
org = orgs[0].ID
}
if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(ctx, old)
}
sess, err := s.sessions.Create(ctx, auth.NewSession{UserID: userID, OrgID: org, Locale: cmpOr(deref(user.Locale), i18n.Lang(ctx)), Method: auth.MethodSSO})
if err != nil {
internalError(c, err)
return
}
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
s.writeAudit(c, store.InsertAuditEventParams{
Kind: "user", ActorUserID: &userID, Action: "auth.login_sso", TargetID: &row.ID, Status: http.StatusSeeOther,
}, map[string]any{"name": row.Name})
c.Redirect(http.StatusSeeOther, "/")
}
func cmpOr(a, b string) string {
if a != "" {
return a
}
return b
}
// signupModeAllows reports whether the sign-up mode lets a new account in,
// regardless of mail: providers confirm addresses themselves.
func (s *Server) signupModeAllows(ctx context.Context) (bool, error) {
switch s.cfg.Signup {
case config.SignupOpen:
return true, nil
case config.SignupFirstUser:
var exists bool
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
exists, err = q.AnyUserExists(ctx)
return err
})
return !exists, err
}
return false, nil
}
// platformResolve finds the account behind an identity or signs one up.
func (s *Server) platformResolve(c *gin.Context, row store.PlatformIdentityProvider, cl sso.Claims) (uuid.UUID, ssoError, error) {
ctx := c.Request.Context()
email := normalizeEmail(cl.Email)
var (
userID uuid.UUID
code ssoError
created bool
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
ident, err := q.GetPlatformIdentity(ctx, store.GetPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
if err == nil {
userID = ident.UserID
return q.TouchPlatformIdentity(ctx, store.TouchPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)})
}
if !errors.Is(err, pgx.ErrNoRows) {
return err
}
allowed, err := s.signupModeAllows(ctx)
switch {
case err != nil:
return err
case !row.AllowSignup || !allowed:
code = "sso_not_provisioned"
return nil
case email == "" || !cl.EmailVerified:
code = "sso_email_unverified"
return nil
}
if _, err := q.GetUserByEmail(ctx, email); err == nil {
code = "sso_link_required"
return nil
} else if !errors.Is(err, pgx.ErrNoRows) {
return err
}
if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken {
code = "sso_link_required"
return err
}
if left, err := s.signupsLeft(c); err != nil || !left {
code = "signup_limit"
return err
}
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
}
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
if err := q.MakeAdmin(ctx, u.ID); err != nil {
return err
}
}
userID, created = u.ID, true
return q.CreatePlatformIdentity(ctx, store.CreatePlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject, UserID: u.ID, Email: nonEmpty(email)})
})
if err == nil && created {
s.countSignup(c)
s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &userID, Action: "account.signup", TargetID: &row.ID, Status: http.StatusOK},
map[string]any{"via": row.Name})
}
return userID, code, err
}
func (s *Server) platformLink(c *gin.Context, row store.PlatformIdentityProvider, userID uuid.UUID, cl sso.Claims) {
ctx := c.Request.Context()
sess := auth.Current(c)
if sess == nil || sess.UserID != userID {
s.ssoAbort(c, uuid.Nil, "sso_expired")
return
}
var code ssoError
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
ident, err := q.GetPlatformIdentity(ctx, store.GetPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
switch {
case err == nil && ident.UserID == userID:
return nil
case err == nil:
code = "sso_identity_taken"
return nil
case !errors.Is(err, pgx.ErrNoRows):
return err
}
return q.CreatePlatformIdentity(ctx, store.CreatePlatformIdentityParams{
ProviderID: row.ID, Subject: cl.Subject, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)),
})
})
if err != nil {
internalError(c, err)
return
}
if code != "" {
s.ssoAbort(c, userID, code)
return
}
s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &userID, Action: "account.identity_link", TargetID: &row.ID, Status: http.StatusSeeOther},
map[string]any{"name": row.Name})
c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked")
}
// unlinkIdentity removes a platform provider from the account, unless it
// is the last way to sign in.
func (s *Server) unlinkIdentity(c *gin.Context) {
id, err := uuid.Parse(c.Param("provider"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
sess := auth.Current(c)
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
ways, err := q.CountUserSignIns(ctx, sess.UserID)
if err != nil {
return err
}
if ways <= 1 {
return errLastSignIn
}
n, err = q.DeletePlatformIdentity(ctx, store.DeletePlatformIdentityParams{UserID: sess.UserID, ProviderID: id})
return err
})
switch {
case errors.Is(err, errLastSignIn):
fail(c, http.StatusConflict, "last_sign_in")
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
c.Status(http.StatusNoContent)
}
}
var errLastSignIn = errors.New("api: last way to sign in")
// idpView is a platform identity provider; the secret is never returned.
type idpView struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Issuer string `json:"issuer"`
ClientID string `json:"client_id"`
SecretSet bool `json:"client_secret_set"`
AllowSignup bool `json:"allow_signup"`
Enabled bool `json:"enabled"`
}
func viewIDP(r store.PlatformIdentityProvider) idpView {
return idpView{r.ID, r.Kind, r.Name, r.Issuer, r.ClientID, r.ClientSecret != nil, r.AllowSignup, r.Enabled}
}
func (s *Server) adminListIDPs(c *gin.Context) {
ctx := c.Request.Context()
var rows []store.PlatformIdentityProvider
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListPlatformIDPs(ctx)
return err
})
if err != nil {
internalError(c, err)
return
}
out := make([]idpView, len(rows))
for i, r := range rows {
out[i] = viewIDP(r)
}
c.JSON(http.StatusOK, gin.H{"providers": out, "callback_url": s.sso.RedirectURL()})
}
// idpRequest registers a platform provider. Issuer is the OIDC issuer, or
// the GitHub server (default https://github.com). An empty secret on
// update keeps the stored one.
type idpRequest struct {
Kind string `json:"kind" binding:"required,oneof=oidc github"`
Name string `json:"name" binding:"required,max=100"`
Issuer string `json:"issuer" binding:"max=500"`
ClientID string `json:"client_id" binding:"required,max=500"`
ClientSecret string `json:"client_secret" binding:"max=2000"`
AllowSignup bool `json:"allow_signup"`
Enabled bool `json:"enabled"`
}
// checkIDP normalizes req and validates its server, contacting OIDC
// issuers so mistakes show when saving.
func (s *Server) checkIDP(c *gin.Context, req *idpRequest) bool {
req.Name, req.Issuer, req.ClientID = strings.TrimSpace(req.Name), strings.TrimSuffix(strings.TrimSpace(req.Issuer), "/"), strings.TrimSpace(req.ClientID)
if req.Kind == sso.GitHub && req.Issuer == "" {
req.Issuer = githubServer
}
var err error
if req.Kind == sso.GitHub {
err = s.sso.CheckURL(req.Issuer)
} else {
err = s.sso.ValidateIssuer(c.Request.Context(), req.Issuer)
}
if err != nil {
code := "sso_discovery_failed"
switch {
case errors.Is(err, sso.ErrInvalidIssuer):
code = "sso_invalid_issuer"
case errors.Is(err, sso.ErrForbiddenAddress):
code = "sso_forbidden_address"
}
fail(c, http.StatusUnprocessableEntity, code)
return false
}
return true
}
func (s *Server) adminCreateIDP(c *gin.Context) {
var req idpRequest
if !bind(c, &req) || !s.checkIDP(c, &req) {
return
}
ctx := c.Request.Context()
id := uuid.New()
var secret []byte
if req.ClientSecret != "" {
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
}
auditDetail(c, "name", req.Name)
var row store.PlatformIdentityProvider
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
row, err = q.CreatePlatformIDP(ctx, store.CreatePlatformIDPParams{
ID: id, Kind: req.Kind, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
ClientSecret: secret, AllowSignup: req.AllowSignup, Enabled: req.Enabled,
})
return err
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, viewIDP(row))
}
func (s *Server) adminUpdateIDP(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req idpRequest
if !bind(c, &req) || !s.checkIDP(c, &req) {
return
}
ctx := c.Request.Context()
var secret []byte
if req.ClientSecret != "" {
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
}
auditDetail(c, "name", req.Name)
var row store.PlatformIdentityProvider
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
old, err := q.GetPlatformIDP(ctx, id)
if err != nil {
return err
}
if old.Kind != req.Kind {
return errKindChange
}
row, err = q.UpdatePlatformIDP(ctx, store.UpdatePlatformIDPParams{
ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
ClientSecret: secret, AllowSignup: req.AllowSignup, Enabled: req.Enabled,
})
return err
})
switch {
case errors.Is(err, errKindChange):
fail(c, http.StatusUnprocessableEntity, "invalid_input")
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, viewIDP(row))
}
}
var errKindChange = errors.New("api: provider kind cannot change")
func (s *Server) adminDeleteIDP(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, sole int64
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
// Deleting would lock out accounts that sign in only this way;
// disabling can be undone.
if sole, err = q.SoleSignInUsers(ctx, id); err != nil || sole > 0 {
return err
}
n, err = q.DeletePlatformIDP(ctx, id)
return err
})
switch {
case err == nil && sole > 0:
fail(c, http.StatusConflict, "idp_in_use", "Count", sole)
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
c.Status(http.StatusNoContent)
}
}
func (s *Server) idpAdminView(ctx context.Context) web.IDPAdminView {
v := web.IDPAdminView{CallbackURL: s.sso.RedirectURL()}
var rows []store.PlatformIdentityProvider
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListPlatformIDPs(ctx)
return err
})
if err != nil {
s.log.WarnContext(ctx, "listing identity providers failed", "error", err)
}
for _, r := range rows {
v.Providers = append(v.Providers, web.IDPRow{
ID: r.ID.String(), Kind: r.Kind, Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID,
SecretSet: r.ClientSecret != nil, AllowSignup: r.AllowSignup, Enabled: r.Enabled,
})
}
return v
}
+200
View File
@@ -0,0 +1,200 @@
package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// fakeGitHub answers like GitHub's OAuth and REST API for one user.
func fakeGitHub(t *testing.T, id int64, email string, verified bool) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/login/oauth/authorize":
back, _ := url.Parse(r.URL.Query().Get("redirect_uri"))
q := back.Query()
q.Set("code", "gh-code")
q.Set("state", r.URL.Query().Get("state"))
back.RawQuery = q.Encode()
http.Redirect(w, r, back.String(), http.StatusFound)
case "/login/oauth/access_token":
if r.FormValue("code") != "gh-code" || r.FormValue("code_verifier") == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"gh-token","token_type":"bearer"}`))
case "/api/v3/user":
if r.Header.Get("Authorization") != "Bearer gh-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": id, "login": "octo", "name": ""})
case "/api/v3/user/emails":
_ = json.NewEncoder(w).Encode([]map[string]any{
{"email": "other@" + uniq("x") + ".test", "primary": false, "verified": true},
{"email": email, "primary": true, "verified": verified},
})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestPlatformSSO(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
idp := ssotest.New(t)
admin := e.browser(t)
admin.signup("admin@"+uniq("psso")+".test", uniq("psso-"))
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)
}
st, google := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
"kind": "oidc", "name": "Google", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
"allow_signup": true, "enabled": true,
})
if st != http.StatusCreated || google["client_secret_set"] != true || strings.Contains(mustJSON(google), idp.Secret) {
t.Fatalf("create provider = %d %v", st, google)
}
start := "/login/sso/" + google["id"].(string)
t.Cleanup(func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_identity_providers`)
return err
})
})
if _, _, html := e.browser(t).page("/login"); !strings.Contains(html, "Continue with Google") || !strings.Contains(html, start) {
t.Error("the login page lacks the provider")
}
// Sign up, then sign in again with the same identity.
newEmail := uniq("new") + "@example.test"
subject := uniq("sub")
idp.SetUser(ssotest.User{Subject: subject, Email: newEmail, EmailVerified: true, Name: "New Person"})
u := e.browser(t)
if got := u.visit(start); got.Path != "/orgs/new" {
t.Fatalf("sign-up landed on %s, want /orgs/new", got)
}
if _, me := u.do("GET", "/api/v1/me", nil); me["email"] != newEmail {
t.Errorf("me = %v", me)
}
if got := e.browser(t).visit(start); got.Path != "/orgs/new" || got.Query().Get("sso_error") != "" {
t.Errorf("second sign-in landed on %s", got)
}
// Existing accounts are never taken over, also not through an alias.
owner := e.browser(t)
ownerBox := uniq("owner")
owner.signup(ownerBox+"@example.test", uniq("psso-o-"))
for _, email := range []string{ownerBox + "@example.test", ownerBox + "+x@example.test"} {
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: email, EmailVerified: true})
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_link_required" {
t.Errorf("%s: landed on %s, want sso_link_required", email, got)
}
}
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("u") + "@example.test", EmailVerified: false})
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_email_unverified" {
t.Errorf("unverified email landed on %s", got)
}
// The owner links the provider while signed in and then signs in with it.
linked := uniq("sub")
idp.SetUser(ssotest.User{Subject: linked, Email: "whatever@" + uniq("x") + ".test", EmailVerified: true})
if got := owner.visit(start + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" {
t.Fatalf("linking landed on %s", got)
}
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "Disconnect") {
t.Error("the security page lacks the linked provider")
}
via := e.browser(t)
if got := via.visit(start); got.Path != "/" {
t.Errorf("sign-in through the linked identity landed on %s", got)
}
if _, me := via.do("GET", "/api/v1/me", nil); me["email"] != ownerBox+"@example.test" {
t.Errorf("signed in as %v", me["email"])
}
// The account's second factor still applies after the provider.
_, codes := owner.enableTOTP()
mfa := e.browser(t)
if got := mfa.visit(start); got.Path != "/login" || got.Query().Get("mfa") != "1" {
t.Fatalf("sign-in with TOTP landed on %s", got)
}
if st, _ := mfa.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Error("signed in before the second factor")
}
if st, body := mfa.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": codes[0]}); st != http.StatusOK {
t.Fatalf("second factor = %d %v", st, body)
}
// Unlinking: never the last way to sign in.
u.page("/orgs/new")
st, body := u.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil)
expect(t, "unlink the only sign-in", st, body, http.StatusConflict, "last_sign_in")
if st, _ := owner.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil); st != http.StatusNoContent {
t.Errorf("unlink = %d", st)
}
// Removing a provider some accounts depend on is refused.
st, body = admin.do("DELETE", "/api/v1/admin/identity-providers/"+google["id"].(string), nil)
expect(t, "delete a provider in use", st, body, http.StatusConflict, "idp_in_use")
// Sign-up closed for this provider.
google["allow_signup"], google["client_secret"] = false, ""
if st, body := admin.do("PUT", "/api/v1/admin/identity-providers/"+google["id"].(string), google); st != http.StatusOK || body["client_secret_set"] != true {
t.Fatalf("update = %d %v", st, body)
}
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("late") + "@example.test", EmailVerified: true})
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_not_provisioned" {
t.Errorf("sign-up through a closed provider landed on %s", got)
}
// GitHub, here a GitHub Enterprise server.
ghEmail := uniq("octo") + "@example.test"
gh := fakeGitHub(t, 4242, ghEmail, true)
st, github := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
"kind": "github", "name": "GitHub", "issuer": gh.URL, "client_id": "gh-client", "client_secret": "gh-secret",
"allow_signup": true, "enabled": true,
})
if st != http.StatusCreated {
t.Fatalf("create github = %d %v", st, github)
}
g := e.browser(t)
if got := g.visit("/login/sso/" + github["id"].(string)); got.Path != "/orgs/new" {
t.Fatalf("GitHub sign-up landed on %s", got)
}
if _, me := g.do("GET", "/api/v1/me", nil); me["email"] != ghEmail || me["display_name"] != "octo" {
t.Errorf("GitHub account = %v", me)
}
unverified := fakeGitHub(t, 777, uniq("u")+"@example.test", false)
_, gh2 := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
"kind": "github", "name": "GHE", "issuer": unverified.URL, "client_id": "c", "client_secret": "s", "allow_signup": true, "enabled": true,
})
if got := e.browser(t).visit("/login/sso/" + gh2["id"].(string)); got.Query().Get("sso_error") != "sso_email_unverified" {
t.Errorf("GitHub with an unverified primary email landed on %s", got)
}
// Admins only, secrets never listed.
if st, _ := u.do("GET", "/api/v1/admin/identity-providers", nil); st != http.StatusForbidden {
t.Errorf("non-admin listing = %d", st)
}
_, list := admin.do("GET", "/api/v1/admin/identity-providers", nil)
if raw := mustJSON(list); strings.Contains(raw, "gh-secret") || strings.Contains(raw, idp.Secret) || !strings.Contains(raw, "/sso/callback") {
t.Errorf("provider list = %s", raw)
}
}
+47
View File
@@ -4,11 +4,15 @@ import (
"context" "context"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"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/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
) )
@@ -153,3 +157,46 @@ func (b *browser) userIDSelf() uuid.UUID {
_, me := b.do("GET", "/api/v1/me", nil) _, me := b.do("GET", "/api/v1/me", nil)
return uuid.MustParse(me["id"].(string)) return uuid.MustParse(me["id"].(string))
} }
func TestAgentInstallConsole(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.PublicURL = "https://uptime.example.com" })
owner := e.browser(t)
owner.signup("o@"+uniq("inst")+".test", uniq("inst-"))
st, body := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "statuspage", "name": "pages"})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, body)
}
tok := body["token"].(string)
old := buildinfo.Version
buildinfo.Version = "v1.4.2"
t.Cleanup(func() { buildinfo.Version = old })
_, _, html := owner.page("/settings/regions")
for _, want := range []string{
"curl -fsSL https://uptime.example.com/install.sh | sudo sh -s -- {kind} --token {token}{manual}",
`data-channel="latest"`, "Update automatically", "}-statuspage:${UPTIME_AGENT_TAG",
"The platform runs v1.4.2.",
} {
if !strings.Contains(html, want) {
t.Errorf("the page lacks %q", want)
}
}
if strings.Contains(html, ">· outdated<") {
t.Error("an agent that never reported is marked outdated")
}
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "v1.4.1").WithHTTPClient(e.srv.Client())
if _, err := client.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, _, html := owner.page("/settings/regions"); !strings.Contains(html, "v1.4.1") || !strings.Contains(html, "outdated") {
t.Error("an agent behind the platform is not marked outdated")
}
current := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "v1.4.2").WithHTTPClient(e.srv.Client())
if _, err := current.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, _, html := owner.page("/settings/regions"); strings.Contains(html, "· outdated") {
t.Error("an agent on the platform's release is marked outdated")
}
}
+37 -1
View File
@@ -44,6 +44,8 @@ type Server struct {
eval *evaluate.Evaluator eval *evaluate.Evaluator
smtp *notify.SMTP smtp *notify.SMTP
legal *versioned[[]agentapi.LegalDoc] legal *versioned[[]agentapi.LegalDoc]
// consent caches the versions of the documents accounts accept.
consent *versioned[map[string]int64]
// checkTypes caches the check types switched off platform-wide. // checkTypes caches the check types switched off platform-wide.
checkTypes *versioned[map[string]bool] checkTypes *versioned[map[string]bool]
// checkerNet caches whether platform checkers may reach private // checkerNet caches whether platform checkers may reach private
@@ -51,6 +53,8 @@ type Server struct {
checkerNet *versioned[bool] checkerNet *versioned[bool]
// limits caches the platform's default limits. // limits caches the platform's default limits.
limits *versioned[Limits] limits *versioned[Limits]
// support caches how the platform runs support tickets.
support *versioned[supportSettings]
} }
// Deps are the external resources a Server needs. // Deps are the external resources a Server needs.
@@ -82,9 +86,11 @@ func New(cfg config.API, d Deps) *Server {
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate), sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis), sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"), legal: newVersioned[[]agentapi.LegalDoc]("legal"),
consent: newVersioned[map[string]int64]("consent"),
checkTypes: newVersioned[map[string]bool]("check-types"), checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"), checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"), limits: newVersioned[Limits]("limits"),
support: newVersioned[supportSettings]("support"),
} }
} }
@@ -97,9 +103,10 @@ func (s *Server) Mount(r gin.IRouter) {
s.mountHeartbeats(r) s.mountHeartbeats(r)
s.mountAlertmanager(r) s.mountAlertmanager(r)
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit()) g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate())
r.GET("/api/openapi.json", s.openAPIJSON) r.GET("/api/openapi.json", s.openAPIJSON)
r.GET("/install.sh", s.installScript)
g.GET("/api/docs", s.apiDocsPage) g.GET("/api/docs", s.apiDocsPage)
v1 := g.Group("/api/v1") v1 := g.Group("/api/v1")
@@ -114,10 +121,12 @@ func (s *Server) Mount(r gin.IRouter) {
a.POST("/login", s.login) a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP) a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout) a.POST("/logout", s.logout)
v1.POST("/consent", auth.Require(), s.acceptConsent)
me := v1.Group("/me", auth.Require()) me := v1.Group("/me", auth.Require())
me.GET("", s.me) me.GET("", s.me)
me.POST("/org", s.switchOrg) me.POST("/org", s.switchOrg)
me.DELETE("/identities/:provider", s.unlinkIdentity)
me.POST("/totp/setup", s.totpSetup) me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable) me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable) me.POST("/totp/disable", s.totpDisable)
@@ -126,6 +135,13 @@ func (s *Server) Mount(r gin.IRouter) {
me.GET("/export", s.exportAccount) me.GET("/export", s.exportAccount)
me.POST("/delete", s.deleteAccount) me.POST("/delete", s.deleteAccount)
support := v1.Group("/support", auth.Require(), s.requireSupport())
support.GET("/tickets", s.listMyTickets)
support.POST("/tickets", s.createTicket)
support.GET("/tickets/:id", s.getMyTicket)
support.POST("/tickets/:id/messages", s.replyMyTicket)
support.PUT("/tickets/:id/status", s.setMyTicketStatus)
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation) v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
v1.POST("/invitations/:token/signup", s.inviteSignup) v1.POST("/invitations/:token/signup", s.inviteSignup)
@@ -175,6 +191,10 @@ func (s *Server) Mount(r gin.IRouter) {
admin.GET("/check-types", s.adminListCheckTypes) admin.GET("/check-types", s.adminListCheckTypes)
admin.PUT("/check-types", s.adminSetCheckTypes) admin.PUT("/check-types", s.adminSetCheckTypes)
admin.GET("/checker-network", s.adminGetCheckerNetwork) admin.GET("/checker-network", s.adminGetCheckerNetwork)
admin.GET("/identity-providers", s.adminListIDPs)
admin.POST("/identity-providers", s.adminCreateIDP)
admin.PUT("/identity-providers/:id", s.adminUpdateIDP)
admin.DELETE("/identity-providers/:id", s.adminDeleteIDP)
admin.GET("/limits", s.adminGetLimits) admin.GET("/limits", s.adminGetLimits)
admin.PUT("/limits", s.adminSetLimits) admin.PUT("/limits", s.adminSetLimits)
admin.GET("/orgs", s.adminListOrgs) admin.GET("/orgs", s.adminListOrgs)
@@ -193,6 +213,12 @@ func (s *Server) Mount(r gin.IRouter) {
admin.GET("/regions", s.adminListRegions) admin.GET("/regions", s.adminListRegions)
admin.POST("/regions", s.adminCreateRegion) admin.POST("/regions", s.adminCreateRegion)
admin.DELETE("/regions/:id", s.adminDeleteRegion) admin.DELETE("/regions/:id", s.adminDeleteRegion)
admin.GET("/support/settings", s.adminGetSupportSettings)
admin.PUT("/support/settings", s.adminSetSupportSettings)
admin.GET("/support/tickets", s.adminListTickets)
admin.GET("/support/tickets/:id", s.adminGetTicket)
admin.POST("/support/tickets/:id/messages", s.adminReplyTicket)
admin.PUT("/support/tickets/:id/status", s.adminSetTicketStatus)
admin.GET("/agents", s.adminListAgents) admin.GET("/agents", s.adminListAgents)
admin.POST("/agents", s.adminCreateAgent) admin.POST("/agents", s.adminCreateAgent)
admin.DELETE("/agents/:id", s.adminDeleteAgent) admin.DELETE("/agents/:id", s.adminDeleteAgent)
@@ -213,6 +239,14 @@ func (s *Server) Mount(r gin.IRouter) {
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage) page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents) org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
org.GET("/incidents/:id", can(authz.IncidentsRead), s.getIncident)
org.PATCH("/incidents/:id", s.setIncidentTitle)
org.POST("/incidents/:id/updates", s.addIncidentUpdate)
org.DELETE("/incidents/:id/updates/:update", s.deleteIncidentUpdate)
org.GET("/incident-statuses", can(authz.IncidentsRead), s.listIncidentStatuses)
org.POST("/incident-statuses", can(authz.OrgManage), s.createIncidentStatus)
org.PUT("/incident-statuses/:id", can(authz.OrgManage), s.updateIncidentStatus)
org.DELETE("/incident-statuses/:id", can(authz.OrgManage), s.deleteIncidentStatus)
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit) org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups) org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
@@ -232,6 +266,7 @@ func (s *Server) Mount(r gin.IRouter) {
org.GET("/members", can(authz.MembersRead), s.listMembers) org.GET("/members", can(authz.MembersRead), s.listMembers)
org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember) org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember)
org.PUT("/members/:user/owner", sessionOnly(), s.setOwner)
org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole) org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole)
org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole) org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole)
@@ -252,6 +287,7 @@ func (s *Server) Mount(r gin.IRouter) {
g.GET("/sso", s.ssoLookup) g.GET("/sso", s.ssoLookup)
g.GET("/sso/callback", s.ssoCallback) g.GET("/sso/callback", s.ssoCallback)
g.GET("/login/sso/:provider", s.platformSSOStart)
g.GET("/sso/:slug", s.ssoChoose) g.GET("/sso/:slug", s.ssoChoose)
g.GET("/sso/:slug/:provider", s.ssoStartProvider) g.GET("/sso/:slug/:provider", s.ssoStartProvider)
+9 -4
View File
@@ -40,6 +40,9 @@ type ssoFlow struct {
// LinkUser is set when a signed-in user connects this IdP to their // LinkUser is set when a signed-in user connects this IdP to their
// existing account instead of signing in. // existing account instead of signing in.
LinkUser uuid.UUID `json:"link_user,omitempty"` LinkUser uuid.UUID `json:"link_user,omitempty"`
// Platform marks a platform identity provider rather than an
// organization's.
Platform bool `json:"platform,omitempty"`
} }
// ssoError aborts a browser flow by redirecting with a code the target page // ssoError aborts a browser flow by redirecting with a code the target page
@@ -206,6 +209,10 @@ func (s *Server) ssoCallback(c *gin.Context) {
s.ssoAbort(c, f.LinkUser, "sso_denied") s.ssoAbort(c, f.LinkUser, "sso_denied")
return return
} }
if f.Platform {
s.platformCallback(c, f, state)
return
}
var row store.SsoProvider var row store.SsoProvider
err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error { err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error {
@@ -254,10 +261,8 @@ func (s *Server) ssoCallback(c *gin.Context) {
internalError(c, err) internalError(c, err)
return return
} }
if user.DisabledAt != nil { // Suspended accounts sign in too, but only to export or delete their
s.ssoAbort(c, uuid.Nil, "account_suspended") // data (accountGate).
return
}
if old := auth.Current(c); old != nil { if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(ctx, old) _ = s.sessions.Delete(ctx, old)
} }
+28
View File
@@ -13,6 +13,7 @@ import (
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"os" "os"
"regexp"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -170,10 +171,37 @@ func (b *browser) visit(path string) *url.URL {
func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") } func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") }
var consentVersionsField = regexp.MustCompile(`name="(?:consent_versions|versions)" value="([^"]*)"`)
// consentShown returns the document versions a page asks to accept, empty
// when it asks for none.
func consentShown(html string) string {
if m := consentVersionsField.FindStringSubmatch(html); m != nil {
return m[1]
}
return ""
}
// acceptConsent accepts the documents the console asks for, as someone
// ticking the box on /consent would.
func (b *browser) acceptConsent() {
b.t.Helper()
_, _, html := b.page("/consent")
if v := consentShown(html); v != "" {
if st, body := b.do("POST", "/api/v1/consent", map[string]any{"versions": v, "accept": true}); st != http.StatusOK {
b.t.Fatalf("accept consent = %d %v", st, body)
}
}
}
func (b *browser) signup(email, slug string) { func (b *browser) signup(email, slug string) {
b.t.Helper() b.t.Helper()
// Tick the consent box the sign-up page shows, if any.
_, _, form := b.page("/signup")
versions := consentShown(form)
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{ st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{
"email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug, "email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
"consent": versions != "", "consent_versions": versions,
}) })
if st != http.StatusOK { if st != http.StatusOK {
b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body) b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body)
+26 -2
View File
@@ -62,6 +62,8 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
hourly []store.HourlyBucketsRow hourly []store.HourlyBucketsRow
regions []store.Region regions []store.Region
incidents []store.Incident incidents []store.Incident
updates []store.PublicIncidentUpdatesRow
statuses customStatuses
planned map[uuid.UUID][]store.MaintenanceWindow planned map[uuid.UUID][]store.MaintenanceWindow
) )
now := time.Now() now := time.Now()
@@ -101,11 +103,22 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil { if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
return err return err
} }
incidentIDs := make([]uuid.UUID, len(incidents))
for i, inc := range incidents {
incidentIDs[i] = inc.ID
}
if updates, err = q.PublicIncidentUpdates(ctx, incidentIDs); err != nil {
return err
}
if statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err
}
if planned, err = maintenanceFor(ctx, q, ids); err != nil { if planned, err = maintenanceFor(ctx, q, ids); err != nil {
return err return err
} }
docs, err := q.LegalDocuments(ctx, &page.OrgID) docs, err := q.LegalDocuments(ctx, &page.OrgID)
snap.Legal = mergeLegal(docs) // Visitors of status pages accept no terms.
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" })
return err return err
}) })
if err != nil { if err != nil {
@@ -190,8 +203,19 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...) snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...)
snap.Status = agentapi.Summarize(states) snap.Status = agentapi.Summarize(states)
snap.Maintenance = pageMaintenance(planned, names, now) snap.Maintenance = pageMaintenance(planned, names, now)
updatesOf := map[uuid.UUID][]agentapi.PageIncidentUpdate{}
for _, u := range updates {
st := statuses.info(&u.Status, u.StatusID)
updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{
Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Message: u.Message, At: u.CreatedAt,
})
}
for _, i := range incidents { for _, i := range incidents {
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt}) st := statuses.of(i)
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{
Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt,
Title: i.Title, Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Updates: updatesOf[i.ID],
})
} }
return snap, nil return snap, nil
} }
+860
View File
@@ -0,0 +1,860 @@
package api
import (
"context"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"time"
"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/notify"
"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"
)
// Support tickets: an account asks the platform's admins for help, also
// while it is suspended or has yet to accept the terms. A ticket is open
// while it waits for the admins and answered while it waits for the
// account; a reply from either side moves it accordingly, also out of
// closed.
const (
ticketOpen = "open"
ticketAnswered = "answered"
ticketClosed = "closed"
)
type supportTicketRequest struct {
Subject string `json:"subject" binding:"required,max=200"`
Message string `json:"message" binding:"required,max=10000"`
// AttachOrg names the active organization in the ticket. Anything else
// attached comes from it and names it too.
AttachOrg bool `json:"attach_org"`
Monitor string `json:"monitor_id" binding:"max=36"`
Channel string `json:"channel_id" binding:"max=36"`
AlertGroup string `json:"alert_group_id" binding:"max=36"`
StatusPage string `json:"status_page_id" binding:"max=36"`
Incident string `json:"incident_id" binding:"max=36"`
}
// supportReference is something a ticket points at, by kind: org,
// monitor, channel, alert_group, status_page or incident.
type supportReference struct {
Kind string `json:"kind"`
Name string `json:"name"`
}
type supportMessageRequest struct {
Message string `json:"message" binding:"required,max=10000"`
}
type supportStatusRequest struct {
Status string `json:"status" binding:"required,oneof=open answered closed"`
}
type supportMessageView struct {
ID uuid.UUID `json:"id"`
FromStaff bool `json:"from_staff"`
// Author is the admin who answered, shown to admins only.
Author string `json:"author,omitempty"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
}
type supportTicketView struct {
ID uuid.UUID `json:"id"`
Subject string `json:"subject"`
Status string `json:"status"`
// Org is the organization the account was in when it opened the ticket.
Org *string `json:"org,omitempty"`
// User is the account's email, shown to admins only.
User string `json:"user,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
References []supportReference `json:"references,omitempty"`
Messages []supportMessageView `json:"messages,omitempty"`
}
// cleanSupportText trims text and reports whether anything is left.
func cleanSupportText(c *gin.Context, texts ...*string) bool {
for _, t := range texts {
*t = strings.TrimSpace(*t)
if *t == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return false
}
}
return true
}
// loadTicket reads a ticket with its messages in scope, which decides
// whose tickets are visible.
func (s *Server) loadTicket(ctx context.Context, scope tenant.Scope, id uuid.UUID, staff bool) (supportTicketView, error) {
var v supportTicketView
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
t, err := q.GetSupportTicket(ctx, id)
if err != nil {
return err
}
v = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
if staff {
v.User = t.UserEmail
}
msgs, err := q.SupportMessages(ctx, id)
for _, m := range msgs {
mv := supportMessageView{ID: m.ID, FromStaff: m.FromStaff, Body: m.Body, CreatedAt: m.CreatedAt}
if staff && m.FromStaff {
mv.Author = m.AuthorEmail
}
v.Messages = append(v.Messages, mv)
}
return err
})
if err != nil {
return v, err
}
v.References, err = s.ticketReferences(ctx, id)
return v, err
}
// ticketReferences names what a ticket points at. The account may no
// longer see those things, so this reads past row-level security, after
// the caller saw the ticket itself.
func (s *Server) ticketReferences(ctx context.Context, id uuid.UUID) ([]supportReference, error) {
var out []supportReference
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
r, err := q.SupportTicketReferences(ctx, id)
if err != nil {
return err
}
add := func(kind string, name *string, extra ...*string) {
if name == nil {
return
}
n := *name
for _, e := range extra {
if e != nil && *e != "" {
n += " (" + *e + ")"
}
}
out = append(out, supportReference{Kind: kind, Name: n})
}
add("org", r.OrgName, r.OrgSlug)
add("monitor", r.MonitorName, r.MonitorType)
add("channel", r.ChannelName, r.ChannelType)
add("alert_group", r.AlertGroupName)
add("status_page", r.StatusPageTitle, r.StatusPageSlug)
if r.IncidentStartedAt != nil {
name := deref(r.IncidentMonitor)
if t := deref(r.IncidentTitle); t != "" {
name = t + " · " + name
}
name += " · " + r.IncidentStartedAt.UTC().Format(timeLayout)
add("incident", &name)
}
return nil
})
return out, err
}
func ticketID(c *gin.Context) (uuid.UUID, bool) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
}
return id, err == nil
}
func (s *Server) listMyTickets(c *gin.Context) {
sess := auth.Current(c)
ctx := c.Request.Context()
var rows []store.SupportTicket
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]supportTicketView, len(rows))
for i, t := range rows {
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
}
c.JSON(http.StatusOK, gin.H{"tickets": out})
}
// optionalID parses a form's optional reference; empty is none.
func optionalID(v string) (*uuid.UUID, bool) {
if v = strings.TrimSpace(v); v == "" {
return nil, true
}
id, err := uuid.Parse(v)
return &id, err == nil
}
// ticketRefs resolves what a new ticket points at. Everything comes from
// the active organization, which the account has to be able to read.
func (s *Server) ticketRefs(c *gin.Context, req supportTicketRequest) (store.CreateSupportTicketParams, bool) {
var p store.CreateSupportTicketParams
ids := []struct {
raw string
dst **uuid.UUID
perm authz.Permission
}{
{req.Monitor, &p.MonitorID, authz.MonitorsRead},
{req.Channel, &p.ChannelID, authz.NotificationsRead},
{req.AlertGroup, &p.AlertGroupID, authz.NotificationsRead},
{req.StatusPage, &p.StatusPageID, authz.StatusPagesRead},
{req.Incident, &p.IncidentID, authz.IncidentsRead},
}
any := req.AttachOrg
for _, r := range ids {
id, ok := optionalID(r.raw)
if !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
*r.dst = id
any = any || id != nil
}
if !any {
return p, true
}
sess := auth.Current(c)
_, principal, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return p, false
}
if principal == nil {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
for _, r := range ids {
if *r.dst != nil && !principal.Grants.Can(r.perm) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
}
ctx := c.Request.Context()
var exists *bool
if err := s.db.Tx(ctx, principal.scope(), func(q *store.Queries) error {
var err error
exists, err = q.SupportReferencesExist(ctx, store.SupportReferencesExistParams{
OrgID: principal.Org.ID, MonitorID: p.MonitorID, ChannelID: p.ChannelID,
AlertGroupID: p.AlertGroupID, StatusPageID: p.StatusPageID, IncidentID: p.IncidentID,
})
return err
}); err != nil {
internalError(c, err)
return p, false
}
if exists == nil || !*exists {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
p.OrgID = &principal.Org.ID
return p, true
}
// errTicketLimit and errSuspendedTicket refuse tickets beyond what the
// platform allows; the error code says which.
var (
errTicketLimit = errors.New("api: too many open tickets")
errSuspendedTicket = errors.New("api: suspended accounts open one ticket")
)
// checkTicketLimits refuses another open ticket for user: more than the
// platform allows at the same time, or a second since a suspension.
func checkTicketLimits(ctx context.Context, q *store.Queries, user uuid.UUID, maxOpen int, newTicket bool) error {
if newTicket {
u, err := q.GetUser(ctx, user)
if err != nil {
return err
}
if u.DisabledAt != nil {
n, err := q.CountSupportTicketsSince(ctx, store.CountSupportTicketsSinceParams{UserID: user, CreatedAt: *u.DisabledAt})
if err != nil {
return err
}
if n > 0 {
return errSuspendedTicket
}
}
}
if maxOpen <= 0 {
return nil
}
n, err := q.CountOpenSupportTickets(ctx, user)
if err != nil {
return err
}
if n >= int64(maxOpen) {
return errTicketLimit
}
return nil
}
// failTicketLimit answers err if it is one of the ticket limits.
func failTicketLimit(c *gin.Context, err error, maxOpen int) bool {
switch {
case errors.Is(err, errSuspendedTicket):
fail(c, http.StatusConflict, "suspended_ticket_limit")
case errors.Is(err, errTicketLimit):
fail(c, http.StatusConflict, "too_many_tickets", "Count", maxOpen)
default:
return false
}
return true
}
func (s *Server) createTicket(c *gin.Context) {
var req supportTicketRequest
if !bind(c, &req) || !cleanSupportText(c, &req.Subject, &req.Message) {
return
}
sess := auth.Current(c)
if !s.limit(c, "support:user:"+sess.UserID.String(), 10, time.Hour) {
return
}
params, ok := s.ticketRefs(c, req)
if !ok {
return
}
params.UserID, params.Subject = sess.UserID, req.Subject
ctx := c.Request.Context()
maxOpen := s.supportSettings(ctx).MaxOpen
var t store.SupportTicket
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
if err := checkTicketLimits(ctx, q, sess.UserID, maxOpen, true); err != nil {
return err
}
var err error
if t, err = q.CreateSupportTicket(ctx, params); err != nil {
return err
}
_, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: t.ID, AuthorID: &sess.UserID, Body: req.Message})
return err
})
if failTicketLimit(c, err, maxOpen) {
return
}
if err != nil {
internalError(c, err)
return
}
auditDetail(c, "ticket", t.ID.String())
s.mailAdmins(ctx, t.ID, t.Subject)
c.JSON(http.StatusCreated, supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt})
}
func (s *Server) getMyTicket(c *gin.Context) {
id, ok := ticketID(c)
if !ok {
return
}
v, err := s.loadTicket(c.Request.Context(), tenant.User(auth.Current(c).UserID), id, false)
s.respondTicket(c, v, err)
}
func (s *Server) respondTicket(c *gin.Context, v supportTicketView, err error) {
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, v)
}
}
// replyTicket adds a message and moves the ticket to the side that has to
// answer next.
func (s *Server) replyTicket(c *gin.Context, scope tenant.Scope, author uuid.UUID, staff bool) (store.GetSupportTicketRow, bool) {
maxOpen := 0
if !staff {
maxOpen = s.supportSettings(c.Request.Context()).MaxOpen
}
id, ok := ticketID(c)
if !ok {
return store.GetSupportTicketRow{}, false
}
var req supportMessageRequest
if !bind(c, &req) || !cleanSupportText(c, &req.Message) {
return store.GetSupportTicketRow{}, false
}
status := ticketOpen
if staff {
status = ticketAnswered
}
ctx := c.Request.Context()
var t store.GetSupportTicketRow
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
var err error
if t, err = q.GetSupportTicket(ctx, id); err != nil {
return err
}
if !staff && t.Status == ticketClosed {
if err := checkTicketLimits(ctx, q, t.UserID, maxOpen, false); err != nil {
return err
}
}
if _, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: id, AuthorID: &author, FromStaff: staff, Body: req.Message}); err != nil {
return err
}
_, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: status})
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
return t, false
case failTicketLimit(c, err, maxOpen):
return t, false
case err != nil:
internalError(c, err)
return t, false
}
auditDetail(c, "ticket", id.String())
c.JSON(http.StatusCreated, gin.H{"status": status})
return t, true
}
func (s *Server) replyMyTicket(c *gin.Context) {
sess := auth.Current(c)
if !s.limit(c, "support:reply:"+sess.UserID.String(), 60, time.Hour) {
return
}
if t, ok := s.replyTicket(c, tenant.User(sess.UserID), sess.UserID, false); ok {
s.mailAdmins(c.Request.Context(), t.ID, t.Subject)
}
}
// setTicketStatus closes or reopens a ticket in scope; accounts can only
// close theirs or reopen them for the admins.
func (s *Server) setTicketStatus(c *gin.Context, scope tenant.Scope, maxOpen int, allowed ...string) {
id, ok := ticketID(c)
if !ok {
return
}
var req supportStatusRequest
if !bind(c, &req) {
return
}
if len(allowed) > 0 && !slices.Contains(allowed, req.Status) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
ctx := c.Request.Context()
var n int64
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
if req.Status != ticketClosed && maxOpen > 0 {
cur, err := q.SupportTicketStatus(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if cur == ticketClosed {
if err := checkTicketLimits(ctx, q, auth.Current(c).UserID, maxOpen, false); err != nil {
return err
}
}
}
var err error
n, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: req.Status})
return err
})
switch {
case failTicketLimit(c, err, maxOpen):
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
auditDetail(c, "status", req.Status)
c.Status(http.StatusNoContent)
}
}
func (s *Server) setMyTicketStatus(c *gin.Context) {
s.setTicketStatus(c, tenant.User(auth.Current(c).UserID), s.supportSettings(c.Request.Context()).MaxOpen, ticketOpen, ticketClosed)
}
// supportStatusFilter reads the status filter of the admins' list; empty
// lists every ticket.
func supportStatusFilter(c *gin.Context) *string {
switch st := c.Query("status"); st {
case ticketOpen, ticketAnswered, ticketClosed:
return &st
case "all":
return nil
default:
open := ticketOpen
return &open
}
}
func (s *Server) adminListTickets(c *gin.Context) {
rows, err := s.supportTickets(c.Request.Context(), supportStatusFilter(c))
if err != nil {
internalError(c, err)
return
}
out := make([]supportTicketView, len(rows))
for i, t := range rows {
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
}
c.JSON(http.StatusOK, gin.H{"tickets": out})
}
// supportTickets lists the latest 200 tickets with status, or all.
func (s *Server) supportTickets(ctx context.Context, status *string) ([]store.ListSupportTicketsRow, error) {
var rows []store.ListSupportTicketsRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListSupportTickets(ctx, status)
return err
})
return rows, err
}
func (s *Server) adminGetTicket(c *gin.Context) {
id, ok := ticketID(c)
if !ok {
return
}
v, err := s.loadTicket(c.Request.Context(), tenant.System(), id, true)
s.respondTicket(c, v, err)
}
func (s *Server) adminReplyTicket(c *gin.Context) {
sess := auth.Current(c)
if t, ok := s.replyTicket(c, tenant.System(), sess.UserID, true); ok {
s.mailTicketOwner(c.Request.Context(), t)
}
}
func (s *Server) adminSetTicketStatus(c *gin.Context) {
s.setTicketStatus(c, tenant.System(), 0)
}
func (s *Server) ticketLink(path string) string {
return strings.TrimSuffix(s.cfg.PublicURL, "/") + path
}
// mailAdmins tells the platform's admins that a ticket waits for them.
// Mail is a courtesy: the ticket stands without it.
func (s *Server) mailAdmins(ctx context.Context, id uuid.UUID, subject string) {
if s.smtp == nil {
return
}
var to []string
if err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
to, err = q.AdminEmails(ctx)
return err
}); err != nil || len(to) == 0 {
return
}
l := s.catalog.Match("")
data := map[string]any{"Subject": subject, "Link": s.ticketLink("/admin/support/" + id.String())}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T("email.support_admin.subject", data), Body: l.T("email.support_admin.body", data)}); err != nil {
slog.WarnContext(ctx, "support: mail to admins failed", "ticket", id, "err", err)
}
}
// mailTicketOwner tells the account that its ticket was answered.
func (s *Server) mailTicketOwner(ctx context.Context, t store.GetSupportTicketRow) {
if s.smtp == nil {
return
}
var locale string
_ = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
u, err := q.GetUser(ctx, t.UserID)
locale = deref(u.Locale)
return err
})
l := s.catalog.Match(locale)
data := map[string]any{"Subject": t.Subject, "Link": s.ticketLink("/support/" + t.ID.String())}
if err := s.smtp.Send(ctx, notify.Mail{To: []string{t.UserEmail}, Subject: l.T("email.support_reply.subject", data), Body: l.T("email.support_reply.body", data)}); err != nil {
slog.WarnContext(ctx, "support: mail to account failed", "ticket", t.ID, "err", err)
}
}
// Pages.
func toWebTicket(v supportTicketView) web.SupportTicket {
t := web.SupportTicket{ID: v.ID.String(), Subject: v.Subject, Status: v.Status, User: v.User, Updated: v.UpdatedAt.UTC().Format(timeLayout)}
if v.Org != nil {
t.Org = *v.Org
}
for _, r := range v.References {
t.References = append(t.References, web.SupportReference{Kind: r.Kind, Name: r.Name})
}
for _, m := range v.Messages {
html, err := web.RenderMarkdown(m.Body)
if err != nil {
html = ""
}
t.Messages = append(t.Messages, web.SupportMessage{FromStaff: m.FromStaff, Author: m.Author, HTML: html, At: m.CreatedAt.UTC().Format(timeLayout)})
}
return t
}
// supportMe is the console frame of the support pages, which accounts
// reach also while restricted.
func (s *Server) supportMe(c *gin.Context) (*auth.Session, web.Me, *principal, bool) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
return nil, web.Me{}, nil, false
}
me, p, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return nil, web.Me{}, nil, false
}
if !me.Support {
web.Render(c, http.StatusOK, web.SupportDisabledPage(s.pageFor(c, "support.title"), me))
return nil, web.Me{}, nil, false
}
return sess, me, p, true
}
// supportOptions lists what of the active organization a new ticket can
// point at, as far as the account may read it.
func (s *Server) supportOptions(ctx context.Context, p *principal) (web.SupportOptions, error) {
var o web.SupportOptions
if p == nil {
return o, nil
}
o.Org = p.Org.Name
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if p.Grants.Can(authz.MonitorsRead) {
rows, err := q.SupportOptionsMonitors(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
o.Monitors = append(o.Monitors, web.SupportOption{ID: r.ID.String(), Name: r.Name})
}
}
if p.Grants.Can(authz.NotificationsRead) {
chans, err := q.SupportOptionsChannels(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range chans {
o.Channels = append(o.Channels, web.SupportOption{ID: r.ID.String(), Name: r.Name + " (" + r.Type + ")"})
}
groups, err := q.SupportOptionsAlertGroups(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range groups {
o.AlertGroups = append(o.AlertGroups, web.SupportOption{ID: r.ID.String(), Name: r.Name})
}
}
if p.Grants.Can(authz.StatusPagesRead) {
rows, err := q.SupportOptionsStatusPages(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
o.StatusPages = append(o.StatusPages, web.SupportOption{ID: r.ID.String(), Name: r.Title})
}
}
if p.Grants.Can(authz.IncidentsRead) {
rows, err := q.SupportOptionsIncidents(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
name := r.MonitorName
if r.Title != "" {
name = r.Title + " · " + name
}
o.Incidents = append(o.Incidents, web.SupportOption{ID: r.ID.String(), Name: name + " · " + r.StartedAt.UTC().Format(timeLayout)})
}
}
return nil
})
return o, err
}
func (s *Server) supportPage(c *gin.Context) {
sess, me, p, ok := s.supportMe(c)
if !ok {
return
}
ctx := c.Request.Context()
opts, err := s.supportOptions(ctx, p)
if err != nil {
internalError(c, err)
return
}
var rows []store.SupportTicket
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
return err
}); err != nil {
internalError(c, err)
return
}
tickets := make([]web.SupportTicket, len(rows))
for i, t := range rows {
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, UpdatedAt: t.UpdatedAt})
}
web.Render(c, http.StatusOK, web.SupportPage(s.pageFor(c, "support.title"), me, tickets, opts))
}
func (s *Server) supportTicketPage(c *gin.Context) {
sess, me, _, ok := s.supportMe(c)
if !ok {
return
}
s.renderTicket(c, me, tenant.User(sess.UserID), false)
}
func (s *Server) renderTicket(c *gin.Context, me web.Me, scope tenant.Scope, staff bool) {
id, err := uuid.Parse(c.Param("id"))
var v supportTicketView
if err == nil {
v, err = s.loadTicket(c.Request.Context(), scope, id, staff)
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
internalError(c, err)
return
}
if err != nil {
back := "/support"
if staff {
back = "/admin/support"
}
c.Redirect(http.StatusSeeOther, back)
return
}
var account *web.SupportAccount
if staff {
a, err := s.ticketAccount(c.Request.Context(), id)
if err != nil {
internalError(c, err)
return
}
account = &a
}
web.Render(c, http.StatusOK, web.SupportTicketPage(s.pageFor(c, "support.title"), me, toWebTicket(v), account))
}
func (s *Server) adminSupportPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
status := supportStatusFilter(c)
rows, err := s.supportTickets(c.Request.Context(), status)
if err != nil {
internalError(c, err)
return
}
tickets := make([]web.SupportTicket, len(rows))
for i, t := range rows {
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, UpdatedAt: t.UpdatedAt})
}
filter := "all"
if status != nil {
filter = *status
}
settings := s.supportSettings(c.Request.Context())
web.Render(c, http.StatusOK, web.AdminSupportPage(s.pageFor(c, "support.admin_title"), me, tickets, filter, web.SupportSettings{Enabled: settings.Enabled, MaxOpen: settings.MaxOpen}))
}
func (s *Server) adminSupportTicketPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
s.renderTicket(c, me, tenant.System(), true)
}
// ticketAccount gathers what admins need to answer a ticket: the account,
// its organizations with their limits and usage, and its other tickets.
func (s *Server) ticketAccount(ctx context.Context, ticket uuid.UUID) (web.SupportAccount, error) {
var a web.SupportAccount
platform := s.platformLimits(ctx)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
t, err := q.GetSupportTicket(ctx, ticket)
if err != nil {
return err
}
u, err := q.GetUser(ctx, t.UserID)
if err != nil {
return err
}
a = web.SupportAccount{
ID: u.ID.String(), Email: u.Email, Name: u.DisplayName, Created: u.CreatedAt.UTC().Format(timeLayout),
Verified: u.EmailVerifiedAt != nil, TOTP: u.TotpEnabledAt != nil, Password: u.PasswordHash != nil,
Admin: u.IsAdmin, Locale: deref(u.Locale),
}
if u.DisabledAt != nil {
a.Suspended = true
a.SuspendedReason = u.DisabledReason
}
a.OrgLimit = platform.OrgsPerAccount
if u.LimitOrgs != nil {
a.OrgLimit = int(*u.LimitOrgs)
}
owned, err := q.CountOwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
a.OrgsOwned = int(owned)
if a.OpenTickets, err = q.CountOpenSupportTickets(ctx, u.ID); err != nil {
return err
}
ms, err := q.UserMemberships(ctx, u.ID)
if err != nil {
return err
}
for _, m := range ms {
o, err := q.GetOrg(ctx, m.ID)
if err != nil {
return err
}
mon, err := q.CountMonitors(ctx, o.ID)
if err != nil {
return err
}
pages, err := q.CountStatusPages(ctx, o.ID)
if err != nil {
return err
}
l := s.orgLimits(ctx, o)
org := web.SupportOrg{
Name: o.Name, Slug: o.Slug, Owner: m.IsOwner, Current: t.OrgID != nil && *t.OrgID == o.ID,
Monitors: int(mon), MonitorLimit: l.Monitors, StatusPages: int(pages), StatusPageLimit: l.StatusPages,
RegionsPerMonitor: l.RegionsPerMonitor,
}
if o.SuspendedAt != nil {
org.Suspended = true
org.SuspendedReason = o.SuspendedReason
}
a.Orgs = append(a.Orgs, org)
}
return nil
})
return a, err
}
+85
View File
@@ -0,0 +1,85 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const settingSupport = "support"
// supportSettings are how the platform runs its support tickets.
type supportSettings struct {
Enabled bool `json:"enabled"`
// MaxOpen limits the tickets an account has open, answered ones
// included, at the same time; 0 means unlimited.
MaxOpen int `json:"max_open_tickets" binding:"min=0,max=1000"`
}
func defaultSupportSettings() supportSettings { return supportSettings{Enabled: true, MaxOpen: 3} }
func (s *Server) supportSettings(ctx context.Context) supportSettings {
v, err := s.support.get(ctx, s.rdb, func(ctx context.Context) (supportSettings, error) {
v := defaultSupportSettings()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingSupport)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &v)
})
return v, err
})
if err != nil {
s.log.WarnContext(ctx, "loading support settings failed", "error", err)
return defaultSupportSettings()
}
return v
}
// requireSupport answers for accounts only while support is enabled; the
// admins keep their tickets either way.
func (s *Server) requireSupport() gin.HandlerFunc {
return func(c *gin.Context) {
if !s.supportSettings(c.Request.Context()).Enabled {
fail(c, http.StatusForbidden, "support_disabled")
c.Abort()
return
}
c.Next()
}
}
func (s *Server) adminGetSupportSettings(c *gin.Context) {
c.JSON(http.StatusOK, s.supportSettings(c.Request.Context()))
}
func (s *Server) adminSetSupportSettings(c *gin.Context) {
var req supportSettings
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(req)
auditDetail(c, "settings", req)
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingSupport, Value: raw})
}); err != nil {
internalError(c, err)
return
}
if err := s.support.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing support settings failed", "error", err)
}
c.Status(http.StatusNoContent)
}
+190
View File
@@ -0,0 +1,190 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestSupportTickets(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("sup")+".test", uniq("sup-"))
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)
}
userEmail := "u@" + uniq("sup") + ".test"
user := e.browser(t)
user.signup(userEmail, uniq("sup-"))
userID := user.userIDSelf()
mailed := func(to, link string) {
t.Helper()
waitFor(t, 5*time.Second, "a mail with "+link, func() bool {
for _, m := range mail.Messages() {
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, link) {
return true
}
}
return false
})
}
st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": " ", "message": "x"})
expect(t, "ticket without subject", st, body, http.StatusUnprocessableEntity, "invalid_input")
st, created := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Checks are late", "message": "Since **Monday**."})
if st != http.StatusCreated || created["status"] != "open" {
t.Fatalf("open ticket = %d %v", st, created)
}
id := created["id"].(string)
mailed(adminEmailOf(t, admin), "/admin/support/"+id)
// Only the account and the admins see it.
other := e.browser(t)
other.signup("o@"+uniq("sup")+".test", uniq("sup-"))
if st, _ := other.do("GET", "/api/v1/support/tickets/"+id, nil); st != http.StatusNotFound {
t.Errorf("another account reads the ticket = %d", st)
}
if st, _ := other.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "me too"}); st != http.StatusNotFound {
t.Errorf("another account replies = %d", st)
}
if st, _ := user.do("GET", "/api/v1/admin/support/tickets", nil); st != http.StatusForbidden && st != http.StatusNotFound {
t.Errorf("an account lists every ticket = %d", st)
}
_, list := admin.do("GET", "/api/v1/admin/support/tickets", nil)
if !strings.Contains(mustJSON(list), id) || !strings.Contains(mustJSON(list), userEmail) {
t.Errorf("open tickets for the admins lack it: %v", list)
}
// Answering moves it to the account and mails it; its reply moves it back.
if st, body := admin.do("POST", "/api/v1/admin/support/tickets/"+id+"/messages", map[string]any{"message": "Fixed, sorry!"}); st != http.StatusCreated || body["status"] != "answered" {
t.Fatalf("answer = %d %v", st, body)
}
mailed(userEmail, "/support/"+id)
_, ticket := user.do("GET", "/api/v1/support/tickets/"+id, nil)
msgs, _ := ticket["messages"].([]any)
if ticket["status"] != "answered" || len(msgs) != 2 || msgs[1].(map[string]any)["from_staff"] != true || msgs[1].(map[string]any)["author"] != nil {
t.Errorf("ticket for the account = %v", ticket)
}
_, _, html := user.page("/support/" + id)
for _, want := range []string{"Checks are late", "<strong>Monday</strong>", "Fixed, sorry!", "Close ticket"} {
if !strings.Contains(html, want) {
t.Errorf("ticket page lacks %q", want)
}
}
if _, _, html := admin.page("/admin/support/" + id); !strings.Contains(html, userEmail) {
t.Error("the admins' ticket page does not name the account")
}
user.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "Thanks!"})
if _, tk := user.do("GET", "/api/v1/support/tickets/"+id, nil); tk["status"] != "open" {
t.Errorf("after the account's reply status = %v", tk["status"])
}
// Accounts close and reopen theirs, nothing else.
st, body = user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "answered"})
expect(t, "account marks answered", st, body, http.StatusUnprocessableEntity, "invalid_input")
if st, _ := user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "closed"}); st != http.StatusNoContent {
t.Errorf("close = %d", st)
}
_, closed := admin.do("GET", "/api/v1/admin/support/tickets?status=closed", nil)
if !strings.Contains(mustJSON(closed), id) {
t.Error("the closed filter lacks the ticket")
}
if _, _, html := user.page("/support"); !strings.Contains(html, "Checks are late") || !strings.Contains(html, "closed") {
t.Error("the support page lacks the closed ticket")
}
// Tickets point at things of the active organization the account can
// read, never at another's; the admins see the account at a glance.
_, mon := user.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Checkout API", "type": "heartbeat", "interval_seconds": 3600})
_, foreign := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Theirs", "type": "heartbeat", "interval_seconds": 3600})
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Peek", "message": "x", "monitor_id": foreign["id"]})
expect(t, "ticket about another organization's monitor", st, body, http.StatusUnprocessableEntity, "invalid_input")
if _, _, page := user.page("/support"); !strings.Contains(page, `name="monitor_id"`) || !strings.Contains(page, "Checkout API") {
t.Error("the new ticket form does not offer the monitors")
}
st, withRef := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Heartbeat missing", "message": "x", "monitor_id": mon["id"], "channel_id": ""})
if st != http.StatusCreated {
t.Fatalf("ticket about a monitor = %d %v", st, withRef)
}
refID := withRef["id"].(string)
_, got := user.do("GET", "/api/v1/support/tickets/"+refID, nil)
if refs := mustJSON(got["references"]); !strings.Contains(refs, "Checkout API") || !strings.Contains(refs, `"org"`) {
t.Errorf("references = %s", refs)
}
if _, _, page := admin.page("/admin/support/" + refID); !strings.Contains(page, "Checkout API") || !strings.Contains(page, "Organizations owned") || !strings.Contains(page, "1 / ") {
t.Error("the admins' ticket page lacks the references or the account's details")
}
// The admins limit open tickets per account and can switch support off.
t.Cleanup(func() {
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 3})
})
if st, body := admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 2}); st != http.StatusNoContent {
t.Fatalf("set support settings = %d %v", st, body)
}
if st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Second", "message": "x"}); st != http.StatusCreated {
t.Fatalf("second open ticket = %d %v", st, body)
}
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Third", "message": "x"})
expect(t, "third open ticket", st, body, http.StatusConflict, "too_many_tickets")
st, body = user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "open"})
expect(t, "reopen beyond the limit", st, body, http.StatusConflict, "too_many_tickets")
st, body = user.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "again"})
expect(t, "reply to a closed ticket beyond the limit", st, body, http.StatusConflict, "too_many_tickets")
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": false, "max_open_tickets": 0})
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Off", "message": "x"})
expect(t, "ticket while support is off", st, body, http.StatusForbidden, "support_disabled")
if _, _, page := user.page("/support"); !strings.Contains(page, "switched off") || strings.Contains(page, `href="/support"`) {
t.Error("the support page or the menu still offers support while it is off")
}
if st, _, _ := admin.page("/admin/support/" + refID); st != http.StatusOK {
t.Errorf("admins read tickets while support is off = %d", st)
}
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 0})
// A suspended account can still ask why, and its export holds the
// conversation.
if st, body := admin.do("PUT", "/api/v1/admin/users/"+userID.String()+"/suspension", map[string]any{"suspended": true, "reason": "Abuse"}); st != http.StatusNoContent {
t.Fatalf("suspend = %d %v", st, body)
}
user = e.browser(t)
if st, body := user.do("POST", "/api/v1/auth/login", map[string]any{"email": userEmail, "password": password}); st != http.StatusOK {
t.Fatalf("suspended account signs in = %d %v", st, body)
}
if _, _, page := user.page("/account/suspended"); !strings.Contains(page, `href="/support"`) {
t.Error("the suspension page does not lead to support")
}
if st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Why?", "message": "I did nothing."}); st != http.StatusCreated {
t.Errorf("suspended account opens a ticket = %d %v", st, body)
}
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Why, again?", "message": "Hello?"})
expect(t, "second ticket of a suspended account", st, body, http.StatusConflict, "suspended_ticket_limit")
if st, _, _ := user.page("/support"); st != http.StatusOK {
t.Errorf("support page of a suspended account = %d", st)
}
_, _, export := user.download("/api/v1/me/export")
if !strings.Contains(string(export), "Checks are late") || !strings.Contains(string(export), "Fixed, sorry!") {
t.Error("the account export lacks the tickets")
}
}
func adminEmailOf(t *testing.T, b *browser) string {
t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
email, _ := me["email"].(string)
if email == "" {
t.Fatalf("no email in %v", me)
}
return email
}
+3
View File
@@ -98,6 +98,9 @@ type API struct {
// StatusPageURL is where the platform's status page servers are // StatusPageURL is where the platform's status page servers are
// reachable; the console links pages as <StatusPageURL>/<slug>. // reachable; the console links pages as <StatusPageURL>/<slug>.
StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"` StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"`
// AgentImage is the image name agents are installed and updated from;
// "-checker" or "-statuspage" is appended. Change it for a mirror.
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
Retention Retention Retention Retention
} }
+206 -7
View File
@@ -10,11 +10,21 @@
"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_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.allow_private_short": "private Adressen",
"agents.create": "Agent anlegen", "agents.create": "Agent anlegen",
"agents.install_auto": "Automatisch aktualisieren",
"agents.install_auto_hint": "Nutzt das selbstaktualisierende Image: Der Agent folgt von allein der Version dieser Plattform, mit signierten Downloads und Rollback. Ohne aktualisierst du den Agent selbst.",
"agents.install_compose": "Oder mit Docker Compose",
"agents.install_compose_hint": "Lege beide Dateien in ein Verzeichnis und führe dort docker compose up -d aus.",
"agents.install_heading": "So installierst du ihn",
"agents.install_oneliner": "Auf einem Linux-Host mit Docker",
"agents.install_statuspage_hint": "Ergänze --host status.example.com für den Hostnamen, unter dem die Seiten erreichbar sind, und --tls --email du@example.com für HTTPS mit Let's Encrypt. --help listet alle Optionen.",
"agents.kind": "Art", "agents.kind": "Art",
"agents.kind_checker": "Checker", "agents.kind_checker": "Checker",
"agents.kind_statuspage": "Statuspage-Server", "agents.kind_statuspage": "Statuspage-Server",
"agents.list": "Agents", "agents.list": "Agents",
"agents.no_region": "– (nur für Statuspage-Server)", "agents.no_region": "– (nur für Statuspage-Server)",
"agents.outdated": "veraltet",
"agents.outdated_hint": "Hinter der Version der Plattform. Selbstaktualisierende Agents holen von allein auf; beim normalen Image dort, wo er installiert ist, docker compose pull && docker compose up -d ausführen.",
"agents.platform_release": "Die Plattform läuft mit {{.Release}}.",
"agents.region": "Region", "agents.region": "Region",
"agents.revoke_confirm": "Diesen Agent widerrufen? Seine Instanzen hören sofort auf zu arbeiten.", "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.", "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.",
@@ -50,8 +60,11 @@
"apidocs.hint": "„Try it out“ nutzt deine aktuelle Sitzung.", "apidocs.hint": "„Try it out“ nutzt deine aktuelle Sitzung.",
"apidocs.title": "API-Dokumentation", "apidocs.title": "API-Dokumentation",
"app.network_error": "Verbindung fehlgeschlagen.", "app.network_error": "Verbindung fehlgeschlagen.",
"audit.action.account.consent": "Datenschutz und AGB zugestimmt",
"audit.action.account.delete": "Konto gelöscht", "audit.action.account.delete": "Konto gelöscht",
"audit.action.account.export": "Persönliche Daten exportiert", "audit.action.account.export": "Persönliche Daten exportiert",
"audit.action.account.identity_link": "Anmelde-Anbieter verbunden",
"audit.action.account.identity_unlink": "Anmelde-Anbieter getrennt",
"audit.action.account.recovery_codes": "Wiederherstellungscodes neu erzeugt", "audit.action.account.recovery_codes": "Wiederherstellungscodes neu erzeugt",
"audit.action.account.signup": "Konto erstellt", "audit.action.account.signup": "Konto erstellt",
"audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert", "audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert",
@@ -76,12 +89,19 @@
"audit.action.group.create": "Gruppe erstellt", "audit.action.group.create": "Gruppe erstellt",
"audit.action.group.delete": "Gruppe gelöscht", "audit.action.group.delete": "Gruppe gelöscht",
"audit.action.group.update": "Gruppe geändert", "audit.action.group.update": "Gruppe geändert",
"audit.action.incident.title": "Ausfall umbenannt",
"audit.action.incident.update": "Update zu einem Ausfall veröffentlicht",
"audit.action.incident.update_delete": "Update zu einem Ausfall gelöscht",
"audit.action.incident_status.create": "Status für Ausfälle hinzugefügt",
"audit.action.incident_status.delete": "Status für Ausfälle gelöscht",
"audit.action.incident_status.update": "Status für Ausfälle geändert",
"audit.action.invitation.create": "Einladung verschickt", "audit.action.invitation.create": "Einladung verschickt",
"audit.action.invitation.delete": "Einladung zurückgezogen", "audit.action.invitation.delete": "Einladung zurückgezogen",
"audit.action.maintenance.create": "Wartung geplant", "audit.action.maintenance.create": "Wartung geplant",
"audit.action.maintenance.delete": "Wartung gelöscht", "audit.action.maintenance.delete": "Wartung gelöscht",
"audit.action.maintenance.update": "Wartung geändert", "audit.action.maintenance.update": "Wartung geändert",
"audit.action.member.join": "Der Organisation beigetreten", "audit.action.member.join": "Der Organisation beigetreten",
"audit.action.member.owner": "Owner geändert",
"audit.action.member.remove": "Mitglied entfernt", "audit.action.member.remove": "Mitglied entfernt",
"audit.action.member.role_assign": "Rolle zugewiesen", "audit.action.member.role_assign": "Rolle zugewiesen",
"audit.action.member.role_unassign": "Rolle entzogen", "audit.action.member.role_unassign": "Rolle entzogen",
@@ -98,6 +118,9 @@
"audit.action.platform.agent_delete": "Plattform-Agent widerrufen", "audit.action.platform.agent_delete": "Plattform-Agent widerrufen",
"audit.action.platform.check_types_update": "Check-Typen geändert", "audit.action.platform.check_types_update": "Check-Typen geändert",
"audit.action.platform.checker_network_update": "Checker-Netzwerk geändert", "audit.action.platform.checker_network_update": "Checker-Netzwerk geändert",
"audit.action.platform.idp_create": "Anmelde-Anbieter hinzugefügt",
"audit.action.platform.idp_delete": "Anmelde-Anbieter entfernt",
"audit.action.platform.idp_update": "Anmelde-Anbieter geändert",
"audit.action.platform.legal_update": "Rechtstext der Plattform geändert", "audit.action.platform.legal_update": "Rechtstext der Plattform geändert",
"audit.action.platform.limits_update": "Standard-Limits 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_delete": "Organisation durch Admin gelöscht",
@@ -128,6 +151,11 @@
"audit.action.statuspage.groups_import": "Statusseiten-Gruppen aus Monitor-Gruppen übernommen", "audit.action.statuspage.groups_import": "Statusseiten-Gruppen aus Monitor-Gruppen übernommen",
"audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert", "audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert",
"audit.action.statuspage.update": "Statusseite geändert", "audit.action.statuspage.update": "Statusseite geändert",
"audit.action.support.answer": "Support-Ticket beantwortet",
"audit.action.support.create": "Support-Ticket eröffnet",
"audit.action.support.reply": "Auf Support-Ticket geantwortet",
"audit.action.support.settings": "Support-Einstellungen geändert",
"audit.action.support.status": "Status eines Support-Tickets geändert",
"audit.action.token.create": "API-Token erstellt", "audit.action.token.create": "API-Token erstellt",
"audit.action.token.delete": "API-Token widerrufen", "audit.action.token.delete": "API-Token widerrufen",
"audit.deleted_user": "Gelöschter Benutzer", "audit.deleted_user": "Gelöschter Benutzer",
@@ -149,11 +177,14 @@
"auth.login.title": "Anmelden", "auth.login.title": "Anmelden",
"auth.login.to_signup": "Registrieren", "auth.login.to_signup": "Registrieren",
"auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.", "auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.",
"auth.or": "oder",
"auth.signup.submit": "Anlegen", "auth.signup.submit": "Anlegen",
"auth.signup.title": "Konto anlegen", "auth.signup.title": "Konto anlegen",
"auth.signup.to_login": "Zur Anmeldung", "auth.signup.to_login": "Zur Anmeldung",
"auth.sso.continue_with": "Weiter mit {{.Name}}",
"auth.sso.heading": "Single Sign-on", "auth.sso.heading": "Single Sign-on",
"auth.sso.org_placeholder": "Kurzname der Organisation", "auth.sso.org_placeholder": "Kurzname der Organisation",
"auth.sso.signup_with": "Registrieren mit {{.Name}}",
"auth.sso.submit": "Weiter", "auth.sso.submit": "Weiter",
"auth.verify.intro": "Drücke den Knopf, um deine E-Mail-Adresse zu bestätigen und dich anzumelden.", "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_intro": "Wenn ein unbestätigtes Konto diese Adresse nutzt, schicken wir ihm einen neuen Link.",
@@ -456,11 +487,22 @@
"common.no": "nein", "common.no": "nein",
"common.save": "Speichern", "common.save": "Speichern",
"common.yes": "ja", "common.yes": "ja",
"consent.accept_prefix": "Ich habe die",
"consent.accept_suffix": "gelesen und stimme zu.",
"consent.and": "und die",
"consent.decline": "Wenn du nicht zustimmst, kannst du deine Daten mitnehmen und dein Konto löschen.",
"consent.doc.privacy": "Datenschutzerklärung",
"consent.doc.terms": "AGB",
"consent.intro": "Um weiterzumachen, lies bitte diese Dokumente und stimme ihnen zu. Sie sind neu oder haben sich seit deiner letzten Zustimmung geändert.",
"consent.sso_hint": "Bei der Registrierung über einen Anbieter fragen wir direkt nach der ersten Anmeldung nach deiner Zustimmung.",
"consent.submit": "Zustimmen und weiter",
"consent.title": "Bitte stimme unseren Bedingungen zu",
"console.monitors.empty": "Noch keine Monitore angelegt.", "console.monitors.empty": "Noch keine Monitore angelegt.",
"console.monitors.title": "Monitore", "console.monitors.title": "Monitore",
"console.nav.admin": "Admin", "console.nav.admin": "Admin",
"console.nav.logout": "Abmelden", "console.nav.logout": "Abmelden",
"console.nav.members": "Mitglieder", "console.nav.members": "Mitglieder",
"console.nav.menu": "Menü",
"console.nav.org": "Organisation", "console.nav.org": "Organisation",
"console.nav.regions": "Regionen & Checker", "console.nav.regions": "Regionen & Checker",
"console.nav.roles": "Rollen", "console.nav.roles": "Rollen",
@@ -476,6 +518,10 @@
"email.opened.subject": "[DOWN] {{.Monitor}}", "email.opened.subject": "[DOWN] {{.Monitor}}",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.", "email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
"email.resolved.subject": "[UP] {{.Monitor}}", "email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hallo,\n\nein Support-Ticket wartet auf eine Antwort:\n\n{{.Subject}}\n\n{{.Link}}",
"email.support_admin.subject": "Support-Ticket: {{.Subject}}",
"email.support_reply.body": "Hallo,\n\nder Support hat dein Ticket „{{.Subject}}“ beantwortet:\n\n{{.Link}}\n\nWenn du weitere Fragen hast, antworte einfach dort.",
"email.support_reply.subject": "Antwort auf dein Support-Ticket: {{.Subject}}",
"email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.", "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.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.",
@@ -490,6 +536,8 @@
"error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert 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.check_type_disabled": "Dieser Check-Typ ist für diese Organisation oder Installation abgeschaltet.",
"error.confirmation_failed": "Die Bestätigung stimmt nicht.", "error.confirmation_failed": "Die Bestätigung stimmt nicht.",
"error.consent_outdated": "Die Dokumente haben sich inzwischen geändert. Lade die Seite neu und stimme der aktuellen Fassung zu.",
"error.consent_required": "Bitte stimme zuerst Datenschutz und AGB zu.",
"error.domain_not_verified": "Der TXT-Eintrag wurde noch nicht gefunden. DNS-Änderungen brauchen manchmal etwas Zeit.", "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.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.", "error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
@@ -498,6 +546,7 @@
"error.forbidden": "Dafür fehlt dir die Berechtigung.", "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_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.group_too_deep": "Gruppen lassen sich höchstens acht Ebenen tief verschachteln.",
"error.idp_in_use": "{{.Count}} Konten melden sich nur über diesen Anbieter an. Deaktiviere ihn stattdessen.",
"error.internal": "Interner Fehler.", "error.internal": "Interner Fehler.",
"error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.", "error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.",
"error.invalid_assertion_op": "Unbekannter Operator.", "error.invalid_assertion_op": "Unbekannter Operator.",
@@ -544,6 +593,8 @@
"error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.",
"error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.",
"error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.", "error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.",
"error.last_owner": "Die Organisation braucht mindestens einen Owner. Mache zuerst jemand anderen zum Owner.",
"error.last_sign_in": "Das ist der einzige Anmeldeweg des Kontos. Setze zuerst ein Passwort oder verbinde einen anderen Anbieter.",
"error.locked": "Die Ressource ist von einem anderen Prozess gesperrt.", "error.locked": "Die Ressource ist von einem anderen Prozess gesperrt.",
"error.maintenance_overlaps": "Die Wartung würde länger dauern als der Abstand bis zur Wiederholung.", "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.maintenance_without_targets": "Wähle mindestens einen Monitor oder eine Gruppe.",
@@ -555,9 +606,9 @@
"error.org_limit": "Dein Konto darf höchstens {{.Max}} Organisationen besitzen.", "error.org_limit": "Dein Konto darf höchstens {{.Max}} Organisationen besitzen.",
"error.org_not_found": "Organisation nicht gefunden.", "error.org_not_found": "Organisation nicht gefunden.",
"error.org_suspended": "Der Betreiber hat diese Organisation gesperrt.", "error.org_suspended": "Der Betreiber hat diese Organisation gesperrt.",
"error.owner_cannot_be_removed": "Der Owner kann nicht entfernt werden.", "error.owner_cannot_be_removed": "Owner können nicht entfernt werden. Entziehe zuerst die Owner-Rechte.",
"error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.", "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.owner_only": "Nur Owner können ändern, wem die Organisation gehört.",
"error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
"error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.", "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.platform_region_limit": "Ein Monitor darf aus höchstens {{.Max}} Plattform-Regionen geprüft werden; eigene Checker-Regionen zählen nicht.",
@@ -576,6 +627,7 @@
"error.slug_taken": "Dieser Kurzname ist bereits vergeben.", "error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
"error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.", "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.", "error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.",
"error.sso_email_unverified": "Der Anbieter hat für dieses Konto keine bestätigte E-Mail-Adresse, darum ist keine Registrierung möglich.",
"error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.", "error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.",
"error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.", "error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.",
"error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.", "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.",
@@ -587,18 +639,22 @@
"error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.", "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_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.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.",
"error.status_in_use": "Updates benutzen diesen Status; er bleibt, damit ihr Verlauf verständlich bleibt. Benenne ihn um oder ändere die Farbe.",
"error.status_name_taken": "Einen Status mit diesem Namen gibt es schon.",
"error.status_page_limit": "Deine Organisation hat ihr Limit von {{.Max}} Statusseiten erreicht.", "error.status_page_limit": "Deine Organisation hat ihr Limit von {{.Max}} Statusseiten erreicht.",
"error.support_disabled": "Support-Tickets sind auf dieser Plattform abgeschaltet.",
"error.suspended_ticket_limit": "Solange dein Konto gesperrt ist, kannst du ein Ticket eröffnen. Antworte stattdessen darauf.",
"error.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.", "error.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.",
"error.token_lifetime_exceeds_policy": { "error.token_lifetime_exceeds_policy": {
"one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.", "one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.",
"other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen." "other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen."
}, },
"error.too_many_tickets": "Du kannst {{.Count}} offene Tickets gleichzeitig haben. Schließe eins oder antworte stattdessen darauf.",
"error.totp_already_enabled": "TOTP ist bereits aktiv.", "error.totp_already_enabled": "TOTP ist bereits aktiv.",
"error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.",
"error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
"error.unauthenticated": "Anmeldung erforderlich.", "error.unauthenticated": "Anmeldung erforderlich.",
"error.unsupported_locale": "Sprache wird nicht unterstützt.", "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_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.", "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": "Antwort-Body",
@@ -641,6 +697,7 @@
"export.account_title": "Export personenbezogener Daten", "export.account_title": "Export personenbezogener Daten",
"export.download_json": "JSON herunterladen", "export.download_json": "JSON herunterladen",
"export.download_pdf": "PDF herunterladen", "export.download_pdf": "PDF herunterladen",
"export.field.accepted_at": "Zugestimmt am",
"export.field.account": "Konto", "export.field.account": "Konto",
"export.field.action": "Aktion", "export.field.action": "Aktion",
"export.field.activity": "Aktivität", "export.field.activity": "Aktivität",
@@ -651,10 +708,12 @@
"export.field.api_tokens": "API-Tokens", "export.field.api_tokens": "API-Tokens",
"export.field.audit_log": "Audit-Log", "export.field.audit_log": "Audit-Log",
"export.field.avg_latency_ms": "Mittlere Latenz (ms)", "export.field.avg_latency_ms": "Mittlere Latenz (ms)",
"export.field.body": "Text",
"export.field.cause": "Ursache", "export.field.cause": "Ursache",
"export.field.client_id": "Client-ID", "export.field.client_id": "Client-ID",
"export.field.config": "Konfiguration", "export.field.config": "Konfiguration",
"export.field.confirmations": "Bestätigungen", "export.field.confirmations": "Bestätigungen",
"export.field.consents": "Zugestimmte Dokumente",
"export.field.created_at": "Erstellt", "export.field.created_at": "Erstellt",
"export.field.custom_domain": "Eigene Domain", "export.field.custom_domain": "Eigene Domain",
"export.field.custom_roles": "Eigene Rollen", "export.field.custom_roles": "Eigene Rollen",
@@ -666,6 +725,7 @@
"export.field.email": "E-Mail", "export.field.email": "E-Mail",
"export.field.enabled": "Aktiv", "export.field.enabled": "Aktiv",
"export.field.expires_at": "Läuft ab", "export.field.expires_at": "Läuft ab",
"export.field.from_staff": "Vom Support",
"export.field.generated_at": "Erstellt am", "export.field.generated_at": "Erstellt am",
"export.field.group_id": "Gruppe", "export.field.group_id": "Gruppe",
"export.field.has_password": "Passwort gesetzt", "export.field.has_password": "Passwort gesetzt",
@@ -681,6 +741,8 @@
"export.field.locale": "Sprache", "export.field.locale": "Sprache",
"export.field.member_since": "Mitglied seit", "export.field.member_since": "Mitglied seit",
"export.field.members": "Mitglieder", "export.field.members": "Mitglieder",
"export.field.message": "Nachricht",
"export.field.messages": "Nachrichten",
"export.field.monitor": "Monitor", "export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitorgruppen", "export.field.monitor_groups": "Monitorgruppen",
"export.field.monitor_id": "Monitor-ID", "export.field.monitor_id": "Monitor-ID",
@@ -697,6 +759,7 @@
"export.field.platform_admin": "Plattform-Admin", "export.field.platform_admin": "Plattform-Admin",
"export.field.prefix": "Präfix", "export.field.prefix": "Präfix",
"export.field.provider": "Anbieter", "export.field.provider": "Anbieter",
"export.field.public": "Öffentlich",
"export.field.published": "Veröffentlicht", "export.field.published": "Veröffentlicht",
"export.field.region": "Region", "export.field.region": "Region",
"export.field.region_ids": "Regionen", "export.field.region_ids": "Regionen",
@@ -715,6 +778,7 @@
"export.field.status": "Status", "export.field.status": "Status",
"export.field.status_pages": "Statusseiten", "export.field.status_pages": "Statusseiten",
"export.field.subject": "Subjekt", "export.field.subject": "Subjekt",
"export.field.support_tickets": "Support-Tickets",
"export.field.target": "Ziel", "export.field.target": "Ziel",
"export.field.target_id": "Ziel", "export.field.target_id": "Ziel",
"export.field.time": "Zeit", "export.field.time": "Zeit",
@@ -723,7 +787,9 @@
"export.field.total": "Checks", "export.field.total": "Checks",
"export.field.totp_enabled_at": "Zwei-Faktor aktiviert", "export.field.totp_enabled_at": "Zwei-Faktor aktiviert",
"export.field.type": "Typ", "export.field.type": "Typ",
"export.field.updates": "Updates",
"export.field.user_agent": "Browser", "export.field.user_agent": "Browser",
"export.field.version": "Version",
"export.json_only": "Nur im JSON-Export enthalten.", "export.json_only": "Nur im JSON-Export enthalten.",
"export.no": "nein", "export.no": "nein",
"export.none": "Keine.", "export.none": "Keine.",
@@ -733,10 +799,11 @@
"gdpr.account_export_intro": "Lade alles herunter, was über dich gespeichert ist: Profil, Mitgliedschaften, Anmeldeidentitäten, API-Tokens und deine Aktivität. JSON ist maschinenlesbar, PDF gut lesbar.", "gdpr.account_export_intro": "Lade alles herunter, was über dich gespeichert ist: Profil, Mitgliedschaften, Anmeldeidentitäten, API-Tokens und deine Aktivität. JSON ist maschinenlesbar, PDF gut lesbar.",
"gdpr.delete_account": "Konto löschen", "gdpr.delete_account": "Konto löschen",
"gdpr.delete_account_confirm": "Konto endgültig löschen? Das lässt sich nicht rückgängig machen.", "gdpr.delete_account_confirm": "Konto endgültig löschen? Das lässt sich nicht rückgängig machen.",
"gdpr.delete_account_intro": "Löscht dein Konto sofort und meldet dich überall ab. Organisationen, denen nur du angehörst, werden mitgelöscht. Organisationen, die du mit anderen teilst und besitzt, musst du vorher übergeben oder löschen. Audit-Einträge in anderen Organisationen bleiben als „Gelöschter Benutzer“ erhalten.", "gdpr.delete_account_intro": "Löscht dein Konto sofort und meldet dich überall ab. Organisationen, deren letzter Owner du bist, werden mit allem darin mitgelöscht, auch für ihre anderen Mitglieder; aus Organisationen mit weiteren Ownern trittst du nur aus. Um eine Organisation zu erhalten, mache vorher jemand anderen zum Owner. Audit-Einträge in anderen Organisationen bleiben als „Gelöschter Benutzer“ erhalten.",
"gdpr.delete_org": "Organisation löschen", "gdpr.delete_org": "Organisation löschen",
"gdpr.delete_org_confirm": "Diese Organisation und alle ihre Daten endgültig löschen?", "gdpr.delete_org_confirm": "Diese Organisation und alle ihre Daten endgültig löschen?",
"gdpr.delete_org_intro": "Löscht die Organisation mit allen Monitoren, Check-Ergebnissen, Statusseiten, Zugängen der Mitglieder und API-Tokens, sofort und endgültig. Die Konten der Mitglieder bleiben bestehen.", "gdpr.delete_org_intro": "Löscht die Organisation mit allen Monitoren, Check-Ergebnissen, Statusseiten, Zugängen der Mitglieder und API-Tokens, sofort und endgültig. Die Konten der Mitglieder bleiben bestehen.",
"gdpr.deletes_orgs": "Du bist der letzte Owner dieser Organisationen. Sie werden mit deinem Konto gelöscht, mit allen Monitoren und Statusseiten, auch für ihre anderen Mitglieder, außer du machst vorher jemand anderen zum Owner:",
"gdpr.org_data": "Daten der Organisation", "gdpr.org_data": "Daten der Organisation",
"gdpr.org_export_intro": "Lade Mitglieder, Rollen, Monitore, Gruppen, Kanäle, Statusseiten, SSO-Einstellungen, Vorfälle, das Audit-Log und die Tagesstatistik herunter. Geheimnisse sind nicht enthalten.", "gdpr.org_export_intro": "Lade Mitglieder, Rollen, Monitore, Gruppen, Kanäle, Statusseiten, SSO-Einstellungen, Vorfälle, das Audit-Log und die Tagesstatistik herunter. Geheimnisse sind nicht enthalten.",
"gdpr.password": "Dein Passwort", "gdpr.password": "Dein Passwort",
@@ -751,6 +818,51 @@
"groups.none": "– oberste Ebene –", "groups.none": "– oberste Ebene –",
"groups.parent": "In Gruppe", "groups.parent": "In Gruppe",
"groups.title": "Monitor-Gruppen", "groups.title": "Monitor-Gruppen",
"idp.add": "Anbieter hinzufügen",
"idp.allow_signup": "Neue Leute dürfen sich damit registrieren",
"idp.callback": "Callback-URL, die beim Anbieter einzutragen ist:",
"idp.client_id": "Client-ID",
"idp.client_secret": "Client-Secret",
"idp.delete_confirm": "{{.Name}} entfernen? Konten verlieren diesen Anmeldeweg.",
"idp.enabled": "Aktiv",
"idp.intro": "Damit können sich Leute registrieren und anmelden. Ein bestehendes Konto mit derselben E-Mail wird nie übernommen: Sein Inhaber verbindet den Anbieter in den Sicherheitseinstellungen.",
"idp.issuer": "Issuer oder Server",
"idp.issuer_hint": "Bei OpenID Connect der Issuer, z. B. https://accounts.google.com oder https://login.microsoftonline.com/<tenant>/v2.0. Bei GitHub leer lassen oder den GitHub-Enterprise-Server angeben.",
"idp.kind": "Art",
"idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)",
"idp.signup_open": "Registrierung offen",
"idp.title": "Anmelde-Anbieter",
"incident.began": "Ausfall begann",
"incident.delete": "Löschen",
"incident.delete_confirm": "Dieses Update löschen? Es verschwindet auch von den Statusseiten.",
"incident.internal": "intern",
"incident.message": "Was ist los",
"incident.message_optional": "Nachricht (optional, Markdown)",
"incident.post": "Update veröffentlichen",
"incident.post_update": "Update veröffentlichen",
"incident.public": "Auf Statusseiten zeigen",
"incident.public_hint": "Ausgeschaltet bleibt es eine interne Notiz für dein Team.",
"incident.recovered": "Monitor wieder erreichbar",
"incident.set_status": "Status setzen",
"incident.status": "Status",
"incident.status.identified": "Ursache gefunden",
"incident.status.investigating": "Untersuchung läuft",
"incident.status.monitoring": "Beobachtung",
"incident.status.resolved": "Behoben",
"incident.timeline": "Verlauf",
"incident.title_heading": "Titel",
"incident.title_hint": "Erscheint auf Statusseiten; leer zeigt den Namen des Monitors.",
"incident.title_label": "Titel",
"incident.title_placeholder": "Anmeldung langsam",
"incident_statuses.add": "Status hinzufügen",
"incident_statuses.builtin": "Eingebaut",
"incident_statuses.color": "Farbe",
"incident_statuses.delete_confirm": "Diesen Status löschen? Geht nur, solange kein Update ihn benutzt.",
"incident_statuses.intro": "Status zur Auswahl, wenn ihr ein Update zu einem Ausfall veröffentlicht. Eigene erscheinen in ihrer Farbe in der Konsole und auf Statusseiten.",
"incident_statuses.none": "Noch keine.",
"incident_statuses.own": "Eigene",
"incident_statuses.placeholder": "Warten auf unseren Anbieter",
"incident_statuses.title": "Status für Ausfälle",
"incidents.all": "Alle Vorfälle", "incidents.all": "Alle Vorfälle",
"incidents.all_of_monitor": "Alle Vorfälle dieses Monitors", "incidents.all_of_monitor": "Alle Vorfälle dieses Monitors",
"incidents.none": "Bisher keine Incidents.", "incidents.none": "Bisher keine Incidents.",
@@ -768,11 +880,14 @@
"legal.hint": "Ein Link hat Vorrang vor dem Text. Beide Felder leer lassen, um das Dokument zu entfernen.", "legal.hint": "Ein Link hat Vorrang vor dem Text. Beide Felder leer lassen, um das Dokument zu entfernen.",
"legal.imprint": "Impressum", "legal.imprint": "Impressum",
"legal.markdown": "Oder Text (Markdown)", "legal.markdown": "Oder Text (Markdown)",
"legal.new_version": "Alle müssen neu zustimmen",
"legal.new_version_hint": "Für wesentliche Änderungen: Jedes Konto wird bei seiner nächsten Anfrage gebeten, der neuen Fassung zuzustimmen, und kann bis dahin nichts anderes nutzen. Für Korrekturen ausgeschaltet lassen.",
"legal.org_intro": "Werden auf den Statusseiten deiner Organisation angezeigt. Ohne eigene Dokumente werden die der Plattform verwendet.", "legal.org_intro": "Werden auf den Statusseiten deiner Organisation angezeigt. Ohne eigene Dokumente werden die der Plattform verwendet.",
"legal.org_title": "Impressum & Datenschutz", "legal.org_title": "Impressum & Datenschutz",
"legal.platform_intro": "Im Footer der Konsole und der Anmeldeseiten verlinkt sowie auf Statusseiten von Organisationen ohne eigene Dokumente.", "legal.platform_intro": "Im Fuß der Konsole und der Anmeldeseiten verlinkt; Impressum und Datenschutz auch auf Statusseiten von Organisationen ohne eigene. Jedes Konto stimmt Datenschutz und AGB bei der Registrierung zu und erneut, wenn du es verlangst.",
"legal.platform_title": "Impressum & Datenschutz der Plattform", "legal.platform_title": "Impressum, Datenschutz & AGB der Plattform",
"legal.privacy": "Datenschutz", "legal.privacy": "Datenschutz",
"legal.terms": "AGB",
"legal.url": "Link auf eine bestehende Seite", "legal.url": "Link auf eine bestehende Seite",
"limits.default": "Standard: {{.Value}}", "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.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.",
@@ -846,19 +961,25 @@
"md.ul": "Aufzählung", "md.ul": "Aufzählung",
"md.write": "Schreiben", "md.write": "Schreiben",
"members.assign": "Rolle hinzufügen", "members.assign": "Rolle hinzufügen",
"members.intro": "Rollen bestimmen, was ein Mitglied darf. Niemand kann Berechtigungen vergeben, die er selbst nicht hat.", "members.intro": "Rollen bestimmen, was ein Mitglied darf. Niemand kann Berechtigungen vergeben, die er selbst nicht hat. Owner dürfen alles; eine Organisation kann mehrere haben und behält immer mindestens einen.",
"members.invite": "Einladen", "members.invite": "Einladen",
"members.invite_link": "Schicke diesen Link an die eingeladene Person. Er gilt 7 Tage und funktioniert einmal.", "members.invite_link": "Schicke diesen Link an die eingeladene Person. Er gilt 7 Tage und funktioniert einmal.",
"members.invite_submit": "Einladung erstellen", "members.invite_submit": "Einladung erstellen",
"members.make_owner": "Zum Owner machen",
"members.make_owner_confirm": "{{.Email}} zum Owner machen? Owner dürfen alles, auch die Organisation löschen und bestimmen, wer noch Owner ist.",
"members.owner": "Owner", "members.owner": "Owner",
"members.pending": "Offene Einladungen", "members.pending": "Offene Einladungen",
"members.remove": "Aus der Organisation entfernen", "members.remove": "Aus der Organisation entfernen",
"members.remove_confirm": "Dieses Mitglied entfernen? Seine Sessions und API-Tokens enden sofort.", "members.remove_confirm": "Dieses Mitglied entfernen? Seine Sessions und API-Tokens enden sofort.",
"members.remove_owner": "Als Owner entfernen",
"members.remove_owner_confirm": "{{.Email}} die Owner-Rechte entziehen? Ohne andere Rollen bleibt die Person als Admin dabei.",
"members.revoke": "Widerrufen", "members.revoke": "Widerrufen",
"members.role": "Rolle", "members.role": "Rolle",
"members.roles": "Rollen", "members.roles": "Rollen",
"members.scope": "Beschränkt auf", "members.scope": "Beschränkt auf",
"members.scope_org": "gesamte Organisation", "members.scope_org": "gesamte Organisation",
"members.step_down": "Als Owner zurücktreten",
"members.step_down_confirm": "Als Owner zurücktreten? Ohne andere Rollen arbeitest du mit der Admin-Rolle weiter.",
"members.title": "Mitglieder", "members.title": "Mitglieder",
"members.unassign": "Rolle entfernen", "members.unassign": "Rolle entfernen",
"moderation.actions": "Sperren oder löschen …", "moderation.actions": "Sperren oder löschen …",
@@ -1184,6 +1305,10 @@
"scope.status_page": "Statuspage", "scope.status_page": "Statuspage",
"security.activity": "Kontoaktivität", "security.activity": "Kontoaktivität",
"security.activity_intro": "Letzte Anmeldungen und Sicherheitsänderungen an deinem Konto. Wende dich an einen Administrator, wenn du einen Eintrag nicht erkennst.", "security.activity_intro": "Letzte Anmeldungen und Sicherheitsänderungen an deinem Konto. Wende dich an einen Administrator, wenn du einen Eintrag nicht erkennst.",
"security.platform_sso.heading": "Anmelden mit anderen Konten",
"security.platform_sso.link": "{{.Name}} verbinden",
"security.platform_sso.unlink": "Trennen",
"security.platform_sso.unlink_confirm": "Nicht mehr mit {{.Name}} anmelden?",
"security.recovery.left": { "security.recovery.left": {
"one": "{{.Count}} Wiederherstellungscode übrig", "one": "{{.Count}} Wiederherstellungscode übrig",
"other": "{{.Count}} Wiederherstellungscodes übrig" "other": "{{.Count}} Wiederherstellungscodes übrig"
@@ -1210,6 +1335,7 @@
"settings.audit": "Wer wann was geändert hat.", "settings.audit": "Wer wann was geändert hat.",
"settings.channels": "Webhooks und E-Mail für Incidents", "settings.channels": "Webhooks und E-Mail für Incidents",
"settings.groups": "Monitore in verschachtelten Gruppen ordnen", "settings.groups": "Monitore in verschachtelten Gruppen ordnen",
"settings.incident_statuses": "Eigene Status mit Farbe für Updates zu Ausfällen.",
"settings.legal": "Impressum und Datenschutzerklärung für deine Statusseiten.", "settings.legal": "Impressum und Datenschutzerklärung für deine Statusseiten.",
"settings.members": "Personen einladen und Rollen vergeben", "settings.members": "Personen einladen und Rollen vergeben",
"settings.org": "Anmelderichtlinien und Token-Laufzeit", "settings.org": "Anmelderichtlinien und Token-Laufzeit",
@@ -1270,6 +1396,79 @@
"storage.retention": "Löschen nach", "storage.retention": "Löschen nach",
"storage.size": "Größe", "storage.size": "Größe",
"storage.title": "Datenspeicher", "storage.title": "Datenspeicher",
"support.account": "Konto",
"support.account.active": "aktiv",
"support.account.created": "Erstellt",
"support.account.email": "E-Mail",
"support.account.email_verified": "E-Mail bestätigt",
"support.account.locale": "Sprache",
"support.account.monitors": "Monitore",
"support.account.name": "Name",
"support.account.open_tickets": "Offene Tickets",
"support.account.org_suspended": "Organisation gesperrt",
"support.account.orgs": "Organisationen",
"support.account.orgs_owned": "Eigene Organisationen",
"support.account.owner": "Owner",
"support.account.password": "Passwort",
"support.account.regions": "Regionen pro Monitor",
"support.account.role": "Rolle",
"support.account.sign_in": "Anmeldung",
"support.account.sso_only": "nur SSO",
"support.account.state": "Zustand",
"support.account.status_pages": "Statusseiten",
"support.account.suspended": "gesperrt",
"support.account.this_ticket": "im Ticket genannt",
"support.admin_intro": "Tickets aller Konten. Eine Antwort wird dem Konto per E-Mail angekündigt; schreibt es zurück, ist das Ticket wieder offen.",
"support.admin_title": "Support-Tickets",
"support.all": "Alle Tickets",
"support.attach": "Details anhängen (optional)",
"support.attach_hint": "Zeig dem Support, worum es geht – aus der aktiven Organisation.",
"support.attach_none": "keine Auswahl",
"support.attach_org": "Organisation {{.Org}}",
"support.close": "Ticket schließen",
"support.closed_hint": "Dieses Ticket ist geschlossen. Mit einer Antwort öffnest du es wieder.",
"support.contact": "Support kontaktieren",
"support.disabled": "Support-Tickets sind gerade abgeschaltet.",
"support.filter": "Tickets filtern",
"support.filter.all": "Alle",
"support.filter.answered": "Beantwortet",
"support.filter.closed": "Geschlossen",
"support.filter.open": "Offen",
"support.from_staff": "Support",
"support.from_you": "Du",
"support.intro": "Fragen, Probleme oder Feedback? Schreib dem Support der Plattform. Sobald er antwortet, bekommst du eine E-Mail.",
"support.message": "Nachricht",
"support.mine": "Deine Tickets",
"support.new": "Neues Ticket",
"support.no": "nein",
"support.none": "Du hast noch keine Tickets eröffnet.",
"support.none_admin": "Hier gibt es keine Tickets.",
"support.ref.alert_group": "Alertgruppe",
"support.ref.channel": "Alert-Typ (Benachrichtigungskanal)",
"support.ref.incident": "Incident",
"support.ref.monitor": "Monitor",
"support.ref.org": "Organisation",
"support.ref.status_page": "Statusseite",
"support.reopen": "Ticket wieder öffnen",
"support.reply": "Antworten",
"support.send": "Senden",
"support.settings": "Einstellungen",
"support.settings.enabled": "Konten können Support-Tickets eröffnen",
"support.settings.enabled_hint": "Abgeschaltet verschwinden die Support-Seiten für Konten; die bestehenden Tickets bleiben hier erhalten.",
"support.settings.max_open": "Offene Tickets pro Konto",
"support.settings.max_open_hint": "Offene und beantwortete Tickets zählen; 0 heißt unbegrenzt. Gesperrte Konten können ein Ticket eröffnen.",
"support.settings.off": "aus",
"support.settings.on": "an",
"support.settings.save": "Speichern",
"support.status.answered": "beantwortet",
"support.status.closed": "geschlossen",
"support.status.open": "offen",
"support.subject": "Betreff",
"support.title": "Support",
"support.yes": "ja",
"suspended.intro": "Die Administratoren der Plattform haben dein Konto gesperrt.",
"suspended.options": "Du kannst deine Daten weiterhin herunterladen oder dein Konto löschen.",
"suspended.title": "Konto gesperrt",
"tokens.copy_now": "Kopiere den Token jetzt. Er wird nicht erneut angezeigt.", "tokens.copy_now": "Kopiere den Token jetzt. Er wird nicht erneut angezeigt.",
"tokens.create": "Token erstellen", "tokens.create": "Token erstellen",
"tokens.created": "Erstellt", "tokens.created": "Erstellt",
+206 -7
View File
@@ -10,11 +10,21 @@
"agents.allow_private_hint": "Checkers only. Switch off if the checker runs in a network monitors must not look into.", "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.allow_private_short": "private addresses",
"agents.create": "Create agent", "agents.create": "Create agent",
"agents.install_auto": "Update automatically",
"agents.install_auto_hint": "Uses the self-updating image: the agent follows this platform's release by itself, with signed downloads and rollback. Without it, you update the agent yourself.",
"agents.install_compose": "Or with Docker Compose",
"agents.install_compose_hint": "Put both files in one directory and run docker compose up -d there.",
"agents.install_heading": "Install it",
"agents.install_oneliner": "On a Linux host with Docker",
"agents.install_statuspage_hint": "Add --host status.example.com for the host name that serves pages, and --tls --email you@example.com for HTTPS with Let's Encrypt. --help lists all options.",
"agents.kind": "Kind", "agents.kind": "Kind",
"agents.kind_checker": "Checker", "agents.kind_checker": "Checker",
"agents.kind_statuspage": "Status page server", "agents.kind_statuspage": "Status page server",
"agents.list": "Agents", "agents.list": "Agents",
"agents.no_region": "– (status page servers only)", "agents.no_region": "– (status page servers only)",
"agents.outdated": "outdated",
"agents.outdated_hint": "Behind the platform's release. Self-updating agents catch up by themselves; for the plain image run docker compose pull && docker compose up -d where it is installed.",
"agents.platform_release": "The platform runs {{.Release}}.",
"agents.region": "Region", "agents.region": "Region",
"agents.revoke_confirm": "Revoke this agent? Its instances stop working immediately.", "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.", "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.",
@@ -50,8 +60,11 @@
"apidocs.hint": "\"Try it out\" uses your current session.", "apidocs.hint": "\"Try it out\" uses your current session.",
"apidocs.title": "API documentation", "apidocs.title": "API documentation",
"app.network_error": "Connection failed.", "app.network_error": "Connection failed.",
"audit.action.account.consent": "Privacy policy and terms accepted",
"audit.action.account.delete": "Account deleted", "audit.action.account.delete": "Account deleted",
"audit.action.account.export": "Personal data exported", "audit.action.account.export": "Personal data exported",
"audit.action.account.identity_link": "Sign-in provider connected",
"audit.action.account.identity_unlink": "Sign-in provider disconnected",
"audit.action.account.recovery_codes": "Recovery codes regenerated", "audit.action.account.recovery_codes": "Recovery codes regenerated",
"audit.action.account.signup": "Account created", "audit.action.account.signup": "Account created",
"audit.action.account.totp_disable": "Two-factor authentication disabled", "audit.action.account.totp_disable": "Two-factor authentication disabled",
@@ -76,12 +89,19 @@
"audit.action.group.create": "Group created", "audit.action.group.create": "Group created",
"audit.action.group.delete": "Group deleted", "audit.action.group.delete": "Group deleted",
"audit.action.group.update": "Group changed", "audit.action.group.update": "Group changed",
"audit.action.incident.title": "Incident renamed",
"audit.action.incident.update": "Incident update posted",
"audit.action.incident.update_delete": "Incident update deleted",
"audit.action.incident_status.create": "Incident status added",
"audit.action.incident_status.delete": "Incident status deleted",
"audit.action.incident_status.update": "Incident status changed",
"audit.action.invitation.create": "Invitation sent", "audit.action.invitation.create": "Invitation sent",
"audit.action.invitation.delete": "Invitation withdrawn", "audit.action.invitation.delete": "Invitation withdrawn",
"audit.action.maintenance.create": "Maintenance planned", "audit.action.maintenance.create": "Maintenance planned",
"audit.action.maintenance.delete": "Maintenance deleted", "audit.action.maintenance.delete": "Maintenance deleted",
"audit.action.maintenance.update": "Maintenance changed", "audit.action.maintenance.update": "Maintenance changed",
"audit.action.member.join": "Joined the organization", "audit.action.member.join": "Joined the organization",
"audit.action.member.owner": "Ownership changed",
"audit.action.member.remove": "Member removed", "audit.action.member.remove": "Member removed",
"audit.action.member.role_assign": "Role assigned", "audit.action.member.role_assign": "Role assigned",
"audit.action.member.role_unassign": "Role removed", "audit.action.member.role_unassign": "Role removed",
@@ -98,6 +118,9 @@
"audit.action.platform.agent_delete": "Platform agent revoked", "audit.action.platform.agent_delete": "Platform agent revoked",
"audit.action.platform.check_types_update": "Check types changed", "audit.action.platform.check_types_update": "Check types changed",
"audit.action.platform.checker_network_update": "Checker network changed", "audit.action.platform.checker_network_update": "Checker network changed",
"audit.action.platform.idp_create": "Sign-in provider added",
"audit.action.platform.idp_delete": "Sign-in provider removed",
"audit.action.platform.idp_update": "Sign-in provider changed",
"audit.action.platform.legal_update": "Platform legal document changed", "audit.action.platform.legal_update": "Platform legal document changed",
"audit.action.platform.limits_update": "Default limits changed", "audit.action.platform.limits_update": "Default limits changed",
"audit.action.platform.org_delete": "Organization deleted by admin", "audit.action.platform.org_delete": "Organization deleted by admin",
@@ -128,6 +151,11 @@
"audit.action.statuspage.groups_import": "Status page groups imported from monitor groups", "audit.action.statuspage.groups_import": "Status page groups imported from monitor groups",
"audit.action.statuspage.monitors_update": "Status page monitors changed", "audit.action.statuspage.monitors_update": "Status page monitors changed",
"audit.action.statuspage.update": "Status page changed", "audit.action.statuspage.update": "Status page changed",
"audit.action.support.answer": "Support ticket answered",
"audit.action.support.create": "Support ticket opened",
"audit.action.support.reply": "Support ticket replied to",
"audit.action.support.settings": "Support settings changed",
"audit.action.support.status": "Support ticket status changed",
"audit.action.token.create": "API token created", "audit.action.token.create": "API token created",
"audit.action.token.delete": "API token revoked", "audit.action.token.delete": "API token revoked",
"audit.deleted_user": "Deleted user", "audit.deleted_user": "Deleted user",
@@ -149,11 +177,14 @@
"auth.login.title": "Sign in", "auth.login.title": "Sign in",
"auth.login.to_signup": "Sign up", "auth.login.to_signup": "Sign up",
"auth.login.totp_hint": "Enter the code from your authenticator app or one of your recovery codes.", "auth.login.totp_hint": "Enter the code from your authenticator app or one of your recovery codes.",
"auth.or": "or",
"auth.signup.submit": "Create", "auth.signup.submit": "Create",
"auth.signup.title": "Create account", "auth.signup.title": "Create account",
"auth.signup.to_login": "Back to sign in", "auth.signup.to_login": "Back to sign in",
"auth.sso.continue_with": "Continue with {{.Name}}",
"auth.sso.heading": "Single sign-on", "auth.sso.heading": "Single sign-on",
"auth.sso.org_placeholder": "Organization short name", "auth.sso.org_placeholder": "Organization short name",
"auth.sso.signup_with": "Sign up with {{.Name}}",
"auth.sso.submit": "Continue", "auth.sso.submit": "Continue",
"auth.verify.intro": "Press the button to confirm your email address and sign in.", "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_intro": "If an unconfirmed account uses this address, we send it a new link.",
@@ -456,11 +487,22 @@
"common.no": "no", "common.no": "no",
"common.save": "Save", "common.save": "Save",
"common.yes": "yes", "common.yes": "yes",
"consent.accept_prefix": "I have read and accept the",
"consent.accept_suffix": ".",
"consent.and": "and the",
"consent.decline": "If you do not agree, you can take your data with you and delete your account.",
"consent.doc.privacy": "privacy policy",
"consent.doc.terms": "terms of service",
"consent.intro": "To continue, please read and accept these documents. They are new or have changed since you last accepted them.",
"consent.sso_hint": "Signing up with a provider asks for your consent right after the first sign-in.",
"consent.submit": "Accept and continue",
"consent.title": "Please accept our terms",
"console.monitors.empty": "No monitors yet.", "console.monitors.empty": "No monitors yet.",
"console.monitors.title": "Monitors", "console.monitors.title": "Monitors",
"console.nav.admin": "Admin", "console.nav.admin": "Admin",
"console.nav.logout": "Sign out", "console.nav.logout": "Sign out",
"console.nav.members": "Members", "console.nav.members": "Members",
"console.nav.menu": "Menu",
"console.nav.org": "Organization", "console.nav.org": "Organization",
"console.nav.regions": "Regions & checkers", "console.nav.regions": "Regions & checkers",
"console.nav.roles": "Roles", "console.nav.roles": "Roles",
@@ -476,6 +518,10 @@
"email.opened.subject": "[DOWN] {{.Monitor}}", "email.opened.subject": "[DOWN] {{.Monitor}}",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.", "email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
"email.resolved.subject": "[UP] {{.Monitor}}", "email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hello,\n\na support ticket waits for an answer:\n\n{{.Subject}}\n\n{{.Link}}",
"email.support_admin.subject": "Support ticket: {{.Subject}}",
"email.support_reply.body": "Hello,\n\nthe support team answered your ticket \"{{.Subject}}\":\n\n{{.Link}}\n\nReply there if you have further questions.",
"email.support_reply.subject": "Answer to your support ticket: {{.Subject}}",
"email.test.body": "This is a test. If you can read it, the channel works.", "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.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.",
@@ -490,6 +536,8 @@
"error.channel_type_immutable": "The type of a channel cannot be changed.", "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.check_type_disabled": "This check type is switched off for this organization or installation.",
"error.confirmation_failed": "The confirmation does not match.", "error.confirmation_failed": "The confirmation does not match.",
"error.consent_outdated": "The documents changed in the meantime. Reload the page and accept the current version.",
"error.consent_required": "Please accept the privacy policy and terms first.",
"error.domain_not_verified": "The TXT record was not found yet. DNS changes can take a while to appear.", "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.domain_taken": "This domain is already used by another status page.",
"error.email_not_configured": "Email is not available on this server.", "error.email_not_configured": "Email is not available on this server.",
@@ -498,6 +546,7 @@
"error.forbidden": "You are not allowed to do this.", "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_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.group_too_deep": "Groups can be nested at most eight levels deep.",
"error.idp_in_use": "{{.Count}} accounts sign in only through this provider. Disable it instead.",
"error.internal": "Internal error.", "error.internal": "Internal error.",
"error.invalid_alert_group": "An alert group does not exist in this organization.", "error.invalid_alert_group": "An alert group does not exist in this organization.",
"error.invalid_assertion_op": "Unknown condition operator.", "error.invalid_assertion_op": "Unknown condition operator.",
@@ -544,6 +593,8 @@
"error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.",
"error.invitation_invalid": "This invitation is invalid, expired or was already used.", "error.invitation_invalid": "This invitation is invalid, expired or was already used.",
"error.keyword_needs_get": "Keyword checks need GET requests.", "error.keyword_needs_get": "Keyword checks need GET requests.",
"error.last_owner": "The organization needs at least one owner. Make someone else owner first.",
"error.last_sign_in": "This is the account's only way to sign in. Set a password or connect another provider first.",
"error.locked": "The resource is locked by another process.", "error.locked": "The resource is locked by another process.",
"error.maintenance_overlaps": "The maintenance would last longer than the time until it repeats.", "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.maintenance_without_targets": "Choose at least one monitor or group.",
@@ -555,9 +606,9 @@
"error.org_limit": "Your account may own at most {{.Max}} organizations.", "error.org_limit": "Your account may own at most {{.Max}} organizations.",
"error.org_not_found": "Organization not found.", "error.org_not_found": "Organization not found.",
"error.org_suspended": "The operator suspended this organization.", "error.org_suspended": "The operator suspended this organization.",
"error.owner_cannot_be_removed": "The owner cannot be removed.", "error.owner_cannot_be_removed": "Owners cannot be removed. Take their ownership away first.",
"error.owner_has_all_permissions": "The owner already has every permission.", "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.owner_only": "Only owners can change who owns the organization.",
"error.password_too_short": "The password needs at least {{.Min}} characters.", "error.password_too_short": "The password needs at least {{.Min}} characters.",
"error.permission_escalation": "You cannot grant permissions you do not hold yourself.", "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.platform_region_limit": "A monitor may be checked from at most {{.Max}} platform regions; your own checker regions do not count.",
@@ -576,6 +627,7 @@
"error.slug_taken": "This short name is already taken.", "error.slug_taken": "This short name is already taken.",
"error.sso_denied": "Sign-in was cancelled at the identity provider.", "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.", "error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.",
"error.sso_email_unverified": "The provider did not confirm an email address for this account, so it cannot sign up here.",
"error.sso_expired": "The sign-in attempt expired, please start again.", "error.sso_expired": "The sign-in attempt expired, please start again.",
"error.sso_forbidden_address": "The issuer points to a non-public address.", "error.sso_forbidden_address": "The issuer points to a non-public address.",
"error.sso_identity_taken": "This SSO sign-in is already linked to another account.", "error.sso_identity_taken": "This SSO sign-in is already linked to another account.",
@@ -587,18 +639,22 @@
"error.sso_provider_error": "The identity provider could not complete the sign-in.", "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_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.sso_unavailable": "Single sign-on is not available for this organization.",
"error.status_in_use": "Updates use this status; it stays so their history keeps its meaning. Rename or recolor it instead.",
"error.status_name_taken": "A status with this name exists already.",
"error.status_page_limit": "Your organization has reached its limit of {{.Max}} status pages.", "error.status_page_limit": "Your organization has reached its limit of {{.Max}} status pages.",
"error.support_disabled": "Support tickets are switched off on this platform.",
"error.suspended_ticket_limit": "While your account is suspended you can open one ticket. Reply to it instead.",
"error.target_is_admin": "Platform admins cannot be suspended or deleted here.", "error.target_is_admin": "Platform admins cannot be suspended or deleted here.",
"error.token_lifetime_exceeds_policy": { "error.token_lifetime_exceeds_policy": {
"one": "Tokens in this organization must expire within {{.Count}} day.", "one": "Tokens in this organization must expire within {{.Count}} day.",
"other": "Tokens in this organization must expire within {{.Count}} days." "other": "Tokens in this organization must expire within {{.Count}} days."
}, },
"error.too_many_tickets": "You can have {{.Count}} open tickets at the same time. Close one or reply to it instead.",
"error.totp_already_enabled": "TOTP is already active.", "error.totp_already_enabled": "TOTP is already active.",
"error.totp_required_by_org": "One of your organizations requires TOTP.", "error.totp_required_by_org": "One of your organizations requires TOTP.",
"error.totp_setup_expired": "Setup expired, please start again.", "error.totp_setup_expired": "Setup expired, please start again.",
"error.unauthenticated": "Authentication required.", "error.unauthenticated": "Authentication required.",
"error.unsupported_locale": "Unsupported language.", "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_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.", "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": "Response body",
@@ -641,6 +697,7 @@
"export.account_title": "Personal data export", "export.account_title": "Personal data export",
"export.download_json": "Download JSON", "export.download_json": "Download JSON",
"export.download_pdf": "Download PDF", "export.download_pdf": "Download PDF",
"export.field.accepted_at": "Accepted at",
"export.field.account": "Account", "export.field.account": "Account",
"export.field.action": "Action", "export.field.action": "Action",
"export.field.activity": "Activity", "export.field.activity": "Activity",
@@ -651,10 +708,12 @@
"export.field.api_tokens": "API tokens", "export.field.api_tokens": "API tokens",
"export.field.audit_log": "Audit log", "export.field.audit_log": "Audit log",
"export.field.avg_latency_ms": "Average latency (ms)", "export.field.avg_latency_ms": "Average latency (ms)",
"export.field.body": "Text",
"export.field.cause": "Cause", "export.field.cause": "Cause",
"export.field.client_id": "Client ID", "export.field.client_id": "Client ID",
"export.field.config": "Configuration", "export.field.config": "Configuration",
"export.field.confirmations": "Confirmations", "export.field.confirmations": "Confirmations",
"export.field.consents": "Accepted documents",
"export.field.created_at": "Created", "export.field.created_at": "Created",
"export.field.custom_domain": "Custom domain", "export.field.custom_domain": "Custom domain",
"export.field.custom_roles": "Custom roles", "export.field.custom_roles": "Custom roles",
@@ -666,6 +725,7 @@
"export.field.email": "Email", "export.field.email": "Email",
"export.field.enabled": "Enabled", "export.field.enabled": "Enabled",
"export.field.expires_at": "Expires", "export.field.expires_at": "Expires",
"export.field.from_staff": "From support",
"export.field.generated_at": "Generated", "export.field.generated_at": "Generated",
"export.field.group_id": "Group", "export.field.group_id": "Group",
"export.field.has_password": "Password set", "export.field.has_password": "Password set",
@@ -681,6 +741,8 @@
"export.field.locale": "Language", "export.field.locale": "Language",
"export.field.member_since": "Member since", "export.field.member_since": "Member since",
"export.field.members": "Members", "export.field.members": "Members",
"export.field.message": "Message",
"export.field.messages": "Messages",
"export.field.monitor": "Monitor", "export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitor groups", "export.field.monitor_groups": "Monitor groups",
"export.field.monitor_id": "Monitor ID", "export.field.monitor_id": "Monitor ID",
@@ -697,6 +759,7 @@
"export.field.platform_admin": "Platform admin", "export.field.platform_admin": "Platform admin",
"export.field.prefix": "Prefix", "export.field.prefix": "Prefix",
"export.field.provider": "Provider", "export.field.provider": "Provider",
"export.field.public": "Public",
"export.field.published": "Published", "export.field.published": "Published",
"export.field.region": "Region", "export.field.region": "Region",
"export.field.region_ids": "Regions", "export.field.region_ids": "Regions",
@@ -715,6 +778,7 @@
"export.field.status": "Status", "export.field.status": "Status",
"export.field.status_pages": "Status pages", "export.field.status_pages": "Status pages",
"export.field.subject": "Subject", "export.field.subject": "Subject",
"export.field.support_tickets": "Support tickets",
"export.field.target": "Target", "export.field.target": "Target",
"export.field.target_id": "Target", "export.field.target_id": "Target",
"export.field.time": "Time", "export.field.time": "Time",
@@ -723,7 +787,9 @@
"export.field.total": "Checks", "export.field.total": "Checks",
"export.field.totp_enabled_at": "Two-factor enabled", "export.field.totp_enabled_at": "Two-factor enabled",
"export.field.type": "Type", "export.field.type": "Type",
"export.field.updates": "Updates",
"export.field.user_agent": "Browser", "export.field.user_agent": "Browser",
"export.field.version": "Version",
"export.json_only": "Included in the JSON export only.", "export.json_only": "Included in the JSON export only.",
"export.no": "no", "export.no": "no",
"export.none": "None.", "export.none": "None.",
@@ -733,10 +799,11 @@
"gdpr.account_export_intro": "Download everything stored about you: profile, memberships, sign-in identities, API tokens and your activity. JSON is machine-readable, PDF easy to read.", "gdpr.account_export_intro": "Download everything stored about you: profile, memberships, sign-in identities, API tokens and your activity. JSON is machine-readable, PDF easy to read.",
"gdpr.delete_account": "Delete account", "gdpr.delete_account": "Delete account",
"gdpr.delete_account_confirm": "Delete your account permanently? This cannot be undone.", "gdpr.delete_account_confirm": "Delete your account permanently? This cannot be undone.",
"gdpr.delete_account_intro": "Deletes your account immediately and signs you out everywhere. Organizations only you belong to are deleted with it. Organizations you own together with others must be handed over or deleted first. Audit entries in other organizations remain, showing \"deleted user\".", "gdpr.delete_account_intro": "Deletes your account immediately and signs you out everywhere. Organizations you are the last owner of are deleted with it, with everything in them, also for their other members; organizations with further owners you just leave. To keep an organization, make someone else owner first. Audit entries in other organizations remain, showing \"deleted user\".",
"gdpr.delete_org": "Delete organization", "gdpr.delete_org": "Delete organization",
"gdpr.delete_org_confirm": "Delete this organization and all its data permanently?", "gdpr.delete_org_confirm": "Delete this organization and all its data permanently?",
"gdpr.delete_org_intro": "Deletes the organization with all monitors, check results, status pages, members' access and API tokens, immediately and permanently. Members' accounts remain.", "gdpr.delete_org_intro": "Deletes the organization with all monitors, check results, status pages, members' access and API tokens, immediately and permanently. Members' accounts remain.",
"gdpr.deletes_orgs": "You are the last owner of these organizations. They are deleted with your account, with all their monitors and status pages, also for their other members, unless you make someone else owner first:",
"gdpr.org_data": "Organization data", "gdpr.org_data": "Organization data",
"gdpr.org_export_intro": "Download members, roles, monitors, groups, channels, status pages, SSO settings, incidents, the audit log and daily statistics. Secrets are not included.", "gdpr.org_export_intro": "Download members, roles, monitors, groups, channels, status pages, SSO settings, incidents, the audit log and daily statistics. Secrets are not included.",
"gdpr.password": "Your password", "gdpr.password": "Your password",
@@ -751,6 +818,51 @@
"groups.none": "– top level –", "groups.none": "– top level –",
"groups.parent": "Inside group", "groups.parent": "Inside group",
"groups.title": "Monitor groups", "groups.title": "Monitor groups",
"idp.add": "Add provider",
"idp.allow_signup": "New people may sign up with it",
"idp.callback": "Callback URL to register at the provider:",
"idp.client_id": "Client ID",
"idp.client_secret": "Client secret",
"idp.delete_confirm": "Remove {{.Name}}? Accounts lose this way to sign in.",
"idp.enabled": "Enabled",
"idp.intro": "People can sign up and sign in with these accounts. An existing account with the same email is never taken over: its owner connects the provider in the security settings.",
"idp.issuer": "Issuer or server",
"idp.issuer_hint": "For OpenID Connect the issuer, e.g. https://accounts.google.com or https://login.microsoftonline.com/<tenant>/v2.0. For GitHub leave it empty, or give your GitHub Enterprise server.",
"idp.kind": "Kind",
"idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)",
"idp.signup_open": "sign-up open",
"idp.title": "Sign-in providers",
"incident.began": "Outage began",
"incident.delete": "Delete",
"incident.delete_confirm": "Delete this update? It disappears from status pages too.",
"incident.internal": "internal",
"incident.message": "What is going on",
"incident.message_optional": "Message (optional, Markdown)",
"incident.post": "Post update",
"incident.post_update": "Post an update",
"incident.public": "Show on status pages",
"incident.public_hint": "Off keeps it an internal note for your team.",
"incident.recovered": "Monitor recovered",
"incident.set_status": "Set status",
"incident.status": "Status",
"incident.status.identified": "Identified",
"incident.status.investigating": "Investigating",
"incident.status.monitoring": "Monitoring",
"incident.status.resolved": "Resolved",
"incident.timeline": "Timeline",
"incident.title_heading": "Title",
"incident.title_hint": "Shown on status pages; empty shows the monitor's name.",
"incident.title_label": "Title",
"incident.title_placeholder": "Sign-in is slow",
"incident_statuses.add": "Add status",
"incident_statuses.builtin": "Built in",
"incident_statuses.color": "Color",
"incident_statuses.delete_confirm": "Delete this status? Only possible while no update uses it.",
"incident_statuses.intro": "Statuses to choose from when posting an incident update. Your own appear in their color in the console and on status pages.",
"incident_statuses.none": "None yet.",
"incident_statuses.own": "Your own",
"incident_statuses.placeholder": "Waiting for our provider",
"incident_statuses.title": "Incident statuses",
"incidents.all": "All incidents", "incidents.all": "All incidents",
"incidents.all_of_monitor": "All incidents of this monitor", "incidents.all_of_monitor": "All incidents of this monitor",
"incidents.none": "No incidents so far.", "incidents.none": "No incidents so far.",
@@ -768,11 +880,14 @@
"legal.hint": "A link takes precedence over the text. Leave both empty to remove the document.", "legal.hint": "A link takes precedence over the text. Leave both empty to remove the document.",
"legal.imprint": "Legal notice", "legal.imprint": "Legal notice",
"legal.markdown": "Or text (Markdown)", "legal.markdown": "Or text (Markdown)",
"legal.new_version": "Everyone has to accept it again",
"legal.new_version_hint": "For material changes: every account is asked to accept the new version at its next request and can use nothing else until then. Leave it off for corrections.",
"legal.org_intro": "Shown on your organization's status pages. Without your own documents, the platform's are shown.", "legal.org_intro": "Shown on your organization's status pages. Without your own documents, the platform's are shown.",
"legal.org_title": "Legal notice & privacy", "legal.org_title": "Legal notice & privacy",
"legal.platform_intro": "Linked in the footer of the console and sign-in pages, and on status pages of organizations without their own documents.", "legal.platform_intro": "Linked in the footer of the console and sign-in pages; legal notice and privacy policy also on status pages of organizations without their own. Every account accepts the privacy policy and terms when signing up, and again when you ask for it.",
"legal.platform_title": "Platform legal notice & privacy", "legal.platform_title": "Platform legal notice, privacy & terms",
"legal.privacy": "Privacy policy", "legal.privacy": "Privacy policy",
"legal.terms": "Terms of service",
"legal.url": "Link to an existing page", "legal.url": "Link to an existing page",
"limits.default": "default: {{.Value}}", "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.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.",
@@ -846,19 +961,25 @@
"md.ul": "Bulleted list", "md.ul": "Bulleted list",
"md.write": "Write", "md.write": "Write",
"members.assign": "Add role", "members.assign": "Add role",
"members.intro": "Roles decide what each member may do. Nobody can grant permissions they do not hold themselves.", "members.intro": "Roles decide what each member may do. Nobody can grant permissions they do not hold themselves. Owners may do everything; an organization can have several and always keeps at least one.",
"members.invite": "Invite", "members.invite": "Invite",
"members.invite_link": "Send this link to the invitee. It is valid for 7 days and works once.", "members.invite_link": "Send this link to the invitee. It is valid for 7 days and works once.",
"members.invite_submit": "Create invitation", "members.invite_submit": "Create invitation",
"members.make_owner": "Make owner",
"members.make_owner_confirm": "Make {{.Email}} an owner? Owners can do everything, including deleting the organization and deciding who else is owner.",
"members.owner": "Owner", "members.owner": "Owner",
"members.pending": "Pending invitations", "members.pending": "Pending invitations",
"members.remove": "Remove from organization", "members.remove": "Remove from organization",
"members.remove_confirm": "Remove this member? Their sessions and API tokens end immediately.", "members.remove_confirm": "Remove this member? Their sessions and API tokens end immediately.",
"members.remove_owner": "Remove as owner",
"members.remove_owner_confirm": "Take ownership away from {{.Email}}? Without other roles they keep working as Admin.",
"members.revoke": "Revoke", "members.revoke": "Revoke",
"members.role": "Role", "members.role": "Role",
"members.roles": "Roles", "members.roles": "Roles",
"members.scope": "Limited to", "members.scope": "Limited to",
"members.scope_org": "whole organization", "members.scope_org": "whole organization",
"members.step_down": "Step down as owner",
"members.step_down_confirm": "Step down as owner? You keep working with the Admin role unless you have other roles.",
"members.title": "Members", "members.title": "Members",
"members.unassign": "Remove role", "members.unassign": "Remove role",
"moderation.actions": "Suspend or delete …", "moderation.actions": "Suspend or delete …",
@@ -1184,6 +1305,10 @@
"scope.status_page": "status page", "scope.status_page": "status page",
"security.activity": "Account activity", "security.activity": "Account activity",
"security.activity_intro": "Recent sign-ins and security changes on your account. Contact an administrator if you do not recognize an entry.", "security.activity_intro": "Recent sign-ins and security changes on your account. Contact an administrator if you do not recognize an entry.",
"security.platform_sso.heading": "Sign in with other accounts",
"security.platform_sso.link": "Connect {{.Name}}",
"security.platform_sso.unlink": "Disconnect",
"security.platform_sso.unlink_confirm": "Stop signing in with {{.Name}}?",
"security.recovery.left": { "security.recovery.left": {
"one": "{{.Count}} recovery code left", "one": "{{.Count}} recovery code left",
"other": "{{.Count}} recovery codes left" "other": "{{.Count}} recovery codes left"
@@ -1210,6 +1335,7 @@
"settings.audit": "Who changed what and when.", "settings.audit": "Who changed what and when.",
"settings.channels": "Webhooks and email for incidents", "settings.channels": "Webhooks and email for incidents",
"settings.groups": "Organize monitors in nested groups", "settings.groups": "Organize monitors in nested groups",
"settings.incident_statuses": "Your own statuses with a color for incident updates.",
"settings.legal": "Legal notice and privacy policy for your status pages.", "settings.legal": "Legal notice and privacy policy for your status pages.",
"settings.members": "Invite people and assign roles", "settings.members": "Invite people and assign roles",
"settings.org": "Sign-in policies and token lifetime", "settings.org": "Sign-in policies and token lifetime",
@@ -1270,6 +1396,79 @@
"storage.retention": "Delete after", "storage.retention": "Delete after",
"storage.size": "Size", "storage.size": "Size",
"storage.title": "Data storage", "storage.title": "Data storage",
"support.account": "Account",
"support.account.active": "active",
"support.account.created": "Created",
"support.account.email": "Email",
"support.account.email_verified": "Email verified",
"support.account.locale": "Language",
"support.account.monitors": "Monitors",
"support.account.name": "Name",
"support.account.open_tickets": "Open tickets",
"support.account.org_suspended": "Organization suspended",
"support.account.orgs": "Organizations",
"support.account.orgs_owned": "Organizations owned",
"support.account.owner": "Owner",
"support.account.password": "Password",
"support.account.regions": "Regions per monitor",
"support.account.role": "Role",
"support.account.sign_in": "Sign-in",
"support.account.sso_only": "SSO only",
"support.account.state": "State",
"support.account.status_pages": "Status pages",
"support.account.suspended": "suspended",
"support.account.this_ticket": "named in the ticket",
"support.admin_intro": "Tickets of every account. Answering mails the account; its reply puts the ticket back among the open ones.",
"support.admin_title": "Support tickets",
"support.all": "All tickets",
"support.attach": "Attach details (optional)",
"support.attach_hint": "Point the support team at what your question is about, from the active organization.",
"support.attach_none": "none",
"support.attach_org": "Organization {{.Org}}",
"support.close": "Close ticket",
"support.closed_hint": "This ticket is closed. Replying opens it again.",
"support.contact": "Contact support",
"support.disabled": "Support tickets are switched off at the moment.",
"support.filter": "Filter tickets",
"support.filter.all": "All",
"support.filter.answered": "Answered",
"support.filter.closed": "Closed",
"support.filter.open": "Open",
"support.from_staff": "Support",
"support.from_you": "You",
"support.intro": "Questions, problems or feedback? Write to the platform's support team. You get an email as soon as they answer.",
"support.message": "Message",
"support.mine": "Your tickets",
"support.new": "New ticket",
"support.no": "no",
"support.none": "You have not opened any tickets yet.",
"support.none_admin": "No tickets here.",
"support.ref.alert_group": "Alert group",
"support.ref.channel": "Alert type (notification channel)",
"support.ref.incident": "Incident",
"support.ref.monitor": "Monitor",
"support.ref.org": "Organization",
"support.ref.status_page": "Status page",
"support.reopen": "Reopen ticket",
"support.reply": "Reply",
"support.send": "Send",
"support.settings": "Settings",
"support.settings.enabled": "Accounts can open support tickets",
"support.settings.enabled_hint": "Switched off, the support pages disappear for accounts; you keep the existing tickets here.",
"support.settings.max_open": "Open tickets per account",
"support.settings.max_open_hint": "Open and answered tickets count; 0 means unlimited. Suspended accounts can open one ticket.",
"support.settings.off": "off",
"support.settings.on": "on",
"support.settings.save": "Save",
"support.status.answered": "answered",
"support.status.closed": "closed",
"support.status.open": "open",
"support.subject": "Subject",
"support.title": "Support",
"support.yes": "yes",
"suspended.intro": "The platform's administrators have suspended your account.",
"suspended.options": "You can still download your data or delete your account.",
"suspended.title": "Account suspended",
"tokens.copy_now": "Copy the token now. It will not be shown again.", "tokens.copy_now": "Copy the token now. It will not be shown again.",
"tokens.create": "Create token", "tokens.create": "Create token",
"tokens.created": "Created", "tokens.created": "Created",
+291
View File
@@ -0,0 +1,291 @@
// Package launcher keeps a self-updating agent on the platform's release.
// It runs the agent as a child process, asks the API which release to run,
// downloads and verifies it, swaps the running agent gracefully and falls
// back to the previous release when the new one does not become ready.
package launcher
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
// Process is a running agent.
type Process interface {
// Stop asks the agent to shut down and kills it after timeout.
Stop(timeout time.Duration)
// Done is closed when the agent has exited.
Done() <-chan struct{}
// Err is the agent's exit error, once Done is closed.
Err() error
}
// Config wires the launcher to its surroundings.
type Config struct {
// Agent is the binary name: checker or statuspage.
Agent string
// Bundled is the binary shipped in the image.
Bundled string
// Dir keeps downloaded releases and the current choice.
Dir string
// Interval is the time between update checks, ±10%.
Interval time.Duration
// ReadyWait is how long a release has to become ready.
ReadyWait time.Duration
// StopTimeout is how long an agent may take to shut down.
StopTimeout time.Duration
// RetryAfter is how long a release that failed is not tried again.
RetryAfter time.Duration
Log *slog.Logger
// Updates asks the API which release to run.
Updates func(context.Context) (agentapi.Update, error)
// Fetch downloads and verifies the agent binary of a release.
Fetch func(context.Context, agentapi.Update) ([]byte, error)
// Start runs an agent binary.
Start func(path string) (Process, error)
// Ready reports whether the running agent is ready.
Ready func(context.Context) error
// Version reads the release a binary was built as.
Version func(path string) (string, error)
}
// release is an agent binary and its version.
type release struct {
version, path string
}
// Launcher runs one agent.
type Launcher struct {
cfg Config
bundled release
failed map[string]time.Time
}
// New returns a launcher for cfg.
func New(cfg Config) *Launcher {
return &Launcher{cfg: cfg, failed: map[string]time.Time{}}
}
var safeVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
func (l *Launcher) releasePath(version string) string {
return filepath.Join(l.cfg.Dir, "releases", version, l.cfg.Agent)
}
func (l *Launcher) currentFile() string { return filepath.Join(l.cfg.Dir, "current") }
// initial picks the release to start with: the one chosen last time if it
// is still there, otherwise the bundled one.
func (l *Launcher) initial() release {
raw, err := os.ReadFile(l.currentFile())
v := strings.TrimSpace(string(raw))
if err != nil || !safeVersion.MatchString(v) || v == l.bundled.version {
return l.bundled
}
p := l.releasePath(v)
if got, err := l.cfg.Version(p); err != nil || got != v {
return l.bundled
}
return release{v, p}
}
// Run starts the agent and keeps it updated until ctx ends, then stops it.
// It returns when the agent exits on its own.
func (l *Launcher) Run(ctx context.Context) error {
v, err := l.cfg.Version(l.cfg.Bundled)
if err != nil {
return fmt.Errorf("launcher: bundled %s: %w", l.cfg.Agent, err)
}
l.bundled = release{v, l.cfg.Bundled}
cur := l.initial()
proc, err := l.cfg.Start(cur.path)
if err != nil {
return err
}
started := time.Now()
l.cfg.Log.Info("agent started", "release", cur.version, "bundled", cur == l.bundled)
// The first check comes soon, so new installations catch up quickly.
timer := time.NewTimer(min(l.cfg.Interval, 30*time.Second))
defer timer.Stop()
for {
select {
case <-ctx.Done():
proc.Stop(l.cfg.StopTimeout)
return nil
case <-proc.Done():
if cur == l.bundled || time.Since(started) > l.cfg.ReadyWait {
return fmt.Errorf("launcher: %s %s exited: %w", l.cfg.Agent, cur.version, proc.Err())
}
// A downloaded release that crashes right after starting is
// not run again for a while.
l.cfg.Log.Error("agent crashed right after starting; falling back to the bundled release",
"release", cur.version, "error", proc.Err())
l.failed[cur.version] = time.Now()
_ = os.Remove(l.currentFile())
cur = l.bundled
if proc, err = l.cfg.Start(cur.path); err != nil {
return err
}
started = time.Now()
case <-timer.C:
next, np := l.check(ctx, cur, proc)
if np != proc {
started = time.Now()
}
cur, proc = next, np
if proc == nil {
return errors.New("launcher: no agent could be started")
}
timer.Reset(time.Duration(float64(l.cfg.Interval) * (0.9 + 0.2*rand.Float64())))
}
}
}
// check updates the agent if the platform names another release. It
// returns the release and process running afterwards.
func (l *Launcher) check(ctx context.Context, cur release, proc Process) (release, Process) {
u, err := l.cfg.Updates(ctx)
switch {
case err != nil:
l.cfg.Log.Warn("asking for updates failed", "error", err)
return cur, proc
case u.Image == "" || u.Version == cur.version:
return cur, proc
case !safeVersion.MatchString(u.Version):
l.cfg.Log.Warn("ignoring an invalid release name", "release", u.Version)
return cur, proc
case time.Since(l.failed[u.Version]) < l.cfg.RetryAfter:
return cur, proc
}
log := l.cfg.Log.With("from", cur.version, "to", u.Version)
next, err := l.obtain(ctx, u)
if err != nil {
log.Error("downloading the release failed", "image", u.Image, "error", err)
return cur, proc
}
log.Info("switching release")
proc.Stop(l.cfg.StopTimeout)
np, err := l.cfg.Start(next.path)
if err == nil && l.ready(ctx, np) {
if err := l.remember(next, cur); err != nil {
log.Warn("saving the release choice failed", "error", err)
}
log.Info("release switched")
return next, np
}
if np != nil {
np.Stop(l.cfg.StopTimeout)
}
log.Error("the release did not become ready; rolling back", "error", err, "retry_in", l.cfg.RetryAfter)
l.failed[u.Version] = time.Now()
back, err := l.cfg.Start(cur.path)
if err != nil {
log.Error("restarting the previous release failed", "error", err)
return cur, nil
}
return cur, back
}
// obtain returns the binary of u's release: the bundled one, one
// downloaded before, or a fresh download.
func (l *Launcher) obtain(ctx context.Context, u agentapi.Update) (release, error) {
if u.Version == l.bundled.version {
return l.bundled, nil
}
path := l.releasePath(u.Version)
if v, err := l.cfg.Version(path); err == nil && v == u.Version {
return release{u.Version, path}, nil
}
bin, err := l.cfg.Fetch(ctx, u)
if err != nil {
return release{}, err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return release{}, err
}
tmp := path + ".tmp"
if err := writeFileSync(tmp, bin, 0o700); err != nil {
return release{}, err
}
if v, err := l.cfg.Version(tmp); err != nil || v != u.Version {
_ = os.Remove(tmp)
if err != nil {
return release{}, fmt.Errorf("launcher: the downloaded binary does not run: %w", err)
}
return release{}, fmt.Errorf("launcher: the downloaded binary is %q, not %s", v, u.Version)
}
if err := os.Rename(tmp, path); err != nil {
return release{}, err
}
return release{u.Version, path}, nil
}
func writeFileSync(path string, data []byte, mode os.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
_ = f.Close()
return err
}
if err := f.Sync(); err != nil {
_ = f.Close()
return err
}
return f.Close()
}
// ready waits until the agent is ready, it exits or ReadyWait passes.
func (l *Launcher) ready(ctx context.Context, p Process) bool {
deadline := time.Now().Add(l.cfg.ReadyWait)
tick := time.NewTicker(min(time.Second, l.cfg.ReadyWait/10))
defer tick.Stop()
for time.Now().Before(deadline) {
select {
case <-ctx.Done():
return false
case <-p.Done():
return false
case <-tick.C:
if l.cfg.Ready(ctx) == nil {
return true
}
}
}
return false
}
// remember records next as the release to start with and deletes all other
// downloads except prev, the fallback.
func (l *Launcher) remember(next, prev release) error {
if next == l.bundled {
if err := os.Remove(l.currentFile()); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
} else if err := writeFileSync(l.currentFile(), []byte(next.version+"\n"), 0o600); err != nil {
return err
}
entries, err := os.ReadDir(filepath.Join(l.cfg.Dir, "releases"))
if err != nil {
return nil
}
for _, e := range entries {
if e.Name() != next.version && e.Name() != prev.version {
_ = os.RemoveAll(filepath.Join(l.cfg.Dir, "releases", e.Name()))
}
}
return nil
}
+307
View File
@@ -0,0 +1,307 @@
package launcher
import (
"context"
"errors"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
// The fake world: a binary is a file holding "version <v>"; a started
// release is ready unless listed in broken and exits at once if listed in
// crashing.
type fakeProc struct {
version string
done chan struct{}
once sync.Once
}
func (p *fakeProc) Stop(time.Duration) { p.once.Do(func() { close(p.done) }) }
func (p *fakeProc) Done() <-chan struct{} { return p.done }
func (p *fakeProc) Err() error { return errors.New("exit status 1") }
type world struct {
t *testing.T
dir string
mu sync.Mutex
// target is what the API names; fetchErr fails downloads.
target agentapi.Update
fetchErr error
fetched int
wrongBin bool
broken map[string]bool
crashing map[string]bool
running *fakeProc
started []string
}
func newWorld(t *testing.T) *world {
w := &world{t: t, dir: t.TempDir(), broken: map[string]bool{}, crashing: map[string]bool{}}
if err := os.WriteFile(filepath.Join(w.dir, "bundled"), []byte("version v1.0.0"), 0o755); err != nil {
t.Fatal(err)
}
return w
}
func (w *world) config() Config {
return Config{
Agent: "checker", Bundled: filepath.Join(w.dir, "bundled"), Dir: filepath.Join(w.dir, "state"),
Interval: 20 * time.Millisecond, ReadyWait: 100 * time.Millisecond, StopTimeout: time.Second, RetryAfter: time.Hour,
Log: slog.New(slog.DiscardHandler),
Updates: func(context.Context) (agentapi.Update, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.target.Version == "" {
return agentapi.Update{}, errors.New("api down")
}
return w.target, nil
},
Fetch: func(_ context.Context, u agentapi.Update) ([]byte, error) {
w.mu.Lock()
defer w.mu.Unlock()
w.fetched++
if w.fetchErr != nil {
return nil, w.fetchErr
}
if w.wrongBin {
return []byte("version v6.6.6"), nil
}
return []byte("version " + u.Version), nil
},
Start: func(path string) (Process, error) {
v, err := fakeVersion(path)
if err != nil {
return nil, err
}
w.mu.Lock()
defer w.mu.Unlock()
p := &fakeProc{version: v, done: make(chan struct{})}
if w.crashing[v] {
close(p.done)
}
w.running = p
w.started = append(w.started, v)
return p, nil
},
Ready: func(context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.running == nil || w.broken[w.running.version] {
return errors.New("not ready")
}
return nil
},
Version: fakeVersion,
}
}
func fakeVersion(path string) (string, error) {
raw, err := os.ReadFile(path)
if err != nil {
return "", err
}
v, ok := strings.CutPrefix(string(raw), "version ")
if !ok {
return "", errors.New("not a binary")
}
return v, nil
}
func (w *world) set(fn func(w *world)) {
w.mu.Lock()
defer w.mu.Unlock()
fn(w)
}
func (w *world) runningVersion() string {
w.mu.Lock()
defer w.mu.Unlock()
if w.running == nil {
return ""
}
return w.running.version
}
// current is the release the launcher starts with next time.
func (w *world) current() string {
raw, _ := os.ReadFile(filepath.Join(w.dir, "state", "current"))
return strings.TrimSpace(string(raw))
}
// eventually waits for cond.
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(5 * time.Millisecond)
}
}
func run(t *testing.T, w *world) (cancel func() error) {
t.Helper()
ctx, stop := context.WithCancel(context.Background())
errc := make(chan error, 1)
go func() { errc <- New(w.config()).Run(ctx) }()
return func() error {
stop()
return <-errc
}
}
func TestUpdateAndRestart(t *testing.T) {
w := newWorld(t)
stop := run(t, w)
eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "reg/uptimesebi-checker:1.1.0"} })
eventually(t, "update to v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// A restart starts the release chosen last time, without downloading.
before := w.fetched
stop = run(t, w)
eventually(t, "restart with v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" })
time.Sleep(60 * time.Millisecond)
if w.fetched != before {
t.Error("the release was downloaded again")
}
// Another update keeps the previous release as fallback and deletes
// older ones; going back to the bundled release needs no download.
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.2.0", Image: "x"} })
eventually(t, "update to v1.2.0", func() bool { return w.runningVersion() == "v1.2.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.0.0", Image: "x"} })
gone := func(p ...string) bool {
_, err := os.Stat(filepath.Join(append([]string{w.dir, "state"}, p...)...))
return os.IsNotExist(err)
}
eventually(t, "back to bundled, old releases deleted", func() bool {
return w.runningVersion() == "v1.0.0" && gone("current") && gone("releases", "v1.1.0")
})
if gone("releases", "v1.2.0") {
t.Error("the fallback release was deleted")
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestRollback(t *testing.T) {
w := newWorld(t)
w.broken["v2.0.0"] = true
stop := run(t, w)
eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v2.0.0", Image: "x"} })
eventually(t, "rollback", func() bool {
w.mu.Lock()
defer w.mu.Unlock()
n := len(w.started)
return n >= 3 && w.started[n-2] == "v2.0.0" && w.started[n-1] == "v1.0.0"
})
// The failed release is not tried again right away.
time.Sleep(100 * time.Millisecond)
w.mu.Lock()
tries := strings.Count(strings.Join(w.started, " "), "v2.0.0")
w.mu.Unlock()
if tries != 1 || w.runningVersion() != "v1.0.0" {
t.Errorf("started %v", w.started)
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestCrashAfterRestart(t *testing.T) {
w := newWorld(t)
stop := run(t, w)
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} })
eventually(t, "update", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// After a restart the remembered release crashes at once: the bundled
// release takes over.
w.set(func(w *world) { w.crashing["v1.1.0"] = true; w.target = agentapi.Update{} })
stop = run(t, w)
eventually(t, "fallback", func() bool { return w.runningVersion() == "v1.0.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// The bundled release crashing ends the launcher, so the container
// restarts.
w.set(func(w *world) { w.crashing["v1.0.0"] = true })
if err := New(w.config()).Run(context.Background()); err == nil {
t.Error("a crashing bundled agent did not end the launcher")
}
}
func TestBadDownloads(t *testing.T) {
w := newWorld(t)
w.fetchErr = errors.New("signature does not match")
stop := run(t, w)
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} })
eventually(t, "retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 2 })
if w.runningVersion() != "v1.0.0" {
t.Error("switched without a verified download")
}
// A binary that is not the release asked for is never run.
w.set(func(w *world) { w.fetchErr = nil; w.wrongBin = true })
eventually(t, "more retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 4 })
w.mu.Lock()
for _, v := range w.started {
if v != "v1.0.0" {
t.Errorf("started %s", v)
}
}
w.mu.Unlock()
// Unreleased platforms and nonsense release names are ignored.
w.set(func(w *world) { w.wrongBin = false; w.target = agentapi.Update{Version: "dev"} })
time.Sleep(60 * time.Millisecond)
w.set(func(w *world) { w.target = agentapi.Update{Version: "../../etc", Image: "x"} })
time.Sleep(60 * time.Millisecond)
if w.runningVersion() != "v1.0.0" {
t.Error("followed an unreleased or invalid release")
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestBinaryVersion(t *testing.T) {
dir := t.TempDir()
script := func(name, body string) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}
if v, err := BinaryVersion(script("good", `[ "$1" = version ] && echo v1.2.3`)); err != nil || v != "v1.2.3" {
t.Errorf("BinaryVersion = %q, %v", v, err)
}
for name, body := range map[string]string{"silent": "true", "failing": "exit 3", "chatty": "echo hello world"} {
if v, err := BinaryVersion(script(name, body)); err == nil {
t.Errorf("%s: BinaryVersion = %q", name, v)
}
}
if _, err := BinaryVersion(filepath.Join(dir, "missing")); err == nil {
t.Error("read a missing file")
}
if p := Platform(); p.OS == "" || p.Architecture == "" {
t.Errorf("Platform = %v", p)
}
}
+86
View File
@@ -0,0 +1,86 @@
package launcher
import (
"context"
"fmt"
"os"
"os/exec"
"runtime"
"runtime/debug"
"strings"
"syscall"
"time"
v1 "github.com/google/go-containerregistry/pkg/v1"
)
type process struct {
cmd *exec.Cmd
done chan struct{}
err error
}
// StartProcess runs path with the launcher's environment and output.
func StartProcess(path string) (Process, error) {
cmd := exec.Command(path)
cmd.Stdout, cmd.Stderr, cmd.Env = os.Stdout, os.Stderr, os.Environ()
if err := cmd.Start(); err != nil {
return nil, err
}
p := &process{cmd: cmd, done: make(chan struct{})}
go func() {
p.err = cmd.Wait()
close(p.done)
}()
return p, nil
}
// Done is closed when the agent has exited.
func (p *process) Done() <-chan struct{} { return p.done }
// Err is the agent's exit error.
func (p *process) Err() error { return p.err }
// Stop sends SIGTERM and kills the agent after timeout.
func (p *process) Stop(timeout time.Duration) {
_ = p.cmd.Process.Signal(syscall.SIGTERM)
select {
case <-p.done:
case <-time.After(timeout):
_ = p.cmd.Process.Kill()
<-p.done
}
}
// BinaryVersion asks an agent binary which release it is.
func BinaryVersion(path string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, path, "version").Output()
if err != nil {
return "", err
}
v := strings.TrimSpace(string(out))
if v == "" || strings.ContainsAny(v, " \n") {
return "", fmt.Errorf("launcher: %s reports no release", path)
}
return v, nil
}
// Platform is the platform this launcher was built for, and so the agent
// binaries it runs.
func Platform() v1.Platform {
p := v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH}
if runtime.GOARCH != "arm" {
return p
}
p.Variant = "v7" // Go's default for linux/arm
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "GOARM" && s.Value != "" {
p.Variant = "v" + s.Value[:1]
}
}
}
return p
}
+9
View File
@@ -34,6 +34,15 @@ func TestAlertGroupsBackfill(t *testing.T) {
if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil { if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Support tickets point at alert groups; take them back first.
later, err := files.ReadFile("sql/00051_support_tickets.sql")
if err != nil {
t.Fatal(err)
}
_, laterDown, _ := strings.Cut(string(later), "-- +goose Down")
if _, err := tx.Exec(ctx, laterDown); err != nil {
t.Fatalf("down 00051: %v", err)
}
raw, err := files.ReadFile("sql/00039_alert_groups.sql") raw, err := files.ReadFile("sql/00039_alert_groups.sql")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -0,0 +1,49 @@
-- +goose Up
-- Identity providers of the whole installation, such as Google or GitHub,
-- for signing up and signing in; organizations' own IdPs stay in
-- sso_providers.
CREATE TABLE platform_identity_providers (
id uuid PRIMARY KEY,
kind text NOT NULL CHECK (kind IN ('oidc', 'github')),
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
-- The OIDC issuer, or the GitHub server (https://github.com or a GitHub
-- Enterprise host).
issuer text NOT NULL CHECK (issuer ~ '^https?://[^\s]+$' AND length(issuer) <= 500),
client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 500),
-- Sealed with the application keyring, bound to the provider id.
client_secret bytea,
-- Whether people without an account may sign up through it.
allow_signup boolean NOT NULL DEFAULT true,
enabled boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Accounts are linked by subject, never by email.
CREATE TABLE platform_identities (
provider_id uuid NOT NULL REFERENCES platform_identity_providers (id) ON DELETE CASCADE,
subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
email citext,
created_at timestamptz NOT NULL DEFAULT now(),
last_login_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (provider_id, subject)
);
CREATE INDEX platform_identities_user_idx ON platform_identities (user_id);
ALTER TABLE platform_identity_providers ENABLE ROW LEVEL SECURITY;
ALTER TABLE platform_identity_providers FORCE ROW LEVEL SECURITY;
-- Sign-in pages list them to everyone; only the system scope changes them.
CREATE POLICY platform_identity_providers_read ON platform_identity_providers FOR SELECT USING (true);
CREATE POLICY platform_identity_providers_write ON platform_identity_providers FOR ALL
USING (app_scope_system()) WITH CHECK (app_scope_system());
ALTER TABLE platform_identities ENABLE ROW LEVEL SECURITY;
ALTER TABLE platform_identities FORCE ROW LEVEL SECURITY;
CREATE POLICY platform_identities_own ON platform_identities FOR ALL
USING (app_scope_system() OR user_id = app_user_id())
WITH CHECK (app_scope_system() OR user_id = app_user_id());
-- +goose Down
DROP TABLE platform_identities;
DROP TABLE platform_identity_providers;
@@ -0,0 +1,40 @@
-- +goose Up
-- Terms of service join the legal documents, for the platform only: status
-- page visitors accept nothing.
ALTER TABLE legal_documents DROP CONSTRAINT legal_documents_kind_check;
ALTER TABLE legal_documents ADD CONSTRAINT legal_documents_kind_check
CHECK (kind IN ('imprint', 'privacy', 'terms'));
ALTER TABLE legal_documents ADD CONSTRAINT legal_documents_terms_platform
CHECK (kind <> 'terms' OR org_id IS NULL);
-- version identifies the text users accept. It changes when a document is
-- created or when an edit asks everyone to accept again, and comes from a
-- sequence so a document removed and written anew never repeats one.
CREATE SEQUENCE legal_document_versions;
ALTER TABLE legal_documents ADD COLUMN version bigint NOT NULL DEFAULT nextval('legal_document_versions');
-- Which version of the platform's privacy policy and terms each account
-- accepted, and when: the proof of consent.
CREATE TABLE legal_acceptances (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
kind text NOT NULL CHECK (kind IN ('privacy', 'terms')),
version bigint NOT NULL,
accepted_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, kind, version)
);
ALTER TABLE legal_acceptances ENABLE ROW LEVEL SECURITY;
ALTER TABLE legal_acceptances FORCE ROW LEVEL SECURITY;
CREATE POLICY legal_acceptances_own ON legal_acceptances FOR ALL
USING (app_scope_system() OR user_id = app_user_id())
WITH CHECK (app_scope_system() OR user_id = app_user_id());
-- +goose Down
DROP TABLE legal_acceptances;
ALTER TABLE legal_documents DROP COLUMN version;
DROP SEQUENCE legal_document_versions;
DELETE FROM legal_documents WHERE kind = 'terms';
ALTER TABLE legal_documents DROP CONSTRAINT legal_documents_terms_platform;
ALTER TABLE legal_documents DROP CONSTRAINT legal_documents_kind_check;
ALTER TABLE legal_documents ADD CONSTRAINT legal_documents_kind_check
CHECK (kind IN ('imprint', 'privacy'));
@@ -0,0 +1,12 @@
-- +goose Up
-- An organization may have several owners; the API keeps at least one.
DROP INDEX memberships_one_owner_idx;
-- +goose Down
-- Keeps the longest-standing owner of each organization.
UPDATE memberships m SET is_owner = false
WHERE m.is_owner AND EXISTS (
SELECT 1 FROM memberships o
WHERE o.org_id = m.org_id AND o.is_owner AND (o.created_at, o.user_id) < (m.created_at, m.user_id)
);
CREATE UNIQUE INDEX memberships_one_owner_idx ON memberships (org_id) WHERE is_owner;
@@ -0,0 +1,31 @@
-- +goose Up
-- Incidents open and close with their monitor; people tell what is going
-- on through a title, a status and updates, public on status pages or
-- internal.
ALTER TABLE incidents ADD COLUMN title text NOT NULL DEFAULT '' CHECK (length(title) <= 200);
-- The status of the latest update, NULL before the first.
ALTER TABLE incidents ADD COLUMN status text
CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved'));
CREATE TABLE incident_updates (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE,
status text NOT NULL CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved')),
message text NOT NULL CHECK (length(message) BETWEEN 1 AND 5000),
public boolean NOT NULL DEFAULT true,
author_id uuid REFERENCES users (id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX incident_updates_incident_idx ON incident_updates (incident_id, created_at);
ALTER TABLE incident_updates ENABLE ROW LEVEL SECURITY;
ALTER TABLE incident_updates FORCE ROW LEVEL SECURITY;
CREATE POLICY incident_updates_tenant ON incident_updates 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 incident_updates;
ALTER TABLE incidents DROP COLUMN status;
ALTER TABLE incidents DROP COLUMN title;
@@ -0,0 +1,48 @@
-- +goose Up
-- Organizations add statuses of their own, with a color, next to the
-- built-in ones. A status in use cannot be deleted: the history would lose
-- its meaning.
CREATE TABLE incident_statuses (
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 40),
color text NOT NULL CHECK (color ~ '^#[0-9a-f]{6}$'),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (org_id, name)
);
ALTER TABLE incident_statuses ENABLE ROW LEVEL SECURITY;
ALTER TABLE incident_statuses FORCE ROW LEVEL SECURITY;
CREATE POLICY incident_statuses_tenant ON incident_statuses FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- status is a built-in status or 'custom' with status_id naming it.
ALTER TABLE incident_updates DROP CONSTRAINT incident_updates_status_check;
ALTER TABLE incident_updates ADD CONSTRAINT incident_updates_status_check
CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved', 'custom'));
ALTER TABLE incident_updates ADD COLUMN status_id uuid REFERENCES incident_statuses (id) ON DELETE RESTRICT;
ALTER TABLE incident_updates ADD CONSTRAINT incident_updates_custom_status
CHECK ((status = 'custom') = (status_id IS NOT NULL));
ALTER TABLE incidents DROP CONSTRAINT incidents_status_check;
ALTER TABLE incidents ADD CONSTRAINT incidents_status_check
CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved', 'custom'));
ALTER TABLE incidents ADD COLUMN status_id uuid REFERENCES incident_statuses (id) ON DELETE RESTRICT;
ALTER TABLE incidents ADD CONSTRAINT incidents_custom_status
CHECK ((status = 'custom') = (status_id IS NOT NULL));
-- +goose Down
DELETE FROM incident_updates WHERE status = 'custom';
UPDATE incidents SET status = NULL WHERE status = 'custom';
ALTER TABLE incidents DROP CONSTRAINT incidents_custom_status;
ALTER TABLE incidents DROP COLUMN status_id;
ALTER TABLE incidents DROP CONSTRAINT incidents_status_check;
ALTER TABLE incidents ADD CONSTRAINT incidents_status_check
CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved'));
ALTER TABLE incident_updates DROP CONSTRAINT incident_updates_custom_status;
ALTER TABLE incident_updates DROP COLUMN status_id;
ALTER TABLE incident_updates DROP CONSTRAINT incident_updates_status_check;
ALTER TABLE incident_updates ADD CONSTRAINT incident_updates_status_check
CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved'));
DROP TABLE incident_statuses;
@@ -0,0 +1,9 @@
-- +goose Up
-- An update may just change the status, without a message.
ALTER TABLE incident_updates DROP CONSTRAINT incident_updates_message_check;
ALTER TABLE incident_updates ADD CONSTRAINT incident_updates_message_check CHECK (length(message) <= 5000);
-- +goose Down
UPDATE incident_updates SET message = '–' WHERE message = '';
ALTER TABLE incident_updates DROP CONSTRAINT incident_updates_message_check;
ALTER TABLE incident_updates ADD CONSTRAINT incident_updates_message_check CHECK (length(message) BETWEEN 1 AND 5000);
@@ -0,0 +1,51 @@
-- +goose Up
-- Accounts ask the platform's admins for help. A ticket belongs to the
-- account that opened it, even a suspended one; deleting the account
-- deletes its tickets. It may point at an organization and things in it
-- the question is about; deleting those leaves the ticket.
CREATE TABLE support_tickets (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
org_id uuid REFERENCES orgs (id) ON DELETE SET NULL,
monitor_id uuid REFERENCES monitors (id) ON DELETE SET NULL,
channel_id uuid REFERENCES notification_channels (id) ON DELETE SET NULL,
alert_group_id uuid REFERENCES alert_groups (id) ON DELETE SET NULL,
status_page_id uuid REFERENCES status_pages (id) ON DELETE SET NULL,
incident_id uuid REFERENCES incidents (id) ON DELETE SET NULL,
subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 200),
-- open waits for the admins, answered for the account.
status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'answered', 'closed')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX support_tickets_user_idx ON support_tickets (user_id, updated_at DESC);
CREATE INDEX support_tickets_status_idx ON support_tickets (status, updated_at DESC);
CREATE TABLE support_messages (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
ticket_id uuid NOT NULL REFERENCES support_tickets (id) ON DELETE CASCADE,
-- author_id is empty once the admin who wrote it is deleted.
author_id uuid REFERENCES users (id) ON DELETE SET NULL,
from_staff boolean NOT NULL,
body text NOT NULL CHECK (length(body) BETWEEN 1 AND 10000),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX support_messages_ticket_idx ON support_messages (ticket_id, created_at);
ALTER TABLE support_tickets ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_tickets FORCE ROW LEVEL SECURITY;
CREATE POLICY support_tickets_own ON support_tickets FOR ALL
USING (app_scope_system() OR user_id = app_user_id())
WITH CHECK (app_scope_system() OR user_id = app_user_id());
ALTER TABLE support_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_messages FORCE ROW LEVEL SECURITY;
CREATE POLICY support_messages_own ON support_messages FOR ALL
USING (app_scope_system() OR EXISTS (
SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id()))
WITH CHECK (app_scope_system() OR (NOT from_staff AND EXISTS (
SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id())));
-- +goose Down
DROP TABLE support_messages;
DROP TABLE support_tickets;
+1 -1
View File
@@ -114,7 +114,7 @@ var emailProviders = []Provider{
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
} }
if json.Unmarshal(reply, &tok) != nil || tok.AccessToken == "" { if json.Unmarshal(reply, &tok) != nil || tok.AccessToken == "" {
return errors.New("Microsoft Entra issued no access token") return errors.New("no access token from Microsoft Entra")
} }
recipients := func(s string) []any { recipients := func(s string) []any {
return addresses(s, func(a string) any { return map[string]any{"emailAddress": map[string]string{"address": a}} }) return addresses(s, func(a string) any { return map[string]any{"emailAddress": map[string]string{"address": a}} })
+1 -1
View File
@@ -124,7 +124,7 @@ var incidentProviders = []Provider{
ID string `json:"id"` ID string `json:"id"`
} }
if json.Unmarshal(reply, &alert) != nil || alert.ID == "" { if json.Unmarshal(reply, &alert) != nil || alert.ID == "" {
return errors.New("Jira Service Management: alert to close not found") return errors.New("alert to close not found in Jira Service Management")
} }
return c.json(ctx, http.MethodPost, base+"/"+url.PathEscape(alert.ID)+"/close", h, map[string]any{"source": "UptimeSebi"}) return c.json(ctx, http.MethodPost, base+"/"+url.PathEscape(alert.ID)+"/close", h, map[string]any{"source": "UptimeSebi"})
} }
+1 -1
View File
@@ -356,7 +356,7 @@ var smsProviders = []Provider{
} `json:"data"` } `json:"data"`
} }
if err != nil || json.Unmarshal(reply, &login) != nil || !login.Success { if err != nil || json.Unmarshal(reply, &login) != nil || !login.Success {
return errors.Join(errors.New("Teltonika: sign-in failed"), err) return errors.Join(errors.New("sign-in to Teltonika failed"), err)
} }
reply, err = c.callJSON(ctx, http.MethodPost, base+"/api/messages/actions/send", bearer(login.Data.Token), map[string]any{ reply, err = c.callJSON(ctx, http.MethodPost, base+"/api/messages/actions/send", bearer(login.Data.Token), map[string]any{
"data": map[string]any{"modem": cfg["modem"], "number": cfg["phone_number"], "message": truncate(m.sms(), 159)}, "data": map[string]any{"modem": cfg["modem"], "number": cfg["phone_number"], "message": truncate(m.sms(), 159)},
+2 -3
View File
@@ -21,11 +21,10 @@ const (
margin = 50.0 margin = 50.0
bodySize = 9.0 bodySize = 9.0
lineHeight = 12.0 lineHeight = 12.0
// Courier advances 0.6 em per character, which makes wrapping exact.
charWidth = 0.6 * bodySize
) )
// maxChars is how many Courier characters fit on a line. // maxChars is how many Courier characters fit on a line: Courier advances
// 0.6 em per character, which makes wrapping exact.
const maxChars = 91 const maxChars = 91
type font string type font string
+36
View File
@@ -0,0 +1,36 @@
package platform
import (
"context"
"fmt"
"net"
"net/http"
"time"
)
// ProbeLocal asks a local health endpoint (path /healthz or /readyz) on
// listen, e.g. ":8081". Images without a shell run it as their HEALTHCHECK.
func ProbeLocal(ctx context.Context, listen, path string) error {
host, port, err := net.SplitHostPort(listen)
if err != nil {
return err
}
if host == "" || host == "0.0.0.0" || host == "::" {
host = "127.0.0.1"
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+path, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
_ = resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("platform: health endpoint answered %s", resp.Status)
}
return nil
}
+9
View File
@@ -0,0 +1,9 @@
package platform
import (
// Agent images are built FROM scratch and have no time zone database.
_ "time/tzdata"
// Nor CA roots; these are used only when the host offers none.
_ "golang.org/x/crypto/x509roots/fallback"
)
+4
View File
@@ -0,0 +1,4 @@
# Keys that sign UptimeSebi releases, one per line. Keep retired keys
# listed so agents can update across a rotation.
untrusted comment: uptimesebi release key 8359FCBB1309986B
RWRrmAkTu/xZg/o8QCsko5rUujqW/N165cj+dyEcp5CDXPTE2jKbLkyA
+193
View File
@@ -0,0 +1,193 @@
// Package signing signs and verifies release files in the minisign format,
// so that anyone can check a release with the minisign tool and the
// self-updating agents can check what they download.
//
// Only prehashed signatures (algorithm "ED": Ed25519 over the BLAKE2b-512
// hash of the file) are produced and accepted.
package signing
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
_ "embed"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/blake2b"
)
var (
// ErrSignature reports a signature that does not match.
ErrSignature = errors.New("signing: signature does not match")
// ErrUnknownKey reports a signature made with a key not trusted.
ErrUnknownKey = errors.New("signing: signed with an unknown key")
)
const (
keyAlg = "Ed"
prehashedAlg = "ED"
idLen = 8
)
// PublicKey is a minisign public key.
type PublicKey struct {
ID [idLen]byte
Key ed25519.PublicKey
}
// PrivateKey is a signing key with the ID of its public key.
type PrivateKey struct {
ID [idLen]byte
Key ed25519.PrivateKey
}
// Public returns the key that verifies k's signatures.
func (k PrivateKey) Public() PublicKey {
return PublicKey{ID: k.ID, Key: k.Key.Public().(ed25519.PublicKey)}
}
// String encodes the key like minisign does on the second line of a .pub
// file.
func (k PublicKey) String() string {
raw := append(append([]byte(keyAlg), k.ID[:]...), k.Key...)
return base64.StdEncoding.EncodeToString(raw)
}
// IDString is the key ID as minisign prints it.
func (k PublicKey) IDString() string {
var b strings.Builder
for i := idLen - 1; i >= 0; i-- {
fmt.Fprintf(&b, "%02X", k.ID[i])
}
return b.String()
}
// ParsePublicKey reads a key in minisign's encoding.
func ParsePublicKey(s string) (PublicKey, error) {
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
if err != nil || len(raw) != 2+idLen+ed25519.PublicKeySize || string(raw[:2]) != keyAlg {
return PublicKey{}, errors.New("signing: not a minisign public key")
}
var k PublicKey
copy(k.ID[:], raw[2:])
k.Key = ed25519.PublicKey(raw[2+idLen:])
return k, nil
}
// ParsePublicKeys reads one key per line, skipping blank lines, comments
// starting with # and minisign's "untrusted comment:" lines.
func ParsePublicKeys(text string) ([]PublicKey, error) {
var keys []PublicKey
for line := range strings.Lines(text) {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "untrusted comment:") {
continue
}
k, err := ParsePublicKey(line)
if err != nil {
return nil, err
}
keys = append(keys, k)
}
return keys, nil
}
// GenerateKey creates a new signing key.
func GenerateKey() (PrivateKey, error) {
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return PrivateKey{}, err
}
k := PrivateKey{Key: priv}
if _, err := rand.Read(k.ID[:]); err != nil {
return PrivateKey{}, err
}
return k, nil
}
// String encodes the key for storage in a secret: base64 of the key ID and
// the Ed25519 seed. It is not minisign's encrypted key format.
func (k PrivateKey) String() string {
return base64.StdEncoding.EncodeToString(append(k.ID[:], k.Key.Seed()...))
}
// ParsePrivateKey reads a key written by PrivateKey.String.
func ParsePrivateKey(s string) (PrivateKey, error) {
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
if err != nil || len(raw) != idLen+ed25519.SeedSize {
return PrivateKey{}, errors.New("signing: not a signing key")
}
var k PrivateKey
copy(k.ID[:], raw)
k.Key = ed25519.NewKeyFromSeed(raw[idLen:])
return k, nil
}
func digest(msg []byte) []byte {
sum := blake2b.Sum512(msg)
return sum[:]
}
// Sign returns a minisign signature file for msg. The trusted comment is
// signed too; it must be a single line.
func Sign(k PrivateKey, msg []byte, trusted string) ([]byte, error) {
if strings.ContainsAny(trusted, "\r\n") {
return nil, errors.New("signing: the trusted comment must be one line")
}
sig := ed25519.Sign(k.Key, digest(msg))
global := ed25519.Sign(k.Key, append(append([]byte{}, sig...), trusted...))
var b bytes.Buffer
fmt.Fprintf(&b, "untrusted comment: signature from uptimesebi release key %s\n", k.Public().IDString())
b.WriteString(base64.StdEncoding.EncodeToString(append(append([]byte(prehashedAlg), k.ID[:]...), sig...)) + "\n")
b.WriteString("trusted comment: " + trusted + "\n")
b.WriteString(base64.StdEncoding.EncodeToString(global) + "\n")
return b.Bytes(), nil
}
// Verify checks a minisign signature file for msg against the trusted
// keys and returns its trusted comment.
func Verify(keys []PublicKey, msg, sigFile []byte) (string, error) {
lines := strings.Split(strings.TrimRight(string(sigFile), "\n"), "\n")
if len(lines) != 4 || !strings.HasPrefix(lines[0], "untrusted comment:") || !strings.HasPrefix(lines[2], "trusted comment: ") {
return "", errors.New("signing: not a minisign signature")
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(lines[1]))
if err != nil || len(raw) != 2+idLen+ed25519.SignatureSize {
return "", errors.New("signing: not a minisign signature")
}
if string(raw[:2]) != prehashedAlg {
return "", errors.New("signing: only prehashed signatures are accepted")
}
global, err := base64.StdEncoding.DecodeString(strings.TrimSpace(lines[3]))
if err != nil || len(global) != ed25519.SignatureSize {
return "", errors.New("signing: not a minisign signature")
}
sig := raw[2+idLen:]
trusted := strings.TrimSuffix(strings.TrimPrefix(lines[2], "trusted comment: "), "\r")
for _, k := range keys {
if !bytes.Equal(k.ID[:], raw[2:2+idLen]) {
continue
}
if !ed25519.Verify(k.Key, digest(msg), sig) || !ed25519.Verify(k.Key, append(append([]byte{}, sig...), trusted...), global) {
return "", ErrSignature
}
return trusted, nil
}
return "", ErrUnknownKey
}
//go:embed release.pub
var releaseKeys string
// ReleaseKeys are the keys that sign UptimeSebi releases. Old keys stay
// listed after a rotation so that agents can update across it.
func ReleaseKeys() []PublicKey {
keys, err := ParsePublicKeys(releaseKeys)
if err != nil {
panic(err)
}
return keys
}
+66
View File
@@ -0,0 +1,66 @@
package signing
import (
"bytes"
"errors"
"strings"
"testing"
)
func TestSignVerify(t *testing.T) {
k, err := GenerateKey()
if err != nil {
t.Fatal(err)
}
pub := k.Public()
msg := []byte("abc uptimesebi_1.0.0_linux_amd64.tar.gz\n")
sig, err := Sign(k, msg, "v1.0.0")
if err != nil {
t.Fatal(err)
}
if got, err := Verify([]PublicKey{pub}, msg, sig); err != nil || got != "v1.0.0" {
t.Fatalf("Verify = %q, %v", got, err)
}
other, _ := GenerateKey()
if _, err := Verify([]PublicKey{other.Public()}, msg, sig); !errors.Is(err, ErrUnknownKey) {
t.Errorf("unknown key: %v", err)
}
if _, err := Verify([]PublicKey{other.Public(), pub}, msg, sig); err != nil {
t.Errorf("rotated key list: %v", err)
}
if _, err := Verify([]PublicKey{pub}, append(msg, 'x'), sig); !errors.Is(err, ErrSignature) {
t.Errorf("changed file: %v", err)
}
forged := bytes.Replace(sig, []byte("trusted comment: v1.0.0"), []byte("trusted comment: v9.0.0"), 1)
if _, err := Verify([]PublicKey{pub}, msg, forged); !errors.Is(err, ErrSignature) {
t.Errorf("changed trusted comment: %v", err)
}
if _, err := Sign(k, msg, "a\nb"); err == nil {
t.Error("multi-line trusted comment accepted")
}
}
func TestEncoding(t *testing.T) {
k, _ := GenerateKey()
back, err := ParsePrivateKey(k.String())
if err != nil || back.ID != k.ID || !back.Key.Equal(k.Key) {
t.Fatalf("private key round trip: %v", err)
}
keys, err := ParsePublicKeys("# comment\nuntrusted comment: minisign public key\n" + k.Public().String() + "\n\n")
if err != nil || len(keys) != 1 || keys[0].ID != k.ID || !keys[0].Key.Equal(k.Public().Key) {
t.Fatalf("public keys = %v, %v", keys, err)
}
if !strings.HasPrefix(k.Public().String(), "RW") {
t.Errorf("public key %s does not look like minisign's", k.Public())
}
if _, err := ParsePublicKey("RWQ" + strings.Repeat("A", 10)); err == nil {
t.Error("short key accepted")
}
}
func TestReleaseKeys(t *testing.T) {
if len(ReleaseKeys()) == 0 {
t.Error("no release key")
}
}
+93
View File
@@ -0,0 +1,93 @@
package sso
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"golang.org/x/oauth2"
)
// GitHub signs users in with OAuth instead of OpenID Connect. A Provider
// with Kind GitHub names the GitHub server as Issuer: https://github.com or
// a GitHub Enterprise host.
const GitHub = "github"
func (c *Client) githubOAuth(p Provider) *oauth2.Config {
web := strings.TrimSuffix(p.Issuer, "/")
return &oauth2.Config{
ClientID: p.ClientID,
ClientSecret: p.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: web + "/login/oauth/authorize", TokenURL: web + "/login/oauth/access_token",
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: c.redirectURL,
Scopes: []string{"read:user", "user:email"},
}
}
// githubAPI is the REST API of a GitHub server.
func githubAPI(issuer string) string {
web := strings.TrimSuffix(issuer, "/")
if web == "https://github.com" {
return "https://api.github.com"
}
return web + "/api/v3"
}
// githubClaims reads the user behind tok. Only the primary email counts,
// and only if GitHub verified it.
func (c *Client) githubClaims(ctx context.Context, p Provider, tok *oauth2.Token) (Claims, error) {
get := func(path string, v any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, githubAPI(p.Issuer)+path, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok.AccessToken)
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("sso: github %s answered %d", path, resp.StatusCode)
}
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(v)
}
var user struct {
ID int64 `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
}
if err := get("/user", &user); err != nil {
return Claims{}, err
}
if user.ID == 0 {
return Claims{}, errors.New("sso: github user without id")
}
var emails []struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
}
if err := get("/user/emails", &emails); err != nil {
return Claims{}, err
}
cl := Claims{Subject: strconv.FormatInt(user.ID, 10), Name: user.Name}
if cl.Name == "" {
cl.Name = user.Login
}
for _, e := range emails {
if e.Primary {
cl.Email, cl.EmailVerified = e.Email, e.Verified
}
}
return cl, nil
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more