Compare commits

...
Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 d2b669ae71 feat(deploy): optional bundled Redis in the Helm chart
ci / lint (push) Skipped
ci / build (push) Skipped
ci / test (push) Skipped
ci / image (push) Skipped
ci / image (pull_request) Waiting for needed jobs
ci / lint (pull_request) Successful in 10m22s
ci / test (pull_request) Successful in 15m16s
ci / build (pull_request) In progress
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 / build (push) Skipped
ci / image (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
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 / image (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
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 / build (push) Successful in 22m27s
ci / lint (push) Successful in 7m27s
ci / test (push) Failing after 14m14s
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 / image (push) Canceled after 0s
ci / lint (push) Canceled after 16s
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 / build (push) Skipped
ci / image (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
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 / image (push) Successful in 7m26s
ci / test (push) Successful in 9m17s
ci / build (push) Successful in 12m39s
ci / lint (push) Successful in 13m16s
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 / image (push) Successful in 6m50s
ci / build (push) Successful in 8m38s
ci / test (push) Successful in 9m15s
ci / lint (push) Successful in 13m18s
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 / image (push) Successful in 4m6s
ci / lint (push) Failing after 15m25s
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 / image (push) Canceled after 0s
ci / test (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 / image (push) Successful in 3m14s
ci / build (push) Successful in 11m43s
ci / test (push) Successful in 14m21s
ci / lint (push) Successful in 9m59s
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
83 changed files with 8478 additions and 790 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
+55 -3
View File
@@ -17,7 +17,7 @@ It is built for teams and hosting providers: organizations with members, roles a
- **Alerting:** incidents with webhooks (signed), email and over 100 services: chat and messengers (Slack, Discord, Microsoft Teams, Telegram, Matrix, WhatsApp gateways, Nostr, …), push (ntfy, Gotify, Pushover, …), SMS and calls (Twilio, Plivo, …), email APIs (SendGrid, Microsoft 365, …) and incident management (PagerDuty, Opsgenie, Grafana OnCall, Jira Service Management, …), plus Apprise; customers bring their own credentials. Confirmations, maintenance windows (one-off or recurring).
- **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body).
- **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages.
- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, enforced 2FA, audit log.
- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, sign-up and sign-in with providers such as Google, Microsoft or GitHub, enforced 2FA, audit log.
- **Privacy:** GDPR data export (JSON, PDF) and deletion, configurable retention, no telemetry.
- **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation.
@@ -67,7 +67,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 +94,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 +123,22 @@ 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.
### 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 +208,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
+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"
+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 {
+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) {
+12
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,
@@ -260,6 +262,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.",
+4
View File
@@ -96,6 +96,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",
+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)
+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)
}
+49 -9
View File
@@ -56,6 +56,7 @@ var flashErrors = map[ssoError]bool{
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
"sso_email_unverified": true, "signup_limit": true,
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
}
@@ -88,25 +89,41 @@ 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")))
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email))
}
func (s *Server) signupSentPage(c *gin.Context) {
@@ -259,7 +276,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 {
@@ -551,7 +590,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 +628,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 +646,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
}
+574
View File
@@ -0,0 +1,574 @@
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
}
if user.DisabledAt != nil {
s.ssoAbort(c, uuid.Nil, "account_suspended")
return
}
// 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")
}
}
+7
View File
@@ -100,6 +100,7 @@ func (s *Server) Mount(r gin.IRouter) {
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit())
r.GET("/api/openapi.json", s.openAPIJSON)
r.GET("/install.sh", s.installScript)
g.GET("/api/docs", s.apiDocsPage)
v1 := g.Group("/api/v1")
@@ -118,6 +119,7 @@ func (s *Server) Mount(r gin.IRouter) {
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 +177,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)
@@ -252,6 +258,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)
+7
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 {
+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.
+39
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.",
@@ -52,6 +62,8 @@
"app.network_error": "Verbindung fehlgeschlagen.",
"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",
@@ -98,6 +110,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 +164,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.",
@@ -498,6 +516,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 +563,7 @@
"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_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.",
@@ -576,6 +596,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.",
@@ -751,6 +772,20 @@
"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",
"incidents.all": "Alle Vorfälle",
"incidents.all_of_monitor": "Alle Vorfälle dieses Monitors",
"incidents.none": "Bisher keine Incidents.",
@@ -1184,6 +1219,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"
+39
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.",
@@ -52,6 +62,8 @@
"app.network_error": "Connection failed.",
"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",
@@ -98,6 +110,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 +164,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.",
@@ -498,6 +516,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 +563,7 @@
"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_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.",
@@ -576,6 +596,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.",
@@ -751,6 +772,20 @@
"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",
"incidents.all": "All incidents",
"incidents.all_of_monitor": "All incidents of this monitor",
"incidents.none": "No incidents so far.",
@@ -1184,6 +1219,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"
+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;
+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) {
+3
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)
+22
View File
@@ -292,6 +292,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
}
+14
View File
@@ -51,6 +51,8 @@ type Querier interface {
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)
@@ -63,6 +65,8 @@ type Querier interface {
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)
@@ -90,6 +94,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)
@@ -139,6 +145,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)
@@ -205,6 +213,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,6 +224,7 @@ 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)
@@ -304,6 +314,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,12 +330,14 @@ 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)
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)
+53
View File
@@ -0,0 +1,53 @@
-- 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 *;
-- name: UpdatePlatformIDP :one
UPDATE platform_identity_providers
SET name = $2, issuer = $3, client_id = $4, client_secret = coalesce(sqlc.narg(client_secret), client_secret),
allow_signup = $5, enabled = $6, updated_at = now()
WHERE id = $1
RETURNING *;
-- name: GetPlatformIDP :one
SELECT * FROM platform_identity_providers WHERE id = $1;
-- name: ListPlatformIDPs :many
SELECT * FROM platform_identity_providers ORDER BY name;
-- name: DeletePlatformIDP :execrows
DELETE FROM platform_identity_providers WHERE id = $1;
-- name: GetPlatformIdentity :one
SELECT * FROM platform_identities WHERE provider_id = $1 AND subject = $2;
-- name: CreatePlatformIdentity :exec
INSERT INTO platform_identities (provider_id, subject, user_id, email) VALUES ($1, $2, $3, $4);
-- name: TouchPlatformIdentity :exec
UPDATE platform_identities SET last_login_at = now(), email = coalesce(sqlc.narg(email), email)
WHERE provider_id = $1 AND subject = $2;
-- 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;
-- name: DeletePlatformIdentity :execrows
DELETE FROM platform_identities WHERE user_id = $1 AND provider_id = $2;
-- name: CountUserSignIns :one
-- Ways the account can sign in besides platform identities.
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;
-- name: SoleSignInUsers :one
-- Accounts that can sign in only through this provider.
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);
+27
View File
@@ -85,6 +85,32 @@
return out;
};
// fillInstall completes the install instructions of a new agent with its
// token and kind; the checkbox picks the self-updating image or not.
const fillInstall = (form, token) => {
const box = form.querySelector("[data-install]");
if (!box) return;
const kind = form.elements.kind?.value || "checker";
const auto = box.querySelector("[data-install-auto]");
const render = () => {
const channel = box.dataset.channel;
const values = {
token,
kind,
manual: auto.checked ? "" : " --manual-updates",
tag: auto.checked ? `${channel}-autoupdate` : channel,
};
for (const el of box.querySelectorAll("[data-install-fill]")) {
el.textContent = el.dataset.installFill.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
}
for (const el of box.querySelectorAll("[data-install-kind]")) {
el.hidden = el.dataset.installKind !== kind;
}
};
auto.onchange = render;
render();
};
document.addEventListener("submit", async (ev) => {
const form = ev.target.closest("form[data-api]");
if (!form) return;
@@ -117,6 +143,7 @@
input.value = shown;
out.hidden = false;
input.select();
fillInstall(form, shown);
if (form.dataset.refreshTarget) {
// Keep the one-time secret visible while refreshing the channel list
// and group choices. A successful create must not be submitted twice.
+43 -11
View File
@@ -5,15 +5,36 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
templ Login(p Page, signupAllowed bool, next string) {
// IDPButton is a platform identity provider to sign in with.
type IDPButton struct {
URL, Name, Kind string
}
templ idpButtons(providers []IDPButton, labelID string) {
if len(providers) > 0 {
<div class="mb-8 grid gap-2">
for _, pr := range providers {
<a href={ templ.SafeURL(pr.URL) } class="block border border-ink px-3 py-2 text-center text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, labelID, "Name", pr.Name) }</a>
}
</div>
<p class="mb-6 text-center text-xs uppercase tracking-wider text-muted">{ i18n.T(ctx, "auth.or") }</p>
}
}
// Login signs in; mfa starts at the second factor, after a provider
// confirmed who it is.
templ Login(p Page, signupAllowed bool, next string, providers []IDPButton, mfa bool) {
@authShell(p) {
if !mfa {
@idpButtons(providers, "auth.sso.continue_with")
}
<form data-api="/auth/login" data-next={ next }>
@formError()
<div data-step="password">
<div data-step="password" hidden?={ mfa }>
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true)
@field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
</div>
<div data-step="totp" hidden>
<div data-step="totp" hidden?={ !mfa }>
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "auth.login.totp_hint") }</p>
@field(i18n.T(ctx, "auth.field.code"), "code", "text", "one-time-code", false)
</div>
@@ -43,15 +64,26 @@ templ Login(p Page, signupAllowed bool, next string) {
}
}
templ Signup(p Page) {
// Signup offers the providers people may sign up through and, if email
// is set, the form for signing up with email and password.
templ Signup(p Page, providers []IDPButton, email bool) {
@authShell(p) {
<form data-api="/auth/signup" data-next="/">
@formError()
@field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false)
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true)
@field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true)
@submit(i18n.T(ctx, "auth.signup.submit"))
</form>
if email {
@idpButtons(providers, "auth.sso.signup_with")
<form data-api="/auth/signup" data-next="/">
@formError()
@field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false)
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true)
@field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true)
@submit(i18n.T(ctx, "auth.signup.submit"))
</form>
} else {
<div class="grid gap-2">
for _, pr := range providers {
<a href={ templ.SafeURL(pr.URL) } class="block border border-ink px-3 py-2 text-center text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "auth.sso.signup_with", "Name", pr.Name) }</a>
}
</div>
}
<p class="mt-8 text-sm text-muted"><a class="text-ink underline underline-offset-2" href="/login">{ i18n.T(ctx, "auth.signup.to_login") }</a></p>
}
}
+371 -209
View File
@@ -14,7 +14,12 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
func Login(p Page, signupAllowed bool, next string) templ.Component {
// IDPButton is a platform identity provider to sign in with.
type IDPButton struct {
URL, Name, Kind string
}
func idpButtons(providers []IDPButton, labelID string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
@@ -31,7 +36,85 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
if len(providers) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"mb-8 grid gap-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, pr := range providers {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(pr.URL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 17, Col: 35}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\" class=\"block border border-ink px-3 py-2 text-center text-sm hover:bg-ink hover:text-paper\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, labelID, "Name", pr.Name))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 17, Col: 169}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div><p class=\"mb-6 text-center text-xs uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.or"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 20, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
return nil
})
}
// Login signs in; mfa starts at the second factor, after a provider
// confirmed who it is.
func Login(p Page, signupAllowed bool, next string, providers []IDPButton, mfa bool) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var6 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -43,20 +126,26 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<form data-api=\"/auth/login\" data-next=\"")
if !mfa {
templ_7745c5c3_Err = idpButtons(providers, "auth.sso.continue_with").Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, " <form data-api=\"/auth/login\" data-next=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(next).Resolve(ctx)
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(next).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 10, Col: 47}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 31, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -64,7 +153,17 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<div data-step=\"password\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<div data-step=\"password\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if mfa {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, " hidden")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, ">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -76,20 +175,30 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</div><div data-step=\"totp\" hidden><p class=\"mb-4 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</div><div data-step=\"totp\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.totp_hint"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 17, Col: 76}
if !mfa {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, " hidden")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "><p class=\"mb-4 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</p>")
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.totp_hint"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 76}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -97,7 +206,7 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -105,110 +214,110 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</form><p class=\"mt-4 text-xs text-muted\"><a href=\"/verify/resend\" class=\"underline underline-offset-2 hover:text-ink\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 22, Col: 154}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</a></p><form action=\"/sso\" method=\"get\" class=\"mt-10 border-t border-rule pt-6\"><p class=\"mb-3 text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p><div class=\"flex gap-2\"><input class=\"min-w-0 flex-1 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\" name=\"org\" placeholder=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 29, Col: 58}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "\" aria-label=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 30, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\" autocomplete=\"organization\" required> <button type=\"submit\" class=\"border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</form><p class=\"mt-4 text-xs text-muted\"><a href=\"/verify/resend\" class=\"underline underline-offset-2 hover:text-ink\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.submit"))
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 34, Col: 134}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 43, Col: 154}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</button></div></form>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</a></p><form action=\"/sso\" method=\"get\" class=\"mt-10 border-t border-rule pt-6\"><p class=\"mb-3 text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 45, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</p><div class=\"flex gap-2\"><input class=\"min-w-0 flex-1 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\" name=\"org\" placeholder=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 50, Col: 58}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "\" aria-label=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 51, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "\" autocomplete=\"organization\" required> <button type=\"submit\" class=\"border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.submit"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 55, Col: 134}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</button></div></form>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if signupAllowed {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<p class=\"mt-8 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<p class=\"mt-8 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account"))
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 42}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 60, Col: 42}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, " <a class=\"text-ink underline underline-offset-2\" href=\"/signup\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, " <a class=\"text-ink underline underline-offset-2\" href=\"/signup\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup"))
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 40, Col: 105}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 61, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var6), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -216,7 +325,9 @@ func Login(p Page, signupAllowed bool, next string) templ.Component {
})
}
func Signup(p Page) templ.Component {
// Signup offers the providers people may sign up through and, if email
// is set, the form for signing up with email and password.
func Signup(p Page, providers []IDPButton, email bool) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
@@ -233,7 +344,7 @@ func Signup(p Page) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var13 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var17 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -245,50 +356,101 @@ func Signup(p Page) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<form data-api=\"/auth/signup\" data-next=\"/\">")
if email {
templ_7745c5c3_Err = idpButtons(providers, "auth.sso.signup_with").Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<form data-api=\"/auth/signup\" data-next=\"/\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.signup.submit")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</form>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<div class=\"grid gap-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, pr := range providers {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(pr.URL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 83, Col: 36}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" class=\"block border border-ink px-3 py-2 text-center text-sm hover:bg-ink hover:text-paper\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.signup_with", "Name", pr.Name))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 83, Col: 185}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, " <p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 87, Col: 137}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.signup.submit")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</form><p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 55, Col: 137}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var13), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var17), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -313,7 +475,7 @@ func SignupSent(p Page) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var16 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var22 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -325,52 +487,52 @@ func SignupSent(p Page) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<p class=\"text-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<p class=\"text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.sent"))
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.sent"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 61, Col: 54}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 93, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</p><p class=\"mt-4 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</p><p class=\"mt-4 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.sent_hint"))
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.sent_hint"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 62, Col: 75}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 94, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</p><p class=\"mt-8 text-sm\"><a href=\"/verify/resend\" class=\"underline underline-offset-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "</p><p class=\"mt-8 text-sm\"><a href=\"/verify/resend\" class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 63, Col: 128}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 95, Col: 128}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var16), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var22), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -396,7 +558,7 @@ func Verify(p Page, token string) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var21 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var27 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -409,38 +571,38 @@ func Verify(p Page, token string) templ.Component {
}
ctx = templ.InitializeContext(ctx)
if token == "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<p class=\"text-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<p class=\"text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "error.verification_expired"))
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "error.verification_expired"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 71, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 103, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</p><p class=\"mt-6 text-sm\"><a href=\"/verify/resend\" class=\"underline underline-offset-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "</p><p class=\"mt-6 text-sm\"><a href=\"/verify/resend\" class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 72, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 104, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<form data-api=\"/auth/verify\" data-next=\"/\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<form data-api=\"/auth/verify\" data-next=\"/\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -448,33 +610,33 @@ func Verify(p Page, token string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "<input type=\"hidden\" name=\"token\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "<input type=\"hidden\" name=\"token\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templruntime.NewAttributeExpression(token).Resolve(ctx)
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templruntime.NewAttributeExpression(token).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 76, Col: 51}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 108, Col: 51}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\"><p class=\"mb-6 text-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\"><p class=\"mb-6 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.intro"))
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 77, Col: 62}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 109, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -482,27 +644,27 @@ func Verify(p Page, token string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</form><p class=\"mt-6 text-xs text-muted\"><a href=\"/verify/resend\" class=\"underline underline-offset-2 hover:text-ink\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "</form><p class=\"mt-6 text-xs text-muted\"><a href=\"/verify/resend\" class=\"underline underline-offset-2 hover:text-ink\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 80, Col: 155}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 112, Col: 155}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var21), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var27), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -527,7 +689,7 @@ func ResendVerification(p Page) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var28 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var34 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -539,7 +701,7 @@ func ResendVerification(p Page) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<form data-api=\"/auth/verify/resend\" data-next=\"/signup/sent\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "<form data-api=\"/auth/verify/resend\" data-next=\"/signup/sent\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -547,20 +709,20 @@ func ResendVerification(p Page) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<p class=\"mb-4 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<p class=\"mb-4 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_intro"))
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.verify.resend_intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 89, Col: 79}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 121, Col: 79}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "</p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -572,26 +734,26 @@ func ResendVerification(p Page) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "</form><p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</form><p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 93, Col: 137}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 125, Col: 137}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</a></p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "</a></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var28), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var34), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -616,7 +778,7 @@ func newOrgForm() templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "<form data-api=\"/orgs\" data-next=\"/\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<form data-api=\"/orgs\" data-next=\"/\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -636,7 +798,7 @@ func newOrgForm() templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</form>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</form>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -664,7 +826,7 @@ func NewOrgPage(p Page, me Me) templ.Component {
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
if len(me.Orgs) == 0 {
templ_7745c5c3_Var33 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var39 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -676,20 +838,20 @@ func NewOrgPage(p Page, me Me) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<p class=\"mb-6 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "<p class=\"mb-6 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.first_intro"))
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.first_intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 111, Col: 71}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 143, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "</p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -697,44 +859,44 @@ func NewOrgPage(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<p class=\"mt-8 text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<p class=\"mt-8 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.invited_hint"))
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.invited_hint"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 113, Col: 72}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 145, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "</p><button data-logout class=\"mt-4 text-sm underline underline-offset-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</p><button data-logout class=\"mt-4 text-sm underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
var templ_7745c5c3_Var42 string
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 114, Col: 108}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 146, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</button>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "</button>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var33), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var39), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Var37 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var43 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -750,7 +912,7 @@ func NewOrgPage(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "<div class=\"max-w-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "<div class=\"max-w-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -758,13 +920,13 @@ func NewOrgPage(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var37), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var43), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+41 -1
View File
@@ -101,7 +101,19 @@ type Identity struct {
Email string
}
templ Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry) {
// PlatformIdentities are the platform providers an account signs in with
// and those it could link.
type PlatformIdentities struct {
Linked []LinkedIdentity
Available []IDPButton
}
// LinkedIdentity is a platform provider linked to the account.
type LinkedIdentity struct {
ProviderID, Name, Email string
}
templ Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry, platform PlatformIdentities) {
@consoleShell(p, me) {
<h1 class="mb-8 text-lg font-semibold">{ i18n.T(ctx, "security.title") }</h1>
<section class="max-w-md">
@@ -162,6 +174,34 @@ templ Security(p Page, me Me, identities []Identity, canLink bool, activity []Au
<a href={ templ.SafeURL("/sso/" + me.ActiveSlug + "?link=1") } class="inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "security.sso.link") }</a>
}
</section>
if len(platform.Linked)+len(platform.Available) > 0 {
<section class="mt-12 max-w-md">
<h2 class="mb-3 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "security.platform_sso.heading") }</h2>
if len(platform.Linked) > 0 {
<ul class="mb-4 divide-y divide-rule border-y border-rule text-sm">
for _, l := range platform.Linked {
<li class="flex items-center justify-between gap-4 py-2">
<span>
{ l.Name }
<span class="block font-mono text-xs text-muted">{ l.Email }</span>
</span>
<button
type="button"
data-delete={ "/me/identities/" + l.ProviderID }
data-confirm={ i18n.T(ctx, "security.platform_sso.unlink_confirm", "Name", l.Name) }
class="text-muted hover:text-down"
>{ i18n.T(ctx, "security.platform_sso.unlink") }</button>
</li>
}
</ul>
}
<div class="flex flex-wrap gap-2">
for _, a := range platform.Available {
<a href={ templ.SafeURL(a.URL) } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "security.platform_sso.link", "Name", a.Name) }</a>
}
</div>
</section>
}
<section class="mt-12">
@sectionHeading("security.activity")
<p class="mb-4 max-w-2xl text-sm text-muted">{ i18n.T(ctx, "security.activity_intro") }</p>
+227 -71
View File
@@ -391,7 +391,19 @@ type Identity struct {
Email string
}
func Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry) templ.Component {
// PlatformIdentities are the platform providers an account signs in with
// and those it could link.
type PlatformIdentities struct {
Linked []LinkedIdentity
Available []IDPButton
}
// LinkedIdentity is a platform provider linked to the account.
type LinkedIdentity struct {
ProviderID, Name, Email string
}
func Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry, platform PlatformIdentities) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
@@ -427,7 +439,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 106, Col: 72}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 118, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -440,7 +452,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 108, Col: 114}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 120, Col: 114}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -458,7 +470,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 98}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 122, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
@@ -511,7 +523,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 112, Col: 75}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 124, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
@@ -524,7 +536,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 115, Col: 116}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 127, Col: 116}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
@@ -561,7 +573,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 125, Col: 109}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 137, Col: 109}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
@@ -599,7 +611,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 134, Col: 105}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 146, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
@@ -612,7 +624,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 136, Col: 141}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 148, Col: 141}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
@@ -625,7 +637,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "security.totp.qr_alt")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 138, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 150, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
if templ_7745c5c3_Err != nil {
@@ -663,7 +675,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 151, Col: 113}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 163, Col: 113}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
@@ -681,7 +693,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 153, Col: 73}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 165, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
@@ -704,7 +716,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 157, Col: 69}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 169, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
@@ -717,7 +729,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 157, Col: 131}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 169, Col: 131}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
@@ -741,7 +753,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL("/sso/" + me.ActiveSlug + "?link=1")).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 162, Col: 64}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 174, Col: 64}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
if templ_7745c5c3_Err != nil {
@@ -754,7 +766,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 162, Col: 190}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 174, Col: 190}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
@@ -765,7 +777,151 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</section><section class=\"mt-12\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</section>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(platform.Linked)+len(platform.Available) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "<section class=\"mt-12 max-w-md\"><h2 class=\"mb-3 text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.platform_sso.heading"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 179, Col: 123}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</h2>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(platform.Linked) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<ul class=\"mb-4 divide-y divide-rule border-y border-rule text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, l := range platform.Linked {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "<li class=\"flex items-center justify-between gap-4 py-2\"><span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(l.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 185, Col: 17}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, " <span class=\"block font-mono text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(l.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 186, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "</span></span> <button type=\"button\" data-delete=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/me/identities/" + l.ProviderID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 190, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var39)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "\" data-confirm=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "security.platform_sso.unlink_confirm", "Name", l.Name)).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 191, Col: 91}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var40)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "\" class=\"text-muted hover:text-down\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.platform_sso.unlink"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 193, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "</button></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "</ul>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "<div class=\"flex flex-wrap gap-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, a := range platform.Available {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var42 string
templ_7745c5c3_Var42, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(a.URL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 200, Col: 36}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "\" class=\"border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var43 string
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.platform_sso.link", "Name", a.Name))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 200, Col: 174}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "</div></section>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, " <section class=\"mt-12\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -773,20 +929,20 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "<p class=\"mb-4 max-w-2xl text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "<p class=\"mb-4 max-w-2xl text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.activity_intro"))
var templ_7745c5c3_Var44 string
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.activity_intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 167, Col: 88}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 207, Col: 88}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -794,7 +950,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool, activity []Aud
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "</section>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "</section>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -831,33 +987,33 @@ func recoveryOutput() templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "<div data-recovery-output hidden class=\"mt-6 border border-ink p-4\"><p class=\"mb-3 text-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "<div data-recovery-output hidden class=\"mt-6 border border-ink p-4\"><p class=\"mb-3 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.save_now"))
var templ_7745c5c3_Var46 string
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.save_now"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 178, Col: 69}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 218, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "</p><ol data-recovery-list class=\"mb-4 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm\"></ol><a href=\"/settings/security\" class=\"text-sm underline underline-offset-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</p><ol data-recovery-list class=\"mb-4 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm\"></ol><a href=\"/settings/security\" class=\"text-sm underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.saved"))
var templ_7745c5c3_Var47 string
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.saved"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 180, Col: 116}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 220, Col: 116}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "</a></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</a></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -882,46 +1038,46 @@ func policyBanner(msgID, actionID, href string) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<div class=\"border-b border-degraded/40 bg-degraded/10\"><p class=\"mx-auto max-w-5xl px-6 py-2 text-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<div class=\"border-b border-degraded/40 bg-degraded/10\"><p class=\"mx-auto max-w-5xl px-6 py-2 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID))
var templ_7745c5c3_Var49 string
templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 187, Col: 23}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 227, Col: 23}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var49))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, " <a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, " <a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var42 string
templ_7745c5c3_Var42, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(href)).ResolveURL(ctx)
var templ_7745c5c3_Var50 string
templ_7745c5c3_Var50, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(href)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 188, Col: 32}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 228, Col: 32}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var50)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "\" class=\"underline underline-offset-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "\" class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var43 string
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, actionID))
var templ_7745c5c3_Var51 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, actionID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 188, Col: 95}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 228, Col: 95}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "</a></p></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "</a></p></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -946,46 +1102,46 @@ func settingsLink(href, titleID, hintID string) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "<a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(href)).ResolveURL(ctx)
var templ_7745c5c3_Var53 string
templ_7745c5c3_Var53, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(href)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 194, Col: 30}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 234, Col: 30}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var45)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var53)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "\" class=\"block border border-rule p-4 hover:border-ink\"><span class=\"block font-medium\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "\" class=\"block border border-rule p-4 hover:border-ink\"><span class=\"block font-medium\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var46 string
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, titleID))
var templ_7745c5c3_Var54 string
templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, titleID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 195, Col: 56}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 235, Col: 56}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var54))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "</span> <span class=\"mt-1 block text-sm text-muted\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "</span> <span class=\"mt-1 block text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var47 string
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, hintID))
var templ_7745c5c3_Var55 string
templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, hintID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 196, Col: 67}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 236, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "</span></a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "</span></a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1011,7 +1167,7 @@ func SettingsIndex(p Page, me Me) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var49 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var57 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -1027,7 +1183,7 @@ func SettingsIndex(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<div class=\"grid gap-4 sm:grid-cols-2 lg:grid-cols-3\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "<div class=\"grid gap-4 sm:grid-cols-2 lg:grid-cols-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1093,13 +1249,13 @@ func SettingsIndex(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var49), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var57), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+87
View File
@@ -0,0 +1,87 @@
package web
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
// IDPAdminView lists the platform identity providers for admins.
type IDPAdminView struct {
Providers []IDPRow
// CallbackURL is what to register at the provider.
CallbackURL string
}
// IDPRow is a platform identity provider; its secret is never shown.
type IDPRow struct {
ID, Kind, Name, Issuer, ClientID string
SecretSet, AllowSignup, Enabled bool
}
templ idpFields(r IDPRow, isNew bool) {
if isNew {
<label class="mb-3 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "idp.kind") }</span>
<select name="kind" class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
<option value="oidc">{ i18n.T(ctx, "idp.kind_oidc") }</option>
<option value="github">GitHub</option>
</select>
</label>
} else {
<input type="hidden" name="kind" value={ r.Kind }/>
}
@valueField(i18n.T(ctx, "sso.field.name"), "name", r.Name, "Google", true)
@valueField(i18n.T(ctx, "idp.issuer"), "issuer", r.Issuer, "https://accounts.google.com", false)
@valueField(i18n.T(ctx, "idp.client_id"), "client_id", r.ClientID, "", true)
@secretField(i18n.T(ctx, "idp.client_secret"), "client_secret", r.SecretSet)
@checkbox(i18n.T(ctx, "idp.allow_signup"), "allow_signup", r.AllowSignup || isNew)
@checkbox(i18n.T(ctx, "idp.enabled"), "enabled", r.Enabled || isNew)
}
templ idpSection(v IDPAdminView) {
<section id="identity-providers" class="mb-12 max-w-3xl">
@sectionHeading("idp.title")
<p class="mb-2 text-sm text-muted">{ i18n.T(ctx, "idp.intro") }</p>
<p class="mb-4 text-sm">{ i18n.T(ctx, "idp.callback") } <code class="font-mono text-xs">{ v.CallbackURL }</code></p>
if len(v.Providers) > 0 {
<ul class="mb-6 divide-y divide-rule border-y border-rule text-sm">
for _, r := range v.Providers {
<li class="py-2.5">
<div class="flex flex-wrap items-baseline gap-x-4 gap-y-1">
if r.Enabled {
@statusDot(StatusUp)
} else {
@statusDot(StatusPaused)
}
<span class="font-medium">{ r.Name }</span>
<span class="font-mono text-xs text-muted">{ r.Issuer }</span>
if r.AllowSignup {
<span class="text-xs text-muted">{ i18n.T(ctx, "idp.signup_open") }</span>
}
<button
type="button"
data-delete={ "/admin/identity-providers/" + r.ID }
data-confirm={ i18n.T(ctx, "idp.delete_confirm", "Name", r.Name) }
class="ml-auto text-muted hover:text-down"
>{ i18n.T(ctx, "regions.delete") }</button>
</div>
<details class="mt-2">
<summary class="cursor-pointer text-xs text-muted hover:text-ink">{ i18n.T(ctx, "sso.action.edit") }</summary>
<form data-api={ "/admin/identity-providers/" + r.ID } data-method="put" data-next="/admin#identity-providers" class="mt-3 max-w-sm">
@formError()
@idpFields(r, false)
@submit(i18n.T(ctx, "common.save"))
</form>
</details>
</li>
}
</ul>
}
<details>
<summary class="cursor-pointer text-sm text-muted hover:text-ink">{ i18n.T(ctx, "idp.add") }</summary>
<form data-api="/admin/identity-providers" data-next="/admin#identity-providers" class="mt-3 max-w-sm">
@formError()
<p class="mb-3 text-xs text-muted">{ i18n.T(ctx, "idp.issuer_hint") }</p>
@idpFields(IDPRow{}, true)
@submit(i18n.T(ctx, "idp.add"))
</form>
</details>
</section>
}
+405
View File
@@ -0,0 +1,405 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1118
package web
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
// IDPAdminView lists the platform identity providers for admins.
type IDPAdminView struct {
Providers []IDPRow
// CallbackURL is what to register at the provider.
CallbackURL string
}
// IDPRow is a platform identity provider; its secret is never shown.
type IDPRow struct {
ID, Kind, Name, Issuer, ClientID string
SecretSet, AllowSignup, Enabled bool
}
func idpFields(r IDPRow, isNew bool) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
if isNew {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<label class=\"mb-3 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.kind"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 21, Col: 109}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</span> <select name=\"kind\" class=\"w-full border border-rule bg-transparent px-2 py-1.5 text-sm\"><option value=\"oidc\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.kind_oidc"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 23, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</option> <option value=\"github\">GitHub</option></select></label>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "<input type=\"hidden\" name=\"kind\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(r.Kind).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 28, Col: 49}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", r.Name, "Google", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = valueField(i18n.T(ctx, "idp.issuer"), "issuer", r.Issuer, "https://accounts.google.com", false).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = valueField(i18n.T(ctx, "idp.client_id"), "client_id", r.ClientID, "", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = secretField(i18n.T(ctx, "idp.client_secret"), "client_secret", r.SecretSet).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = checkbox(i18n.T(ctx, "idp.allow_signup"), "allow_signup", r.AllowSignup || isNew).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = checkbox(i18n.T(ctx, "idp.enabled"), "enabled", r.Enabled || isNew).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
func idpSection(v IDPAdminView) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<section id=\"identity-providers\" class=\"mb-12 max-w-3xl\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = sectionHeading("idp.title").Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<p class=\"mb-2 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 41, Col: 63}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</p><p class=\"mb-4 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.callback"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 42, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, " <code class=\"font-mono text-xs\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(v.CallbackURL)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 42, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</code></p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(v.Providers) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<ul class=\"mb-6 divide-y divide-rule border-y border-rule text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, r := range v.Providers {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<li class=\"py-2.5\"><div class=\"flex flex-wrap items-baseline gap-x-4 gap-y-1\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if r.Enabled {
templ_7745c5c3_Err = statusDot(StatusUp).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = statusDot(StatusPaused).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<span class=\"font-medium\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(r.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 53, Col: 41}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</span> <span class=\"font-mono text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(r.Issuer)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 54, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if r.AllowSignup {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<span class=\"text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.signup_open"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 56, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "<button type=\"button\" data-delete=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/identity-providers/" + r.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 60, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "\" data-confirm=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "idp.delete_confirm", "Name", r.Name)).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 61, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "\" class=\"ml-auto text-muted hover:text-down\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.delete"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 63, Col: 39}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</button></div><details class=\"mt-2\"><summary class=\"cursor-pointer text-xs text-muted hover:text-ink\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.edit"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 66, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</summary><form data-api=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/identity-providers/" + r.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 67, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "\" data-method=\"put\" data-next=\"/admin#identity-providers\" class=\"mt-3 max-w-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = idpFields(r, false).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = submit(i18n.T(ctx, "common.save")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</form></details></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</ul>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<details><summary class=\"cursor-pointer text-sm text-muted hover:text-ink\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.add"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 78, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</summary><form data-api=\"/admin/identity-providers\" data-next=\"/admin#identity-providers\" class=\"mt-3 max-w-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<p class=\"mb-3 text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "idp.issuer_hint"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/idp.templ`, Line: 81, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = idpFields(IDPRow{}, true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = submit(i18n.T(ctx, "idp.add")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</form></details></section>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
+65 -2
View File
@@ -25,6 +25,27 @@ type Agent struct {
// AllowPrivate is set for an organization's checkers: whether they
// may check private addresses.
AllowPrivate *bool
// Release is what the agent last reported; Outdated marks agents
// behind the platform's release.
Release string
Outdated bool
}
// InstallView fills the install instructions shown with a new agent's
// token.
type InstallView struct {
// ScriptURL is the platform's install script.
ScriptURL string
// APIURL goes into UPTIME_API_URL.
APIURL string
// Image is the image name without -checker or -statuspage.
Image string
// Channel is the image tag following the platform: latest, beta or edge.
Channel string
// Compose holds the Compose file per agent kind.
Compose map[string]string
// Release is the platform's release.
Release string
}
// RegionsView is the data of the org regions page and the admin panel.
@@ -38,6 +59,7 @@ type RegionsView struct {
Next string
// OwnRegions are the regions agents can be created in.
OwnRegions []Region
Install InstallView
}
templ regionsBody(v RegionsView) {
@@ -117,6 +139,7 @@ templ regionsBody(v RegionsView) {
<div data-link-output hidden class="mt-6 border border-ink p-4">
<p class="mb-2 text-sm">{ i18n.T(ctx, "agents.token_now") }</p>
<input data-link readonly class="w-full border border-rule bg-transparent px-2 py-1.5 font-mono text-xs"/>
@agentInstall(v.Install)
</div>
</form>
</section>
@@ -124,6 +147,9 @@ templ regionsBody(v RegionsView) {
if len(v.Agents) > 0 {
<section>
@sectionHeading("agents.list")
if v.Install.Release != "" {
<p class="mb-3 text-xs text-muted">{ i18n.T(ctx, "agents.platform_release", "Release", v.Install.Release) }</p>
}
<ul class="divide-y divide-rule border-y border-rule text-sm">
for _, a := range v.Agents {
<li class="flex items-center justify-between gap-4 py-2">
@@ -133,7 +159,15 @@ templ regionsBody(v RegionsView) {
if a.Region != "" {
<span class="text-muted">· { a.Region }</span>
}
<span class="block font-mono text-xs text-muted">{ a.Prefix }… · { a.LastSeen }</span>
<span class="block font-mono text-xs text-muted">
{ a.Prefix }… · { a.LastSeen }
if a.Release != "" {
· { a.Release }
}
if a.Outdated {
<span class="text-degraded" title={ i18n.T(ctx, "agents.outdated_hint") }>· { i18n.T(ctx, "agents.outdated") }</span>
}
</span>
</span>
if a.AllowPrivate != nil {
<form data-api={ v.APIBase + "/agents/" + a.ID } data-method="patch" data-autosave class="ml-auto">
@@ -159,10 +193,11 @@ templ RegionsPage(p Page, me Me, v RegionsView) {
}
}
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, limits LimitsView) {
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, limits LimitsView, idps IDPAdminView) {
@consoleShell(p, me) {
@settingsHeading("admin.title", "admin.intro")
@adminLinks()
@idpSection(idps)
@limitsSection(limits)
@regionsBody(v)
@checkerNetworkSection(platformPrivate)
@@ -382,3 +417,31 @@ templ AdminOrgsPage(p Page, me Me, v OrgsView) {
@orgsSection(v)
}
}
// agentInstall shows how to run the agent just created; the script fills
// in the token, the kind chosen and whether it updates itself.
templ agentInstall(in InstallView) {
<div data-install data-channel={ in.Channel } class="mt-6 border-t border-rule pt-4">
<h3 class="mb-2 text-sm font-medium">{ i18n.T(ctx, "agents.install_heading") }</h3>
<label class="mb-1 flex items-center gap-2 text-sm">
<input type="checkbox" data-install-auto checked class="accent-ink"/>
{ i18n.T(ctx, "agents.install_auto") }
</label>
<p class="mb-4 ml-6 text-xs text-muted">{ i18n.T(ctx, "agents.install_auto_hint") }</p>
<p class="mb-1 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "agents.install_oneliner") }</p>
<pre data-install-fill={ "curl -fsSL " + in.ScriptURL + " | sudo sh -s -- {kind} --token {token}{manual}" } class="mb-1 overflow-x-auto whitespace-pre-wrap break-all border border-rule p-2 font-mono text-xs"></pre>
<p data-install-kind="statuspage" class="mb-4 text-xs text-muted">{ i18n.T(ctx, "agents.install_statuspage_hint") }</p>
<details class="mt-4">
<summary class="cursor-pointer text-sm">{ i18n.T(ctx, "agents.install_compose") }</summary>
for _, kind := range []string{"checker", "statuspage"} {
<div data-install-kind={ kind } class="mt-3">
<p class="mb-1 font-mono text-xs text-muted">compose.yaml</p>
<pre class="mb-3 max-h-64 overflow-auto border border-rule p-2 font-mono text-xs">{ in.Compose[kind] }</pre>
<p class="mb-1 font-mono text-xs text-muted">.env</p>
<pre data-install-fill={ "UPTIME_API_URL=" + in.APIURL + "\nUPTIME_AGENT_TOKEN={token}\nUPTIME_AGENT_IMAGE=" + in.Image + "\nUPTIME_AGENT_TAG={tag}" } class="overflow-x-auto border border-rule p-2 font-mono text-xs"></pre>
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "agents.install_compose_hint") }</p>
</div>
}
</details>
</div>
}
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
// Command image builds and publishes the multi-arch images of an agent
// (checker or status page server) from cross-compiled binaries, without
// Docker.
//
// image -name checker -dist dist -repo registry/owner/uptimesebi-checker \
// -version v1.2.3 -commit abc123 -ref refs/tags/v1.2.3 [-autoupdate] [-push]
//
// dist holds one directory per platform: linux_amd64, linux_arm64,
// linux_arm_v7 and linux_arm_v6, each with the binaries. Without -push
// the index is only built. The registry login comes from REGISTRY_USER and
// REGISTRY_PASSWORD; when RELEASE_SIGNING_KEY is set, pushed images are
// signed so self-updating agents accept them.
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/google/go-containerregistry/pkg/name"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentimage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
type listFlag []string
func (l *listFlag) String() string { return strings.Join(*l, ",") }
func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil }
func run(args []string) error {
fs := flag.NewFlagSet("image", flag.ContinueOnError)
var o agentimage.Options
fs.StringVar(&o.Name, "name", "", "binary name: checker or statuspage")
fs.StringVar(&o.Dist, "dist", "dist", "directory with one subdirectory per platform")
fs.StringVar(&o.Version, "version", "dev", "release version, as the binaries report it")
fs.StringVar(&o.Commit, "commit", "", "git revision")
fs.StringVar(&o.Source, "source", "", "repository URL for the image labels")
fs.BoolVar(&o.Launcher, "autoupdate", false, "build the self-updating variant (tags get -autoupdate)")
fs.Var((*listFlag)(&o.Env), "env", "NAME=value baked into the image (repeatable)")
fs.Var((*listFlag)(&o.Ports), "port", "exposed port, e.g. 8081/tcp (repeatable)")
repo := fs.String("repo", "", "image repository, e.g. git.example.com/owner/uptimesebi-checker")
ref := fs.String("ref", "", "git ref being built, e.g. refs/heads/main or refs/tags/v1.2.3")
created := fs.Int64("created", 0, "creation time as Unix seconds, for reproducible images")
push := fs.Bool("push", false, "push to the registry")
insecure := fs.Bool("insecure", false, "talk plain HTTP to the registry")
if err := fs.Parse(args); err != nil {
return err
}
if o.Name == "" || *repo == "" {
return errors.New("image: -name and -repo are required")
}
o.Created = time.Unix(*created, 0).UTC()
idx, err := agentimage.Build(o)
if err != nil {
return err
}
digest, err := idx.Digest()
if err != nil {
return err
}
fmt.Printf("built %s@%s\n", *repo, digest)
if !*push {
return nil
}
suffix := ""
if o.Launcher {
suffix = "autoupdate"
}
tags := agentimage.ChannelTags(*ref, o.Version, suffix)
if len(tags) == 0 {
return fmt.Errorf("image: %q is not a ref that publishes images", *ref)
}
var nameOpts []name.Option
if *insecure {
nameOpts = append(nameOpts, name.Insecure)
}
ctx := context.Background()
login := agentimage.Credentials{User: os.Getenv("REGISTRY_USER"), Password: os.Getenv("REGISTRY_PASSWORD")}
if err := agentimage.Publish(ctx, idx, *repo, tags, login, nameOpts...); err != nil {
return err
}
fmt.Printf("pushed %s:%s\n", *repo, strings.Join(tags, ", :"))
raw := os.Getenv("RELEASE_SIGNING_KEY")
if raw == "" {
fmt.Println("RELEASE_SIGNING_KEY is not set; self-updating agents will not accept this image.")
return nil
}
key, err := signing.ParsePrivateKey(raw)
if err != nil {
return err
}
if err := agentimage.Sign(ctx, idx, *repo, o.Name, o.Version, key, login, nameOpts...); err != nil {
return err
}
fmt.Printf("signed %s@%s as %s\n", *repo, digest, o.Version)
return nil
}
+185
View File
@@ -0,0 +1,185 @@
// Command release derives versions and release notes from Conventional
// Commits.
//
// release next [stable|beta] print the tag the next release gets
// release notes [-json] <tag> print the release notes of a tag, with
// -json as the body of a Gitea release
// release check <tag> fail unless tag is a valid release tag
// release sbom <tag> <bin>... print the SPDX SBOM of a release
// release sign <file> <tag> write file.minisig with the key in
// RELEASE_SIGNING_KEY
// release verify <file> check file.minisig against the release keys
// release keygen <secret-file> create a signing key, print its public key
//
// Stable releases follow semantic versioning from the commits since the
// last stable release: breaking changes move the major version (the minor
// one before 1.0), features the minor and fixes the patch version. Betas
// are numbered prereleases of the coming stable version.
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
const usage = `usage: release next [stable|beta] | notes [-json] <tag> | check <tag> | sbom <tag> <binary>... | sign <file> <tag> | verify <file> | keygen <secret-file>`
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) == 0 {
return usageError{}
}
switch args[0] {
case "next":
channel := "stable"
if len(args) > 1 {
channel = args[1]
}
tags, err := gitTags()
if err != nil {
return err
}
from := ""
if base := lastStable(tags); base != (version{}) {
from = base.String()
}
commits, err := gitCommits(from, "HEAD")
if err != nil {
return err
}
v, err := next(tags, commits, channel)
if err != nil {
return err
}
fmt.Println(v)
case "notes":
asJSON := len(args) == 3 && args[1] == "-json"
if asJSON {
args = args[1:]
}
if len(args) != 2 {
return usageError{}
}
v, err := parseVersion(args[1])
if err != nil {
return err
}
tags, err := gitTags()
if err != nil {
return err
}
prev, ok := previous(tags, v)
from := ""
var pp *version
if ok {
from, pp = prev.String(), &prev
}
commits, err := gitCommits(from, v.String())
if err != nil {
return err
}
text := notes(v, pp, commits, repoURL())
if !asJSON {
fmt.Print(text)
return nil
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{
"tag_name": v.String(), "name": v.String(), "body": text, "prerelease": v.Beta > 0,
})
case "check":
if len(args) != 2 {
return usageError{}
}
_, err := parseVersion(args[1])
return err
case "sbom":
if len(args) < 3 {
return usageError{}
}
v, err := parseVersion(args[1])
if err != nil {
return err
}
return writeSBOM(v, args[2:])
case "sign":
if len(args) != 3 {
return usageError{}
}
return signFile(args[1], args[2])
case "verify":
if len(args) != 2 {
return usageError{}
}
return verifyFile(args[1])
case "keygen":
if len(args) != 2 {
return usageError{}
}
return keygen(args[1])
default:
return usageError{}
}
return nil
}
type usageError struct{}
func (usageError) Error() string { return usage }
func git(args ...string) (string, error) {
out, err := exec.Command("git", args...).Output()
var exit *exec.ExitError
if errors.As(err, &exit) {
return "", fmt.Errorf("git %s: %s", strings.Join(args, " "), strings.TrimSpace(string(exit.Stderr)))
}
return string(out), err
}
func gitTags() ([]version, error) {
out, err := git("tag", "--list", "v*")
if err != nil {
return nil, err
}
return parseTags(strings.Split(out, "\n")), nil
}
// gitCommits lists the commits after from up to to, oldest first, without
// merge commits. An empty from means the whole history.
func gitCommits(from, to string) ([]commit, error) {
rng := to
if from != "" {
rng = from + ".." + to
}
out, err := git("log", "--reverse", "--no-merges", "--format=%H%x1f%s%x1f%b%x1e", rng, "--")
if err != nil {
return nil, err
}
var commits []commit
for rec := range strings.SplitSeq(out, "\x1e") {
f := strings.SplitN(strings.TrimLeft(rec, "\n"), "\x1f", 3)
if len(f) != 3 {
continue
}
commits = append(commits, commit{Hash: f[0], Subject: f[1], Body: f[2]})
}
return commits, nil
}
// repoURL is the repository's web address in CI, for links in the notes.
func repoURL() string {
server, repo := os.Getenv("GITHUB_SERVER_URL"), os.Getenv("GITHUB_REPOSITORY")
if server == "" || repo == "" {
return ""
}
return strings.TrimSuffix(server, "/") + "/" + repo
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"fmt"
"regexp"
"strings"
)
// commit is one Conventional Commit.
type commit struct {
Hash, Subject, Body string
}
var subjectPattern = regexp.MustCompile(`^([a-z]+)(?:\(([^)]+)\))?(!)?: (.+)$`)
// parsed splits the subject into type, scope and description.
func (c commit) parsed() (typ, scope, desc string, breaking bool) {
m := subjectPattern.FindStringSubmatch(c.Subject)
if m == nil {
return "", "", c.Subject, false
}
return m[1], m[2], m[4], m[3] == "!" || c.breakingNote() != ""
}
// breakingNote returns the BREAKING CHANGE footer.
func (c commit) breakingNote() string {
for _, prefix := range []string{"BREAKING CHANGE: ", "BREAKING-CHANGE: "} {
if _, after, ok := strings.Cut(c.Body, prefix); ok {
note, _, _ := strings.Cut(after, "\n\n")
return strings.Join(strings.Fields(note), " ")
}
}
return ""
}
func (c commit) bump() bump {
typ, _, _, breaking := c.parsed()
switch {
case breaking:
return bumpMajor
case typ == "feat":
return bumpMinor
case typ == "fix" || typ == "perf":
return bumpPatch
}
return bumpNone
}
var sections = []struct{ typ, title string }{
{"feat", "Features"},
{"fix", "Fixes"},
{"perf", "Performance"},
}
// notes renders the changelog of a release in Markdown. Changes outside
// features, fixes and performance stay out, except breaking ones.
func notes(v version, prev *version, commits []commit, repoURL string) string {
var b strings.Builder
line := func(c commit, desc, scope string) {
if scope != "" {
desc = "**" + scope + ":** " + desc
}
short := c.Hash[:min(len(c.Hash), 7)]
if repoURL != "" {
fmt.Fprintf(&b, "- %s ([%s](%s/commit/%s))\n", desc, short, repoURL, c.Hash)
} else {
fmt.Fprintf(&b, "- %s (%s)\n", desc, short)
}
}
var breaking []commit
for _, c := range commits {
if _, _, _, br := c.parsed(); br {
breaking = append(breaking, c)
}
}
if len(breaking) > 0 {
b.WriteString("### Breaking changes\n\n")
for _, c := range breaking {
_, scope, desc, _ := c.parsed()
if n := c.breakingNote(); n != "" {
desc += ": " + n
}
line(c, desc, scope)
}
b.WriteString("\n")
}
for _, s := range sections {
head := false
for _, c := range commits {
typ, scope, desc, _ := c.parsed()
if typ != s.typ {
continue
}
if !head {
fmt.Fprintf(&b, "### %s\n\n", s.title)
head = true
}
line(c, desc, scope)
}
if head {
b.WriteString("\n")
}
}
if b.Len() == 0 {
b.WriteString("No user-facing changes.\n\n")
}
if prev != nil && repoURL != "" {
fmt.Fprintf(&b, "**Full changes:** [%s...%s](%s/compare/%s...%s)\n", prev, v, repoURL, prev, v)
}
return b.String()
}
+127
View File
@@ -0,0 +1,127 @@
package main
import (
"errors"
"strings"
"testing"
)
func tags(t *testing.T, names ...string) []version {
t.Helper()
out := parseTags(names)
if len(out) != len(names) {
t.Fatalf("invalid tags in %v", names)
}
return out
}
func commits(subjects ...string) []commit {
var out []commit
for i, s := range subjects {
subject, body, _ := strings.Cut(s, "\n\n")
out = append(out, commit{Hash: strings.Repeat(string(rune('a'+i)), 40), Subject: subject, Body: body})
}
return out
}
func TestNext(t *testing.T) {
cases := []struct {
name string
tags []string
commits []string
channel string
want string
}{
{"first release", nil, []string{"feat: monitors"}, "stable", "v0.1.0"},
{"fix", []string{"v0.3.1"}, []string{"fix: retry", "chore: deps"}, "stable", "v0.3.2"},
{"feature", []string{"v0.3.1"}, []string{"fix: retry", "feat(api): paging"}, "stable", "v0.4.0"},
{"breaking before 1.0", []string{"v0.3.1"}, []string{"feat!: new config"}, "stable", "v0.4.0"},
{"breaking footer", []string{"v1.3.1"}, []string{"refactor: config\n\nBREAKING CHANGE: UPTIME_X is gone"}, "stable", "v2.0.0"},
{"breaking after 1.0", []string{"v1.3.1"}, []string{"feat(api)!: drop v0"}, "stable", "v2.0.0"},
{"first beta", []string{"v1.3.1"}, []string{"feat: x"}, "beta", "v1.4.0-beta.1"},
{"next beta", []string{"v1.3.1", "v1.4.0-beta.1", "v1.4.0-beta.2"}, []string{"feat: x", "fix: y"}, "beta", "v1.4.0-beta.3"},
{"stable after betas", []string{"v1.3.1", "v1.4.0-beta.2"}, []string{"feat: x"}, "stable", "v1.4.0"},
{"betas of another version", []string{"v1.3.1", "v1.3.2-beta.4"}, []string{"feat: x"}, "beta", "v1.4.0-beta.1"},
{"perf", []string{"v1.0.0"}, []string{"perf: cache"}, "stable", "v1.0.1"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := next(tags(t, c.tags...), commits(c.commits...), c.channel)
if err != nil || got.String() != c.want {
t.Errorf("next = %v, %v; want %s", got, err, c.want)
}
})
}
if _, err := next(nil, commits("chore: x", "docs: y", "Merge branch"), "stable"); !errors.Is(err, errNothingToRelease) {
t.Errorf("nothing to release: err = %v", err)
}
if _, err := next(nil, commits("feat: x"), "nightly"); err == nil {
t.Error("unknown channel accepted")
}
}
func TestVersion(t *testing.T) {
for _, bad := range []string{"1.0.0", "v1.0", "v01.0.0", "v1.0.0-rc.1", "v1.0.0-beta.0", "v1.0.0-beta", "v1.0.0\n"} {
if _, err := parseVersion(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
got := tags(t, "v1.0.0", "v0.9.0", "v1.0.0-beta.10", "v1.0.0-beta.2", "v0.10.0")
var names []string
for _, v := range got {
names = append(names, v.String())
}
if want := "v0.9.0 v0.10.0 v1.0.0-beta.2 v1.0.0-beta.10 v1.0.0"; strings.Join(names, " ") != want {
t.Errorf("order = %v, want %s", names, want)
}
}
func TestPrevious(t *testing.T) {
all := tags(t, "v0.1.0", "v0.2.0-beta.1", "v0.2.0-beta.2", "v0.2.0", "v0.3.0-beta.1")
for tag, want := range map[string]string{
"v0.2.0": "v0.1.0",
"v0.2.0-beta.2": "v0.2.0-beta.1",
"v0.3.0-beta.1": "v0.2.0",
"v0.3.0": "v0.2.0",
"v0.2.0-beta.1": "v0.1.0",
} {
v, _ := parseVersion(tag)
if got, ok := previous(all, v); !ok || got.String() != want {
t.Errorf("previous(%s) = %v, want %s", tag, got, want)
}
}
first, _ := parseVersion("v0.1.0")
if _, ok := previous(all, first); ok {
t.Error("the first release has a predecessor")
}
}
func TestNotes(t *testing.T) {
v, _ := parseVersion("v0.4.0")
prev, _ := parseVersion("v0.3.1")
got := notes(v, &prev, commits(
"feat(api): keyset paging",
"fix: retry DNS",
"chore: bump deps",
"feat!: config in one file\n\nBREAKING CHANGE: UPTIME_FOO is\nnow UPTIME_BAR.\n\nCo-Authored-By: x",
"perf(check): reuse connections",
), "https://git.example/o/r")
for _, want := range []string{
"### Breaking changes\n\n- config in one file: UPTIME_FOO is now UPTIME_BAR. ([ddddddd](https://git.example/o/r/commit/" + strings.Repeat("d", 40) + "))",
"### Features\n\n- **api:** keyset paging ([aaaaaaa]",
"- config in one file ([ddddddd]",
"### Fixes\n\n- retry DNS ([bbbbbbb]",
"### Performance\n\n- **check:** reuse connections",
"[v0.3.1...v0.4.0](https://git.example/o/r/compare/v0.3.1...v0.4.0)",
} {
if !strings.Contains(got, want) {
t.Errorf("notes lack %q:\n%s", want, got)
}
}
if strings.Contains(got, "bump deps") || strings.Contains(got, "Co-Authored") {
t.Errorf("notes contain internal changes:\n%s", got)
}
if got := notes(v, nil, commits("ci: x"), ""); got != "No user-facing changes.\n\n" {
t.Errorf("empty notes = %q", got)
}
}
+183
View File
@@ -0,0 +1,183 @@
package main
import (
"crypto/rand"
"debug/buildinfo"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"regexp"
"sort"
"strings"
"time"
)
// SPDX 2.3, the subset needed to list the components of a release.
type spdxDoc struct {
SPDXVersion string `json:"spdxVersion"`
DataLicense string `json:"dataLicense"`
SPDXID string `json:"SPDXID"`
Name string `json:"name"`
DocumentNamespace string `json:"documentNamespace"`
CreationInfo spdxCreation `json:"creationInfo"`
Packages []spdxPackage `json:"packages"`
Relationships []spdxRelationship `json:"relationships"`
}
type spdxCreation struct {
Created string `json:"created"`
Creators []string `json:"creators"`
}
type spdxPackage struct {
Name string `json:"name"`
SPDXID string `json:"SPDXID"`
VersionInfo string `json:"versionInfo"`
DownloadLocation string `json:"downloadLocation"`
FilesAnalyzed bool `json:"filesAnalyzed"`
LicenseConcluded string `json:"licenseConcluded,omitempty"`
LicenseDeclared string `json:"licenseDeclared,omitempty"`
CopyrightText string `json:"copyrightText,omitempty"`
ExternalRefs []spdxExtRef `json:"externalRefs,omitempty"`
Checksums []spdxSummary `json:"checksums,omitempty"`
}
type spdxExtRef struct {
Category string `json:"referenceCategory"`
Type string `json:"referenceType"`
Locator string `json:"referenceLocator"`
}
type spdxSummary struct {
Algorithm string `json:"algorithm"`
Value string `json:"checksumValue"`
}
type spdxRelationship struct {
Element string `json:"spdxElementId"`
Type string `json:"relationshipType"`
Related string `json:"relatedSpdxElement"`
}
// component is one third-party part of a release.
type component struct{ purl, name, version string }
var spdxIDUnsafe = regexp.MustCompile(`[^A-Za-z0-9.-]+`)
// sbom describes a release: the Go modules and toolchain compiled into the
// binaries and the npm packages whose files the frontend build copies.
func sbom(v version, binaries []string, packageJSON, packageLock []byte, now time.Time, repoURL string) ([]byte, error) {
seen := map[string]component{}
for _, path := range binaries {
info, err := buildinfo.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("release: %s: %w", path, err)
}
toolchain := strings.TrimPrefix(strings.SplitN(info.GoVersion, " ", 2)[0], "go")
toolchain, _, _ = strings.Cut(toolchain, "-")
seen["stdlib"] = component{"pkg:golang/stdlib@v" + toolchain, "stdlib", "v" + toolchain}
for _, d := range info.Deps {
if d.Replace != nil {
d = d.Replace
}
seen[d.Path] = component{"pkg:golang/" + d.Path + "@" + d.Version, d.Path, d.Version}
}
}
npm, err := bundledNPM(packageJSON, packageLock)
if err != nil {
return nil, err
}
for _, c := range npm {
seen["npm:"+c.name] = c
}
comps := make([]component, 0, len(seen))
for _, c := range seen {
comps = append(comps, c)
}
sort.Slice(comps, func(i, j int) bool { return comps[i].purl < comps[j].purl })
ns := make([]byte, 8)
_, _ = rand.Read(ns)
root := spdxPackage{
Name: "uptimesebi", SPDXID: "SPDXRef-uptimesebi", VersionInfo: v.String(),
DownloadLocation: "NOASSERTION", LicenseConcluded: "AGPL-3.0-only", LicenseDeclared: "AGPL-3.0-only",
CopyrightText: "NOASSERTION",
}
if repoURL != "" {
root.DownloadLocation = "git+" + repoURL + ".git@" + v.String()
}
doc := spdxDoc{
SPDXVersion: "SPDX-2.3", DataLicense: "CC0-1.0", SPDXID: "SPDXRef-DOCUMENT",
Name: "uptimesebi-" + v.String(),
DocumentNamespace: "https://uptimesebi.invalid/spdx/" + v.String() + "-" + hex.EncodeToString(ns),
CreationInfo: spdxCreation{Created: now.UTC().Format(time.RFC3339), Creators: []string{"Tool: uptimesebi-release"}},
Packages: []spdxPackage{root},
Relationships: []spdxRelationship{{"SPDXRef-DOCUMENT", "DESCRIBES", root.SPDXID}},
}
for _, c := range comps {
id := "SPDXRef-" + spdxIDUnsafe.ReplaceAllString(strings.TrimPrefix(c.purl, "pkg:"), "-")
doc.Packages = append(doc.Packages, spdxPackage{
Name: c.name, SPDXID: id, VersionInfo: c.version, DownloadLocation: "NOASSERTION",
ExternalRefs: []spdxExtRef{{"PACKAGE-MANAGER", "purl", c.purl}},
})
doc.Relationships = append(doc.Relationships, spdxRelationship{root.SPDXID, "CONTAINS", id})
}
return json.MarshalIndent(doc, "", " ")
}
var nodeModule = regexp.MustCompile(`node_modules/((?:@[^/\s]+/)?[^/\s]+)/`)
// bundledNPM finds the npm packages the build scripts copy files from, with
// their locked versions. Build tools such as Tailwind are not shipped and
// stay out.
func bundledNPM(packageJSON, packageLock []byte) ([]component, error) {
var pkg struct {
Scripts map[string]string `json:"scripts"`
}
var lock struct {
Packages map[string]struct {
Version string `json:"version"`
} `json:"packages"`
}
if err := json.Unmarshal(packageJSON, &pkg); err != nil {
return nil, fmt.Errorf("release: package.json: %w", err)
}
if err := json.Unmarshal(packageLock, &lock); err != nil {
return nil, fmt.Errorf("release: package-lock.json: %w", err)
}
names := map[string]bool{}
for _, s := range pkg.Scripts {
for _, m := range nodeModule.FindAllStringSubmatch(s, -1) {
names[m[1]] = true
}
}
var out []component
for name := range names {
p, ok := lock.Packages["node_modules/"+name]
if !ok {
return nil, fmt.Errorf("release: %s is not in package-lock.json", name)
}
// purl encodes the @ of a scope.
purl := "pkg:npm/" + strings.Replace(name, "@", "%40", 1) + "@" + p.Version
out = append(out, component{purl, name, p.Version})
}
return out, nil
}
func writeSBOM(v version, binaries []string) error {
pj, err := os.ReadFile("package.json")
if err != nil {
return err
}
pl, err := os.ReadFile("package-lock.json")
if err != nil {
return err
}
out, err := sbom(v, binaries, pj, pl, time.Now(), repoURL())
if err != nil {
return err
}
_, err = os.Stdout.Write(append(out, '\n'))
return err
}
+92
View File
@@ -0,0 +1,92 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
func TestSBOM(t *testing.T) {
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
pj := []byte(`{"scripts":{"build":"tailwindcss -o x && cp node_modules/axios/dist/a.js node_modules/@fontsource/ibm-plex-sans/files/b.woff2 out/"}}`)
pl := []byte(`{"packages":{"node_modules/axios":{"version":"1.21.1"},"node_modules/@fontsource/ibm-plex-sans":{"version":"5.3.0"},"node_modules/tailwindcss":{"version":"4.3.5"}}}`)
v, _ := parseVersion("v1.2.3")
raw, err := sbom(v, []string{self}, pj, pl, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), "https://git.example/o/r")
if err != nil {
t.Fatal(err)
}
var doc spdxDoc
if err := json.Unmarshal(raw, &doc); err != nil {
t.Fatal(err)
}
purls := map[string]bool{}
ids := map[string]bool{}
for _, p := range doc.Packages {
if ids[p.SPDXID] {
t.Errorf("duplicate SPDXID %s", p.SPDXID)
}
ids[p.SPDXID] = true
for _, r := range p.ExternalRefs {
purls[r.Locator] = true
}
}
for _, want := range []string{"pkg:npm/axios@1.21.1", "pkg:npm/%40fontsource/ibm-plex-sans@5.3.0", "pkg:golang/golang.org/x/crypto@", "pkg:golang/stdlib@v1."} {
if !hasPrefix(purls, want) {
t.Errorf("SBOM lacks %s", want)
}
}
if hasPrefix(purls, "pkg:npm/tailwindcss") {
t.Error("build tools are not shipped")
}
if doc.Packages[0].VersionInfo != "v1.2.3" || doc.Packages[0].LicenseDeclared != "AGPL-3.0-only" ||
len(doc.Relationships) != len(doc.Packages) || doc.CreationInfo.Created != "2026-01-02T03:04:05Z" {
t.Errorf("document = %+v", doc.Packages[0])
}
if _, err := bundledNPM([]byte(`{"scripts":{"b":"cp node_modules/missing/x ."}}`), pl); err == nil {
t.Error("a package missing from the lock file was accepted")
}
}
func TestSignFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "SHA256SUMS")
if err := os.WriteFile(path, []byte("abc x.tar.gz\n"), 0o644); err != nil {
t.Fatal(err)
}
k, _ := signing.GenerateKey()
t.Setenv("RELEASE_SIGNING_KEY", k.String())
if err := signFile(path, "v1.0.0"); err == nil || !strings.Contains(err.Error(), "release.pub") {
t.Errorf("a key not in release.pub signed: %v", err)
}
t.Setenv("RELEASE_SIGNING_KEY", "")
if err := signFile(path, "v1.0.0"); err == nil {
t.Error("signed without a key")
}
if err := keygen(filepath.Join(dir, "k")); err != nil {
t.Fatal(err)
}
if err := keygen(filepath.Join(dir, "k")); err == nil {
t.Error("keygen overwrote a key")
}
if st, _ := os.Stat(filepath.Join(dir, "k")); st.Mode().Perm() != 0o600 {
t.Errorf("key file mode = %v", st.Mode())
}
}
func hasPrefix(set map[string]bool, prefix string) bool {
for s := range set {
if strings.HasPrefix(s, prefix) {
return true
}
}
return false
}
+85
View File
@@ -0,0 +1,85 @@
package main
import (
"errors"
"fmt"
"os"
"git.zb-server.de/ZB-Server/uptimesebi/internal/signing"
)
// signFile signs path for release tag; the tag becomes the trusted comment,
// so a signature cannot be passed off for another release.
func signFile(path, tag string) error {
if _, err := parseVersion(tag); err != nil {
return err
}
raw := os.Getenv("RELEASE_SIGNING_KEY")
if raw == "" {
return errors.New("release: RELEASE_SIGNING_KEY is not set")
}
key, err := signing.ParsePrivateKey(raw)
if err != nil {
return err
}
if !trusted(key.Public()) {
return fmt.Errorf("release: key %s is not in internal/signing/release.pub", key.Public().IDString())
}
msg, err := os.ReadFile(path)
if err != nil {
return err
}
sig, err := signing.Sign(key, msg, tag)
if err != nil {
return err
}
return os.WriteFile(path+".minisig", sig, 0o644)
}
func trusted(k signing.PublicKey) bool {
for _, r := range signing.ReleaseKeys() {
if r.ID == k.ID && r.Key.Equal(k.Key) {
return true
}
}
return false
}
func verifyFile(path string) error {
msg, err := os.ReadFile(path)
if err != nil {
return err
}
sig, err := os.ReadFile(path + ".minisig")
if err != nil {
return err
}
tag, err := signing.Verify(signing.ReleaseKeys(), msg, sig)
if err != nil {
return err
}
fmt.Printf("%s: good signature for %s\n", path, tag)
return nil
}
// keygen writes a new signing key to secretPath, readable only by the
// owner, and prints the public key for internal/signing/release.pub.
func keygen(secretPath string) error {
k, err := signing.GenerateKey()
if err != nil {
return err
}
f, err := os.OpenFile(secretPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
if _, err := fmt.Fprintln(f, k.String()); err != nil {
_ = f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
fmt.Printf("untrusted comment: uptimesebi release key %s\n%s\n", k.Public().IDString(), k.Public())
return nil
}
+154
View File
@@ -0,0 +1,154 @@
package main
import (
"errors"
"fmt"
"regexp"
"slices"
"strconv"
"strings"
)
// version is a release tag: vMAJOR.MINOR.PATCH, or a beta of the next
// stable release with -beta.N.
type version struct {
Major, Minor, Patch int
// Beta is 0 for stable releases.
Beta int
}
var tagPattern = regexp.MustCompile(`^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.([1-9]\d*))?$`)
func parseVersion(tag string) (version, error) {
m := tagPattern.FindStringSubmatch(tag)
if m == nil {
return version{}, fmt.Errorf("release: %q is not vX.Y.Z or vX.Y.Z-beta.N", tag)
}
var v version
for i, p := range []*int{&v.Major, &v.Minor, &v.Patch, &v.Beta} {
if m[i+1] != "" {
*p, _ = strconv.Atoi(m[i+1])
}
}
return v, nil
}
func (v version) String() string {
s := fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch)
if v.Beta > 0 {
s += fmt.Sprintf("-beta.%d", v.Beta)
}
return s
}
func (v version) stable() version { return version{v.Major, v.Minor, v.Patch, 0} }
// compare orders versions; a beta comes before its stable release.
func (v version) compare(o version) int {
for _, d := range []int{v.Major - o.Major, v.Minor - o.Minor, v.Patch - o.Patch} {
if d != 0 {
return d
}
}
switch {
case v.Beta == o.Beta:
return 0
case v.Beta == 0:
return 1
case o.Beta == 0:
return -1
}
return v.Beta - o.Beta
}
// bump is how much a set of changes moves the version.
type bump int
const (
bumpNone bump = iota
bumpPatch
bumpMinor
bumpMajor
)
func (v version) bumped(b bump) version {
// Before 1.0, breaking changes move the minor version.
if b == bumpMajor && v.Major == 0 {
b = bumpMinor
}
switch b {
case bumpMajor:
return version{Major: v.Major + 1}
case bumpMinor:
return version{Major: v.Major, Minor: v.Minor + 1}
}
return version{Major: v.Major, Minor: v.Minor, Patch: v.Patch + 1}
}
var errNothingToRelease = errors.New("release: no feat, fix or perf commits since the last release")
// next returns the tag to release on channel from the existing tags and the
// commits since the last stable release.
func next(tags []version, commits []commit, channel string) (version, error) {
if channel != "stable" && channel != "beta" {
return version{}, fmt.Errorf("release: channel %q is not stable or beta", channel)
}
base := lastStable(tags)
b := bumpNone
for _, c := range commits {
b = max(b, c.bump())
}
if b == bumpNone {
return version{}, errNothingToRelease
}
v := base.bumped(b)
if channel == "stable" {
return v, nil
}
beta := v
for _, t := range tags {
if t.stable() == v && t.Beta > beta.Beta {
beta.Beta = t.Beta
}
}
beta.Beta++
return beta, nil
}
// lastStable returns the highest stable tag, v0.0.0 without one.
func lastStable(tags []version) version {
var out version
for _, t := range tags {
if t.Beta == 0 && t.compare(out) > 0 {
out = t
}
}
return out
}
// previous returns the release the notes of v start after: the last stable
// release for a stable one, the last release of any kind for a beta.
func previous(tags []version, v version) (version, bool) {
var out version
found := false
for _, t := range tags {
if t.compare(v) >= 0 || (v.Beta == 0 && t.Beta > 0) {
continue
}
if !found || t.compare(out) > 0 {
out, found = t, true
}
}
return out, found
}
func parseTags(lines []string) []version {
var out []version
for _, l := range lines {
if v, err := parseVersion(strings.TrimSpace(l)); err == nil {
out = append(out, v)
}
}
slices.SortFunc(out, version.compare)
return out
}