Compare commits

...
Author SHA1 Message Date
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 13m8s
ci / lint (push) Successful in 12m14s
ci / build (push) In progress
release / release (push) Successful in 11m48s
ci / image (push) Waiting for needed jobs
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 / build (push) Skipped
ci / image (pull_request) Waiting for needed jobs
ci / build (pull_request) In progress
ci / test (pull_request) Successful in 13m1s
ci / lint (pull_request) Successful in 10m19s
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 / build (push) Successful in 20m6s
ci / image (push) Successful in 4m39s
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 / build (push) Canceled after 0s
ci / lint (push) Canceled after 17s
ci / test (push) Canceled after 17s
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 (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 / 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 / build (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 / 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 / build (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 / 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 / lint (pull_request) Successful in 12m24s
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
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 / build (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 / 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 / build (push) Canceled after 15s
ci / lint (push) Canceled after 16s
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 / build (push) Successful in 5m57s
ci / lint (push) Failing after 15m25s
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 / build (push) Canceled after 0s
ci / test (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 / build (push) Successful in 11m43s
ci / test (push) Successful in 14m21s
ci / lint (push) Successful in 9m59s
ci / image (push) Successful in 3m14s
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
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 / lint (pull_request) Successful in 5m45s
ci / image (pull_request) Successful in 6m20s
ci / test (pull_request) Successful in 11m46s
ci / build (pull_request) Successful in 5m13s
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
134 changed files with 15881 additions and 2693 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.
# 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.
UPTIME_STATUSPAGE_URL=http://localhost:8082
UPTIME_STATUSPAGE_HOSTS=localhost
+86 -14
View File
@@ -13,6 +13,7 @@ concurrency:
env:
GOLANGCI_LINT_VERSION: v2.15.0
SQLC_VERSION: v1.31.1
HELM_VERSION: v3.19.0
jobs:
lint:
@@ -38,13 +39,34 @@ jobs:
sqlc generate
git diff --exit-code -- '*.go'
- 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
run: go vet ./...
- name: golangci-lint
run: |
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION}
"$(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:
runs-on: ubuntu-latest
@@ -58,7 +80,7 @@ jobs:
# Targets of the database checks; SQL Server is left to local runs,
# its image is too large for ephemeral runners.
mariadb:
image: mariadb:11
image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
env:
MARIADB_ROOT_PASSWORD: checkpw
MARIADB_DATABASE: shop
@@ -74,7 +96,7 @@ jobs:
RABBITMQ_DEFAULT_USER: check
RABBITMQ_DEFAULT_PASS: checkpw
kafka:
image: apache/kafka-native:4.1.1
image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
env:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller
@@ -116,7 +138,12 @@ jobs:
run: go test -p 1 -count=1 ./...
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
outputs:
version: ${{ steps.binaries.outputs.version }}
steps:
- uses: actions/checkout@v7
# The runners are ephemeral and clone every action from GitHub, which
@@ -131,12 +158,47 @@ jobs:
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
- name: Build binaries
id: binaries
run: |
for platform in linux/amd64 linux/arm64; do
CGO_ENABLED=0 GOOS=${platform%/*} GOARCH=${platform#*/} \
go build -trimpath -ldflags "-s -w" -o "dist/${platform%/*}_${platform#*/}/" ./cmd/...
set -eu
pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo
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
ls -R dist
image:
# Kaniko runs rootless from docker:cli, the same way as the other
@@ -144,9 +206,12 @@ jobs:
# 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
# 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
container:
image: docker:cli
image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d
defaults:
run:
shell: sh
@@ -155,22 +220,29 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
VERSION: ${{ needs.build.outputs.version }}
run: |
set -eu
REGISTRY="${GITHUB_SERVER_URL#*://}"
IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')"
SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)"
case "$GITHUB_REF" in
refs/tags/v*) TAG="$GITHUB_REF_NAME" ;;
*) TAG="$(date -u +%Y%m%d%H%M%S)-$SHORT" ;;
esac
TAG="$VERSION"
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
refs/heads/main|refs/tags/v*)
if [ -n "${PACKAGE_TOKEN:-}" ]; then
PUSH=""
[ "$GITHUB_REF" = refs/heads/main ] && DEST="$DEST --destination ${IMAGE}:latest"
for c in $CHANNELS; do DEST="$DEST --destination ${IMAGE}:$c"; done
else
echo "PACKAGE_TOKEN is not set; building without pushing."
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
@@ -1,4 +1,4 @@
# syntax=docker/dockerfile:1
# syntax=docker/dockerfile:1@sha256:572cebbc2b15e6f84c077742952674889cb63cd5e9b80abdffcbe587b6f19183
FROM node:24-alpine AS web
WORKDIR /src
COPY package.json package-lock.json ./
@@ -18,7 +18,7 @@ RUN CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo.Version=${VERSION} -X git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo.Commit=${COMMIT}" \
-o /out/ ./cmd/...
FROM gcr.io/distroless/static-debian12:nonroot
FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab
COPY --from=build /out/ /usr/local/bin/
USER nonroot
ENTRYPOINT ["/usr/local/bin/api"]
+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
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:
sqlc generate
@@ -22,6 +22,19 @@ test:
lint:
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:
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.
- **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).
- **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.
- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, enforced 2FA, audit log.
- **Privacy:** GDPR data export (JSON, PDF) and deletion, configurable retention, no telemetry.
- **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, 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.
## Installation
@@ -67,7 +68,24 @@ UPTIME_STATUSPAGE_CACHE_DIR=./.statuspage-cache go run ./cmd/statuspage
### 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
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
```
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.
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_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:
| 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)).
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
+1
View File
@@ -21,6 +21,7 @@ import (
const usage = `usage:
api [serve]
api migrate up|down|status
api health
api admin grant|revoke <email>
api region add <key> [name]
api agent create --kind checker|statuspage [--region <key>] --name <name>
+3
View File
@@ -48,6 +48,9 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
return migrate(ctx, log, cfg, args[1:])
case "admin", "agent", "region":
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":
default:
return usageError{}
+21
View File
@@ -5,6 +5,7 @@
package main
import (
"context"
"errors"
"fmt"
"log/slog"
@@ -20,6 +21,17 @@ import (
)
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")
// Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
@@ -68,3 +80,12 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
}
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
}
+20
View File
@@ -28,6 +28,17 @@ import (
)
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")
// Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
@@ -168,3 +179,12 @@ func resolveCacheDir(dir string) (string, error) {
}
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:
# docker compose --profile checks up -d --wait
mariadb:
image: mariadb:11
image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
profiles: [checks]
environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop}
ports: ["13306:3306"]
@@ -93,7 +93,7 @@ services:
retries: 60
kafka:
image: apache/kafka-native:4.1.1
image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
profiles: [checks]
ports: ["19092:9092"]
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
go 1.27.1
go 1.27.4
require (
github.com/a-h/templ v0.3.1118
@@ -10,9 +10,10 @@ require (
github.com/coreos/go-oidc/v3 v3.21.0
github.com/eclipse/paho.mqtt.golang v1.5.1
github.com/gin-gonic/gin v1.12.0
github.com/go-jose/go-jose/v4 v4.1.4
github.com/go-jose/go-jose/v4 v4.1.9
github.com/go-playground/validator/v10 v10.30.6
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/gosnmp/gosnmp v1.47.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/twmb/franz-go v1.22.3
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.uber.org/zap v1.28.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/oauth2 v0.38.0
golang.org/x/text v0.44.0
@@ -56,6 +58,8 @@ require (
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/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/fsnotify/fsnotify v1.10.1 // 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/reflect2 v1.0.2 // 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/pierrec/lz4/v4 v4.1.33 // 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/sethvargo/go-retry v0.5.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/match v1.1.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/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools/v3 v3.5.2 // indirect
)
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/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
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/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
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-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
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.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY=
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/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
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/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
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.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
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/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
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/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4=
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.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
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/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI=
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/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
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.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
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/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
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/go.mod h1:QRf+8aRqXc019kHkpcs/CTgyWXFzf+bxlsyuo2nAl1o=
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)
}
// 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
// deregisters it. Call it during graceful shutdown.
func (c *Client) Release(ctx context.Context) error {
+36
View File
@@ -88,6 +88,26 @@ type PageIncident struct {
Component string `json:"component"`
StartedAt time.Time `json:"started_at"`
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.
@@ -255,6 +275,22 @@ func (s PageSnapshot) IncidentsForComponent(componentName string) []PageIncident
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
// into ongoing and upcoming occurrences at now.
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"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
@@ -13,12 +14,15 @@ import (
"github.com/jackc/pgx/v5"
"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/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"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.
@@ -34,6 +38,7 @@ const (
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/update", s.agentUpdate)
sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage)
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 {
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 {
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) {
var req agentapi.JobsRequest
if !bind(c, &req) {
+40 -3
View File
@@ -41,6 +41,8 @@ var endpoints = []endpoint{
req: secondFactorRequest{}, resp: sessionStarted},
{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: "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,
req: switchOrgRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/locale", tag: "Account", summary: "Set the interface language", public: true,
@@ -58,8 +60,11 @@ var endpoints = []endpoint{
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)",
description: "`?format=pdf` returns a PDF instead of JSON.", resp: accountExport{}},
{method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
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": ""}},
{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: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it",
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,
@@ -125,6 +130,24 @@ var endpoints = []endpoint{
status: http.StatusNoContent},
{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{}})},
{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
{method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}},
@@ -184,6 +207,10 @@ var endpoints = []endpoint{
description: "Paged by email.", resp: paged(obj{"members": []memberView{}})},
{method: "DELETE", path: "/api/v1/org/members/:user", tag: "Organization", summary: "Remove a member", perm: "members.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "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",
description: "Nobody can grant permissions they do not hold.", perm: "members.manage", sessionOnly: true,
req: assignRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}}},
@@ -260,6 +287,16 @@ var endpoints = []endpoint{
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/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: "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.",
@@ -282,10 +319,10 @@ var endpoints = []endpoint{
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/orgs/:id", tag: "Platform", summary: "Delete an organization with all its data", perm: "platform admin", status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/admin/users/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an account",
description: "A suspended account is signed out everywhere and can neither sign in nor use its API tokens. Platform admins cannot be suspended.",
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},
{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},
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
resp: obj{"regions": []regionView{}}},
+33 -21
View File
@@ -25,27 +25,35 @@ import (
// empty name marks a route deliberately not audited. A test fails for
// routes missing here, so new endpoints cannot slip past the log.
var auditActions = map[string]string{
"POST /api/v1/org/alert-groups": "alert_group.create",
"PUT /api/v1/org/alert-groups/:id": "alert_group.update",
"DELETE /api/v1/org/alert-groups/:id": "alert_group.delete",
"POST /api/v1/locale": "",
"POST /api/v1/markdown/preview": "",
"POST /api/v1/auth/signup": "account.signup",
"POST /api/v1/auth/verify": "account.verify",
"POST /api/v1/auth/verify/resend": "",
"POST /api/v1/orgs": "org.create",
"POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/me/org": "",
"POST /api/v1/me/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable",
"POST /api/v1/me/totp/disable": "account.totp_disable",
"POST /api/v1/me/totp/recovery-codes": "account.recovery_codes",
"POST /api/v1/me/delete": "account.delete",
"POST /api/v1/org/delete": "org.delete",
"POST /api/v1/invitations/:token/accept": "member.join",
"POST /api/v1/invitations/:token/signup": "member.join",
"POST /api/v1/org/alert-groups": "alert_group.create",
"PUT /api/v1/org/alert-groups/:id": "alert_group.update",
"DELETE /api/v1/org/alert-groups/:id": "alert_group.delete",
"POST /api/v1/locale": "",
"POST /api/v1/markdown/preview": "",
"POST /api/v1/auth/signup": "account.signup",
"POST /api/v1/auth/verify": "account.verify",
"POST /api/v1/auth/verify/resend": "",
"POST /api/v1/orgs": "org.create",
"POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/consent": "account.consent",
"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/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable",
"POST /api/v1/me/totp/disable": "account.totp_disable",
"POST /api/v1/me/totp/recovery-codes": "account.recovery_codes",
"POST /api/v1/me/delete": "account.delete",
"POST /api/v1/org/delete": "org.delete",
"POST /api/v1/invitations/:token/accept": "member.join",
"POST /api/v1/invitations/:token/signup": "member.join",
"PUT /api/v1/org/policy": "org.policy_update",
"POST /api/v1/org/monitors": "monitor.create",
@@ -96,6 +104,10 @@ var auditActions = map[string]string{
"PUT /api/v1/admin/check-types": "platform.check_types_update",
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
"PUT /api/v1/admin/limits": "platform.limits_update",
"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/users/:id/limits": "platform.user_limits_update",
"PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension",
+16 -10
View File
@@ -35,6 +35,10 @@ type signupRequest struct {
// after confirming.
OrgName string `json:"org_name" binding:"max=200"`
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) {
@@ -60,6 +64,10 @@ func (s *Server) signup(c *gin.Context) {
fail(c, http.StatusTooManyRequests, "signup_limit")
return
}
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
verify := s.verificationRequired()
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
hash, err := auth.HashPassword(req.Password)
@@ -103,6 +111,11 @@ func (s *Server) signup(c *gin.Context) {
}
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 {
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
fail(c, http.StatusConflict, "email_taken")
@@ -195,12 +208,9 @@ func (s *Server) login(c *gin.Context) {
invalidCredentials(c)
return
}
// Only someone who knows the password learns of the suspension or a
// missing confirmation.
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
// Only someone who knows the password learns of a missing
// confirmation. Suspended accounts sign in, but only to export or
// delete their data.
if user.EmailVerifiedAt == nil {
fail(c, http.StatusForbidden, "email_unverified")
return
@@ -289,10 +299,6 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Metho
internalError(c, err)
return
}
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
var org uuid.UUID
if len(orgs) > 0 {
org = orgs[0].ID
+18 -2
View File
@@ -289,6 +289,10 @@ type incidentView struct {
StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"`
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
@@ -329,14 +333,26 @@ func (s *Server) listIncidents(c *gin.Context) {
if !ok {
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 {
internalError(c, err)
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))
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)
}
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 (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
@@ -13,7 +15,9 @@ import (
"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/buildinfo"
"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/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 {
b.t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
+359
View File
@@ -0,0 +1,359 @@
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. 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",
"/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.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.
first map[uuid.UUID]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
@@ -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 {
return err
}
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err
}
ids := make([]uuid.UUID, len(monitors))
for i, m := range monitors {
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{
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))
}
page.TitleID = "console.monitors.title"
@@ -556,6 +562,7 @@ func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentR
row := web.IncidentRow{
ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor,
Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil,
Title: i.Title, Status: d.statuses.of(i),
}
end := time.Now()
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 {
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 {
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,
}, 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 m, ok := d.byID[*monitor]; ok {
+8 -1
View File
@@ -5,12 +5,16 @@ import (
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"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) {
b.t.Helper()
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() }()
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)
}
+60 -25
View File
@@ -31,9 +31,17 @@ type accountExport struct {
Organizations []exportMembership `json:"organizations"`
Identities []exportIdentity `json:"sso_identities"`
Tokens []exportToken `json:"api_tokens"`
Consents []exportConsent `json:"consents"`
Activity []exportActivity `json:"activity"`
}
// 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 {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
@@ -133,6 +141,14 @@ func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (acco
if err != nil {
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{}
for _, t := range toks {
x.Tokens = append(x.Tokens, exportToken{
@@ -321,6 +337,16 @@ type exportIncident struct {
StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"`
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 {
@@ -502,10 +528,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
if err != nil {
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{}
for _, i := range incidents {
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)
@@ -586,9 +621,12 @@ func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
return err
}
// deleteAccount erases the signed-in user (Art. 17). Organizations only the
// user belongs to go with the account; an organization shared with others
// must be handed over or deleted first, so nobody loses access to it.
// deleteAccount erases the signed-in user (Art. 17). Organizations the
// user is the last owner of go with the account, monitors and all, even
// 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) {
var req deletionRequest
if !bind(c, &req) {
@@ -609,17 +647,11 @@ func (s *Server) deleteAccount(c *gin.Context) {
fail(c, http.StatusForbidden, "confirmation_failed")
return
}
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.owns_shared_orgs"), "organizations": shared,
})
return
}
auth.ClearCookie(c)
// Kept as proof of erasure, without saying whose.
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
@@ -627,24 +659,27 @@ func (s *Server) deleteAccount(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
// eraseAccount deletes u with the organizations only u belongs to and
// ends u's sessions. If u owns organizations shared with others, nothing
// is deleted and their slugs are returned.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []string, orgsDeleted int, err error) {
// eraseAccount deletes u with the organizations u is the last owner of and
// ends u's sessions; u leaves the others.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted int, err error) {
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
for _, o := range owned {
if o.Members > 1 {
shared = append(shared, o.Slug)
if err := q.LockOrgOwners(ctx, o.ID); err != nil {
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 n > 1 {
continue
}
}
if len(shared) > 0 {
return nil
}
for _, o := range owned {
if err := purgeOrg(ctx, q, o.ID); err != nil {
return err
}
@@ -663,13 +698,13 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []strin
}
return nil
})
if err != nil || len(shared) > 0 {
return shared, 0, err
if err != nil {
return 0, err
}
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
}
return nil, orgsDeleted, nil
return orgsDeleted, nil
}
type orgDeletionRequest struct {
+20 -4
View File
@@ -228,10 +228,6 @@ func TestDeleteAccount(t *testing.T) {
memberID := member.userIDSelf()
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 {
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 {
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)
}
}
+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)
}
}
+17 -2
View File
@@ -244,8 +244,10 @@ func (s *Server) acceptInvitation(c *gin.Context) {
}
type inviteSignupRequest struct {
DisplayName string `json:"display_name" binding:"max=200"`
Password string `json:"password" binding:"required,max=1024"`
DisplayName string `json:"display_name" binding:"max=200"`
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
@@ -268,6 +270,10 @@ func (s *Server) inviteSignup(c *gin.Context) {
fail(c, http.StatusGone, "invitation_invalid")
return
}
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
@@ -288,6 +294,11 @@ func (s *Server) inviteSignup(c *gin.Context) {
})
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") {
fail(c, http.StatusConflict, "email_taken")
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))
}
+34 -11
View File
@@ -51,11 +51,20 @@ func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc {
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 {
URL string `json:"url" binding:"max=2000"`
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
@@ -69,7 +78,7 @@ func validLegalURL(raw string) bool {
// nil for the platform.
func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool {
kind := c.Param("kind")
if !validLegalKind(kind) {
if !slices.Contains(legalKinds(org), kind) {
fail(c, http.StatusNotFound, "not_found")
return false
}
@@ -83,12 +92,16 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b
return false
}
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()
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
if req.URL == "" && req.Markdown == "" {
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 {
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) {
if s.saveLegal(c, tenant.System(), nil) {
if err := s.legal.bump(c.Request.Context(), s.rdb); err != nil {
s.log.ErrorContext(c.Request.Context(), "announcing legal document change failed", "error", err)
ctx := c.Request.Context()
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"`
URL string `json:"url"`
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),
@@ -126,12 +144,15 @@ func (s *Server) ownLegal(ctx context.Context, scope tenant.Scope, org *uuid.UUI
rows, err = q.LegalDocuments(ctx, org)
return err
})
out := make([]legalView, 0, len(web.LegalKinds))
for _, kind := range web.LegalKinds {
out := make([]legalView, 0, len(legalKinds(org)))
for _, kind := range legalKinds(org) {
v := legalView{Kind: kind}
for _, r := range rows {
if r.Kind == kind && (r.OrgID == nil) == (org == nil) {
v.URL, v.Markdown = r.Url, r.Markdown
if org == nil && slices.Contains(web.ConsentKinds, kind) {
v.Version = r.Version
}
}
}
out = append(out, v)
@@ -190,10 +211,12 @@ func (s *Server) legalPage(c *gin.Context) {
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))
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
}
@@ -203,7 +226,7 @@ func (s *Server) orgLegalView(c *gin.Context, p *principal, page web.Page, me we
if err != nil {
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) {
@@ -216,5 +239,5 @@ func (s *Server) adminLegalPage(c *gin.Context) {
internalError(c, err)
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 {
t.Fatal(err)
}
t.Cleanup(func() {
for _, kind := range []string{"imprint", "privacy"} {
admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{})
}
})
t.Cleanup(func() { clearPlatformLegal(admin) })
imprint := "# Impressum\n\nBetreiber GmbH <script>alert(1)</script>"
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")
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, "")
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")
// The console footer links them, also before signing in.
@@ -121,7 +118,7 @@ func TestLegalChangeReachesOtherReplicas(t *testing.T) {
if err != nil {
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{})
visitor := b.browser(t)
@@ -147,3 +144,14 @@ func TestMarkdownPreview(t *testing.T) {
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 (
"errors"
"net/http"
"slices"
"strings"
"time"
@@ -495,3 +496,81 @@ func (s *Server) updatePolicy(c *gin.Context) {
}
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/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -262,17 +261,11 @@ func (s *Server) adminDeleteUser(c *gin.Context) {
return
}
ctx := c.Request.Context()
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.user_owns_shared_orgs"), "organizations": shared,
})
return
}
auditDetail(c, "organizations_deleted", orgsDeleted)
c.Status(http.StatusNoContent)
}
+7 -9
View File
@@ -140,7 +140,8 @@ func TestModeration(t *testing.T) {
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, "")
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
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)
}
fresh := e.browser(t)
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword})
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, body := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
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 {
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)
expect(t, "delete an admin", st, body, http.StatusConflict, "target_is_admin")
// An owner of a shared organization cannot be deleted before it.
fresh.do("POST", "/api/v1/me/org", map[string]any{"org_id": orgID})
e.joinVia(t, fresh.invite("m@"+uniq("mod")+".test", fresh.roleID("viewer")))
st, body = admin.do("DELETE", "/api/v1/admin/users/"+userID, nil)
expect(t, "delete the owner of a shared org", st, body, http.StatusConflict, "owns_shared_orgs")
// Deleting: page, organization, account.
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
t.Errorf("delete page = %d", st)
+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")
}
}
+70 -10
View File
@@ -47,7 +47,11 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/admin/orgs", s.adminOrgsPage)
r.GET("/admin/legal", s.adminLegalPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/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("/consent", s.consentPage)
r.GET("/account/suspended", s.suspendedPage)
}
// flashErrors lists the codes a redirect may ask a page to display. Anything
@@ -56,6 +60,7 @@ var flashErrors = map[ssoError]bool{
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
"sso_email_unverified": true, "signup_limit": true,
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
}
@@ -88,25 +93,46 @@ func (s *Server) loginPage(c *gin.Context) {
c.Redirect(http.StatusSeeOther, next)
return
}
allowed, err := s.signupAllowed(c.Request.Context())
email, signupProviders, err := s.signupOptions(c.Request.Context())
if err != nil {
internalError(c, err)
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) {
allowed, err := s.signupAllowed(c.Request.Context())
email, providers, err := s.signupOptions(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
if !allowed {
if !email && len(providers) == 0 {
c.Redirect(http.StatusSeeOther, "/login")
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) {
@@ -232,6 +258,10 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err)
return
}
if me.DeletesOrgs, err = s.lastOwnedOrgs(ctx, sess.UserID); err != nil {
internalError(c, err)
return
}
var (
identities []web.Identity
canLink bool
@@ -259,7 +289,29 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err)
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 {
@@ -350,19 +402,26 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
var (
roles []store.Role
pending []store.ListPendingInvitationsRow
owners int64
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if roles, err = q.ListRoles(ctx); err != nil {
return err
}
if owners, err = q.CountOwners(ctx, p.Org.ID); err != nil {
return err
}
pending, err = q.ListPendingInvitations(ctx)
return err
})
if err != nil {
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)
if err != nil {
return nil, err
@@ -551,7 +610,7 @@ func (s *Server) adminPage(c *gin.Context) {
for _, t := range check.Types {
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
}
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx))))
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) {
@@ -589,7 +648,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) {
v := web.RegionsView{APIBase: apiBase, Next: next}
v := web.RegionsView{APIBase: apiBase, Next: next, Install: s.installView()}
never := i18n.T(ctx, "tokens.never")
for _, r := range regions {
n, err := s.sched.Instances(ctx, r.ID.String())
@@ -607,7 +666,8 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
if a.LastSeenAt != nil {
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 {
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 {
t.Helper()
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 {
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"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"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/tenant"
)
@@ -153,3 +157,46 @@ func (b *browser) userIDSelf() uuid.UUID {
_, me := b.do("GET", "/api/v1/me", nil)
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")
}
}
+21 -1
View File
@@ -44,6 +44,8 @@ type Server struct {
eval *evaluate.Evaluator
smtp *notify.SMTP
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 *versioned[map[string]bool]
// checkerNet caches whether platform checkers may reach private
@@ -82,6 +84,7 @@ func New(cfg config.API, d Deps) *Server {
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
consent: newVersioned[map[string]int64]("consent"),
checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"),
@@ -97,9 +100,10 @@ func (s *Server) Mount(r gin.IRouter) {
s.mountHeartbeats(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("/install.sh", s.installScript)
g.GET("/api/docs", s.apiDocsPage)
v1 := g.Group("/api/v1")
@@ -114,10 +118,12 @@ func (s *Server) Mount(r gin.IRouter) {
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
v1.POST("/consent", auth.Require(), s.acceptConsent)
me := v1.Group("/me", auth.Require())
me.GET("", s.me)
me.POST("/org", s.switchOrg)
me.DELETE("/identities/:provider", s.unlinkIdentity)
me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
@@ -175,6 +181,10 @@ func (s *Server) Mount(r gin.IRouter) {
admin.GET("/check-types", s.adminListCheckTypes)
admin.PUT("/check-types", s.adminSetCheckTypes)
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.PUT("/limits", s.adminSetLimits)
admin.GET("/orgs", s.adminListOrgs)
@@ -213,6 +223,14 @@ func (s *Server) Mount(r gin.IRouter) {
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
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("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
@@ -232,6 +250,7 @@ func (s *Server) Mount(r gin.IRouter) {
org.GET("/members", can(authz.MembersRead), s.listMembers)
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.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole)
@@ -252,6 +271,7 @@ func (s *Server) Mount(r gin.IRouter) {
g.GET("/sso", s.ssoLookup)
g.GET("/sso/callback", s.ssoCallback)
g.GET("/login/sso/:provider", s.platformSSOStart)
g.GET("/sso/:slug", s.ssoChoose)
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
// existing account instead of signing in.
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
@@ -206,6 +209,10 @@ func (s *Server) ssoCallback(c *gin.Context) {
s.ssoAbort(c, f.LinkUser, "sso_denied")
return
}
if f.Platform {
s.platformCallback(c, f, state)
return
}
var row store.SsoProvider
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)
return
}
if user.DisabledAt != nil {
s.ssoAbort(c, uuid.Nil, "account_suspended")
return
}
// Suspended accounts sign in too, but only to export or delete their
// data (accountGate).
if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(ctx, old)
}
+28
View File
@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"net/url"
"os"
"regexp"
"strings"
"testing"
"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], "-", "") }
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) {
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{
"email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
"consent": versions != "", "consent_versions": versions,
})
if st != http.StatusOK {
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
regions []store.Region
incidents []store.Incident
updates []store.PublicIncidentUpdatesRow
statuses customStatuses
planned map[uuid.UUID][]store.MaintenanceWindow
)
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 {
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 {
return err
}
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
})
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.Status = agentapi.Summarize(states)
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 {
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
}
+4 -1
View File
@@ -98,7 +98,10 @@ type API struct {
// StatusPageURL is where the platform's status page servers are
// reachable; the console links pages as <StatusPageURL>/<slug>.
StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"`
Retention Retention
// 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 sets how long data is kept. Zero keeps it forever.
+119 -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_short": "private Adressen",
"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_checker": "Checker",
"agents.kind_statuspage": "Statuspage-Server",
"agents.list": "Agents",
"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.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.",
@@ -50,8 +60,11 @@
"apidocs.hint": "„Try it out“ nutzt deine aktuelle Sitzung.",
"apidocs.title": "API-Dokumentation",
"app.network_error": "Verbindung fehlgeschlagen.",
"audit.action.account.consent": "Datenschutz und AGB zugestimmt",
"audit.action.account.delete": "Konto gelöscht",
"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.signup": "Konto erstellt",
"audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert",
@@ -76,12 +89,19 @@
"audit.action.group.create": "Gruppe erstellt",
"audit.action.group.delete": "Gruppe gelöscht",
"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.delete": "Einladung zurückgezogen",
"audit.action.maintenance.create": "Wartung geplant",
"audit.action.maintenance.delete": "Wartung gelöscht",
"audit.action.maintenance.update": "Wartung geändert",
"audit.action.member.join": "Der Organisation beigetreten",
"audit.action.member.owner": "Owner geändert",
"audit.action.member.remove": "Mitglied entfernt",
"audit.action.member.role_assign": "Rolle zugewiesen",
"audit.action.member.role_unassign": "Rolle entzogen",
@@ -98,6 +118,9 @@
"audit.action.platform.agent_delete": "Plattform-Agent widerrufen",
"audit.action.platform.check_types_update": "Check-Typen geändert",
"audit.action.platform.checker_network_update": "Checker-Netzwerk geändert",
"audit.action.platform.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.limits_update": "Standard-Limits geändert",
"audit.action.platform.org_delete": "Organisation durch Admin gelöscht",
@@ -149,11 +172,14 @@
"auth.login.title": "Anmelden",
"auth.login.to_signup": "Registrieren",
"auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.",
"auth.or": "oder",
"auth.signup.submit": "Anlegen",
"auth.signup.title": "Konto anlegen",
"auth.signup.to_login": "Zur Anmeldung",
"auth.sso.continue_with": "Weiter mit {{.Name}}",
"auth.sso.heading": "Single Sign-on",
"auth.sso.org_placeholder": "Kurzname der Organisation",
"auth.sso.signup_with": "Registrieren mit {{.Name}}",
"auth.sso.submit": "Weiter",
"auth.verify.intro": "Drücke den Knopf, um deine E-Mail-Adresse zu bestätigen und dich anzumelden.",
"auth.verify.resend_intro": "Wenn ein unbestätigtes Konto diese Adresse nutzt, schicken wir ihm einen neuen Link.",
@@ -456,6 +482,16 @@
"common.no": "nein",
"common.save": "Speichern",
"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.title": "Monitore",
"console.nav.admin": "Admin",
@@ -490,6 +526,8 @@
"error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.",
"error.check_type_disabled": "Dieser Check-Typ ist für diese Organisation oder Installation abgeschaltet.",
"error.confirmation_failed": "Die Bestätigung stimmt nicht.",
"error.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_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
@@ -498,6 +536,7 @@
"error.forbidden": "Dafür fehlt dir die Berechtigung.",
"error.group_cycle": "Eine Gruppe kann nicht in sich selbst oder eine ihrer Untergruppen verschoben werden.",
"error.group_too_deep": "Gruppen lassen sich höchstens acht Ebenen tief verschachteln.",
"error.idp_in_use": "{{.Count}} Konten melden sich nur über diesen Anbieter an. Deaktiviere ihn stattdessen.",
"error.internal": "Interner Fehler.",
"error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.",
"error.invalid_assertion_op": "Unbekannter Operator.",
@@ -544,6 +583,8 @@
"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.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.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.",
@@ -555,9 +596,9 @@
"error.org_limit": "Dein Konto darf höchstens {{.Max}} Organisationen besitzen.",
"error.org_not_found": "Organisation nicht gefunden.",
"error.org_suspended": "Der Betreiber hat diese Organisation gesperrt.",
"error.owner_cannot_be_removed": "Der Owner kann nicht entfernt werden.",
"error.owner_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.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.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.",
@@ -576,6 +617,7 @@
"error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
"error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.",
"error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.",
"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_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.",
@@ -587,6 +629,8 @@
"error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.",
"error.sso_required_by_org": "Diese Organisation verlangt die Anmeldung über ihren SSO-Provider.",
"error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.",
"error.status_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.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.",
"error.token_lifetime_exceeds_policy": {
@@ -598,7 +642,6 @@
"error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
"error.unauthenticated": "Anmeldung erforderlich.",
"error.unsupported_locale": "Sprache wird nicht unterstützt.",
"error.user_owns_shared_orgs": "Dem Account gehören Organisationen mit weiteren Mitgliedern. Lösche diese zuerst oder übertrage sie.",
"error.verification_expired": "Dieser Bestätigungslink ist ungültig oder abgelaufen. Fordere einen neuen an.",
"error.verification_mail_failed": "Dein Konto wurde angelegt, aber die Bestätigungs-E-Mail konnte nicht gesendet werden. Fordere später einen neuen Link an.",
"evidence.body": "Antwort-Body",
@@ -641,6 +684,7 @@
"export.account_title": "Export personenbezogener Daten",
"export.download_json": "JSON herunterladen",
"export.download_pdf": "PDF herunterladen",
"export.field.accepted_at": "Zugestimmt am",
"export.field.account": "Konto",
"export.field.action": "Aktion",
"export.field.activity": "Aktivität",
@@ -655,6 +699,7 @@
"export.field.client_id": "Client-ID",
"export.field.config": "Konfiguration",
"export.field.confirmations": "Bestätigungen",
"export.field.consents": "Zugestimmte Dokumente",
"export.field.created_at": "Erstellt",
"export.field.custom_domain": "Eigene Domain",
"export.field.custom_roles": "Eigene Rollen",
@@ -681,6 +726,7 @@
"export.field.locale": "Sprache",
"export.field.member_since": "Mitglied seit",
"export.field.members": "Mitglieder",
"export.field.message": "Nachricht",
"export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitorgruppen",
"export.field.monitor_id": "Monitor-ID",
@@ -697,6 +743,7 @@
"export.field.platform_admin": "Plattform-Admin",
"export.field.prefix": "Präfix",
"export.field.provider": "Anbieter",
"export.field.public": "Öffentlich",
"export.field.published": "Veröffentlicht",
"export.field.region": "Region",
"export.field.region_ids": "Regionen",
@@ -723,7 +770,9 @@
"export.field.total": "Checks",
"export.field.totp_enabled_at": "Zwei-Faktor aktiviert",
"export.field.type": "Typ",
"export.field.updates": "Updates",
"export.field.user_agent": "Browser",
"export.field.version": "Version",
"export.json_only": "Nur im JSON-Export enthalten.",
"export.no": "nein",
"export.none": "Keine.",
@@ -733,10 +782,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.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_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_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.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_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",
@@ -751,6 +801,51 @@
"groups.none": "– oberste Ebene –",
"groups.parent": "In Gruppe",
"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_of_monitor": "Alle Vorfälle dieses Monitors",
"incidents.none": "Bisher keine Incidents.",
@@ -768,11 +863,14 @@
"legal.hint": "Ein Link hat Vorrang vor dem Text. Beide Felder leer lassen, um das Dokument zu entfernen.",
"legal.imprint": "Impressum",
"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_title": "Impressum & Datenschutz",
"legal.platform_intro": "Im Footer der Konsole und der Anmeldeseiten verlinkt sowie auf Statusseiten von Organisationen ohne eigene Dokumente.",
"legal.platform_title": "Impressum & Datenschutz der Plattform",
"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 & AGB der Plattform",
"legal.privacy": "Datenschutz",
"legal.terms": "AGB",
"legal.url": "Link auf eine bestehende Seite",
"limits.default": "Standard: {{.Value}}",
"limits.intro": "Gelten für jede Organisation und jeden Account ohne eigenen Wert, auch wenn du sie später änderst. 0 heißt unbegrenzt. Ein gesenktes Limit lässt alles Bestehende stehen; nur neue Monitore, Statusseiten, Regionen oder Organisationen werden abgelehnt.",
@@ -846,19 +944,25 @@
"md.ul": "Aufzählung",
"md.write": "Schreiben",
"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_link": "Schicke diesen Link an die eingeladene Person. Er gilt 7 Tage und funktioniert einmal.",
"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.pending": "Offene Einladungen",
"members.remove": "Aus der Organisation entfernen",
"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.role": "Rolle",
"members.roles": "Rollen",
"members.scope": "Beschränkt auf",
"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.unassign": "Rolle entfernen",
"moderation.actions": "Sperren oder löschen …",
@@ -1184,6 +1288,10 @@
"scope.status_page": "Statuspage",
"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.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": {
"one": "{{.Count}} Wiederherstellungscode übrig",
"other": "{{.Count}} Wiederherstellungscodes übrig"
@@ -1210,6 +1318,7 @@
"settings.audit": "Wer wann was geändert hat.",
"settings.channels": "Webhooks und E-Mail für Incidents",
"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.members": "Personen einladen und Rollen vergeben",
"settings.org": "Anmelderichtlinien und Token-Laufzeit",
@@ -1270,6 +1379,9 @@
"storage.retention": "Löschen nach",
"storage.size": "Größe",
"storage.title": "Datenspeicher",
"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.create": "Token erstellen",
"tokens.created": "Erstellt",
+119 -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_short": "private addresses",
"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_checker": "Checker",
"agents.kind_statuspage": "Status page server",
"agents.list": "Agents",
"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.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.",
@@ -50,8 +60,11 @@
"apidocs.hint": "\"Try it out\" uses your current session.",
"apidocs.title": "API documentation",
"app.network_error": "Connection failed.",
"audit.action.account.consent": "Privacy policy and terms accepted",
"audit.action.account.delete": "Account deleted",
"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.signup": "Account created",
"audit.action.account.totp_disable": "Two-factor authentication disabled",
@@ -76,12 +89,19 @@
"audit.action.group.create": "Group created",
"audit.action.group.delete": "Group deleted",
"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.delete": "Invitation withdrawn",
"audit.action.maintenance.create": "Maintenance planned",
"audit.action.maintenance.delete": "Maintenance deleted",
"audit.action.maintenance.update": "Maintenance changed",
"audit.action.member.join": "Joined the organization",
"audit.action.member.owner": "Ownership changed",
"audit.action.member.remove": "Member removed",
"audit.action.member.role_assign": "Role assigned",
"audit.action.member.role_unassign": "Role removed",
@@ -98,6 +118,9 @@
"audit.action.platform.agent_delete": "Platform agent revoked",
"audit.action.platform.check_types_update": "Check types changed",
"audit.action.platform.checker_network_update": "Checker network changed",
"audit.action.platform.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.limits_update": "Default limits changed",
"audit.action.platform.org_delete": "Organization deleted by admin",
@@ -149,11 +172,14 @@
"auth.login.title": "Sign in",
"auth.login.to_signup": "Sign up",
"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.title": "Create account",
"auth.signup.to_login": "Back to sign in",
"auth.sso.continue_with": "Continue with {{.Name}}",
"auth.sso.heading": "Single sign-on",
"auth.sso.org_placeholder": "Organization short name",
"auth.sso.signup_with": "Sign up with {{.Name}}",
"auth.sso.submit": "Continue",
"auth.verify.intro": "Press the button to confirm your email address and sign in.",
"auth.verify.resend_intro": "If an unconfirmed account uses this address, we send it a new link.",
@@ -456,6 +482,16 @@
"common.no": "no",
"common.save": "Save",
"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.title": "Monitors",
"console.nav.admin": "Admin",
@@ -490,6 +526,8 @@
"error.channel_type_immutable": "The type of a channel cannot be changed.",
"error.check_type_disabled": "This check type is switched off for this organization or installation.",
"error.confirmation_failed": "The confirmation does not match.",
"error.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_taken": "This domain is already used by another status page.",
"error.email_not_configured": "Email is not available on this server.",
@@ -498,6 +536,7 @@
"error.forbidden": "You are not allowed to do this.",
"error.group_cycle": "A group cannot be placed inside itself or one of its subgroups.",
"error.group_too_deep": "Groups can be nested at most eight levels deep.",
"error.idp_in_use": "{{.Count}} accounts sign in only through this provider. Disable it instead.",
"error.internal": "Internal error.",
"error.invalid_alert_group": "An alert group does not exist in this organization.",
"error.invalid_assertion_op": "Unknown condition operator.",
@@ -544,6 +583,8 @@
"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.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.maintenance_overlaps": "The maintenance would last longer than the time until it repeats.",
"error.maintenance_without_targets": "Choose at least one monitor or group.",
@@ -555,9 +596,9 @@
"error.org_limit": "Your account may own at most {{.Max}} organizations.",
"error.org_not_found": "Organization not found.",
"error.org_suspended": "The operator suspended this organization.",
"error.owner_cannot_be_removed": "The owner cannot be removed.",
"error.owner_cannot_be_removed": "Owners cannot be removed. Take their ownership away first.",
"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.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.",
@@ -576,6 +617,7 @@
"error.slug_taken": "This short name is already taken.",
"error.sso_denied": "Sign-in was cancelled at the identity provider.",
"error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.",
"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_forbidden_address": "The issuer points to a non-public address.",
"error.sso_identity_taken": "This SSO sign-in is already linked to another account.",
@@ -587,6 +629,8 @@
"error.sso_provider_error": "The identity provider could not complete the sign-in.",
"error.sso_required_by_org": "This organization requires signing in through its SSO provider.",
"error.sso_unavailable": "Single sign-on is not available for this organization.",
"error.status_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.target_is_admin": "Platform admins cannot be suspended or deleted here.",
"error.token_lifetime_exceeds_policy": {
@@ -598,7 +642,6 @@
"error.totp_setup_expired": "Setup expired, please start again.",
"error.unauthenticated": "Authentication required.",
"error.unsupported_locale": "Unsupported language.",
"error.user_owns_shared_orgs": "The account owns organizations with other members. Delete those or hand them over first.",
"error.verification_expired": "This confirmation link is invalid or expired. Ask for a new one.",
"error.verification_mail_failed": "Your account was created, but the confirmation email could not be sent. Ask for a new link in a while.",
"evidence.body": "Response body",
@@ -641,6 +684,7 @@
"export.account_title": "Personal data export",
"export.download_json": "Download JSON",
"export.download_pdf": "Download PDF",
"export.field.accepted_at": "Accepted at",
"export.field.account": "Account",
"export.field.action": "Action",
"export.field.activity": "Activity",
@@ -655,6 +699,7 @@
"export.field.client_id": "Client ID",
"export.field.config": "Configuration",
"export.field.confirmations": "Confirmations",
"export.field.consents": "Accepted documents",
"export.field.created_at": "Created",
"export.field.custom_domain": "Custom domain",
"export.field.custom_roles": "Custom roles",
@@ -681,6 +726,7 @@
"export.field.locale": "Language",
"export.field.member_since": "Member since",
"export.field.members": "Members",
"export.field.message": "Message",
"export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitor groups",
"export.field.monitor_id": "Monitor ID",
@@ -697,6 +743,7 @@
"export.field.platform_admin": "Platform admin",
"export.field.prefix": "Prefix",
"export.field.provider": "Provider",
"export.field.public": "Public",
"export.field.published": "Published",
"export.field.region": "Region",
"export.field.region_ids": "Regions",
@@ -723,7 +770,9 @@
"export.field.total": "Checks",
"export.field.totp_enabled_at": "Two-factor enabled",
"export.field.type": "Type",
"export.field.updates": "Updates",
"export.field.user_agent": "Browser",
"export.field.version": "Version",
"export.json_only": "Included in the JSON export only.",
"export.no": "no",
"export.none": "None.",
@@ -733,10 +782,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.delete_account": "Delete account",
"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_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.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_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",
@@ -751,6 +801,51 @@
"groups.none": "– top level –",
"groups.parent": "Inside group",
"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_of_monitor": "All incidents of this monitor",
"incidents.none": "No incidents so far.",
@@ -768,11 +863,14 @@
"legal.hint": "A link takes precedence over the text. Leave both empty to remove the document.",
"legal.imprint": "Legal notice",
"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_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_title": "Platform legal notice & privacy",
"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 & terms",
"legal.privacy": "Privacy policy",
"legal.terms": "Terms of service",
"legal.url": "Link to an existing page",
"limits.default": "default: {{.Value}}",
"limits.intro": "Apply to every organization and account without an override of its own, also when you change them later. 0 means unlimited. Lowering a limit keeps everything that exists; only new monitors, status pages, regions or organizations are refused.",
@@ -846,19 +944,25 @@
"md.ul": "Bulleted list",
"md.write": "Write",
"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_link": "Send this link to the invitee. It is valid for 7 days and works once.",
"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.pending": "Pending invitations",
"members.remove": "Remove from organization",
"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.role": "Role",
"members.roles": "Roles",
"members.scope": "Limited to",
"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.unassign": "Remove role",
"moderation.actions": "Suspend or delete …",
@@ -1184,6 +1288,10 @@
"scope.status_page": "status page",
"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.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": {
"one": "{{.Count}} recovery code left",
"other": "{{.Count}} recovery codes left"
@@ -1210,6 +1318,7 @@
"settings.audit": "Who changed what and when.",
"settings.channels": "Webhooks and email for incidents",
"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.members": "Invite people and assign roles",
"settings.org": "Sign-in policies and token lifetime",
@@ -1270,6 +1379,9 @@
"storage.retention": "Delete after",
"storage.size": "Size",
"storage.title": "Data storage",
"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.create": "Create token",
"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
}
@@ -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);
+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
}
+16 -1
View File
@@ -16,8 +16,10 @@ import (
"golang.org/x/oauth2"
)
// Provider is one organization's IdP registration.
// Provider is an IdP registration, of an organization or the platform.
type Provider struct {
// Kind is empty for OpenID Connect or GitHub.
Kind string
Issuer string
ClientID string
ClientSecret string
@@ -91,6 +93,9 @@ func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error {
return err
}
// CheckURL checks that a server URL may be used, without contacting it.
func (c *Client) CheckURL(issuer string) error { return c.checkIssuer(issuer) }
func (c *Client) checkIssuer(issuer string) error {
u, err := url.Parse(issuer)
if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
@@ -144,6 +149,9 @@ func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error
if err := c.checkIssuer(p.Issuer); err != nil {
return "", err
}
if p.Kind == GitHub {
return c.githubOAuth(p).AuthCodeURL(f.State, oauth2.S256ChallengeOption(f.Verifier)), nil
}
op, err := c.discover(ctx, p.Issuer)
if err != nil {
return "", err
@@ -157,6 +165,13 @@ func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error
// Exchange redeems the authorization code and verifies the ID token's
// signature, issuer, audience, expiry and nonce.
func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) {
if p.Kind == GitHub {
tok, err := c.githubOAuth(p).Exchange(oidc.ClientContext(ctx, c.http), code, oauth2.VerifierOption(f.Verifier))
if err != nil {
return Claims{}, fmt.Errorf("sso: code exchange: %w", err)
}
return c.githubClaims(ctx, p, tok)
}
op, err := c.discover(ctx, p.Issuer)
if err != nil {
return Claims{}, err
+6 -1
View File
@@ -60,6 +60,8 @@ type Server struct {
mu sync.Mutex
cache map[string]entry
refreshing map[string]bool
// background tracks refreshes started by visits.
background sync.WaitGroup
}
// entry is one cached page, also its on-disk form.
@@ -309,7 +311,7 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
s.mu.Unlock()
if cached {
if s.now().Sub(e.Fetched) >= freshFor {
go s.refresh(context.WithoutCancel(ctx), key, host, slug)
s.background.Go(func() { s.refresh(context.WithoutCancel(ctx), key, host, slug) })
}
return e, true
}
@@ -356,6 +358,9 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
s.fetch(ctx, key, host, slug)
}
// Wait returns once the background refreshes started by visits are done.
func (s *Server) Wait() { s.background.Wait() }
// Run keeps every known page fresh until ctx ends, so pages stay current
// even without visitors and the cache is warm when the API goes away.
func (s *Server) Run(ctx context.Context) {
+37
View File
@@ -73,6 +73,9 @@ func newHarness(t *testing.T, src *fakeSource, dir string, now *time.Time) harne
t.Fatal(err)
}
s.now = func() time.Time { return *now }
// Runs before the cleanup of a TempDir created earlier, so no refresh
// writes into a directory being removed.
t.Cleanup(s.Wait)
gin.SetMode(gin.TestMode)
r := gin.New()
s.Mount(r)
@@ -354,6 +357,17 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) {
},
Incidents: []agentapi.PageIncident{
{Component: "Public API", StartedAt: now.Add(-10 * time.Minute)},
{
Component: "Website", StartedAt: now.Add(-time.Hour), Title: "Anmeldung langsam", Status: "monitoring",
Updates: []agentapi.PageIncidentUpdate{
{Status: "monitoring", Message: "Fix ist **ausgerollt**.", At: now.Add(-5 * time.Minute)},
{Status: "investigating", Message: "Wir schauen.\n\n<script>alert(1)</script>", At: now.Add(-50 * time.Minute)},
},
},
{Component: "Website", StartedAt: now.Add(-2 * time.Hour), Title: "Zahlungen", Status: "custom", StatusName: "Warten auf Anbieter", StatusColor: "#7c3aed"},
},
Maintenance: []agentapi.PageMaintenance{
{Title: "Datenbank-Upgrade", Start: now.Add(24 * time.Hour), End: now.Add(25 * time.Hour), Components: []string{"Website"}},
},
}
@@ -363,6 +377,29 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) {
}}
h := newHarness(t, src, t.TempDir(), &now)
t.Run("incidents show their title, status and updates", func(t *testing.T) {
_, body := h.get("status.example.test", "/acme")
for _, want := range []string{"Anmeldung langsam", "Beobachtung", "Untersuchung läuft", "<strong>ausgerollt</strong>", "Wir schauen."} {
if !strings.Contains(body, want) {
t.Errorf("GET /acme missing %q", want)
}
}
if strings.Contains(body, "<script>alert") {
t.Error("an update's HTML reached the page")
}
if !strings.Contains(body, "Warten auf Anbieter") || !strings.Contains(body, "background-color:#7c3aed") {
t.Error("the own status lacks its name or color")
}
// The component list names the status of the newest open incident.
if i, j := strings.Index(body, "Beobachtung"), strings.Index(body, "Letzte Vorfälle"); i < 0 || i > j {
t.Error("the component list lacks the status of the open incident")
}
// Recent incidents come before planned maintenance.
if i, j := strings.Index(body, "Letzte Vorfälle"), strings.Index(body, "Geplante Wartung"); i < 0 || j < 0 || i > j {
t.Errorf("incidents at %d, planned maintenance at %d: want incidents first", i, j)
}
})
t.Run("main page renders nested groups and clickable links", func(t *testing.T) {
code, body := h.get("status.example.test", "/acme")
if code != http.StatusOK {
+49 -3
View File
@@ -176,8 +176,47 @@ func (q *Queries) OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDail
return items, nil
}
const orgIncidentUpdatesExport = `-- name: OrgIncidentUpdatesExport :many
SELECT incident_id, status, message, public, created_at FROM incident_updates
WHERE org_id = $1 ORDER BY created_at
`
type OrgIncidentUpdatesExportRow struct {
IncidentID uuid.UUID
Status string
Message string
Public bool
CreatedAt time.Time
}
func (q *Queries) OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error) {
rows, err := q.db.Query(ctx, orgIncidentUpdatesExport, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []OrgIncidentUpdatesExportRow{}
for rows.Next() {
var i OrgIncidentUpdatesExportRow
if err := rows.Scan(
&i.IncidentID,
&i.Status,
&i.Message,
&i.Public,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const orgIncidentsExport = `-- name: OrgIncidentsExport :many
SELECT i.id, i.monitor_id, m.name AS monitor, i.started_at, i.resolved_at, i.cause
SELECT i.id, i.monitor_id, m.name AS monitor, i.started_at, i.resolved_at, i.cause, i.title, i.status
FROM incidents i LEFT JOIN monitors m ON m.id = i.monitor_id
WHERE i.org_id = $1 ORDER BY i.started_at
`
@@ -189,6 +228,8 @@ type OrgIncidentsExportRow struct {
StartedAt time.Time
ResolvedAt *time.Time
Cause []byte
Title string
Status *string
}
func (q *Queries) OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error) {
@@ -207,6 +248,8 @@ func (q *Queries) OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]Or
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
); err != nil {
return nil, err
}
@@ -260,7 +303,8 @@ func (q *Queries) OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgM
const ownedOrgs = `-- name: OwnedOrgs :many
SELECT o.id, o.slug, o.name,
(SELECT count(*) FROM memberships m2 WHERE m2.org_id = o.id)::bigint AS members
(SELECT count(*) FROM memberships m2 WHERE m2.org_id = o.id)::bigint AS members,
(SELECT count(*) FROM memberships m3 WHERE m3.org_id = o.id AND m3.is_owner)::bigint AS owners
FROM orgs o JOIN memberships m ON m.org_id = o.id
WHERE m.user_id = $1 AND m.is_owner
ORDER BY o.name
@@ -271,9 +315,10 @@ type OwnedOrgsRow struct {
Slug string
Name string
Members int64
Owners int64
}
// Organizations user owns, with their member count.
// Organizations user owns, with their member and owner counts.
func (q *Queries) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error) {
rows, err := q.db.Query(ctx, ownedOrgs, userID)
if err != nil {
@@ -288,6 +333,7 @@ func (q *Queries) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsR
&i.Slug,
&i.Name,
&i.Members,
&i.Owners,
); err != nil {
return nil, err
}
+326 -5
View File
@@ -12,6 +12,47 @@ import (
"github.com/google/uuid"
)
const addIncidentUpdate = `-- name: AddIncidentUpdate :one
INSERT INTO incident_updates (org_id, incident_id, status, status_id, message, public, author_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, org_id, incident_id, status, message, public, author_id, created_at, status_id
`
type AddIncidentUpdateParams struct {
OrgID uuid.UUID
IncidentID uuid.UUID
Status string
StatusID *uuid.UUID
Message string
Public bool
AuthorID *uuid.UUID
}
func (q *Queries) AddIncidentUpdate(ctx context.Context, arg AddIncidentUpdateParams) (IncidentUpdate, error) {
row := q.db.QueryRow(ctx, addIncidentUpdate,
arg.OrgID,
arg.IncidentID,
arg.Status,
arg.StatusID,
arg.Message,
arg.Public,
arg.AuthorID,
)
var i IncidentUpdate
err := row.Scan(
&i.ID,
&i.OrgID,
&i.IncidentID,
&i.Status,
&i.Message,
&i.Public,
&i.AuthorID,
&i.CreatedAt,
&i.StatusID,
)
return i, err
}
const claimNotifications = `-- name: ClaimNotifications :many
UPDATE notifications SET next_attempt_at = now() + interval '5 minutes'
WHERE id IN (
@@ -82,6 +123,29 @@ func (q *Queries) CreateChannel(ctx context.Context, arg CreateChannelParams) (N
return i, err
}
const createIncidentStatus = `-- name: CreateIncidentStatus :one
INSERT INTO incident_statuses (org_id, name, color) VALUES ($1, $2, $3) RETURNING id, org_id, name, color, created_at
`
type CreateIncidentStatusParams struct {
OrgID uuid.UUID
Name string
Color string
}
func (q *Queries) CreateIncidentStatus(ctx context.Context, arg CreateIncidentStatusParams) (IncidentStatus, error) {
row := q.db.QueryRow(ctx, createIncidentStatus, arg.OrgID, arg.Name, arg.Color)
var i IncidentStatus
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Name,
&i.Color,
&i.CreatedAt,
)
return i, err
}
const deleteChannel = `-- name: DeleteChannel :execrows
DELETE FROM notification_channels WHERE id = $1
`
@@ -94,6 +158,35 @@ func (q *Queries) DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error
return result.RowsAffected(), nil
}
const deleteIncidentStatus = `-- name: DeleteIncidentStatus :execrows
DELETE FROM incident_statuses WHERE id = $1
`
func (q *Queries) DeleteIncidentStatus(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deleteIncidentStatus, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteIncidentUpdate = `-- name: DeleteIncidentUpdate :execrows
DELETE FROM incident_updates WHERE id = $1 AND incident_id = $2
`
type DeleteIncidentUpdateParams struct {
ID uuid.UUID
IncidentID uuid.UUID
}
func (q *Queries) DeleteIncidentUpdate(ctx context.Context, arg DeleteIncidentUpdateParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteIncidentUpdate, arg.ID, arg.IncidentID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const enqueueNotification = `-- name: EnqueueNotification :exec
INSERT INTO notifications (org_id, channel_id, incident_id, event)
VALUES ($1, $2, $3, $4)
@@ -137,8 +230,47 @@ func (q *Queries) GetChannel(ctx context.Context, id uuid.UUID) (NotificationCha
return i, err
}
const getIncident = `-- name: GetIncident :one
SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, i.title, i.status, i.status_id, m.name AS monitor_name, m.group_id AS monitor_group_id
FROM incidents i JOIN monitors m ON m.id = i.monitor_id
WHERE i.id = $1
`
type GetIncidentRow struct {
ID uuid.UUID
OrgID uuid.UUID
MonitorID uuid.UUID
StartedAt time.Time
ResolvedAt *time.Time
Cause []byte
Title string
Status *string
StatusID *uuid.UUID
MonitorName string
MonitorGroupID *uuid.UUID
}
func (q *Queries) GetIncident(ctx context.Context, id uuid.UUID) (GetIncidentRow, error) {
row := q.db.QueryRow(ctx, getIncident, id)
var i GetIncidentRow
err := row.Scan(
&i.ID,
&i.OrgID,
&i.MonitorID,
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
&i.MonitorName,
&i.MonitorGroupID,
)
return i, err
}
const incidentsForMonitors = `-- name: IncidentsForMonitors :many
SELECT id, org_id, monitor_id, started_at, resolved_at, cause FROM incidents
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents
WHERE monitor_id = ANY ($1::uuid[]) AND (resolved_at IS NULL OR resolved_at > $2)
ORDER BY started_at DESC
LIMIT 50
@@ -165,6 +297,9 @@ func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMoni
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
); err != nil {
return nil, err
}
@@ -241,8 +376,90 @@ func (q *Queries) ListChannels(ctx context.Context) ([]NotificationChannel, erro
return items, nil
}
const listIncidentStatuses = `-- name: ListIncidentStatuses :many
SELECT id, org_id, name, color, created_at FROM incident_statuses ORDER BY name
`
func (q *Queries) ListIncidentStatuses(ctx context.Context) ([]IncidentStatus, error) {
rows, err := q.db.Query(ctx, listIncidentStatuses)
if err != nil {
return nil, err
}
defer rows.Close()
items := []IncidentStatus{}
for rows.Next() {
var i IncidentStatus
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Name,
&i.Color,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listIncidentUpdates = `-- name: ListIncidentUpdates :many
SELECT u.id, u.org_id, u.incident_id, u.status, u.message, u.public, u.author_id, u.created_at, u.status_id, coalesce(nullif(usr.display_name, ''), usr.email::text, '')::text AS author_name
FROM incident_updates u LEFT JOIN users usr ON usr.id = u.author_id
WHERE u.incident_id = $1
ORDER BY u.created_at DESC, u.id DESC
`
type ListIncidentUpdatesRow struct {
ID uuid.UUID
OrgID uuid.UUID
IncidentID uuid.UUID
Status string
Message string
Public bool
AuthorID *uuid.UUID
CreatedAt time.Time
StatusID *uuid.UUID
AuthorName string
}
// Newest first, with the author's name.
func (q *Queries) ListIncidentUpdates(ctx context.Context, incidentID uuid.UUID) ([]ListIncidentUpdatesRow, error) {
rows, err := q.db.Query(ctx, listIncidentUpdates, incidentID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListIncidentUpdatesRow{}
for rows.Next() {
var i ListIncidentUpdatesRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.IncidentID,
&i.Status,
&i.Message,
&i.Public,
&i.AuthorID,
&i.CreatedAt,
&i.StatusID,
&i.AuthorName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listIncidents = `-- name: ListIncidents :many
SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, m.name AS monitor_name
SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, i.title, i.status, i.status_id, m.name AS monitor_name
FROM incidents i
JOIN monitors m ON m.id = i.monitor_id
WHERE ($1::uuid IS NULL OR i.monitor_id = $1)
@@ -271,6 +488,9 @@ type ListIncidentsRow struct {
StartedAt time.Time
ResolvedAt *time.Time
Cause []byte
Title string
Status *string
StatusID *uuid.UUID
MonitorName string
}
@@ -299,6 +519,9 @@ func (q *Queries) ListIncidents(ctx context.Context, arg ListIncidentsParams) ([
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
&i.MonitorName,
); err != nil {
return nil, err
@@ -416,7 +639,7 @@ const openIncident = `-- name: OpenIncident :one
INSERT INTO incidents (org_id, monitor_id, started_at, cause)
VALUES ($1, $2, $3, $4)
ON CONFLICT (monitor_id) WHERE resolved_at IS NULL DO NOTHING
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id
`
type OpenIncidentParams struct {
@@ -441,12 +664,15 @@ func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Inc
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
)
return i, err
}
const openIncidents = `-- name: OpenIncidents :many
SELECT id, org_id, monitor_id, started_at, resolved_at, cause FROM incidents WHERE resolved_at IS NULL
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE resolved_at IS NULL
`
func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) {
@@ -465,6 +691,9 @@ func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) {
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
); err != nil {
return nil, err
}
@@ -476,10 +705,64 @@ func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) {
return items, nil
}
const publicIncidentUpdates = `-- name: PublicIncidentUpdates :many
SELECT incident_id, status, status_id, message, created_at FROM incident_updates
WHERE incident_id = ANY($1::uuid[]) AND public
ORDER BY created_at DESC, id DESC
`
type PublicIncidentUpdatesRow struct {
IncidentID uuid.UUID
Status string
StatusID *uuid.UUID
Message string
CreatedAt time.Time
}
// The public updates of incidents shown on a status page, newest first.
func (q *Queries) PublicIncidentUpdates(ctx context.Context, ids []uuid.UUID) ([]PublicIncidentUpdatesRow, error) {
rows, err := q.db.Query(ctx, publicIncidentUpdates, ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PublicIncidentUpdatesRow{}
for rows.Next() {
var i PublicIncidentUpdatesRow
if err := rows.Scan(
&i.IncidentID,
&i.Status,
&i.StatusID,
&i.Message,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const refreshIncidentStatus = `-- name: RefreshIncidentStatus :exec
UPDATE incidents SET (status, status_id) = (
SELECT u.status, u.status_id FROM incident_updates u WHERE u.incident_id = incidents.id
ORDER BY u.created_at DESC, u.id DESC LIMIT 1
) WHERE incidents.id = $1
`
// The incident shows the status of its latest update.
func (q *Queries) RefreshIncidentStatus(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, refreshIncidentStatus, id)
return err
}
const resolveIncident = `-- name: ResolveIncident :one
UPDATE incidents SET resolved_at = $1
WHERE monitor_id = $2 AND resolved_at IS NULL
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id
`
type ResolveIncidentParams struct {
@@ -497,10 +780,30 @@ func (q *Queries) ResolveIncident(ctx context.Context, arg ResolveIncidentParams
&i.StartedAt,
&i.ResolvedAt,
&i.Cause,
&i.Title,
&i.Status,
&i.StatusID,
)
return i, err
}
const setIncidentTitle = `-- name: SetIncidentTitle :execrows
UPDATE incidents SET title = $1 WHERE id = $2
`
type SetIncidentTitleParams struct {
Title string
ID uuid.UUID
}
func (q *Queries) SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error) {
result, err := q.db.Exec(ctx, setIncidentTitle, arg.Title, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateChannel = `-- name: UpdateChannel :one
UPDATE notification_channels SET name = $2, config = $3, enabled = $4, updated_at = now()
WHERE id = $1
@@ -534,3 +837,21 @@ func (q *Queries) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (N
)
return i, err
}
const updateIncidentStatus = `-- name: UpdateIncidentStatus :execrows
UPDATE incident_statuses SET name = $1, color = $2 WHERE id = $3
`
type UpdateIncidentStatusParams struct {
Name string
Color string
ID uuid.UUID
}
func (q *Queries) UpdateIncidentStatus(ctx context.Context, arg UpdateIncidentStatusParams) (int64, error) {
result, err := q.db.Exec(ctx, updateIncidentStatus, arg.Name, arg.Color, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+120 -6
View File
@@ -7,10 +7,56 @@ package store
import (
"context"
"time"
"github.com/google/uuid"
)
const acceptLegal = `-- name: AcceptLegal :exec
INSERT INTO legal_acceptances (user_id, kind, version) VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING
`
type AcceptLegalParams struct {
UserID uuid.UUID
Kind string
Version int64
}
func (q *Queries) AcceptLegal(ctx context.Context, arg AcceptLegalParams) error {
_, err := q.db.Exec(ctx, acceptLegal, arg.UserID, arg.Kind, arg.Version)
return err
}
const acceptedLegalVersions = `-- name: AcceptedLegalVersions :many
SELECT kind, version FROM legal_acceptances WHERE user_id = $1
`
type AcceptedLegalVersionsRow struct {
Kind string
Version int64
}
func (q *Queries) AcceptedLegalVersions(ctx context.Context, userID uuid.UUID) ([]AcceptedLegalVersionsRow, error) {
rows, err := q.db.Query(ctx, acceptedLegalVersions, userID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []AcceptedLegalVersionsRow{}
for rows.Next() {
var i AcceptedLegalVersionsRow
if err := rows.Scan(&i.Kind, &i.Version); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const deleteLegalDocument = `-- name: DeleteLegalDocument :exec
DELETE FROM legal_documents WHERE org_id IS NOT DISTINCT FROM $1 AND kind = $2
`
@@ -25,8 +71,38 @@ func (q *Queries) DeleteLegalDocument(ctx context.Context, arg DeleteLegalDocume
return err
}
const legalAcceptances = `-- name: LegalAcceptances :many
SELECT kind, version, accepted_at FROM legal_acceptances WHERE user_id = $1 ORDER BY accepted_at, kind
`
type LegalAcceptancesRow struct {
Kind string
Version int64
AcceptedAt time.Time
}
func (q *Queries) LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error) {
rows, err := q.db.Query(ctx, legalAcceptances, userID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LegalAcceptancesRow{}
for rows.Next() {
var i LegalAcceptancesRow
if err := rows.Scan(&i.Kind, &i.Version, &i.AcceptedAt); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const legalDocuments = `-- name: LegalDocuments :many
SELECT org_id, kind, url, markdown, updated_at FROM legal_documents
SELECT org_id, kind, url, markdown, updated_at, version FROM legal_documents
WHERE org_id IS NULL OR org_id = $1
ORDER BY org_id NULLS LAST, kind
`
@@ -47,6 +123,7 @@ func (q *Queries) LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]Legal
&i.Url,
&i.Markdown,
&i.UpdatedAt,
&i.Version,
); err != nil {
return nil, err
}
@@ -58,25 +135,62 @@ func (q *Queries) LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]Legal
return items, nil
}
const requiredLegalVersions = `-- name: RequiredLegalVersions :many
SELECT kind, version FROM legal_documents
WHERE org_id IS NULL AND kind IN ('privacy', 'terms') AND (url <> '' OR markdown <> '')
ORDER BY kind
`
type RequiredLegalVersionsRow struct {
Kind string
Version int64
}
// The platform documents accounts have to accept, in their current version.
func (q *Queries) RequiredLegalVersions(ctx context.Context) ([]RequiredLegalVersionsRow, error) {
rows, err := q.db.Query(ctx, requiredLegalVersions)
if err != nil {
return nil, err
}
defer rows.Close()
items := []RequiredLegalVersionsRow{}
for rows.Next() {
var i RequiredLegalVersionsRow
if err := rows.Scan(&i.Kind, &i.Version); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const upsertLegalDocument = `-- name: UpsertLegalDocument :exec
INSERT INTO legal_documents (org_id, kind, url, markdown)
VALUES ($1, $2, $3, $4)
ON CONFLICT (org_id, kind) DO UPDATE SET url = EXCLUDED.url, markdown = EXCLUDED.markdown, updated_at = now()
ON CONFLICT (org_id, kind) DO UPDATE SET url = EXCLUDED.url, markdown = EXCLUDED.markdown, updated_at = now(),
version = CASE WHEN $5::boolean THEN nextval('legal_document_versions') ELSE legal_documents.version END
`
type UpsertLegalDocumentParams struct {
OrgID *uuid.UUID
Kind string
Url string
Markdown string
OrgID *uuid.UUID
Kind string
Url string
Markdown string
NewVersion bool
}
// A new version starts when the document is created or when the edit asks
// everyone to accept it again.
func (q *Queries) UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error {
_, err := q.db.Exec(ctx, upsertLegalDocument,
arg.OrgID,
arg.Kind,
arg.Url,
arg.Markdown,
arg.NewVersion,
)
return err
}
+40
View File
@@ -27,6 +27,17 @@ func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) er
return err
}
const countOwners = `-- name: CountOwners :one
SELECT count(*) FROM memberships WHERE org_id = $1 AND is_owner
`
func (q *Queries) CountOwners(ctx context.Context, orgID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countOwners, orgID)
var count int64
err := row.Scan(&count)
return count, err
}
const getMembership = `-- name: GetMembership :one
SELECT org_id, user_id, is_owner, created_at FROM memberships WHERE org_id = $1 AND user_id = $2
`
@@ -196,6 +207,17 @@ func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUse
return items, nil
}
const lockOrgOwners = `-- name: LockOrgOwners :exec
SELECT pg_advisory_xact_lock(hashtextextended('owners:' || $1::uuid::text, 0))
`
// Serializes ownership changes of an organization, so two owners stepping
// down at once cannot leave it without one.
func (q *Queries) LockOrgOwners(ctx context.Context, orgID uuid.UUID) error {
_, err := q.db.Exec(ctx, lockOrgOwners, orgID)
return err
}
const removeMembership = `-- name: RemoveMembership :execrows
DELETE FROM memberships WHERE org_id = $1 AND user_id = $2 AND NOT is_owner
`
@@ -212,3 +234,21 @@ func (q *Queries) RemoveMembership(ctx context.Context, arg RemoveMembershipPara
}
return result.RowsAffected(), nil
}
const setOwner = `-- name: SetOwner :execrows
UPDATE memberships SET is_owner = $1 WHERE org_id = $2 AND user_id = $3
`
type SetOwnerParams struct {
Owner bool
OrgID uuid.UUID
UserID uuid.UUID
}
func (q *Queries) SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error) {
result, err := q.db.Exec(ctx, setOwner, arg.Owner, arg.OrgID, arg.UserID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+53
View File
@@ -160,6 +160,29 @@ type Incident struct {
StartedAt time.Time
ResolvedAt *time.Time
Cause []byte
Title string
Status *string
StatusID *uuid.UUID
}
type IncidentStatus struct {
ID uuid.UUID
OrgID uuid.UUID
Name string
Color string
CreatedAt time.Time
}
type IncidentUpdate struct {
ID uuid.UUID
OrgID uuid.UUID
IncidentID uuid.UUID
Status string
Message string
Public bool
AuthorID *uuid.UUID
CreatedAt time.Time
StatusID *uuid.UUID
}
type Invitation struct {
@@ -174,12 +197,20 @@ type Invitation struct {
CreatedAt time.Time
}
type LegalAcceptance struct {
UserID uuid.UUID
Kind string
Version int64
AcceptedAt time.Time
}
type LegalDocument struct {
OrgID *uuid.UUID
Kind string
Url string
Markdown string
UpdatedAt time.Time
Version int64
}
type MaintenanceTarget struct {
@@ -292,6 +323,28 @@ type Org struct {
LimitOwnRegionsCount *bool
}
type PlatformIdentity struct {
ProviderID uuid.UUID
Subject string
UserID uuid.UUID
Email *string
CreatedAt time.Time
LastLoginAt time.Time
}
type PlatformIdentityProvider struct {
ID uuid.UUID
Kind string
Name string
Issuer string
ClientID string
ClientSecret []byte
AllowSignup bool
Enabled bool
CreatedAt time.Time
UpdatedAt time.Time
}
type PlatformSetting struct {
Key string
Value []byte
+318
View File
@@ -0,0 +1,318 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: platform_sso.sql
package store
import (
"context"
"time"
"github.com/google/uuid"
)
const countUserSignIns = `-- name: CountUserSignIns :one
SELECT (password_hash IS NOT NULL)::integer
+ (SELECT count(*) FROM user_identities ui WHERE ui.user_id = users.id)::integer
+ (SELECT count(*) FROM platform_identities pi WHERE pi.user_id = users.id)::integer AS ways
FROM users WHERE id = $1
`
// Ways the account can sign in besides platform identities.
func (q *Queries) CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error) {
row := q.db.QueryRow(ctx, countUserSignIns, id)
var ways int32
err := row.Scan(&ways)
return ways, err
}
const createPlatformIDP = `-- name: CreatePlatformIDP :one
INSERT INTO platform_identity_providers (id, kind, name, issuer, client_id, client_secret, allow_signup, enabled)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at
`
type CreatePlatformIDPParams struct {
ID uuid.UUID
Kind string
Name string
Issuer string
ClientID string
ClientSecret []byte
AllowSignup bool
Enabled bool
}
func (q *Queries) CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error) {
row := q.db.QueryRow(ctx, createPlatformIDP,
arg.ID,
arg.Kind,
arg.Name,
arg.Issuer,
arg.ClientID,
arg.ClientSecret,
arg.AllowSignup,
arg.Enabled,
)
var i PlatformIdentityProvider
err := row.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.Issuer,
&i.ClientID,
&i.ClientSecret,
&i.AllowSignup,
&i.Enabled,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const createPlatformIdentity = `-- name: CreatePlatformIdentity :exec
INSERT INTO platform_identities (provider_id, subject, user_id, email) VALUES ($1, $2, $3, $4)
`
type CreatePlatformIdentityParams struct {
ProviderID uuid.UUID
Subject string
UserID uuid.UUID
Email *string
}
func (q *Queries) CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error {
_, err := q.db.Exec(ctx, createPlatformIdentity,
arg.ProviderID,
arg.Subject,
arg.UserID,
arg.Email,
)
return err
}
const deletePlatformIDP = `-- name: DeletePlatformIDP :execrows
DELETE FROM platform_identity_providers WHERE id = $1
`
func (q *Queries) DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deletePlatformIDP, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deletePlatformIdentity = `-- name: DeletePlatformIdentity :execrows
DELETE FROM platform_identities WHERE user_id = $1 AND provider_id = $2
`
type DeletePlatformIdentityParams struct {
UserID uuid.UUID
ProviderID uuid.UUID
}
func (q *Queries) DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error) {
result, err := q.db.Exec(ctx, deletePlatformIdentity, arg.UserID, arg.ProviderID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getPlatformIDP = `-- name: GetPlatformIDP :one
SELECT id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at FROM platform_identity_providers WHERE id = $1
`
func (q *Queries) GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error) {
row := q.db.QueryRow(ctx, getPlatformIDP, id)
var i PlatformIdentityProvider
err := row.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.Issuer,
&i.ClientID,
&i.ClientSecret,
&i.AllowSignup,
&i.Enabled,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getPlatformIdentity = `-- name: GetPlatformIdentity :one
SELECT provider_id, subject, user_id, email, created_at, last_login_at FROM platform_identities WHERE provider_id = $1 AND subject = $2
`
type GetPlatformIdentityParams struct {
ProviderID uuid.UUID
Subject string
}
func (q *Queries) GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error) {
row := q.db.QueryRow(ctx, getPlatformIdentity, arg.ProviderID, arg.Subject)
var i PlatformIdentity
err := row.Scan(
&i.ProviderID,
&i.Subject,
&i.UserID,
&i.Email,
&i.CreatedAt,
&i.LastLoginAt,
)
return i, err
}
const listPlatformIDPs = `-- name: ListPlatformIDPs :many
SELECT id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at FROM platform_identity_providers ORDER BY name
`
func (q *Queries) ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error) {
rows, err := q.db.Query(ctx, listPlatformIDPs)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PlatformIdentityProvider{}
for rows.Next() {
var i PlatformIdentityProvider
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.Issuer,
&i.ClientID,
&i.ClientSecret,
&i.AllowSignup,
&i.Enabled,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUserPlatformIdentities = `-- name: ListUserPlatformIdentities :many
SELECT i.provider_id, i.email, i.created_at, p.name AS provider_name, p.kind
FROM platform_identities i JOIN platform_identity_providers p ON p.id = i.provider_id
WHERE i.user_id = $1
ORDER BY p.name
`
type ListUserPlatformIdentitiesRow struct {
ProviderID uuid.UUID
Email *string
CreatedAt time.Time
ProviderName string
Kind string
}
func (q *Queries) ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error) {
rows, err := q.db.Query(ctx, listUserPlatformIdentities, userID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListUserPlatformIdentitiesRow{}
for rows.Next() {
var i ListUserPlatformIdentitiesRow
if err := rows.Scan(
&i.ProviderID,
&i.Email,
&i.CreatedAt,
&i.ProviderName,
&i.Kind,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const soleSignInUsers = `-- name: SoleSignInUsers :one
SELECT count(*) FROM platform_identities pi JOIN users u ON u.id = pi.user_id
WHERE pi.provider_id = $1 AND u.password_hash IS NULL
AND NOT EXISTS (SELECT 1 FROM user_identities ui WHERE ui.user_id = u.id)
AND NOT EXISTS (SELECT 1 FROM platform_identities o WHERE o.user_id = u.id AND o.provider_id <> pi.provider_id)
`
// Accounts that can sign in only through this provider.
func (q *Queries) SoleSignInUsers(ctx context.Context, providerID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, soleSignInUsers, providerID)
var count int64
err := row.Scan(&count)
return count, err
}
const touchPlatformIdentity = `-- name: TouchPlatformIdentity :exec
UPDATE platform_identities SET last_login_at = now(), email = coalesce($3, email)
WHERE provider_id = $1 AND subject = $2
`
type TouchPlatformIdentityParams struct {
ProviderID uuid.UUID
Subject string
Email *string
}
func (q *Queries) TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error {
_, err := q.db.Exec(ctx, touchPlatformIdentity, arg.ProviderID, arg.Subject, arg.Email)
return err
}
const updatePlatformIDP = `-- name: UpdatePlatformIDP :one
UPDATE platform_identity_providers
SET name = $2, issuer = $3, client_id = $4, client_secret = coalesce($7, client_secret),
allow_signup = $5, enabled = $6, updated_at = now()
WHERE id = $1
RETURNING id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at
`
type UpdatePlatformIDPParams struct {
ID uuid.UUID
Name string
Issuer string
ClientID string
AllowSignup bool
Enabled bool
ClientSecret []byte
}
func (q *Queries) UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error) {
row := q.db.QueryRow(ctx, updatePlatformIDP,
arg.ID,
arg.Name,
arg.Issuer,
arg.ClientID,
arg.AllowSignup,
arg.Enabled,
arg.ClientSecret,
)
var i PlatformIdentityProvider
err := row.Scan(
&i.ID,
&i.Kind,
&i.Name,
&i.Issuer,
&i.ClientID,
&i.ClientSecret,
&i.AllowSignup,
&i.Enabled,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
+42 -1
View File
@@ -13,7 +13,10 @@ import (
type Querier interface {
APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
AcceptLegal(ctx context.Context, arg AcceptLegalParams) error
AcceptedLegalVersions(ctx context.Context, userID uuid.UUID) ([]AcceptedLegalVersionsRow, error)
AddAlertGroupChannel(ctx context.Context, arg AddAlertGroupChannelParams) (int64, error)
AddIncidentUpdate(ctx context.Context, arg AddIncidentUpdateParams) (IncidentUpdate, error)
AddMaintenanceTarget(ctx context.Context, arg AddMaintenanceTargetParams) error
AddMembership(ctx context.Context, arg AddMembershipParams) error
AddMonitorAlertGroup(ctx context.Context, arg AddMonitorAlertGroupParams) (int64, error)
@@ -48,9 +51,12 @@ type Querier interface {
ClearStatusPageMonitors(ctx context.Context, pageID uuid.UUID) error
CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, error)
CountOwnedOrgs(ctx context.Context, userID uuid.UUID) (int64, error)
CountOwners(ctx context.Context, orgID uuid.UUID) (int64, error)
CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error)
CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error)
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
// Ways the account can sign in besides platform identities.
CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error)
CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error)
CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error)
CreateAlertGroup(ctx context.Context, arg CreateAlertGroupParams) (AlertGroup, error)
@@ -59,10 +65,13 @@ type Querier interface {
CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error)
CreateGroup(ctx context.Context, arg CreateGroupParams) (MonitorGroup, error)
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
CreateIncidentStatus(ctx context.Context, arg CreateIncidentStatusParams) (IncidentStatus, error)
CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error)
CreateMaintenance(ctx context.Context, arg CreateMaintenanceParams) (MaintenanceWindow, error)
CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error)
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error)
CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error
CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error)
CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error)
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
@@ -81,6 +90,8 @@ type Querier interface {
DeleteAssignmentsForResource(ctx context.Context, arg DeleteAssignmentsForResourceParams) error
DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error)
DeleteGroup(ctx context.Context, id uuid.UUID) (int64, error)
DeleteIncidentStatus(ctx context.Context, id uuid.UUID) (int64, error)
DeleteIncidentUpdate(ctx context.Context, arg DeleteIncidentUpdateParams) (int64, error)
DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error)
DeleteInvitationsForEmail(ctx context.Context, email string) error
DeleteLegalDocument(ctx context.Context, arg DeleteLegalDocumentParams) error
@@ -90,6 +101,8 @@ type Querier interface {
DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
DeleteOrgStorage(ctx context.Context, orgID uuid.UUID) error
DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error)
DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error)
DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error
DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error)
DeleteRole(ctx context.Context, id uuid.UUID) (int64, error)
@@ -132,6 +145,7 @@ type Querier interface {
GetEvidence(ctx context.Context, arg GetEvidenceParams) (CheckEvidence, error)
GetGroup(ctx context.Context, id uuid.UUID) (MonitorGroup, error)
GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error)
GetIncident(ctx context.Context, id uuid.UUID) (GetIncidentRow, error)
GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error)
GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error)
GetMaintenance(ctx context.Context, id uuid.UUID) (MaintenanceWindow, error)
@@ -139,6 +153,8 @@ type Querier interface {
GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
GetOrgBySlug(ctx context.Context, slug string) (Org, error)
GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error)
GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error)
GetPlatformSetting(ctx context.Context, key string) ([]byte, error)
GetRegion(ctx context.Context, id uuid.UUID) (Region, error)
GetRole(ctx context.Context, id uuid.UUID) (Role, error)
@@ -171,6 +187,7 @@ type Querier interface {
// Newest result per monitor and region in the org.
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error)
// The organization's documents and the platform's, organization first.
LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error)
ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error)
@@ -190,6 +207,9 @@ type Querier interface {
// Newest first, a page from a keyset cursor (see paging.go).
ListEvidence(ctx context.Context, arg ListEvidenceParams) ([]ListEvidenceRow, error)
ListGroups(ctx context.Context) ([]MonitorGroup, error)
ListIncidentStatuses(ctx context.Context) ([]IncidentStatus, error)
// Newest first, with the author's name.
ListIncidentUpdates(ctx context.Context, incidentID uuid.UUID) ([]ListIncidentUpdatesRow, error)
// Newest first, a page from a keyset cursor (see paging.go); optionally of
// one monitor.
ListIncidents(ctx context.Context, arg ListIncidentsParams) ([]ListIncidentsRow, error)
@@ -205,6 +225,7 @@ type Querier interface {
ListOrgMembersPage(ctx context.Context, arg ListOrgMembersPageParams) ([]ListOrgMembersPageRow, error)
ListOrgs(ctx context.Context) ([]Org, error)
ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error)
ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error)
ListPlatformRegions(ctx context.Context) ([]Region, error)
// A monitor's results newest first, a page from a keyset cursor (see
// paging.go) whose string key is region and checker.
@@ -215,9 +236,13 @@ type Querier interface {
ListStatusPages(ctx context.Context) ([]StatusPage, error)
ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error)
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error)
// Row-level security limits this to platform regions and the scope's org;
// the org's own regions come first.
ListVisibleRegions(ctx context.Context) ([]Region, error)
// Serializes ownership changes of an organization, so two owners stepping
// down at once cannot leave it without one.
LockOrgOwners(ctx context.Context, orgID uuid.UUID) error
// Serializes creations counted against org's limits until the transaction
// ends.
LockOrgUsage(ctx context.Context, orgID uuid.UUID) error
@@ -250,10 +275,13 @@ type Querier interface {
OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error)
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
// Organizations user owns, with their member count.
// Organizations user owns, with their member and owner counts.
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
// The public updates of incidents shown on a status page, newest first.
PublicIncidentUpdates(ctx context.Context, ids []uuid.UUID) ([]PublicIncidentUpdatesRow, error)
// Resolved and long silent alerts are history the monitors' results keep.
PurgeAlertmanagerAlerts(ctx context.Context, updatedAt time.Time) (int64, error)
PurgeAuditEvents(ctx context.Context, argTime time.Time) (int64, error)
@@ -273,6 +301,8 @@ type Querier interface {
RangeBucketsDaily(ctx context.Context, arg RangeBucketsDailyParams) ([]RangeBucketsDailyRow, error)
// The hourly aggregate rebucketed by width, for ranges of days.
RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourlyParams) ([]RangeBucketsHourlyRow, error)
// The incident shows the status of its latest update.
RefreshIncidentStatus(ctx context.Context, id uuid.UUID) error
// One monitor's raw results per region.
RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error)
RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error)
@@ -283,6 +313,8 @@ type Querier interface {
ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error
ReparentStatusPageGroupChildren(ctx context.Context, arg ReparentStatusPageGroupChildrenParams) error
ReparentStatusPageGroupMonitors(ctx context.Context, arg ReparentStatusPageGroupMonitorsParams) error
// The platform documents accounts have to accept, in their current version.
RequiredLegalVersions(ctx context.Context) ([]RequiredLegalVersionsRow, error)
ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error)
// Heartbeats of an organization wait afresh after its suspension, during
// which pings were refused.
@@ -292,8 +324,10 @@ type Querier interface {
ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error)
ScrubAuditEmail(ctx context.Context, email string) error
SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error)
SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error)
SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error
SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (SetOrgLimitsRow, error)
SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
// Changing the domain drops a previous verification.
@@ -304,6 +338,8 @@ type Querier interface {
SetUserOrgLimit(ctx context.Context, arg SetUserOrgLimitParams) (SetUserOrgLimitRow, error)
// Other instances of the same agent seen in the last day.
SiblingInstances(ctx context.Context, agentID uuid.UUID) ([]SiblingInstancesRow, error)
// Accounts that can sign in only through this provider.
SoleSignInUsers(ctx context.Context, providerID uuid.UUID) (int64, error)
StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error)
// Deletes key and, as certmagic expects, everything below it.
StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error)
@@ -318,17 +354,22 @@ type Querier interface {
// Writes at most once a minute per instance; agents poll far more often.
TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error
UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error)
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
UpdateIncidentStatus(ctx context.Context, arg UpdateIncidentStatusParams) (int64, error)
UpdateMaintenance(ctx context.Context, arg UpdateMaintenanceParams) (MaintenanceWindow, error)
UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error)
UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error)
UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error)
UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error)
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error)
UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error
// A new version starts when the document is created or when the edit asks
// everyone to accept it again.
UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error
// Uptime per monitor from the hourly aggregate, including the not yet
// materialized most recent hours (real-time aggregation).
+8 -3
View File
@@ -1,7 +1,8 @@
-- name: OwnedOrgs :many
-- Organizations user owns, with their member count.
-- Organizations user owns, with their member and owner counts.
SELECT o.id, o.slug, o.name,
(SELECT count(*) FROM memberships m2 WHERE m2.org_id = o.id)::bigint AS members
(SELECT count(*) FROM memberships m2 WHERE m2.org_id = o.id)::bigint AS members,
(SELECT count(*) FROM memberships m3 WHERE m3.org_id = o.id AND m3.is_owner)::bigint AS owners
FROM orgs o JOIN memberships m ON m.org_id = o.id
WHERE m.user_id = $1 AND m.is_owner
ORDER BY o.name;
@@ -65,10 +66,14 @@ FROM role_assignments ra JOIN roles r ON r.id = ra.role_id
WHERE ra.org_id = $1;
-- name: OrgIncidentsExport :many
SELECT i.id, i.monitor_id, m.name AS monitor, i.started_at, i.resolved_at, i.cause
SELECT i.id, i.monitor_id, m.name AS monitor, i.started_at, i.resolved_at, i.cause, i.title, i.status
FROM incidents i LEFT JOIN monitors m ON m.id = i.monitor_id
WHERE i.org_id = $1 ORDER BY i.started_at;
-- name: OrgIncidentUpdatesExport :many
SELECT incident_id, status, message, public, created_at FROM incident_updates
WHERE org_id = $1 ORDER BY created_at;
-- name: OrgAuditExport :many
SELECT e.time, e.action, coalesce(u.email::text, '')::text AS actor, e.target_id, e.details, e.status,
coalesce(host(e.ip), '')::text AS ip
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more