Compare commits
157
Commits
No files matched your search
@@ -13,6 +13,17 @@ UPTIME_PUBLIC_URL=http://localhost:8080
|
||||
# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud.
|
||||
UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
|
||||
|
||||
# Who may sign up: first-user (only the operator of a fresh installation),
|
||||
# open or closed. New accounts confirm their email address before signing in:
|
||||
# auto = always in the cloud edition, self-hosted only when UPTIME_SMTP_URL is
|
||||
# set; required; off (self-hosted only). Sign-ups per client address (IPv6:
|
||||
# per /64) in 24 hours, 0 = unlimited.
|
||||
# UPTIME_SIGNUP=first-user
|
||||
# UPTIME_SIGNUP_VERIFY=auto
|
||||
# UPTIME_SIGNUPS_PER_IP=2
|
||||
# Outgoing mail, for email channels and sign-up confirmation.
|
||||
# UPTIME_SMTP_URL=smtp://user:pass@mail.example.com:587?from=uptime@example.com
|
||||
|
||||
# Checker and status page reach the API only. Create tokens with:
|
||||
# api agent create --kind checker --region local --name dev
|
||||
# api agent create --kind statuspage --name dev
|
||||
@@ -22,6 +33,33 @@ UPTIME_API_URL=http://localhost:8080
|
||||
# Integration tests (make test). The Redis database is flushed by the tests.
|
||||
UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable
|
||||
UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
|
||||
# Database checks are also tested against these when set
|
||||
# (docker compose --profile checks up -d --wait).
|
||||
# UPTIME_TEST_MYSQL_ADDR=localhost:13306
|
||||
# UPTIME_TEST_MONGO_ADDR=localhost:27018
|
||||
# UPTIME_TEST_MSSQL_ADDR=localhost:11433
|
||||
# UPTIME_TEST_RABBITMQ_ADDR=localhost:15672
|
||||
# UPTIME_TEST_KAFKA_ADDR=localhost:19092
|
||||
|
||||
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
|
||||
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8
|
||||
|
||||
# Data retention (0 keeps forever). Raw results feed charts up to 24h, the
|
||||
# hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved
|
||||
# incidents follow the daily aggregate.
|
||||
# UPTIME_RETENTION_RAW=2160h
|
||||
# UPTIME_RETENTION_HOURLY=9600h
|
||||
# UPTIME_RETENTION_DAILY=26280h
|
||||
# Delivered notifications, expired invitations and expired API tokens.
|
||||
# UPTIME_RETENTION_HOUSEKEEPING=720h
|
||||
# Audit log entries.
|
||||
# UPTIME_RETENTION_AUDIT=8760h
|
||||
# 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
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GOLANGCI_LINT_VERSION: v2.15.0
|
||||
SQLC_VERSION: v1.31.1
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
# The runners are ephemeral and clone every action from GitHub, which
|
||||
# takes minutes; Go comes as a tarball instead, and the job image
|
||||
# already has the Node version the frontend build needs.
|
||||
- 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"
|
||||
echo "$HOME/go/bin" >> "$GITHUB_PATH"
|
||||
- name: Build frontend
|
||||
run: npm ci --no-audit --no-fund && npm run build
|
||||
- name: Generated code is up to date
|
||||
run: |
|
||||
go tool templ generate
|
||||
# The release binary avoids compiling sqlc's cgo parser.
|
||||
curl -fsSL "https://github.com/sqlc-dev/sqlc/releases/download/${SQLC_VERSION}/sqlc_${SQLC_VERSION#v}_linux_amd64.tar.gz" | tar -xz -C /usr/local/bin sqlc
|
||||
sqlc generate
|
||||
git diff --exit-code -- '*.go'
|
||||
- name: gofmt
|
||||
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 ./...
|
||||
# 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
|
||||
services:
|
||||
timescaledb:
|
||||
image: timescale/timescaledb:2.30.1-pg16
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
redis:
|
||||
image: redis:8-alpine
|
||||
# Targets of the database checks; SQL Server is left to local runs,
|
||||
# its image is too large for ephemeral runners.
|
||||
mariadb:
|
||||
image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
|
||||
env:
|
||||
MARIADB_ROOT_PASSWORD: checkpw
|
||||
MARIADB_DATABASE: shop
|
||||
options: --health-cmd "healthcheck.sh --connect" --health-interval 2s --health-retries 60
|
||||
mongo:
|
||||
image: mongo:8
|
||||
env:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: checkpw
|
||||
rabbitmq:
|
||||
image: rabbitmq:4-alpine
|
||||
env:
|
||||
RABBITMQ_DEFAULT_USER: check
|
||||
RABBITMQ_DEFAULT_PASS: checkpw
|
||||
kafka:
|
||||
image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
|
||||
env:
|
||||
KAFKA_NODE_ID: 1
|
||||
KAFKA_PROCESS_ROLES: broker,controller
|
||||
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
|
||||
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
|
||||
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
|
||||
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
|
||||
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
|
||||
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
|
||||
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
|
||||
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
|
||||
env:
|
||||
UPTIME_TEST_DATABASE_URL: postgres://uptime:uptime@timescaledb:5432/uptime_test?sslmode=disable
|
||||
UPTIME_TEST_REDIS_URL: redis://redis:6379/15
|
||||
UPTIME_TEST_MYSQL_ADDR: mariadb:3306
|
||||
UPTIME_TEST_MONGO_ADDR: mongo:27017
|
||||
UPTIME_TEST_RABBITMQ_ADDR: rabbitmq:5672
|
||||
UPTIME_TEST_KAFKA_ADDR: kafka:9092
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
# The runners are ephemeral and clone every action from GitHub, which
|
||||
# takes minutes; Go comes as a tarball instead, and the job image
|
||||
# already has the Node version the frontend build needs.
|
||||
- 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"
|
||||
echo "$HOME/go/bin" >> "$GITHUB_PATH"
|
||||
- name: Build frontend
|
||||
run: npm ci --no-audit --no-fund && npm run build
|
||||
- name: Prepare database
|
||||
# The same roles and databases as the local environment: the
|
||||
# application role must not be a superuser, or row-level security
|
||||
# is bypassed and the isolation tests prove nothing.
|
||||
run: go run ./internal/devtools/pginit "postgres://postgres:postgres@timescaledb:5432/postgres?sslmode=disable" deploy/dev/postgres-init.sql
|
||||
- name: Test
|
||||
# Integration tests share one database, so packages run one at a time.
|
||||
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
|
||||
# takes minutes; Go comes as a tarball instead, and the job image
|
||||
# already has the Node version the frontend build needs.
|
||||
- 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"
|
||||
echo "$HOME/go/bin" >> "$GITHUB_PATH"
|
||||
- name: Build frontend
|
||||
run: npm ci --no-audit --no-fund && npm run build
|
||||
- name: Build binaries
|
||||
id: binaries
|
||||
run: |
|
||||
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
|
||||
|
||||
image:
|
||||
# Kaniko runs rootless from docker:cli, the same way as the other
|
||||
# repositories on this instance: the default job image has no docker
|
||||
# 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@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d
|
||||
defaults:
|
||||
run:
|
||||
shell: sh
|
||||
steps:
|
||||
- name: Build (and push from main and tags)
|
||||
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)"
|
||||
TAG="$VERSION"
|
||||
PUSH="--no-push"
|
||||
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=""
|
||||
for c in $CHANNELS; do DEST="$DEST --destination ${IMAGE}:$c"; done
|
||||
else
|
||||
echo "PACKAGE_TOKEN is not set; building without pushing."
|
||||
fi ;;
|
||||
esac
|
||||
case "$GITHUB_SERVER_URL" in https://*) PULL=https ;; *) PULL=http ;; esac
|
||||
# Pull requests are built from their head, which Gitea exposes as
|
||||
# refs/pull/<n>/head.
|
||||
REF="$GITHUB_REF"
|
||||
case "$REF" in refs/pull/*/merge) REF="${REF%/merge}/head" ;; esac
|
||||
AUTH="$(printf '%s:%s' "$GITHUB_ACTOR" "${PACKAGE_TOKEN:-none}" | base64 | tr -d '\n')"
|
||||
CFG="$(printf '{"auths":{"%s":{"auth":"%s"}}}' "$REGISTRY" "$AUTH")"
|
||||
docker run --rm \
|
||||
-e GIT_PULL_METHOD="$PULL" \
|
||||
-e GIT_USERNAME="x-access-token" \
|
||||
-e GIT_PASSWORD="$GITEA_TOKEN" \
|
||||
-e CFG="$CFG" \
|
||||
--entrypoint /busybox/sh \
|
||||
gcr.io/kaniko-project/executor:v1.23.2-debug \
|
||||
-c 'mkdir -p /kaniko/.docker && printf %s "$CFG" > /kaniko/.docker/config.json && exec /kaniko/executor "$@"' _ \
|
||||
--context "git://${REGISTRY}/${GITHUB_REPOSITORY}.git#${REF}" \
|
||||
--dockerfile Dockerfile \
|
||||
--build-arg VERSION="$TAG" \
|
||||
--build-arg COMMIT="$SHORT" \
|
||||
$DEST $PUSH \
|
||||
--compressed-caching=false
|
||||
@@ -0,0 +1,80 @@
|
||||
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: 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 ./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/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
|
||||
@@ -8,3 +8,4 @@
|
||||
/api
|
||||
/checker
|
||||
/statuspage
|
||||
/.statuspage-cache/
|
||||
+2
-2
@@ -4,8 +4,6 @@ run:
|
||||
tests: true
|
||||
|
||||
linters:
|
||||
# staticcheck and unused are left out until honnef.co/go/tools supports
|
||||
# the Go 1.27 standard library; they panic during analysis otherwise.
|
||||
default: none
|
||||
enable:
|
||||
- errcheck
|
||||
@@ -17,6 +15,8 @@ linters:
|
||||
- misspell
|
||||
- unconvert
|
||||
- usestdlibvars
|
||||
- staticcheck
|
||||
- unused
|
||||
settings:
|
||||
revive:
|
||||
rules:
|
||||
|
||||
+2
-2
@@ -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"]
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
<img src="docs/images/logo.svg" alt="" width="260">
|
||||
|
||||
# UptimeSebi
|
||||
|
||||
[](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
|
||||
|
||||
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
|
||||
|
||||
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
|
||||
|
||||

|
||||
|
||||
**What it does**
|
||||
|
||||
- **Checks:** HTTP(S) with keyword, JSON APIs with conditions on values, Prometheus queries, TCP, TLS certificate expiry, DNS, ICMP; PostgreSQL, MySQL/MariaDB, SQL Server, MongoDB, Redis; MQTT, Kafka, RabbitMQ; gRPC health, SMTP, RADIUS, SNMP; Steam and Minecraft servers; Docker containers; heartbeats pinged by cron jobs, and Prometheus Alertmanager alerts. Credentials are stored encrypted. Platform admins can switch off types an installation cannot offer.
|
||||
- **Multi-region:** checkers run per region, several per region for load and failover; any number of regions per monitor.
|
||||
- **Alerting:** incidents with webhooks (signed), 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, 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.
|
||||
|
||||
## Installation
|
||||
|
||||
### Requirements
|
||||
|
||||
| To run | To develop |
|
||||
| --- | --- |
|
||||
| PostgreSQL 16 with TimescaleDB 2.30 | Go 1.27 |
|
||||
| Redis 8, or Redis with Sentinel | Node.js 20 or newer |
|
||||
| The container image or the binaries | Docker with Compose |
|
||||
| | [sqlc](https://sqlc.dev) 1.31 and [golangci-lint](https://golangci-lint.run) 2.12, for `make generate` and `make lint` |
|
||||
|
||||
### Run locally
|
||||
|
||||
Start PostgreSQL and Redis, build the frontend, create the schema and start the API:
|
||||
|
||||
```sh
|
||||
git clone https://git.zb-server.de/ZB-Server/uptimesebi.git
|
||||
cd uptimesebi
|
||||
cp .env.example .env
|
||||
set -a && . ./.env && set +a
|
||||
|
||||
docker compose up -d --wait
|
||||
npm ci && npm run build
|
||||
go run ./cmd/api migrate up
|
||||
go run ./cmd/api
|
||||
```
|
||||
|
||||
Open <http://localhost:8080/signup>. On a self-hosted installation the first account also becomes the platform administrator.
|
||||
|
||||
Checks need a checker, which talks to the API only. In a second terminal, with the same environment loaded:
|
||||
|
||||
```sh
|
||||
go run ./cmd/api region add local "Local"
|
||||
export UPTIME_AGENT_TOKEN="$(go run ./cmd/api agent create --kind checker --region local --name local-1)"
|
||||
go run ./cmd/checker
|
||||
```
|
||||
|
||||
Status pages are served by their own process, on <http://localhost:8082/your-page-slug>:
|
||||
|
||||
```sh
|
||||
export UPTIME_AGENT_TOKEN="$(go run ./cmd/api agent create --kind statuspage --name local)"
|
||||
UPTIME_STATUSPAGE_CACHE_DIR=./.statuspage-cache go run ./cmd/statuspage
|
||||
```
|
||||
|
||||
### Run in production
|
||||
|
||||
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 .
|
||||
docker run --rm --env-file .env uptimesebi migrate up # before every rollout
|
||||
docker run -d --env-file .env -p 8080:8080 uptimesebi
|
||||
docker run -d -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN=usa_… \
|
||||
--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:
|
||||
|
||||
- `UPTIME_SECRET_KEYS` encrypts stored secrets. Generate one with `echo "k1:$(head -c32 /dev/urandom | base64)"` and keep it safe; rotate by prepending a new key.
|
||||
- `UPTIME_PUBLIC_URL` is the address users reach the console at.
|
||||
- `UPTIME_SIGNUP` (`first-user`, `open`, `closed`) decides who may sign up. New accounts confirm their email address before signing in (`UPTIME_SIGNUP_VERIFY`: always in the cloud edition, self-hosted when `UPTIME_SMTP_URL` is set); one account per mailbox, and at most `UPTIME_SIGNUPS_PER_IP` (default 2) a day per client address.
|
||||
- `UPTIME_TRUSTED_PROXIES` must name your reverse proxy, or client addresses in the audit log and rate limits will be the proxy's.
|
||||
- `UPTIME_RETENTION_*` set how long results, aggregates, audit entries and captured responses are kept.
|
||||
|
||||
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 |
|
||||
| --- | --- | --- | --- |
|
||||
| Cloud | hosted | hosted, organizations may add their own | hosted, organizations may add their own |
|
||||
| Hybrid | hosted | at the customer | at the customer |
|
||||
| Self-hosted | at the customer | at the customer | at the customer |
|
||||
|
||||
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks.
|
||||
|
||||
## Usage
|
||||
|
||||
Work in the console, or script everything through the REST API with an API token from **Settings → API tokens**:
|
||||
|
||||
```sh
|
||||
curl -H "Authorization: Bearer ust_…" https://uptime.example.com/api/v1/org/monitors
|
||||
```
|
||||
|
||||
The interactive API documentation is at `/api/docs` of every installation, the OpenAPI 3.1 document at `/api/openapi.json`.
|
||||
|
||||
Alert groups bundle notification channels under **Settings → Notifications**. Assign one or
|
||||
more groups in the monitor editor. Each organization has a default group, automatically
|
||||
assigned to new monitors and new channels. Existing monitors and channels are migrated
|
||||
to that group to preserve delivery. The default group can be renamed and its channels
|
||||
changed, but cannot be deleted. A channel in multiple assigned groups receives each
|
||||
incident event once. Selecting no groups disables notifications for that monitor. Each group
|
||||
can also define recurring quiet hours (`quiet_hours`) in a chosen time zone to suppress its
|
||||
notifications during those periods while incidents continue to be recorded.
|
||||
|
||||
The API exposes `/api/v1/org/alert-groups` for managing groups and `alert_group_ids`
|
||||
on monitor requests and responses. Omit the field when creating a monitor to use the
|
||||
default; omit it when updating to preserve assignments. Send `[]` to remove them all.
|
||||
Deleting a custom group removes its assignments without assigning a fallback.
|
||||
|
||||
## Examples
|
||||
|
||||
Create a monitor that checks a website from two regions every minute:
|
||||
|
||||
```sh
|
||||
curl -X POST https://uptime.example.com/api/v1/org/monitors \
|
||||
-H "Authorization: Bearer ust_…" -H "Content-Type: application/json" \
|
||||
-d '{"name": "Shop", "type": "http", "target": "https://shop.example.com",
|
||||
"interval_seconds": 60, "regions": ["<region id>", "<region id>"]}'
|
||||
```
|
||||
|
||||
Report a nightly backup to a heartbeat monitor, including failures:
|
||||
|
||||
```sh
|
||||
if backup.sh > /tmp/backup.log 2>&1; then
|
||||
curl -fsS -m 10 --retry 3 https://uptime.example.com/hb/<token>
|
||||
else
|
||||
curl -fsS -m 10 --retry 3 --data-binary @/tmp/backup.log https://uptime.example.com/hb/<token>/fail
|
||||
fi
|
||||
```
|
||||
|
||||
A public status page:
|
||||
|
||||

|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
make generate # sqlc and templ code
|
||||
make test # needs the database and Redis from docker compose
|
||||
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/), 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
|
||||
|
||||
[GNU Affero General Public License v3.0 only](LICENSE) © ZB-Server.
|
||||
|
||||
If you run a modified version as a network service, you must offer its source code to its users.
|
||||
|
||||
## Contributors and contact
|
||||
|
||||
Maintained by ZB-Server. Report bugs and ideas as [issues](https://git.zb-server.de/ZB-Server/uptimesebi/issues); please include the `request_id` from error messages.
|
||||
+7
-2
@@ -30,6 +30,11 @@ const usage = `usage:
|
||||
region and agent manage platform resources shared by all organizations;
|
||||
organizations manage their own in the console.`
|
||||
|
||||
// usageError reports a command line the binary does not understand.
|
||||
type usageError struct{}
|
||||
|
||||
func (usageError) Error() string { return usage }
|
||||
|
||||
// admin runs operator commands. They act across all organizations, hence the
|
||||
// system scope, and print to stdout for humans and scripts.
|
||||
func admin(ctx context.Context, cfg config.API, args []string) error {
|
||||
@@ -96,7 +101,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error {
|
||||
return err
|
||||
})
|
||||
}
|
||||
return errors.New(usage)
|
||||
return usageError{}
|
||||
}
|
||||
|
||||
func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
|
||||
@@ -108,7 +113,7 @@ func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
|
||||
return err
|
||||
}
|
||||
if *name == "" || (*kind == "checker") != (*region != "") {
|
||||
return errors.New(usage)
|
||||
return usageError{}
|
||||
}
|
||||
var tok string
|
||||
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
|
||||
+35
-5
@@ -9,8 +9,11 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
@@ -42,18 +45,21 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
if len(args) > 0 {
|
||||
switch args[0] {
|
||||
case "migrate":
|
||||
return migrate(ctx, log, cfg.DatabaseURL, args[1:])
|
||||
return migrate(ctx, log, cfg, args[1:])
|
||||
case "admin", "agent", "region":
|
||||
return admin(ctx, cfg, args)
|
||||
case "serve":
|
||||
default:
|
||||
return errors.New(usage)
|
||||
return usageError{}
|
||||
}
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retentionOf(cfg).Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
keys, err := sealed.Parse(cfg.SecretKeys)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -74,16 +80,22 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog})
|
||||
health := platform.NewHealth(deps.Probes())
|
||||
r := platform.NewRouter(log)
|
||||
if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil {
|
||||
return err
|
||||
}
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
srv.Mount(r)
|
||||
go srv.RunScheduler(ctx)
|
||||
go srv.RunNotifier(ctx)
|
||||
go srv.RunHousekeeping(ctx)
|
||||
go srv.RunHeartbeats(ctx)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
}
|
||||
|
||||
func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) error {
|
||||
func migrate(ctx context.Context, log *slog.Logger, cfg config.API, args []string) error {
|
||||
dsn := cfg.DatabaseURL
|
||||
if dsn == "" {
|
||||
return errors.New("UPTIME_DATABASE_URL is required")
|
||||
}
|
||||
@@ -98,10 +110,13 @@ func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) e
|
||||
for _, r := range res {
|
||||
log.Info("migration applied", "migration", r.Source.Version, "file", r.Source.Path, "duration_ms", r.Duration.Milliseconds())
|
||||
}
|
||||
if err == nil && len(res) == 0 {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(res) == 0 {
|
||||
log.Info("schema up to date")
|
||||
}
|
||||
return err
|
||||
return applyRetention(ctx, log, cfg)
|
||||
case "down":
|
||||
r, err := migrations.Down(ctx, dsn)
|
||||
if r != nil {
|
||||
@@ -117,3 +132,18 @@ func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) e
|
||||
}
|
||||
return errors.New("unknown migrate command " + cmd)
|
||||
}
|
||||
|
||||
func retentionOf(cfg config.API) datapolicy.Retention {
|
||||
return datapolicy.Retention{Raw: cfg.Retention.Raw, Hourly: cfg.Retention.Hourly, Daily: cfg.Retention.Daily}
|
||||
}
|
||||
|
||||
// applyRetention runs with the migration's owner rights, which changing
|
||||
// TimescaleDB policies needs.
|
||||
func applyRetention(ctx context.Context, log *slog.Logger, cfg config.API) error {
|
||||
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
return datapolicy.Apply(ctx, pool, retentionOf(cfg), log)
|
||||
}
|
||||
+22
-1
@@ -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)
|
||||
@@ -35,7 +47,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
level.Set(cfg.LogLevel)
|
||||
if err := cfg.Common.Validate(); err != nil {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := platform.SignalContext()
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+24
-1
@@ -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)
|
||||
@@ -43,7 +54,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
level.Set(cfg.LogLevel)
|
||||
if err := cfg.Common.Validate(); err != nil {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := platform.SignalContext()
|
||||
@@ -71,6 +82,9 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
"pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) },
|
||||
})
|
||||
r := platform.NewRouter(log)
|
||||
if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil {
|
||||
return err
|
||||
}
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
pages.Mount(r)
|
||||
@@ -165,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")
|
||||
}
|
||||
@@ -50,5 +50,63 @@ services:
|
||||
<<: *sentinel
|
||||
environment: {PORT: "26381"}
|
||||
|
||||
# Databases the database checks are tested against:
|
||||
# docker compose --profile checks up -d --wait
|
||||
mariadb:
|
||||
image: mariadb:11@sha256:e1d5495f445654134f226f55a41ce0da227116f6f27f283101f405c794d841fc
|
||||
profiles: [checks]
|
||||
environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop}
|
||||
ports: ["13306:3306"]
|
||||
healthcheck:
|
||||
test: ["CMD", "healthcheck.sh", "--connect"]
|
||||
interval: 2s
|
||||
retries: 60
|
||||
|
||||
mongo:
|
||||
image: mongo:8
|
||||
profiles: [checks]
|
||||
environment: {MONGO_INITDB_ROOT_USERNAME: root, MONGO_INITDB_ROOT_PASSWORD: checkpw}
|
||||
ports: ["27018:27017"]
|
||||
healthcheck:
|
||||
test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping: 1})"]
|
||||
interval: 2s
|
||||
retries: 60
|
||||
|
||||
mssql:
|
||||
image: mcr.microsoft.com/mssql/server:2022-latest
|
||||
profiles: [checks]
|
||||
environment: {ACCEPT_EULA: "Y", MSSQL_SA_PASSWORD: "Check-pw-2026"}
|
||||
ports: ["11433:1433"]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -Q 'SELECT 1' || exit 1"]
|
||||
interval: 3s
|
||||
retries: 60
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:4-alpine
|
||||
profiles: [checks]
|
||||
environment: {RABBITMQ_DEFAULT_USER: check, RABBITMQ_DEFAULT_PASS: checkpw}
|
||||
ports: ["15672:5672"]
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
|
||||
interval: 3s
|
||||
retries: 60
|
||||
|
||||
kafka:
|
||||
image: apache/kafka-native:4.4.0@sha256:11fde816adf384402de9f3e57aeaf2c3722ba0671610247817688d07441714b4
|
||||
profiles: [checks]
|
||||
ports: ["19092:9092"]
|
||||
environment:
|
||||
KAFKA_NODE_ID: 1
|
||||
KAFKA_PROCESS_ROLES: broker,controller
|
||||
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
|
||||
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:19092
|
||||
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
|
||||
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
|
||||
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
|
||||
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
|
||||
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
|
||||
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
@@ -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}"
|
||||
@@ -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:
|
||||
@@ -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"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 48" role="img" aria-label="UptimeSebi">
|
||||
<style>
|
||||
.ink { stroke: #1c1d1f; fill: #1c1d1f }
|
||||
@media (prefers-color-scheme: dark) { .ink { stroke: #e6e3dc; fill: #e6e3dc } }
|
||||
</style>
|
||||
<path class="ink" d="M3 26h9l4-12 6 23 5-16 3 5h6" style="fill:none" stroke-width="5" stroke-linejoin="round" stroke-linecap="square"/>
|
||||
<circle cx="42" cy="26" r="5.5" fill="#2f7d4f"/>
|
||||
<text class="ink" x="58" y="34" stroke="none" font-family="IBM Plex Sans, ui-sans-serif, system-ui, sans-serif" font-weight="600" font-size="26" letter-spacing="-0.3">UptimeSebi</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 629 B |
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@@ -1,32 +1,53 @@
|
||||
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
|
||||
github.com/caarlos0/env/v11 v11.4.2
|
||||
github.com/caddyserver/certmagic v0.25.6
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/go-jose/go-jose/v4 v4.1.4
|
||||
github.com/go-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
|
||||
github.com/microsoft/go-mssqldb v1.12.0
|
||||
github.com/mochi-mqtt/server/v2 v2.7.9
|
||||
github.com/nbd-wtf/go-nostr v0.52.3
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/pressly/goose/v3 v3.30.1
|
||||
github.com/rabbitmq/amqp091-go v1.17.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
github.com/twmb/franz-go v1.22.3
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.15.1
|
||||
github.com/yuin/goldmark v1.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
|
||||
google.golang.org/grpc v1.85.0
|
||||
layeh.com/radius v0.0.0-20231213012653-1006025d24f8
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 // indirect
|
||||
github.com/a-h/parse v0.0.42 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect
|
||||
github.com/btcsuite/btcd/btcutil v1.1.5 // indirect
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
@@ -35,6 +56,10 @@ require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cli/browser v1.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/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
|
||||
@@ -43,13 +68,19 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
|
||||
github.com/golang-sql/sqlexp v0.1.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/libdns/libdns v1.1.1 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mfridman/interpolate v0.2.0 // indirect
|
||||
@@ -58,23 +89,40 @@ 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
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/rs/xid v1.4.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/shopspring/decimal v1.6.0 // indirect
|
||||
github.com/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
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.2.0 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap/exp v0.3.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 // indirect
|
||||
golang.org/x/mod v0.43.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/tools v0.52.0 // indirect
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gotest.tools/v3 v3.5.2 // indirect
|
||||
)
|
||||
|
||||
tool github.com/a-h/templ/cmd/templ
|
||||
@@ -1,11 +1,28 @@
|
||||
code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
|
||||
code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 h1:w3gDUJlJ0BfBsHH02DCBDwbkmMSXJqBj6nBOCo9iocY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0/go.mod h1:7scl8mG/IFLVjJ9ef/ltdND2T1z0CkgVSaQoUxLvmeU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0 h1:MaKvxE6D0KkjOg6Wd9M00iqP5PR0kUxCfiezes4JweM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0/go.mod h1:i2h9fsTFKZorh8RdV2IcSUf/Qj98GlTkrTvUbX/s8as=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0/go.mod h1:ucUjca2JtSZboY8IoUqyQyuuXvwbMBVwFOm0vdQPNhA=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 h1:0O6j18nQDoIff6/mtosT5LNU2WehEwp+LqfX6699oqY=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1/go.mod h1:xdYAf5bjkOpsd3auA8riiJW4vneBubt9caavL7626jQ=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 h1:ClzzXMDDuUbWfNNZqGeYq4PnYOlwlOVIvSyNaIy0ykg=
|
||||
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3/go.mod h1:we0YA5CsBbH5+/NUzC/AlMmxaDtWlXeNsqrwXjTzmzA=
|
||||
github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ=
|
||||
github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w=
|
||||
github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI=
|
||||
github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjPuCS4=
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
|
||||
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
|
||||
@@ -14,6 +31,30 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M=
|
||||
github.com/btcsuite/btcd v0.23.5-0.20231215221805-96c9fd8078fd/go.mod h1:nm3Bko6zh6bWP60UxwoT5LzdGJsQJaPo6HjduXq9p6A=
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA=
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE=
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.3.4 h1:3EJjcN70HCu/mwqlUsGK8GcNVyLVxFDlWurTXGPFfiQ=
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.3.4/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
|
||||
github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A=
|
||||
github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE=
|
||||
github.com/btcsuite/btcd/btcutil v1.1.5 h1:+wER79R5670vs/ZusMTF1yTcRYE5GUsFbdjdisflzM8=
|
||||
github.com/btcsuite/btcd/btcutil v1.1.5/go.mod h1:PSZZ4UitpLBWzxGd5VGOrLnmOjtPP/a6HaFo12zMs00=
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ=
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
|
||||
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
|
||||
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
|
||||
github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I=
|
||||
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
|
||||
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
|
||||
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
@@ -34,15 +75,34 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
|
||||
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
|
||||
github.com/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=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
@@ -51,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=
|
||||
@@ -61,15 +121,44 @@ github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dm
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo=
|
||||
github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4=
|
||||
github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0=
|
||||
github.com/go-sql-driver/mysql v1.10.2/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
|
||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/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=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gosnmp/gosnmp v1.47.0 h1:nQ0H9erruu03QP0lviAJ6vB6iiIGE0R5u73MKFr6QPs=
|
||||
github.com/gosnmp/gosnmp v1.47.0/go.mod h1:LWPVcDKeRsiioQGeITGTQha4mdlx9lgmRmXz6zGINQ4=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -78,10 +167,26 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg=
|
||||
github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=
|
||||
@@ -90,6 +195,8 @@ github.com/letsencrypt/pebble/v2 v2.10.1 h1:oKHx3lgN4e5Nno2LKTMrVx+b+NkDptkO9aDi
|
||||
github.com/letsencrypt/pebble/v2 v2.10.1/go.mod h1:KtYhQ4YTjT5MtoCZ6RTCXlbrrz6cKyXROCuTpIUDJFY=
|
||||
github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
|
||||
github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
|
||||
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
|
||||
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
|
||||
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
@@ -98,8 +205,12 @@ github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48
|
||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
||||
github.com/mholt/acmez/v3 v3.1.7 h1:XTqpuUcRdRoIBuDoI+M4mCnRnPTPN4rqH3Mb723Rg4U=
|
||||
github.com/mholt/acmez/v3 v3.1.7/go.mod h1:Lwv6P/czh/AOq+c99tAzP68/VP92s+8y+hDs4FCgxvo=
|
||||
github.com/microsoft/go-mssqldb v1.12.0 h1:Jwg/8jz2MKlFOYf4Oj7wMOQuTpCLrP4PIx0aINasMfw=
|
||||
github.com/microsoft/go-mssqldb v1.12.0/go.mod h1:iYsISdcqI4Tf8x/JwwkHfBu5pxtSD6lSJB8tCrOoo6E=
|
||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
github.com/mochi-mqtt/server/v2 v2.7.9 h1:y0g4vrSLAag7T07l2oCzOa/+nKVLoazKEWAArwqBNYI=
|
||||
github.com/mochi-mqtt/server/v2 v2.7.9/go.mod h1:lZD3j35AVNqJL5cezlnSkuG05c0FCHSsfAKSPBOSbqc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -107,32 +218,64 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
|
||||
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
|
||||
github.com/nbd-wtf/go-nostr v0.52.3 h1:Xd87pXfJEJRXHpM+fLjQQln8dBNNaoPA10V7BbyP4KI=
|
||||
github.com/nbd-wtf/go-nostr v0.52.3/go.mod h1:4avYoc9mDGZ9wHsvCOhHH9vPzKucCfuYBtJUSpHTfNk=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
|
||||
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/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=
|
||||
github.com/pierrec/lz4/v4 v4.1.33/go.mod h1:7SE9MC2STkNtL4PIwGhjmyVwvILaGI9/COYQNBhKM/c=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
|
||||
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/rs/xid v1.4.0 h1:qd7wPTDkN6KQx2VmMBLrpHkiyQwgFXRnkOLacUiaSNY=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4=
|
||||
github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/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=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
@@ -140,12 +283,35 @@ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/twmb/franz-go v1.22.3 h1:RHe35s34pKefMLyL+ZYJ6mQVtfFZz4zHDHVkTyACur0=
|
||||
github.com/twmb/franz-go v1.22.3/go.mod h1:OhbFLkvp6GLcN5daC7I4Q2z0W/rFP16HG+gTbe9CDC4=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.15.1 h1:3sj7ekbH33t73nsBcHS0wtp/PyMIViHLNItZrE8V9zM=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.15.1/go.mod h1:sGkGxKexpRLBThFHJLjjywcyfkK09qB/g+X+wFWZQ/A=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
|
||||
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/goldmark v1.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=
|
||||
@@ -172,27 +338,112 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/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=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
|
||||
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
|
||||
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
|
||||
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640=
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
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=
|
||||
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
|
||||
@@ -78,6 +78,9 @@ type Result struct {
|
||||
LatencyMS int `json:"latency_ms"`
|
||||
StatusCode int `json:"status_code,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// Evidence is what the check saw (check.Evidence), sent only now and
|
||||
// then to bound traffic; see the checker's policy.
|
||||
Evidence json.RawMessage `json:"evidence,omitempty"`
|
||||
}
|
||||
|
||||
// ResultsRequest reports finished checks in a batch.
|
||||
@@ -177,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 {
|
||||
|
||||
+252
-5
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -14,6 +15,8 @@ const (
|
||||
PageDegraded = "degraded"
|
||||
PageOutage = "outage"
|
||||
PageUnknown = "unknown"
|
||||
// PageUnderMaintenance marks planned maintenance in progress.
|
||||
PageUnderMaintenance = "maintenance"
|
||||
)
|
||||
|
||||
// Theme customizes a page.
|
||||
@@ -31,19 +34,53 @@ type Day struct {
|
||||
Uptime float64 `json:"uptime"`
|
||||
}
|
||||
|
||||
// HourBucket is one hourly summary of a component's recent 24-hour history.
|
||||
// Uptime is -1 when no checks were recorded during that hour.
|
||||
type HourBucket struct {
|
||||
Time time.Time `json:"time"`
|
||||
Uptime float64 `json:"uptime"`
|
||||
AvgLatencyMS int `json:"avg_latency_ms"`
|
||||
}
|
||||
|
||||
// ComponentRegion is the public status of one monitoring region for a
|
||||
// component. Error details and checker IDs stay private.
|
||||
type ComponentRegion struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
LatencyMS int `json:"latency_ms,omitempty"`
|
||||
}
|
||||
|
||||
// ComponentDetails holds the public metrics shown on a component's detail page
|
||||
// when the status page opts in via ShowDetails.
|
||||
type ComponentDetails struct {
|
||||
SLA24h float64 `json:"sla_24h"`
|
||||
SLA7d float64 `json:"sla_7d"`
|
||||
SLA30d float64 `json:"sla_30d"`
|
||||
SLA90d float64 `json:"sla_90d"`
|
||||
Hours []HourBucket `json:"hours,omitempty"`
|
||||
Regions []ComponentRegion `json:"regions,omitempty"`
|
||||
}
|
||||
|
||||
// Component is one monitor as the public sees it. Targets, check details
|
||||
// and error messages stay private.
|
||||
type Component struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Uptime float64 `json:"uptime"`
|
||||
Days []Day `json:"days"`
|
||||
// ID identifies the component on detail URLs when ShowDetails is enabled.
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Uptime float64 `json:"uptime"`
|
||||
Days []Day `json:"days"`
|
||||
Details *ComponentDetails `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// Section groups components under a heading; the first may be unnamed.
|
||||
// Section groups components and nested child sections under a heading; a
|
||||
// top-level section with an empty Name holds ungrouped components.
|
||||
type Section struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Total int `json:"total,omitempty"`
|
||||
Components []Component `json:"components"`
|
||||
Children []Section `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
// PageIncident is an incident of a listed component.
|
||||
@@ -60,9 +97,219 @@ type PageSnapshot struct {
|
||||
Description string `json:"description"`
|
||||
Theme Theme `json:"theme"`
|
||||
Status string `json:"status"`
|
||||
ShowDetails bool `json:"show_details,omitempty"`
|
||||
Sections []Section `json:"sections"`
|
||||
Incidents []PageIncident `json:"incidents"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
// Legal holds the legal notice and privacy policy shown on the page.
|
||||
// They travel with the snapshot so they stay available during an API
|
||||
// outage, which some jurisdictions require.
|
||||
Legal []LegalDoc `json:"legal,omitempty"`
|
||||
// Maintenance lists occurrences of planned maintenance from shortly
|
||||
// before generation to two weeks ahead. Whether one is in progress is
|
||||
// decided when the page is shown, see WithMaintenance, so a cached
|
||||
// snapshot stays right while the API is unreachable.
|
||||
Maintenance []PageMaintenance `json:"maintenance,omitempty"`
|
||||
}
|
||||
|
||||
// PageMaintenance is one occurrence of planned maintenance.
|
||||
type PageMaintenance struct {
|
||||
Title string `json:"title"`
|
||||
// Description is Markdown.
|
||||
Description string `json:"description,omitempty"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
// Components are the names of the affected components.
|
||||
Components []string `json:"components"`
|
||||
}
|
||||
|
||||
// Summarize derives a page or group state from component states. Unknown
|
||||
// components do not make a page look broken, and a single failed component is
|
||||
// a partial problem: only when all fail is it an outage.
|
||||
func Summarize(states []string) string {
|
||||
rank := map[string]int{PageOperational: 0, PageUnknown: 0, PageDegraded: 1, PageOutage: 2}
|
||||
worst, allUnknown, allDown := PageOperational, true, len(states) > 0
|
||||
for _, s := range states {
|
||||
if rank[s] > rank[worst] {
|
||||
worst = s
|
||||
}
|
||||
allUnknown = allUnknown && s == PageUnknown
|
||||
allDown = allDown && s == PageOutage
|
||||
}
|
||||
switch {
|
||||
case allUnknown:
|
||||
return PageUnknown
|
||||
case worst == PageOutage && !allDown:
|
||||
return PageDegraded
|
||||
}
|
||||
return worst
|
||||
}
|
||||
|
||||
func summarizeWithMaintenance(states []string, hasMaintenance bool) string {
|
||||
if len(states) == 0 {
|
||||
if hasMaintenance {
|
||||
return PageUnderMaintenance
|
||||
}
|
||||
return PageUnknown
|
||||
}
|
||||
status := Summarize(states)
|
||||
if hasMaintenance && (status == PageOperational || status == PageUnknown) {
|
||||
return PageUnderMaintenance
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// WithMaintenance returns s as of now: components under maintenance in
|
||||
// progress show as such and the page and group states reflect it.
|
||||
func (s PageSnapshot) WithMaintenance(now time.Time) PageSnapshot {
|
||||
affected := map[string]bool{}
|
||||
for _, m := range s.Maintenance {
|
||||
if !now.Before(m.Start) && now.Before(m.End) {
|
||||
for _, c := range m.Components {
|
||||
affected[c] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(affected) == 0 {
|
||||
return s
|
||||
}
|
||||
var allStates []string
|
||||
var anyMaint bool
|
||||
var apply func(src Section) (Section, []string, bool)
|
||||
apply = func(src Section) (Section, []string, bool) {
|
||||
dst := Section{
|
||||
Name: src.Name,
|
||||
Total: src.Total,
|
||||
Components: make([]Component, len(src.Components)),
|
||||
}
|
||||
var subStates []string
|
||||
subMaint := false
|
||||
for i, c := range src.Components {
|
||||
if affected[c.Name] {
|
||||
c.Status = PageUnderMaintenance
|
||||
subMaint = true
|
||||
} else {
|
||||
subStates = append(subStates, c.Status)
|
||||
}
|
||||
dst.Components[i] = c
|
||||
}
|
||||
if len(src.Children) > 0 {
|
||||
dst.Children = make([]Section, len(src.Children))
|
||||
for i, child := range src.Children {
|
||||
var childStates []string
|
||||
var childMaint bool
|
||||
dst.Children[i], childStates, childMaint = apply(child)
|
||||
subStates = append(subStates, childStates...)
|
||||
subMaint = subMaint || childMaint
|
||||
}
|
||||
}
|
||||
if dst.Name != "" {
|
||||
dst.Status = summarizeWithMaintenance(subStates, subMaint)
|
||||
}
|
||||
return dst, subStates, subMaint
|
||||
}
|
||||
|
||||
sections := make([]Section, len(s.Sections))
|
||||
for i, sec := range s.Sections {
|
||||
var states []string
|
||||
var maint bool
|
||||
sections[i], states, maint = apply(sec)
|
||||
allStates = append(allStates, states...)
|
||||
anyMaint = anyMaint || maint
|
||||
}
|
||||
s.Sections = sections
|
||||
s.Status = summarizeWithMaintenance(allStates, anyMaint)
|
||||
return s
|
||||
}
|
||||
|
||||
// ComponentByID finds a component anywhere in s.Sections by its ID.
|
||||
func (s PageSnapshot) ComponentByID(id string) (Component, bool) {
|
||||
if id == "" {
|
||||
return Component{}, false
|
||||
}
|
||||
var find func(secs []Section) (Component, bool)
|
||||
find = func(secs []Section) (Component, bool) {
|
||||
for _, sec := range secs {
|
||||
for _, c := range sec.Components {
|
||||
if c.ID == id {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
if c, ok := find(sec.Children); ok {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
return Component{}, false
|
||||
}
|
||||
return find(s.Sections)
|
||||
}
|
||||
|
||||
// IncidentsForComponent returns incidents belonging to componentName.
|
||||
func (s PageSnapshot) IncidentsForComponent(componentName string) []PageIncident {
|
||||
var out []PageIncident
|
||||
for _, inc := range s.Incidents {
|
||||
if inc.Component == componentName {
|
||||
out = append(out, inc)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MaintenanceForComponent splits planned maintenance affecting componentName
|
||||
// into ongoing and upcoming occurrences at now.
|
||||
func (s PageSnapshot) MaintenanceForComponent(componentName string, now time.Time) (ongoing, upcoming []PageMaintenance) {
|
||||
for _, m := range s.Maintenance {
|
||||
if !slices.Contains(m.Components, componentName) {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case !now.Before(m.Start) && now.Before(m.End):
|
||||
ongoing = append(ongoing, m)
|
||||
case now.Before(m.Start):
|
||||
upcoming = append(upcoming, m)
|
||||
}
|
||||
}
|
||||
return ongoing, upcoming
|
||||
}
|
||||
|
||||
// Ongoing returns occurrences in progress at now.
|
||||
func (s PageSnapshot) Ongoing(now time.Time) []PageMaintenance {
|
||||
var out []PageMaintenance
|
||||
for _, m := range s.Maintenance {
|
||||
if !now.Before(m.Start) && now.Before(m.End) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Upcoming returns occurrences that have not started at now.
|
||||
func (s PageSnapshot) Upcoming(now time.Time) []PageMaintenance {
|
||||
var out []PageMaintenance
|
||||
for _, m := range s.Maintenance {
|
||||
if now.Before(m.Start) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LegalDoc is a legal notice ("imprint") or privacy policy ("privacy"):
|
||||
// a link to a page elsewhere or Markdown to render.
|
||||
type LegalDoc struct {
|
||||
Kind string `json:"kind"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Markdown string `json:"markdown,omitempty"`
|
||||
}
|
||||
|
||||
// LegalDocByKind returns the document of kind, if any.
|
||||
func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) {
|
||||
for _, d := range s.Legal {
|
||||
if d.Kind == kind {
|
||||
return d, true
|
||||
}
|
||||
}
|
||||
return LegalDoc{}, false
|
||||
}
|
||||
|
||||
// ErrNotFound means no published page matches.
|
||||
|
||||
@@ -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}})
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,9 @@ func (s *Server) resolvePrincipal(c *gin.Context) (*principal, int, string, erro
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if p.Org.SuspendedAt != nil {
|
||||
return nil, http.StatusForbidden, "org_suspended", nil
|
||||
}
|
||||
if code := policyViolation(p.Org, p.Grants.Owner, sess); code != "" {
|
||||
return nil, http.StatusForbidden, code, nil
|
||||
}
|
||||
|
||||
+133
-14
@@ -5,18 +5,24 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"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.
|
||||
@@ -32,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)
|
||||
@@ -74,7 +81,15 @@ func (s *Server) agentAuth() gin.HandlerFunc {
|
||||
if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release})
|
||||
// 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
|
||||
}
|
||||
return q.TouchAgentInstance(ctx, store.TouchAgentInstanceParams{ID: instance, AgentID: a.ID, OrgID: a.OrgID, Release: release})
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
@@ -114,12 +129,6 @@ func regionOf(c *gin.Context) string {
|
||||
return ""
|
||||
}
|
||||
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
|
||||
func (s *Server) allowPrivate(a store.GetAgentByHashRow) bool {
|
||||
// Operator checkers in the cloud share our network; customers must not
|
||||
// reach it through them. Customer-run checkers and self-hosted
|
||||
// installations check whatever their operator can reach.
|
||||
return !s.cloud() || a.OrgID != nil
|
||||
}
|
||||
|
||||
func (s *Server) agentHello(c *gin.Context) {
|
||||
a := agentOf(c)
|
||||
@@ -129,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) {
|
||||
@@ -146,20 +200,23 @@ func (s *Server) agentJobs(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
jobs, err := s.resolveJobs(ctx, agentOf(c), entries)
|
||||
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.trackRunning(ctx, instance, jobs, orgs)
|
||||
c.JSON(http.StatusOK, agentapi.JobsResponse{Jobs: jobs})
|
||||
}
|
||||
|
||||
// resolveJobs attaches the current monitor settings to dispatched runs.
|
||||
// Checking is cross-tenant work, hence the system scope.
|
||||
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, error) {
|
||||
// It also returns each monitor's organization.
|
||||
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, map[uuid.UUID]uuid.UUID, error) {
|
||||
jobs := []agentapi.Job{}
|
||||
orgs := map[uuid.UUID]uuid.UUID{}
|
||||
if len(entries) == 0 {
|
||||
return jobs, nil
|
||||
return jobs, orgs, nil
|
||||
}
|
||||
ids := make([]uuid.UUID, len(entries))
|
||||
for i, e := range entries {
|
||||
@@ -172,8 +229,9 @@ func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, ent
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
allowPrivate := s.allowPrivate(ctx, a)
|
||||
byID := make(map[uuid.UUID]store.Monitor, len(rows))
|
||||
for _, m := range rows {
|
||||
byID[m.ID] = m
|
||||
@@ -183,12 +241,18 @@ func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, ent
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
cfg, err := s.openMonitorConfig(check.Type(m.Type), m.Config)
|
||||
if err != nil {
|
||||
s.log.ErrorContext(ctx, "opening monitor secrets failed", "monitor", m.ID, "error", err)
|
||||
continue
|
||||
}
|
||||
jobs = append(jobs, agentapi.Job{
|
||||
MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target,
|
||||
TimeoutMS: int(m.TimeoutMs), Config: m.Config, AllowPrivate: s.allowPrivate(a),
|
||||
TimeoutMS: int(m.TimeoutMs), Config: cfg, AllowPrivate: allowPrivate,
|
||||
})
|
||||
orgs[m.ID] = m.OrgID
|
||||
}
|
||||
return jobs, nil
|
||||
return jobs, orgs, nil
|
||||
}
|
||||
|
||||
func (s *Server) agentResults(c *gin.Context) {
|
||||
@@ -202,6 +266,12 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
region, instance := regionOf(c), instanceOf(c)
|
||||
fresh, seen, err := s.claimResults(ctx, instance, req.Results)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
req.Results = fresh
|
||||
ids := make([]uuid.UUID, len(req.Results))
|
||||
for i, r := range req.Results {
|
||||
ids[i] = r.MonitorID
|
||||
@@ -209,7 +279,7 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
now := time.Now()
|
||||
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
|
||||
var accepted []agentapi.Result
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
a := agentOf(c)
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
|
||||
if err != nil {
|
||||
@@ -248,10 +318,14 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
// Unclaimed, the checker's retry is stored instead.
|
||||
s.unclaimResults(context.WithoutCancel(ctx), seen)
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
s.storeEvidence(ctx, region, instance, accepted, monitors)
|
||||
s.finishRunning(ctx, instance, accepted)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -273,3 +347,48 @@ func truncateValid(s string, n int) string {
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
// resultClaimTTL covers the retries of a checker that lost the answer to a
|
||||
// report, which happen within minutes.
|
||||
const resultClaimTTL = 2 * time.Hour
|
||||
|
||||
// claimResults drops results already received. A checker that does not get
|
||||
// the answer to a report, say because the connection broke while the API was
|
||||
// still working, sends the batch again; without this, the retry would be
|
||||
// stored twice. A run is identified by instance, monitor and schedule time.
|
||||
// It returns the new results and the claim keys to release if storing fails.
|
||||
func (s *Server) claimResults(ctx context.Context, instance uuid.UUID, results []agentapi.Result) ([]agentapi.Result, []string, error) {
|
||||
if len(results) == 0 {
|
||||
return results, nil, nil
|
||||
}
|
||||
keys := make([]string, len(results))
|
||||
cmds := make([]*redis.BoolCmd, len(results))
|
||||
_, err := s.rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
|
||||
for i, r := range results {
|
||||
keys[i] = "result:" + instance.String() + ":" + r.MonitorID.String() + ":" + strconv.FormatInt(r.ScheduledAt.UnixMilli(), 10)
|
||||
cmds[i] = p.SetNX(ctx, keys[i], 1, resultClaimTTL)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fresh := results[:0:0]
|
||||
var claimed []string
|
||||
for i, r := range results {
|
||||
if cmds[i].Val() {
|
||||
fresh = append(fresh, r)
|
||||
claimed = append(claimed, keys[i])
|
||||
}
|
||||
}
|
||||
return fresh, claimed, nil
|
||||
}
|
||||
|
||||
func (s *Server) unclaimResults(ctx context.Context, keys []string) {
|
||||
if len(keys) == 0 {
|
||||
return
|
||||
}
|
||||
if err := s.rdb.Del(ctx, keys...).Err(); err != nil {
|
||||
s.log.WarnContext(ctx, "releasing result claims failed", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type alertGroupRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
ChannelIDs []uuid.UUID `json:"channel_ids" binding:"max=200"`
|
||||
// QuietHours suppresses notifications from this group during the given
|
||||
// windows. Omitting it on update preserves existing quiet hours; an
|
||||
// empty array clears them.
|
||||
QuietHours []quietHourRequest `json:"quiet_hours" binding:"max=20"`
|
||||
}
|
||||
|
||||
type alertGroupView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
ChannelIDs []uuid.UUID `json:"channel_ids"`
|
||||
QuietHours []quietHourView `json:"quiet_hours"`
|
||||
}
|
||||
|
||||
var errInvalidAlertGroup = errors.New("api: invalid alert group")
|
||||
var errInvalidChannel = errors.New("api: invalid notification channel")
|
||||
|
||||
func (s *Server) listAlertGroups(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
out := []alertGroupView{}
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
rows, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, alertGroupView{
|
||||
ID: row.ID, Name: row.Name, IsDefault: row.IsDefault,
|
||||
ChannelIDs: row.ChannelIds, QuietHours: decodeQuietHours(row.QuietHours),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"alert_groups": out})
|
||||
}
|
||||
|
||||
func (s *Server) saveAlertGroup(c *gin.Context) {
|
||||
var req alertGroupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
var id uuid.UUID
|
||||
if c.Param("id") != "" {
|
||||
var err error
|
||||
id, err = uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
}
|
||||
var quietRaw []byte
|
||||
switch {
|
||||
case req.QuietHours != nil:
|
||||
qh, code := validateQuietHours(req.QuietHours)
|
||||
if code != "" {
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return
|
||||
}
|
||||
var err error
|
||||
quietRaw, err = json.Marshal(qh)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
case c.Param("id") == "":
|
||||
quietRaw = []byte("[]")
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
p := current(c)
|
||||
var row store.AlertGroup
|
||||
// Stable ordering also avoids deadlocks when concurrent edits share channels.
|
||||
slices.SortFunc(req.ChannelIDs, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
req.ChannelIDs = slices.Compact(req.ChannelIDs)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if c.Param("id") == "" {
|
||||
row, err = q.CreateAlertGroup(ctx, store.CreateAlertGroupParams{OrgID: p.Org.ID, Name: req.Name, QuietHours: quietRaw})
|
||||
} else {
|
||||
row, err = q.UpdateAlertGroup(ctx, store.UpdateAlertGroupParams{ID: id, Name: req.Name, QuietHours: quietRaw})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteAlertGroupChannels(ctx, row.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ch := range req.ChannelIDs {
|
||||
n, err := q.AddAlertGroupChannel(ctx, store.AddAlertGroupChannelParams{OrgID: p.Org.ID, GroupID: row.ID, ChannelID: ch})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errInvalidChannel
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errInvalidChannel) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_channel")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if c.Param("id") == "" {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
if req.ChannelIDs == nil {
|
||||
req.ChannelIDs = []uuid.UUID{}
|
||||
}
|
||||
c.JSON(status, alertGroupView{
|
||||
ID: row.ID, Name: row.Name, IsDefault: row.IsDefault,
|
||||
ChannelIDs: req.ChannelIDs, QuietHours: decodeQuietHours(row.QuietHours),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) deleteAlertGroup(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
n, err = q.DeleteAlertGroup(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "alert_group_not_deletable")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// setMonitorAlertGroups preserves assignments when ids is omitted. On creation,
|
||||
// the database assigns the default group; an explicit empty list opts out.
|
||||
func setMonitorAlertGroups(ctx context.Context, q *store.Queries, m store.Monitor, ids []uuid.UUID) error {
|
||||
if ids == nil {
|
||||
return nil
|
||||
}
|
||||
if err := q.DeleteMonitorAlertGroups(ctx, m.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
n, err := q.AddMonitorAlertGroup(ctx, store.AddMonitorAlertGroupParams{OrgID: m.OrgID, MonitorID: m.ID, GroupID: id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errInvalidAlertGroup
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAlertGroups(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("ag")+".test", uniq("ag-"))
|
||||
groups := func(b *browser) []any {
|
||||
t.Helper()
|
||||
st, body := b.do("GET", "/api/v1/org/alert-groups", nil)
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("list groups = %d %v", st, body)
|
||||
}
|
||||
return body["alert_groups"].([]any)
|
||||
}
|
||||
initial := groups(owner)
|
||||
if len(initial) != 1 || initial[0].(map[string]any)["is_default"] != true {
|
||||
t.Fatalf("initial groups = %v", initial)
|
||||
}
|
||||
defaultID := initial[0].(map[string]any)["id"].(string)
|
||||
channel := func(b *browser, name string, enabled bool) string {
|
||||
t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/org/channels", map[string]any{"name": name, "type": "webhook", "url": "https://example.test/hook", "enabled": enabled})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create channel = %d %v", st, body)
|
||||
}
|
||||
return body["channel"].(map[string]any)["id"].(string)
|
||||
}
|
||||
selected := channel(owner, "Selected", true)
|
||||
unselected := channel(owner, "Unselected", true)
|
||||
disabled := channel(owner, "Disabled", false)
|
||||
if got := groups(owner)[0].(map[string]any)["channel_ids"].([]any); len(got) != 3 {
|
||||
t.Fatalf("default channels = %v", got)
|
||||
}
|
||||
group := func(name string, channels []string) string {
|
||||
t.Helper()
|
||||
st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": name, "channel_ids": channels})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create group = %d %v", st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
a := group("Operations", []string{selected, selected, disabled})
|
||||
b := group("Escalation", []string{selected})
|
||||
monitor := map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600}
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
token := body["target"].(string)
|
||||
if got := body["alert_group_ids"].([]any); len(got) != 1 || got[0] != defaultID {
|
||||
t.Fatalf("default monitor assignments = %v", got)
|
||||
}
|
||||
st, _, html := owner.page("/monitors/" + id + "/edit")
|
||||
if st != http.StatusOK || !strings.Contains(html, `name="alert_group_ids"`) || !strings.Contains(html, "Operations") {
|
||||
t.Fatalf("monitor editor = %d, lacks alert groups", st)
|
||||
}
|
||||
st, _, html = owner.page("/settings/channels")
|
||||
if st != http.StatusOK || !strings.Contains(html, "/org/alert-groups/"+a) {
|
||||
t.Fatalf("settings = %d, lacks alert group editor", st)
|
||||
}
|
||||
monitor["alert_group_ids"] = []string{a, b, a}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("assign groups = %d %v", st, body)
|
||||
}
|
||||
delete(monitor, "alert_group_ids")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("preserve assignments = %d %v", st, body)
|
||||
}
|
||||
// Exercise actual incident transitions and their outbox, including recovery.
|
||||
for _, suffix := range []string{"/fail", ""} {
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
count := func(ch string) int {
|
||||
return e.count(t, `SELECT count(*) FROM notifications n JOIN incidents i ON i.id=n.incident_id WHERE i.monitor_id=$1 AND n.channel_id=$2`, id, ch)
|
||||
}
|
||||
if count(selected) != 2 || count(unselected) != 0 || count(disabled) != 0 {
|
||||
t.Fatalf("deliveries selected/unselected/disabled = %d/%d/%d", count(selected), count(unselected), count(disabled))
|
||||
}
|
||||
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("ag")+".test", uniq("agx-"))
|
||||
foreignGroup := groups(other)[0].(map[string]any)["id"].(string)
|
||||
foreignChannel := channel(other, "Foreign", true)
|
||||
monitor["alert_group_ids"] = []string{foreignGroup}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
expect(t, "foreign monitor assignment", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
expect(t, "foreign assignment on creation", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Changed", "channel_ids": []string{foreignChannel}})
|
||||
expect(t, "foreign channel assignment", st, body, http.StatusUnprocessableEntity, "invalid_channel")
|
||||
st, body = other.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Stolen"})
|
||||
expect(t, "foreign group update", st, body, http.StatusNotFound, "not_found")
|
||||
for _, g := range groups(owner) {
|
||||
g := g.(map[string]any)
|
||||
if g["id"] == a && (g["name"] != "Operations" || len(g["channel_ids"].([]any)) != 2) {
|
||||
t.Fatalf("failed update changed group: %v", g)
|
||||
}
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
monitors := body["monitors"].([]any)
|
||||
if len(monitors) != 1 || len(monitors[0].(map[string]any)["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("failed assignment changed monitors: %v", monitors)
|
||||
}
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("ag")+".test", owner.roleID("viewer")))
|
||||
st, body = viewer.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": "Forbidden"})
|
||||
expect(t, "viewer creates group", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+defaultID, nil)
|
||||
expect(t, "protected default", st, body, http.StatusNotFound, "alert_group_not_deletable")
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+defaultID, map[string]any{"name": "Standard", "channel_ids": []string{selected}})
|
||||
if st != http.StatusOK || body["is_default"] != true {
|
||||
t.Fatalf("edit default = %d %v", st, body)
|
||||
}
|
||||
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+a, nil)
|
||||
expect(t, "delete custom group", st, body, http.StatusNoContent, "")
|
||||
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
assigned := body["monitors"].([]any)[0].(map[string]any)["alert_group_ids"].([]any)
|
||||
if !slices.Equal(assigned, []any{b}) {
|
||||
t.Fatalf("assignments after group deletion = %v", assigned)
|
||||
}
|
||||
monitor["alert_group_ids"] = []string{}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 0 {
|
||||
t.Fatalf("clear assignments = %d %v", st, body)
|
||||
}
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+"/fail", "text/plain", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || count(selected) != 2 {
|
||||
t.Fatalf("unassigned monitor queued notifications, status=%d count=%d", resp.StatusCode, count(selected))
|
||||
}
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
if st != http.StatusCreated || len(body["alert_group_ids"].([]any)) != 0 {
|
||||
t.Fatalf("explicit empty creation = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertGroupQuietHours(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("q@"+uniq("agq")+".test", uniq("agq-"))
|
||||
channel := func(name string) string {
|
||||
t.Helper()
|
||||
req := map[string]any{
|
||||
"name": name,
|
||||
"type": "webhook",
|
||||
"url": "https://example.test/hook",
|
||||
"enabled": true,
|
||||
}
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", req)
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("POST /api/v1/org/channels = %d %v, want %d", st, body, http.StatusCreated)
|
||||
}
|
||||
return body["channel"].(map[string]any)["id"].(string)
|
||||
}
|
||||
quietCh := channel("QuietOnly")
|
||||
sharedCh := channel("Shared")
|
||||
activeCh := channel("ActiveOnly")
|
||||
|
||||
// Invalid quiet hours are rejected.
|
||||
st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
|
||||
"name": "BadTZ",
|
||||
"channel_ids": []string{quietCh},
|
||||
"quiet_hours": []map[string]any{{"start": "22:00", "end": "07:00", "time_zone": "Not/AZone"}},
|
||||
})
|
||||
expect(t, "invalid timezone", st, body, http.StatusUnprocessableEntity, "invalid_time_zone")
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
|
||||
"name": "BadRange",
|
||||
"channel_ids": []string{quietCh},
|
||||
"quiet_hours": []map[string]any{{"start": "12:00", "end": "12:00", "time_zone": "UTC"}},
|
||||
})
|
||||
expect(t, "equal non-zero times", st, body, http.StatusUnprocessableEntity, "invalid_quiet_hours")
|
||||
|
||||
// Create a group that is muted 24/7 (00:00-00:00 every day) and an active group.
|
||||
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
|
||||
"name": "Muted",
|
||||
"channel_ids": []string{quietCh, sharedCh},
|
||||
"quiet_hours": []map[string]any{{"weekdays": []string{}, "start": "00:00", "end": "00:00", "time_zone": "UTC"}},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create muted group = %d %v", st, body)
|
||||
}
|
||||
mutedGroup := body["id"].(string)
|
||||
if qh := body["quiet_hours"].([]any); len(qh) != 1 {
|
||||
t.Fatalf("quiet_hours = %v", qh)
|
||||
}
|
||||
|
||||
// Updating without quiet_hours preserves existing quiet hours.
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{
|
||||
"name": "Muted Renamed",
|
||||
"channel_ids": []string{quietCh, sharedCh},
|
||||
})
|
||||
if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 1 {
|
||||
t.Fatalf("preserve quiet_hours = %d %v", st, body)
|
||||
}
|
||||
|
||||
// Settings page shows the quiet hours inputs and active badge.
|
||||
st, _, html := owner.page("/settings/channels")
|
||||
if st != http.StatusOK || !strings.Contains(html, `name="quiet_hours.0.start"`) || !strings.Contains(html, "Quiet hours active") {
|
||||
t.Fatalf("settings page = %d, lacks quiet hours UI", st)
|
||||
}
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{
|
||||
"name": "AlwaysOn",
|
||||
"channel_ids": []string{activeCh, sharedCh},
|
||||
"quiet_hours": []map[string]any{},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create active group = %d %v", st, body)
|
||||
}
|
||||
activeGroup := body["id"].(string)
|
||||
|
||||
// Monitor assigned only to Muted: incident opens & resolves, 0 notifications sent.
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "SilentBackup", "type": "heartbeat", "interval_seconds": 3600,
|
||||
"alert_group_ids": []string{mutedGroup},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
monID := body["id"].(string)
|
||||
token := body["target"].(string)
|
||||
ping := func(suffix string) {
|
||||
t.Helper()
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
count := func(ch string) int {
|
||||
const q = `SELECT count(*) FROM notifications n
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
WHERE i.monitor_id = $1 AND n.channel_id = $2`
|
||||
return e.count(t, q, monID, ch)
|
||||
}
|
||||
ping("/fail")
|
||||
ping("")
|
||||
if inc := e.count(t, `SELECT count(*) FROM incidents WHERE monitor_id=$1`, monID); inc != 1 {
|
||||
t.Fatalf("incidents = %d, want 1", inc)
|
||||
}
|
||||
if q, s := count(quietCh), count(sharedCh); q != 0 || s != 0 {
|
||||
t.Fatalf("muted notifications quiet/shared = %d/%d, want 0/0", q, s)
|
||||
}
|
||||
|
||||
// Assign both Muted and AlwaysOn: only AlwaysOn's channels (activeCh + sharedCh) notify,
|
||||
// while quietCh stays silent.
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+monID, map[string]any{
|
||||
"name": "SilentBackup",
|
||||
"type": "heartbeat",
|
||||
"interval_seconds": 3600,
|
||||
"alert_group_ids": []string{mutedGroup, activeGroup},
|
||||
})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("PUT /api/v1/org/monitors/%s = %d %v, want %d", monID, st, body, http.StatusOK)
|
||||
}
|
||||
ping("/fail")
|
||||
ping("")
|
||||
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 0 || a != 2 || s != 2 {
|
||||
t.Fatalf("mixed deliveries quiet/active/shared = %d/%d/%d, want 0/2/2", q, a, s)
|
||||
}
|
||||
|
||||
// Explicitly clearing quiet_hours re-enables notifications on quietCh.
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{
|
||||
"name": "Muted Renamed",
|
||||
"channel_ids": []string{quietCh, sharedCh},
|
||||
"quiet_hours": []map[string]any{},
|
||||
})
|
||||
if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 0 {
|
||||
t.Fatalf("clear quiet_hours = %d %v, want 200 with empty quiet_hours", st, body)
|
||||
}
|
||||
ping("/fail")
|
||||
ping("")
|
||||
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 2 || a != 4 || s != 4 {
|
||||
t.Fatalf("after clearing quiet hours quiet/active/shared = %d/%d/%d, want 2/4/4", q, a, s)
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,22 @@ const (
|
||||
// acts on the resulting transitions.
|
||||
func (s *Server) evaluateResults(ctx context.Context, region string, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
||||
slices.SortFunc(results, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
|
||||
ids := make([]uuid.UUID, 0, len(monitors))
|
||||
for id := range monitors {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
planned := s.monitorsInMaintenance(ctx, ids)
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Failures during planned maintenance are expected: they neither
|
||||
// open incidents nor count towards one afterwards. Successes still
|
||||
// go through, so an incident from before can resolve.
|
||||
if _, _, active := inMaintenance(planned[m.ID], r.StartedAt); active && !r.OK {
|
||||
continue
|
||||
}
|
||||
t, err := s.eval.Observe(ctx, evaluate.Observation{
|
||||
MonitorID: m.ID, Region: region, OK: r.OK, At: r.StartedAt,
|
||||
Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions,
|
||||
@@ -50,7 +61,8 @@ func (s *Server) evaluateResults(ctx context.Context, region string, results []a
|
||||
}
|
||||
|
||||
// transition opens or resolves the monitor's incident and queues a
|
||||
// notification for every enabled channel of the org, in one transaction.
|
||||
// notification for every enabled channel assigned to the monitor, in one
|
||||
// transaction.
|
||||
func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error {
|
||||
return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
var (
|
||||
@@ -85,10 +97,25 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID)
|
||||
routes, err := q.MonitorAlertRoutes(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
quiet := map[uuid.UUID]bool{}
|
||||
seen := map[uuid.UUID]bool{}
|
||||
var channels []uuid.UUID
|
||||
for _, r := range routes {
|
||||
muted, ok := quiet[r.GroupID]
|
||||
if !ok {
|
||||
muted = isQuietRawAt(r.QuietHours, at)
|
||||
quiet[r.GroupID] = muted
|
||||
}
|
||||
if muted || seen[r.ChannelID] {
|
||||
continue
|
||||
}
|
||||
seen[r.ChannelID] = true
|
||||
channels = append(channels, r.ChannelID)
|
||||
}
|
||||
for _, ch := range channels {
|
||||
if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil {
|
||||
return err
|
||||
@@ -206,6 +233,13 @@ func (s *Server) send(ctx context.Context, typ string, config []byte, ev notify.
|
||||
}
|
||||
return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale))
|
||||
}
|
||||
if p, ok := notify.Lookup(typ); ok {
|
||||
settings, locale, err := s.openProviderSettings(typ, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Send(ctx, settings, s.messageFor(ev, locale), !s.cloud())
|
||||
}
|
||||
return fmt.Errorf("unknown channel type %q", typ)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ func (r *receiver) kinds() []string {
|
||||
|
||||
func TestAlerting(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL = mail.URL() })
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Alertmanager feeds monitors: it sends its alerts to a receiver URL of an
|
||||
// organization, and a monitor of type alertmanager is down while an alert
|
||||
// matching its label matchers fires.
|
||||
|
||||
const (
|
||||
alertmanagerRegion = "alertmanager"
|
||||
// receiverTokenPrefix tells receiver tokens apart from API tokens.
|
||||
receiverTokenPrefix = "uam_"
|
||||
// maxAlertmanagerBody bounds one webhook; Alertmanager batches alerts
|
||||
// per group, and its default limit is far lower.
|
||||
maxAlertmanagerBody = 4 << 20
|
||||
// keepAlerts outlasts the longest stale period a monitor may set.
|
||||
keepAlerts = 31 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// alertmanagerWebhook is Alertmanager's webhook payload (version 4).
|
||||
type alertmanagerWebhook struct {
|
||||
Version string `json:"version"`
|
||||
Status string `json:"status"`
|
||||
Alerts []struct {
|
||||
Status string `json:"status"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Annotations map[string]string `json:"annotations"`
|
||||
StartsAt time.Time `json:"startsAt"`
|
||||
GeneratorURL string `json:"generatorURL"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
} `json:"alerts"`
|
||||
}
|
||||
|
||||
func (s *Server) mountAlertmanager(r gin.IRouter) {
|
||||
r.POST("/am", s.alertmanagerWebhook)
|
||||
r.POST("/am/:token", s.alertmanagerWebhook)
|
||||
}
|
||||
|
||||
// alertmanagerWebhook takes the receiver token from the path or, as
|
||||
// Alertmanager's http_config can send it, as a bearer token.
|
||||
func (s *Server) alertmanagerWebhook(c *gin.Context) {
|
||||
tok := c.Param("token")
|
||||
if tok == "" {
|
||||
tok = bearerToken(c)
|
||||
}
|
||||
if !strings.HasPrefix(tok, receiverTokenPrefix) {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "am:"+tok[:min(len(tok), 16)], 600, time.Minute) {
|
||||
return
|
||||
}
|
||||
var payload alertmanagerWebhook
|
||||
if err := json.NewDecoder(http.MaxBytesReader(c.Writer, c.Request.Body, maxAlertmanagerBody)).Decode(&payload); err != nil {
|
||||
fail(c, http.StatusBadRequest, "invalid_input")
|
||||
return
|
||||
}
|
||||
var receiver store.AlertmanagerReceiverByHashRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if receiver, err = q.AlertmanagerReceiverByHash(ctx, HashToken(tok)); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range payload.Alerts {
|
||||
if a.Fingerprint == "" || len(a.Fingerprint) > 200 || (a.Status != "firing" && a.Status != "resolved") {
|
||||
continue
|
||||
}
|
||||
labels, _ := json.Marshal(nonNil(a.Labels))
|
||||
annotations, _ := json.Marshal(nonNil(a.Annotations))
|
||||
if err := q.UpsertAlertmanagerAlert(ctx, store.UpsertAlertmanagerAlertParams{
|
||||
OrgID: receiver.OrgID, Fingerprint: a.Fingerprint, ReceiverID: receiver.ID, Status: a.Status,
|
||||
Labels: labels, Annotations: annotations, StartsAt: a.StartsAt, GeneratorUrl: truncate(a.GeneratorURL, 2000),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
// State changes show at once; unchanged monitors wait for their interval.
|
||||
if err := s.CheckAlertmanagerMonitors(ctx, &receiver.OrgID, time.Now(), true); err != nil {
|
||||
s.log.ErrorContext(ctx, "evaluating alertmanager monitors failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func nonNil(m map[string]string) map[string]string {
|
||||
if m == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// firingAlert is an alert of the overview and of monitor evaluation.
|
||||
type firingAlert struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Annotations map[string]string `json:"annotations"`
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
GeneratorURL string `json:"generator_url,omitempty"`
|
||||
}
|
||||
|
||||
func loadFiringAlerts(ctx context.Context, q *store.Queries, org uuid.UUID, since time.Time) ([]firingAlert, error) {
|
||||
rows, err := q.FiringAlerts(ctx, store.FiringAlertsParams{OrgID: org, UpdatedAt: since})
|
||||
out := make([]firingAlert, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
a := firingAlert{Fingerprint: r.Fingerprint, StartsAt: r.StartsAt, UpdatedAt: r.UpdatedAt, GeneratorURL: r.GeneratorUrl}
|
||||
_ = json.Unmarshal(r.Labels, &a.Labels)
|
||||
_ = json.Unmarshal(r.Annotations, &a.Annotations)
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// alertSummary names an alert for result messages: alertname, the summary
|
||||
// annotation if any.
|
||||
func alertSummary(a firingAlert) string {
|
||||
name := a.Labels["alertname"]
|
||||
if name == "" {
|
||||
name = a.Fingerprint
|
||||
}
|
||||
if sum := a.Annotations["summary"]; sum != "" {
|
||||
return name + ": " + sum
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// CheckAlertmanagerMonitors records the state of alertmanager monitors, of
|
||||
// org or of all organizations. On a webhook (changed) it records monitors
|
||||
// whose state differs from their last result; otherwise it records those
|
||||
// whose interval has passed, so charts and the SLA have results to show.
|
||||
func (s *Server) CheckAlertmanagerMonitors(ctx context.Context, org *uuid.UUID, now time.Time, changed bool) error {
|
||||
var (
|
||||
monitors []store.AlertmanagerMonitorsRow
|
||||
alerts = map[uuid.UUID][]firingAlert{}
|
||||
latest = map[uuid.UUID]store.LatestResultForMonitorRow{}
|
||||
)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if monitors, err = q.AlertmanagerMonitors(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if _, ok := alerts[m.OrgID]; !ok {
|
||||
// Alerts older than the longest stale period are filtered
|
||||
// per monitor below.
|
||||
if alerts[m.OrgID], err = loadFiringAlerts(ctx, q, m.OrgID, now.Add(-30*24*time.Hour)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
r, err := q.LatestResultForMonitor(ctx, store.LatestResultForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID})
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if err == nil {
|
||||
latest[m.ID] = r
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range monitors {
|
||||
var cfg check.AlertmanagerConfig
|
||||
_ = json.Unmarshal(m.Config, &cfg)
|
||||
stale := now.Add(-time.Duration(max(cfg.StaleHours, 1)) * time.Hour)
|
||||
var matching []string
|
||||
for _, a := range alerts[m.OrgID] {
|
||||
if a.UpdatedAt.After(stale) && cfg.Matches(a.Labels) {
|
||||
matching = append(matching, alertSummary(a))
|
||||
}
|
||||
}
|
||||
ok := len(matching) == 0
|
||||
msg := ""
|
||||
if !ok {
|
||||
sort.Strings(matching)
|
||||
msg = fmt.Sprintf("%d firing: %s", len(matching), strings.Join(matching, "; "))
|
||||
}
|
||||
if changed {
|
||||
last, seen := latest[m.ID]
|
||||
if seen && last.Ok == ok && last.Error == msg {
|
||||
continue
|
||||
}
|
||||
} else if now.Sub(m.LastResult) < time.Duration(m.IntervalSeconds)*time.Second {
|
||||
continue
|
||||
}
|
||||
if err := s.recordPassive(ctx, alertmanagerRegion, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type receiverView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastReceivedAt *time.Time `json:"last_received_at"`
|
||||
}
|
||||
|
||||
type receiverRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
}
|
||||
|
||||
func (s *Server) listReceivers(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListAlertmanagerReceiversRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAlertmanagerReceivers(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]receiverView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = receiverView{ID: r.ID, Name: r.Name, Prefix: r.Prefix, CreatedAt: r.CreatedAt, LastReceivedAt: r.LastReceivedAt}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"receivers": out})
|
||||
}
|
||||
|
||||
// createReceiver returns the webhook URL once; only its hash is kept.
|
||||
func (s *Server) createReceiver(c *gin.Context) {
|
||||
var req receiverRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
tok := receiverTokenPrefix + auth.RandomToken()
|
||||
var row store.CreateAlertmanagerReceiverRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateAlertmanagerReceiver(ctx, store.CreateAlertmanagerReceiverParams{
|
||||
OrgID: p.Org.ID, Name: strings.TrimSpace(req.Name), TokenHash: HashToken(tok), Prefix: tok[:len(receiverTokenPrefix)+6],
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"receiver": receiverView{ID: row.ID, Name: row.Name, Prefix: row.Prefix, CreatedAt: row.CreatedAt},
|
||||
"url": s.alertmanagerURL(tok),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) alertmanagerURL(tok string) string {
|
||||
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/am/" + tok
|
||||
}
|
||||
|
||||
func (s *Server) deleteReceiver(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
n, err = q.DeleteAlertmanagerReceiver(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// alertView is a firing alert with the monitors that follow it.
|
||||
type alertView struct {
|
||||
firingAlert
|
||||
Monitors []alertMonitorRef `json:"monitors"`
|
||||
}
|
||||
|
||||
type alertMonitorRef struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// firingAlertViews lists the organization's firing alerts and which
|
||||
// monitors they hold down, so alerts no monitor follows stand out.
|
||||
// firingAlertViews reads a page of firing alerts, newest first, with the
|
||||
// monitors they match.
|
||||
func (s *Server) firingAlertViews(ctx context.Context, p *principal, pg pageReq) ([]alertView, pageInfo, error) {
|
||||
now := time.Now()
|
||||
var (
|
||||
rows []store.FiringAlertsPageRow
|
||||
monitors []store.AlertmanagerMonitorsRow
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if rows, err = q.FiringAlertsPage(ctx, store.FiringAlertsPageParams{
|
||||
OrgID: p.Org.ID, Since: now.Add(-time.Duration(check.DefaultStaleHours) * time.Hour),
|
||||
AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
monitors, err = q.AlertmanagerMonitors(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, pageInfo{}, err
|
||||
}
|
||||
rows, info := paginate(pg, rows, func(r store.FiringAlertsPageRow) cursor { return cursor{T: r.StartsAt, S: r.Fingerprint} })
|
||||
alerts := make([]firingAlert, len(rows))
|
||||
for i, r := range rows {
|
||||
alerts[i] = firingAlert{Fingerprint: r.Fingerprint, StartsAt: r.StartsAt, UpdatedAt: r.UpdatedAt, GeneratorURL: r.GeneratorUrl}
|
||||
_ = json.Unmarshal(r.Labels, &alerts[i].Labels)
|
||||
_ = json.Unmarshal(r.Annotations, &alerts[i].Annotations)
|
||||
}
|
||||
out := make([]alertView, len(alerts))
|
||||
for i, a := range alerts {
|
||||
out[i] = alertView{firingAlert: a, Monitors: []alertMonitorRef{}}
|
||||
for _, m := range monitors {
|
||||
var cfg check.AlertmanagerConfig
|
||||
_ = json.Unmarshal(m.Config, &cfg)
|
||||
if cfg.Matches(a.Labels) {
|
||||
out[i].Monitors = append(out[i].Monitors, alertMonitorRef{ID: m.ID, Name: m.Name})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, info, nil
|
||||
}
|
||||
|
||||
func (s *Server) listFiringAlerts(c *gin.Context) {
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, info, err := s.firingAlertViews(c.Request.Context(), current(c), pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"alerts": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
// suggestedMatchers proposes matchers for a monitor following a: its
|
||||
// alertname and the labels that usually tell services apart.
|
||||
func suggestedMatchers(a firingAlert) []check.Matcher {
|
||||
var out []check.Matcher
|
||||
for _, l := range []string{"alertname", "service", "job", "namespace", "instance"} {
|
||||
if v, ok := a.Labels[l]; ok && v != "" {
|
||||
out = append(out, check.Matcher{Label: l, Op: "=", Value: v})
|
||||
}
|
||||
if len(out) == 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return slices.Clip(out)
|
||||
}
|
||||
|
||||
func (s *Server) alertmanagerPage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return nil, errAborted
|
||||
}
|
||||
alerts, info, err := s.firingAlertViews(ctx, p, pg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.AlertmanagerView{CanManage: p.Grants.Can(authz.OrgManage), Pager: pager(c, info)}
|
||||
for _, a := range alerts {
|
||||
row := web.AlertRow{
|
||||
Name: a.Labels["alertname"], Summary: a.Annotations["summary"],
|
||||
Since: a.StartsAt.Local().Format("2006-01-02 15:04"), Labels: sortedLabels(a.Labels),
|
||||
}
|
||||
if row.Name == "" {
|
||||
row.Name = a.Fingerprint
|
||||
}
|
||||
for _, m := range a.Monitors {
|
||||
row.Monitors = append(row.Monitors, web.CheckerLink{URL: "/monitors/" + m.ID.String(), Label: m.Name})
|
||||
}
|
||||
q := url.Values{"type": {string(check.Alertmanager)}, "name": {row.Name}}
|
||||
for _, m := range suggestedMatchers(a.firingAlert) {
|
||||
q.Add("m", m.Label+"="+m.Value)
|
||||
}
|
||||
row.CreateURL = "/monitors/new?" + q.Encode()
|
||||
v.Alerts = append(v.Alerts, row)
|
||||
}
|
||||
if v.CanManage {
|
||||
var rows []store.ListAlertmanagerReceiversRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAlertmanagerReceivers(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
row := web.ReceiverRow{ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, Created: r.CreatedAt.Local().Format("2006-01-02"), LastSeen: "–"}
|
||||
if r.LastReceivedAt != nil {
|
||||
row.LastSeen = r.LastReceivedAt.Local().Format("2006-01-02 15:04")
|
||||
}
|
||||
v.Receivers = append(v.Receivers, row)
|
||||
}
|
||||
}
|
||||
return web.AlertmanagerPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func sortedLabels(labels map[string]string) [][2]string {
|
||||
keys := make([]string, 0, len(labels))
|
||||
for k := range labels {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
out := make([][2]string, len(keys))
|
||||
for i, k := range keys {
|
||||
out[i] = [2]string{k, labels[k]}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestAlertmanagerMonitor(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("am")+".test", uniq("am-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/alertmanager/receivers", map[string]any{"name": "prod"})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create receiver = %d %v", st, body)
|
||||
}
|
||||
hook := body["url"].(string)
|
||||
token := hook[strings.LastIndex(hook, "/")+1:]
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop errors", "type": "alertmanager", "interval_seconds": 60,
|
||||
"config": map[string]any{"matchers": []map[string]string{
|
||||
{"label": "alertname", "op": "=", "value": "HighErrorRate"},
|
||||
{"label": "severity", "op": "=~", "value": "critical|page"},
|
||||
}},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
monitor := body["id"].(string)
|
||||
|
||||
send := func(url, auth string, alerts ...map[string]any) int {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(map[string]any{"version": "4", "status": "firing", "alerts": alerts})
|
||||
req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if auth != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+auth)
|
||||
}
|
||||
resp, err := e.srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
alert := func(fp, status, name, severity, service string) map[string]any {
|
||||
return map[string]any{
|
||||
"status": status, "fingerprint": fp, "startsAt": time.Now().Add(-time.Minute),
|
||||
"labels": map[string]string{"alertname": name, "severity": severity, "service": service},
|
||||
"annotations": map[string]string{"summary": "Error rate above 5%"},
|
||||
}
|
||||
}
|
||||
open := func() bool {
|
||||
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
for _, i := range b["incidents"].([]any) {
|
||||
if i.(map[string]any)["resolved_at"] == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if st := send(e.srv.URL+"/am/uam_wrong", "", alert("a1", "firing", "HighErrorRate", "critical", "shop")); st != http.StatusUnauthorized {
|
||||
t.Errorf("wrong token = %d, want 401", st)
|
||||
}
|
||||
if st := send(hook, "", alert("a1", "firing", "HighErrorRate", "critical", "shop"), alert("a2", "firing", "DiskFull", "warning", "db")); st != http.StatusNoContent {
|
||||
t.Fatalf("webhook = %d", st)
|
||||
}
|
||||
if !open() {
|
||||
t.Fatal("a matching firing alert opened no incident")
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
if !strings.Contains(mustJSON(list), "1 firing: HighErrorRate: Error rate above 5%") {
|
||||
t.Errorf("result message missing: %s", mustJSON(list))
|
||||
}
|
||||
|
||||
// The overview shows which alerts no monitor follows, with a way to add one.
|
||||
_, alerts := owner.do("GET", "/api/v1/org/alertmanager/alerts", nil)
|
||||
var followed, unfollowed int
|
||||
for _, a := range alerts["alerts"].([]any) {
|
||||
if len(a.(map[string]any)["monitors"].([]any)) > 0 {
|
||||
followed++
|
||||
} else {
|
||||
unfollowed++
|
||||
}
|
||||
}
|
||||
if followed != 1 || unfollowed != 1 {
|
||||
t.Errorf("alerts followed/unfollowed = %d/%d, want 1/1", followed, unfollowed)
|
||||
}
|
||||
_, _, page := owner.page("/settings/alertmanager")
|
||||
if !strings.Contains(page, "/monitors/new?") || !strings.Contains(page, "DiskFull") {
|
||||
t.Error("the overview does not offer to create a monitor for DiskFull")
|
||||
}
|
||||
_, _, editor := owner.page("/monitors/new?type=alertmanager&name=DiskFull&m=alertname%3DDiskFull&m=service%3Ddb")
|
||||
if !strings.Contains(editor, `value="DiskFull"`) || !strings.Contains(editor, `value="db"`) {
|
||||
t.Error("the editor is not prefilled from the alert")
|
||||
}
|
||||
|
||||
// Resolved, sent with the token as bearer.
|
||||
if st := send(e.srv.URL+"/am", token, alert("a1", "resolved", "HighErrorRate", "critical", "shop")); st != http.StatusNoContent {
|
||||
t.Fatalf("bearer webhook = %d", st)
|
||||
}
|
||||
if open() {
|
||||
t.Fatal("the resolved alert did not resolve the incident")
|
||||
}
|
||||
|
||||
// An alert Alertmanager stopped repeating ends after the stale period.
|
||||
send(hook, "", alert("a3", "firing", "HighErrorRate", "page", "shop"))
|
||||
if !open() {
|
||||
t.Fatal("no incident for the second alert")
|
||||
}
|
||||
ctx := context.Background()
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE alertmanager_alerts SET updated_at = now() - interval '25 hours' WHERE org_id = $1 AND fingerprint = 'a3'`, org)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.api.CheckAlertmanagerMonitors(ctx, &org, time.Now(), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if open() {
|
||||
t.Error("a stale alert still holds the monitor down")
|
||||
}
|
||||
|
||||
// Other organizations see none of it.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("am")+".test", uniq("amx-"))
|
||||
if _, oa := other.do("GET", "/api/v1/org/alertmanager/alerts", nil); len(oa["alerts"].([]any)) != 0 {
|
||||
t.Error("another organization sees the alerts")
|
||||
}
|
||||
_ = monitor
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
)
|
||||
|
||||
// sessionStarted is the answer of requests that sign in.
|
||||
var sessionStarted = obj{"status": "", "csrf_token": ""}
|
||||
|
||||
// paged adds the cursors of a paged list to its response.
|
||||
func paged(o obj) obj {
|
||||
o["next_cursor"], o["prev_cursor"] = "", ""
|
||||
return o
|
||||
}
|
||||
|
||||
// endpoints documents every route under /api/v1, in the order the docs
|
||||
// show them.
|
||||
var endpoints = []endpoint{
|
||||
// Account
|
||||
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
|
||||
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
|
||||
req: signupRequest{}, resp: sessionStarted},
|
||||
{method: "POST", path: "/api/v1/auth/verify", tag: "Account", summary: "Confirm an email address with the mailed token", public: true,
|
||||
description: "Signs the account in. Tokens are valid for 24 hours and once; `410 verification_expired` otherwise.",
|
||||
req: verifyRequest{}, resp: sessionStarted},
|
||||
{method: "POST", path: "/api/v1/auth/verify/resend", tag: "Account", summary: "Mail a new confirmation link", public: true,
|
||||
description: "Answers the same whether or not an unconfirmed account with that address exists.",
|
||||
req: resendRequest{}, status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/orgs", tag: "Account", summary: "Create an organization", sessionOnly: true,
|
||||
description: "The account owns it, and it becomes the active organization. Limited per account by the platform (`422 org_limit`).",
|
||||
req: createOrgRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "slug": "", "redirect": ""}},
|
||||
{method: "POST", path: "/api/v1/auth/login", tag: "Account", summary: "Sign in with email and password", public: true,
|
||||
description: "Answers `{\"status\": \"totp_required\"}` when the account has two-factor authentication; continue with /auth/login/totp.",
|
||||
req: loginRequest{}, resp: sessionStarted},
|
||||
{method: "POST", path: "/api/v1/auth/login/totp", tag: "Account", summary: "Complete sign-in with a TOTP or recovery code", public: true,
|
||||
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,
|
||||
req: localeRequest{}, status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/me/totp/setup", tag: "Account", summary: "Start setting up two-factor authentication", sessionOnly: true,
|
||||
resp: obj{"secret": "", "otpauth_url": "", "qr": ""}},
|
||||
{method: "POST", path: "/api/v1/me/totp/enable", tag: "Account", summary: "Enable two-factor authentication", sessionOnly: true,
|
||||
description: "Returns single-use recovery codes, shown only this once.", req: totpRequest{}, resp: obj{"recovery_codes": []string{}}},
|
||||
{method: "POST", path: "/api/v1/me/totp/disable", tag: "Account", summary: "Disable two-factor authentication", sessionOnly: true,
|
||||
req: reauthRequest{}, status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/me/totp/recovery-codes", tag: "Account", summary: "Replace the recovery codes", sessionOnly: true,
|
||||
req: reauthRequest{}, resp: obj{"recovery_codes": []string{}}},
|
||||
{method: "GET", path: "/api/v1/me/audit", tag: "Account", summary: "Sign-ins and security changes of the account",
|
||||
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
|
||||
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)",
|
||||
description: "`?format=pdf` returns a PDF instead of JSON.", resp: accountExport{}},
|
||||
{method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
|
||||
description: "Refused with `owns_shared_orgs` while the user owns organizations with other members. Organizations only the user belongs to are deleted with the account.",
|
||||
req: deletionRequest{}, resp: obj{"status": ""}},
|
||||
{method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it",
|
||||
req: previewRequest{}, resp: obj{"html": ""}},
|
||||
{method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/invitations/:token/signup", tag: "Account", summary: "Create an account through an invitation", public: true,
|
||||
req: inviteSignupRequest{}, resp: sessionStarted},
|
||||
|
||||
// Monitors
|
||||
{method: "GET", path: "/api/v1/org/monitors", tag: "Monitors", summary: "List monitors with their latest results",
|
||||
description: "Paged by name. Only monitors the caller may read, so a page may hold fewer; header values and heartbeat tokens only for those who may change the monitor.",
|
||||
perm: "monitors.read", resp: paged(obj{"monitors": []monitorView{}})},
|
||||
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
|
||||
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
|
||||
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
|
||||
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
|
||||
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
|
||||
req: monitorRequest{}, resp: monitorView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Delete a monitor and its history", perm: "monitors.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/monitors/:id/evidence", tag: "Monitors", summary: "What checkers saw: captured responses",
|
||||
description: "Paged, newest first.", perm: "monitors.write", resp: paged(obj{"evidence": []evidenceSummary{}})},
|
||||
{method: "GET", path: "/api/v1/org/monitors/:id/results", tag: "Monitors", summary: "A monitor's check results",
|
||||
description: "Paged, newest first, back to the end of raw result retention.", resp: paged(obj{"results": []resultView{}})},
|
||||
{method: "GET", path: "/api/v1/org/monitors/:id/evidence/:evidence", tag: "Monitors", summary: "One captured response",
|
||||
description: "Redirect chain with headers, timing, certificate and the first 32 KiB of the body.",
|
||||
perm: "monitors.write", resp: obj{"id": uuid.UUID{}, "region": "", "checker_id": uuid.UUID{}, "time": time.Time{}, "ok": false, "status_code": new(int32), "error": new(string), "evidence": check.Evidence{}}},
|
||||
{method: "GET", path: "/api/v1/org/checkers/:id", tag: "Monitors", summary: "What a checker instance is doing",
|
||||
description: "Platform checkers serve every organization; other organizations' work appears only as a count. `recent` is paged, newest first; a page may hold fewer results than `limit` when some belong to monitors you cannot read.",
|
||||
resp: checkerActivity{}},
|
||||
{method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage",
|
||||
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, region_limit or platform_region_limit.",
|
||||
resp: usageView{}},
|
||||
{method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types this installation offers",
|
||||
resp: obj{"types": []string{}}},
|
||||
{method: "PUT", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Choose the monitor types offered to members",
|
||||
description: "Out of the types the platform offers; types left out are not offered for new monitors or type changes, existing monitors keep running.",
|
||||
perm: "org.manage", sessionOnly: true, req: checkTypesRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/groups", tag: "Monitors", summary: "List monitor groups", resp: obj{"groups": []groupView{}}},
|
||||
{method: "POST", path: "/api/v1/org/groups", tag: "Monitors", summary: "Create a group", perm: "monitors.write",
|
||||
req: groupRequest{}, status: http.StatusCreated, resp: groupView{}},
|
||||
{method: "PUT", path: "/api/v1/org/groups/:id", tag: "Monitors", summary: "Rename or move a group", perm: "monitors.write",
|
||||
req: groupRequest{}, resp: groupView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/groups/:id", tag: "Monitors", summary: "Delete a group; its content moves up", perm: "monitors.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/maintenance", tag: "Monitors", summary: "List maintenance windows", perm: "monitors.read",
|
||||
description: "Paged, latest start first. Only windows the caller may read, so a page may hold fewer.", resp: paged(obj{"maintenance": []maintenanceView{}})},
|
||||
{method: "POST", path: "/api/v1/org/maintenance", tag: "Monitors", summary: "Plan maintenance",
|
||||
description: "During maintenance, failures open no incidents and send no notifications.",
|
||||
perm: "monitors.write", req: maintenanceRequest{}, status: http.StatusCreated, resp: maintenanceView{}},
|
||||
{method: "PUT", path: "/api/v1/org/maintenance/:id", tag: "Monitors", summary: "Change maintenance", perm: "monitors.write",
|
||||
req: maintenanceRequest{}, resp: maintenanceView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/maintenance/:id", tag: "Monitors", summary: "Delete maintenance", perm: "monitors.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/alertmanager/alerts", tag: "Monitors", summary: "Alerts Alertmanager reports as firing",
|
||||
description: "Paged, newest first. With the alertmanager monitors each alert holds down; alerts no monitor follows have none.",
|
||||
perm: "monitors.read", resp: paged(obj{"alerts": []alertView{}})},
|
||||
{method: "GET", path: "/api/v1/org/alertmanager/receivers", tag: "Monitors", summary: "List Alertmanager receivers", perm: "org.manage",
|
||||
resp: obj{"receivers": []receiverView{}}},
|
||||
{method: "POST", path: "/api/v1/org/alertmanager/receivers", tag: "Monitors", summary: "Create a receiver URL for Alertmanager's webhook",
|
||||
description: "The URL is returned only this once. Alertmanager may also send its token as `Authorization: Bearer` to `/am`.",
|
||||
perm: "org.manage", sessionOnly: true, req: receiverRequest{}, status: http.StatusCreated, resp: obj{"receiver": receiverView{}, "url": ""}},
|
||||
{method: "DELETE", path: "/api/v1/org/alertmanager/receivers/:id", tag: "Monitors", summary: "Delete a receiver", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/incidents", tag: "Monitors", summary: "List incidents", perm: "incidents.read",
|
||||
description: "Paged, newest first. `monitor_id` limits them to one monitor.", resp: paged(obj{"incidents": []incidentView{}})},
|
||||
|
||||
// Status pages
|
||||
{method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "Create a status page", perm: "statuspages.write",
|
||||
req: statusPageRequest{}, status: http.StatusCreated, resp: statusPageView{}},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id", tag: "Status pages", summary: "Change a status page", perm: "statuspages.write",
|
||||
req: statusPageRequest{}, resp: statusPageView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id", tag: "Status pages", summary: "Delete a status page", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "List status page groups", perm: "statuspages.read",
|
||||
resp: obj{"groups": []pageGroupView{}}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "Create a status page group", perm: "statuspages.write",
|
||||
req: pageGroupRequest{}, status: http.StatusCreated, resp: pageGroupView{}},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Rename, move or reorder a status page group", perm: "statuspages.write",
|
||||
req: pageGroupRequest{}, resp: pageGroupView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Delete a status page group", perm: "statuspages.write",
|
||||
description: "Child groups and monitors move up to the deleted group's parent.", status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/groups/import", tag: "Status pages", summary: "Import monitor groups into a status page", perm: "statuspages.write",
|
||||
description: "Copies the organization's monitor group tree for the page's monitors and maps them into the imported groups.", resp: obj{"groups": []pageGroupView{}}},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/monitors", tag: "Status pages", summary: "Set the monitors shown", perm: "statuspages.write",
|
||||
description: "Assigns monitors to optional nested groups via `group_id`. Legacy `section` names are mapped to top-level groups.", req: pageMonitorsRequest{}, status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/domain", tag: "Status pages", summary: "Set a custom domain", perm: "statuspages.write",
|
||||
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/export", tag: "Status pages", summary: "Export the page as a single HTML file", perm: "statuspages.read",
|
||||
media: "text/html"},
|
||||
|
||||
// Alerting
|
||||
{method: "GET", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "List alert groups and their channels", perm: "notifications.read",
|
||||
resp: obj{"alert_groups": []alertGroupView{}}},
|
||||
{method: "POST", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "Create an alert group", perm: "notifications.write",
|
||||
description: "Optional `quiet_hours` suppress notifications from this group during recurring local time windows (`start`/`end` as `HH:MM`, `start > end` wraps overnight, `00:00`–`00:00` or `24:00` covers the full day, empty `weekdays` means every day).",
|
||||
req: alertGroupRequest{}, status: http.StatusCreated, resp: alertGroupView{}},
|
||||
{method: "PUT", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Update an alert group, its channels and quiet hours", perm: "notifications.write",
|
||||
description: "Omitting `quiet_hours` preserves existing quiet hours; an empty array removes them.",
|
||||
req: alertGroupRequest{}, resp: alertGroupView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Delete an alert group", perm: "notifications.write",
|
||||
description: "The default group cannot be deleted. Deleting other groups removes their monitor assignments; no fallback group is assigned.", status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read",
|
||||
resp: obj{"channels": []channelView{}, "email_available": false}},
|
||||
{method: "POST", path: "/api/v1/org/channels", tag: "Alerting", summary: "Create a channel",
|
||||
description: "`type` is webhook (`url`), email (`to`, `locale`) or one of slack, discord, teams, googlechat, mattermost, rocketchat, telegram, matrix, ntfy, gotify, pushover, pushbullet, signal, pagerduty, opsgenie, apprise with their `settings`. Secret settings are stored encrypted and never returned; on update, leaving one empty keeps it. Webhook channels return their signing secret once. New channels join the default alert group.",
|
||||
perm: "notifications.write",
|
||||
req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}},
|
||||
{method: "PUT", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Change a channel", perm: "notifications.write",
|
||||
req: channelRequest{}, resp: obj{"channel": channelView{}, "signing_secret": ""}},
|
||||
{method: "DELETE", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Delete a channel", perm: "notifications.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/org/channels/:id/test", tag: "Alerting", summary: "Send a test notification", perm: "notifications.write",
|
||||
status: http.StatusNoContent},
|
||||
|
||||
// Organization
|
||||
{method: "PUT", path: "/api/v1/org/policy", tag: "Organization", summary: "Set sign-in and token policies", perm: "org.manage", sessionOnly: true,
|
||||
req: policyRequest{}, resp: obj{"require_totp": false, "require_sso": false, "api_token_max_days": new(int32)}},
|
||||
{method: "GET", path: "/api/v1/org/members", tag: "Organization", summary: "List members and their roles", perm: "members.read",
|
||||
description: "Paged by email.", resp: paged(obj{"members": []memberView{}})},
|
||||
{method: "DELETE", path: "/api/v1/org/members/:user", tag: "Organization", summary: "Remove a member", perm: "members.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/org/members/:user/roles", tag: "Organization", summary: "Assign a role, optionally limited to a group or status page",
|
||||
description: "Nobody can grant permissions they do not hold.", perm: "members.manage", sessionOnly: true,
|
||||
req: assignRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}}},
|
||||
{method: "DELETE", path: "/api/v1/org/assignments/:id", tag: "Organization", summary: "Remove a role assignment", perm: "members.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/invitations", tag: "Organization", summary: "List pending invitations", perm: "members.read",
|
||||
resp: obj{"invitations": []invitationView{}}},
|
||||
{method: "POST", path: "/api/v1/org/invitations", tag: "Organization", summary: "Invite someone", perm: "members.manage", sessionOnly: true,
|
||||
req: inviteRequest{}, status: http.StatusCreated, resp: obj{"url": ""}},
|
||||
{method: "DELETE", path: "/api/v1/org/invitations/:id", tag: "Organization", summary: "Withdraw an invitation", perm: "members.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/roles", tag: "Organization", summary: "List roles and all permissions", perm: "members.read",
|
||||
resp: obj{"roles": []roleView{}, "permissions": []string{}}},
|
||||
{method: "POST", path: "/api/v1/org/roles", tag: "Organization", summary: "Create a custom role", perm: "roles.manage", sessionOnly: true,
|
||||
req: roleRequest{}, status: http.StatusCreated, resp: roleView{}},
|
||||
{method: "PUT", path: "/api/v1/org/roles/:id", tag: "Organization", summary: "Change a custom role", perm: "roles.manage", sessionOnly: true,
|
||||
req: roleRequest{}, resp: roleView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/roles/:id", tag: "Organization", summary: "Delete an unused custom role", perm: "roles.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/tokens", tag: "Organization", summary: "List API tokens",
|
||||
description: "Members see their own tokens; with tokens.manage, all of the organization.", resp: obj{"tokens": []tokenView{}}},
|
||||
{method: "POST", path: "/api/v1/org/tokens", tag: "Organization", summary: "Create an API token", sessionOnly: true,
|
||||
description: "The token is returned only this once. Its permissions are capped by the creator's.",
|
||||
req: createTokenRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "token": "", "prefix": "", "permissions": []string{}}},
|
||||
{method: "DELETE", path: "/api/v1/org/tokens/:id", tag: "Organization", summary: "Revoke an API token", status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/sso", tag: "Organization", summary: "List single sign-on providers", perm: "org.manage",
|
||||
resp: obj{"providers": []ssoProviderView{}, "redirect_url": ""}},
|
||||
{method: "POST", path: "/api/v1/org/sso", tag: "Organization", summary: "Add an OpenID Connect provider", perm: "org.manage", sessionOnly: true,
|
||||
req: ssoProviderRequest{}, status: http.StatusCreated, resp: ssoProviderView{}},
|
||||
{method: "PUT", path: "/api/v1/org/sso/:id", tag: "Organization", summary: "Change a provider", perm: "org.manage", sessionOnly: true,
|
||||
req: ssoProviderRequest{}, resp: ssoProviderView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/sso/:id", tag: "Organization", summary: "Remove a provider", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/regions", tag: "Organization", summary: "Regions available to the organization", resp: obj{"regions": []regionView{}}},
|
||||
{method: "POST", path: "/api/v1/org/regions", tag: "Organization", summary: "Create an own region", perm: "org.manage", sessionOnly: true,
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Delete an own region", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/agents", tag: "Organization", summary: "List own checkers and status page servers", perm: "org.manage",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/org/agents", tag: "Organization", summary: "Create an agent token", perm: "org.manage", sessionOnly: true,
|
||||
description: "The token is returned only this once.", req: agentRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "token": ""}},
|
||||
{method: "PATCH", path: "/api/v1/org/agents/:id", tag: "Organization", summary: "Let a checker check private addresses or not",
|
||||
description: "Applies from the checker's next poll.", perm: "org.manage", sessionOnly: true, req: agentUpdate{}, status: http.StatusNoContent},
|
||||
{method: "DELETE", path: "/api/v1/org/agents/:id", tag: "Organization", summary: "Revoke an agent", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/legal", tag: "Organization", summary: "Legal notice and privacy policy of the status pages", perm: "org.manage",
|
||||
resp: obj{"documents": []legalView{}}},
|
||||
{method: "PUT", path: "/api/v1/org/legal/:kind", tag: "Organization", summary: "Set the legal notice (imprint) or privacy policy",
|
||||
description: "Markdown or a link; a link wins. Both empty removes the document.", perm: "org.manage",
|
||||
req: legalRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/audit", tag: "Organization", summary: "The organization's audit log", perm: "audit.read",
|
||||
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
|
||||
{method: "GET", path: "/api/v1/org/export", tag: "Organization", summary: "Export the organization's data", perm: "org.manage", sessionOnly: true,
|
||||
description: "`?format=pdf` returns a PDF instead of JSON.", resp: orgExport{}},
|
||||
{method: "POST", path: "/api/v1/org/delete", tag: "Organization", summary: "Delete the organization with all its data", sessionOnly: true,
|
||||
description: "Owner only, confirmed with the organization's slug and the owner's password.",
|
||||
req: orgDeletionRequest{}, resp: obj{"status": ""}},
|
||||
|
||||
// Platform
|
||||
{method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin",
|
||||
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
|
||||
{method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin",
|
||||
resp: obj{"documents": []legalView{}}},
|
||||
{method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin",
|
||||
req: legalRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Check types and whether they are offered", perm: "platform admin",
|
||||
resp: obj{"types": []checkTypeView{}}},
|
||||
{method: "PUT", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Choose the check types offered for new monitors",
|
||||
description: "Types left out are switched off: not offered for new monitors or type changes; existing monitors keep running.",
|
||||
perm: "platform admin", req: checkTypesRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Whether platform checkers may check private addresses", perm: "platform admin",
|
||||
resp: checkerNetwork{}},
|
||||
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
||||
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
||||
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/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.",
|
||||
perm: "platform admin", req: limitsRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/orgs", tag: "Platform", summary: "Organizations with usage, limits and owner",
|
||||
description: "Paged, newest first. `q` searches name, slug and owner email.", perm: "platform admin", resp: paged(obj{"orgs": []adminOrg{}})},
|
||||
{method: "PUT", path: "/api/v1/admin/orgs/:id/limits", tag: "Platform", summary: "Override an organization's limits",
|
||||
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: orgLimitsView{}, status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/admin/users/:id/limits", tag: "Platform", summary: "Override how many organizations an account may own",
|
||||
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: userLimitsRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/status-pages", tag: "Platform", summary: "Public and suspended status pages with organization and owner",
|
||||
description: "Paged, newest first. `q` searches title, slug, domain, organization and owner email.",
|
||||
perm: "platform admin", resp: paged(obj{"status_pages": []moderatedPage{}})},
|
||||
{method: "PUT", path: "/api/v1/admin/status-pages/:id/suspension", tag: "Platform", summary: "Suspend or reinstate a status page",
|
||||
description: "A suspended page is not served; status page servers drop it when they next ask for it.",
|
||||
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
|
||||
{method: "DELETE", path: "/api/v1/admin/status-pages/:id", tag: "Platform", summary: "Delete a status page", perm: "platform admin", status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/admin/orgs/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an organization",
|
||||
description: "A suspended organization's monitors are not checked, its status pages are not served, heartbeats and Alertmanager webhooks are refused, and its members and API tokens get 403 org_suspended.",
|
||||
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
|
||||
{method: "DELETE", path: "/api/v1/admin/orgs/:id", tag: "Platform", summary: "Delete an organization with all its data", perm: "platform admin", status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/admin/users/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an account",
|
||||
description: "A suspended account is signed out everywhere and can neither sign in nor use its API tokens. Platform admins cannot be suspended.",
|
||||
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
|
||||
{method: "DELETE", path: "/api/v1/admin/users/:id", tag: "Platform", summary: "Delete an account",
|
||||
description: "Organizations only the account belongs to are deleted with it; owning one shared with others gives 409 owns_shared_orgs. Platform admins cannot be deleted.",
|
||||
perm: "platform admin", status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
|
||||
resp: obj{"regions": []regionView{}}},
|
||||
{method: "POST", path: "/api/v1/admin/regions", tag: "Platform", summary: "Create a platform region", perm: "platform admin",
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Delete a platform region", perm: "platform admin",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/agents", tag: "Platform", summary: "List platform agents", perm: "platform admin",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/admin/agents", tag: "Platform", summary: "Create a platform agent token", perm: "platform admin",
|
||||
req: agentRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}, "token": ""}},
|
||||
{method: "DELETE", path: "/api/v1/admin/agents/:id", tag: "Platform", summary: "Revoke a platform agent", perm: "platform admin",
|
||||
status: http.StatusNoContent},
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"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"
|
||||
)
|
||||
|
||||
// auditActions names the audited action of every state-changing route. An
|
||||
// empty name marks a route deliberately not audited. A test fails for
|
||||
// routes missing here, so new endpoints cannot slip past the log.
|
||||
var auditActions = map[string]string{
|
||||
"POST /api/v1/org/alert-groups": "alert_group.create",
|
||||
"PUT /api/v1/org/alert-groups/:id": "alert_group.update",
|
||||
"DELETE /api/v1/org/alert-groups/:id": "alert_group.delete",
|
||||
"POST /api/v1/locale": "",
|
||||
"POST /api/v1/markdown/preview": "",
|
||||
"POST /api/v1/auth/signup": "account.signup",
|
||||
"POST /api/v1/auth/verify": "account.verify",
|
||||
"POST /api/v1/auth/verify/resend": "",
|
||||
"POST /api/v1/orgs": "org.create",
|
||||
"POST /api/v1/auth/login": "auth.login",
|
||||
"POST /api/v1/auth/login/totp": "auth.login",
|
||||
"POST /api/v1/auth/logout": "auth.logout",
|
||||
"POST /api/v1/me/org": "",
|
||||
"POST /api/v1/me/totp/setup": "",
|
||||
"POST /api/v1/me/totp/enable": "account.totp_enable",
|
||||
"POST /api/v1/me/totp/disable": "account.totp_disable",
|
||||
"POST /api/v1/me/totp/recovery-codes": "account.recovery_codes",
|
||||
"POST /api/v1/me/delete": "account.delete",
|
||||
"POST /api/v1/org/delete": "org.delete",
|
||||
"POST /api/v1/invitations/:token/accept": "member.join",
|
||||
"POST /api/v1/invitations/:token/signup": "member.join",
|
||||
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
|
||||
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
|
||||
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
|
||||
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
"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",
|
||||
"DELETE /api/v1/admin/status-pages/:id": "platform.status_page_delete",
|
||||
"PUT /api/v1/admin/orgs/:id/suspension": "platform.org_suspension",
|
||||
"DELETE /api/v1/admin/orgs/:id": "platform.org_delete",
|
||||
"PUT /api/v1/admin/users/:id/suspension": "platform.user_suspension",
|
||||
"DELETE /api/v1/admin/users/:id": "platform.user_delete",
|
||||
"PUT /api/v1/org/check-types": "org.check_types_update",
|
||||
"PATCH /api/v1/org/agents/:id": "agent.update",
|
||||
"POST /api/v1/admin/regions": "platform.region_create",
|
||||
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
|
||||
"POST /api/v1/admin/agents": "platform.agent_create",
|
||||
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
|
||||
}
|
||||
|
||||
// Failed attempts of these actions are recorded too.
|
||||
var auditFailures = map[string]bool{"auth.login": true}
|
||||
|
||||
const (
|
||||
ctxAuditActor = "api.audit.actor"
|
||||
ctxAuditOrg = "api.audit.org"
|
||||
ctxAuditDetails = "api.audit.details"
|
||||
ctxAuditSkip = "api.audit.skip"
|
||||
)
|
||||
|
||||
// auditOrg files the entry under org for requests outside the org API,
|
||||
// such as accepting an invitation.
|
||||
func auditOrg(c *gin.Context, org uuid.UUID) { c.Set(ctxAuditOrg, org) }
|
||||
|
||||
// auditSkip leaves the current request out, for steps that are not the
|
||||
// action yet, like a password check awaiting the second factor.
|
||||
func auditSkip(c *gin.Context) { c.Set(ctxAuditSkip, true) }
|
||||
|
||||
// auditActor names the acting user where no session or principal does yet,
|
||||
// as when signing in.
|
||||
func auditActor(c *gin.Context, user uuid.UUID) { c.Set(ctxAuditActor, user) }
|
||||
|
||||
// auditDetail adds a value to the entry of the current request.
|
||||
func auditDetail(c *gin.Context, key string, v any) {
|
||||
d, _ := c.Get(ctxAuditDetails)
|
||||
m, _ := d.(map[string]any)
|
||||
if m == nil {
|
||||
m = map[string]any{}
|
||||
c.Set(ctxAuditDetails, m)
|
||||
}
|
||||
m[key] = v
|
||||
}
|
||||
|
||||
// captureWriter keeps the start of a JSON response to take the target's id
|
||||
// and name from it.
|
||||
type captureWriter struct {
|
||||
gin.ResponseWriter
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(b []byte) (int, error) {
|
||||
if room := 8192 - w.buf.Len(); room > 0 {
|
||||
w.buf.Write(b[:min(len(b), room)])
|
||||
}
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// Response fields worth keeping; anything else may be a secret, such as a
|
||||
// freshly created token.
|
||||
var auditFields = []string{"name", "key", "slug", "email", "type", "target", "domain", "kind"}
|
||||
|
||||
// audit records state-changing requests after they ran.
|
||||
func (s *Server) audit() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
switch c.Request.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
cw := &captureWriter{ResponseWriter: c.Writer}
|
||||
c.Writer = cw
|
||||
c.Next()
|
||||
|
||||
action := auditActions[c.Request.Method+" "+c.FullPath()]
|
||||
status := c.Writer.Status()
|
||||
if action == "" || c.GetBool(ctxAuditSkip) || (status >= 400 && (!auditFailures[action] || status >= 500)) {
|
||||
return
|
||||
}
|
||||
if status >= 400 {
|
||||
action += "_failed"
|
||||
}
|
||||
e := store.InsertAuditEventParams{Action: action, Status: int32(status), Kind: "user"}
|
||||
details := map[string]any{}
|
||||
if d, ok := c.Get(ctxAuditDetails); ok {
|
||||
for k, v := range d.(map[string]any) {
|
||||
details[k] = v
|
||||
}
|
||||
}
|
||||
if obj := responseObject(cw.buf.Bytes()); obj != nil {
|
||||
if id, err := uuid.Parse(asString(obj["id"])); err == nil {
|
||||
e.TargetID = &id
|
||||
}
|
||||
for _, f := range auditFields {
|
||||
if v := asString(obj[f]); v != "" {
|
||||
details[f] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if status < 400 && strings.HasPrefix(action, "auth.") {
|
||||
// The address only identifies attempts on unknown accounts.
|
||||
delete(details, "email")
|
||||
}
|
||||
for _, param := range []string{"id", "user"} {
|
||||
if id, err := uuid.Parse(c.Param(param)); err == nil {
|
||||
e.TargetID = &id
|
||||
}
|
||||
}
|
||||
if p, ok := c.Get(ctxPrincipal); ok {
|
||||
p := p.(*principal)
|
||||
e.Kind, e.OrgID, e.ActorUserID = "org", &p.Org.ID, &p.UserID
|
||||
if p.TokenID != uuid.Nil {
|
||||
e.ActorTokenID = &p.TokenID
|
||||
}
|
||||
} else if sess := auth.Current(c); sess != nil {
|
||||
e.ActorUserID = &sess.UserID
|
||||
}
|
||||
if u, ok := c.Get(ctxAuditActor); ok {
|
||||
id := u.(uuid.UUID)
|
||||
e.ActorUserID = &id
|
||||
}
|
||||
if o, ok := c.Get(ctxAuditOrg); ok {
|
||||
org := o.(uuid.UUID)
|
||||
e.Kind, e.OrgID = "org", &org
|
||||
}
|
||||
if strings.HasPrefix(c.FullPath(), "/api/v1/admin/") || e.ActorUserID == nil {
|
||||
e.Kind, e.OrgID = "platform", nil
|
||||
}
|
||||
s.writeAudit(c, e, details)
|
||||
}
|
||||
}
|
||||
|
||||
// responseObject returns the object a response describes: the response
|
||||
// itself or, for responses like {"channel": {...}, "signing_secret": ...},
|
||||
// the nested object carrying an id.
|
||||
func responseObject(body []byte) map[string]any {
|
||||
var resp map[string]any
|
||||
if json.Unmarshal(body, &resp) != nil {
|
||||
return nil
|
||||
}
|
||||
if _, ok := resp["id"]; ok {
|
||||
return resp
|
||||
}
|
||||
for _, v := range resp {
|
||||
if m, ok := v.(map[string]any); ok {
|
||||
if _, ok := m["id"]; ok {
|
||||
return m
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// writeAudit stores e with the request's origin. A failure is logged, not
|
||||
// returned: the change it describes has already happened.
|
||||
func (s *Server) writeAudit(c *gin.Context, e store.InsertAuditEventParams, details map[string]any) {
|
||||
ctx := context.WithoutCancel(c.Request.Context())
|
||||
if len(details) > 0 {
|
||||
e.Details, _ = json.Marshal(details)
|
||||
} else {
|
||||
e.Details = []byte("{}")
|
||||
}
|
||||
if ip, err := netip.ParseAddr(c.ClientIP()); err == nil {
|
||||
e.Ip = &ip
|
||||
}
|
||||
if ua := c.Request.UserAgent(); ua != "" {
|
||||
ua = ua[:min(len(ua), 300)]
|
||||
e.UserAgent = &ua
|
||||
}
|
||||
if id := requestid.FromContext(ctx); id != "" {
|
||||
e.RequestID = &id
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return q.InsertAuditEvent(ctx, e) })
|
||||
if err != nil {
|
||||
s.log.ErrorContext(ctx, "writing audit event failed", "action", e.Action, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// auditQuery reads a page of entries, newest first.
|
||||
func (s *Server) auditQuery(ctx context.Context, scope tenant.Scope, p store.ListAuditEventsParams, pg pageReq) ([]store.ListAuditEventsRow, pageInfo, error) {
|
||||
p.AfterT, p.AfterID, p.BeforeT, p.BeforeID, p.MaxRows = pg.afterT(), pg.afterID(), pg.beforeT(), pg.beforeID(), pg.fetch()
|
||||
var rows []store.ListAuditEventsRow
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAuditEvents(ctx, p)
|
||||
return err
|
||||
})
|
||||
rows, info := paginate(pg, rows, func(r store.ListAuditEventsRow) cursor { return cursor{T: r.Time, ID: r.ID} })
|
||||
return rows, info, err
|
||||
}
|
||||
|
||||
type auditEventView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Action string `json:"action"`
|
||||
ActorID *uuid.UUID `json:"actor_id"`
|
||||
ActorEmail string `json:"actor_email,omitempty"`
|
||||
TokenID *uuid.UUID `json:"token_id,omitempty"`
|
||||
TargetID *uuid.UUID `json:"target_id,omitempty"`
|
||||
Details json.RawMessage `json:"details"`
|
||||
Status int32 `json:"status"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
}
|
||||
|
||||
func auditJSON(c *gin.Context, rows []store.ListAuditEventsRow, info pageInfo, err error) {
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]auditEventView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = auditEventView{
|
||||
ID: r.ID, Time: r.Time, Action: r.Action, ActorID: r.ActorUserID, ActorEmail: r.ActorEmail,
|
||||
TokenID: r.ActorTokenID, TargetID: r.TargetID, Details: r.Details, Status: r.Status,
|
||||
IP: r.Ip, UserAgent: r.UserAgent, RequestID: r.RequestID,
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"events": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
func (s *Server) listOrgAudit(c *gin.Context) {
|
||||
if pg, ok := parsePage(c, apiPageSize); ok {
|
||||
p := current(c)
|
||||
rows, info, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, pg)
|
||||
auditJSON(c, rows, info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listMyAudit(c *gin.Context) {
|
||||
if pg, ok := parsePage(c, apiPageSize); ok {
|
||||
sess := auth.Current(c)
|
||||
rows, info, err := s.auditQuery(c.Request.Context(), tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, pg)
|
||||
auditJSON(c, rows, info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listPlatformAudit(c *gin.Context) {
|
||||
if pg, ok := parsePage(c, apiPageSize); ok {
|
||||
rows, info, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, pg)
|
||||
auditJSON(c, rows, info, err)
|
||||
}
|
||||
}
|
||||
|
||||
// auditEntries prepares rows for the console. Unknown actions, say from a
|
||||
// newer release during a rollout, show their raw name.
|
||||
func auditEntries(c *gin.Context, rows []store.ListAuditEventsRow) []web.AuditEntry {
|
||||
ctx := c.Request.Context()
|
||||
out := make([]web.AuditEntry, len(rows))
|
||||
for i, r := range rows {
|
||||
e := web.AuditEntry{
|
||||
Time: r.Time.Local().Format("2006-01-02 15:04:05"), Action: r.Action,
|
||||
IP: r.Ip, RequestID: r.RequestID, Failed: r.Status >= 400,
|
||||
}
|
||||
if label := i18n.T(ctx, "audit.action."+r.Action); label != "audit.action."+r.Action {
|
||||
e.Action = label
|
||||
}
|
||||
var details map[string]any
|
||||
_ = json.Unmarshal(r.Details, &details)
|
||||
switch {
|
||||
case r.ActorEmail != "":
|
||||
e.Actor = r.ActorEmail
|
||||
case r.ActorUserID != nil || details["actor_deleted"] == true:
|
||||
e.Actor = i18n.T(ctx, "audit.deleted_user")
|
||||
}
|
||||
if r.ActorTokenID != nil {
|
||||
e.Actor += " · " + i18n.T(ctx, "audit.via_token")
|
||||
}
|
||||
if details != nil {
|
||||
for _, f := range auditFields {
|
||||
if v := asString(details[f]); v != "" {
|
||||
e.Target = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) auditView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return nil, errAborted
|
||||
}
|
||||
rows, info, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, pg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return web.AuditPage(page, me, "audit.title", "audit.intro", auditEntries(c, rows), pager(c, info)), nil
|
||||
}
|
||||
|
||||
func (s *Server) adminAuditPage(c *gin.Context) {
|
||||
me, ok := s.adminMe(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, info, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AuditPage(s.pageFor(c, "audit.platform_title"), me, "audit.platform_title", "audit.platform_intro", auditEntries(c, rows), pager(c, info)))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestEveryChangingRouteIsAudited(t *testing.T) {
|
||||
r := gin.New()
|
||||
api.New(config.API{}, api.Deps{Log: slog.New(slog.DiscardHandler)}).Mount(r)
|
||||
for _, rt := range r.Routes() {
|
||||
if rt.Method == http.MethodGet || rt.Method == http.MethodHead || !strings.HasPrefix(rt.Path, "/api/v1/") {
|
||||
continue
|
||||
}
|
||||
if _, ok := api.AuditActions[rt.Method+" "+rt.Path]; !ok {
|
||||
t.Errorf("%s %s is missing from auditActions", rt.Method, rt.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditActionsAreTranslated(t *testing.T) {
|
||||
catalog, err := i18n.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lang := range catalog.Supported() {
|
||||
ctx := i18n.NewContext(context.Background(), catalog.Match(lang))
|
||||
for _, action := range api.AuditActions {
|
||||
if action == "" {
|
||||
continue
|
||||
}
|
||||
for _, id := range []string{"audit.action." + action, "audit.action." + action + "_failed"} {
|
||||
if id == "audit.action."+action+"_failed" && action != "auth.login" {
|
||||
continue
|
||||
}
|
||||
if i18n.T(ctx, id) == id {
|
||||
t.Errorf("%s: %s is not translated", lang, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditLog(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
email := "o@" + uniq("au") + ".test"
|
||||
owner.signup(email, uniq("au-"))
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("au")+".test", uniq("au-"))
|
||||
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{
|
||||
"name": "Ops hook", "type": "webhook", "url": "https://hooks.example.com/x",
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create channel = %d %v", st, body)
|
||||
}
|
||||
signing := body["signing_secret"].(string)
|
||||
st, body = owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create token = %d %v", st, body)
|
||||
}
|
||||
token := body["token"].(string)
|
||||
// Rejected requests change nothing and are not logged.
|
||||
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": ""})
|
||||
|
||||
_, list := owner.do("GET", "/api/v1/org/audit", nil)
|
||||
events := list["events"].([]any)
|
||||
actions := map[string]map[string]any{}
|
||||
for _, ev := range events {
|
||||
m := ev.(map[string]any)
|
||||
actions[m["action"].(string)] = m
|
||||
}
|
||||
ch, ok := actions["channel.create"]
|
||||
if !ok || ch["details"].(map[string]any)["name"] != "Ops hook" || ch["actor_email"] != email || ch["request_id"] == "" {
|
||||
t.Errorf("channel.create entry = %v", ch)
|
||||
}
|
||||
if _, ok := actions["token.create"]; !ok {
|
||||
t.Error("token.create is not logged")
|
||||
}
|
||||
if _, ok := actions["monitor.create"]; ok {
|
||||
t.Error("a rejected request was logged")
|
||||
}
|
||||
|
||||
// Nothing secret ends up in the log.
|
||||
var raw string
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
return tx.QueryRow(context.Background(), `SELECT coalesce(string_agg(details::text, ' '), '') FROM audit_events`).Scan(&raw)
|
||||
})
|
||||
for _, secret := range []string{token, signing} {
|
||||
if strings.Contains(raw, secret) {
|
||||
t.Errorf("audit details contain a secret")
|
||||
}
|
||||
}
|
||||
|
||||
// Other organizations see nothing of it.
|
||||
_, otherList := other.do("GET", "/api/v1/org/audit", nil)
|
||||
for _, ev := range otherList["events"].([]any) {
|
||||
if ev.(map[string]any)["action"] == "channel.create" {
|
||||
t.Error("another organization sees the entry")
|
||||
}
|
||||
}
|
||||
|
||||
// Members without audit.read are refused.
|
||||
viewerEmail := "v@" + uniq("au") + ".test"
|
||||
viewer := e.joinVia(t, owner.invite(viewerEmail, owner.roleID("viewer")))
|
||||
if st, _ := viewer.do("GET", "/api/v1/org/audit", nil); st != http.StatusForbidden {
|
||||
t.Errorf("viewer GET audit = %d, want 403", st)
|
||||
}
|
||||
|
||||
// Failed sign-ins show up in the account's own activity.
|
||||
intruder := e.browser(t)
|
||||
if st, _ := intruder.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "wrong password"}); st != http.StatusUnauthorized {
|
||||
t.Fatalf("login with wrong password = %d", st)
|
||||
}
|
||||
_, mine := owner.do("GET", "/api/v1/me/audit", nil)
|
||||
var failed, signedUp bool
|
||||
for _, ev := range mine["events"].([]any) {
|
||||
switch ev.(map[string]any)["action"] {
|
||||
case "auth.login_failed":
|
||||
failed = true
|
||||
case "account.signup":
|
||||
signedUp = true
|
||||
}
|
||||
}
|
||||
if !failed || !signedUp {
|
||||
t.Errorf("own activity lacks failed sign-in (%t) or signup (%t): %v", failed, signedUp, mine)
|
||||
}
|
||||
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "Sign-in failed") && !strings.Contains(html, "Anmeldung fehlgeschlagen") {
|
||||
t.Error("security page does not show the failed sign-in")
|
||||
}
|
||||
if st, _, html := owner.page("/settings/audit"); st != http.StatusOK || !strings.Contains(html, "Ops hook") {
|
||||
t.Errorf("audit page = %d, lacks the channel", st)
|
||||
}
|
||||
|
||||
// Platform admins see sign-in attempts for unknown accounts.
|
||||
intruder.do("POST", "/api/v1/auth/login", map[string]any{"email": "nobody@" + uniq("n") + ".test", "password": "x"})
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), owner.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, platform := owner.do("GET", "/api/v1/admin/audit", nil)
|
||||
found := false
|
||||
for _, ev := range platform["events"].([]any) {
|
||||
found = found || ev.(map[string]any)["action"] == "auth.login_failed"
|
||||
}
|
||||
if !found {
|
||||
t.Error("platform log lacks the failed sign-in for an unknown account")
|
||||
}
|
||||
}
|
||||
+66
-11
@@ -30,8 +30,11 @@ type signupRequest struct {
|
||||
Email string `json:"email" binding:"required,email,max=320"`
|
||||
Password string `json:"password" binding:"required,max=1024"`
|
||||
DisplayName string `json:"display_name" binding:"max=200"`
|
||||
OrgName string `json:"org_name" binding:"required,max=200"`
|
||||
OrgSlug string `json:"org_slug" binding:"required,max=63"`
|
||||
// OrgName and OrgSlug create a first organization at once, when no
|
||||
// email confirmation is needed; otherwise the account creates one
|
||||
// after confirming.
|
||||
OrgName string `json:"org_name" binding:"max=200"`
|
||||
OrgSlug string `json:"org_slug" binding:"max=63"`
|
||||
}
|
||||
|
||||
func (s *Server) signup(c *gin.Context) {
|
||||
@@ -50,6 +53,15 @@ func (s *Server) signup(c *gin.Context) {
|
||||
fail(c, http.StatusForbidden, "signup_closed")
|
||||
return
|
||||
}
|
||||
if left, err := s.signupsLeft(c); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
} else if !left {
|
||||
fail(c, http.StatusTooManyRequests, "signup_limit")
|
||||
return
|
||||
}
|
||||
verify := s.verificationRequired()
|
||||
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if errors.Is(err, auth.ErrPasswordTooShort) {
|
||||
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
||||
@@ -63,20 +75,27 @@ func (s *Server) signup(c *gin.Context) {
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
user, err = q.CreateUser(ctx, store.CreateUserParams{
|
||||
params := store.CreateUserParams{
|
||||
Email: normalizeEmail(req.Email),
|
||||
DisplayName: strings.TrimSpace(req.DisplayName),
|
||||
PasswordHash: &hash,
|
||||
Locale: ptr(i18n.Lang(ctx)),
|
||||
})
|
||||
EmailKey: ptr(emailKey(req.Email)),
|
||||
}
|
||||
if !verify {
|
||||
params.EmailVerifiedAt = ptr(time.Now())
|
||||
}
|
||||
user, err = q.CreateUser(ctx, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
|
||||
return err
|
||||
if withOrg {
|
||||
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Whoever sets up a self-hosted installation operates it.
|
||||
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
|
||||
@@ -85,7 +104,7 @@ func (s *Server) signup(c *gin.Context) {
|
||||
return nil
|
||||
})
|
||||
switch {
|
||||
case isUniqueViolation(err, "users_email_key"):
|
||||
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
|
||||
fail(c, http.StatusConflict, "email_taken")
|
||||
return
|
||||
case isUniqueViolation(err, "orgs_slug_key"):
|
||||
@@ -98,10 +117,27 @@ func (s *Server) signup(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.countSignup(c)
|
||||
if verify {
|
||||
auditActor(c, user.ID)
|
||||
if err := s.sendVerification(ctx, user); err != nil {
|
||||
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
|
||||
fail(c, http.StatusBadGateway, "verification_mail_failed")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "verification_sent", "redirect": "/signup/sent"})
|
||||
return
|
||||
}
|
||||
if !withOrg {
|
||||
orgID = uuid.Nil
|
||||
}
|
||||
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: orgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
|
||||
}
|
||||
|
||||
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
|
||||
if s.signupClosedWithoutMail() {
|
||||
return false, nil
|
||||
}
|
||||
switch s.cfg.Signup {
|
||||
case config.SignupOpen:
|
||||
return true, nil
|
||||
@@ -129,6 +165,7 @@ func (s *Server) login(c *gin.Context) {
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
email := normalizeEmail(req.Email)
|
||||
auditDetail(c, "email", email)
|
||||
if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
@@ -148,15 +185,26 @@ func (s *Server) login(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auditActor(c, user.ID)
|
||||
ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok || user.DisabledAt != nil {
|
||||
if !ok {
|
||||
invalidCredentials(c)
|
||||
return
|
||||
}
|
||||
// Only someone who knows the password learns of the suspension or a
|
||||
// missing confirmation.
|
||||
if user.DisabledAt != nil {
|
||||
fail(c, http.StatusForbidden, "account_suspended")
|
||||
return
|
||||
}
|
||||
if user.EmailVerifiedAt == nil {
|
||||
fail(c, http.StatusForbidden, "email_unverified")
|
||||
return
|
||||
}
|
||||
if rehash {
|
||||
s.rehashPassword(ctx, user.ID, req.Password)
|
||||
}
|
||||
@@ -168,6 +216,7 @@ func (s *Server) login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setCookie(c, mfaCookie, token, int(mfaTTL.Seconds()))
|
||||
auditSkip(c)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "totp_required"})
|
||||
return
|
||||
}
|
||||
@@ -207,6 +256,7 @@ func (s *Server) loginTOTP(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auditActor(c, userID)
|
||||
ok, err := s.verifySecondFactor(ctx, userID, req.Code)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
@@ -239,6 +289,10 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Metho
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if user.DisabledAt != nil {
|
||||
fail(c, http.StatusForbidden, "account_suspended")
|
||||
return
|
||||
}
|
||||
var org uuid.UUID
|
||||
if len(orgs) > 0 {
|
||||
org = orgs[0].ID
|
||||
@@ -255,6 +309,7 @@ func (s *Server) startSession(c *gin.Context, n auth.NewSession) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auditActor(c, n.UserID)
|
||||
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -22,11 +23,14 @@ import (
|
||||
|
||||
type channelRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Type string `json:"type" binding:"required,oneof=webhook email"`
|
||||
Type string `json:"type" binding:"required,max=32"`
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
To []string `json:"to" binding:"max=20,dive,max=320"`
|
||||
Locale string `json:"locale" binding:"max=10"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
// Settings configure the other channel types, as listed by
|
||||
// notify.Providers; secret settings left empty keep their value.
|
||||
Settings map[string]string `json:"settings" binding:"max=20"`
|
||||
}
|
||||
|
||||
type channelView struct {
|
||||
@@ -37,6 +41,10 @@ type channelView struct {
|
||||
URL string `json:"url,omitempty"`
|
||||
To []string `json:"to,omitempty"`
|
||||
Locale string `json:"locale,omitempty"`
|
||||
// Settings and SecretsSet describe other channel types; secret values
|
||||
// are never returned.
|
||||
Settings map[string]string `json:"settings,omitempty"`
|
||||
SecretsSet []string `json:"secrets_set,omitempty"`
|
||||
}
|
||||
|
||||
func viewChannel(ch store.NotificationChannel) channelView {
|
||||
@@ -50,6 +58,8 @@ func viewChannel(ch store.NotificationChannel) channelView {
|
||||
var c emailConfig
|
||||
_ = json.Unmarshal(ch.Config, &c)
|
||||
v.To, v.Locale = c.To, c.Locale
|
||||
default:
|
||||
v.Settings, v.SecretsSet, v.Locale = providerView(ch.Config)
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -109,6 +119,10 @@ func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []b
|
||||
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
|
||||
return config, "", ""
|
||||
}
|
||||
if p, ok := notify.Lookup(req.Type); ok {
|
||||
config, code = s.providerSettings(p, req, previous)
|
||||
return config, "", code
|
||||
}
|
||||
return nil, "", "invalid_input"
|
||||
}
|
||||
|
||||
@@ -277,15 +291,45 @@ type incidentView struct {
|
||||
Cause map[string]string `json:"cause"`
|
||||
}
|
||||
|
||||
func (s *Server) listIncidents(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
// incidentPage reads a page of incidents, newest first, of one monitor
|
||||
// if monitor is set.
|
||||
func (s *Server) incidentPage(ctx context.Context, p *principal, pg pageReq, monitor *uuid.UUID) ([]store.ListIncidentsRow, pageInfo, error) {
|
||||
var rows []store.ListIncidentsRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListIncidents(ctx)
|
||||
rows, err = q.ListIncidents(ctx, store.ListIncidentsParams{
|
||||
MonitorID: monitor, AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
||||
})
|
||||
return err
|
||||
})
|
||||
rows, info := paginate(pg, rows, func(r store.ListIncidentsRow) cursor { return cursor{T: r.StartedAt, ID: r.ID} })
|
||||
return rows, info, err
|
||||
}
|
||||
|
||||
// monitorFilter reads the optional monitor query parameter.
|
||||
func monitorFilter(c *gin.Context, name string) (*uuid.UUID, bool) {
|
||||
raw := c.Query(name)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
func (s *Server) listIncidents(c *gin.Context) {
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
monitor, ok := monitorFilter(c, "monitor_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, info, err := s.incidentPage(c.Request.Context(), current(c), pg, monitor)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -295,5 +339,5 @@ func (s *Server) listIncidents(c *gin.Context) {
|
||||
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt}
|
||||
_ = json.Unmarshal(r.Cause, &out[i].Cause)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"incidents": out})
|
||||
c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
@@ -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)
|
||||
@@ -207,3 +259,38 @@ func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A checker that lost the answer to a report sends it again; the results
|
||||
// must not be stored twice.
|
||||
func TestResultReportIsIdempotent(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
monitor := uuid.MustParse(m["id"].(string))
|
||||
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
at := time.Now().Truncate(time.Millisecond)
|
||||
batch := []agentapi.Result{
|
||||
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
|
||||
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
|
||||
}
|
||||
for range 3 {
|
||||
if err := client.Report(context.Background(), batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 {
|
||||
t.Errorf("stored results = %d, want 2", n)
|
||||
}
|
||||
// Another instance's run of the same schedule time is its own result.
|
||||
other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
if err := other.Report(context.Background(), batch[:1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 {
|
||||
t.Errorf("stored results = %d, want 3", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Whether checkers may check private addresses: platform checkers follow
|
||||
// a platform setting, organizations' checkers their own flag.
|
||||
|
||||
const settingPlatformPrivate = "platform_checkers_private"
|
||||
|
||||
// platformPrivate reports whether platform checkers may reach private
|
||||
// addresses. Unset, they may on self-hosted installations only: in the
|
||||
// cloud they share the operator's network.
|
||||
func (s *Server) platformPrivate(ctx context.Context) bool {
|
||||
v, err := s.checkerNet.get(ctx, s.rdb, func(ctx context.Context) (bool, error) {
|
||||
allow := !s.cloud()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingPlatformPrivate)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, &allow)
|
||||
})
|
||||
return allow, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading checker network setting failed", "error", err)
|
||||
return false
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (s *Server) allowPrivate(ctx context.Context, a store.GetAgentByHashRow) bool {
|
||||
if a.OrgID != nil {
|
||||
return a.AllowPrivate
|
||||
}
|
||||
return s.platformPrivate(ctx)
|
||||
}
|
||||
|
||||
type checkerNetwork struct {
|
||||
// AllowPrivate lets platform checkers check private addresses.
|
||||
AllowPrivate bool `json:"allow_private"`
|
||||
}
|
||||
|
||||
func (s *Server) adminGetCheckerNetwork(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, checkerNetwork{AllowPrivate: s.platformPrivate(c.Request.Context())})
|
||||
}
|
||||
|
||||
func (s *Server) adminSetCheckerNetwork(c *gin.Context) {
|
||||
var req checkerNetwork
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(req.AllowPrivate)
|
||||
auditDetail(c, "allow_private", req.AllowPrivate)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingPlatformPrivate, Value: raw})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.checkerNet.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing checker network change failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type agentUpdate struct {
|
||||
AllowPrivate bool `json:"allow_private"`
|
||||
}
|
||||
|
||||
// updateOrgAgent changes whether one of the organization's checkers may
|
||||
// check private addresses; it applies from the checker's next poll.
|
||||
func (s *Server) updateOrgAgent(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req agentUpdate
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
auditDetail(c, "allow_private", req.AllowPrivate)
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
n, err = q.SetAgentAllowPrivate(ctx, store.SetAgentAllowPrivateParams{ID: id, OrgID: &p.Org.ID, AllowPrivate: req.AllowPrivate})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// latestOf returns the newest result of a monitor: ok and the error.
|
||||
func latestOf(b *browser, id string) (bool, string, bool) {
|
||||
_, list := b.do("GET", "/api/v1/org/monitors", nil)
|
||||
for _, m := range list["monitors"].([]any) {
|
||||
m := m.(map[string]any)
|
||||
if m["id"] != id {
|
||||
continue
|
||||
}
|
||||
if l := m["latest"].([]any); len(l) > 0 {
|
||||
r := l[0].(map[string]any)
|
||||
msg, _ := r["error"].(string)
|
||||
return r["ok"] == true, msg, true
|
||||
}
|
||||
}
|
||||
return false, "", false
|
||||
}
|
||||
|
||||
func TestCheckerNetwork(t *testing.T) {
|
||||
// In the cloud edition, platform checkers stay off private networks
|
||||
// unless an admin allows it.
|
||||
cloud := newEnvWith(t, func(c *config.API) { c.Edition, c.SignupVerify = config.EditionCloud, "off" })
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
reset := func() {
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(context.Background(), `DELETE FROM platform_settings WHERE key = 'platform_checkers_private'`)
|
||||
return err
|
||||
})
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(reset)
|
||||
|
||||
// A private service: the test's own loopback.
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = l.Close() })
|
||||
go func() {
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
tok, platformRegion := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("net")+".test", uniq("net-"))
|
||||
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), owner.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
monitor := func(region string) string {
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Internal", "type": "tcp", "target": l.Addr().String(), "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
waitResult := func(id string, ok bool, what string) {
|
||||
t.Helper()
|
||||
waitFor(t, 20*time.Second, what, func() bool {
|
||||
got, msg, seen := latestOf(owner, id)
|
||||
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
|
||||
})
|
||||
}
|
||||
|
||||
admin := cloud.browser(t)
|
||||
admin.signup("a@"+uniq("net")+".test", uniq("neta-"))
|
||||
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, body := admin.do("GET", "/api/v1/admin/checker-network", nil); body["allow_private"] != false {
|
||||
t.Errorf("cloud default = %v", body)
|
||||
}
|
||||
|
||||
// Self-hosted, platform checkers may by default; an admin can forbid it.
|
||||
pm := monitor(platformRegion)
|
||||
waitResult(pm, true, "platform checker reaching a private address")
|
||||
if st, body := owner.do("PUT", "/api/v1/admin/checker-network", map[string]any{"allow_private": false}); st != http.StatusNoContent {
|
||||
t.Fatalf("forbid = %d %v", st, body)
|
||||
}
|
||||
waitResult(pm, false, "platform checker refusing the private address once forbidden")
|
||||
owner.do("DELETE", "/api/v1/org/monitors/"+pm, nil)
|
||||
|
||||
// An organization's checker can be kept off private networks.
|
||||
_, region := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
|
||||
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region["id"], "allow_private": false})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create agent = %d %v", st, agent)
|
||||
}
|
||||
e.startChecker(t, agent["token"].(string))
|
||||
om := monitor(region["id"].(string))
|
||||
waitResult(om, false, "org checker kept off private addresses")
|
||||
_, agents := owner.do("GET", "/api/v1/org/agents", nil)
|
||||
if raw := mustJSON(agents); !strings.Contains(raw, `"allow_private":false`) {
|
||||
t.Errorf("agents = %s", raw)
|
||||
}
|
||||
if st, body := owner.do("PATCH", "/api/v1/org/agents/"+agent["id"].(string), map[string]any{"allow_private": true}); st != http.StatusNoContent {
|
||||
t.Fatalf("patch agent = %d %v", st, body)
|
||||
}
|
||||
waitResult(om, true, "org checker reaching the private address once allowed")
|
||||
|
||||
// Other organizations cannot change it.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("net")+".test", uniq("netx-"))
|
||||
st, body := other.do("PATCH", "/api/v1/org/agents/"+agent["id"].(string), map[string]any{"allow_private": false})
|
||||
expect(t, "foreign agent", st, body, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestOrgCheckTypes(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("oct")+".test", uniq("oct-"))
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("oct")+".test", uniq("octx-"))
|
||||
|
||||
_, tcp := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Port", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
|
||||
if st, body := owner.do("PUT", "/api/v1/org/check-types", map[string]any{"enabled": []string{"http", "dns"}}); st != http.StatusNoContent {
|
||||
t.Fatalf("set = %d %v", st, body)
|
||||
}
|
||||
if _, body := owner.do("GET", "/api/v1/org/check-types", nil); mustJSON(body["types"]) != `["http","dns"]` {
|
||||
t.Errorf("offered = %v", body["types"])
|
||||
}
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
|
||||
expect(t, "switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+tcp["id"].(string), map[string]any{"name": "Port 2", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
|
||||
expect(t, "existing monitor of a switched-off type", st, body, http.StatusOK, "")
|
||||
if _, _, page := owner.page("/monitors/new"); strings.Contains(page, `value="tcp"`) || !strings.Contains(page, `value="dns"`) {
|
||||
t.Error("the editor offers types the organization switched off")
|
||||
}
|
||||
if _, _, page := owner.page("/settings/org"); !strings.Contains(page, `value="icmp"`) {
|
||||
t.Error("the settings page lacks the check types")
|
||||
}
|
||||
st, body = owner.do("PUT", "/api/v1/org/check-types", map[string]any{"enabled": []string{}})
|
||||
expect(t, "switching off everything", st, body, http.StatusUnprocessableEntity, "all_check_types_disabled")
|
||||
|
||||
// Other organizations keep everything.
|
||||
if _, body := other.do("GET", "/api/v1/org/check-types", nil); !strings.Contains(mustJSON(body), `"icmp"`) {
|
||||
t.Errorf("other organization offered %v", body["types"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"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/web"
|
||||
)
|
||||
|
||||
// running:<instance> maps monitor IDs to "<org>|<taken ms>|<timeout ms>"
|
||||
// for runs handed out and not yet reported. It shows what a checker is
|
||||
// doing; entries of crashed instances are ignored once their checks would
|
||||
// have timed out.
|
||||
func runningKey(instance uuid.UUID) string { return "running:" + instance.String() }
|
||||
|
||||
// runningGrace is how long past its timeout a run counts as in progress,
|
||||
// covering the report delay.
|
||||
const runningGrace = 30 * time.Second
|
||||
|
||||
func (s *Server) trackRunning(ctx context.Context, instance uuid.UUID, jobs []agentapi.Job, orgs map[uuid.UUID]uuid.UUID) {
|
||||
if len(jobs) == 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
fields := make([]any, 0, 2*len(jobs))
|
||||
for _, j := range jobs {
|
||||
fields = append(fields, j.MonitorID.String(), fmt.Sprintf("%s|%d|%d", orgs[j.MonitorID], now, j.TimeoutMS))
|
||||
}
|
||||
key := runningKey(instance)
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.HSet(ctx, key, fields...)
|
||||
p.Expire(ctx, key, 15*time.Minute)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "tracking running checks failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) finishRunning(ctx context.Context, instance uuid.UUID, results []agentapi.Result) {
|
||||
if len(results) == 0 {
|
||||
return
|
||||
}
|
||||
ids := make([]string, len(results))
|
||||
for i, r := range results {
|
||||
ids[i] = r.MonitorID.String()
|
||||
}
|
||||
if err := s.rdb.HDel(ctx, runningKey(instance), ids...).Err(); err != nil {
|
||||
s.log.WarnContext(ctx, "clearing running checks failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// runningRun is a check an instance is working on.
|
||||
type runningRun struct {
|
||||
MonitorID uuid.UUID
|
||||
Org uuid.UUID
|
||||
Since time.Time
|
||||
}
|
||||
|
||||
func (s *Server) runningOn(ctx context.Context, instance uuid.UUID, now time.Time) ([]runningRun, error) {
|
||||
all, err := s.rdb.HGetAll(ctx, runningKey(instance)).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []runningRun
|
||||
for id, v := range all {
|
||||
parts := strings.Split(v, "|")
|
||||
if len(parts) != 3 {
|
||||
continue
|
||||
}
|
||||
m, err1 := uuid.Parse(id)
|
||||
org, err2 := uuid.Parse(parts[0])
|
||||
at, err3 := strconv.ParseInt(parts[1], 10, 64)
|
||||
timeout, err4 := strconv.ParseInt(parts[2], 10, 64)
|
||||
if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
|
||||
continue
|
||||
}
|
||||
since := time.UnixMilli(at)
|
||||
if now.Sub(since) > time.Duration(timeout)*time.Millisecond+runningGrace {
|
||||
continue
|
||||
}
|
||||
out = append(out, runningRun{MonitorID: m, Org: org, Since: since})
|
||||
}
|
||||
slices.SortFunc(out, func(a, b runningRun) int { return a.Since.Compare(b.Since) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// checkerActivity is what the console and API show of a checker instance.
|
||||
// Platform checkers work for every organization: only the viewer's own
|
||||
// monitors are named, the rest is counted.
|
||||
type checkerActivity struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Agent string `json:"agent"`
|
||||
Region string `json:"region"`
|
||||
Platform bool `json:"platform"`
|
||||
Release string `json:"release"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
LastSeenAt time.Time `json:"last_seen_at"`
|
||||
Live bool `json:"live"`
|
||||
Queued int64 `json:"queued"`
|
||||
Running []runningView `json:"running"`
|
||||
OtherOrgs int `json:"running_for_others"`
|
||||
LastHour checkerHourStats `json:"last_hour"`
|
||||
Recent []recentByCheck `json:"recent"`
|
||||
// NextCursor and PrevCursor page through Recent, newest first.
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
PrevCursor string `json:"prev_cursor,omitempty"`
|
||||
Siblings []uuid.UUID `json:"other_instances"`
|
||||
regionID string
|
||||
monitorName map[uuid.UUID]string
|
||||
}
|
||||
|
||||
type runningView struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Monitor string `json:"monitor"`
|
||||
Since time.Time `json:"since"`
|
||||
}
|
||||
|
||||
type checkerHourStats struct {
|
||||
Checks int64 `json:"checks"`
|
||||
Failed int64 `json:"failed"`
|
||||
AvgLatencyMS float32 `json:"avg_latency_ms"`
|
||||
}
|
||||
|
||||
type recentByCheck struct {
|
||||
Time time.Time `json:"time"`
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Monitor string `json:"monitor"`
|
||||
OK bool `json:"ok"`
|
||||
LatencyMS *int32 `json:"latency_ms,omitempty"`
|
||||
StatusCode *int32 `json:"status_code,omitempty"`
|
||||
Error *string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
var errNoChecker = errors.New("api: checker not found")
|
||||
|
||||
// loadCheckerActivity gathers the activity of a checker instance visible to
|
||||
// p: platform instances and those of p's organization.
|
||||
func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance uuid.UUID, pg pageReq) (checkerActivity, error) {
|
||||
now := time.Now()
|
||||
a := checkerActivity{ID: instance, Running: []runningView{}, Recent: []recentByCheck{}, Siblings: []uuid.UUID{}, monitorName: map[uuid.UUID]string{}}
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
readable := map[uuid.UUID]bool{}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
rows, err := q.AgentInstancesByID(ctx, []uuid.UUID{instance})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 || rows[0].Kind != "checker" {
|
||||
return errNoChecker
|
||||
}
|
||||
r := rows[0]
|
||||
a.Agent, a.Region, a.Platform, a.Release = r.AgentName, r.RegionName, r.OrgID == nil, r.Release
|
||||
a.StartedAt, a.LastSeenAt = r.StartedAt, r.LastSeenAt
|
||||
if r.RegionID != nil {
|
||||
a.regionID = r.RegionID.String()
|
||||
}
|
||||
siblings, err := q.SiblingInstances(ctx, r.AgentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, sb := range siblings {
|
||||
if sb.ID != instance {
|
||||
a.Siblings = append(a.Siblings, sb.ID)
|
||||
}
|
||||
}
|
||||
monitors, err := q.ListMonitors(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if canInGroup(p, authz.MonitorsRead, t, m.GroupID) {
|
||||
readable[m.ID] = true
|
||||
a.monitorName[m.ID] = m.Name
|
||||
}
|
||||
}
|
||||
stats, err := q.CheckerStats(ctx, store.CheckerStatsParams{OrgID: p.Org.ID, CheckerID: instance})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.LastHour = checkerHourStats{Checks: stats.Total, Failed: stats.Failed, AvgLatencyMS: stats.AvgLatencyMs}
|
||||
recent, err := q.ResultsByChecker(ctx, store.ResultsByCheckerParams{
|
||||
OrgID: p.Org.ID, CheckerID: instance, AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
|
||||
})
|
||||
// Pages are cut before filtering, so cursors follow every result
|
||||
// and a page may show fewer than it read.
|
||||
recent, info := paginate(pg, recent, func(r store.ResultsByCheckerRow) cursor {
|
||||
return cursor{T: r.Time, S: r.MonitorID.String() + "|" + r.Region}
|
||||
})
|
||||
a.NextCursor, a.PrevCursor = info.Next, info.Prev
|
||||
for _, r := range recent {
|
||||
if readable[r.MonitorID] {
|
||||
a.Recent = append(a.Recent, recentByCheck{
|
||||
Time: r.Time, MonitorID: r.MonitorID, Monitor: a.monitorName[r.MonitorID], OK: r.Ok,
|
||||
LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error,
|
||||
})
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
if a.regionID != "" {
|
||||
if seen, err := s.sched.LastSeen(ctx, a.regionID, instance); err == nil && !seen.IsZero() {
|
||||
a.LastSeenAt = seen
|
||||
a.Live = now.Sub(seen) < schedule.StaleAfter
|
||||
}
|
||||
}
|
||||
if a.Queued, err = s.sched.QueueLen(ctx, instance); err != nil {
|
||||
return a, err
|
||||
}
|
||||
running, err := s.runningOn(ctx, instance, now)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
for _, r := range running {
|
||||
if r.Org != p.Org.ID || !readable[r.MonitorID] {
|
||||
a.OtherOrgs++
|
||||
continue
|
||||
}
|
||||
a.Running = append(a.Running, runningView{MonitorID: r.MonitorID, Monitor: a.monitorName[r.MonitorID], Since: r.Since})
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *Server) getChecker(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a, err := s.loadCheckerActivity(c.Request.Context(), current(c), id, pg)
|
||||
if errors.Is(err, errNoChecker) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, a)
|
||||
}
|
||||
|
||||
func (s *Server) checkerPage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return nil, errAborted
|
||||
}
|
||||
a, err := s.loadCheckerActivity(c.Request.Context(), p, id, pg)
|
||||
if errors.Is(err, errNoChecker) {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
const layout = "2006-01-02 15:04:05"
|
||||
v := web.CheckerView{
|
||||
ID: a.ID.String(), Agent: a.Agent, Region: a.Region, Platform: a.Platform, Release: a.Release,
|
||||
Started: a.StartedAt.Local().Format(layout), LastSeen: a.LastSeenAt.Local().Format(layout), Live: a.Live,
|
||||
Queued: int(a.Queued), OtherOrgs: a.OtherOrgs,
|
||||
Checks: int(a.LastHour.Checks), Failed: int(a.LastHour.Failed), AvgLatency: fmt.Sprintf("%.0f ms", a.LastHour.AvgLatencyMS),
|
||||
}
|
||||
now := time.Now()
|
||||
for _, r := range a.Running {
|
||||
v.Running = append(v.Running, web.CheckerRun{
|
||||
MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor, For: now.Sub(r.Since).Round(time.Second).String(),
|
||||
})
|
||||
}
|
||||
// Live while showing the latest results; paged back, with dates.
|
||||
timeLayout := "15:04:05"
|
||||
if pg.at() != nil {
|
||||
timeLayout = "01-02 15:04:05"
|
||||
}
|
||||
v.Pager = pager(c, pageInfo{Next: a.NextCursor, Prev: a.PrevCursor})
|
||||
for _, r := range a.Recent {
|
||||
row := web.CheckerResult{
|
||||
Time: r.Time.Local().Format(timeLayout), MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor,
|
||||
OK: r.OK, Latency: "–", Detail: deref(r.Error),
|
||||
}
|
||||
if r.LatencyMS != nil {
|
||||
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMS)
|
||||
}
|
||||
if row.Detail == "" && r.StatusCode != nil {
|
||||
row.Detail = strconv.Itoa(int(*r.StatusCode))
|
||||
}
|
||||
v.Recent = append(v.Recent, row)
|
||||
}
|
||||
for _, sb := range a.Siblings {
|
||||
v.Siblings = append(v.Siblings, web.CheckerLink{URL: "/checkers/" + sb.String(), Label: shortID(sb)})
|
||||
}
|
||||
if pg.at() == nil {
|
||||
page.RefreshSeconds = 5
|
||||
}
|
||||
return web.CheckerPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func shortID(id uuid.UUID) string { return id.String()[:8] }
|
||||
|
||||
// checkerLinks names the checker instances in ids for result lists.
|
||||
func (s *Server) checkerLinks(ctx context.Context, p *principal, ids []uuid.UUID) (map[uuid.UUID]web.CheckerLink, error) {
|
||||
out := map[uuid.UUID]web.CheckerLink{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
var rows []store.AgentInstancesByIDRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.AgentInstancesByID(ctx, ids)
|
||||
return err
|
||||
})
|
||||
for _, r := range rows {
|
||||
out[r.ID] = web.CheckerLink{URL: "/checkers/" + r.ID.String(), Label: r.AgentName + " · " + shortID(r.ID)}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestCheckerActivity(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(3 * time.Second)
|
||||
}))
|
||||
defer slow.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
instance, _ := e.startChecker(t, tok)
|
||||
|
||||
alice, bob := e.browser(t), e.browser(t)
|
||||
alice.signup("a@"+uniq("ca")+".test", uniq("ca-"))
|
||||
bob.signup("b@"+uniq("cb")+".test", uniq("cb-"))
|
||||
create := func(b *browser, name string) string {
|
||||
t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": name, "type": "http", "target": slow.URL, "interval_seconds": 3600, "timeout_ms": 5000, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
aliceMonitor := create(alice, "Alice shop")
|
||||
create(bob, "Bob secret service")
|
||||
|
||||
path := "/api/v1/org/checkers/" + instance.String()
|
||||
var view map[string]any
|
||||
waitFor(t, 10*time.Second, "both checks in progress", func() bool {
|
||||
_, view = alice.do("GET", path, nil)
|
||||
running, _ := view["running"].([]any)
|
||||
return len(running) == 1 && view["running_for_others"] == float64(1)
|
||||
})
|
||||
if raw := mustJSON(view); strings.Contains(raw, "Bob secret service") || view["live"] != true || view["platform"] != true {
|
||||
t.Errorf("alice's view = %s", raw)
|
||||
}
|
||||
if _, bv := bob.do("GET", path, nil); strings.Contains(mustJSON(bv), "Alice shop") {
|
||||
t.Error("bob sees alice's monitor")
|
||||
}
|
||||
|
||||
waitFor(t, 10*time.Second, "the finished check listed", func() bool {
|
||||
_, view = alice.do("GET", path, nil)
|
||||
recent, _ := view["recent"].([]any)
|
||||
running, _ := view["running"].([]any)
|
||||
return len(recent) == 1 && len(running) == 0
|
||||
})
|
||||
if _, _, page := alice.page("/monitors/" + aliceMonitor); !strings.Contains(page, `href="/checkers/`+instance.String()+`"`) {
|
||||
t.Error("the monitor page does not link the checker that ran the check")
|
||||
}
|
||||
st, _, page := alice.page("/checkers/" + instance.String())
|
||||
if st != http.StatusOK || !strings.Contains(page, "Alice shop") || strings.Contains(page, "Bob secret service") || !strings.Contains(page, `http-equiv="refresh"`) {
|
||||
t.Errorf("checker page = %d, lacks own monitor, shows others or does not refresh", st)
|
||||
}
|
||||
|
||||
// Checkers of another organization stay invisible.
|
||||
bobOrg := uuid.MustParse(bob.orgID())
|
||||
var bobTok string
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.System(), func(q *store.Queries) error {
|
||||
r, err := q.CreateRegion(context.Background(), store.CreateRegionParams{OrgID: &bobOrg, Key: uniq("own-"), Name: "Bob DC"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var params store.CreateAgentParams
|
||||
bobTok, params = api.NewAgentToken(&bobOrg, "checker", "bob-dc", &r.ID)
|
||||
_, err = q.CreateAgent(context.Background(), params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bobInstance, _ := e.startChecker(t, bobTok)
|
||||
waitFor(t, 5*time.Second, "bob's checker registered", func() bool {
|
||||
st, _ := bob.do("GET", "/api/v1/org/checkers/"+bobInstance.String(), nil)
|
||||
return st == http.StatusOK
|
||||
})
|
||||
if st, _ := alice.do("GET", "/api/v1/org/checkers/"+bobInstance.String(), nil); st != http.StatusNotFound {
|
||||
t.Errorf("alice sees bob's own checker: %d", st)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Platform admins can switch off check types the installation cannot
|
||||
// offer, such as Docker on shared cloud checkers. Switched-off types are
|
||||
// not offered for new monitors; existing ones keep running and stay
|
||||
// editable.
|
||||
|
||||
const settingDisabledChecks = "disabled_check_types"
|
||||
|
||||
func (s *Server) disabledChecks(ctx context.Context) map[string]bool {
|
||||
set, err := s.checkTypes.get(ctx, s.rdb, func(ctx context.Context) (map[string]bool, error) {
|
||||
out := map[string]bool{}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingDisabledChecks)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var list []string
|
||||
_ = json.Unmarshal(raw, &list)
|
||||
for _, t := range list {
|
||||
out[t] = true
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading disabled check types failed", "error", err)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// offered reports whether org may create monitors of type t: neither the
|
||||
// platform nor the organization switched it off.
|
||||
func (s *Server) offered(ctx context.Context, org store.Org, t string) bool {
|
||||
return slices.Contains(s.enabledCheckTypes(ctx, org, ""), t)
|
||||
}
|
||||
|
||||
// enabledCheckTypes lists the types offered to org for new monitors, plus
|
||||
// keep when a monitor of a switched-off type is being edited. The
|
||||
// organization's choice is ignored if it would leave nothing, which can
|
||||
// happen when the platform later switches off what it kept.
|
||||
func (s *Server) enabledCheckTypes(ctx context.Context, org store.Org, keep string) []string {
|
||||
off := s.disabledChecks(ctx)
|
||||
var platform, out []string
|
||||
for _, t := range check.Types {
|
||||
if off[string(t)] && string(t) != keep {
|
||||
continue
|
||||
}
|
||||
platform = append(platform, string(t))
|
||||
if !slices.Contains(org.DisabledCheckTypes, string(t)) || string(t) == keep {
|
||||
out = append(out, string(t))
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return platform
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type checkTypeView struct {
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func (s *Server) adminListCheckTypes(c *gin.Context) {
|
||||
off := s.disabledChecks(c.Request.Context())
|
||||
out := make([]checkTypeView, len(check.Types))
|
||||
for i, t := range check.Types {
|
||||
out[i] = checkTypeView{Type: string(t), Enabled: !off[string(t)]}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"types": out})
|
||||
}
|
||||
|
||||
type checkTypesRequest struct {
|
||||
// Enabled lists the types to offer; all others are switched off.
|
||||
Enabled []string `json:"enabled" binding:"max=100"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetCheckTypes(c *gin.Context) {
|
||||
var req checkTypesRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
var disabled []string
|
||||
for _, t := range check.Types {
|
||||
if !slices.Contains(req.Enabled, string(t)) {
|
||||
disabled = append(disabled, string(t))
|
||||
}
|
||||
}
|
||||
for _, t := range req.Enabled {
|
||||
if !slices.Contains(check.Types, check.Type(t)) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_type")
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(disabled) == len(check.Types) {
|
||||
fail(c, http.StatusUnprocessableEntity, "all_check_types_disabled")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(append([]string{}, disabled...))
|
||||
auditDetail(c, "disabled", disabled)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingDisabledChecks, Value: raw})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.checkTypes.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing check type change failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// orgCheckTypes tells API clients which monitor types they can create.
|
||||
func (s *Server) orgCheckTypes(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"types": s.enabledCheckTypes(c.Request.Context(), current(c).Org, "")})
|
||||
}
|
||||
|
||||
// orgSetCheckTypes chooses which of the platform's types the organization
|
||||
// offers its members.
|
||||
func (s *Server) orgSetCheckTypes(c *gin.Context) {
|
||||
var req checkTypesRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
off := s.disabledChecks(ctx)
|
||||
disabled := []string{}
|
||||
enabled := 0
|
||||
for _, t := range check.Types {
|
||||
switch {
|
||||
case slices.Contains(req.Enabled, string(t)):
|
||||
enabled++
|
||||
case !off[string(t)]:
|
||||
disabled = append(disabled, string(t))
|
||||
}
|
||||
}
|
||||
for _, t := range req.Enabled {
|
||||
if !slices.Contains(check.Types, check.Type(t)) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_type")
|
||||
return
|
||||
}
|
||||
}
|
||||
if enabled == 0 {
|
||||
fail(c, http.StatusUnprocessableEntity, "all_check_types_disabled")
|
||||
return
|
||||
}
|
||||
auditDetail(c, "disabled", disabled)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
return q.SetOrgDisabledCheckTypes(ctx, store.SetOrgDisabledCheckTypesParams{ID: p.Org.ID, DisabledCheckTypes: disabled})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestCheckTypesCanBeSwitchedOff(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
// A second replica, started first: starting it clears the Redis test
|
||||
// database, sessions included.
|
||||
other := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
admin := e.browser(t)
|
||||
admin.signup("a@"+uniq("ct")+".test", uniq("ct-"))
|
||||
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all := make([]string, len(check.Types))
|
||||
for i, ty := range check.Types {
|
||||
all[i] = string(ty)
|
||||
}
|
||||
// The setting is platform-wide: reset it directly, whatever happens
|
||||
// to sessions during the test.
|
||||
reset := func() {
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(context.Background(), `DELETE FROM platform_settings WHERE key = 'disabled_check_types'`)
|
||||
return err
|
||||
})
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(reset)
|
||||
|
||||
// A heartbeat created while allowed stays editable afterwards.
|
||||
_, hb := admin.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600})
|
||||
_, tcp := admin.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Port", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
|
||||
|
||||
enabled := slices.DeleteFunc(slices.Clone(all), func(s string) bool { return s == "icmp" || s == "heartbeat" })
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/check-types", map[string]any{"enabled": enabled}); st != http.StatusNoContent {
|
||||
t.Fatalf("switch off = %d %v", st, body)
|
||||
}
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/check-types", map[string]any{"enabled": []string{}}); st != http.StatusUnprocessableEntity {
|
||||
t.Errorf("switching off everything = %d %v", st, body)
|
||||
}
|
||||
|
||||
// Another replica sees the change at once.
|
||||
member := other.browser(t)
|
||||
member.signup("m@"+uniq("ct")+".test", uniq("ctm-"))
|
||||
_, types := member.do("GET", "/api/v1/org/check-types", nil)
|
||||
if raw := mustJSON(types); strings.Contains(raw, `"icmp"`) || strings.Contains(raw, `"heartbeat"`) || !strings.Contains(raw, `"http"`) {
|
||||
t.Errorf("offered types = %s", raw)
|
||||
}
|
||||
st, body := member.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
|
||||
expect(t, "create switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
if _, _, page := member.page("/monitors/new"); strings.Contains(page, `value="icmp"`) || !strings.Contains(page, `value="http"`) {
|
||||
t.Error("the editor still offers a switched-off type")
|
||||
}
|
||||
|
||||
st, body = admin.do("PUT", "/api/v1/org/monitors/"+hb["id"].(string), map[string]any{"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200})
|
||||
expect(t, "edit existing heartbeat", st, body, http.StatusOK, "")
|
||||
st, body = admin.do("PUT", "/api/v1/org/monitors/"+tcp["id"].(string), map[string]any{"name": "Port", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{region}})
|
||||
expect(t, "switch to a switched-off type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
if _, _, page := admin.page("/monitors/" + hb["id"].(string) + "/edit"); !strings.Contains(page, `value="heartbeat" selected`) {
|
||||
t.Error("editing a monitor of a switched-off type does not keep its type")
|
||||
}
|
||||
}
|
||||
+912
-65
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
}
|
||||
|
||||
@@ -58,6 +65,7 @@ func TestConsolePages(t *testing.T) {
|
||||
"/monitors/new": {`name="regions"`},
|
||||
"/incidents": {"Checkout API", "unexpected status 502"},
|
||||
"/settings/channels": {"hooks.example.test"},
|
||||
"/settings": {`href="/settings/members"`, `href="/groups"`},
|
||||
}
|
||||
for path, wants := range pages {
|
||||
st, final, html := owner.page(path)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestDatabaseMonitorSecrets(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
pg, _ := url.Parse(os.Getenv("UPTIME_TEST_DATABASE_URL"))
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("db")+".test", uniq("db-"))
|
||||
monitor := map[string]any{
|
||||
"name": "Main DB", "type": "postgres", "target": pg.Host, "interval_seconds": 10, "timeout_ms": 5000, "confirmations": 1,
|
||||
"regions": []string{region},
|
||||
"config": map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"},
|
||||
}
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
if _, hasPassword := body["config"].(map[string]any)["password"]; hasPassword || mustJSON(body["secrets_set"]) != `["password"]` {
|
||||
t.Errorf("create answer exposes or misses the password: %s", mustJSON(body))
|
||||
}
|
||||
var stored string
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
return tx.QueryRow(context.Background(), `SELECT config::text FROM monitors WHERE id = $1`, id).Scan(&stored)
|
||||
})
|
||||
if strings.Contains(stored, `"password"`) || !strings.Contains(stored, "sealed_password") {
|
||||
t.Errorf("stored config = %s", stored)
|
||||
}
|
||||
|
||||
latestOK := func() bool {
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
for _, m := range list["monitors"].([]any) {
|
||||
if l := m.(map[string]any)["latest"].([]any); len(l) > 0 && l[0].(map[string]any)["ok"] == true {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
waitFor(t, 15*time.Second, "the checker signing in with the sealed password", latestOK)
|
||||
|
||||
// Saving without the password keeps it.
|
||||
monitor["config"] = map[string]any{"user": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"}
|
||||
if st, body := owner.do("PUT", "/api/v1/org/monitors/"+id, monitor); st != http.StatusOK || mustJSON(body["secrets_set"]) != `["password"]` {
|
||||
t.Fatalf("update without password = %d %v", st, body)
|
||||
}
|
||||
if _, _, page := owner.page("/monitors/" + id + "/edit"); strings.Contains(page, `value="uptime_test"`) == false || strings.Contains(page, "sealed_") {
|
||||
t.Error("the editor lacks the settings or shows the sealed password")
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
_, _, export := owner.download("/api/v1/org/export?format=json")
|
||||
for _, raw := range []string{mustJSON(list), string(export)} {
|
||||
if strings.Contains(raw, "sealed_password") {
|
||||
t.Error("a sealed password leaves the API")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolMonitorSecrets(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("proto")+".test", uniq("proto-"))
|
||||
for _, tc := range []struct {
|
||||
typ, target string
|
||||
config map[string]any
|
||||
secrets string
|
||||
}{
|
||||
{"radius", "radius.example.com:1812", map[string]any{"secret": "radius-shared-1", "user": "probe", "password": "radius-pw-1"}, `["password","secret"]`},
|
||||
{"snmp", "switch.example.com:161", map[string]any{"community": "snmp-comm-1", "oid": "1.3.6.1.2.1.1.5.0"}, `["community"]`},
|
||||
} {
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": tc.typ, "type": tc.typ, "target": tc.target, "interval_seconds": 60, "regions": []string{region}, "config": tc.config,
|
||||
})
|
||||
if st != http.StatusCreated || mustJSON(body["secrets_set"]) != tc.secrets {
|
||||
t.Fatalf("create %s = %d %s", tc.typ, st, mustJSON(body))
|
||||
}
|
||||
_, _, page := owner.page("/monitors/" + body["id"].(string) + "/edit")
|
||||
for _, v := range tc.config {
|
||||
if s := v.(string); strings.Contains(s, "-1") && (strings.Contains(page, s) || strings.Contains(mustJSON(body), s)) {
|
||||
t.Errorf("%s: secret %q leaves the server", tc.typ, s)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(page, `name="config.`) {
|
||||
t.Errorf("%s: editor lacks the settings", tc.typ)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxEvidence bounds what a checker may send per result; the body
|
||||
// excerpt is 32 KiB before JSON escaping.
|
||||
maxEvidence = 256 << 10
|
||||
// failureEvidenceEvery thins out evidence of a lasting outage that
|
||||
// keeps failing the same way.
|
||||
failureEvidenceEvery = 5 * time.Minute
|
||||
)
|
||||
|
||||
// storeEvidence keeps the evidence of accepted results: per monitor and
|
||||
// region the latest success, and failures unless an identical one was kept
|
||||
// within failureEvidenceEvery. Evidence is an aid; failures are logged and
|
||||
// never fail the report.
|
||||
func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if len(r.Evidence) == 0 || !ok {
|
||||
continue
|
||||
}
|
||||
if len(r.Evidence) > maxEvidence || !json.Valid(r.Evidence) {
|
||||
s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence))
|
||||
continue
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if r.OK {
|
||||
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
last, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{MonitorID: m.ID, Region: region})
|
||||
if err == nil && last.Error == r.Error && r.StartedAt.Sub(last.Time) < failureEvidenceEvery {
|
||||
return nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
row := store.InsertEvidenceParams{
|
||||
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
|
||||
}
|
||||
if r.StatusCode > 0 {
|
||||
row.StatusCode = ptr(int32(r.StatusCode))
|
||||
}
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
return q.InsertEvidence(ctx, row)
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// evidenceMonitor loads the monitor of an evidence request, enforcing write
|
||||
// access: responses may contain personal data or secrets of the checked
|
||||
// service, so only those who configure the monitor see them.
|
||||
func (s *Server) evidenceMonitor(c *gin.Context) (store.Monitor, groupTree, bool) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return store.Monitor{}, groupTree{}, false
|
||||
}
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return store.Monitor{}, groupTree{}, false
|
||||
}
|
||||
var m store.Monitor
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
m, err = q.GetMonitor(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !canInGroup(p, authz.MonitorsRead, t, m.GroupID)) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return m, t, false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return m, t, false
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return m, t, false
|
||||
}
|
||||
return m, t, true
|
||||
}
|
||||
|
||||
type evidenceSummary struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Region string `json:"region"`
|
||||
Time time.Time `json:"time"`
|
||||
OK bool `json:"ok"`
|
||||
StatusCode *int32 `json:"status_code,omitempty"`
|
||||
Error *string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) listEvidence(c *gin.Context) {
|
||||
m, _, ok := s.evidenceMonitor(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListEvidenceRow
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEvidence(ctx, store.ListEvidenceParams{
|
||||
MonitorID: m.ID, AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
rows, info := paginate(pg, rows, func(r store.ListEvidenceRow) cursor { return cursor{T: r.Time, ID: r.ID} })
|
||||
out := make([]evidenceSummary, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = evidenceSummary{ID: r.ID, Region: r.Region, Time: r.Time, OK: r.Ok, StatusCode: r.StatusCode, Error: r.Error}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"evidence": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
func (s *Server) loadEvidence(c *gin.Context, m store.Monitor) (store.CheckEvidence, check.Evidence, bool) {
|
||||
id, err := uuid.Parse(c.Param("evidence"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return store.CheckEvidence{}, check.Evidence{}, false
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.CheckEvidence
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.GetEvidence(ctx, store.GetEvidenceParams{ID: id, MonitorID: m.ID})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return row, check.Evidence{}, false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return row, check.Evidence{}, false
|
||||
}
|
||||
var ev check.Evidence
|
||||
_ = json.Unmarshal(row.Evidence, &ev)
|
||||
return row, ev, true
|
||||
}
|
||||
|
||||
func (s *Server) getEvidence(c *gin.Context) {
|
||||
m, _, ok := s.evidenceMonitor(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
row, ev, ok := s.loadEvidence(c, m)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"id": row.ID, "region": row.Region, "checker_id": row.CheckerID, "time": row.Time, "ok": row.Ok,
|
||||
"status_code": row.StatusCode, "error": row.Error, "evidence": ev,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) evidencePage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
d, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, ok := d.byID[id]
|
||||
if !ok || !canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID) {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
evID, err := uuid.Parse(c.Param("evidence"))
|
||||
if err != nil {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
var row store.CheckEvidence
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.GetEvidence(ctx, store.GetEvidenceParams{ID: evID, MonitorID: m.ID})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ev check.Evidence
|
||||
_ = json.Unmarshal(row.Evidence, &ev)
|
||||
return web.EvidencePage(page, me, evidenceView(m, d.regionNameString(row.Region), row, ev)), nil
|
||||
}
|
||||
|
||||
func evidenceView(m store.Monitor, region string, row store.CheckEvidence, ev check.Evidence) web.EvidenceView {
|
||||
v := web.EvidenceView{
|
||||
MonitorID: m.ID.String(), MonitorName: m.Name, Time: row.Time.Local().Format("2006-01-02 15:04:05"), Region: region,
|
||||
OK: row.Ok, Error: deref(row.Error), RemoteAddr: ev.RemoteAddr, ContentType: ev.ContentType,
|
||||
Truncated: ev.BodyTruncated, Binary: ev.BodyBinary, Body: prettyBody(ev.ContentType, ev.Body),
|
||||
Total: fmt.Sprintf("%.1f ms", ev.Timing.Total),
|
||||
}
|
||||
if slices.Contains([]string{"dns", "connect", "tls", "response", "body"}, ev.FailedAt) {
|
||||
v.FailedAt = ev.FailedAt
|
||||
}
|
||||
phases := []struct {
|
||||
key string
|
||||
ms float64
|
||||
}{{"dns", ev.Timing.DNS}, {"connect", ev.Timing.Connect}, {"tls", ev.Timing.TLS}, {"wait", ev.Timing.Wait}, {"download", ev.Timing.Download}}
|
||||
var sum float64
|
||||
for _, ph := range phases {
|
||||
sum += ph.ms
|
||||
}
|
||||
for _, ph := range phases {
|
||||
p := web.TimingPhase{Key: ph.key, Value: fmt.Sprintf("%.1f ms", ph.ms)}
|
||||
if sum > 0 {
|
||||
p.Percent = ph.ms / sum * 100
|
||||
}
|
||||
v.Phases = append(v.Phases, p)
|
||||
}
|
||||
for _, st := range ev.Steps {
|
||||
ws := web.EvidenceStep{Method: st.Method, URL: st.URL, Proto: st.Proto,
|
||||
RequestHeaders: sortedHeaders(st.RequestHeaders), ResponseHeaders: sortedHeaders(st.ResponseHeaders)}
|
||||
if st.Status > 0 {
|
||||
ws.Status = strconv.Itoa(st.Status) + " " + http.StatusText(st.Status)
|
||||
}
|
||||
v.Steps = append(v.Steps, ws)
|
||||
}
|
||||
if t := ev.TLS; t != nil {
|
||||
v.TLS = &web.TLSView{
|
||||
Version: t.Version, Cipher: t.Cipher, Subject: t.Subject, Issuer: t.Issuer, Names: strings.Join(t.DNSNames, ", "),
|
||||
NotBefore: t.NotBefore.UTC().Format("2006-01-02"), NotAfter: t.NotAfter.UTC().Format("2006-01-02"),
|
||||
DaysLeft: int(math.Floor(time.Until(t.NotAfter).Hours() / 24)),
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func sortedHeaders(h map[string][]string) [][2]string {
|
||||
keys := make([]string, 0, len(h))
|
||||
for k := range h {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
var out [][2]string
|
||||
for _, k := range keys {
|
||||
for _, v := range h[k] {
|
||||
out = append(out, [2]string{k, v})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// prettyBody indents complete JSON bodies; anything else is shown as sent.
|
||||
func prettyBody(contentType, body string) string {
|
||||
if !strings.Contains(contentType, "json") {
|
||||
return body
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if json.Indent(&buf, []byte(body), "", " ") != nil {
|
||||
return body
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// evidenceShown is how much of a monitor's evidence its page lists.
|
||||
const evidenceShown = 20
|
||||
|
||||
// evidenceRows lists the latest stored evidence of m for its page.
|
||||
func (s *Server) evidenceRows(ctx context.Context, p *principal, d monitorData, m store.Monitor) ([]web.EvidenceRow, error) {
|
||||
var rows []store.ListEvidenceRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEvidence(ctx, store.ListEvidenceParams{MonitorID: m.ID, MaxRows: evidenceShown})
|
||||
return err
|
||||
})
|
||||
out := make([]web.EvidenceRow, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
detail := deref(r.Error)
|
||||
if detail == "" && r.StatusCode != nil {
|
||||
detail = strconv.Itoa(int(*r.StatusCode))
|
||||
}
|
||||
out = append(out, web.EvidenceRow{
|
||||
URL: "/monitors/" + m.ID.String() + "/evidence/" + r.ID.String(), Time: r.Time.Local().Format("01-02 15:04:05"),
|
||||
Region: d.regionNameString(r.Region), OK: r.Ok, Detail: detail,
|
||||
})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// evidenceKey matches evidence with the check result it belongs to.
|
||||
func evidenceKey(region string, t time.Time) string {
|
||||
return region + "@" + strconv.FormatInt(t.UnixMicro(), 10)
|
||||
}
|
||||
|
||||
// resultView is one check result.
|
||||
type resultView struct {
|
||||
Time time.Time `json:"time"`
|
||||
Region string `json:"region"`
|
||||
CheckerID uuid.UUID `json:"checker_id"`
|
||||
OK bool `json:"ok"`
|
||||
LatencyMS *int32 `json:"latency_ms"`
|
||||
StatusCode *int32 `json:"status_code,omitempty"`
|
||||
Error *string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// listResults pages through a monitor's check results, newest first.
|
||||
func (s *Server) listResults(c *gin.Context) {
|
||||
m, _, ok := s.evidenceMonitor(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, info, err := s.resultPage(c.Request.Context(), current(c), m, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]resultView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = resultView{r.Time, r.Region, r.CheckerID, r.Ok, r.LatencyMs, r.StatusCode, r.Error}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"results": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEvidence(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
var healthy atomic.Bool
|
||||
site := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/" {
|
||||
http.Redirect(w, r, "/app", http.StatusFound)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "cookie-secret"})
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
_, _ = w.Write([]byte(`<script>alert("pwned")</script> upstream down`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("all good"))
|
||||
}))
|
||||
defer site.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("ev")+".test", uniq("ev-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "http", "target": site.URL + "/", "interval_seconds": 10, "timeout_ms": 2000,
|
||||
"confirmations": 1, "regions": []string{region}, "config": map[string]any{"verify_tls": false, "headers": map[string]string{"X-Token": "header-secret"}},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
evidence := func() []any {
|
||||
_, b := owner.do("GET", "/api/v1/org/monitors/"+id+"/evidence", nil)
|
||||
list, _ := b["evidence"].([]any)
|
||||
return list
|
||||
}
|
||||
waitFor(t, 15*time.Second, "evidence of the failure", func() bool { return len(evidence()) > 0 })
|
||||
first := evidence()[0].(map[string]any)
|
||||
_, detail := owner.do("GET", "/api/v1/org/monitors/"+id+"/evidence/"+first["id"].(string), nil)
|
||||
raw := mustJSON(detail)
|
||||
for _, want := range []string{`"status":302`, `"status":502`, `"not_after"`, `upstream down`} {
|
||||
if !strings.Contains(raw, want) {
|
||||
t.Errorf("evidence lacks %s: %.600s", want, raw)
|
||||
}
|
||||
}
|
||||
steps := detail["evidence"].(map[string]any)["steps"].([]any)
|
||||
cookie := steps[len(steps)-1].(map[string]any)["response_headers"].(map[string]any)["Set-Cookie"].([]any)
|
||||
if len(cookie) != 1 || cookie[0] != "sid=<redacted>" {
|
||||
t.Errorf("Set-Cookie = %v, want the name only", cookie)
|
||||
}
|
||||
for _, secret := range []string{"cookie-secret", "header-secret"} {
|
||||
if strings.Contains(raw, secret) {
|
||||
t.Errorf("evidence contains %s", secret)
|
||||
}
|
||||
}
|
||||
|
||||
// The page shows the body as text, never as markup.
|
||||
_, _, page := owner.page("/monitors/" + id + "/evidence/" + first["id"].(string))
|
||||
if strings.Contains(page, `<script>alert("pwned")`) || !strings.Contains(page, "<script>") {
|
||||
t.Error("the evidence page renders the response body as HTML")
|
||||
}
|
||||
if !strings.Contains(page, "502 Bad Gateway") || !strings.Contains(page, "/app") {
|
||||
t.Error("the evidence page lacks the redirect chain")
|
||||
}
|
||||
if _, _, mp := owner.page("/monitors/" + id); !strings.Contains(mp, "/evidence/") {
|
||||
t.Error("the monitor page does not link the evidence")
|
||||
}
|
||||
|
||||
// A lasting outage with the same error is kept once.
|
||||
time.Sleep(12 * time.Second)
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, id); n != 1 {
|
||||
t.Errorf("failure evidence rows = %d, want 1", n)
|
||||
}
|
||||
healthy.Store(true)
|
||||
waitFor(t, 25*time.Second, "evidence of a success", func() bool {
|
||||
return e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok`, id) == 1
|
||||
})
|
||||
|
||||
// Readers get neither the list nor the page.
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("ev")+".test", owner.roleID("viewer")))
|
||||
if st, _ := viewer.do("GET", "/api/v1/org/monitors/"+id+"/evidence", nil); st != http.StatusForbidden {
|
||||
t.Errorf("viewer lists evidence = %d, want 403", st)
|
||||
}
|
||||
if got := viewer.visit("/monitors/" + id + "/evidence/" + first["id"].(string)); got.Path != "/" {
|
||||
t.Errorf("viewer opening evidence ended at %s, want /", got.Path)
|
||||
}
|
||||
if _, _, vp := viewer.page("/monitors/" + id); strings.Contains(vp, "/evidence/") {
|
||||
t.Error("the monitor page links evidence for a viewer")
|
||||
}
|
||||
}
|
||||
@@ -2,3 +2,18 @@ package api
|
||||
|
||||
// LookupTXT lets tests replace DNS lookups for domain verification.
|
||||
var LookupTXT = &lookupTXT
|
||||
|
||||
// AuditActions exposes the audited routes to tests.
|
||||
var AuditActions = auditActions
|
||||
|
||||
// DocumentedRoutes lists the routes in the OpenAPI table.
|
||||
func DocumentedRoutes() []string {
|
||||
out := make([]string, len(endpoints))
|
||||
for i, e := range endpoints {
|
||||
out[i] = e.method + " " + e.path
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OpenAPI builds the OpenAPI document.
|
||||
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
|
||||
@@ -0,0 +1,164 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/pdf"
|
||||
)
|
||||
|
||||
// renderExportPDF lays out an export struct as a readable document. It
|
||||
// walks the same values as the JSON export, so both always contain the
|
||||
// same data; fields tagged pdf:"-" are too bulky for paper and are only in
|
||||
// the JSON file.
|
||||
func renderExportPDF(ctx context.Context, w io.Writer, title string, x any) error {
|
||||
d := pdf.New(title)
|
||||
d.Title(title)
|
||||
v := reflect.ValueOf(x)
|
||||
t := v.Type()
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
name := jsonName(f)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if f.Tag.Get("pdf") == "-" {
|
||||
d.Heading(exportLabel(ctx, name))
|
||||
d.Paragraph(i18n.T(ctx, "export.json_only"))
|
||||
continue
|
||||
}
|
||||
fv := v.Field(i)
|
||||
if fv.Kind() == reflect.Struct && !isScalar(fv) {
|
||||
d.Heading(exportLabel(ctx, name))
|
||||
writeStruct(ctx, d, 0, fv)
|
||||
continue
|
||||
}
|
||||
if fv.Kind() == reflect.Slice && !isScalar(fv) {
|
||||
d.Heading(fmt.Sprintf("%s (%d)", exportLabel(ctx, name), fv.Len()))
|
||||
writeList(ctx, d, fv)
|
||||
continue
|
||||
}
|
||||
d.Field(0, exportLabel(ctx, name), scalar(ctx, fv))
|
||||
}
|
||||
return d.Write(w)
|
||||
}
|
||||
|
||||
func writeList(ctx context.Context, d *pdf.Document, v reflect.Value) {
|
||||
if v.Len() == 0 {
|
||||
d.Paragraph(i18n.T(ctx, "export.none"))
|
||||
return
|
||||
}
|
||||
for i := range v.Len() {
|
||||
if i > 0 {
|
||||
d.Gap()
|
||||
}
|
||||
writeStruct(ctx, d, 0, v.Index(i))
|
||||
}
|
||||
}
|
||||
|
||||
func writeStruct(ctx context.Context, d *pdf.Document, indent int, v reflect.Value) {
|
||||
t := v.Type()
|
||||
for i := range t.NumField() {
|
||||
name := jsonName(t.Field(i))
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
fv := v.Field(i)
|
||||
if fv.Kind() == reflect.Slice && !isScalar(fv) && fv.Type().Elem().Kind() == reflect.Struct {
|
||||
d.Field(indent, exportLabel(ctx, name), fmt.Sprint(fv.Len()))
|
||||
for j := range fv.Len() {
|
||||
writeStruct(ctx, d, indent+1, fv.Index(j))
|
||||
}
|
||||
continue
|
||||
}
|
||||
d.Field(indent, exportLabel(ctx, name), scalar(ctx, fv))
|
||||
}
|
||||
}
|
||||
|
||||
func jsonName(f reflect.StructField) string {
|
||||
tag, _, _ := strings.Cut(f.Tag.Get("json"), ",")
|
||||
if tag == "-" {
|
||||
return ""
|
||||
}
|
||||
return tag
|
||||
}
|
||||
|
||||
var (
|
||||
timeType = reflect.TypeFor[time.Time]()
|
||||
uuidType = reflect.TypeFor[uuid.UUID]()
|
||||
rawType = reflect.TypeFor[json.RawMessage]()
|
||||
)
|
||||
|
||||
// isScalar reports whether v prints on one line.
|
||||
func isScalar(v reflect.Value) bool {
|
||||
switch v.Type() {
|
||||
case timeType, uuidType, rawType:
|
||||
return true
|
||||
}
|
||||
if v.Kind() == reflect.Slice {
|
||||
k := v.Type().Elem().Kind()
|
||||
return k != reflect.Struct || v.Type().Elem() == uuidType
|
||||
}
|
||||
return v.Kind() != reflect.Struct
|
||||
}
|
||||
|
||||
func scalar(ctx context.Context, v reflect.Value) string {
|
||||
if v.Kind() == reflect.Pointer {
|
||||
if v.IsNil() {
|
||||
return "–"
|
||||
}
|
||||
v = v.Elem()
|
||||
}
|
||||
switch v.Type() {
|
||||
case timeType:
|
||||
return v.Interface().(time.Time).UTC().Format("2006-01-02 15:04:05 UTC")
|
||||
case uuidType:
|
||||
return v.Interface().(uuid.UUID).String()
|
||||
case rawType:
|
||||
var buf bytes.Buffer
|
||||
if json.Compact(&buf, v.Interface().(json.RawMessage)) != nil {
|
||||
return string(v.Interface().(json.RawMessage))
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
switch v.Kind() {
|
||||
case reflect.Bool:
|
||||
if v.Bool() {
|
||||
return i18n.T(ctx, "export.yes")
|
||||
}
|
||||
return i18n.T(ctx, "export.no")
|
||||
case reflect.Slice:
|
||||
if v.Len() == 0 {
|
||||
return "–"
|
||||
}
|
||||
parts := make([]string, v.Len())
|
||||
for i := range v.Len() {
|
||||
parts[i] = scalar(ctx, v.Index(i))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
case reflect.String:
|
||||
if v.String() == "" {
|
||||
return "–"
|
||||
}
|
||||
}
|
||||
return fmt.Sprint(v.Interface())
|
||||
}
|
||||
|
||||
// exportLabel translates a JSON field name, falling back to the name
|
||||
// itself for fields added without a translation.
|
||||
func exportLabel(ctx context.Context, name string) string {
|
||||
id := "export.field." + name
|
||||
if s := i18n.T(ctx, id); s != id {
|
||||
return s
|
||||
}
|
||||
return strings.ReplaceAll(name, "_", " ")
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"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/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Exports answer GDPR access and portability requests (Art. 15 and 20):
|
||||
// the account export holds everything stored about a person, the
|
||||
// organization export what an organization configured and recorded.
|
||||
// Secrets such as password hashes, token hashes and sealed credentials are
|
||||
// never part of them.
|
||||
|
||||
type accountExport struct {
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Account exportAccount `json:"account"`
|
||||
Organizations []exportMembership `json:"organizations"`
|
||||
Identities []exportIdentity `json:"sso_identities"`
|
||||
Tokens []exportToken `json:"api_tokens"`
|
||||
Activity []exportActivity `json:"activity"`
|
||||
}
|
||||
|
||||
type exportAccount struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Locale string `json:"locale"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
TOTPEnabledAt *time.Time `json:"totp_enabled_at"`
|
||||
PlatformAdmin bool `json:"platform_admin"`
|
||||
}
|
||||
|
||||
type exportMembership struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
Owner bool `json:"owner"`
|
||||
MemberSince time.Time `json:"member_since"`
|
||||
Roles []exportRole `json:"roles"`
|
||||
}
|
||||
|
||||
type exportRole struct {
|
||||
Name string `json:"name"`
|
||||
ResourceType *string `json:"resource_type,omitempty"`
|
||||
ResourceID *uuid.UUID `json:"resource_id,omitempty"`
|
||||
}
|
||||
|
||||
type exportIdentity struct {
|
||||
Provider string `json:"provider"`
|
||||
Organization uuid.UUID `json:"organization_id"`
|
||||
Subject string `json:"subject"`
|
||||
Email *string `json:"email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastLoginAt time.Time `json:"last_login_at"`
|
||||
}
|
||||
|
||||
type exportToken struct {
|
||||
Organization uuid.UUID `json:"organization_id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Permissions []string `json:"permissions"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type exportActivity struct {
|
||||
Time time.Time `json:"time"`
|
||||
Action string `json:"action"`
|
||||
Organization *uuid.UUID `json:"organization_id,omitempty"`
|
||||
TargetID *uuid.UUID `json:"target_id,omitempty"`
|
||||
Details json.RawMessage `json:"details"`
|
||||
Status int32 `json:"status"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (accountExport, error) {
|
||||
x := accountExport{GeneratedAt: time.Now().UTC()}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
u, err := q.GetUser(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Account = exportAccount{
|
||||
ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, Locale: deref(u.Locale), CreatedAt: u.CreatedAt,
|
||||
HasPassword: u.PasswordHash != nil, TOTPEnabledAt: u.TotpEnabledAt, PlatformAdmin: u.IsAdmin,
|
||||
}
|
||||
roles, err := q.UserRoleNames(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byOrg := map[uuid.UUID][]exportRole{}
|
||||
for _, r := range roles {
|
||||
byOrg[r.OrgID] = append(byOrg[r.OrgID], exportRole{Name: r.Name, ResourceType: r.ResourceType, ResourceID: r.ResourceID})
|
||||
}
|
||||
ms, err := q.UserMemberships(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Organizations = []exportMembership{}
|
||||
for _, m := range ms {
|
||||
x.Organizations = append(x.Organizations, exportMembership{
|
||||
ID: m.ID, Slug: m.Slug, Name: m.Name, Owner: m.IsOwner, MemberSince: m.CreatedAt, Roles: orEmpty(byOrg[m.ID]),
|
||||
})
|
||||
}
|
||||
ids, err := q.UserIdentities(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Identities = []exportIdentity{}
|
||||
for _, i := range ids {
|
||||
x.Identities = append(x.Identities, exportIdentity{
|
||||
Provider: i.Provider, Organization: i.OrgID, Subject: i.Subject, Email: i.Email, CreatedAt: i.CreatedAt, LastLoginAt: i.LastLoginAt,
|
||||
})
|
||||
}
|
||||
toks, err := q.UserTokens(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Tokens = []exportToken{}
|
||||
for _, t := range toks {
|
||||
x.Tokens = append(x.Tokens, exportToken{
|
||||
Organization: t.OrgID, Name: t.Name, Prefix: t.Prefix, Permissions: t.Permissions,
|
||||
ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt,
|
||||
})
|
||||
}
|
||||
events, err := q.UserAuditEvents(ctx, &userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Activity = []exportActivity{}
|
||||
for _, e := range events {
|
||||
x.Activity = append(x.Activity, exportActivity{
|
||||
Time: e.Time, Action: e.Action, Organization: e.OrgID, TargetID: e.TargetID,
|
||||
Details: e.Details, Status: e.Status, IP: e.Ip, UserAgent: e.UserAgent,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return x, err
|
||||
}
|
||||
|
||||
func orEmpty[T any](s []T) []T {
|
||||
if s == nil {
|
||||
return []T{}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) exportAccount(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
ctx := c.Request.Context()
|
||||
x, err := s.buildAccountExport(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
format := exportFormat(c)
|
||||
s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &sess.UserID, Action: "account.export", Status: http.StatusOK},
|
||||
map[string]any{"format": format})
|
||||
s.sendExport(c, format, "account-"+x.Account.ID.String()[:8], i18n.T(ctx, "export.account_title"), x)
|
||||
}
|
||||
|
||||
// exportFormat is "json" unless the request asks for "pdf".
|
||||
func exportFormat(c *gin.Context) string {
|
||||
if c.Query("format") == "pdf" {
|
||||
return "pdf"
|
||||
}
|
||||
return "json"
|
||||
}
|
||||
|
||||
func (s *Server) sendExport(c *gin.Context, format, name, title string, x any) {
|
||||
stamp := time.Now().UTC().Format("20060102")
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if format == "pdf" {
|
||||
var buf bytes.Buffer
|
||||
if err := renderExportPDF(c.Request.Context(), &buf, title, x); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="uptimesebi-%s-%s.pdf"`, name, stamp))
|
||||
c.Data(http.StatusOK, "application/pdf", buf.Bytes())
|
||||
return
|
||||
}
|
||||
raw, err := json.MarshalIndent(x, "", " ")
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="uptimesebi-%s-%s.json"`, name, stamp))
|
||||
c.Data(http.StatusOK, "application/json", raw)
|
||||
}
|
||||
|
||||
type orgExport struct {
|
||||
AlertGroups []alertGroupView `json:"alert_groups"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Organization exportOrg `json:"organization"`
|
||||
Members []exportMember `json:"members"`
|
||||
Roles []exportCustomRole `json:"custom_roles"`
|
||||
Groups []exportGroup `json:"monitor_groups"`
|
||||
Monitors []exportMonitor `json:"monitors"`
|
||||
Channels []exportChannel `json:"notification_channels"`
|
||||
StatusPages []exportStatusPage `json:"status_pages"`
|
||||
SSO []exportSSO `json:"sso_providers"`
|
||||
Agents []exportAgent `json:"agents"`
|
||||
Incidents []exportIncident `json:"incidents"`
|
||||
Audit []exportAuditEntry `json:"audit_log"`
|
||||
DailyStats []exportDailyStat `json:"daily_statistics" pdf:"-"`
|
||||
}
|
||||
|
||||
type exportOrg struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
RequireTOTP bool `json:"require_totp"`
|
||||
RequireSSO bool `json:"require_sso"`
|
||||
APITokenMaxDays *int32 `json:"api_token_max_days"`
|
||||
}
|
||||
|
||||
type exportMember struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Owner bool `json:"owner"`
|
||||
MemberSince time.Time `json:"member_since"`
|
||||
Roles []exportRole `json:"roles"`
|
||||
}
|
||||
|
||||
type exportCustomRole struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Permissions []string `json:"permissions"`
|
||||
}
|
||||
|
||||
type exportGroup struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ParentID *uuid.UUID `json:"parent_id"`
|
||||
}
|
||||
|
||||
type exportMonitor struct {
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Target string `json:"target"`
|
||||
IntervalSeconds int32 `json:"interval_seconds"`
|
||||
TimeoutMS int32 `json:"timeout_ms"`
|
||||
Confirmations int32 `json:"confirmations"`
|
||||
Enabled bool `json:"enabled"`
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
Regions []uuid.UUID `json:"region_ids"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type exportChannel struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type exportStatusPage struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
Groups []pageGroupView `json:"groups"`
|
||||
Monitors []exportPageMember `json:"monitors"`
|
||||
}
|
||||
|
||||
type exportPageMember struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
Section string `json:"section"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
type exportSSO struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Issuer string `json:"issuer"`
|
||||
ClientID string `json:"client_id"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedDomains []string `json:"allowed_domains"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type exportAgent struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
Region *string `json:"region"`
|
||||
}
|
||||
|
||||
type exportIncident struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Monitor *string `json:"monitor"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ResolvedAt *time.Time `json:"resolved_at"`
|
||||
Cause json.RawMessage `json:"cause"`
|
||||
}
|
||||
|
||||
type exportAuditEntry struct {
|
||||
Time time.Time `json:"time"`
|
||||
Action string `json:"action"`
|
||||
Actor string `json:"actor"`
|
||||
TargetID *uuid.UUID `json:"target_id,omitempty"`
|
||||
Details json.RawMessage `json:"details"`
|
||||
Status int32 `json:"status"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
}
|
||||
|
||||
type exportDailyStat struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Region string `json:"region"`
|
||||
Day time.Time `json:"day"`
|
||||
Total int64 `json:"total"`
|
||||
OK int64 `json:"ok"`
|
||||
AvgLatencyMS float32 `json:"avg_latency_ms"`
|
||||
}
|
||||
|
||||
func rawJSON(b []byte) json.RawMessage {
|
||||
if len(b) == 0 {
|
||||
return json.RawMessage("null")
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, error) {
|
||||
x := orgExport{GeneratedAt: time.Now().UTC()}
|
||||
org := p.Org.ID
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
o, err := q.GetOrg(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Organization = exportOrg{ID: o.ID, Slug: o.Slug, Name: o.Name, CreatedAt: o.CreatedAt,
|
||||
RequireTOTP: o.RequireTotp, RequireSSO: o.RequireSso, APITokenMaxDays: o.ApiTokenMaxDays}
|
||||
|
||||
assignments, err := q.OrgAssignmentsExport(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
roles := map[uuid.UUID][]exportRole{}
|
||||
for _, a := range assignments {
|
||||
roles[a.UserID] = append(roles[a.UserID], exportRole{Name: a.Role, ResourceType: a.ResourceType, ResourceID: a.ResourceID})
|
||||
}
|
||||
members, err := q.OrgMembersExport(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Members = []exportMember{}
|
||||
for _, m := range members {
|
||||
x.Members = append(x.Members, exportMember{ID: m.ID, Email: m.Email, DisplayName: m.DisplayName, Owner: m.IsOwner, MemberSince: m.CreatedAt, Roles: orEmpty(roles[m.ID])})
|
||||
}
|
||||
|
||||
rs, err := q.ListRoles(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Roles = []exportCustomRole{}
|
||||
for _, r := range rs {
|
||||
if r.OrgID != nil {
|
||||
x.Roles = append(x.Roles, exportCustomRole{ID: r.ID, Name: r.Name, Permissions: r.Permissions})
|
||||
}
|
||||
}
|
||||
groups, err := q.ListGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Groups = []exportGroup{}
|
||||
for _, g := range groups {
|
||||
x.Groups = append(x.Groups, exportGroup{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
||||
}
|
||||
|
||||
alertGroups, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.AlertGroups = []alertGroupView{}
|
||||
for _, g := range alertGroups {
|
||||
x.AlertGroups = append(x.AlertGroups, alertGroupView{
|
||||
ID: g.ID, Name: g.Name, IsDefault: g.IsDefault,
|
||||
ChannelIDs: g.ChannelIds, QuietHours: decodeQuietHours(g.QuietHours),
|
||||
})
|
||||
}
|
||||
alertAssignments, err := q.AllMonitorAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
alertGroupsByMonitor := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, a := range alertAssignments {
|
||||
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regionRows, err := q.AllMonitorRegions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
regions := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, r := range regionRows {
|
||||
regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID)
|
||||
}
|
||||
monitors, err := q.ListMonitors(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Monitors = []exportMonitor{}
|
||||
for _, m := range monitors {
|
||||
x.Monitors = append(x.Monitors, exportMonitor{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Confirmations: m.Confirmations, Enabled: m.Enabled, GroupID: m.GroupID,
|
||||
AlertGroupIDs: orEmpty(alertGroupsByMonitor[m.ID]),
|
||||
Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
channels, err := q.ListChannels(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Channels = []exportChannel{}
|
||||
for _, ch := range channels {
|
||||
x.Channels = append(x.Channels, exportChannel{ID: ch.ID, Name: ch.Name, Type: ch.Type, Enabled: ch.Enabled})
|
||||
}
|
||||
|
||||
pages, err := q.ListStatusPages(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.StatusPages = []exportStatusPage{}
|
||||
for _, pg := range pages {
|
||||
pgGroups, err := q.ListStatusPageGroups(ctx, pg.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exportedGroups := []pageGroupView{}
|
||||
newPageGroupTree(pgGroups).walk(func(g store.StatusPageGroup, _ int) {
|
||||
exportedGroups = append(exportedGroups, pageGroupView{
|
||||
ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position,
|
||||
})
|
||||
})
|
||||
pm, err := q.StatusPageMonitors(ctx, pg.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
members := []exportPageMember{}
|
||||
for _, m := range pm {
|
||||
members = append(members, exportPageMember{
|
||||
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
|
||||
})
|
||||
}
|
||||
x.StatusPages = append(x.StatusPages, exportStatusPage{
|
||||
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
|
||||
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
|
||||
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
|
||||
})
|
||||
}
|
||||
|
||||
providers, err := q.ListSSOProviders(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.SSO = []exportSSO{}
|
||||
for _, sp := range providers {
|
||||
x.SSO = append(x.SSO, exportSSO{ID: sp.ID, Name: sp.Name, Issuer: sp.Issuer, ClientID: sp.ClientID,
|
||||
Scopes: sp.Scopes, AllowedDomains: sp.AllowedDomains, Enabled: sp.Enabled})
|
||||
}
|
||||
|
||||
agents, err := q.ListAgents(ctx, &org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Agents = []exportAgent{}
|
||||
for _, a := range agents {
|
||||
x.Agents = append(x.Agents, exportAgent{ID: a.ID, Kind: a.Kind, Name: a.Name, Region: a.RegionName})
|
||||
}
|
||||
|
||||
incidents, err := q.OrgIncidentsExport(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Incidents = []exportIncident{}
|
||||
for _, i := range incidents {
|
||||
x.Incidents = append(x.Incidents, exportIncident{ID: i.ID, MonitorID: i.MonitorID, Monitor: i.Monitor,
|
||||
StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause)})
|
||||
}
|
||||
|
||||
audit, err := q.OrgAuditExport(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Audit = []exportAuditEntry{}
|
||||
for _, a := range audit {
|
||||
x.Audit = append(x.Audit, exportAuditEntry{Time: a.Time, Action: a.Action, Actor: a.Actor, TargetID: a.TargetID,
|
||||
Details: rawJSON(a.Details), Status: a.Status, IP: a.Ip})
|
||||
}
|
||||
|
||||
stats, err := q.OrgDailyStats(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.DailyStats = []exportDailyStat{}
|
||||
for _, st := range stats {
|
||||
x.DailyStats = append(x.DailyStats, exportDailyStat{MonitorID: st.MonitorID, Region: st.Region, Day: st.Day,
|
||||
Total: st.Total, OK: st.OkCount, AvgLatencyMS: st.AvgLatencyMs})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return x, err
|
||||
}
|
||||
|
||||
func (s *Server) exportOrg(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
x, err := s.buildOrgExport(ctx, p)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
format := exportFormat(c)
|
||||
s.writeAudit(c, store.InsertAuditEventParams{Kind: "org", OrgID: &p.Org.ID, ActorUserID: &p.UserID, Action: "org.export", Status: http.StatusOK},
|
||||
map[string]any{"format": format})
|
||||
s.sendExport(c, format, p.Org.Slug, i18n.T(ctx, "export.org_title", "Name", p.Org.Name), x)
|
||||
}
|
||||
|
||||
type deletionRequest struct {
|
||||
// Password confirms the deletion; accounts without one, signing in
|
||||
// through SSO only, type their email address instead.
|
||||
Password string `json:"password" binding:"max=1024"`
|
||||
Confirm string `json:"confirm" binding:"max=320"`
|
||||
}
|
||||
|
||||
// confirmIdentity checks the re-entered password, or the typed email for
|
||||
// accounts without a password.
|
||||
func (s *Server) confirmIdentity(ctx context.Context, u store.User, req deletionRequest) bool {
|
||||
if u.PasswordHash == nil {
|
||||
return req.Confirm != "" && normalizeEmail(req.Confirm) == normalizeEmail(u.Email)
|
||||
}
|
||||
ok, _, err := auth.VerifyPassword(*u.PasswordHash, req.Password)
|
||||
return err == nil && ok
|
||||
}
|
||||
|
||||
func (s *Server) loadUser(ctx context.Context, id uuid.UUID) (store.User, error) {
|
||||
var u store.User
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
u, err = q.GetUser(ctx, id)
|
||||
return err
|
||||
})
|
||||
return u, err
|
||||
}
|
||||
|
||||
// purgeOrg deletes an organization with everything in it, including check
|
||||
// results and status page server storage, which have no foreign key.
|
||||
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
||||
if err := q.PurgeOrgCheckData(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteOrg(ctx, org)
|
||||
return err
|
||||
}
|
||||
|
||||
// deleteAccount erases the signed-in user (Art. 17). Organizations only the
|
||||
// user belongs to go with the account; an organization shared with others
|
||||
// must be handed over or deleted first, so nobody loses access to it.
|
||||
func (s *Server) deleteAccount(c *gin.Context) {
|
||||
var req deletionRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
auditSkip(c)
|
||||
sess := auth.Current(c)
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "delete:"+sess.UserID.String(), 5, 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
u, err := s.loadUser(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !s.confirmIdentity(ctx, u, req) {
|
||||
fail(c, http.StatusForbidden, "confirmation_failed")
|
||||
return
|
||||
}
|
||||
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if len(shared) > 0 {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.owns_shared_orgs"), "organizations": shared,
|
||||
})
|
||||
return
|
||||
}
|
||||
auth.ClearCookie(c)
|
||||
// Kept as proof of erasure, without saying whose.
|
||||
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
|
||||
map[string]any{"organizations_deleted": orgsDeleted})
|
||||
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
||||
}
|
||||
|
||||
// eraseAccount deletes u with the organizations only u belongs to and
|
||||
// ends u's sessions. If u owns organizations shared with others, nothing
|
||||
// is deleted and their slugs are returned.
|
||||
func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []string, orgsDeleted int, err error) {
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
owned, err := q.OwnedOrgs(ctx, u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, o := range owned {
|
||||
if o.Members > 1 {
|
||||
shared = append(shared, o.Slug)
|
||||
}
|
||||
}
|
||||
if len(shared) > 0 {
|
||||
return nil
|
||||
}
|
||||
for _, o := range owned {
|
||||
if err := purgeOrg(ctx, q, o.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
orgsDeleted++
|
||||
}
|
||||
for _, step := range []func() error{
|
||||
func() error { return q.DeleteAccountAudit(ctx, &u.ID) },
|
||||
func() error { return q.ForgetAuditActor(ctx, &u.ID) },
|
||||
func() error { return q.ScrubAuditEmail(ctx, u.Email) },
|
||||
func() error { return q.DeleteInvitationsForEmail(ctx, u.Email) },
|
||||
func() error { _, err := q.DeleteUser(ctx, u.ID); return err },
|
||||
} {
|
||||
if err := step(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || len(shared) > 0 {
|
||||
return shared, 0, err
|
||||
}
|
||||
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
|
||||
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
|
||||
}
|
||||
return nil, orgsDeleted, nil
|
||||
}
|
||||
|
||||
type orgDeletionRequest struct {
|
||||
deletionRequest
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
}
|
||||
|
||||
// deleteOrg erases the current organization. Only its owner may, after
|
||||
// typing its slug and confirming their identity.
|
||||
func (s *Server) deleteOrg(c *gin.Context) {
|
||||
var req orgDeletionRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
auditSkip(c)
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
if !p.Grants.Owner {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
if !s.limit(c, "delete:"+p.UserID.String(), 5, 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
u, err := s.loadUser(ctx, p.UserID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if req.Slug != p.Org.Slug || !s.confirmIdentity(ctx, u, req.deletionRequest) {
|
||||
fail(c, http.StatusForbidden, "confirmation_failed")
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return purgeOrg(ctx, q, p.Org.ID) })
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
_ = s.sessions.SwitchOrg(ctx, sess, uuid.Nil)
|
||||
}
|
||||
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "org.delete", TargetID: &p.Org.ID, Status: http.StatusOK},
|
||||
map[string]any{"slug": p.Org.Slug, "name": p.Org.Name})
|
||||
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
||||
}
|
||||
|
||||
func first[A, B any](a A, _ B) A { return a }
|
||||
@@ -0,0 +1,276 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// download fetches path and returns status, content type and body.
|
||||
func (b *browser) download(path string) (int, string, []byte) {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, resp.Header.Get("Content-Type"), raw
|
||||
}
|
||||
|
||||
func pdfText(t *testing.T, raw []byte) string {
|
||||
t.Helper()
|
||||
if !bytes.HasPrefix(raw, []byte("%PDF-")) {
|
||||
t.Fatalf("not a PDF: %.40q", raw)
|
||||
}
|
||||
if _, err := exec.LookPath("pdftotext"); err != nil {
|
||||
return ""
|
||||
}
|
||||
cmd := exec.Command("pdftotext", "-", "-")
|
||||
cmd.Stdin = bytes.NewReader(raw)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("pdftotext: %v\n%s", err, out)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func TestExports(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
email := "jörg@" + uniq("ex") + ".test"
|
||||
owner.signup(email, uniq("ex-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatal(body)
|
||||
}
|
||||
_, ch := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Hook", "type": "webhook", "url": "https://hooks.example.com/x"})
|
||||
signing := ch["signing_secret"].(string)
|
||||
_, tok := owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
|
||||
token := tok["token"].(string)
|
||||
|
||||
st, ctype, raw := owner.download("/api/v1/me/export?format=json")
|
||||
if st != http.StatusOK || !strings.HasPrefix(ctype, "application/json") {
|
||||
t.Fatalf("account export = %d %s", st, ctype)
|
||||
}
|
||||
var acc map[string]any
|
||||
if err := json.Unmarshal(raw, &acc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if acc["account"].(map[string]any)["email"] != email || len(acc["organizations"].([]any)) != 1 ||
|
||||
len(acc["api_tokens"].([]any)) != 1 || len(acc["activity"].([]any)) == 0 {
|
||||
t.Errorf("account export = %s", raw)
|
||||
}
|
||||
for _, secret := range []string{token, signing, "password_hash", "totp_secret", "token_hash"} {
|
||||
if bytes.Contains(raw, []byte(secret)) {
|
||||
t.Errorf("account export contains %q", secret)
|
||||
}
|
||||
}
|
||||
st, ctype, raw = owner.download("/api/v1/me/export?format=pdf")
|
||||
if st != http.StatusOK || ctype != "application/pdf" {
|
||||
t.Fatalf("account PDF = %d %s", st, ctype)
|
||||
}
|
||||
if text := pdfText(t, raw); text != "" && !strings.Contains(text, email) {
|
||||
t.Errorf("account PDF lacks the email address:\n%.500s", text)
|
||||
}
|
||||
|
||||
st, _, raw = owner.download("/api/v1/org/export?format=json")
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("org export = %d", st)
|
||||
}
|
||||
var org map[string]any
|
||||
if err := json.Unmarshal(raw, &org); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groups := org["alert_groups"].([]any)
|
||||
monitors := org["monitors"].([]any)
|
||||
if len(groups) != 1 || len(monitors) != 1 {
|
||||
t.Fatalf("export groups/monitors = %v/%v", groups, monitors)
|
||||
}
|
||||
group := groups[0].(map[string]any)
|
||||
assigned := monitors[0].(map[string]any)["alert_group_ids"].([]any)
|
||||
if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(group["quiet_hours"].([]any)) != 0 || len(assigned) != 1 || assigned[0] != group["id"] {
|
||||
t.Fatalf("export lost alert routing: group=%v assignments=%v", group, assigned)
|
||||
}
|
||||
if !bytes.Contains(raw, []byte(`"Shop"`)) || !bytes.Contains(raw, []byte(`"Hook"`)) {
|
||||
t.Errorf("org export lacks monitor or channel")
|
||||
}
|
||||
for _, secret := range []string{token, signing, "client_secret", "domain_token"} {
|
||||
if bytes.Contains(raw, []byte(secret)) {
|
||||
t.Errorf("org export contains %q", secret)
|
||||
}
|
||||
}
|
||||
_, _, raw = owner.download("/api/v1/org/export?format=pdf")
|
||||
if text := pdfText(t, raw); text != "" && (!strings.Contains(text, "Shop") || !strings.Contains(text, "example.com:443")) {
|
||||
t.Errorf("org PDF lacks the monitor:\n%.800s", text)
|
||||
}
|
||||
|
||||
// Exports are recorded.
|
||||
_, audit := owner.do("GET", "/api/v1/org/audit", nil)
|
||||
if !strings.Contains(mustJSON(audit), "org.export") {
|
||||
t.Error("org export is not in the audit log")
|
||||
}
|
||||
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("ex")+".test", owner.roleID("viewer")))
|
||||
if st, _, _ := viewer.download("/api/v1/org/export"); st != http.StatusForbidden {
|
||||
t.Errorf("viewer org export = %d, want 403", st)
|
||||
}
|
||||
}
|
||||
|
||||
func mustJSON(v any) string {
|
||||
raw, _ := json.Marshal(v)
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
func (e *env) count(t *testing.T, query string, args ...any) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(context.Background(), query, args...).Scan(&n) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (e *env) seedResults(t *testing.T, org, monitor uuid.UUID) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for h := 1; h <= 30; h++ {
|
||||
if _, err := e.dbPool.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES ($1, $2, $3, 'eu', $4, true, 10)`,
|
||||
time.Now().Add(-time.Duration(h)*time.Hour), org, monitor, uuid.New()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := e.dbPool.Exec(ctx, `CALL refresh_continuous_aggregate('check_results_1h', NULL, NULL)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteOrganization(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
slug := uniq("del-")
|
||||
owner.signup("o@"+uniq("d")+".test", slug)
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
e.seedResults(t, org, uuid.MustParse(m["id"].(string)))
|
||||
|
||||
keep := e.browser(t)
|
||||
keep.signup("k@"+uniq("d")+".test", uniq("keep-"))
|
||||
_, km := keep.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "K", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
keepOrg := uuid.MustParse(keep.orgID())
|
||||
e.seedResults(t, keepOrg, uuid.MustParse(km["id"].(string)))
|
||||
|
||||
admin := e.joinVia(t, owner.invite("a@"+uniq("d")+".test", owner.roleID("admin")))
|
||||
if st, body := admin.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusForbidden {
|
||||
t.Errorf("admin deletes org = %d %v, want 403", st, body)
|
||||
}
|
||||
if st, _ := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": "wrong", "password": password}); st != http.StatusForbidden {
|
||||
t.Errorf("wrong slug = %d, want 403", st)
|
||||
}
|
||||
if st, _ := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": "wrong password"}); st != http.StatusForbidden {
|
||||
t.Errorf("wrong password = %d, want 403", st)
|
||||
}
|
||||
if st, body := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusOK {
|
||||
t.Fatalf("owner deletes org = %d %v", st, body)
|
||||
}
|
||||
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
|
||||
} {
|
||||
if got := e.count(t, query, org); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM check_results_1h WHERE org_id = $1`, keepOrg) == 0 {
|
||||
t.Error("another organization's aggregates were deleted")
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM audit_events WHERE action = 'org.delete' AND details->>'slug' = $1`, slug) != 1 {
|
||||
t.Error("deletion is not in the platform log")
|
||||
}
|
||||
// Former members keep working accounts without the organization.
|
||||
for _, b := range []*browser{owner, admin} {
|
||||
if st, _, _ := b.page("/"); st != http.StatusOK {
|
||||
t.Errorf("console after deletion = %d", st)
|
||||
}
|
||||
if st, me := b.do("GET", "/api/v1/me", nil); st != http.StatusOK || len(me["orgs"].([]any)) != 0 {
|
||||
t.Errorf("GET /me after deletion = %d %v", st, me)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAccount(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("da")+".test", uniq("da-"))
|
||||
memberEmail := "m@" + uniq("da") + ".test"
|
||||
member := e.joinVia(t, owner.invite(memberEmail, owner.roleID("admin")))
|
||||
memberID := member.userIDSelf()
|
||||
member.do("POST", "/api/v1/org/groups", map[string]any{"name": "By member"})
|
||||
|
||||
// An owner of a shared organization must hand it over first.
|
||||
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusConflict || body["error"] != "owns_shared_orgs" {
|
||||
t.Errorf("owner of shared org deletes account = %d %v, want 409", st, body)
|
||||
}
|
||||
if st, _ := member.do("POST", "/api/v1/me/delete", map[string]any{"password": "wrong password"}); st != http.StatusForbidden {
|
||||
t.Errorf("wrong password = %d, want 403", st)
|
||||
}
|
||||
if st, body := member.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
|
||||
t.Fatalf("member deletes account = %d %v", st, body)
|
||||
}
|
||||
if st, _ := member.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
|
||||
t.Errorf("old session after deletion = %d, want 401", st)
|
||||
}
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM users WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE actor_user_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE details::text LIKE '%' || $1::text || '%'`: 0,
|
||||
} {
|
||||
arg := any(memberID)
|
||||
if strings.Contains(query, "LIKE") {
|
||||
arg = memberEmail
|
||||
}
|
||||
if got := e.count(t, query, arg); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": memberEmail, "password": password}); st != http.StatusUnauthorized {
|
||||
t.Errorf("login after deletion = %d, want 401", st)
|
||||
}
|
||||
// The organization's log still shows what happened, by a deleted user.
|
||||
_, _, html := owner.page("/settings/audit")
|
||||
if !strings.Contains(html, "By member") || !strings.Contains(html, "Deleted user") {
|
||||
t.Error("audit page lacks the group created by the deleted member")
|
||||
}
|
||||
|
||||
// A sole owner's organization goes with the account.
|
||||
solo := e.browser(t)
|
||||
solo.signup("s@"+uniq("da")+".test", uniq("solo-"))
|
||||
soloOrg := uuid.MustParse(solo.orgID())
|
||||
if st, body := solo.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
|
||||
t.Fatalf("sole owner deletes account = %d %v", st, body)
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, soloOrg) != 0 {
|
||||
t.Error("sole owner's organization survived")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// groupTree is an organization's monitor groups. Role assignments scoped to
|
||||
// a group cover its whole subtree, so permission checks look at a group and
|
||||
// all its ancestors.
|
||||
type groupTree struct {
|
||||
byID map[uuid.UUID]store.MonitorGroup
|
||||
children map[uuid.UUID][]uuid.UUID
|
||||
roots []uuid.UUID
|
||||
}
|
||||
|
||||
func newGroupTree(groups []store.MonitorGroup) groupTree {
|
||||
t := groupTree{byID: map[uuid.UUID]store.MonitorGroup{}, children: map[uuid.UUID][]uuid.UUID{}}
|
||||
for _, g := range groups {
|
||||
t.byID[g.ID] = g
|
||||
}
|
||||
for _, g := range groups {
|
||||
if g.ParentID != nil {
|
||||
if _, ok := t.byID[*g.ParentID]; ok {
|
||||
t.children[*g.ParentID] = append(t.children[*g.ParentID], g.ID)
|
||||
continue
|
||||
}
|
||||
}
|
||||
t.roots = append(t.roots, g.ID)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (s *Server) loadGroupTree(ctx context.Context, scope tenant.Scope) (groupTree, error) {
|
||||
var groups []store.MonitorGroup
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
groups, err = q.ListGroups(ctx)
|
||||
return err
|
||||
})
|
||||
return newGroupTree(groups), err
|
||||
}
|
||||
|
||||
// resources returns the group and its ancestors as authorization scopes,
|
||||
// nearest first. A monitor without a group has none: only org-wide rights
|
||||
// cover it.
|
||||
func (t groupTree) resources(group *uuid.UUID) []authz.Resource {
|
||||
var out []authz.Resource
|
||||
for id := group; id != nil; {
|
||||
g, ok := t.byID[*id]
|
||||
if !ok || len(out) > 20 {
|
||||
break
|
||||
}
|
||||
out = append(out, authz.Resource{Type: authz.MonitorGroup, ID: g.ID})
|
||||
id = g.ParentID
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// walk visits groups depth-first in name order.
|
||||
func (t groupTree) walk(fn func(g store.MonitorGroup, depth int)) {
|
||||
var visit func(ids []uuid.UUID, depth int)
|
||||
visit = func(ids []uuid.UUID, depth int) {
|
||||
for _, id := range ids {
|
||||
fn(t.byID[id], depth)
|
||||
visit(t.children[id], depth+1)
|
||||
}
|
||||
}
|
||||
visit(t.roots, 0)
|
||||
}
|
||||
|
||||
// canInGroup reports whether p holds perm for things in group.
|
||||
func canInGroup(p *principal, perm authz.Permission, t groupTree, group *uuid.UUID) bool {
|
||||
return p.Grants.Can(perm, t.resources(group)...)
|
||||
}
|
||||
|
||||
type groupView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ParentID *uuid.UUID `json:"parent_id"`
|
||||
}
|
||||
|
||||
func (s *Server) listGroups(c *gin.Context) {
|
||||
p := current(c)
|
||||
t, err := s.loadGroupTree(c.Request.Context(), p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := []groupView{}
|
||||
t.walk(func(g store.MonitorGroup, _ int) {
|
||||
out = append(out, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{"groups": out})
|
||||
}
|
||||
|
||||
type groupRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
ParentID *uuid.UUID `json:"parent_id"`
|
||||
}
|
||||
|
||||
func groupError(c *gin.Context, err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if !errors.As(err, &pgErr) {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case pgErr.ConstraintName == "monitor_groups_cycle", pgErr.ConstraintName == "monitor_groups_check":
|
||||
fail(c, http.StatusUnprocessableEntity, "group_cycle")
|
||||
case pgErr.ConstraintName == "monitor_groups_depth":
|
||||
fail(c, http.StatusUnprocessableEntity, "group_too_deep")
|
||||
case pgErr.Code == "23503":
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) createGroup(c *gin.Context) {
|
||||
var req groupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if req.ParentID != nil {
|
||||
if _, ok := t.byID[*req.ParentID]; !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, req.ParentID) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
var g store.MonitorGroup
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
g, err = q.CreateGroup(ctx, store.CreateGroupParams{OrgID: p.Org.ID, ParentID: req.ParentID, Name: req.Name})
|
||||
return err
|
||||
})
|
||||
if groupError(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
||||
}
|
||||
|
||||
// updateGroup renames or moves a group. Moving needs write access both where
|
||||
// the group is and where it goes.
|
||||
func (s *Server) updateGroup(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req groupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if _, ok := t.byID[id]; !ok || req.Name == "" {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if req.ParentID != nil {
|
||||
if _, ok := t.byID[*req.ParentID]; !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, &id) || !canInGroup(p, authz.MonitorsWrite, t, req.ParentID) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
var g store.MonitorGroup
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
g, err = q.UpdateGroup(ctx, store.UpdateGroupParams{ID: id, Name: req.Name, ParentID: req.ParentID})
|
||||
return err
|
||||
})
|
||||
if groupError(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
||||
}
|
||||
|
||||
// deleteGroup moves the group's subgroups and monitors to its parent and
|
||||
// removes assignments scoped to it. As things move up, write access to the
|
||||
// parent is required.
|
||||
func (s *Server) deleteGroup(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
g, ok := t.byID[id]
|
||||
if !ok {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, g.ParentID) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if err := q.ReparentGroups(ctx, store.ReparentGroupsParams{OldParent: &id, NewParent: g.ParentID}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.RegroupMonitors(ctx, store.RegroupMonitorsParams{OldGroup: &id, NewGroup: g.ParentID}); err != nil {
|
||||
return err
|
||||
}
|
||||
rt := string(authz.MonitorGroup)
|
||||
if err := q.DeleteAssignmentsForResource(ctx, store.DeleteAssignmentsForResourceParams{ResourceType: &rt, ResourceID: &id}); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteGroup(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func (b *browser) group(name string, parent string) string {
|
||||
b.t.Helper()
|
||||
body := map[string]any{"name": name}
|
||||
if parent != "" {
|
||||
body["parent_id"] = parent
|
||||
}
|
||||
st, resp := b.do("POST", "/api/v1/org/groups", body)
|
||||
if st != http.StatusCreated {
|
||||
b.t.Fatalf("create group %s = %d %v", name, st, resp)
|
||||
}
|
||||
return resp["id"].(string)
|
||||
}
|
||||
|
||||
func monitorBody(name, group, region string) map[string]any {
|
||||
b := map[string]any{"name": name, "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region}}
|
||||
if group != "" {
|
||||
b["group_id"] = group
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestMonitorGroups(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("g")+".test", uniq("grp-"))
|
||||
|
||||
prod := owner.group("Prod", "")
|
||||
eu := owner.group("EU", prod)
|
||||
fra := owner.group("Frankfurt", eu)
|
||||
staging := owner.group("Staging", "")
|
||||
|
||||
newMonitor := func(b *browser, name, group string) (int, map[string]any) {
|
||||
return b.do("POST", "/api/v1/org/monitors", monitorBody(name, group, region))
|
||||
}
|
||||
for name, g := range map[string]string{"fra-web": fra, "eu-db": eu, "staging-web": staging, "loose": ""} {
|
||||
if st, body := newMonitor(owner, name, g); st != http.StatusCreated {
|
||||
t.Fatalf("create monitor %s = %d %v", name, st, body)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("no cycles and limited depth", func(t *testing.T) {
|
||||
st, body := owner.do("PUT", "/api/v1/org/groups/"+prod, map[string]any{"name": "Prod", "parent_id": fra})
|
||||
expect(t, "move group into its descendant", st, body, http.StatusUnprocessableEntity, "group_cycle")
|
||||
parent := staging
|
||||
for i := 0; i < 7; i++ {
|
||||
parent = owner.group("level", parent)
|
||||
}
|
||||
st, body = owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "too deep", "parent_id": parent})
|
||||
expect(t, "ninth level", st, body, http.StatusUnprocessableEntity, "group_too_deep")
|
||||
})
|
||||
|
||||
t.Run("scoped permissions follow the subtree", func(t *testing.T) {
|
||||
owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Readers", "permissions": []string{"members.read"}})
|
||||
owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Monitor editor", "permissions": []string{"monitors.write"}})
|
||||
email := "ed@" + uniq("ed") + ".test"
|
||||
ed := e.joinVia(t, owner.invite(email, owner.roleID("Readers")))
|
||||
st, body := owner.do("POST", "/api/v1/org/members/"+owner.userID(email)+"/roles", map[string]any{
|
||||
"role_id": owner.roleID("Monitor editor"), "resource_type": "monitor_group", "resource_id": prod,
|
||||
})
|
||||
expect(t, "assign scoped role", st, body, http.StatusCreated, "")
|
||||
|
||||
_, list := ed.do("GET", "/api/v1/org/monitors", nil)
|
||||
var names []string
|
||||
for _, m := range list["monitors"].([]any) {
|
||||
names = append(names, m.(map[string]any)["name"].(string))
|
||||
}
|
||||
if got := strings.Join(names, ","); !strings.Contains(got, "fra-web") || !strings.Contains(got, "eu-db") || len(names) != 2 {
|
||||
t.Errorf("scoped user sees %v, want only the Prod subtree", names)
|
||||
}
|
||||
st, body = newMonitor(ed, "x", staging)
|
||||
expect(t, "create outside scope", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = newMonitor(ed, "x", "")
|
||||
expect(t, "create at top level", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = newMonitor(ed, "fra-cache", fra)
|
||||
expect(t, "create deep inside scope", st, body, http.StatusCreated, "")
|
||||
created := body["id"].(string)
|
||||
st, body = ed.do("PUT", "/api/v1/org/monitors/"+created, monitorBody("fra-cache", staging, region))
|
||||
expect(t, "move out of scope", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = ed.do("POST", "/api/v1/org/groups", map[string]any{"name": "Root"})
|
||||
expect(t, "create root group", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = ed.do("POST", "/api/v1/org/groups", map[string]any{"name": "Paris", "parent_id": eu})
|
||||
expect(t, "create subgroup inside scope", st, body, http.StatusCreated, "")
|
||||
|
||||
_, _, html := ed.page("/")
|
||||
if !strings.Contains(html, "Frankfurt") || strings.Contains(html, "staging-web") {
|
||||
t.Errorf("scoped dashboard: Frankfurt shown %t, staging-web hidden %t",
|
||||
strings.Contains(html, "Frankfurt"), !strings.Contains(html, "staging-web"))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deleting a group moves its content up", func(t *testing.T) {
|
||||
st, body := owner.do("DELETE", "/api/v1/org/groups/"+eu, nil)
|
||||
expect(t, "delete EU", st, body, http.StatusNoContent, "")
|
||||
_, groups := owner.do("GET", "/api/v1/org/groups", nil)
|
||||
for _, g := range groups["groups"].([]any) {
|
||||
g := g.(map[string]any)
|
||||
if g["id"] == fra && g["parent_id"] != prod {
|
||||
t.Errorf("Frankfurt parent = %v, want Prod", g["parent_id"])
|
||||
}
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
for _, m := range list["monitors"].([]any) {
|
||||
m := m.(map[string]any)
|
||||
if m["name"] == "eu-db" && m["group_id"] != prod {
|
||||
t.Errorf("eu-db group = %v, want Prod", m["group_id"])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("groups stay in their org", func(t *testing.T) {
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("gx")+".test", uniq("grp-x-"))
|
||||
st, body := newMonitor(other, "x", prod)
|
||||
expect(t, "foreign group", st, body, http.StatusUnprocessableEntity, "invalid_group")
|
||||
})
|
||||
|
||||
if st, final, html := owner.page("/groups"); st != http.StatusOK || final != "/groups" || !strings.Contains(html, "Frankfurt") {
|
||||
t.Errorf("GET /groups = %d at %s", st, final)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"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/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// heartbeatRegion is the region heartbeat results are filed under: pings
|
||||
// arrive from wherever the job runs, not from a checker region.
|
||||
const heartbeatRegion = "heartbeat"
|
||||
|
||||
// newPingToken returns the secret that makes up a ping URL.
|
||||
func newPingToken() string { return auth.RandomToken() }
|
||||
|
||||
func (s *Server) pingURL(token string) string {
|
||||
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/hb/" + token
|
||||
}
|
||||
|
||||
func (s *Server) mountHeartbeats(r gin.IRouter) {
|
||||
methods := []string{http.MethodGet, http.MethodHead, http.MethodPost}
|
||||
r.Match(methods, "/hb/:token", s.ping)
|
||||
r.Match(methods, "/hb/:token/fail", s.ping)
|
||||
}
|
||||
|
||||
// ping records a heartbeat. Jobs call it with curl or wget, so it takes
|
||||
// GET, HEAD and POST, needs no headers and answers in plain text. A path
|
||||
// ending in /fail reports a failure; a message may come as ?msg= or as the
|
||||
// POST body.
|
||||
func (s *Server) ping(c *gin.Context) {
|
||||
token := c.Param("token")
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "ping:"+token, 60, time.Minute) {
|
||||
return
|
||||
}
|
||||
var m store.HeartbeatMonitorRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
m, err = q.HeartbeatMonitor(ctx, token)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.String(http.StatusNotFound, "unknown heartbeat\n")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !m.Enabled {
|
||||
c.String(http.StatusOK, "OK (paused)\n")
|
||||
return
|
||||
}
|
||||
ok := !strings.HasSuffix(c.FullPath(), "/fail")
|
||||
msg := c.Query("msg")
|
||||
if msg == "" && c.Request.Method == http.MethodPost {
|
||||
body, _ := io.ReadAll(io.LimitReader(c.Request.Body, 2000))
|
||||
msg = strings.TrimSpace(string(body))
|
||||
}
|
||||
if !ok && msg == "" {
|
||||
msg = "reported failure"
|
||||
}
|
||||
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, time.Now()); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.String(http.StatusOK, "OK\n")
|
||||
}
|
||||
|
||||
// recordHeartbeat stores a ping or a missed deadline and evaluates it like
|
||||
// a checker result.
|
||||
func (s *Server) recordHeartbeat(ctx context.Context, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
|
||||
return s.recordPassive(ctx, heartbeatRegion, id, org, interval, confirmations, ok, msg, at)
|
||||
}
|
||||
|
||||
// recordPassive stores a result reported to us instead of by a checker,
|
||||
// under the pseudo-region of its kind, and evaluates it.
|
||||
func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
|
||||
row := store.InsertCheckResultsParams{Time: at, OrgID: org, MonitorID: id, Region: region, Ok: ok}
|
||||
if msg != "" {
|
||||
row.Error = ptr(truncateValid(msg, 500))
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.evaluateResults(ctx, region,
|
||||
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
|
||||
map[uuid.UUID]store.MonitorsForResultsRow{id: {
|
||||
ID: id, OrgID: org, IntervalSeconds: interval, Confirmations: confirmations, Regions: []string{region},
|
||||
}})
|
||||
return nil
|
||||
}
|
||||
|
||||
// missedPing is the error recorded for an overdue heartbeat.
|
||||
const missedPing = "no ping received in time"
|
||||
|
||||
// RunHeartbeats records a failure for every heartbeat monitor whose ping is
|
||||
// overdue, until ctx ends. Every replica runs it; a short Redis lock lets
|
||||
// one of them do each round.
|
||||
func (s *Server) RunHeartbeats(ctx context.Context) {
|
||||
tick := time.NewTicker(10 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
got, err := s.rdb.SetNX(ctx, "lock:heartbeats", 1, 9*time.Second).Result()
|
||||
if err != nil || !got {
|
||||
continue
|
||||
}
|
||||
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
|
||||
}
|
||||
if err := s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking alertmanager monitors failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CheckHeartbeats records missed deadlines as of now. A recorded failure
|
||||
// restarts the wait, so a silent job fails once per interval plus grace.
|
||||
func (s *Server) CheckHeartbeats(ctx context.Context, now time.Time) error {
|
||||
var due []store.HeartbeatsDueRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
due, err = q.HeartbeatsDue(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range due {
|
||||
deadline := m.WaitingSince.Add(time.Duration(m.IntervalSeconds+m.GraceSeconds) * time.Second)
|
||||
if now.Before(deadline) {
|
||||
continue
|
||||
}
|
||||
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds+m.GraceSeconds, m.Confirmations, false, missedPing, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestHeartbeatMonitor(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("hb")+".test", uniq("hb-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 3600, "config": map[string]any{"grace_seconds": 300},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create heartbeat = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
pingURL, _ := body["ping_url"].(string)
|
||||
token := body["target"].(string)
|
||||
if !strings.HasSuffix(pingURL, "/hb/"+token) || len(token) < 40 {
|
||||
t.Fatalf("ping_url = %q, target = %q", pingURL, token)
|
||||
}
|
||||
path := "/hb/" + token
|
||||
ping := func(method, suffix, payload string) (int, string) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest(method, e.srv.URL+path+suffix, strings.NewReader(payload))
|
||||
resp, err := e.srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
incidents := func() []any {
|
||||
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
return b["incidents"].([]any)
|
||||
}
|
||||
open := func() bool {
|
||||
for _, i := range incidents() {
|
||||
if i.(map[string]any)["resolved_at"] == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if st, _ := ping("GET", "x", ""); st != http.StatusNotFound {
|
||||
t.Errorf("unknown token = %d, want 404", st)
|
||||
}
|
||||
|
||||
// Silence past interval plus grace is an outage.
|
||||
ctx := context.Background()
|
||||
waitingFor := func(d time.Duration) {
|
||||
t.Helper()
|
||||
err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE monitors SET updated_at = now() - $2::interval WHERE id = $1`, id, d)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
waitingFor(50 * time.Minute)
|
||||
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if open() {
|
||||
t.Fatal("incident before the deadline")
|
||||
}
|
||||
waitingFor(66 * time.Minute)
|
||||
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !open() {
|
||||
t.Fatal("no incident after a missed ping")
|
||||
}
|
||||
// A failure restarts the wait instead of piling up.
|
||||
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1 AND NOT ok`, id); n != 1 {
|
||||
t.Errorf("failures recorded = %d, want 1", n)
|
||||
}
|
||||
// The next ping resolves it.
|
||||
if st, out := ping("HEAD", "", ""); st != http.StatusOK {
|
||||
t.Fatalf("ping = %d %q", st, out)
|
||||
}
|
||||
if open() {
|
||||
t.Fatal("ping did not resolve the incident")
|
||||
}
|
||||
// A reported failure is an outage at once, with its message.
|
||||
if st, _ := ping("POST", "/fail", "disk full"); st != http.StatusOK {
|
||||
t.Fatalf("fail ping = %d", st)
|
||||
}
|
||||
if !open() {
|
||||
t.Fatal("reported failure opened no incident")
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
if !strings.Contains(mustJSON(list), "disk full") {
|
||||
t.Error("failure message is not stored")
|
||||
}
|
||||
ping("POST", "", "")
|
||||
|
||||
// Editing keeps the URL; readers never see it.
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, map[string]any{
|
||||
"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200,
|
||||
})
|
||||
if st != http.StatusOK || body["target"] != token {
|
||||
t.Errorf("edit = %d, target %v, want unchanged", st, body["target"])
|
||||
}
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("hb")+".test", owner.roleID("viewer")))
|
||||
_, vl := viewer.do("GET", "/api/v1/org/monitors", nil)
|
||||
if strings.Contains(mustJSON(vl), token) {
|
||||
t.Error("a viewer sees the ping token")
|
||||
}
|
||||
for _, b := range []*browser{owner, viewer} {
|
||||
_, _, html := b.page("/")
|
||||
if strings.Contains(html, token) {
|
||||
t.Error("the dashboard shows the ping token")
|
||||
}
|
||||
}
|
||||
if _, _, html := owner.page("/monitors/" + id); !strings.Contains(html, pingURL) {
|
||||
t.Error("the monitor page does not show the ping URL to its editor")
|
||||
}
|
||||
if _, _, html := viewer.page("/monitors/" + id); strings.Contains(html, token) {
|
||||
t.Error("the monitor page shows the ping URL to a viewer")
|
||||
}
|
||||
|
||||
// Other monitor types still need a target and regions.
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "x", "type": "tcp", "target": "example.com:443", "interval_seconds": 60})
|
||||
expect(t, "tcp without regions", st, body, http.StatusUnprocessableEntity, "invalid_region")
|
||||
|
||||
// Paused heartbeats accept pings but never fail.
|
||||
owner.do("PUT", "/api/v1/org/monitors/"+id, map[string]any{"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200, "enabled": false})
|
||||
before := len(incidents())
|
||||
if st, out := ping("GET", "", ""); st != http.StatusOK || !strings.Contains(out, "paused") {
|
||||
t.Errorf("ping while paused = %d %q", st, out)
|
||||
}
|
||||
if err := e.api.CheckHeartbeats(ctx, time.Now().Add(48*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(incidents()) != before {
|
||||
t.Error("a paused heartbeat failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
|
||||
"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"
|
||||
)
|
||||
|
||||
func (s *Server) retention() datapolicy.Retention {
|
||||
r := s.cfg.Retention
|
||||
return datapolicy.Retention{Raw: r.Raw, Hourly: r.Hourly, Daily: r.Daily}
|
||||
}
|
||||
|
||||
// RunHousekeeping aligns TimescaleDB's retention with the configuration and
|
||||
// then purges rows TimescaleDB does not manage, hourly, until ctx ends.
|
||||
// Every replica runs it; the deletes are idempotent.
|
||||
func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
if err := datapolicy.Apply(ctx, s.db.Pool(), s.retention(), s.log); err != nil {
|
||||
// The API role may not own the tables; "api migrate up" applies the
|
||||
// policies as owner.
|
||||
s.log.WarnContext(ctx, "applying retention policies failed", "error", err)
|
||||
}
|
||||
tick := time.NewTicker(time.Hour)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.Housekeep(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "housekeeping failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Housekeep deletes delivered notifications, stale invitations, expired API
|
||||
// tokens and incidents older than the daily aggregate.
|
||||
func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
|
||||
keep := s.cfg.Retention
|
||||
var counts [7]int64
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if keep.Housekeeping > 0 {
|
||||
before := now.Add(-keep.Housekeeping)
|
||||
if counts[0], err = q.PurgeNotifications(ctx, before); err != nil {
|
||||
return err
|
||||
}
|
||||
if counts[1], err = q.PurgeInvitations(ctx, before); err != nil {
|
||||
return err
|
||||
}
|
||||
if counts[2], err = q.PurgeExpiredTokens(ctx, &before); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if keep.Evidence > 0 {
|
||||
if counts[5], err = q.PurgeEvidence(ctx, now.Add(-keep.Evidence)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if keep.Audit > 0 {
|
||||
if counts[4], err = q.PurgeAuditEvents(ctx, now.Add(-keep.Audit)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = q.PurgeAlertmanagerAlerts(ctx, now.Add(-keepAlerts)); err != nil {
|
||||
return err
|
||||
}
|
||||
if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
|
||||
return err
|
||||
}
|
||||
if keep.Daily > 0 {
|
||||
before := now.Add(-keep.Daily)
|
||||
counts[3], err = q.PurgeIncidents(ctx, &before)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err == nil && counts != [7]int64{} {
|
||||
s.log.InfoContext(ctx, "housekeeping purged rows",
|
||||
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5],
|
||||
"unverified_accounts", counts[6])
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func storageView(c *gin.Context, st datapolicy.Stats) web.StorageView {
|
||||
ctx := c.Request.Context()
|
||||
var v web.StorageView
|
||||
for _, r := range st.Relations {
|
||||
l := web.StorageLevel{
|
||||
Key: strings.TrimPrefix(strings.TrimPrefix(r.Name, "check_results"), "_"),
|
||||
Size: web.Bytes(r.TotalBytes),
|
||||
Chunks: fmt.Sprintf("%d / %d", r.CompressedChunks, r.Chunks),
|
||||
Retention: web.Days(ctx, r.Retention),
|
||||
CompressAfter: "–",
|
||||
}
|
||||
if l.Key == "" {
|
||||
l.Key = "raw"
|
||||
}
|
||||
if r.CompressAfter > 0 {
|
||||
l.CompressAfter = web.Days(ctx, r.CompressAfter)
|
||||
}
|
||||
if r.AfterBytes > 0 {
|
||||
l.Compressed = fmt.Sprintf("%s → %s", web.Bytes(r.BeforeBytes), web.Bytes(r.AfterBytes))
|
||||
}
|
||||
v.Levels = append(v.Levels, l)
|
||||
}
|
||||
const layout = "2006-01-02 15:04"
|
||||
for _, j := range st.Jobs {
|
||||
sj := web.StorageJob{
|
||||
Name: strings.TrimPrefix(j.Proc, "policy_"), Relation: j.Relation,
|
||||
OK: j.LastStatus != "Failed", Failures: j.Failures, LastRun: "–", NextRun: "–",
|
||||
}
|
||||
if j.LastRun != nil {
|
||||
sj.LastRun = j.LastRun.Local().Format(layout)
|
||||
}
|
||||
if j.NextRun != nil {
|
||||
sj.NextRun = j.NextRun.Local().Format(layout)
|
||||
}
|
||||
v.Jobs = append(v.Jobs, sj)
|
||||
}
|
||||
for name, size := range st.TableBytes {
|
||||
v.Tables = append(v.Tables, web.StorageTable{Name: name, Size: web.Bytes(size)})
|
||||
}
|
||||
slices.SortFunc(v.Tables, func(a, b web.StorageTable) int { return strings.Compare(a.Name, b.Name) })
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestHousekeepingPurgesOnlyOldRows(t *testing.T) {
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.Retention = config.Retention{Daily: 365 * 24 * time.Hour, Housekeeping: 30 * 24 * time.Hour}
|
||||
})
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("hk")+".test", uniq("hk-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatal(body)
|
||||
}
|
||||
monitor := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
user := owner.userIDSelf()
|
||||
role := uuid.MustParse(owner.roleID("viewer"))
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
old, fresh := now.Add(-40*24*time.Hour), now.Add(-time.Hour)
|
||||
ancient := now.Add(-400 * 24 * time.Hour)
|
||||
var oldInc, freshInc, ancientInc uuid.UUID
|
||||
err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
var channel uuid.UUID
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO notification_channels (org_id, name, type, config) VALUES ($1, 'c', 'webhook', '{}') RETURNING id`, org).Scan(&channel); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, inc := range []struct {
|
||||
id *uuid.UUID
|
||||
started time.Time
|
||||
}{{&ancientInc, ancient}, {&oldInc, old}, {&freshInc, fresh}} {
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at) VALUES ($1, $2, $3::timestamptz, $3::timestamptz + interval '5 minutes') RETURNING id`,
|
||||
org, monitor, inc.started).Scan(inc.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, n := range []struct {
|
||||
inc uuid.UUID
|
||||
status string
|
||||
created time.Time
|
||||
}{{oldInc, "sent", old}, {freshInc, "sent", fresh}} {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'opened', $4, $5)`,
|
||||
org, channel, n.inc, n.status, n.created); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'resolved', 'pending', $4)`,
|
||||
org, channel, oldInc, old); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, exp := range []time.Time{old, now.Add(24 * time.Hour)} {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO invitations (org_id, email, role_id, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
org, uniq("i")+"@x.test", role, []byte(uniq("h")), exp); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO api_tokens (org_id, user_id, name, token_hash, prefix, permissions, expires_at) VALUES ($1, $2, $3, $4, 'usk_x', '{}', $5)`,
|
||||
org, user, "t"+string(rune('a'+i)), []byte(uniq("t")), exp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := e.api.Housekeep(ctx, now); err != nil {
|
||||
t.Fatalf("Housekeep() = %v", err)
|
||||
}
|
||||
|
||||
count := func(query string) int {
|
||||
var n int
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(ctx, query, org).Scan(&n) })
|
||||
return n
|
||||
}
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'sent'`: 1,
|
||||
`SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'pending'`: 1,
|
||||
`SELECT count(*) FROM invitations WHERE org_id = $1`: 1,
|
||||
`SELECT count(*) FROM api_tokens WHERE org_id = $1 AND expires_at IS NOT NULL`: 1,
|
||||
`SELECT count(*) FROM incidents WHERE org_id = $1`: 2,
|
||||
} {
|
||||
if got := count(query); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminSeesStorage(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
a := e.browser(t)
|
||||
a.signup("a@"+uniq("st")+".test", uniq("st-"))
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), a.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, _, html := a.page("/admin")
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("GET /admin = %d", st)
|
||||
}
|
||||
for _, want := range []string{"Data storage", "Raw results", "Daily aggregate", "Background jobs", "Compression"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("admin page lacks %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// asSystem runs fn in a transaction that bypasses tenant isolation.
|
||||
func (e *env) asSystem(t *testing.T, fn func(pgx.Tx) error) error {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
return pgx.BeginFunc(ctx, e.dbPool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `SELECT set_config('app.scope', 'system', true)`); err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(tx)
|
||||
})
|
||||
}
|
||||
@@ -85,6 +85,14 @@ func (s *Server) createInvitation(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// invitationView is a pending invitation.
|
||||
type invitationView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
RoleName string `json:"role_name"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (s *Server) listInvitations(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
@@ -98,15 +106,9 @@ func (s *Server) listInvitations(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
type view struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
RoleName string `json:"role_name"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
out := make([]view, len(rows))
|
||||
out := make([]invitationView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = view{ID: r.ID, Email: r.Email, RoleName: r.RoleName, ExpiresAt: r.ExpiresAt}
|
||||
out[i] = invitationView{ID: r.ID, Email: r.Email, RoleName: r.RoleName, ExpiresAt: r.ExpiresAt}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"invitations": out})
|
||||
}
|
||||
@@ -233,6 +235,7 @@ func (s *Server) acceptInvitation(c *gin.Context) {
|
||||
fail(c, http.StatusGone, code)
|
||||
return
|
||||
}
|
||||
auditOrg(c, inv.OrgID)
|
||||
if err := s.sessions.SwitchOrg(ctx, sess, inv.OrgID); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -276,13 +279,16 @@ func (s *Server) inviteSignup(c *gin.Context) {
|
||||
}
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
// The organization invited this address, which stands in for
|
||||
// confirming it.
|
||||
user, err = q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName),
|
||||
PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)),
|
||||
EmailKey: ptr(emailKey(inv.Email)), EmailVerifiedAt: ptr(time.Now()),
|
||||
})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "users_email_key") {
|
||||
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
|
||||
fail(c, http.StatusConflict, "email_taken")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestJSONCheck(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
var depth atomic.Int64
|
||||
depth.Store(3)
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-Api-Key") != "s3cret-key" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"ok","queue":{"depth":` + itoa(depth.Load()) + `}}`))
|
||||
}))
|
||||
defer api.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("jc")+".test", uniq("jc-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Queue", "type": "json", "target": api.URL, "interval_seconds": 10, "timeout_ms": 2000, "confirmations": 1,
|
||||
"regions": []string{region},
|
||||
"config": map[string]any{
|
||||
"headers": map[string]string{"X-Api-Key": "s3cret-key"},
|
||||
"assertions": []map[string]string{
|
||||
{"path": "status", "op": "==", "value": "ok"},
|
||||
{"path": "queue.depth", "op": "<", "value": "10"},
|
||||
{"path": "", "op": "==", "value": ""},
|
||||
},
|
||||
},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create json monitor = %d %v", st, body)
|
||||
}
|
||||
latest := func() map[string]any {
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
for _, m := range list["monitors"].([]any) {
|
||||
if l := m.(map[string]any)["latest"].([]any); len(l) > 0 {
|
||||
return l[0].(map[string]any)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
waitFor(t, 15*time.Second, "a successful JSON check", func() bool {
|
||||
l := latest()
|
||||
return l != nil && l["ok"] == true
|
||||
})
|
||||
depth.Store(42)
|
||||
waitFor(t, 25*time.Second, "a failed assertion", func() bool {
|
||||
l := latest()
|
||||
return l != nil && l["ok"] == false && strings.Contains(asString(l["error"]), "queue.depth is 42, expected < 10")
|
||||
})
|
||||
|
||||
// Readers see the condition, not the credential.
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("jc")+".test", owner.roleID("viewer")))
|
||||
_, vl := viewer.do("GET", "/api/v1/org/monitors", nil)
|
||||
if raw := mustJSON(vl); strings.Contains(raw, "s3cret-key") || !strings.Contains(raw, "queue.depth") {
|
||||
t.Errorf("viewer sees %s", raw)
|
||||
}
|
||||
if _, ol := owner.do("GET", "/api/v1/org/monitors", nil); !strings.Contains(mustJSON(ol), "s3cret-key") {
|
||||
t.Error("the editor does not see the header to edit it")
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int64) string {
|
||||
return strconv.FormatInt(n, 10)
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
|
||||
func TestPrometheusMonitor(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
prom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","job":"api"},"value":[1,"0"]}]}}`))
|
||||
}))
|
||||
defer prom.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("pm")+".test", uniq("pm-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "API targets", "type": "prometheus", "target": prom.URL, "interval_seconds": 10, "timeout_ms": 2000,
|
||||
"confirmations": 1, "regions": []string{region}, "config": map[string]any{"query": `up{job="api"}`, "op": "==", "threshold": 1},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create prometheus monitor = %d %v", st, body)
|
||||
}
|
||||
waitFor(t, 15*time.Second, "an incident for the down target", func() bool {
|
||||
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
return len(b["incidents"].([]any)) == 1
|
||||
})
|
||||
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
if !strings.Contains(mustJSON(list), `up{job=\"api\"} = 0, expected == 1`) {
|
||||
t.Errorf("result lacks the failing series: %s", mustJSON(list))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// mergeLegal picks one document per kind, the organization's over the
|
||||
// platform's. rows come organization first.
|
||||
func mergeLegal(rows []store.LegalDocument) []agentapi.LegalDoc {
|
||||
out := []agentapi.LegalDoc{}
|
||||
seen := map[string]bool{}
|
||||
for _, r := range rows {
|
||||
if seen[r.Kind] || (r.Url == "" && r.Markdown == "") {
|
||||
continue
|
||||
}
|
||||
seen[r.Kind] = true
|
||||
out = append(out, agentapi.LegalDoc{Kind: r.Kind, URL: r.Url, Markdown: r.Markdown})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// platformLegalDocs returns the platform's documents, which every console
|
||||
// page links in its footer.
|
||||
func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc {
|
||||
docs, err := s.legal.get(ctx, s.rdb, func(ctx context.Context) ([]agentapi.LegalDoc, error) {
|
||||
var rows []store.LegalDocument
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.LegalDocuments(ctx, nil)
|
||||
return err
|
||||
})
|
||||
return mergeLegal(rows), err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading legal documents failed", "error", err)
|
||||
}
|
||||
return docs
|
||||
}
|
||||
|
||||
func validLegalKind(kind string) bool { return slices.Contains(web.LegalKinds, kind) }
|
||||
|
||||
type legalRequest struct {
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
Markdown string `json:"markdown" binding:"max=100000"`
|
||||
}
|
||||
|
||||
// validLegalURL accepts absolute http and https URLs only, so a stored link
|
||||
// cannot run script when clicked.
|
||||
func validLegalURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != ""
|
||||
}
|
||||
|
||||
// saveLegal stores or, with both fields empty, removes a document of org,
|
||||
// nil for the platform.
|
||||
func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool {
|
||||
kind := c.Param("kind")
|
||||
if !validLegalKind(kind) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return false
|
||||
}
|
||||
var req legalRequest
|
||||
if !bind(c, &req) {
|
||||
return false
|
||||
}
|
||||
req.URL, req.Markdown = strings.TrimSpace(req.URL), strings.TrimSpace(req.Markdown)
|
||||
if req.URL != "" && !validLegalURL(req.URL) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
return false
|
||||
}
|
||||
auditDetail(c, "kind", kind)
|
||||
ctx := c.Request.Context()
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
if req.URL == "" && req.Markdown == "" {
|
||||
return q.DeleteLegalDocument(ctx, store.DeleteLegalDocumentParams{OrgID: org, Kind: kind})
|
||||
}
|
||||
return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) adminSaveLegal(c *gin.Context) {
|
||||
if s.saveLegal(c, tenant.System(), nil) {
|
||||
if err := s.legal.bump(c.Request.Context(), s.rdb); err != nil {
|
||||
s.log.ErrorContext(c.Request.Context(), "announcing legal document change failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) orgSaveLegal(c *gin.Context) {
|
||||
p := current(c)
|
||||
s.saveLegal(c, p.scope(), &p.Org.ID)
|
||||
}
|
||||
|
||||
type legalView struct {
|
||||
Kind string `json:"kind"`
|
||||
URL string `json:"url"`
|
||||
Markdown string `json:"markdown"`
|
||||
}
|
||||
|
||||
// ownLegal returns the documents stored for org (nil: the platform),
|
||||
// without fallbacks.
|
||||
func (s *Server) ownLegal(ctx context.Context, scope tenant.Scope, org *uuid.UUID) ([]legalView, error) {
|
||||
var rows []store.LegalDocument
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.LegalDocuments(ctx, org)
|
||||
return err
|
||||
})
|
||||
out := make([]legalView, 0, len(web.LegalKinds))
|
||||
for _, kind := range web.LegalKinds {
|
||||
v := legalView{Kind: kind}
|
||||
for _, r := range rows {
|
||||
if r.Kind == kind && (r.OrgID == nil) == (org == nil) {
|
||||
v.URL, v.Markdown = r.Url, r.Markdown
|
||||
}
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (s *Server) adminListLegal(c *gin.Context) {
|
||||
docs, err := s.ownLegal(c.Request.Context(), tenant.System(), nil)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"documents": docs})
|
||||
}
|
||||
|
||||
func (s *Server) orgListLegal(c *gin.Context) {
|
||||
p := current(c)
|
||||
docs, err := s.ownLegal(c.Request.Context(), p.scope(), &p.Org.ID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"documents": docs})
|
||||
}
|
||||
|
||||
// legalPage serves a platform document to anyone: Markdown rendered here,
|
||||
// links redirected.
|
||||
func (s *Server) legalPage(c *gin.Context) {
|
||||
kind := c.Param("kind")
|
||||
for _, d := range s.platformLegalDocs(c.Request.Context()) {
|
||||
if d.Kind != kind {
|
||||
continue
|
||||
}
|
||||
if d.URL != "" {
|
||||
c.Redirect(http.StatusFound, d.URL)
|
||||
return
|
||||
}
|
||||
html, err := web.RenderMarkdown(d.Markdown)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var me *web.Me
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
m, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
me = &m
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), me, html))
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNotFound)
|
||||
}
|
||||
|
||||
func toLegalForms(docs []legalView) []web.LegalForm {
|
||||
out := make([]web.LegalForm, len(docs))
|
||||
for i, d := range docs {
|
||||
out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) orgLegalView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
docs, err := s.ownLegal(c.Request.Context(), p.scope(), &p.Org.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs)), nil
|
||||
}
|
||||
|
||||
func (s *Server) adminLegalPage(c *gin.Context) {
|
||||
me, ok := s.adminMe(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
docs, err := s.ownLegal(c.Request.Context(), tenant.System(), nil)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs)))
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestLegalDocuments(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
admin := e.browser(t)
|
||||
admin.signup("a@"+uniq("lg")+".test", uniq("lg-"))
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, kind := range []string{"imprint", "privacy"} {
|
||||
admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{})
|
||||
}
|
||||
})
|
||||
|
||||
imprint := "# Impressum\n\nBetreiber GmbH <script>alert(1)</script>"
|
||||
st, body := admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": imprint})
|
||||
expect(t, "admin sets imprint", st, body, http.StatusNoContent, "")
|
||||
st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "javascript:alert(1)"})
|
||||
expect(t, "javascript link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "https://operator.example/privacy"})
|
||||
expect(t, "admin sets privacy link", st, body, http.StatusNoContent, "")
|
||||
st, body = admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "x"})
|
||||
expect(t, "unknown kind", st, body, http.StatusNotFound, "not_found")
|
||||
|
||||
// The console footer links them, also before signing in.
|
||||
_, _, login := e.browser(t).page("/login")
|
||||
if !strings.Contains(login, `href="/legal/imprint"`) || !strings.Contains(login, `href="https://operator.example/privacy"`) {
|
||||
t.Error("login page footer lacks the legal links")
|
||||
}
|
||||
st, _, html := e.browser(t).page("/legal/imprint")
|
||||
if st != http.StatusOK || !strings.Contains(html, "<h1>Impressum</h1>") || strings.Contains(html, "<script>alert") {
|
||||
t.Errorf("GET /legal/imprint = %d, rendered %q", st, html)
|
||||
}
|
||||
if !strings.Contains(html, `href="/login"`) {
|
||||
t.Error("the imprint offers visitors no way to sign in")
|
||||
}
|
||||
// Signed in, the imprint keeps the console navigation.
|
||||
if _, _, html := admin.page("/legal/imprint"); !strings.Contains(html, `href="/monitors`) && !strings.Contains(html, `href="/incidents"`) {
|
||||
t.Error("the imprint lacks the console navigation for signed-in users")
|
||||
}
|
||||
|
||||
// Status pages fall back to the platform's documents.
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("lg")+".test", uniq("lg-"))
|
||||
slug := uniq("lgp-")
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme"})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Acme", "published": true})
|
||||
client := e.statuspageClient(t, nil)
|
||||
legalOf := func() map[string]agentapi.LegalDoc {
|
||||
snap, err := client.Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]agentapi.LegalDoc{}
|
||||
for _, d := range snap.Legal {
|
||||
out[d.Kind] = d
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := legalOf(); got["imprint"].Markdown != imprint || got["privacy"].URL != "https://operator.example/privacy" {
|
||||
t.Errorf("snapshot legal = %+v, want the platform's", got)
|
||||
}
|
||||
|
||||
// An organization's own documents win.
|
||||
st, body = owner.do("PUT", "/api/v1/org/legal/imprint", map[string]any{"markdown": "# Acme GmbH"})
|
||||
expect(t, "org sets imprint", st, body, http.StatusNoContent, "")
|
||||
if got := legalOf(); got["imprint"].Markdown != "# Acme GmbH" || got["privacy"].URL != "https://operator.example/privacy" {
|
||||
t.Errorf("snapshot legal = %+v, want own imprint and platform privacy", got)
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/legal", nil)
|
||||
if !strings.Contains(mustJSON(list), "Acme GmbH") || strings.Contains(mustJSON(list), "operator.example") {
|
||||
t.Errorf("org legal list = %v, want only its own documents", list)
|
||||
}
|
||||
st, _ = owner.do("PUT", "/api/v1/org/legal/imprint", map[string]any{})
|
||||
if got := legalOf(); st != http.StatusNoContent || got["imprint"].Markdown != imprint {
|
||||
t.Errorf("after removing the own imprint snapshot = %+v", got)
|
||||
}
|
||||
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("lg")+".test", owner.roleID("viewer")))
|
||||
if st, _ := viewer.do("PUT", "/api/v1/org/legal/imprint", map[string]any{"markdown": "x"}); st != http.StatusForbidden {
|
||||
t.Errorf("viewer sets imprint = %d, want 403", st)
|
||||
}
|
||||
if st, _ := owner.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": "x"}); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin sets platform imprint = %d, want 403", st)
|
||||
}
|
||||
for path, want := range map[string]string{"/admin/legal": "Platform legal notice", "/settings/legal": "Legal notice & privacy"} {
|
||||
b := admin
|
||||
if path == "/settings/legal" {
|
||||
b = owner
|
||||
}
|
||||
if st, _, html := b.page(path); st != http.StatusOK || !strings.Contains(html, want) {
|
||||
t.Errorf("GET %s = %d, lacks %q", path, st, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A change on one replica shows on another with the next request.
|
||||
func TestLegalChangeReachesOtherReplicas(t *testing.T) {
|
||||
a := newEnv(t)
|
||||
b := newEnv(t)
|
||||
admin := a.browser(t)
|
||||
admin.signup("a@"+uniq("lr")+".test", uniq("lr-"))
|
||||
err := tenant.New(a.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) })
|
||||
admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{})
|
||||
|
||||
visitor := b.browser(t)
|
||||
if _, _, html := visitor.page("/login"); strings.Contains(html, `href="/legal/imprint"`) {
|
||||
t.Fatal("imprint linked before it exists")
|
||||
}
|
||||
admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": "# Impressum"})
|
||||
if _, _, html := visitor.page("/login"); !strings.Contains(html, `href="/legal/imprint"`) {
|
||||
t.Error("the other replica still serves the old footer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkdownPreview(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/markdown/preview", map[string]any{"markdown": "x"}); st != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous preview = %d, want 401", st)
|
||||
}
|
||||
b := e.browser(t)
|
||||
b.signup("p@"+uniq("md")+".test", uniq("md-"))
|
||||
st, body := b.do("POST", "/api/v1/markdown/preview", map[string]any{"markdown": "**hi** <script>x</script> "})
|
||||
html, _ := body["html"].(string)
|
||||
if st != http.StatusOK || !strings.Contains(html, "<strong>hi</strong>") || strings.Contains(html, "<script") || strings.Contains(html, "<img") {
|
||||
t.Errorf("preview = %d %q", st, html)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Platform admins limit what organizations and accounts may create. The
|
||||
// platform defaults apply to every organization without an override of its
|
||||
// own, also after they change. 0 means unlimited.
|
||||
|
||||
const settingLimits = "limits"
|
||||
|
||||
// Limits are the limits in effect for an organization, or the platform
|
||||
// defaults.
|
||||
type Limits struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
RegionsPerMonitor int `json:"regions_per_monitor"`
|
||||
// OwnRegionsCount makes the organization's own checker regions count
|
||||
// towards RegionsPerMonitor; otherwise only platform regions do.
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
// OrgsPerAccount limits the organizations an account owns.
|
||||
OrgsPerAccount int `json:"orgs_per_account"`
|
||||
}
|
||||
|
||||
func (s *Server) defaultLimits() Limits {
|
||||
if s.cloud() {
|
||||
return Limits{OrgsPerAccount: 3}
|
||||
}
|
||||
return Limits{}
|
||||
}
|
||||
|
||||
// platformLimits returns the platform defaults.
|
||||
func (s *Server) platformLimits(ctx context.Context) Limits {
|
||||
l, err := s.limits.get(ctx, s.rdb, func(ctx context.Context) (Limits, error) {
|
||||
l := s.defaultLimits()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingLimits)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, &l)
|
||||
})
|
||||
return l, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading limits failed", "error", err)
|
||||
return s.defaultLimits()
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// orgLimits applies org's overrides to the platform defaults.
|
||||
func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
|
||||
l := s.platformLimits(ctx)
|
||||
override := func(dst *int, v *int32) {
|
||||
if v != nil {
|
||||
*dst = int(*v)
|
||||
}
|
||||
}
|
||||
override(&l.Monitors, org.LimitMonitors)
|
||||
override(&l.StatusPages, org.LimitStatusPages)
|
||||
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
|
||||
if org.LimitOwnRegionsCount != nil {
|
||||
l.OwnRegionsCount = *org.LimitOwnRegionsCount
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// limitError reports a reached limit from inside a transaction.
|
||||
type limitError struct {
|
||||
code string
|
||||
max int
|
||||
}
|
||||
|
||||
func (e limitError) Error() string { return fmt.Sprintf("api: %s (%d)", e.code, e.max) }
|
||||
|
||||
// failLimit answers err if it is a limitError and reports whether it was.
|
||||
func failLimit(c *gin.Context, err error) bool {
|
||||
var le limitError
|
||||
if errors.As(err, &le) {
|
||||
fail(c, http.StatusUnprocessableEntity, le.code, "Max", le.max)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// reserve locks org's usage and fails if count, from countFn, has reached
|
||||
// max.
|
||||
func reserve(ctx context.Context, q *store.Queries, org uuid.UUID, max int, code string, countFn func(context.Context, uuid.UUID) (int64, error)) error {
|
||||
if max == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := q.LockOrgUsage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := countFn(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n >= int64(max) {
|
||||
return limitError{code, max}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// countedRegions counts the regions that count towards the limit.
|
||||
func countedRegions(l Limits, regions []uuid.UUID, platform map[uuid.UUID]bool) int {
|
||||
n := 0
|
||||
for _, r := range regions {
|
||||
if l.OwnRegionsCount || platform[r] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// checkRegions fails if a monitor would use more counted regions than
|
||||
// allowed. A monitor already beyond a lowered limit may keep its regions
|
||||
// but not add any.
|
||||
func checkRegions(l Limits, regions, previous []uuid.UUID, platform map[uuid.UUID]bool) error {
|
||||
n := countedRegions(l, regions, platform)
|
||||
if l.RegionsPerMonitor == 0 || n <= l.RegionsPerMonitor || n <= countedRegions(l, previous, platform) {
|
||||
return nil
|
||||
}
|
||||
if l.OwnRegionsCount {
|
||||
return limitError{"region_limit", l.RegionsPerMonitor}
|
||||
}
|
||||
return limitError{"platform_region_limit", l.RegionsPerMonitor}
|
||||
}
|
||||
|
||||
type usageView struct {
|
||||
Limits Limits `json:"limits"`
|
||||
Usage struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
func (s *Server) orgUsage(ctx context.Context, p *principal) (usageView, error) {
|
||||
v := usageView{Limits: s.orgLimits(ctx, p.Org)}
|
||||
v.Limits.OrgsPerAccount = 0
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
m, err := q.CountMonitors(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pg, err := q.CountStatusPages(ctx, p.Org.ID)
|
||||
v.Usage.Monitors, v.Usage.StatusPages = int(m), int(pg)
|
||||
return err
|
||||
})
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (s *Server) getOrgLimits(c *gin.Context) {
|
||||
v, err := s.orgUsage(c.Request.Context(), current(c))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
|
||||
func (s *Server) adminGetLimits(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, s.platformLimits(c.Request.Context()))
|
||||
}
|
||||
|
||||
type limitsRequest struct {
|
||||
Monitors int `json:"monitors" binding:"min=0,max=1000000"`
|
||||
StatusPages int `json:"status_pages" binding:"min=0,max=1000000"`
|
||||
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetLimits(c *gin.Context) {
|
||||
var req limitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(Limits(req))
|
||||
auditDetail(c, "limits", Limits(req))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingLimits, Value: raw})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.limits.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing limit change failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// optBool is a JSON boolean that may be null, and also accepts "true",
|
||||
// "false" and "" from forms.
|
||||
type optBool struct{ v *bool }
|
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (o *optBool) UnmarshalJSON(b []byte) error {
|
||||
switch strings.Trim(string(b), `"`) {
|
||||
case "null", "":
|
||||
o.v = nil
|
||||
case "true":
|
||||
t := true
|
||||
o.v = &t
|
||||
case "false":
|
||||
f := false
|
||||
o.v = &f
|
||||
default:
|
||||
return errors.New("not a boolean")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
|
||||
|
||||
// orgLimitsRequest overrides limits for one organization; null follows the
|
||||
// platform default.
|
||||
type orgLimitsRequest struct {
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req orgLimitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
auditDetail(c, "limits", req)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
|
||||
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
|
||||
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
|
||||
})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
type userLimitsRequest struct {
|
||||
// Orgs limits the organizations the account owns; null follows the
|
||||
// platform default.
|
||||
Orgs *int32 `json:"orgs" binding:"omitempty,min=0,max=100000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetUserLimits(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req userLimitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
auditDetail(c, "orgs", req.Orgs)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SetUserOrgLimit(ctx, store.SetUserOrgLimitParams{ID: id, Orgs: req.Orgs})
|
||||
auditDetail(c, "email", row.Email)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// adminOrg is an organization in the admin list.
|
||||
type adminOrg struct {
|
||||
moderatedOrg
|
||||
Created string `json:"created_at"`
|
||||
Overrides orgLimitsView `json:"overrides"`
|
||||
Limits Limits `json:"limits"`
|
||||
Usage struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
} `json:"usage"`
|
||||
Owner *adminOwner `json:"owner"`
|
||||
}
|
||||
|
||||
type orgLimitsView struct {
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
}
|
||||
|
||||
type adminOwner struct {
|
||||
moderatedUser
|
||||
// OrgLimit overrides the organizations the account may own.
|
||||
OrgLimit *int32 `json:"org_limit"`
|
||||
Orgs int `json:"orgs"`
|
||||
}
|
||||
|
||||
func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]adminOrg, pageInfo, error) {
|
||||
var rows []store.AdminListOrgsRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.AdminListOrgs(ctx, store.AdminListOrgsParams{
|
||||
Search: truncate(strings.TrimSpace(search), 200), MaxRows: pg.fetch(),
|
||||
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(),
|
||||
})
|
||||
return err
|
||||
})
|
||||
rows, info := paginate(pg, rows, func(r store.AdminListOrgsRow) cursor { return cursor{T: r.CreatedAt, ID: r.ID} })
|
||||
defaults := s.platformLimits(ctx)
|
||||
out := make([]adminOrg, len(rows))
|
||||
for i, r := range rows {
|
||||
o := &out[i]
|
||||
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
|
||||
o.Created = r.CreatedAt.Format("2006-01-02")
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount}
|
||||
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
|
||||
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount})
|
||||
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
|
||||
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
|
||||
if r.OwnerID != uuid.Nil {
|
||||
o.Owner = &adminOwner{
|
||||
moderatedUser: moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin},
|
||||
OrgLimit: r.OwnerLimitOrgs, Orgs: int(r.OwnerOrgs),
|
||||
}
|
||||
if r.OwnerLimitOrgs != nil {
|
||||
o.Limits.OrgsPerAccount = int(*r.OwnerLimitOrgs)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, info, err
|
||||
}
|
||||
|
||||
func (s *Server) adminListOrgs(c *gin.Context) {
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
orgs, info, err := s.adminOrgs(c.Request.Context(), c.Query("q"), pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"orgs": orgs, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
func webLimits(l Limits) web.LimitsView { return web.LimitsView(l) }
|
||||
|
||||
func optInt(v *int32) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.Itoa(int(*v))
|
||||
}
|
||||
|
||||
func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
|
||||
ctx := c.Request.Context()
|
||||
orgs, info, err := s.adminOrgs(ctx, c.Query("q"), pg)
|
||||
v := web.OrgsView{
|
||||
Search: strings.TrimSpace(c.Query("q")), Pager: pager(c, info), Next: c.Request.URL.RequestURI(),
|
||||
Defaults: webLimits(s.platformLimits(ctx)),
|
||||
}
|
||||
state := func(at *time.Time, reason string) string {
|
||||
switch {
|
||||
case at == nil:
|
||||
return ""
|
||||
case reason == "":
|
||||
return "-"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
for _, o := range orgs {
|
||||
row := web.OrgRow{
|
||||
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
|
||||
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
|
||||
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
|
||||
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor),
|
||||
}
|
||||
if o.Overrides.OwnRegionsCount != nil {
|
||||
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
|
||||
}
|
||||
if o.Owner != nil {
|
||||
row.Owner = &web.ModeratedTarget{ID: o.Owner.ID.String(), Name: o.Owner.Email, Suspended: state(o.Owner.SuspendedAt, o.Owner.Reason), Admin: o.Owner.Admin}
|
||||
row.OwnerOrgs, row.OwnerOrgLimit = o.Owner.Orgs, optInt(o.Owner.OrgLimit)
|
||||
}
|
||||
v.Orgs = append(v.Orgs, row)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestLimits(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx := context.Background()
|
||||
reset := func() {
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
|
||||
return err
|
||||
})
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(reset)
|
||||
admin := e.browser(t)
|
||||
admin.signup("admin@"+uniq("lim")+".test", uniq("lim-admin-"))
|
||||
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(ctx, admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setDefaults := func(l map[string]any) {
|
||||
t.Helper()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/limits", l); st != http.StatusNoContent {
|
||||
t.Fatalf("set defaults = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
setDefaults(map[string]any{"monitors": 2, "status_pages": 1, "regions_per_monitor": 1, "own_regions_count": false, "orgs_per_account": 3})
|
||||
|
||||
_, p1 := e.platformChecker(t, uniq("eu-"))
|
||||
_, p2 := e.platformChecker(t, uniq("us-"))
|
||||
owner := e.browser(t)
|
||||
orgSlug := uniq("lim-org-")
|
||||
owner.signup("o@"+uniq("lim")+".test", orgSlug)
|
||||
_, own := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
|
||||
o1 := own["id"].(string)
|
||||
monitor := func(regions ...string) (int, map[string]any) {
|
||||
return owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": regions,
|
||||
})
|
||||
}
|
||||
|
||||
// Monitors, passive ones included.
|
||||
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
|
||||
t.Fatalf("heartbeat = %d %v", st, body)
|
||||
}
|
||||
if st, body := monitor(p1); st != http.StatusCreated {
|
||||
t.Fatalf("second monitor = %d %v", st, body)
|
||||
}
|
||||
st, body := monitor(p1)
|
||||
expect(t, "third monitor", st, body, http.StatusUnprocessableEntity, "monitor_limit")
|
||||
if !strings.Contains(body["message"].(string), "2") {
|
||||
t.Errorf("message lacks the limit: %v", body["message"])
|
||||
}
|
||||
_, usage := owner.do("GET", "/api/v1/org/limits", nil)
|
||||
if raw := mustJSON(usage); !strings.Contains(raw, `"monitors":2`) || !strings.Contains(raw, `"usage":{"monitors":2,"status_pages":0}`) {
|
||||
t.Errorf("org limits = %s", raw)
|
||||
}
|
||||
|
||||
// An override lifts the monitor limit; own regions do not count.
|
||||
_, orgs := admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
|
||||
org := orgs["orgs"].([]any)[0].(map[string]any)
|
||||
orgID := org["id"].(string)
|
||||
setOrg := func(l map[string]any) {
|
||||
t.Helper()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+orgID+"/limits", l); st != http.StatusNoContent {
|
||||
t.Fatalf("set org limits = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
setOrg(map[string]any{"monitors": 10, "status_pages": nil, "regions_per_monitor": nil, "own_regions_count": nil})
|
||||
st, body = monitor(p1, p2)
|
||||
expect(t, "two platform regions", st, body, http.StatusUnprocessableEntity, "platform_region_limit")
|
||||
st, mixed := monitor(p1, o1)
|
||||
expect(t, "platform and own region", st, mixed, http.StatusCreated, "")
|
||||
|
||||
// Once own regions count, the existing monitor keeps both but may not
|
||||
// grow, and new ones are refused.
|
||||
setOrg(map[string]any{"monitors": 10, "own_regions_count": "true"})
|
||||
st, body = monitor(p1, o1)
|
||||
expect(t, "own region counted", st, body, http.StatusUnprocessableEntity, "region_limit")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
|
||||
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, o1},
|
||||
})
|
||||
expect(t, "edit a monitor beyond a lowered limit", st, body, http.StatusOK, "")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
|
||||
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, p2, o1},
|
||||
})
|
||||
expect(t, "grow a monitor beyond the limit", st, body, http.StatusUnprocessableEntity, "region_limit")
|
||||
|
||||
// Status pages; concurrent creations cannot overshoot.
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
created := 0
|
||||
for range 5 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
st, _ := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("p-"), "title": "x"})
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if st == http.StatusCreated {
|
||||
created++
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if created != 1 {
|
||||
t.Errorf("%d status pages created under a limit of 1", created)
|
||||
}
|
||||
|
||||
// Defaults change for every organization without an override, at once.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("lim")+".test", uniq("lim-x-"))
|
||||
setDefaults(map[string]any{"monitors": 1})
|
||||
if st, _ := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
|
||||
t.Fatalf("first monitor = %d", st)
|
||||
}
|
||||
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
|
||||
expect(t, "default lowered", st, body, http.StatusUnprocessableEntity, "monitor_limit")
|
||||
setDefaults(map[string]any{"monitors": 0})
|
||||
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
|
||||
expect(t, "default unlimited", st, body, http.StatusCreated, "")
|
||||
|
||||
// Account limits and the admin list.
|
||||
ownerID := org["owner"].(map[string]any)["id"].(string)
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/users/"+ownerID+"/limits", map[string]any{"orgs": 5}); st != http.StatusNoContent {
|
||||
t.Fatalf("set user limit = %d %v", st, body)
|
||||
}
|
||||
_, orgs = admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
|
||||
raw := mustJSON(orgs)
|
||||
for _, want := range []string{`"org_limit":5`, `"orgs":1`, `"monitors":10`, `"own_regions_count":true`, `"usage":{"monitors":3,"status_pages":1}`} {
|
||||
if !strings.Contains(raw, want) {
|
||||
t.Errorf("admin org list lacks %s: %s", want, raw)
|
||||
}
|
||||
}
|
||||
if st, _ := owner.do("GET", "/api/v1/admin/orgs", nil); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin org list = %d", st)
|
||||
}
|
||||
if _, _, html := admin.page("/admin/orgs?q=" + orgSlug); !strings.Contains(html, `id="orgs"`) || !strings.Contains(html, orgSlug) {
|
||||
t.Error("the admin page lacks the organization list")
|
||||
}
|
||||
if _, _, html := owner.page("/settings/org"); !strings.Contains(html, "3 / 10") {
|
||||
t.Error("the organization settings lack the usage")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
|
||||
"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"
|
||||
)
|
||||
|
||||
// upcomingHorizon is how far ahead status pages and the console list
|
||||
// maintenance.
|
||||
const upcomingHorizon = 14 * 24 * time.Hour
|
||||
|
||||
func loadLocation(name string) *time.Location {
|
||||
if loc, err := time.LoadLocation(name); err == nil {
|
||||
return loc
|
||||
}
|
||||
return time.UTC
|
||||
}
|
||||
|
||||
func weekdaysOf(ws []int16) []time.Weekday {
|
||||
out := make([]time.Weekday, len(ws))
|
||||
for i, w := range ws {
|
||||
out[i] = time.Weekday(w)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ruleOf(w store.MaintenanceWindow) maintenance.Rule {
|
||||
return maintenance.Rule{
|
||||
Start: w.StartsAt, Duration: time.Duration(w.DurationSeconds) * time.Second, Location: loadLocation(w.TimeZone),
|
||||
Recurrence: maintenance.Recurrence(w.Recurrence), Every: int(w.Every), Weekdays: weekdaysOf(w.Weekdays), Until: w.Until,
|
||||
}
|
||||
}
|
||||
|
||||
func windowOf(r store.MaintenanceForMonitorsRow) store.MaintenanceWindow {
|
||||
return store.MaintenanceWindow{
|
||||
ID: r.ID, Title: r.Title, Description: r.Description, StartsAt: r.StartsAt, DurationSeconds: r.DurationSeconds,
|
||||
TimeZone: r.TimeZone, Recurrence: r.Recurrence, Every: r.Every, Weekdays: r.Weekdays, Until: r.Until,
|
||||
}
|
||||
}
|
||||
|
||||
// maintenanceFor loads the windows covering monitors, by monitor.
|
||||
func maintenanceFor(ctx context.Context, q *store.Queries, ids []uuid.UUID) (map[uuid.UUID][]store.MaintenanceWindow, error) {
|
||||
rows, err := q.MaintenanceForMonitors(ctx, ids)
|
||||
out := map[uuid.UUID][]store.MaintenanceWindow{}
|
||||
for _, r := range rows {
|
||||
if r.MonitorID != nil {
|
||||
out[*r.MonitorID] = append(out[*r.MonitorID], windowOf(r))
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// inMaintenance returns the window of ws in progress at t.
|
||||
func inMaintenance(ws []store.MaintenanceWindow, t time.Time) (store.MaintenanceWindow, maintenance.Span, bool) {
|
||||
for _, w := range ws {
|
||||
if s, ok := ruleOf(w).ActiveAt(t); ok {
|
||||
return w, s, true
|
||||
}
|
||||
}
|
||||
return store.MaintenanceWindow{}, maintenance.Span{}, false
|
||||
}
|
||||
|
||||
// flexInts accepts numbers or numeric strings, as HTML forms send them.
|
||||
type flexInts []int
|
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (f *flexInts) UnmarshalJSON(b []byte) error {
|
||||
var raw []json.RawMessage
|
||||
if err := json.Unmarshal(b, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = make(flexInts, 0, len(raw))
|
||||
for _, r := range raw {
|
||||
s := strings.Trim(string(r), `"`)
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*f = append(*f, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type maintenanceRequest struct {
|
||||
Title string `json:"title" binding:"required,max=200"`
|
||||
Description string `json:"description" binding:"max=20000"`
|
||||
// Start is the local wall-clock time of the first occurrence,
|
||||
// "2006-01-02T15:04", in TimeZone.
|
||||
Start string `json:"start" binding:"required"`
|
||||
TimeZone string `json:"time_zone" binding:"required,max=64"`
|
||||
DurationMinutes int `json:"duration_minutes" binding:"required"`
|
||||
Recurrence string `json:"recurrence"`
|
||||
Every int `json:"every"`
|
||||
Weekdays flexInts `json:"weekdays"`
|
||||
// Until is the last day occurrences may start on, "2006-01-02".
|
||||
Until string `json:"until"`
|
||||
MonitorIDs []uuid.UUID `json:"monitor_ids"`
|
||||
GroupIDs []uuid.UUID `json:"group_ids"`
|
||||
}
|
||||
|
||||
// params validates req into the stored form.
|
||||
func (req maintenanceRequest) params() (store.CreateMaintenanceParams, string) {
|
||||
loc, err := time.LoadLocation(req.TimeZone)
|
||||
if err != nil || req.TimeZone == "" || req.TimeZone == "Local" {
|
||||
return store.CreateMaintenanceParams{}, "invalid_time_zone"
|
||||
}
|
||||
start, err := time.ParseInLocation("2006-01-02T15:04", req.Start, loc)
|
||||
if err != nil {
|
||||
return store.CreateMaintenanceParams{}, "invalid_maintenance_time"
|
||||
}
|
||||
p := store.CreateMaintenanceParams{
|
||||
Title: strings.TrimSpace(req.Title), Description: strings.TrimSpace(req.Description), StartsAt: start,
|
||||
DurationSeconds: int32(req.DurationMinutes * 60), TimeZone: req.TimeZone,
|
||||
Recurrence: req.Recurrence, Every: int32(max(req.Every, 1)), Weekdays: []int16{},
|
||||
}
|
||||
if p.Recurrence == "" {
|
||||
p.Recurrence = string(maintenance.Once)
|
||||
}
|
||||
if p.Title == "" {
|
||||
return p, "invalid_input"
|
||||
}
|
||||
if p.Recurrence == string(maintenance.Weekly) {
|
||||
for _, w := range req.Weekdays {
|
||||
if w < 0 || w > 6 {
|
||||
return p, "invalid_maintenance_time"
|
||||
}
|
||||
p.Weekdays = append(p.Weekdays, int16(w))
|
||||
}
|
||||
}
|
||||
if req.Until != "" && p.Recurrence != string(maintenance.Once) {
|
||||
day, err := time.ParseInLocation("2006-01-02", req.Until, loc)
|
||||
if err != nil {
|
||||
return p, "invalid_maintenance_time"
|
||||
}
|
||||
end := day.AddDate(0, 0, 1).Add(-time.Second)
|
||||
p.Until = &end
|
||||
}
|
||||
if err := ruleOf(store.MaintenanceWindow{
|
||||
StartsAt: p.StartsAt, DurationSeconds: p.DurationSeconds, TimeZone: p.TimeZone, Recurrence: p.Recurrence,
|
||||
Every: p.Every, Weekdays: p.Weekdays, Until: p.Until,
|
||||
}).Validate(); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, maintenance.ErrOverlap):
|
||||
return p, "maintenance_overlaps"
|
||||
case errors.Is(err, maintenance.ErrDuration):
|
||||
return p, "invalid_maintenance_duration"
|
||||
}
|
||||
return p, "invalid_maintenance_time"
|
||||
}
|
||||
if len(req.MonitorIDs)+len(req.GroupIDs) == 0 {
|
||||
return p, "maintenance_without_targets"
|
||||
}
|
||||
return p, ""
|
||||
}
|
||||
|
||||
type maintenanceSpan struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
}
|
||||
|
||||
type maintenanceView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Start string `json:"start"`
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
DurationMinutes int `json:"duration_minutes"`
|
||||
Recurrence string `json:"recurrence"`
|
||||
Every int32 `json:"every"`
|
||||
Weekdays []int16 `json:"weekdays"`
|
||||
Until string `json:"until,omitempty"`
|
||||
MonitorIDs []uuid.UUID `json:"monitor_ids"`
|
||||
GroupIDs []uuid.UUID `json:"group_ids"`
|
||||
Active bool `json:"active"`
|
||||
Next *maintenanceSpan `json:"next"`
|
||||
}
|
||||
|
||||
func viewMaintenance(w store.MaintenanceWindow, targets []store.MaintenanceTarget, now time.Time) maintenanceView {
|
||||
loc := loadLocation(w.TimeZone)
|
||||
v := maintenanceView{
|
||||
ID: w.ID, Title: w.Title, Description: w.Description, Start: w.StartsAt.In(loc).Format("2006-01-02T15:04"),
|
||||
StartsAt: w.StartsAt, TimeZone: w.TimeZone, DurationMinutes: int(w.DurationSeconds / 60), Recurrence: w.Recurrence,
|
||||
Every: w.Every, Weekdays: w.Weekdays, MonitorIDs: []uuid.UUID{}, GroupIDs: []uuid.UUID{},
|
||||
}
|
||||
if w.Until != nil {
|
||||
v.Until = w.Until.In(loc).Format("2006-01-02")
|
||||
}
|
||||
for _, t := range targets {
|
||||
if t.WindowID != w.ID {
|
||||
continue
|
||||
}
|
||||
if t.MonitorID != nil {
|
||||
v.MonitorIDs = append(v.MonitorIDs, *t.MonitorID)
|
||||
} else if t.GroupID != nil {
|
||||
v.GroupIDs = append(v.GroupIDs, *t.GroupID)
|
||||
}
|
||||
}
|
||||
if s, ok := ruleOf(w).Next(now, 400*24*time.Hour); ok {
|
||||
v.Next = &maintenanceSpan{Start: s.Start, End: s.End}
|
||||
v.Active = !now.Before(s.Start)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// maintenanceScope holds what permission checks on windows need.
|
||||
type maintenanceScope struct {
|
||||
tree groupTree
|
||||
monitors map[uuid.UUID]store.Monitor
|
||||
}
|
||||
|
||||
func (s *Server) loadMaintenanceScope(ctx context.Context, p *principal) (maintenanceScope, error) {
|
||||
ms := maintenanceScope{monitors: map[uuid.UUID]store.Monitor{}}
|
||||
var err error
|
||||
if ms.tree, err = s.loadGroupTree(ctx, p.scope()); err != nil {
|
||||
return ms, err
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
rows, err := q.ListMonitors(ctx)
|
||||
for _, m := range rows {
|
||||
ms.monitors[m.ID] = m
|
||||
}
|
||||
return err
|
||||
})
|
||||
return ms, err
|
||||
}
|
||||
|
||||
// can reports whether p holds perm on every target, or with any=true on at
|
||||
// least one. Unknown targets fail.
|
||||
func (ms maintenanceScope) can(p *principal, perm authz.Permission, monitors, groups []uuid.UUID, any bool) bool {
|
||||
n := 0
|
||||
check := func(ok bool) {
|
||||
if ok {
|
||||
n++
|
||||
}
|
||||
}
|
||||
for _, id := range monitors {
|
||||
m, ok := ms.monitors[id]
|
||||
check(ok && canInGroup(p, perm, ms.tree, m.GroupID))
|
||||
}
|
||||
for _, id := range groups {
|
||||
_, ok := ms.tree.byID[id]
|
||||
check(ok && canInGroup(p, perm, ms.tree, &id))
|
||||
}
|
||||
if any {
|
||||
return n > 0
|
||||
}
|
||||
return n == len(monitors)+len(groups)
|
||||
}
|
||||
|
||||
// listMaintenanceViews reads a page of maintenance windows, latest start
|
||||
// first, keeping those p may read: a page may hold fewer.
|
||||
func (s *Server) listMaintenanceViews(ctx context.Context, p *principal, ms maintenanceScope, pg pageReq) ([]maintenanceView, pageInfo, error) {
|
||||
var (
|
||||
windows []store.MaintenanceWindow
|
||||
targets []store.MaintenanceTarget
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if windows, err = q.ListMaintenancePage(ctx, store.ListMaintenancePageParams{
|
||||
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
targets, err = q.ListMaintenanceTargets(ctx)
|
||||
return err
|
||||
})
|
||||
windows, info := paginate(pg, windows, func(w store.MaintenanceWindow) cursor { return cursor{T: w.StartsAt, ID: w.ID} })
|
||||
out := []maintenanceView{}
|
||||
now := time.Now()
|
||||
for _, w := range windows {
|
||||
v := viewMaintenance(w, targets, now)
|
||||
if ms.can(p, authz.MonitorsRead, v.MonitorIDs, v.GroupIDs, true) {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, info, err
|
||||
}
|
||||
|
||||
func (s *Server) listMaintenance(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
ms, err := s.loadMaintenanceScope(ctx, p)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, info, err := s.listMaintenanceViews(ctx, p, ms, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"maintenance": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
func (s *Server) saveMaintenance(c *gin.Context, id *uuid.UUID) {
|
||||
var req maintenanceRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
params, code := req.params()
|
||||
if code != "" {
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
ms, err := s.loadMaintenanceScope(ctx, p)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ms.can(p, authz.MonitorsWrite, req.MonitorIDs, req.GroupIDs, false) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
params.OrgID = p.Org.ID
|
||||
var (
|
||||
w store.MaintenanceWindow
|
||||
targets []store.MaintenanceTarget
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if id == nil {
|
||||
w, err = q.CreateMaintenance(ctx, params)
|
||||
} else {
|
||||
old, err := q.GetMaintenance(ctx, *id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prev, err := q.ListMaintenanceTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Changing a window needs write access to what it covered too.
|
||||
v := viewMaintenance(old, prev, time.Now())
|
||||
if !ms.can(p, authz.MonitorsWrite, v.MonitorIDs, v.GroupIDs, false) {
|
||||
return errForbidden
|
||||
}
|
||||
w, err = q.UpdateMaintenance(ctx, store.UpdateMaintenanceParams{
|
||||
ID: *id, Title: params.Title, Description: params.Description, StartsAt: params.StartsAt,
|
||||
DurationSeconds: params.DurationSeconds, TimeZone: params.TimeZone, Recurrence: params.Recurrence,
|
||||
Every: params.Every, Weekdays: params.Weekdays, Until: params.Until,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.ClearMaintenanceTargets(ctx, w.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range dedupe(req.MonitorIDs) {
|
||||
if err := q.AddMaintenanceTarget(ctx, store.AddMaintenanceTargetParams{WindowID: w.ID, OrgID: p.Org.ID, MonitorID: &m}); err != nil {
|
||||
return err
|
||||
}
|
||||
targets = append(targets, store.MaintenanceTarget{WindowID: w.ID, MonitorID: &m})
|
||||
}
|
||||
for _, g := range dedupe(req.GroupIDs) {
|
||||
if err := q.AddMaintenanceTarget(ctx, store.AddMaintenanceTargetParams{WindowID: w.ID, OrgID: p.Org.ID, GroupID: &g}); err != nil {
|
||||
return err
|
||||
}
|
||||
targets = append(targets, store.MaintenanceTarget{WindowID: w.ID, GroupID: &g})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
case errors.Is(err, errForbidden):
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if id == nil {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
c.JSON(status, viewMaintenance(w, targets, time.Now()))
|
||||
}
|
||||
|
||||
var errForbidden = errors.New("api: forbidden")
|
||||
|
||||
func dedupe(ids []uuid.UUID) []uuid.UUID {
|
||||
seen := map[uuid.UUID]bool{}
|
||||
var out []uuid.UUID
|
||||
for _, id := range ids {
|
||||
if !seen[id] {
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) createMaintenance(c *gin.Context) { s.saveMaintenance(c, nil) }
|
||||
|
||||
func (s *Server) updateMaintenance(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
s.saveMaintenance(c, &id)
|
||||
}
|
||||
|
||||
func (s *Server) deleteMaintenance(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
ms, err := s.loadMaintenanceScope(ctx, p)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
w, err := q.GetMaintenance(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targets, err := q.ListMaintenanceTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v := viewMaintenance(w, targets, time.Now())
|
||||
if !ms.can(p, authz.MonitorsWrite, v.MonitorIDs, v.GroupIDs, false) {
|
||||
return errForbidden
|
||||
}
|
||||
auditDetail(c, "name", w.Title)
|
||||
_, err = q.DeleteMaintenance(ctx, id)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case errors.Is(err, errForbidden):
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// monitorsInMaintenance loads, in system scope, which of ids are covered by
|
||||
// which windows; used while evaluating results.
|
||||
func (s *Server) monitorsInMaintenance(ctx context.Context, ids []uuid.UUID) map[uuid.UUID][]store.MaintenanceWindow {
|
||||
var out map[uuid.UUID][]store.MaintenanceWindow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
out, err = maintenanceFor(ctx, q, ids)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
// Without the windows, failures alert as usual: better a page
|
||||
// during maintenance than silence during an outage.
|
||||
s.log.ErrorContext(ctx, "loading maintenance windows failed", "error", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// scheduleText describes when a window repeats, e.g. "Every 2 weeks on
|
||||
// Tue, Thu until 2026-12-31".
|
||||
func scheduleText(ctx context.Context, v maintenanceView) string {
|
||||
var s string
|
||||
switch v.Recurrence {
|
||||
case string(maintenance.Daily):
|
||||
s = i18n.T(ctx, "maintenance.schedule_daily", "Count", int(v.Every))
|
||||
case string(maintenance.Weekly):
|
||||
days := v.Weekdays
|
||||
if len(days) == 0 {
|
||||
days = []int16{int16(v.StartsAt.In(loadLocation(v.TimeZone)).Weekday())}
|
||||
}
|
||||
names := make([]string, 0, len(days))
|
||||
for _, d := range []int16{1, 2, 3, 4, 5, 6, 0} {
|
||||
if slices.Contains(days, d) {
|
||||
names = append(names, i18n.T(ctx, "weekday."+strconv.Itoa(int(d))))
|
||||
}
|
||||
}
|
||||
s = i18n.T(ctx, "maintenance.schedule_weekly", "Count", int(v.Every), "Days", strings.Join(names, ", "))
|
||||
case string(maintenance.Monthly):
|
||||
s = i18n.T(ctx, "maintenance.schedule_monthly", "Count", int(v.Every), "Day", v.StartsAt.In(loadLocation(v.TimeZone)).Day())
|
||||
default:
|
||||
s = i18n.T(ctx, "maintenance.schedule_once")
|
||||
}
|
||||
start := strings.Replace(v.Start, "T", " ", 1)
|
||||
s += " · " + i18n.T(ctx, "maintenance.schedule_from", "Time", start, "Minutes", v.DurationMinutes, "Zone", v.TimeZone)
|
||||
if v.Until != "" {
|
||||
s += " · " + i18n.T(ctx, "maintenance.schedule_until", "Date", v.Until)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) maintenancePage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
ms, err := s.loadMaintenanceScope(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return nil, errAborted
|
||||
}
|
||||
windows, info, err := s.listMaintenanceViews(ctx, p, ms, pg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.MaintenanceView{Form: web.MaintenanceForm{Duration: 60, Recurrence: "none", Every: 1}, Pager: pager(c, info)}
|
||||
ms.tree.walk(func(g store.MonitorGroup, depth int) {
|
||||
if canInGroup(p, authz.MonitorsWrite, ms.tree, &g.ID) {
|
||||
v.Groups = append(v.Groups, web.TargetOption{ID: g.ID.String(), Name: g.Name, Depth: depth})
|
||||
}
|
||||
})
|
||||
names := map[uuid.UUID]string{}
|
||||
for _, m := range ms.monitors {
|
||||
names[m.ID] = m.Name
|
||||
if canInGroup(p, authz.MonitorsWrite, ms.tree, m.GroupID) {
|
||||
v.Monitors = append(v.Monitors, web.TargetOption{ID: m.ID.String(), Name: m.Name})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(v.Monitors, func(a, b web.TargetOption) int { return strings.Compare(a.Name, b.Name) })
|
||||
v.CanWrite = len(v.Monitors)+len(v.Groups) > 0
|
||||
for id, g := range ms.tree.byID {
|
||||
names[id] = g.Name
|
||||
}
|
||||
for _, w := range windows {
|
||||
row := web.MaintenanceRow{
|
||||
ID: w.ID.String(), Title: w.Title, Schedule: scheduleText(ctx, w), Active: w.Active,
|
||||
CanWrite: ms.can(p, authz.MonitorsWrite, w.MonitorIDs, w.GroupIDs, false),
|
||||
}
|
||||
row.Description, _ = web.RenderMarkdown(w.Description)
|
||||
var targets []string
|
||||
for _, id := range w.GroupIDs {
|
||||
targets = append(targets, i18n.T(ctx, "maintenance.group_target", "Name", names[id]))
|
||||
}
|
||||
for _, id := range w.MonitorIDs {
|
||||
targets = append(targets, names[id])
|
||||
}
|
||||
row.Targets = strings.Join(targets, ", ")
|
||||
if w.Next != nil && !w.Active {
|
||||
row.Next = w.Next.Start.In(loadLocation(w.TimeZone)).Format("2006-01-02 15:04")
|
||||
}
|
||||
v.Windows = append(v.Windows, row)
|
||||
if w.ID.String() == c.Query("edit") && row.CanWrite {
|
||||
f := web.MaintenanceForm{
|
||||
ID: row.ID, Title: w.Title, Description: w.Description, Start: w.Start, TimeZone: w.TimeZone,
|
||||
Duration: w.DurationMinutes, Recurrence: w.Recurrence, Every: int(w.Every), Until: w.Until,
|
||||
Weekdays: map[int]bool{}, Monitors: map[string]bool{}, Groups: map[string]bool{},
|
||||
}
|
||||
for _, d := range w.Weekdays {
|
||||
f.Weekdays[int(d)] = true
|
||||
}
|
||||
for _, id := range w.MonitorIDs {
|
||||
f.Monitors[id.String()] = true
|
||||
}
|
||||
for _, id := range w.GroupIDs {
|
||||
f.Groups[id.String()] = true
|
||||
}
|
||||
v.Form = f
|
||||
}
|
||||
}
|
||||
return web.MaintenancePage(page, me, v), nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func TestMaintenance(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
token, region := e.platformChecker(t, uniq("eu-"))
|
||||
client := agentapi.NewClient(e.srv.URL, token, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("mt")+".test", uniq("mt-"))
|
||||
|
||||
infra := owner.group("Infra", "")
|
||||
db := owner.group("Databases", infra)
|
||||
other := owner.group("Other", "")
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Postgres", "type": "tcp", "target": "db.example.com:5432", "interval_seconds": 3600,
|
||||
"confirmations": 1, "regions": []string{region}, "group_id": db,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
monitor := uuid.MustParse(body["id"].(string))
|
||||
|
||||
now := time.Now().UTC()
|
||||
window := map[string]any{
|
||||
"title": "DB upgrade", "description": "Upgrade to **Postgres 18**.",
|
||||
"start": now.Add(-10 * time.Minute).Format("2006-01-02T15:04"), "time_zone": "UTC", "duration_minutes": 60,
|
||||
"group_ids": []string{infra},
|
||||
}
|
||||
for name, tc := range map[string]struct {
|
||||
change map[string]any
|
||||
code string
|
||||
}{
|
||||
"time zone": {map[string]any{"time_zone": "Mars/Olympus"}, "invalid_time_zone"},
|
||||
"no targets": {map[string]any{"group_ids": []string{}}, "maintenance_without_targets"},
|
||||
"overlapping": {map[string]any{"recurrence": "daily", "duration_minutes": 25 * 60}, "maintenance_overlaps"},
|
||||
} {
|
||||
req := map[string]any{}
|
||||
for k, v := range window {
|
||||
req[k] = v
|
||||
}
|
||||
for k, v := range tc.change {
|
||||
req[k] = v
|
||||
}
|
||||
st, body := owner.do("POST", "/api/v1/org/maintenance", req)
|
||||
expect(t, name, st, body, http.StatusUnprocessableEntity, tc.code)
|
||||
}
|
||||
st, body = owner.do("POST", "/api/v1/org/maintenance", window)
|
||||
if st != http.StatusCreated || body["active"] != true {
|
||||
t.Fatalf("create maintenance = %d %v", st, body)
|
||||
}
|
||||
windowID := body["id"].(string)
|
||||
|
||||
// A failure during maintenance of a parent group opens no incident.
|
||||
report := func(ok bool) {
|
||||
t.Helper()
|
||||
if err := client.Report(context.Background(), []agentapi.Result{{MonitorID: monitor, ScheduledAt: time.Now(), StartedAt: time.Now(), OK: ok}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
report(false)
|
||||
report(false)
|
||||
if _, inc := owner.do("GET", "/api/v1/org/incidents", nil); len(inc["incidents"].([]any)) != 0 {
|
||||
t.Fatalf("incident opened during maintenance: %v", inc)
|
||||
}
|
||||
_, _, dash := owner.page("/")
|
||||
if !strings.Contains(dash, `title="maintenance"`) && !strings.Contains(dash, `title="Wartung"`) {
|
||||
t.Error("dashboard does not show the monitor under maintenance")
|
||||
}
|
||||
if _, _, page := owner.page("/maintenance"); !strings.Contains(page, "<strong>Postgres 18</strong>") {
|
||||
t.Error("maintenance page does not render the Markdown description")
|
||||
}
|
||||
|
||||
// Status pages show the component under maintenance.
|
||||
slug := uniq("mtp-")
|
||||
_, sp := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme", "description": "See [docs](https://docs.example)"})
|
||||
pageID := sp["id"].(string)
|
||||
_, m2 := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Replica", "type": "tcp", "target": "db2.example.com:5432", "interval_seconds": 3600, "regions": []string{region}, "group_id": db,
|
||||
})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{
|
||||
{"monitor_id": monitor.String(), "section": "", "label": "Database"},
|
||||
{"monitor_id": m2["id"].(string), "section": "", "label": "Replica"},
|
||||
}})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme", "description": "See [docs](https://docs.example)", "published": true})
|
||||
snap, err := e.statuspageClient(t, nil).Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// One occurrence covering two components is listed once.
|
||||
if len(snap.Maintenance) != 1 || strings.Join(snap.Maintenance[0].Components, ",") != "Database,Replica" {
|
||||
t.Fatalf("snapshot maintenance = %+v", snap.Maintenance)
|
||||
}
|
||||
if got := snap.WithMaintenance(time.Now()); got.Status != agentapi.PageUnderMaintenance || got.Sections[0].Components[0].Status != agentapi.PageUnderMaintenance {
|
||||
t.Errorf("WithMaintenance() = %s / %+v", got.Status, got.Sections)
|
||||
}
|
||||
if got := snap.WithMaintenance(time.Now().Add(2 * time.Hour)); got.Status == agentapi.PageUnderMaintenance {
|
||||
t.Error("page still under maintenance after it ended")
|
||||
}
|
||||
|
||||
// Members limited to another group may not plan maintenance here.
|
||||
scopedEmail := "s@" + uniq("mt") + ".test"
|
||||
scoped := e.joinVia(t, owner.invite(scopedEmail, owner.roleID("viewer")))
|
||||
st, body = owner.do("POST", "/api/v1/org/members/"+owner.userID(scopedEmail)+"/roles", map[string]any{
|
||||
"role_id": owner.roleID("editor"), "resource_type": "monitor_group", "resource_id": other,
|
||||
})
|
||||
expect(t, "assign scoped editor", st, body, http.StatusCreated, "")
|
||||
st, body = scoped.do("POST", "/api/v1/org/maintenance", window)
|
||||
expect(t, "scoped editor targets foreign group", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = scoped.do("DELETE", "/api/v1/org/maintenance/"+windowID, nil)
|
||||
expect(t, "scoped editor deletes foreign maintenance", st, body, http.StatusForbidden, "forbidden")
|
||||
w2 := map[string]any{}
|
||||
for k, v := range window {
|
||||
w2[k] = v
|
||||
}
|
||||
w2["group_ids"] = []string{other}
|
||||
w2["recurrence"], w2["weekdays"] = "weekly", []string{"1", "4"}
|
||||
st, body = scoped.do("POST", "/api/v1/org/maintenance", w2)
|
||||
if st != http.StatusCreated || body["next"] == nil {
|
||||
t.Errorf("scoped editor plans weekly maintenance for own group = %d %v", st, body)
|
||||
}
|
||||
|
||||
// Without maintenance the failure alerts again.
|
||||
st, body = owner.do("DELETE", "/api/v1/org/maintenance/"+windowID, nil)
|
||||
expect(t, "delete maintenance", st, body, http.StatusNoContent, "")
|
||||
report(false)
|
||||
if _, inc := owner.do("GET", "/api/v1/org/incidents", nil); len(inc["incidents"].([]any)) != 1 {
|
||||
t.Errorf("no incident after the maintenance ended: %v", inc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditMaintenanceReplacesTargets(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("me")+".test", uniq("me-"))
|
||||
a, b := owner.group("A", ""), owner.group("B", "")
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
req := map[string]any{
|
||||
"title": "Patch", "start": "2030-01-01T02:00", "time_zone": "Europe/Berlin", "duration_minutes": 30,
|
||||
"recurrence": "monthly", "until": "2030-12-31", "group_ids": []string{a},
|
||||
}
|
||||
_, body := owner.do("POST", "/api/v1/org/maintenance", req)
|
||||
id := body["id"].(string)
|
||||
req["group_ids"], req["monitor_ids"], req["title"] = []string{b}, []string{m["id"].(string)}, "Patch v2"
|
||||
st, body := owner.do("PUT", "/api/v1/org/maintenance/"+id, req)
|
||||
if st != http.StatusOK || body["title"] != "Patch v2" {
|
||||
t.Fatalf("update = %d %v", st, body)
|
||||
}
|
||||
_, list := owner.do("GET", "/api/v1/org/maintenance", nil)
|
||||
got := list["maintenance"].([]any)[0].(map[string]any)
|
||||
if mustJSON(got["group_ids"]) != `["`+b+`"]` || len(got["monitor_ids"].([]any)) != 1 || got["until"] != "2030-12-31" {
|
||||
t.Errorf("after update = %v", got)
|
||||
}
|
||||
next, _ := time.Parse(time.RFC3339, got["next"].(map[string]any)["start"].(string))
|
||||
if want := time.Date(2030, 1, 1, 1, 0, 0, 0, time.UTC); !next.Equal(want) {
|
||||
t.Errorf("next start = %v, want 02:00 Berlin = %v", next, want)
|
||||
}
|
||||
if _, _, page := owner.page("/maintenance?edit=" + id); !strings.Contains(page, `value="Patch v2"`) {
|
||||
t.Error("edit form is not prefilled")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
type previewRequest struct {
|
||||
Markdown string `json:"markdown" binding:"max=100000"`
|
||||
}
|
||||
|
||||
// previewMarkdown renders Markdown exactly as pages will, for the editor's
|
||||
// preview tab.
|
||||
func (s *Server) previewMarkdown(c *gin.Context) {
|
||||
var req previewRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
if !s.limit(c, "md-preview:"+auth.Current(c).UserID.String(), 120, time.Minute) {
|
||||
return
|
||||
}
|
||||
html, err := web.RenderMarkdown(req.Markdown)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"html": html})
|
||||
}
|
||||
+3
-1
@@ -40,6 +40,8 @@ type meView struct {
|
||||
RecoveryCodesLeft int `json:"recovery_codes_left"`
|
||||
// IsAdmin marks platform admins, who manage shared regions and agents.
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
// HasPassword is false for accounts that only sign in through SSO.
|
||||
HasPassword bool `json:"has_password"`
|
||||
}
|
||||
|
||||
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
|
||||
@@ -57,7 +59,7 @@ func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left), IsAdmin: u.IsAdmin}
|
||||
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left), IsAdmin: u.IsAdmin, HasPassword: u.PasswordHash != nil}
|
||||
for _, o := range orgs {
|
||||
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
|
||||
if o.RequireTotp && !me.TOTP {
|
||||
|
||||
+14
-5
@@ -32,15 +32,20 @@ type memberView struct {
|
||||
Assignments []assignmentView `json:"assignments"`
|
||||
}
|
||||
|
||||
func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) {
|
||||
// loadMembers reads a page of members by email.
|
||||
func (s *Server) loadMembers(c *gin.Context, pg pageReq) ([]memberView, pageInfo, error) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var out []memberView
|
||||
var info pageInfo
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
members, err := q.ListOrgMembers(ctx, p.Org.ID)
|
||||
members, err := q.ListOrgMembersPage(ctx, store.ListOrgMembersPageParams{
|
||||
OrgID: p.Org.ID, AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
members, info = paginate(pg, members, func(m store.ListOrgMembersPageRow) cursor { return cursor{S: m.Email, ID: m.ID} })
|
||||
assigns, err := q.ListAssignments(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -64,16 +69,20 @@ func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) {
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
return out, info, err
|
||||
}
|
||||
|
||||
func (s *Server) listMembers(c *gin.Context) {
|
||||
members, err := s.loadMembers(c)
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
members, info, err := s.loadMembers(c, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"members": members})
|
||||
c.JSON(http.StatusOK, gin.H{"members": members, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
// removeMember requires the actor to hold every permission the member holds
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Platform admins moderate public status pages and the organizations and
|
||||
// accounts behind them: suspending hides or stops them and can be undone,
|
||||
// deleting cannot. Suspended pages leave status page servers when these
|
||||
// next ask for them, within half a minute.
|
||||
|
||||
type moderatedPage struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Published bool `json:"published"`
|
||||
Domain string `json:"custom_domain,omitempty"`
|
||||
SuspendedAt *time.Time `json:"suspended_at"`
|
||||
Reason string `json:"suspended_reason,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Org moderatedOrg `json:"org"`
|
||||
Owner *moderatedUser `json:"owner"`
|
||||
}
|
||||
|
||||
type moderatedOrg struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
SuspendedAt *time.Time `json:"suspended_at"`
|
||||
Reason string `json:"suspended_reason,omitempty"`
|
||||
}
|
||||
|
||||
type moderatedUser struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
SuspendedAt *time.Time `json:"suspended_at"`
|
||||
Reason string `json:"suspended_reason,omitempty"`
|
||||
// Admin marks platform admins, who cannot be suspended or deleted.
|
||||
Admin bool `json:"admin,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) moderatedPages(ctx context.Context, search string, pg pageReq) ([]moderatedPage, pageInfo, error) {
|
||||
var rows []store.AdminListStatusPagesRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.AdminListStatusPages(ctx, store.AdminListStatusPagesParams{
|
||||
Search: truncate(strings.TrimSpace(search), 200), MaxRows: pg.fetch(),
|
||||
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(),
|
||||
})
|
||||
return err
|
||||
})
|
||||
rows, info := paginate(pg, rows, func(r store.AdminListStatusPagesRow) cursor { return cursor{T: r.CreatedAt, ID: r.ID} })
|
||||
out := make([]moderatedPage, len(rows))
|
||||
for i, r := range rows {
|
||||
p := &out[i]
|
||||
p.ID, p.Slug, p.Title, p.Published, p.SuspendedAt, p.Reason, p.CreatedAt = r.ID, r.Slug, r.Title, r.Published, r.SuspendedAt, r.SuspendedReason, r.CreatedAt
|
||||
if r.CustomDomain != nil && r.DomainVerifiedAt != nil {
|
||||
p.Domain = *r.CustomDomain
|
||||
}
|
||||
p.Org = moderatedOrg{r.OrgID, r.OrgSlug, r.OrgName, r.OrgSuspendedAt, r.OrgSuspendedReason}
|
||||
if r.OwnerID != uuid.Nil {
|
||||
p.Owner = &moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin}
|
||||
}
|
||||
}
|
||||
return out, info, err
|
||||
}
|
||||
|
||||
func (s *Server) adminListStatusPages(c *gin.Context) {
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pages, info, err := s.moderatedPages(c.Request.Context(), c.Query("q"), pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status_pages": pages, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
type suspensionRequest struct {
|
||||
Suspended bool `json:"suspended"`
|
||||
Reason string `json:"reason" binding:"max=500"`
|
||||
}
|
||||
|
||||
// suspension binds a suspension request and the target ID.
|
||||
func suspension(c *gin.Context) (uuid.UUID, suspensionRequest, bool) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return uuid.Nil, suspensionRequest{}, false
|
||||
}
|
||||
var req suspensionRequest
|
||||
if !bind(c, &req) {
|
||||
return uuid.Nil, req, false
|
||||
}
|
||||
req.Reason = strings.TrimSpace(req.Reason)
|
||||
auditDetail(c, "suspended", req.Suspended)
|
||||
if req.Reason != "" {
|
||||
auditDetail(c, "reason", req.Reason)
|
||||
}
|
||||
return id, req, true
|
||||
}
|
||||
|
||||
// moderated finishes a moderation request: 404 for unknown targets.
|
||||
func moderated(c *gin.Context, err error) bool {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) adminSuspendStatusPage(c *gin.Context) {
|
||||
id, req, ok := suspension(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SuspendStatusPage(ctx, store.SuspendStatusPageParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) adminDeleteStatusPage(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
page, err := q.GetStatusPage(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
auditDetail(c, "slug", page.Slug)
|
||||
_, err = q.DeleteStatusPage(ctx, id)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) adminSuspendOrg(c *gin.Context) {
|
||||
id, req, ok := suspension(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SuspendOrg(ctx, store.SuspendOrgParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
if !req.Suspended {
|
||||
return q.RestartHeartbeatWait(ctx, id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !moderated(c, err) {
|
||||
return
|
||||
}
|
||||
// Monitors leave or rejoin the schedule with its next reconciliation.
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) adminDeleteOrg(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
org, err := q.GetOrg(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
auditDetail(c, "slug", org.Slug)
|
||||
auditDetail(c, "name", org.Name)
|
||||
return purgeOrg(ctx, q, id)
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// moderatedUser loads the target account, refusing platform admins: they
|
||||
// would otherwise lock each other, or themselves, out.
|
||||
func (s *Server) moderatedUser(c *gin.Context) (store.User, bool) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return store.User{}, false
|
||||
}
|
||||
u, err := s.loadUser(c.Request.Context(), id)
|
||||
if !moderated(c, err) {
|
||||
return u, false
|
||||
}
|
||||
auditDetail(c, "email", u.Email)
|
||||
if u.IsAdmin {
|
||||
fail(c, http.StatusConflict, "target_is_admin")
|
||||
return u, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (s *Server) adminSuspendUser(c *gin.Context) {
|
||||
id, req, ok := suspension(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
u, ok := s.moderatedUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
_, err := q.SuspendUser(ctx, store.SuspendUserParams{ID: id, Suspend: req.Suspended, Reason: req.Reason})
|
||||
return err
|
||||
})
|
||||
if !moderated(c, err) {
|
||||
return
|
||||
}
|
||||
if req.Suspended {
|
||||
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) adminDeleteUser(c *gin.Context) {
|
||||
u, ok := s.moderatedUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if len(shared) > 0 {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.user_owns_shared_orgs"), "organizations": shared,
|
||||
})
|
||||
return
|
||||
}
|
||||
auditDetail(c, "organizations_deleted", orgsDeleted)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) moderationView(c *gin.Context, pg pageReq) (web.ModerationView, error) {
|
||||
pages, info, err := s.moderatedPages(c.Request.Context(), c.Query("q"), pg)
|
||||
v := web.ModerationView{Search: strings.TrimSpace(c.Query("q")), Pager: pager(c, info), Next: c.Request.URL.RequestURI()}
|
||||
state := func(at *time.Time, reason string) string {
|
||||
switch {
|
||||
case at == nil:
|
||||
return ""
|
||||
case reason == "":
|
||||
return "-"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
for _, p := range pages {
|
||||
u := strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
|
||||
if p.Domain != "" {
|
||||
u = "https://" + p.Domain + "/"
|
||||
}
|
||||
mp := web.ModeratedPage{
|
||||
ID: p.ID.String(), Title: p.Title, Slug: p.Slug, URL: u, Created: p.CreatedAt.Format(time.DateOnly),
|
||||
Published: p.Published, Suspended: state(p.SuspendedAt, p.Reason),
|
||||
Org: web.ModeratedTarget{ID: p.Org.ID.String(), Name: p.Org.Name, Detail: p.Org.Slug, Suspended: state(p.Org.SuspendedAt, p.Org.Reason)},
|
||||
}
|
||||
if p.Domain != "" {
|
||||
mp.Slug = p.Domain
|
||||
}
|
||||
if p.Owner != nil {
|
||||
mp.Owner = &web.ModeratedTarget{ID: p.Owner.ID.String(), Name: p.Owner.Email, Suspended: state(p.Owner.SuspendedAt, p.Owner.Reason), Admin: p.Owner.Admin}
|
||||
}
|
||||
v.Pages = append(v.Pages, mp)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const testPassword = "correct horse battery"
|
||||
|
||||
func TestModeration(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx := context.Background()
|
||||
admin := e.browser(t)
|
||||
admin.signup("admin@"+uniq("mod")+".test", uniq("mod-admin-"))
|
||||
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(ctx, admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ownerEmail := "owner@" + uniq("mod") + ".test"
|
||||
owner := e.browser(t)
|
||||
owner.signup(ownerEmail, uniq("mod-org-"))
|
||||
slug := uniq("acme-")
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "published": true})
|
||||
_, draft := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("draft-"), "title": "Draft", "published": false})
|
||||
_, hb := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600})
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
_, web := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Web", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{region}})
|
||||
scheduled := func() bool {
|
||||
var rows []store.ListEnabledMonitorsForScheduleRow
|
||||
_ = tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
|
||||
return err
|
||||
})
|
||||
for _, r := range rows {
|
||||
if r.ID.String() == web["id"] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
_, tok := owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
|
||||
api := &browser{t: t, base: owner.base, hc: e.srv.Client(), bearer: tok["token"].(string)}
|
||||
sp := e.statuspageClient(t, nil)
|
||||
served := func() bool {
|
||||
_, err := sp.Page(ctx, "", slug)
|
||||
if err != nil && !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
// Pings of paused monitors are answered, so cron jobs do not fail, but
|
||||
// not recorded.
|
||||
recorded := func() bool {
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+hb["target"].(string), "text/plain", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
return resp.StatusCode == http.StatusOK && !strings.Contains(string(b), "paused")
|
||||
}
|
||||
|
||||
// Only admins see the list; it holds published pages with their
|
||||
// organization and owner, and search narrows it.
|
||||
if st, _ := owner.do("GET", "/api/v1/admin/status-pages", nil); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin listing = %d", st)
|
||||
}
|
||||
_, list := admin.do("GET", "/api/v1/admin/status-pages?q="+slug, nil)
|
||||
raw := mustJSON(list)
|
||||
if !strings.Contains(raw, slug) || !strings.Contains(raw, ownerEmail) || strings.Contains(raw, draft["slug"].(string)) {
|
||||
t.Fatalf("list = %s", raw)
|
||||
}
|
||||
pg := list["status_pages"].([]any)[0].(map[string]any)
|
||||
orgID := pg["org"].(map[string]any)["id"].(string)
|
||||
userID := pg["owner"].(map[string]any)["id"].(string)
|
||||
if _, other := admin.do("GET", "/api/v1/admin/status-pages?q=no-such-page-"+slug, nil); len(other["status_pages"].([]any)) != 0 {
|
||||
t.Error("search does not narrow the list")
|
||||
}
|
||||
if !served() {
|
||||
t.Fatal("the page is not served before suspension")
|
||||
}
|
||||
|
||||
// A suspended page goes offline and its organization learns why.
|
||||
suspend := func(path string, on bool, reason string) {
|
||||
t.Helper()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/"+path+"/suspension", map[string]any{"suspended": on, "reason": reason}); st != http.StatusNoContent {
|
||||
t.Fatalf("suspend %s = %d %v", path, st, body)
|
||||
}
|
||||
}
|
||||
suspend("status-pages/"+page["id"].(string), true, "phishing")
|
||||
if served() {
|
||||
t.Error("a suspended page is served")
|
||||
}
|
||||
_, pages := owner.do("GET", "/api/v1/org/statuspages", nil)
|
||||
if raw := mustJSON(pages); !strings.Contains(raw, `"suspended":true`) || !strings.Contains(raw, `"suspended_reason":"phishing"`) {
|
||||
t.Errorf("the organization does not see the suspension: %s", raw)
|
||||
}
|
||||
if _, _, html := owner.page("/statuspages"); !strings.Contains(html, "suspended by the operator") {
|
||||
t.Error("the page list does not mark the suspension")
|
||||
}
|
||||
suspend("status-pages/"+page["id"].(string), false, "")
|
||||
if !served() {
|
||||
t.Error("a reinstated page is not served")
|
||||
}
|
||||
|
||||
// A suspended organization is locked out, checks and pages stop.
|
||||
suspend("orgs/"+orgID, true, "unpaid")
|
||||
st, body := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
expect(t, "member of a suspended org", st, body, http.StatusForbidden, "org_suspended")
|
||||
st, body = api.do("GET", "/api/v1/org/monitors", nil)
|
||||
expect(t, "token of a suspended org", st, body, http.StatusForbidden, "org_suspended")
|
||||
if served() {
|
||||
t.Error("a suspended organization's page is served")
|
||||
}
|
||||
if recorded() {
|
||||
t.Error("a heartbeat of a suspended org is recorded")
|
||||
}
|
||||
if scheduled() {
|
||||
t.Error("monitors of a suspended org are scheduled")
|
||||
}
|
||||
if _, _, html := owner.page("/"); !strings.Contains(html, "The operator suspended this organization") || !strings.Contains(html, "unpaid") {
|
||||
t.Error("the console does not explain the suspension")
|
||||
}
|
||||
suspend("orgs/"+orgID, false, "")
|
||||
if st, _ := owner.do("GET", "/api/v1/org/monitors", nil); st != http.StatusOK || !scheduled() {
|
||||
t.Errorf("member of a reinstated org = %d, scheduled = %v", st, scheduled())
|
||||
}
|
||||
if !recorded() {
|
||||
t.Error("a heartbeat after reinstatement is not recorded")
|
||||
}
|
||||
|
||||
// A suspended account is signed out and kept out, tokens included.
|
||||
suspend("users/"+userID, true, "")
|
||||
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
|
||||
t.Errorf("session of a suspended account = %d", st)
|
||||
}
|
||||
if st, _ := api.do("GET", "/api/v1/org/monitors", nil); st != http.StatusUnauthorized {
|
||||
t.Errorf("token of a suspended account = %d", st)
|
||||
}
|
||||
fresh := e.browser(t)
|
||||
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword})
|
||||
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended")
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": "wrong password"}); st != http.StatusUnauthorized {
|
||||
t.Error("a wrong password reveals the suspension")
|
||||
}
|
||||
suspend("users/"+userID, false, "")
|
||||
if st, _ := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
|
||||
t.Errorf("sign-in after reinstatement = %d", st)
|
||||
}
|
||||
|
||||
// Admins are out of reach, also for themselves.
|
||||
st, body = admin.do("PUT", "/api/v1/admin/users/"+admin.userIDSelf().String()+"/suspension", map[string]any{"suspended": true})
|
||||
expect(t, "suspend an admin", st, body, http.StatusConflict, "target_is_admin")
|
||||
st, body = admin.do("DELETE", "/api/v1/admin/users/"+admin.userIDSelf().String(), nil)
|
||||
expect(t, "delete an admin", st, body, http.StatusConflict, "target_is_admin")
|
||||
|
||||
// An owner of a shared organization cannot be deleted before it.
|
||||
fresh.do("POST", "/api/v1/me/org", map[string]any{"org_id": orgID})
|
||||
e.joinVia(t, fresh.invite("m@"+uniq("mod")+".test", fresh.roleID("viewer")))
|
||||
st, body = admin.do("DELETE", "/api/v1/admin/users/"+userID, nil)
|
||||
expect(t, "delete the owner of a shared org", st, body, http.StatusConflict, "owns_shared_orgs")
|
||||
|
||||
// Deleting: page, organization, account.
|
||||
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
|
||||
t.Errorf("delete page = %d", st)
|
||||
}
|
||||
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNoContent {
|
||||
t.Errorf("delete org = %d", st)
|
||||
}
|
||||
if st, body := admin.do("DELETE", "/api/v1/admin/users/"+userID, nil); st != http.StatusNoContent {
|
||||
t.Errorf("delete account = %d %v", st, body)
|
||||
}
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusUnauthorized {
|
||||
t.Error("the deleted account can still sign in")
|
||||
}
|
||||
if st, _ := admin.do("DELETE", "/api/v1/admin/orgs/"+orgID, nil); st != http.StatusNotFound {
|
||||
t.Error("deleting a deleted org is not 404")
|
||||
}
|
||||
|
||||
// The admin page shows the list.
|
||||
if _, _, html := admin.page("/admin/status-pages"); !strings.Contains(html, `id="moderation"`) {
|
||||
t.Error("the admin page lacks the status page list")
|
||||
}
|
||||
}
|
||||
+268
-24
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
@@ -20,17 +21,27 @@ import (
|
||||
)
|
||||
|
||||
type monitorRequest struct {
|
||||
Name string `json:"name" binding:"required,max=200"`
|
||||
Type string `json:"type" binding:"required"`
|
||||
Target string `json:"target" binding:"required,max=2000"`
|
||||
Name string `json:"name" binding:"required,max=200"`
|
||||
Type string `json:"type" binding:"required"`
|
||||
// Target is ignored for heartbeat monitors, whose target is their
|
||||
// generated ping token.
|
||||
Target string `json:"target" binding:"max=2000"`
|
||||
IntervalSeconds int `json:"interval_seconds" binding:"required"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Regions []uuid.UUID `json:"regions" binding:"required,min=1,max=50"`
|
||||
Regions []uuid.UUID `json:"regions" binding:"max=50"`
|
||||
// Confirmations is how many failures in a row make a region count as
|
||||
// down; 0 keeps the default of 2.
|
||||
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
|
||||
// platform marks the platform regions among those visible, filled by
|
||||
// validateMonitor.
|
||||
platform map[uuid.UUID]bool
|
||||
// GroupID places the monitor in a group; nil keeps it at the top level.
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
// AlertGroupIDs defaults on creation and preserves assignments on update
|
||||
// when omitted. An explicit empty list disables notifications.
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids" binding:"max=100"`
|
||||
}
|
||||
|
||||
type latestView struct {
|
||||
@@ -43,6 +54,7 @@ type latestView struct {
|
||||
}
|
||||
|
||||
type monitorView struct {
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
@@ -52,14 +64,30 @@ type monitorView struct {
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Confirmations int32 `json:"confirmations"`
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
Regions []uuid.UUID `json:"regions"`
|
||||
Latest []latestView `json:"latest"`
|
||||
// PingURL is where heartbeat monitors are pinged.
|
||||
PingURL string `json:"ping_url,omitempty"`
|
||||
// SecretsSet names secret settings that are set; their values are
|
||||
// never returned.
|
||||
SecretsSet []string `json:"secrets_set,omitempty"`
|
||||
}
|
||||
|
||||
// withPingURL adds the ping URL of heartbeat monitors.
|
||||
func (s *Server) withPingURL(v monitorView) monitorView {
|
||||
if check.Type(v.Type) == check.Heartbeat && v.Target != "" {
|
||||
v.PingURL = s.pingURL(v.Target)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView {
|
||||
cfg, secrets := publicMonitorConfig(m.Config)
|
||||
return monitorView{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, Regions: regions, Latest: []latestView{},
|
||||
TimeoutMS: m.TimeoutMs, Config: cfg, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{},
|
||||
SecretsSet: secrets,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,8 +100,19 @@ func (s *Server) minInterval() int {
|
||||
}
|
||||
|
||||
// validateMonitor normalizes req and writes an error response if it is not
|
||||
// acceptable.
|
||||
func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
// acceptable, including when the principal may not write monitors in the
|
||||
// requested group.
|
||||
func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTree) bool {
|
||||
if req.GroupID != nil {
|
||||
if _, ok := t.byID[*req.GroupID]; !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !canInGroup(current(c), authz.MonitorsWrite, t, req.GroupID) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return false
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
req.Target = strings.TrimSpace(req.Target)
|
||||
if req.Name == "" {
|
||||
@@ -84,6 +123,21 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval())
|
||||
return false
|
||||
}
|
||||
heartbeat := check.Passive(check.Type(req.Type))
|
||||
if heartbeat {
|
||||
// Pings arrive from one place, so one late ping is an outage, and
|
||||
// there is neither a target nor a timeout to check against.
|
||||
req.Target, req.Regions = "", nil
|
||||
if req.Confirmations == 0 {
|
||||
req.Confirmations = 1
|
||||
}
|
||||
if req.TimeoutMS == 0 {
|
||||
req.TimeoutMS = 1000
|
||||
}
|
||||
} else if len(req.Regions) == 0 {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region")
|
||||
return false
|
||||
}
|
||||
if req.Confirmations == 0 {
|
||||
req.Confirmations = 2
|
||||
}
|
||||
@@ -118,6 +172,10 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
req.platform = map[uuid.UUID]bool{}
|
||||
for _, k := range known {
|
||||
req.platform[k.ID] = k.OrgID == nil
|
||||
}
|
||||
for _, r := range req.Regions {
|
||||
// Row-level security limits known to the org's own and the
|
||||
// platform regions.
|
||||
@@ -129,15 +187,39 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// listMonitors returns the monitors the principal may read, org-wide or
|
||||
// through a group assignment.
|
||||
func (s *Server) listMonitors(c *gin.Context) {
|
||||
pg, ok := parsePage(c, apiPageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var out []monitorView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
monitors, err := q.ListMonitors(ctx)
|
||||
var info pageInfo
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := []monitorView{}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
monitors, err := q.ListMonitorsPage(ctx, store.ListMonitorsPageParams{
|
||||
AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Paged before filtering by permission: a page may hold fewer.
|
||||
monitors, info = paginate(pg, monitors, func(m store.Monitor) cursor { return cursor{S: m.Name, ID: m.ID} })
|
||||
assignments, err := q.AllMonitorAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
alertGroups := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, a := range assignments {
|
||||
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regions, err := q.AllMonitorRegions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -156,12 +238,23 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
Region: l.Region, Time: l.Time, OK: l.Ok, LatencyMS: l.LatencyMs, StatusCode: l.StatusCode, Error: l.Error,
|
||||
})
|
||||
}
|
||||
out = make([]monitorView, len(monitors))
|
||||
for i, m := range monitors {
|
||||
out[i] = viewMonitor(m, byMonitor[m.ID])
|
||||
if l := latestBy[m.ID]; l != nil {
|
||||
out[i].Latest = l
|
||||
for _, m := range monitors {
|
||||
if !canInGroup(p, authz.MonitorsRead, t, m.GroupID) {
|
||||
continue
|
||||
}
|
||||
v := viewMonitor(m, byMonitor[m.ID])
|
||||
v.AlertGroupIDs = alertGroups[m.ID]
|
||||
if v.AlertGroupIDs == nil {
|
||||
v.AlertGroupIDs = []uuid.UUID{}
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
|
||||
v = redactMonitor(v)
|
||||
}
|
||||
v = s.withPingURL(v)
|
||||
if l := latestBy[m.ID]; l != nil {
|
||||
v.Latest = l
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
@@ -169,29 +262,65 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"monitors": out})
|
||||
c.JSON(http.StatusOK, gin.H{"monitors": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
||||
}
|
||||
|
||||
func (s *Server) createMonitor(c *gin.Context) {
|
||||
var req monitorRequest
|
||||
if !bind(c, &req) || !s.validateMonitor(c, &req) {
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !s.validateMonitor(c, &req, t) {
|
||||
return
|
||||
}
|
||||
if !s.offered(ctx, p.Org, req.Type) {
|
||||
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
return
|
||||
}
|
||||
req.Target = passiveTarget(check.Type(req.Type), req.Target)
|
||||
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
|
||||
limits := s.orgLimits(ctx, p.Org)
|
||||
if err := checkRegions(limits, req.Regions, nil, req.platform); failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
var m store.Monitor
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if err := reserve(ctx, q, p.Org.ID, limits.Monitors, "monitor_limit", q.CountMonitors); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
GroupID: req.GroupID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setRegions(ctx, q, m, req.Regions)
|
||||
})
|
||||
if errors.Is(err, errInvalidAlertGroup) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
return
|
||||
}
|
||||
if failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -200,7 +329,9 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, viewMonitor(m, req.Regions))
|
||||
v := viewMonitor(m, req.Regions)
|
||||
v.AlertGroupIDs = req.AlertGroupIDs
|
||||
c.JSON(http.StatusCreated, s.withPingURL(v))
|
||||
}
|
||||
|
||||
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []uuid.UUID) error {
|
||||
@@ -241,31 +372,85 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
var req monitorRequest
|
||||
if !bind(c, &req) || !s.validateMonitor(c, &req) {
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !s.validateMonitor(c, &req, t) {
|
||||
return
|
||||
}
|
||||
var (
|
||||
m store.Monitor
|
||||
previous []uuid.UUID
|
||||
denied bool
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
old, err := q.GetMonitor(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Moving out of a group needs write access where it was, too.
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, old.GroupID) {
|
||||
denied = true
|
||||
return nil
|
||||
}
|
||||
if previous, err = q.MonitorRegions(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Type != req.Type && !s.offered(ctx, p.Org, req.Type) {
|
||||
return errCheckTypeDisabled
|
||||
}
|
||||
if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Type == req.Type {
|
||||
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, old.Config)
|
||||
} else {
|
||||
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
|
||||
}
|
||||
if check.Passive(check.Type(req.Type)) {
|
||||
// The ping URL stays the same across edits.
|
||||
req.Target = old.Target
|
||||
if old.Type != req.Type {
|
||||
req.Target = passiveTarget(check.Type(req.Type), "")
|
||||
}
|
||||
}
|
||||
m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{
|
||||
ID: id, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
GroupID: req.GroupID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setRegions(ctx, q, m, req.Regions)
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if errors.Is(err, errInvalidAlertGroup) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errCheckTypeDisabled) {
|
||||
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
return
|
||||
}
|
||||
if failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && denied) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
@@ -277,7 +462,9 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, viewMonitor(m, req.Regions))
|
||||
v := viewMonitor(m, req.Regions)
|
||||
v.AlertGroupIDs = req.AlertGroupIDs
|
||||
c.JSON(http.StatusOK, s.withPingURL(v))
|
||||
}
|
||||
|
||||
func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
@@ -288,12 +475,26 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var (
|
||||
regions []uuid.UUID
|
||||
n int64
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
old, err := q.GetMonitor(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, old.GroupID) {
|
||||
return nil
|
||||
}
|
||||
if regions, err = q.MonitorRegions(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -369,3 +570,46 @@ func (s *Server) reconcile(ctx context.Context) {
|
||||
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// redactMonitor hides what only editors may see: the ping token of a
|
||||
// heartbeat, which can report the job healthy, and request header values,
|
||||
// which typically carry credentials.
|
||||
func redactMonitor(v monitorView) monitorView {
|
||||
if check.Passive(check.Type(v.Type)) {
|
||||
v.Target = ""
|
||||
}
|
||||
var cfg map[string]any
|
||||
if json.Unmarshal(v.Config, &cfg) != nil {
|
||||
return v
|
||||
}
|
||||
if h, ok := cfg["headers"].(map[string]any); ok {
|
||||
for k := range h {
|
||||
h[k] = "redacted"
|
||||
}
|
||||
v.Config, _ = json.Marshal(cfg)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// passiveTarget fills the target of monitors that are reported to us:
|
||||
// heartbeats get their secret ping token; alertmanager monitors, matched by
|
||||
// labels, a fixed placeholder.
|
||||
func passiveTarget(t check.Type, target string) string {
|
||||
switch t {
|
||||
case check.Heartbeat:
|
||||
return newPingToken()
|
||||
case check.Alertmanager:
|
||||
return alertmanagerRegion
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// passiveRegion is the pseudo-region results of passive monitors carry.
|
||||
func passiveRegion(t check.Type) string {
|
||||
if t == check.Alertmanager {
|
||||
return alertmanagerRegion
|
||||
}
|
||||
return heartbeatRegion
|
||||
}
|
||||
|
||||
var errCheckTypeDisabled = errors.New("api: check type switched off")
|
||||
@@ -0,0 +1,98 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
)
|
||||
|
||||
// Monitor settings listed by check.SecretFields, such as database
|
||||
// passwords, are stored as "sealed_<field>": encrypted and bound to the
|
||||
// monitor type and field. They are never returned; checkers get them in
|
||||
// plain text with their jobs.
|
||||
|
||||
const sealedPrefix = "sealed_"
|
||||
|
||||
func monitorSecretAAD(t check.Type, field string) []byte {
|
||||
return []byte("monitor:" + string(t) + ":" + field)
|
||||
}
|
||||
|
||||
// sealMonitorConfig replaces secret settings in cfg by their sealed form.
|
||||
// A secret left empty keeps its value from previous, so forms need not ask
|
||||
// for passwords again.
|
||||
func (s *Server) sealMonitorConfig(t check.Type, cfg, previous []byte) []byte {
|
||||
fields := check.SecretFields(t)
|
||||
if len(fields) == 0 {
|
||||
return cfg
|
||||
}
|
||||
var m, old map[string]any
|
||||
if json.Unmarshal(cfg, &m) != nil {
|
||||
return cfg
|
||||
}
|
||||
_ = json.Unmarshal(previous, &old)
|
||||
for _, f := range fields {
|
||||
v, _ := m[f].(string)
|
||||
delete(m, f)
|
||||
switch {
|
||||
case v != "":
|
||||
m[sealedPrefix+f] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), monitorSecretAAD(t, f)))
|
||||
case old[sealedPrefix+f] != nil:
|
||||
m[sealedPrefix+f] = old[sealedPrefix+f]
|
||||
}
|
||||
}
|
||||
out, _ := json.Marshal(m)
|
||||
return out
|
||||
}
|
||||
|
||||
// openMonitorConfig restores secret settings for a checker.
|
||||
func (s *Server) openMonitorConfig(t check.Type, cfg []byte) ([]byte, error) {
|
||||
fields := check.SecretFields(t)
|
||||
if len(fields) == 0 {
|
||||
return cfg, nil
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(cfg, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, f := range fields {
|
||||
sealed, ok := m[sealedPrefix+f].(string)
|
||||
delete(m, sealedPrefix+f)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(sealed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plain, err := s.keys.Open(raw, monitorSecretAAD(t, f))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[f] = string(plain)
|
||||
}
|
||||
return json.Marshal(m)
|
||||
}
|
||||
|
||||
// publicMonitorConfig drops sealed secrets from cfg and names those set.
|
||||
func publicMonitorConfig(cfg []byte) ([]byte, []string) {
|
||||
var m map[string]any
|
||||
if json.Unmarshal(cfg, &m) != nil {
|
||||
return cfg, nil
|
||||
}
|
||||
var set []string
|
||||
for k := range m {
|
||||
if f, ok := strings.CutPrefix(k, sealedPrefix); ok {
|
||||
set = append(set, f)
|
||||
delete(m, k)
|
||||
}
|
||||
}
|
||||
if set == nil {
|
||||
return cfg, nil
|
||||
}
|
||||
slices.Sort(set)
|
||||
out, _ := json.Marshal(m)
|
||||
return out, set
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"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/web"
|
||||
)
|
||||
|
||||
// The OpenAPI document is generated from the endpoint table in apidocs.go
|
||||
// and the Go types the handlers bind and return, so field names, types and
|
||||
// validation limits cannot drift from the code. A test fails for routes
|
||||
// missing from the table.
|
||||
|
||||
// obj describes an inline JSON object, e.g. obj{"monitors": []monitorView{}}.
|
||||
type obj map[string]any
|
||||
|
||||
// endpoint documents one route.
|
||||
type endpoint struct {
|
||||
method, path string
|
||||
tag, summary string
|
||||
// description adds detail beyond the summary.
|
||||
description string
|
||||
// perm is the permission required, in the words of the API.
|
||||
perm string
|
||||
// sessionOnly marks routes API tokens may not use.
|
||||
sessionOnly bool
|
||||
public bool
|
||||
// req is the request body; nil for none.
|
||||
req any
|
||||
// status and resp describe the success response; resp nil means no
|
||||
// body. media overrides application/json.
|
||||
status int
|
||||
resp any
|
||||
media string
|
||||
}
|
||||
|
||||
// schemaBuilder turns Go types into JSON Schema, collecting named structs as
|
||||
// components.
|
||||
type schemaBuilder struct {
|
||||
components map[string]any
|
||||
}
|
||||
|
||||
func (b *schemaBuilder) schema(t reflect.Type) map[string]any {
|
||||
switch t {
|
||||
case uuidType:
|
||||
return map[string]any{"type": "string", "format": "uuid"}
|
||||
case timeType:
|
||||
return map[string]any{"type": "string", "format": "date-time"}
|
||||
case rawType:
|
||||
return map[string]any{"description": "Any JSON value."}
|
||||
}
|
||||
switch t.Kind() {
|
||||
case reflect.Pointer:
|
||||
s := b.schema(t.Elem())
|
||||
if typ, ok := s["type"].(string); ok {
|
||||
s["type"] = []string{typ, "null"}
|
||||
return s
|
||||
}
|
||||
return map[string]any{"oneOf": []any{s, map[string]any{"type": "null"}}}
|
||||
case reflect.String:
|
||||
return map[string]any{"type": "string"}
|
||||
case reflect.Bool:
|
||||
return map[string]any{"type": "boolean"}
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return map[string]any{"type": "integer"}
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return map[string]any{"type": "number"}
|
||||
case reflect.Slice, reflect.Array:
|
||||
if t.Elem().Kind() == reflect.Uint8 {
|
||||
return map[string]any{"type": "string", "contentEncoding": "base64"}
|
||||
}
|
||||
return map[string]any{"type": "array", "items": b.schema(t.Elem())}
|
||||
case reflect.Map:
|
||||
return map[string]any{"type": "object", "additionalProperties": b.schema(t.Elem())}
|
||||
case reflect.Interface:
|
||||
return map[string]any{}
|
||||
case reflect.Struct:
|
||||
name := componentName(t)
|
||||
if name == "" {
|
||||
return b.object(t)
|
||||
}
|
||||
if _, done := b.components[name]; !done {
|
||||
b.components[name] = nil // breaks recursion
|
||||
b.components[name] = b.object(t)
|
||||
}
|
||||
return map[string]any{"$ref": "#/components/schemas/" + name}
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
// object builds the schema of a struct from its json and binding tags.
|
||||
func (b *schemaBuilder) object(t reflect.Type) map[string]any {
|
||||
props := map[string]any{}
|
||||
var required []string
|
||||
var walk func(t reflect.Type)
|
||||
walk = func(t reflect.Type) {
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
tag := f.Tag.Get("json")
|
||||
name, opts, _ := strings.Cut(tag, ",")
|
||||
if name == "-" {
|
||||
continue
|
||||
}
|
||||
if f.Anonymous && name == "" {
|
||||
walk(f.Type)
|
||||
continue
|
||||
}
|
||||
if name == "" {
|
||||
name = f.Name
|
||||
}
|
||||
s := b.schema(f.Type)
|
||||
binding := strings.Split(f.Tag.Get("binding"), ",")
|
||||
applyBinding(s, f.Type, binding)
|
||||
props[name] = s
|
||||
if slices.Contains(binding, "required") && !strings.Contains(opts, "omitempty") {
|
||||
required = append(required, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(t)
|
||||
s := map[string]any{"type": "object", "properties": props}
|
||||
if len(required) > 0 {
|
||||
slices.Sort(required)
|
||||
s["required"] = required
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// applyBinding carries validator limits over to the schema.
|
||||
func applyBinding(s map[string]any, t reflect.Type, rules []string) {
|
||||
for t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
for _, r := range rules {
|
||||
key, val, ok := strings.Cut(r, "=")
|
||||
if r == "email" {
|
||||
s["format"] = "email"
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.Atoi(val)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var bound string
|
||||
switch t.Kind() {
|
||||
case reflect.String:
|
||||
bound = map[string]string{"max": "maxLength", "min": "minLength"}[key]
|
||||
case reflect.Slice, reflect.Map:
|
||||
bound = map[string]string{"max": "maxItems", "min": "minItems"}[key]
|
||||
default:
|
||||
bound = map[string]string{"max": "maximum", "min": "minimum"}[key]
|
||||
}
|
||||
if bound != "" {
|
||||
s[bound] = n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// componentName derives a schema name from a Go type: monitorView becomes
|
||||
// Monitor, monitorRequest MonitorRequest. Types of other packages keep their
|
||||
// package as prefix to stay unique.
|
||||
func componentName(t reflect.Type) string {
|
||||
name := t.Name()
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
name = strings.TrimSuffix(name, "View")
|
||||
r := []rune(name)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
name = string(r)
|
||||
if pkg := t.PkgPath(); !strings.HasSuffix(pkg, "/internal/api") {
|
||||
p := []rune(pkg[strings.LastIndex(pkg, "/")+1:])
|
||||
p[0] = unicode.ToUpper(p[0])
|
||||
name = string(p) + name
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// bodySchema describes a request or response value.
|
||||
func (b *schemaBuilder) bodySchema(v any) map[string]any {
|
||||
if o, ok := v.(obj); ok {
|
||||
props := map[string]any{}
|
||||
keys := make([]string, 0, len(o))
|
||||
for k, val := range o {
|
||||
props[k] = b.schema(reflect.TypeOf(val))
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
return map[string]any{"type": "object", "properties": props, "required": keys}
|
||||
}
|
||||
return b.schema(reflect.TypeOf(v))
|
||||
}
|
||||
|
||||
// openAPIPath turns gin's ":id" parameters into "{id}".
|
||||
func openAPIPath(p string) (string, []string) {
|
||||
var params []string
|
||||
parts := strings.Split(p, "/")
|
||||
for i, part := range parts {
|
||||
if strings.HasPrefix(part, ":") {
|
||||
params = append(params, part[1:])
|
||||
parts[i] = "{" + part[1:] + "}"
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "/"), params
|
||||
}
|
||||
|
||||
// buildOpenAPI assembles the document for publicURL.
|
||||
func buildOpenAPI(publicURL string) map[string]any {
|
||||
b := &schemaBuilder{components: map[string]any{}}
|
||||
errorRef := map[string]any{"$ref": "#/components/schemas/Error"}
|
||||
b.components["Error"] = map[string]any{
|
||||
"type": "object",
|
||||
"required": []string{"error", "message"},
|
||||
"properties": map[string]any{
|
||||
"error": map[string]any{"type": "string", "description": "Stable code for programs, e.g. invalid_target."},
|
||||
"message": map[string]any{"type": "string", "description": "Explanation in the request's language."},
|
||||
"request_id": map[string]any{"type": "string", "description": "Quote it when reporting a problem."},
|
||||
},
|
||||
}
|
||||
// Monitor settings travel as untyped config; their shapes per type.
|
||||
for _, c := range []any{check.HTTPConfig{}, check.JSONConfig{}, check.PrometheusConfig{}, check.DNSConfig{}, check.TLSConfig{}, check.DBConfig{}, check.BrokerConfig{}, check.GRPCConfig{}, check.SMTPConfig{}, check.RADIUSConfig{}, check.SNMPConfig{}, check.GameConfig{}, check.DockerConfig{}, check.HeartbeatConfig{}, check.AlertmanagerConfig{}} {
|
||||
b.schema(reflect.TypeOf(c))
|
||||
}
|
||||
paths := map[string]map[string]any{}
|
||||
tags := []string{}
|
||||
for _, e := range endpoints {
|
||||
p, params := openAPIPath(e.path)
|
||||
op := map[string]any{"summary": e.summary, "tags": []string{e.tag}, "operationId": operationID(e)}
|
||||
desc := e.description
|
||||
if e.perm != "" {
|
||||
desc = strings.TrimSpace(desc + "\n\nRequires the permission `" + e.perm + "`.")
|
||||
}
|
||||
if e.sessionOnly {
|
||||
desc = strings.TrimSpace(desc + "\n\nOnly in a browser session, not with an API token.")
|
||||
}
|
||||
if desc != "" {
|
||||
op["description"] = desc
|
||||
}
|
||||
if e.public {
|
||||
op["security"] = []any{}
|
||||
} else if e.sessionOnly {
|
||||
op["security"] = []any{map[string]any{"session": []string{}}}
|
||||
}
|
||||
var ps []any
|
||||
for _, name := range params {
|
||||
ps = append(ps, map[string]any{"name": name, "in": "path", "required": true, "schema": map[string]any{"type": "string"}})
|
||||
}
|
||||
if ps != nil {
|
||||
op["parameters"] = ps
|
||||
}
|
||||
if e.req != nil {
|
||||
op["requestBody"] = map[string]any{"required": true, "content": map[string]any{
|
||||
"application/json": map[string]any{"schema": b.bodySchema(e.req)},
|
||||
}}
|
||||
}
|
||||
status := e.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
success := map[string]any{"description": http.StatusText(status)}
|
||||
switch {
|
||||
case e.media != "":
|
||||
success["content"] = map[string]any{e.media: map[string]any{}}
|
||||
case e.resp != nil:
|
||||
success["content"] = map[string]any{"application/json": map[string]any{"schema": b.bodySchema(e.resp)}}
|
||||
}
|
||||
op["responses"] = map[string]any{
|
||||
strconv.Itoa(status): success,
|
||||
"default": map[string]any{"description": "Error", "content": map[string]any{"application/json": map[string]any{"schema": errorRef}}},
|
||||
}
|
||||
if paths[p] == nil {
|
||||
paths[p] = map[string]any{}
|
||||
}
|
||||
paths[p][strings.ToLower(e.method)] = op
|
||||
if !slices.Contains(tags, e.tag) {
|
||||
tags = append(tags, e.tag)
|
||||
}
|
||||
}
|
||||
tagObjs := make([]any, len(tags))
|
||||
for i, t := range tags {
|
||||
tagObjs[i] = map[string]any{"name": t}
|
||||
}
|
||||
return map[string]any{
|
||||
"openapi": "3.1.0",
|
||||
"info": map[string]any{
|
||||
"title": "UptimeSebi API",
|
||||
"version": buildinfo.Version,
|
||||
"description": "Manage monitors, status pages, alerting and members of an organization.\n\n" +
|
||||
"Authenticate with an API token as `Authorization: Bearer ust_…` (create one under Settings → API tokens; " +
|
||||
"it never exceeds its owner's permissions), or use the browser session, which additionally needs the " +
|
||||
"`" + auth.CSRFHeader + "` header on changes. Errors share one format with a stable `error` code.\n\n" +
|
||||
"Lists marked as paged return at most 100 items (`limit` takes up to 500) with `next_cursor` and " +
|
||||
"`prev_cursor`; pass one as `after` or `before` to get the next or previous page. A missing cursor " +
|
||||
"means the list ends there. Cursors are opaque and stay valid while items are added.",
|
||||
"license": map[string]any{"name": "AGPL-3.0-only", "identifier": "AGPL-3.0-only"},
|
||||
},
|
||||
"servers": []any{map[string]any{"url": strings.TrimSuffix(publicURL, "/")}},
|
||||
"security": []any{
|
||||
map[string]any{"token": []string{}},
|
||||
map[string]any{"session": []string{}},
|
||||
},
|
||||
"tags": tagObjs,
|
||||
"paths": paths,
|
||||
"components": map[string]any{
|
||||
"schemas": b.components,
|
||||
"securitySchemes": map[string]any{
|
||||
"token": map[string]any{"type": "http", "scheme": "bearer", "description": "API token, prefix ust_."},
|
||||
"session": map[string]any{"type": "apiKey", "in": "cookie", "name": auth.CookieName},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func operationID(e endpoint) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(strings.ToLower(e.method))
|
||||
for _, part := range strings.Split(strings.TrimPrefix(e.path, "/api/v1/"), "/") {
|
||||
part = strings.TrimPrefix(part, ":")
|
||||
for _, w := range strings.FieldsFunc(part, func(r rune) bool { return r == '-' || r == '_' }) {
|
||||
r := []rune(w)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
b.WriteString(string(r))
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
var (
|
||||
openAPIOnce sync.Once
|
||||
openAPIDoc []byte
|
||||
)
|
||||
|
||||
func (s *Server) openAPIJSON(c *gin.Context) {
|
||||
openAPIOnce.Do(func() {
|
||||
openAPIDoc, _ = json.MarshalIndent(buildOpenAPI(s.cfg.PublicURL), "", " ")
|
||||
})
|
||||
c.Header("Cache-Control", "public, max-age=300")
|
||||
c.Data(http.StatusOK, "application/json", openAPIDoc)
|
||||
}
|
||||
|
||||
func (s *Server) apiDocsPage(c *gin.Context) {
|
||||
web.Render(c, http.StatusOK, web.APIDocsPage(s.pageFor(c, "apidocs.title")))
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
func TestEveryRouteIsDocumented(t *testing.T) {
|
||||
r := gin.New()
|
||||
api.New(config.API{}, api.Deps{Log: slog.New(slog.DiscardHandler)}).Mount(r)
|
||||
documented := api.DocumentedRoutes()
|
||||
var served []string
|
||||
for _, rt := range r.Routes() {
|
||||
if strings.HasPrefix(rt.Path, "/api/v1/") {
|
||||
served = append(served, rt.Method+" "+rt.Path)
|
||||
}
|
||||
}
|
||||
for _, s := range served {
|
||||
if !slices.Contains(documented, s) {
|
||||
t.Errorf("%s is not documented in apidocs.go", s)
|
||||
}
|
||||
}
|
||||
for _, d := range documented {
|
||||
if !slices.Contains(served, d) {
|
||||
t.Errorf("%s is documented but not served", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAPIDocument(t *testing.T) {
|
||||
doc := api.OpenAPI()
|
||||
raw, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var generic map[string]any
|
||||
_ = json.Unmarshal(raw, &generic)
|
||||
schemas := generic["components"].(map[string]any)["schemas"].(map[string]any)
|
||||
|
||||
// Every reference resolves and every required field exists.
|
||||
var walk func(v any)
|
||||
walk = func(v any) {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
if ref, ok := x["$ref"].(string); ok {
|
||||
if _, ok := schemas[strings.TrimPrefix(ref, "#/components/schemas/")]; !ok {
|
||||
t.Errorf("unresolved %s", ref)
|
||||
}
|
||||
}
|
||||
if req, ok := x["required"].([]any); ok {
|
||||
if props, ok := x["properties"].(map[string]any); ok {
|
||||
for _, r := range req {
|
||||
if _, ok := props[r.(string)]; !ok {
|
||||
t.Errorf("required %v is not a property", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range x {
|
||||
walk(child)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(generic)
|
||||
|
||||
// Limits come from the binding tags the API validates with.
|
||||
mr := schemas["MonitorRequest"].(map[string]any)
|
||||
name := mr["properties"].(map[string]any)["name"].(map[string]any)
|
||||
if name["maxLength"] != float64(200) || !slices.Contains(mr["required"].([]any), any("name")) {
|
||||
t.Errorf("MonitorRequest.name = %v, required %v", name, mr["required"])
|
||||
}
|
||||
if _, ok := schemas["Monitor"].(map[string]any)["properties"].(map[string]any)["ping_url"]; !ok {
|
||||
t.Error("Monitor lacks ping_url")
|
||||
}
|
||||
for _, s := range []string{"CheckHTTPConfig", "CheckJSONConfig", "CheckPrometheusConfig", "Error"} {
|
||||
if _, ok := schemas[s]; !ok {
|
||||
t.Errorf("schema %s missing", s)
|
||||
}
|
||||
}
|
||||
paths := generic["paths"].(map[string]any)
|
||||
put := paths["/api/v1/org/monitors/{id}"].(map[string]any)["put"].(map[string]any)
|
||||
if params := put["parameters"].([]any); len(params) != 1 || params[0].(map[string]any)["name"] != "id" {
|
||||
t.Errorf("path parameters = %v", put["parameters"])
|
||||
}
|
||||
if login := paths["/api/v1/auth/login"].(map[string]any)["post"].(map[string]any); len(login["security"].([]any)) != 0 {
|
||||
t.Error("login is not marked public")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIDocsServed(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
resp, err := e.srv.Client().Get(e.srv.URL + "/api/openapi.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), `"openapi": "3.1.0"`) || !strings.Contains(string(body), e.srv.URL) {
|
||||
t.Errorf("openapi.json = %d %.200s", resp.StatusCode, body)
|
||||
}
|
||||
if st, _, page := e.browser(t).page("/api/docs"); st != http.StatusOK || !strings.Contains(page, "swagger-ui-bundle.js") {
|
||||
t.Errorf("/api/docs = %d", st)
|
||||
}
|
||||
// Every page carries the favicons, which ship in the embedded /static.
|
||||
for _, path := range []string{"/brand/favicon.svg", "/brand/favicon-32.png", "/brand/apple-touch-icon.png", "/brand/site.webmanifest"} {
|
||||
f, err := web.Static().Open(path)
|
||||
if err != nil {
|
||||
t.Errorf("static %s: %v", path, err)
|
||||
continue
|
||||
}
|
||||
_ = f.Close()
|
||||
}
|
||||
if _, _, login := e.browser(t).page("/login"); !strings.Contains(login, `href="/static/brand/favicon.svg"`) {
|
||||
t.Error("the login page lacks the favicon")
|
||||
}
|
||||
// Linked from every console page and where tokens are created.
|
||||
if _, _, login := e.browser(t).page("/login"); !strings.Contains(login, `href="/api/docs"`) {
|
||||
t.Error("the footer does not link the API documentation")
|
||||
}
|
||||
b := e.browser(t)
|
||||
b.signup("d@"+uniq("ad")+".test", uniq("ad-"))
|
||||
if _, _, tokens := b.page("/settings/tokens"); !strings.Contains(tokens, `href="/api/docs"`) || !strings.Contains(tokens, "Authorization: Bearer") {
|
||||
t.Error("the token page does not explain usage with a link to the API documentation")
|
||||
}
|
||||
}
|
||||
+230
-19
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -11,9 +12,12 @@ import (
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
@@ -23,6 +27,10 @@ import (
|
||||
func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/login", s.loginPage)
|
||||
r.GET("/signup", s.signupPage)
|
||||
r.GET("/signup/sent", s.signupSentPage)
|
||||
r.GET("/verify", s.verifyPage)
|
||||
r.GET("/verify/resend", s.resendPage)
|
||||
r.GET("/orgs/new", s.newOrgPage)
|
||||
r.GET("/invite/:token", s.invitePage)
|
||||
s.registerConsole(r)
|
||||
r.GET("/settings/security", s.securityPage)
|
||||
@@ -32,7 +40,14 @@ func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/settings/roles", s.orgPage("roles.title", authz.MembersRead, s.rolesView))
|
||||
r.GET("/settings/tokens", s.orgPage("tokens.title", "", s.tokensView))
|
||||
r.GET("/settings/regions", s.orgPage("regions.title", authz.OrgManage, s.regionsView))
|
||||
r.GET("/settings/audit", s.orgPage("audit.title", authz.AuditRead, s.auditView))
|
||||
r.GET("/admin", s.adminPage)
|
||||
r.GET("/admin/audit", s.adminAuditPage)
|
||||
r.GET("/admin/status-pages", s.adminStatusPagesPage)
|
||||
r.GET("/admin/orgs", s.adminOrgsPage)
|
||||
r.GET("/admin/legal", s.adminLegalPage)
|
||||
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
|
||||
r.GET("/legal/:kind", s.legalPage)
|
||||
}
|
||||
|
||||
// flashErrors lists the codes a redirect may ask a page to display. Anything
|
||||
@@ -41,11 +56,12 @@ var flashErrors = map[ssoError]bool{
|
||||
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
|
||||
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
|
||||
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
|
||||
"totp_required_by_org": true, "sso_required_by_org": true,
|
||||
"sso_email_unverified": true, "signup_limit": true,
|
||||
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
|
||||
}
|
||||
|
||||
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
p := web.Page{TitleID: titleID, Languages: s.catalog.Supported()}
|
||||
p := web.Page{TitleID: titleID, Languages: s.catalog.Supported(), Legal: web.LegalLinks(s.platformLegalDocs(c.Request.Context()), "/legal/")}
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
p.CSRF = sess.CSRF
|
||||
}
|
||||
@@ -73,25 +89,71 @@ 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) {
|
||||
web.Render(c, http.StatusOK, web.SignupSent(s.pageFor(c, "auth.verify.sent_title")))
|
||||
}
|
||||
|
||||
// verifyPage confirms an address only when the visitor presses the
|
||||
// button: mail scanners that open links must not sign in.
|
||||
func (s *Server) verifyPage(c *gin.Context) {
|
||||
web.Render(c, http.StatusOK, web.Verify(s.pageFor(c, "auth.verify.title"), c.Query("token")))
|
||||
}
|
||||
|
||||
func (s *Server) resendPage(c *gin.Context) {
|
||||
web.Render(c, http.StatusOK, web.ResendVerification(s.pageFor(c, "auth.verify.resend_title")))
|
||||
}
|
||||
|
||||
// newOrgPage lets a signed-in account create an organization: the first
|
||||
// one after signing up, or another.
|
||||
func (s *Server) newOrgPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login?next=/orgs/new")
|
||||
return
|
||||
}
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.NewOrgPage(s.pageFor(c, "orgs.new_title"), me))
|
||||
}
|
||||
|
||||
// consoleMe loads the signed-in user and, if an organization is active,
|
||||
@@ -118,9 +180,17 @@ func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *princip
|
||||
p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// The organization was deleted or the user removed from it.
|
||||
return me, nil, nil
|
||||
}
|
||||
if err != nil || !member {
|
||||
return me, nil, err
|
||||
}
|
||||
if p.Org.SuspendedAt != nil {
|
||||
me.OrgSuspended, me.SuspendedReason = true, p.Org.SuspendedReason
|
||||
return me, nil, nil
|
||||
}
|
||||
for _, perm := range authz.All {
|
||||
me.Can[string(perm)] = p.Grants.Can(perm)
|
||||
}
|
||||
@@ -201,7 +271,34 @@ func (s *Server) securityPage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink))
|
||||
rows, _, err := s.auditQuery(ctx, tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, pageReq{limit: 20})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
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 {
|
||||
@@ -259,8 +356,19 @@ func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me
|
||||
return web.SSOSettingsPage(page, me, view), nil
|
||||
}
|
||||
|
||||
func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
func (s *Server) orgSettingsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
v := web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}
|
||||
u, err := s.orgUsage(c.Request.Context(), p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Usage = web.UsageView{Limits: webLimits(u.Limits), Monitors: u.Usage.Monitors, StatusPages: u.Usage.StatusPages}
|
||||
off := s.disabledChecks(c.Request.Context())
|
||||
for _, t := range check.Types {
|
||||
if !off[string(t)] {
|
||||
v.CheckTypes = append(v.CheckTypes, web.CheckTypeOption{Type: string(t), Enabled: !slices.Contains(p.Org.DisabledCheckTypes, string(t))})
|
||||
}
|
||||
}
|
||||
if p.Org.ApiTokenMaxDays != nil {
|
||||
v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays)
|
||||
}
|
||||
@@ -269,7 +377,11 @@ func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me
|
||||
|
||||
func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
c.Set(ctxPrincipal, p)
|
||||
members, err := s.loadMembers(c)
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return nil, errAborted
|
||||
}
|
||||
members, info, err := s.loadMembers(c, pg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -289,7 +401,12 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage)}
|
||||
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info)}
|
||||
scopeNames, scopes, err := s.scopeOptions(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Scopes = scopes
|
||||
for _, r := range toWebRoles(roles) {
|
||||
if p.Grants.CanGrant(authz.NewSet(r.Permissions...), nil) {
|
||||
v.Roles = append(v.Roles, r)
|
||||
@@ -299,8 +416,11 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
|
||||
wm := web.Member{UserID: m.UserID.String(), Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner}
|
||||
for _, a := range m.Assignments {
|
||||
wa := web.Assignment{ID: a.ID.String(), RoleName: a.RoleName}
|
||||
if a.ResourceType != nil {
|
||||
if a.ResourceType != nil && a.ResourceID != nil {
|
||||
wa.Scope = i18n.T(ctx, "scope."+*a.ResourceType)
|
||||
if name := scopeNames[*a.ResourceID]; name != "" {
|
||||
wa.Scope += " " + name
|
||||
}
|
||||
}
|
||||
wm.Assignments = append(wm.Assignments, wa)
|
||||
}
|
||||
@@ -413,22 +533,32 @@ func (s *Server) regionsView(c *gin.Context, p *principal, page web.Page, me web
|
||||
return web.RegionsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) adminPage(c *gin.Context) {
|
||||
// adminMe loads the console user of an admin page, redirecting anyone else.
|
||||
func (s *Server) adminMe(c *gin.Context) (web.Me, bool) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login?next=/admin")
|
||||
return
|
||||
c.Redirect(http.StatusSeeOther, "/login?next="+url.QueryEscape(c.Request.URL.Path))
|
||||
return web.Me{}, false
|
||||
}
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
return web.Me{}, false
|
||||
}
|
||||
if !me.IsAdmin {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return web.Me{}, false
|
||||
}
|
||||
return me, true
|
||||
}
|
||||
|
||||
func (s *Server) adminPage(c *gin.Context) {
|
||||
me, ok := s.adminMe(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var err error
|
||||
var (
|
||||
regions []store.Region
|
||||
agents []store.ListAgentsRow
|
||||
@@ -450,11 +580,55 @@ func (s *Server) adminPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v))
|
||||
stats, err := datapolicy.Collect(ctx, s.db.Pool())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
off := s.disabledChecks(ctx)
|
||||
var types []web.CheckTypeOption
|
||||
for _, t := range check.Types {
|
||||
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||
}
|
||||
|
||||
func (s *Server) adminStatusPagesPage(c *gin.Context) {
|
||||
me, ok := s.adminMe(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
v, err := s.moderationView(c, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminStatusPagesPage(s.pageFor(c, "moderation.title"), me, v))
|
||||
}
|
||||
|
||||
func (s *Server) adminOrgsPage(c *gin.Context) {
|
||||
me, ok := s.adminMe(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pg, ok := parsePage(c, consolePageSize)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
v, err := s.orgsView(c, pg)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminOrgsPage(s.pageFor(c, "orgs.title"), me, v))
|
||||
}
|
||||
|
||||
func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) {
|
||||
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())
|
||||
@@ -472,7 +646,12 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
|
||||
if a.LastSeenAt != nil {
|
||||
seen = a.LastSeenAt.Format(time.DateTime)
|
||||
}
|
||||
v.Agents = append(v.Agents, web.Agent{ID: a.ID.String(), Kind: a.Kind, Name: a.Name, Region: deref(a.RegionName), Prefix: a.Prefix, LastSeen: seen})
|
||||
wa := web.Agent{ID: a.ID.String(), Kind: a.Kind, Name: a.Name, Region: deref(a.RegionName), Prefix: a.Prefix, LastSeen: seen, 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
|
||||
}
|
||||
v.Agents = append(v.Agents, wa)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -485,6 +664,7 @@ func toWebMe(m meView) web.Me {
|
||||
ActiveOrg: m.ActiveOrg.String(),
|
||||
RecoveryCodesLeft: m.RecoveryCodesLeft,
|
||||
IsAdmin: m.IsAdmin,
|
||||
HasPassword: m.HasPassword,
|
||||
}
|
||||
for _, o := range m.Orgs {
|
||||
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
|
||||
@@ -495,3 +675,34 @@ func toWebMe(m meView) web.Me {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// scopeOptions lists the monitor groups and status pages assignments can be
|
||||
// limited to, with names for displaying existing assignments.
|
||||
func (s *Server) scopeOptions(ctx context.Context, p *principal) (map[uuid.UUID]string, []web.ScopeOption, error) {
|
||||
names := map[uuid.UUID]string{}
|
||||
var opts []web.ScopeOption
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
groupLabel := i18n.T(ctx, "scope.monitor_group")
|
||||
t.walk(func(g store.MonitorGroup, depth int) {
|
||||
names[g.ID] = g.Name
|
||||
opts = append(opts, web.ScopeOption{Value: "monitor_group:" + g.ID.String(), Label: groupLabel + ": " + strings.Repeat("— ", depth) + g.Name})
|
||||
})
|
||||
var pages []store.StatusPage
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
pages, err = q.ListStatusPages(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pageLabel := i18n.T(ctx, "scope.status_page")
|
||||
for _, pg := range pages {
|
||||
names[pg.ID] = pg.Title
|
||||
opts = append(opts, web.ScopeOption{Value: "status_page:" + pg.ID.String(), Label: pageLabel + ": " + pg.Title})
|
||||
}
|
||||
return names, opts, nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Lists are paged by keyset: a cursor holds the sort key of an item and
|
||||
// its ID, so pages neither skip nor repeat items when others are added.
|
||||
// after pages forward in the list's order, before backward.
|
||||
|
||||
const (
|
||||
apiPageSize = 100
|
||||
maxPageSize = 500
|
||||
consolePageSize = 50
|
||||
)
|
||||
|
||||
// cursor is the position of an item: a time or string sort key and a
|
||||
// tie-breaking ID.
|
||||
type cursor struct {
|
||||
T time.Time `json:"t,omitzero"`
|
||||
S string `json:"s,omitempty"`
|
||||
ID uuid.UUID `json:"i,omitzero"`
|
||||
}
|
||||
|
||||
func (c cursor) encode() string {
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func decodeCursor(s string) (*cursor, bool) {
|
||||
if s == "" {
|
||||
return nil, true
|
||||
}
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
var c cursor
|
||||
if err != nil || json.Unmarshal(b, &c) != nil {
|
||||
return nil, false
|
||||
}
|
||||
return &c, true
|
||||
}
|
||||
|
||||
// pageReq is a requested page.
|
||||
type pageReq struct {
|
||||
after, before *cursor
|
||||
limit int
|
||||
}
|
||||
|
||||
// backward reports whether the page is read against the list's order.
|
||||
func (p pageReq) backward() bool { return p.before != nil }
|
||||
|
||||
// fetch is how many rows to read: one more tells whether more follow.
|
||||
func (p pageReq) fetch() int32 { return int32(p.limit + 1) }
|
||||
|
||||
// at is the cursor to read from, in reading direction.
|
||||
func (p pageReq) at() *cursor {
|
||||
if p.before != nil {
|
||||
return p.before
|
||||
}
|
||||
return p.after
|
||||
}
|
||||
|
||||
// Keys of the cursor for queries; nil when not paging from a position.
|
||||
func (p pageReq) afterT() *time.Time { return timeOf(p.after) }
|
||||
func (p pageReq) beforeT() *time.Time { return timeOf(p.before) }
|
||||
func (p pageReq) afterS() *string { return strOf(p.after) }
|
||||
func (p pageReq) beforeS() *string { return strOf(p.before) }
|
||||
func (p pageReq) afterID() *uuid.UUID { return idOf(p.after) }
|
||||
func (p pageReq) beforeID() *uuid.UUID { return idOf(p.before) }
|
||||
|
||||
func timeOf(c *cursor) *time.Time {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &c.T
|
||||
}
|
||||
|
||||
func strOf(c *cursor) *string {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &c.S
|
||||
}
|
||||
|
||||
func idOf(c *cursor) *uuid.UUID {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &c.ID
|
||||
}
|
||||
|
||||
// parsePage reads after, before and limit, answering 422 when invalid.
|
||||
func parsePage(c *gin.Context, def int) (pageReq, bool) {
|
||||
p := pageReq{limit: def}
|
||||
if l := c.Query("limit"); l != "" {
|
||||
n, err := strconv.Atoi(l)
|
||||
if err != nil || n < 1 || n > maxPageSize {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_limit", "Max", maxPageSize)
|
||||
return p, false
|
||||
}
|
||||
p.limit = n
|
||||
}
|
||||
var okA, okB bool
|
||||
p.after, okA = decodeCursor(c.Query("after"))
|
||||
p.before, okB = decodeCursor(c.Query("before"))
|
||||
if !okA || !okB || p.after != nil && p.before != nil {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_cursor")
|
||||
return p, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// pageInfo holds the cursors of the neighbouring pages, empty at either
|
||||
// end of the list.
|
||||
type pageInfo struct {
|
||||
Next string `json:"next_cursor,omitempty"`
|
||||
Prev string `json:"prev_cursor,omitempty"`
|
||||
}
|
||||
|
||||
// paginate trims rows read for p to one page in the list's order and
|
||||
// works out the neighbouring pages.
|
||||
func paginate[T any](p pageReq, rows []T, key func(T) cursor) ([]T, pageInfo) {
|
||||
var info pageInfo
|
||||
more := len(rows) > p.limit
|
||||
if more {
|
||||
rows = rows[:p.limit]
|
||||
}
|
||||
if p.backward() {
|
||||
slices.Reverse(rows)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return rows, info
|
||||
}
|
||||
first, last := key(rows[0]).encode(), key(rows[len(rows)-1]).encode()
|
||||
switch {
|
||||
case p.backward():
|
||||
info.Next = last
|
||||
if more {
|
||||
info.Prev = first
|
||||
}
|
||||
default:
|
||||
if more {
|
||||
info.Next = last
|
||||
}
|
||||
if p.after != nil {
|
||||
info.Prev = first
|
||||
}
|
||||
}
|
||||
return rows, info
|
||||
}
|
||||
|
||||
// pager builds the console's page links from info, keeping the request's
|
||||
// other query parameters.
|
||||
func pager(c *gin.Context, info pageInfo) web.Pager {
|
||||
link := func(key, cur string) string {
|
||||
q := c.Request.URL.Query()
|
||||
q.Del("after")
|
||||
q.Del("before")
|
||||
if key != "" {
|
||||
q.Set(key, cur)
|
||||
}
|
||||
if len(q) == 0 {
|
||||
return c.Request.URL.Path
|
||||
}
|
||||
return c.Request.URL.Path + "?" + q.Encode()
|
||||
}
|
||||
var pg web.Pager
|
||||
if info.Next != "" {
|
||||
pg.Next = link("after", info.Next)
|
||||
}
|
||||
if info.Prev != "" {
|
||||
pg.Prev = link("before", info.Prev)
|
||||
pg.First = link("", "")
|
||||
}
|
||||
return pg
|
||||
}
|
||||
|
||||
// pageSlice pages through items held in memory the way the queries page
|
||||
// through tables. items must be sorted ascending by key.
|
||||
func pageSlice[T any](items []T, pg pageReq, key func(T) cursor) ([]T, pageInfo) {
|
||||
cmp := func(a, b cursor) int {
|
||||
if c := strings.Compare(a.S, b.S); c != 0 {
|
||||
return c
|
||||
}
|
||||
if c := a.T.Compare(b.T); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID.String(), b.ID.String())
|
||||
}
|
||||
var read []T
|
||||
if pg.backward() {
|
||||
for i := len(items) - 1; i >= 0 && len(read) < int(pg.fetch()); i-- {
|
||||
if cmp(key(items[i]), *pg.before) < 0 {
|
||||
read = append(read, items[i])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, it := range items {
|
||||
if len(read) == int(pg.fetch()) {
|
||||
break
|
||||
}
|
||||
if pg.after == nil || cmp(key(it), *pg.after) > 0 {
|
||||
read = append(read, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
return paginate(pg, read, key)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestPaginate(t *testing.T) {
|
||||
// A list of 0..9 shown in order, read the way the queries do: from a
|
||||
// cursor in reading direction, one row more than the page.
|
||||
all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
key := func(i int) cursor { return cursor{S: string(rune('a' + i)), ID: uuid.Nil} }
|
||||
read := func(p pageReq) []int {
|
||||
var out []int
|
||||
if p.backward() {
|
||||
for i := len(all) - 1; i >= 0; i-- {
|
||||
if key(all[i]).S < p.before.S {
|
||||
out = append(out, all[i])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, v := range all {
|
||||
if p.after == nil || key(v).S > p.after.S {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out[:min(len(out), int(p.fetch()))]
|
||||
}
|
||||
page := func(p pageReq) ([]int, pageInfo) { return paginate(p, read(p), key) }
|
||||
|
||||
first, info := page(pageReq{limit: 4})
|
||||
if !slices.Equal(first, []int{0, 1, 2, 3}) || info.Prev != "" || info.Next == "" {
|
||||
t.Fatalf("first = %v %+v", first, info)
|
||||
}
|
||||
next, _ := decodeCursor(info.Next)
|
||||
second, info := page(pageReq{limit: 4, after: next})
|
||||
if !slices.Equal(second, []int{4, 5, 6, 7}) || info.Prev == "" || info.Next == "" {
|
||||
t.Fatalf("second = %v %+v", second, info)
|
||||
}
|
||||
n3, _ := decodeCursor(info.Next)
|
||||
last, lastInfo := page(pageReq{limit: 4, after: n3})
|
||||
if !slices.Equal(last, []int{8, 9}) || lastInfo.Next != "" || lastInfo.Prev == "" {
|
||||
t.Fatalf("last = %v %+v", last, lastInfo)
|
||||
}
|
||||
// Back from the last page and from the second to the first.
|
||||
prev, _ := decodeCursor(lastInfo.Prev)
|
||||
back, backInfo := page(pageReq{limit: 4, before: prev})
|
||||
if !slices.Equal(back, []int{4, 5, 6, 7}) || backInfo.Prev == "" || backInfo.Next == "" {
|
||||
t.Fatalf("back = %v %+v", back, backInfo)
|
||||
}
|
||||
p2, _ := decodeCursor(backInfo.Prev)
|
||||
start, startInfo := page(pageReq{limit: 4, before: p2})
|
||||
if !slices.Equal(start, []int{0, 1, 2, 3}) || startInfo.Prev != "" || startInfo.Next == "" {
|
||||
t.Fatalf("start = %v %+v", start, startInfo)
|
||||
}
|
||||
if _, ok := decodeCursor("not a cursor!"); ok {
|
||||
t.Error("garbage cursor accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageSlice(t *testing.T) {
|
||||
items := []string{"a", "b", "c", "d", "e"}
|
||||
key := func(s string) cursor { return cursor{S: s} }
|
||||
first, info := pageSlice(items, pageReq{limit: 2}, key)
|
||||
next, _ := decodeCursor(info.Next)
|
||||
second, info2 := pageSlice(items, pageReq{limit: 2, after: next}, key)
|
||||
prev, _ := decodeCursor(info2.Prev)
|
||||
back, _ := pageSlice(items, pageReq{limit: 2, before: prev}, key)
|
||||
if !slices.Equal(first, []string{"a", "b"}) || !slices.Equal(second, []string{"c", "d"}) || !slices.Equal(back, first) {
|
||||
t.Errorf("first %v, second %v, back %v", first, second, back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailKey(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"Max.Power+uptime@googlemail.com": "maxpower@gmail.com",
|
||||
"max.power@gmail.com": "maxpower@gmail.com",
|
||||
"a.b+c@example.com": "a.b@example.com",
|
||||
"A.B@Example.com": "a.b@example.com",
|
||||
} {
|
||||
if got := emailKey(in); got != want {
|
||||
t.Errorf("emailKey(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
if clientKey("2001:db8:1:2:aaaa::1") != clientKey("2001:db8:1:2:bbbb::9") || clientKey("2001:db8:1:3::1") == clientKey("2001:db8:1:2::1") {
|
||||
t.Error("IPv6 clients are not grouped by /64")
|
||||
}
|
||||
if clientKey("203.0.113.7") != "203.0.113.7" {
|
||||
t.Error("IPv4 clients are grouped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// pages follows next_cursor through a list and back through prev_cursor,
|
||||
// returning the IDs in order both ways.
|
||||
func pages(t *testing.T, b *browser, path, key string) (forward, backward []string) {
|
||||
t.Helper()
|
||||
sep := "?"
|
||||
if strings.Contains(path, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
ids := func(body map[string]any) []string {
|
||||
var out []string
|
||||
for _, it := range body[key].([]any) {
|
||||
out = append(out, it.(map[string]any)["id"].(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
var last map[string]any
|
||||
cursor := ""
|
||||
for range 20 {
|
||||
q := path + sep + "limit=2"
|
||||
if cursor != "" {
|
||||
q += "&after=" + url.QueryEscape(cursor)
|
||||
}
|
||||
st, body := b.do("GET", q, nil)
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %v", q, st, body)
|
||||
}
|
||||
forward = append(forward, ids(body)...)
|
||||
last = body
|
||||
if cursor, _ = body["next_cursor"].(string); cursor == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Back from the last page to the first.
|
||||
page := ids(last)
|
||||
backward = append(page, backward...)
|
||||
prev, _ := last["prev_cursor"].(string)
|
||||
for prev != "" {
|
||||
st, body := b.do("GET", path+sep+"limit=2&before="+url.QueryEscape(prev), nil)
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("before = %d %v", st, body)
|
||||
}
|
||||
backward = append(ids(body), backward...)
|
||||
prev, _ = body["prev_cursor"].(string)
|
||||
}
|
||||
return forward, backward
|
||||
}
|
||||
|
||||
func TestPaging(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("pg")+".test", uniq("pg-"))
|
||||
var monitors []string
|
||||
for _, name := range []string{"e", "a", "d", "b", "c"} {
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": name, "type": "heartbeat", "interval_seconds": 3600})
|
||||
monitors = append(monitors, m["id"].(string))
|
||||
}
|
||||
|
||||
// Monitors page by name.
|
||||
fwd, back := pages(t, owner, "/api/v1/org/monitors", "monitors")
|
||||
if len(fwd) != 5 || !slices.Equal(fwd, back) {
|
||||
t.Errorf("monitors forward %v, backward %v", fwd, back)
|
||||
}
|
||||
_, first := owner.do("GET", "/api/v1/org/monitors?limit=1", nil)
|
||||
if first["monitors"].([]any)[0].(map[string]any)["name"] != "a" {
|
||||
t.Errorf("monitors are not by name: %v", first["monitors"])
|
||||
}
|
||||
|
||||
// Incidents with the same start time: none skipped or repeated.
|
||||
started := time.Now().Add(-time.Hour).Truncate(time.Second)
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
for _, m := range monitors {
|
||||
if _, err := tx.Exec(context.Background(), `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at, cause)
|
||||
SELECT org_id, id, $2::timestamptz, $2::timestamptz + interval '1 minute', '{}' FROM monitors WHERE id = $1`, m, started); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fwd, back = pages(t, owner, "/api/v1/org/incidents", "incidents")
|
||||
if len(fwd) != 5 || !slices.Equal(fwd, back) {
|
||||
t.Errorf("incidents forward %v, backward %v", fwd, back)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range fwd {
|
||||
if seen[id] {
|
||||
t.Errorf("incident %s repeated", id)
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
fwd, _ = pages(t, owner, "/api/v1/org/incidents?monitor_id="+monitors[0], "incidents")
|
||||
if len(fwd) != 1 {
|
||||
t.Errorf("incidents of one monitor = %v", fwd)
|
||||
}
|
||||
|
||||
// Invalid requests.
|
||||
st, body := owner.do("GET", "/api/v1/org/incidents?after=nonsense!", nil)
|
||||
expect(t, "bad cursor", st, body, http.StatusUnprocessableEntity, "invalid_cursor")
|
||||
st, body = owner.do("GET", "/api/v1/org/incidents?limit=501", nil)
|
||||
expect(t, "limit too large", st, body, http.StatusUnprocessableEntity, "invalid_limit")
|
||||
|
||||
// The console pages with links.
|
||||
_, _, html := owner.page("/incidents?limit=2")
|
||||
if !strings.Contains(html, `rel="next"`) || strings.Contains(html, `rel="prev"`) {
|
||||
t.Error("the first console page lacks a next link or has a previous one")
|
||||
}
|
||||
if _, _, html := owner.page(nextLink(t, html)); !strings.Contains(html, `rel="prev"`) || !strings.Contains(html, "To the start") {
|
||||
t.Error("a later console page lacks the way back")
|
||||
}
|
||||
}
|
||||
|
||||
var nextHref = regexp.MustCompile(`href="([^"]+)" rel="next"`)
|
||||
|
||||
// nextLink returns the console's link to the next page.
|
||||
func nextLink(t *testing.T, html string) string {
|
||||
t.Helper()
|
||||
m := nextHref.FindStringSubmatch(html)
|
||||
if m == nil {
|
||||
t.Fatal("no next link")
|
||||
}
|
||||
return strings.ReplaceAll(m[1], "&", "&")
|
||||
}
|
||||
|
||||
// shown counts the monitors a dashboard page links to.
|
||||
func shown(html string) int {
|
||||
return strings.Count(html, `href="/monitors/`) - strings.Count(html, `href="/monitors/new"`)
|
||||
}
|
||||
|
||||
func TestDashboardPaging(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("dash")+".test", uniq("dash-"))
|
||||
_, g := owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "Fleet"})
|
||||
group := g["id"].(string)
|
||||
for i := range 55 {
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "node-" + strconv.Itoa(100+i), "type": "heartbeat", "interval_seconds": 3600, "group_id": group,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "loner", "type": "heartbeat", "interval_seconds": 3600})
|
||||
|
||||
_, _, html := owner.page("/")
|
||||
if n := shown(html); n != 51 {
|
||||
t.Errorf("dashboard shows %d monitors, want 50 of the group and the ungrouped one", n)
|
||||
}
|
||||
if !strings.Contains(html, "Show all 55") || !strings.Contains(html, "/?group="+group) {
|
||||
t.Error("the group lacks its show-all link")
|
||||
}
|
||||
|
||||
_, _, html = owner.page("/?group=" + group)
|
||||
if n := shown(html); n != 50 || !strings.Contains(html, `rel="next"`) || !strings.Contains(html, "Fleet") {
|
||||
t.Errorf("focused group shows %d monitors or lacks paging", n)
|
||||
}
|
||||
if _, _, page2 := owner.page(nextLink(t, html)); shown(page2) != 5 || !strings.Contains(page2, "node-154") {
|
||||
t.Error("the second page of the group is wrong")
|
||||
}
|
||||
|
||||
if _, _, html := owner.page("/?q=node-107"); shown(html) != 1 || !strings.Contains(html, "node-107") {
|
||||
t.Error("search does not find the one monitor")
|
||||
}
|
||||
if _, _, html := owner.page("/?group=none"); !strings.Contains(html, "loner") || strings.Contains(html, "node-100") {
|
||||
t.Error("the ungrouped view is wrong")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
)
|
||||
|
||||
// providerConfig is stored for channels of notify.Providers. Secret
|
||||
// settings are sealed, bound to the channel type and field, and never
|
||||
// shown again.
|
||||
type providerConfig struct {
|
||||
Settings map[string]string `json:"settings"`
|
||||
Sealed map[string]string `json:"sealed"`
|
||||
Locale string `json:"locale"`
|
||||
}
|
||||
|
||||
func secretAAD(typ, field string) []byte { return []byte("channel:" + typ + ":" + field) }
|
||||
|
||||
// providerSettings validates the settings of a provider channel. Secret
|
||||
// fields left empty keep their previous value, so a form can be saved
|
||||
// without asking for tokens again.
|
||||
func (s *Server) providerSettings(p notify.Provider, req *channelRequest, previous []byte) ([]byte, string) {
|
||||
var old providerConfig
|
||||
if previous != nil {
|
||||
_ = json.Unmarshal(previous, &old)
|
||||
}
|
||||
cfg := providerConfig{Settings: map[string]string{}, Sealed: map[string]string{}, Locale: req.Locale}
|
||||
for _, f := range p.Fields {
|
||||
v := strings.TrimSpace(req.Settings[f.Name])
|
||||
if f.Secret {
|
||||
if v == "" {
|
||||
if sealed, ok := old.Sealed[f.Name]; ok {
|
||||
cfg.Sealed[f.Name] = sealed
|
||||
continue
|
||||
}
|
||||
if f.Required {
|
||||
return nil, "invalid_channel_settings"
|
||||
}
|
||||
continue
|
||||
}
|
||||
} else if v == "" {
|
||||
v = f.Default
|
||||
}
|
||||
if v == "" {
|
||||
if f.Required {
|
||||
return nil, "invalid_channel_settings"
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(v) > 2000 || !s.validSetting(f, v) {
|
||||
return nil, "invalid_channel_settings"
|
||||
}
|
||||
if f.Secret {
|
||||
cfg.Sealed[f.Name] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), secretAAD(p.Type, f.Name)))
|
||||
} else {
|
||||
cfg.Settings[f.Name] = v
|
||||
}
|
||||
}
|
||||
if cfg.Locale == "" || !s.catalog.IsSupported(cfg.Locale) {
|
||||
cfg.Locale = "en"
|
||||
}
|
||||
raw, _ := json.Marshal(cfg)
|
||||
return raw, ""
|
||||
}
|
||||
|
||||
func (s *Server) validSetting(f notify.Field, v string) bool {
|
||||
switch f.Kind {
|
||||
case "url":
|
||||
u, err := url.Parse(v)
|
||||
// Plain http only where services may live on private networks.
|
||||
return err == nil && u.Host != "" && u.User == nil && (u.Scheme == "https" || (u.Scheme == "http" && !s.cloud()))
|
||||
case "number":
|
||||
_, err := strconv.Atoi(v)
|
||||
return err == nil
|
||||
case "select":
|
||||
return slices.Contains(f.Options, v)
|
||||
}
|
||||
return !strings.ContainsAny(v, "\r\n")
|
||||
}
|
||||
|
||||
// providerView shows the settings of a provider channel; secrets appear
|
||||
// only as the names of fields that are set.
|
||||
func providerView(raw []byte) (map[string]string, []string, string) {
|
||||
var cfg providerConfig
|
||||
_ = json.Unmarshal(raw, &cfg)
|
||||
set := make([]string, 0, len(cfg.Sealed))
|
||||
for k := range cfg.Sealed {
|
||||
set = append(set, k)
|
||||
}
|
||||
slices.Sort(set)
|
||||
if cfg.Settings == nil {
|
||||
cfg.Settings = map[string]string{}
|
||||
}
|
||||
return cfg.Settings, set, cfg.Locale
|
||||
}
|
||||
|
||||
// openProviderSettings returns all settings with secrets unsealed.
|
||||
func (s *Server) openProviderSettings(typ string, raw []byte) (map[string]string, string, error) {
|
||||
var cfg providerConfig
|
||||
if err := json.Unmarshal(raw, &cfg); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
out := map[string]string{}
|
||||
for k, v := range cfg.Settings {
|
||||
out[k] = v
|
||||
}
|
||||
for k, v := range cfg.Sealed {
|
||||
sealed, err := base64.StdEncoding.DecodeString(v)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
plain, err := s.keys.Open(sealed, secretAAD(typ, k))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
out[k] = string(plain)
|
||||
}
|
||||
return out, cfg.Locale, nil
|
||||
}
|
||||
|
||||
// messageFor renders an event for chat and push services in locale.
|
||||
func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
|
||||
l := s.catalog.Match(locale)
|
||||
data := map[string]any{"Monitor": ev.Monitor.Name}
|
||||
m := notify.Message{Event: ev.Kind, Key: ev.IncidentID, Monitor: ev.Monitor.Name, MonitorID: ev.Monitor.ID, Target: ev.Monitor.Target}
|
||||
var lines []string
|
||||
switch ev.Kind {
|
||||
case notify.Opened:
|
||||
m.Title = l.T("notify.title_opened", data)
|
||||
for region, msg := range ev.Cause {
|
||||
lines = append(lines, region+": "+msg)
|
||||
}
|
||||
slices.Sort(lines)
|
||||
case notify.Resolved:
|
||||
m.Title = l.T("notify.title_resolved", data)
|
||||
if ev.ResolvedAt != nil {
|
||||
lines = append(lines, l.T("notify.duration", map[string]any{"Duration": ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()}))
|
||||
}
|
||||
default:
|
||||
m.Title = l.T("notify.title_test", data)
|
||||
lines = append(lines, l.T("notify.test_body", nil))
|
||||
}
|
||||
if ev.Monitor.Target != "" && ev.Monitor.Type != "heartbeat" {
|
||||
lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...)
|
||||
}
|
||||
m.Body = strings.Join(lines, "\n")
|
||||
if ev.Monitor.ID != [16]byte{} {
|
||||
m.URL = strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
)
|
||||
|
||||
func TestProvidersAreTranslated(t *testing.T) {
|
||||
catalog, err := i18n.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lang := range catalog.Supported() {
|
||||
ctx := i18n.NewContext(context.Background(), catalog.Match(lang))
|
||||
for _, p := range notify.Providers {
|
||||
ids := []string{"channels.type_" + p.Type}
|
||||
for _, f := range p.Fields {
|
||||
ids = append(ids, "channels.field_"+f.Name)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if i18n.T(ctx, id) == id {
|
||||
t.Errorf("%s: %s is not translated", lang, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderChannel(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
var mu sync.Mutex
|
||||
var paths, bodies []string
|
||||
telegram := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
|
||||
mu.Unlock()
|
||||
}))
|
||||
defer telegram.Close()
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("pr")+".test", uniq("pr-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops chat", "type": "telegram", "settings": map[string]string{"chat_id": "-100"}})
|
||||
expect(t, "missing bot token", st, body, http.StatusUnprocessableEntity, "invalid_channel_settings")
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "carrierpigeon"})
|
||||
expect(t, "unknown type", st, body, http.StatusUnprocessableEntity, "invalid_input")
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{
|
||||
"name": "Ops chat", "type": "telegram", "locale": "de",
|
||||
"settings": map[string]string{"bot_token": "4711:very-secret", "chat_id": "-100123", "api_url": telegram.URL},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create telegram channel = %d %v", st, body)
|
||||
}
|
||||
ch := body["channel"].(map[string]any)
|
||||
id := ch["id"].(string)
|
||||
if raw := mustJSON(body); strings.Contains(raw, "very-secret") || ch["settings"].(map[string]any)["chat_id"] != "-100123" ||
|
||||
mustJSON(ch["secrets_set"]) != `["bot_token"]` {
|
||||
t.Errorf("create answer = %s", raw)
|
||||
}
|
||||
var stored string
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
return tx.QueryRow(context.Background(), `SELECT config::text FROM notification_channels WHERE id = $1`, id).Scan(&stored)
|
||||
})
|
||||
if strings.Contains(stored, "very-secret") {
|
||||
t.Error("the bot token is stored in plain text")
|
||||
}
|
||||
if _, list := owner.do("GET", "/api/v1/org/channels", nil); strings.Contains(mustJSON(list), "very-secret") {
|
||||
t.Error("the channel list shows the bot token")
|
||||
}
|
||||
|
||||
if st, body := owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil); st != http.StatusNoContent {
|
||||
t.Fatalf("test send = %d %v", st, body)
|
||||
}
|
||||
// Saving without the token keeps it.
|
||||
st, body = owner.do("PUT", "/api/v1/org/channels/"+id, map[string]any{
|
||||
"name": "Ops chat", "type": "telegram", "locale": "de",
|
||||
"settings": map[string]string{"chat_id": "-100999", "api_url": telegram.URL},
|
||||
})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("update = %d %v", st, body)
|
||||
}
|
||||
owner.do("POST", "/api/v1/org/channels/"+id+"/test", nil)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(paths) != 2 || paths[0] != "/bot4711:very-secret/sendMessage" || paths[1] != paths[0] {
|
||||
t.Errorf("telegram requests = %v", paths)
|
||||
}
|
||||
if !strings.Contains(bodies[0], "Test von UptimeSebi") || !strings.Contains(bodies[1], `"chat_id":"-100999"`) {
|
||||
t.Errorf("telegram bodies = %v", bodies)
|
||||
}
|
||||
_, _, page := owner.page("/settings/channels")
|
||||
if !strings.Contains(page, `name="settings.bot_token"`) || !strings.Contains(page, "-100999") {
|
||||
t.Error("the channels page lacks the service form or the channel")
|
||||
}
|
||||
// Services are grouped, and every one has its settings form.
|
||||
if !strings.Contains(page, `<optgroup label="SMS and calls">`) {
|
||||
t.Error("the services are not grouped")
|
||||
}
|
||||
for _, p := range notify.Providers {
|
||||
if !strings.Contains(page, `<fieldset data-type="`+p.Type+`"`) {
|
||||
t.Errorf("the channels page lacks the form of %s", p.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// quietHourRequest is one recurring time window during which an alert group
|
||||
// suppresses notifications.
|
||||
type quietHourRequest struct {
|
||||
// Weekdays are days of the week (0 = Sunday .. 6 = Saturday); empty
|
||||
// means every day.
|
||||
Weekdays flexInts `json:"weekdays" binding:"max=7"`
|
||||
// Start and End are wall-clock times "HH:MM" in TimeZone. End may be
|
||||
// "24:00"; Start > End wraps overnight into the next day, and
|
||||
// "00:00" to "00:00" (or "24:00") covers the entire day.
|
||||
Start string `json:"start" binding:"required,max=5"`
|
||||
End string `json:"end" binding:"required,max=5"`
|
||||
TimeZone string `json:"time_zone" binding:"required,max=64"`
|
||||
}
|
||||
|
||||
// quietHourView is one normalized quiet window returned by the API and stored
|
||||
// on an alert group.
|
||||
type quietHourView struct {
|
||||
Weekdays []int `json:"weekdays"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
}
|
||||
|
||||
// validateQuietHours validates and normalizes quiet windows, returning an
|
||||
// error code on failure.
|
||||
func validateQuietHours(in []quietHourRequest) ([]quietHourView, string) {
|
||||
out := make([]quietHourView, 0, len(in))
|
||||
for _, w := range in {
|
||||
tz := strings.TrimSpace(w.TimeZone)
|
||||
if tz == "" || tz == "Local" {
|
||||
return nil, "invalid_time_zone"
|
||||
}
|
||||
if _, err := time.LoadLocation(tz); err != nil {
|
||||
return nil, "invalid_time_zone"
|
||||
}
|
||||
start := strings.TrimSpace(w.Start)
|
||||
end := strings.TrimSpace(w.End)
|
||||
startMin, startOK := parseClockMinutes(start)
|
||||
endMin, endOK := parseEndMinutes(end)
|
||||
if !startOK || !endOK {
|
||||
return nil, "invalid_quiet_hours"
|
||||
}
|
||||
// Identical non-zero times would be an empty window; 00:00-00:00
|
||||
// (like 00:00-24:00) means the whole day.
|
||||
if startMin == endMin && startMin != 0 {
|
||||
return nil, "invalid_quiet_hours"
|
||||
}
|
||||
days := make([]int, 0, len(w.Weekdays))
|
||||
for _, d := range w.Weekdays {
|
||||
if d < 0 || d > 6 {
|
||||
return nil, "invalid_quiet_hours"
|
||||
}
|
||||
days = append(days, d)
|
||||
}
|
||||
slices.Sort(days)
|
||||
days = slices.Compact(days)
|
||||
out = append(out, quietHourView{
|
||||
Weekdays: days,
|
||||
Start: start,
|
||||
End: end,
|
||||
TimeZone: tz,
|
||||
})
|
||||
}
|
||||
return out, ""
|
||||
}
|
||||
|
||||
// parseClockMinutes parses "HH:MM" (00:00..23:59) into minutes since midnight.
|
||||
func parseClockMinutes(s string) (int, bool) {
|
||||
if len(s) != 5 || s[2] != ':' {
|
||||
return 0, false
|
||||
}
|
||||
hour, err := strconv.Atoi(s[:2])
|
||||
if err != nil || hour < 0 || hour > 23 {
|
||||
return 0, false
|
||||
}
|
||||
minute, err := strconv.Atoi(s[3:])
|
||||
if err != nil || minute < 0 || minute > 59 {
|
||||
return 0, false
|
||||
}
|
||||
return hour*60 + minute, true
|
||||
}
|
||||
|
||||
// parseEndMinutes parses a window end time, accepting "24:00" in addition to
|
||||
// 00:00..23:59.
|
||||
func parseEndMinutes(s string) (int, bool) {
|
||||
if s == "24:00" {
|
||||
return 24 * 60, true
|
||||
}
|
||||
return parseClockMinutes(s)
|
||||
}
|
||||
|
||||
// decodeQuietHours decodes stored JSONB quiet windows, always returning a
|
||||
// non-nil slice so JSON responses serialize as [] rather than null.
|
||||
func decodeQuietHours(raw []byte) []quietHourView {
|
||||
if len(raw) == 0 {
|
||||
return []quietHourView{}
|
||||
}
|
||||
var out []quietHourView
|
||||
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
|
||||
return []quietHourView{}
|
||||
}
|
||||
for i := range out {
|
||||
if out[i].Weekdays == nil {
|
||||
out[i].Weekdays = []int{}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// contains reports whether t falls inside w in w's time zone.
|
||||
func (w quietHourView) contains(t time.Time) bool {
|
||||
startMin, startOK := parseClockMinutes(w.Start)
|
||||
endMin, endOK := parseEndMinutes(w.End)
|
||||
if !startOK || !endOK {
|
||||
return false
|
||||
}
|
||||
local := t.In(loadLocation(w.TimeZone))
|
||||
nowMin := local.Hour()*60 + local.Minute()
|
||||
today := int(local.Weekday())
|
||||
hasDay := func(d int) bool {
|
||||
return len(w.Weekdays) == 0 || slices.Contains(w.Weekdays, d)
|
||||
}
|
||||
if startMin == 0 && (endMin == 0 || endMin == 24*60) {
|
||||
return hasDay(today)
|
||||
}
|
||||
if startMin < endMin {
|
||||
return hasDay(today) && nowMin >= startMin && nowMin < endMin
|
||||
}
|
||||
// Overnight window (Start > End), e.g. 22:00-07:00 or 18:00-00:00:
|
||||
// covers [Start, 24:00) on matching days and [00:00, End) on the next day.
|
||||
yesterday := (today + 6) % 7
|
||||
return (hasDay(today) && nowMin >= startMin) || (hasDay(yesterday) && nowMin < endMin)
|
||||
}
|
||||
|
||||
// isQuietAt reports whether any window in windows suppresses notifications at t.
|
||||
func isQuietAt(windows []quietHourView, t time.Time) bool {
|
||||
for _, w := range windows {
|
||||
if w.contains(t) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isQuietRawAt(raw []byte, t time.Time) bool {
|
||||
return isQuietAt(decodeQuietHours(raw), t)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestValidateQuietHours(t *testing.T) {
|
||||
in := []quietHourRequest{
|
||||
{Weekdays: flexInts{5, 1, 5, 3}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"},
|
||||
{Weekdays: nil, Start: "00:00", End: "24:00", TimeZone: "UTC"},
|
||||
{Weekdays: flexInts{0, 6}, Start: "00:00", End: "00:00", TimeZone: "UTC"},
|
||||
}
|
||||
got, code := validateQuietHours(in)
|
||||
if code != "" {
|
||||
t.Fatalf("validateQuietHours(%+v) error code = %q, want %q", in, code, "")
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("len(validateQuietHours(...)) = %d, want 3", len(got))
|
||||
}
|
||||
if want := []int{1, 3, 5}; !slices.Equal(got[0].Weekdays, want) {
|
||||
t.Errorf("got[0].Weekdays = %v, want %v", got[0].Weekdays, want)
|
||||
}
|
||||
if got[1].Weekdays == nil || len(got[1].Weekdays) != 0 {
|
||||
t.Errorf("got[1].Weekdays = %#v, want non-nil empty []int{}", got[1].Weekdays)
|
||||
}
|
||||
|
||||
invalid := []struct {
|
||||
name string
|
||||
req quietHourRequest
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "empty time zone",
|
||||
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: ""},
|
||||
want: "invalid_time_zone",
|
||||
},
|
||||
{
|
||||
name: "local time zone",
|
||||
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Local"},
|
||||
want: "invalid_time_zone",
|
||||
},
|
||||
{
|
||||
name: "unknown time zone",
|
||||
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Mars/Olympus"},
|
||||
want: "invalid_time_zone",
|
||||
},
|
||||
{
|
||||
name: "invalid start hour",
|
||||
req: quietHourRequest{Start: "24:00", End: "07:00", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
{
|
||||
name: "invalid end minute",
|
||||
req: quietHourRequest{Start: "22:00", End: "24:01", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
{
|
||||
name: "short clock format",
|
||||
req: quietHourRequest{Start: "9:00", End: "17:00", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
{
|
||||
name: "equal non-zero start and end",
|
||||
req: quietHourRequest{Start: "12:00", End: "12:00", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
{
|
||||
name: "negative weekday",
|
||||
req: quietHourRequest{Weekdays: flexInts{-1}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
{
|
||||
name: "weekday out of range",
|
||||
req: quietHourRequest{Weekdays: flexInts{7}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
|
||||
want: "invalid_quiet_hours",
|
||||
},
|
||||
}
|
||||
for _, tc := range invalid {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, got := validateQuietHours([]quietHourRequest{tc.req})
|
||||
if got != tc.want {
|
||||
t.Errorf("validateQuietHours(%+v) error code = %q, want %q", tc.req, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuietHoursContains(t *testing.T) {
|
||||
berlin, err := time.LoadLocation("Europe/Berlin")
|
||||
if err != nil {
|
||||
t.Fatalf("time.LoadLocation(%q) error = %v", "Europe/Berlin", err)
|
||||
}
|
||||
at := func(y int, m time.Month, d, hh, mm int, loc *time.Location) time.Time {
|
||||
return time.Date(y, m, d, hh, mm, 0, 0, loc)
|
||||
}
|
||||
|
||||
// 2026-11-23 is Monday, 2026-11-27 is Friday, 2026-11-28 is Saturday,
|
||||
// and 2026-11-29 is Sunday.
|
||||
daytime := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "09:00", End: "17:00", TimeZone: "Europe/Berlin"}
|
||||
overnight := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"}
|
||||
weekendZero := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "00:00", TimeZone: "Europe/Berlin"}
|
||||
weekend24 := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "24:00", TimeZone: "Europe/Berlin"}
|
||||
eveningEndZero := quietHourView{Weekdays: []int{5}, Start: "18:00", End: "00:00", TimeZone: "UTC"}
|
||||
dailyNight := quietHourView{Weekdays: []int{}, Start: "23:00", End: "06:00", TimeZone: "Europe/Berlin"}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
window quietHourView
|
||||
ts time.Time
|
||||
want bool
|
||||
}{
|
||||
{name: "daytime before start", window: daytime, ts: at(2026, 11, 23, 8, 59, berlin), want: false},
|
||||
{name: "daytime at start", window: daytime, ts: at(2026, 11, 23, 9, 0, berlin), want: true},
|
||||
{name: "daytime inside", window: daytime, ts: at(2026, 11, 23, 16, 59, berlin), want: true},
|
||||
{name: "daytime at end", window: daytime, ts: at(2026, 11, 23, 17, 0, berlin), want: false},
|
||||
{name: "daytime wrong day", window: daytime, ts: at(2026, 11, 28, 12, 0, berlin), want: false},
|
||||
|
||||
{name: "overnight mon before", window: overnight, ts: at(2026, 11, 23, 21, 59, berlin), want: false},
|
||||
{name: "overnight mon start", window: overnight, ts: at(2026, 11, 23, 22, 0, berlin), want: true},
|
||||
{name: "overnight mon early from sun", window: overnight, ts: at(2026, 11, 23, 3, 0, berlin), want: false},
|
||||
{name: "overnight tue early from mon", window: overnight, ts: at(2026, 11, 24, 6, 59, berlin), want: true},
|
||||
{name: "overnight tue at end", window: overnight, ts: at(2026, 11, 24, 7, 0, berlin), want: false},
|
||||
{name: "overnight sat early from fri", window: overnight, ts: at(2026, 11, 28, 3, 0, berlin), want: true},
|
||||
{name: "overnight sat late", window: overnight, ts: at(2026, 11, 28, 23, 0, berlin), want: false},
|
||||
{name: "overnight sun early", window: overnight, ts: at(2026, 11, 29, 3, 0, berlin), want: false},
|
||||
|
||||
{name: "weekend 00-00 sat", window: weekendZero, ts: at(2026, 11, 28, 0, 0, berlin), want: true},
|
||||
{name: "weekend 00-00 sun late", window: weekendZero, ts: at(2026, 11, 29, 23, 59, berlin), want: true},
|
||||
{name: "weekend 00-00 mon", window: weekendZero, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
|
||||
{name: "weekend 00-24 sat", window: weekend24, ts: at(2026, 11, 28, 15, 0, berlin), want: true},
|
||||
{name: "weekend 00-24 mon", window: weekend24, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
|
||||
|
||||
{name: "evening 18-00 fri inside", window: eveningEndZero, ts: at(2026, 11, 27, 23, 59, time.UTC), want: true},
|
||||
{name: "evening 18-00 sat midnight", window: eveningEndZero, ts: at(2026, 11, 28, 0, 0, time.UTC), want: false},
|
||||
|
||||
// Winter (CET = UTC+1) vs summer (CEST = UTC+2) in Europe/Berlin.
|
||||
{name: "daily winter 22:30 UTC is 23:30 CET", window: dailyNight, ts: at(2026, 1, 15, 22, 30, time.UTC), want: true},
|
||||
{name: "daily winter 21:30 UTC is 22:30 CET", window: dailyNight, ts: at(2026, 1, 15, 21, 30, time.UTC), want: false},
|
||||
{name: "daily summer 21:30 UTC is 23:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 21, 30, time.UTC), want: true},
|
||||
{name: "daily summer 03:30 UTC is 05:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 3, 30, time.UTC), want: true},
|
||||
{name: "daily summer 04:00 UTC is 06:00 CEST", window: dailyNight, ts: at(2026, 7, 15, 4, 0, time.UTC), want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := tc.window.contains(tc.ts); got != tc.want {
|
||||
t.Errorf("contains(%s) = %t, want %t", tc.ts.Format(time.RFC3339), got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestTimeRangesAndSLA(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("r")+".test", uniq("rng-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two days old, down for six minutes half an hour ago.
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
conn, err := e.dbPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
if _, err := conn.Exec(ctx, `SELECT set_config('app.scope', 'system', false)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `UPDATE monitors SET created_at = $2 WHERE id = $1`, id, now.Add(-48*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at) VALUES ($1, $2, $3, $4)`,
|
||||
org, id, now.Add(-30*time.Minute), now.Add(-24*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = conn.Exec(ctx, `SELECT set_config('app.scope', '', false)`)
|
||||
|
||||
_, _, html := owner.page("/monitors/" + id.String() + "?range=1h")
|
||||
// The monitor is two days old, so 7d and longer cover only those two
|
||||
// days: 6 of 2880 minutes down.
|
||||
for _, want := range []string{">1h<", "90.0%", ">7d<", "99.79%", ">90d<"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("monitor page lacks %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
for key, n := range bars {
|
||||
st, _, html := owner.page("/?range=" + key)
|
||||
if st != http.StatusOK {
|
||||
t.Errorf("GET /?range=%s = %d", key, st)
|
||||
continue
|
||||
}
|
||||
// The dashboard has one monitor; its chart holds one rect per bar.
|
||||
if got := strings.Count(html, "<rect "); got != n {
|
||||
t.Errorf("range %s shows %d bars, want %d", key, got, n)
|
||||
}
|
||||
}
|
||||
if _, _, html := owner.page("/?range=1h"); !strings.Contains(html, "90.0%") {
|
||||
t.Error("dashboard 1h does not show the 1h SLA")
|
||||
}
|
||||
if _, _, html := owner.page("/?range=24h"); !strings.Contains(html, "99.58") {
|
||||
t.Error("dashboard 24h does not show the 24h SLA (6 of 1440 minutes down)")
|
||||
}
|
||||
|
||||
// A monitor created five minutes ago is measured only since then.
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "New", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatal(body)
|
||||
}
|
||||
if _, _, html := owner.page("/monitors/" + body["id"].(string)); !strings.Contains(html, "100%") {
|
||||
t.Error("new monitor without incidents does not show 100%")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRangeAvailabilityAndRegions(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, eu := e.platformChecker(t, uniq("eu-"))
|
||||
_, us := e.platformChecker(t, uniq("us-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("ra")+".test", uniq("ra-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "API", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{eu, us},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two hours of results: eu always fine, us always failing.
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
checker := uuid.New()
|
||||
for m := 0; m <= 120; m += 5 {
|
||||
at := now.Add(-time.Duration(m) * time.Minute)
|
||||
for region, ok := range map[string]bool{eu: true, us: false} {
|
||||
if _, err := e.dbPool.Exec(ctx,
|
||||
`INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES ($1, $2, $3, $4, $5, $6, 50)`,
|
||||
at, org, id, region, checker, ok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_, _, html := owner.page("/monitors/" + id.String() + "?range=1h")
|
||||
for key, disabled := range map[string]bool{"3h": false, "12h": true, "24h": true, "1y": true} {
|
||||
got := strings.Contains(html, `aria-disabled="true">`+key+"<")
|
||||
if got != disabled {
|
||||
t.Errorf("range %s disabled = %t, want %t", key, got, disabled)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(html, `href="/monitors/`+id.String()+`?range=3h"`) {
|
||||
t.Error("3h is not selectable with two hours of data")
|
||||
}
|
||||
if !strings.Contains(html, "By region") && !strings.Contains(html, "Nach Region") {
|
||||
t.Fatal("monitor page lacks the per-region section")
|
||||
}
|
||||
if !strings.Contains(html, ">100%<") || !strings.Contains(html, ">0.0%<") {
|
||||
t.Error("per-region availability does not show 100% for eu and 0.0% for us")
|
||||
}
|
||||
|
||||
// The dashboard follows the monitor with the oldest data.
|
||||
if _, _, dash := owner.page("/?range=1h"); !strings.Contains(dash, `aria-disabled="true">12h<`) || strings.Contains(dash, `aria-disabled="true">3h<`) {
|
||||
t.Error("dashboard range availability does not follow the data")
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -151,6 +151,9 @@ type agentView struct {
|
||||
Prefix string `json:"prefix"`
|
||||
LastSeenAt *time.Time `json:"last_seen_at"`
|
||||
Release string `json:"release,omitempty"`
|
||||
// AllowPrivate tells whether an organization's checker may check
|
||||
// private addresses; platform checkers follow the platform setting.
|
||||
AllowPrivate *bool `json:"allow_private,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) listAgents(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
@@ -171,6 +174,9 @@ func (s *Server) listAgents(c *gin.Context, scope tenant.Scope, org *uuid.UUID)
|
||||
ID: a.ID, Kind: a.Kind, Name: a.Name, RegionID: a.RegionID, RegionKey: deref(a.RegionKey),
|
||||
RegionName: deref(a.RegionName), Prefix: a.Prefix, LastSeenAt: a.LastSeenAt, Release: deref(a.Release),
|
||||
}
|
||||
if a.Kind == "checker" && a.OrgID != nil {
|
||||
out[i].AllowPrivate = &a.AllowPrivate
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"agents": out})
|
||||
}
|
||||
@@ -179,6 +185,9 @@ type agentRequest struct {
|
||||
Kind string `json:"kind" binding:"required,oneof=checker statuspage"`
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
RegionID *uuid.UUID `json:"region_id"`
|
||||
// AllowPrivate lets an organization's checker check private
|
||||
// addresses; it defaults to true.
|
||||
AllowPrivate *bool `json:"allow_private"`
|
||||
}
|
||||
|
||||
// createAgent creates an agent and returns its token, which is shown once.
|
||||
@@ -193,6 +202,9 @@ func (s *Server) createAgent(c *gin.Context, scope tenant.Scope, org *uuid.UUID)
|
||||
return
|
||||
}
|
||||
tok, params := NewAgentToken(org, req.Kind, req.Name, req.RegionID)
|
||||
if req.AllowPrivate != nil && org != nil {
|
||||
params.AllowPrivate = *req.AllowPrivate
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.Agent
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
@@ -218,7 +230,7 @@ func NewAgentToken(org *uuid.UUID, kind, name string, region *uuid.UUID) (string
|
||||
tok := AgentTokenPrefix + auth.RandomToken()
|
||||
return tok, store.CreateAgentParams{
|
||||
OrgID: org, Kind: kind, Name: name, RegionID: region,
|
||||
TokenHash: HashToken(tok), Prefix: tok[:len(AgentTokenPrefix)+6],
|
||||
TokenHash: HashToken(tok), Prefix: tok[:len(AgentTokenPrefix)+6], AllowPrivate: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
+106
-19
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
@@ -42,6 +43,14 @@ type Server struct {
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
legal *versioned[[]agentapi.LegalDoc]
|
||||
// checkTypes caches the check types switched off platform-wide.
|
||||
checkTypes *versioned[map[string]bool]
|
||||
// checkerNet caches whether platform checkers may reach private
|
||||
// addresses.
|
||||
checkerNet *versioned[bool]
|
||||
// limits caches the platform's default limits.
|
||||
limits *versioned[Limits]
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -59,19 +68,23 @@ func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
db: d.DB,
|
||||
rdb: d.Redis,
|
||||
keys: d.Keys,
|
||||
catalog: d.Catalog,
|
||||
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
|
||||
limiter: auth.NewLimiter(d.Redis),
|
||||
totp: auth.NewTOTPVerifier(d.Redis),
|
||||
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
|
||||
sched: schedule.New(d.Redis),
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
db: d.DB,
|
||||
rdb: d.Redis,
|
||||
keys: d.Keys,
|
||||
catalog: d.Catalog,
|
||||
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
|
||||
limiter: auth.NewLimiter(d.Redis),
|
||||
totp: auth.NewTOTPVerifier(d.Redis),
|
||||
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
|
||||
sched: schedule.New(d.Redis),
|
||||
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
|
||||
checkTypes: newVersioned[map[string]bool]("check-types"),
|
||||
checkerNet: newVersioned[bool]("checker-network"),
|
||||
limits: newVersioned[Limits]("limits"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,14 +94,24 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
// Agents authenticate with tokens and never carry cookies, so they skip
|
||||
// the session and CSRF middleware.
|
||||
s.mountAgentAPI(r)
|
||||
s.mountHeartbeats(r)
|
||||
s.mountAlertmanager(r)
|
||||
|
||||
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF())
|
||||
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")
|
||||
v1.POST("/locale", s.setLocale)
|
||||
v1.POST("/markdown/preview", auth.Require(), s.previewMarkdown)
|
||||
|
||||
a := v1.Group("/auth")
|
||||
a.POST("/signup", s.signup)
|
||||
a.POST("/verify", s.verifyEmail)
|
||||
a.POST("/verify/resend", s.resendVerification)
|
||||
v1.POST("/orgs", auth.Require(), s.createOrg)
|
||||
a.POST("/login", s.login)
|
||||
a.POST("/login/totp", s.loginTOTP)
|
||||
a.POST("/logout", s.logout)
|
||||
@@ -96,30 +119,83 @@ 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)
|
||||
me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
|
||||
me.GET("/audit", s.listMyAudit)
|
||||
me.GET("/export", s.exportAccount)
|
||||
me.POST("/delete", s.deleteAccount)
|
||||
|
||||
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
|
||||
v1.POST("/invitations/:token/signup", s.inviteSignup)
|
||||
|
||||
org := v1.Group("/org", s.orgAccess())
|
||||
org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy)
|
||||
org.GET("/export", sessionOnly(), can(authz.OrgManage), s.exportOrg)
|
||||
org.GET("/legal", can(authz.OrgManage), s.orgListLegal)
|
||||
org.PUT("/legal/:kind", can(authz.OrgManage), s.orgSaveLegal)
|
||||
org.POST("/delete", sessionOnly(), s.deleteOrg)
|
||||
|
||||
org.GET("/monitors", can(authz.MonitorsRead), s.listMonitors)
|
||||
org.POST("/monitors", can(authz.MonitorsWrite), s.createMonitor)
|
||||
org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor)
|
||||
// Monitor and group handlers check permissions themselves: assignments
|
||||
// scoped to a group grant access below that group only.
|
||||
org.GET("/monitors", s.listMonitors)
|
||||
org.POST("/monitors", s.createMonitor)
|
||||
org.PUT("/monitors/:id", s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", s.deleteMonitor)
|
||||
org.GET("/monitors/:id/evidence", s.listEvidence)
|
||||
org.GET("/monitors/:id/results", s.listResults)
|
||||
org.GET("/checkers/:id", s.getChecker)
|
||||
org.GET("/monitors/:id/evidence/:evidence", s.getEvidence)
|
||||
org.GET("/alertmanager/receivers", can(authz.OrgManage), s.listReceivers)
|
||||
org.POST("/alertmanager/receivers", sessionOnly(), can(authz.OrgManage), s.createReceiver)
|
||||
org.DELETE("/alertmanager/receivers/:id", sessionOnly(), can(authz.OrgManage), s.deleteReceiver)
|
||||
org.GET("/alertmanager/alerts", can(authz.MonitorsRead), s.listFiringAlerts)
|
||||
org.GET("/check-types", s.orgCheckTypes)
|
||||
org.GET("/limits", s.getOrgLimits)
|
||||
org.PUT("/check-types", sessionOnly(), can(authz.OrgManage), s.orgSetCheckTypes)
|
||||
org.GET("/maintenance", s.listMaintenance)
|
||||
org.POST("/maintenance", s.createMaintenance)
|
||||
org.PUT("/maintenance/:id", s.updateMaintenance)
|
||||
org.DELETE("/maintenance/:id", s.deleteMaintenance)
|
||||
org.GET("/groups", s.listGroups)
|
||||
org.POST("/groups", s.createGroup)
|
||||
org.PUT("/groups/:id", s.updateGroup)
|
||||
org.DELETE("/groups/:id", s.deleteGroup)
|
||||
|
||||
org.GET("/regions", can(authz.MonitorsRead), s.listOrgRegions)
|
||||
org.GET("/regions", s.listOrgRegions)
|
||||
org.POST("/regions", sessionOnly(), can(authz.OrgManage), s.createOrgRegion)
|
||||
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
|
||||
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
|
||||
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
|
||||
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
|
||||
org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
|
||||
|
||||
admin := v1.Group("/admin", s.requireAdmin())
|
||||
admin.GET("/audit", s.listPlatformAudit)
|
||||
admin.GET("/check-types", s.adminListCheckTypes)
|
||||
admin.PUT("/check-types", s.adminSetCheckTypes)
|
||||
admin.GET("/checker-network", s.adminGetCheckerNetwork)
|
||||
admin.GET("/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)
|
||||
admin.PUT("/orgs/:id/limits", s.adminSetOrgLimits)
|
||||
admin.PUT("/users/:id/limits", s.adminSetUserLimits)
|
||||
admin.GET("/status-pages", s.adminListStatusPages)
|
||||
admin.PUT("/status-pages/:id/suspension", s.adminSuspendStatusPage)
|
||||
admin.DELETE("/status-pages/:id", s.adminDeleteStatusPage)
|
||||
admin.PUT("/orgs/:id/suspension", s.adminSuspendOrg)
|
||||
admin.DELETE("/orgs/:id", s.adminDeleteOrg)
|
||||
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
|
||||
admin.DELETE("/users/:id", s.adminDeleteUser)
|
||||
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
|
||||
admin.GET("/legal", s.adminListLegal)
|
||||
admin.PUT("/legal/:kind", s.adminSaveLegal)
|
||||
admin.GET("/regions", s.adminListRegions)
|
||||
admin.POST("/regions", s.adminCreateRegion)
|
||||
admin.DELETE("/regions/:id", s.adminDeleteRegion)
|
||||
@@ -132,13 +208,23 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
page := org.Group("/statuspages/:id")
|
||||
page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
|
||||
page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
|
||||
page.GET("/groups", canPage(authz.StatusPagesRead), s.listStatusPageGroups)
|
||||
page.POST("/groups", canPage(authz.StatusPagesWrite), s.createStatusPageGroup)
|
||||
page.PUT("/groups/:group_id", canPage(authz.StatusPagesWrite), s.updateStatusPageGroup)
|
||||
page.DELETE("/groups/:group_id", canPage(authz.StatusPagesWrite), s.deleteStatusPageGroup)
|
||||
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
|
||||
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
|
||||
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
|
||||
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
|
||||
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
|
||||
|
||||
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
|
||||
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
|
||||
|
||||
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
|
||||
org.POST("/alert-groups", can(authz.NotificationsWrite), s.saveAlertGroup)
|
||||
org.PUT("/alert-groups/:id", can(authz.NotificationsWrite), s.saveAlertGroup)
|
||||
org.DELETE("/alert-groups/:id", can(authz.NotificationsWrite), s.deleteAlertGroup)
|
||||
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
|
||||
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
|
||||
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
|
||||
@@ -172,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)
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// New accounts confirm their email address before signing in, through a
|
||||
// link mailed to them. One mailbox holds one account, aliases included,
|
||||
// and a client address may create only a few accounts a day.
|
||||
|
||||
const (
|
||||
verifyTTL = 24 * time.Hour
|
||||
// unverifiedKeep is how long an account waits for confirmation.
|
||||
unverifiedKeep = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// emailKey identifies the mailbox behind an address: +suffixes are dropped
|
||||
// everywhere, and Gmail ignores dots and treats googlemail.com as gmail.com.
|
||||
// The migration adding users.email_key computes the same.
|
||||
func emailKey(email string) string {
|
||||
local, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@")
|
||||
if !ok {
|
||||
return strings.ToLower(email)
|
||||
}
|
||||
local, _, _ = strings.Cut(local, "+")
|
||||
if domain == "gmail.com" || domain == "googlemail.com" {
|
||||
local, domain = strings.ReplaceAll(local, ".", ""), "gmail.com"
|
||||
}
|
||||
return local + "@" + domain
|
||||
}
|
||||
|
||||
// clientKey groups client addresses for sign-up limits: IPv6 clients
|
||||
// usually hold a whole /64.
|
||||
func clientKey(ip string) string {
|
||||
a := net.ParseIP(ip)
|
||||
if a == nil || a.To4() != nil {
|
||||
return ip
|
||||
}
|
||||
return a.Mask(net.CIDRMask(64, 128)).String() + "/64"
|
||||
}
|
||||
|
||||
// verificationRequired reports whether new accounts confirm their email.
|
||||
func (s *Server) verificationRequired() bool {
|
||||
switch s.cfg.SignupVerify {
|
||||
case "required":
|
||||
return true
|
||||
case "off":
|
||||
return false
|
||||
}
|
||||
return s.cloud() || s.smtp != nil
|
||||
}
|
||||
|
||||
// signupsLeft reports whether the client may create another account.
|
||||
func (s *Server) signupsLeft(c *gin.Context) (bool, error) {
|
||||
if s.cfg.SignupsPerIP == 0 {
|
||||
return true, nil
|
||||
}
|
||||
n, err := s.rdb.Get(c.Request.Context(), "signups:"+clientKey(c.ClientIP())).Int()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return true, nil
|
||||
}
|
||||
return n < s.cfg.SignupsPerIP, err
|
||||
}
|
||||
|
||||
// countSignup counts a created account against the client's daily limit.
|
||||
func (s *Server) countSignup(c *gin.Context) {
|
||||
if s.cfg.SignupsPerIP == 0 {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
key := "signups:" + clientKey(c.ClientIP())
|
||||
pipe := s.rdb.TxPipeline()
|
||||
pipe.Incr(ctx, key)
|
||||
pipe.ExpireNX(ctx, key, 24*time.Hour)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
s.log.WarnContext(ctx, "counting sign-up failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func verifyKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "verify:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// sendVerification mails u a link that confirms their address.
|
||||
func (s *Server) sendVerification(ctx context.Context, u store.User) error {
|
||||
if s.smtp == nil {
|
||||
return errors.New("api: no mail server to send verification")
|
||||
}
|
||||
token := auth.RandomToken()
|
||||
if err := s.rdb.Set(ctx, verifyKey(token), u.ID.String(), verifyTTL).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
l := s.catalog.Match(deref(u.Locale))
|
||||
link := strings.TrimSuffix(s.cfg.PublicURL, "/") + "/verify?token=" + url.QueryEscape(token)
|
||||
data := map[string]any{"Link": link, "Hours": int(verifyTTL.Hours())}
|
||||
return s.smtp.Send(ctx, notify.Mail{
|
||||
To: []string{u.Email}, Subject: l.T("email.verify.subject", data), Body: l.T("email.verify.body", data),
|
||||
})
|
||||
}
|
||||
|
||||
type verifyRequest struct {
|
||||
Token string `json:"token" binding:"required,max=200"`
|
||||
}
|
||||
|
||||
// verifyEmail confirms the address the token was mailed to and signs the
|
||||
// account in: whoever holds the link controls the mailbox.
|
||||
func (s *Server) verifyEmail(c *gin.Context) {
|
||||
var req verifyRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "verify:ip:"+c.ClientIP(), 30, 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
raw, err := s.rdb.GetDel(ctx, verifyKey(req.Token)).Result()
|
||||
id, perr := uuid.Parse(raw)
|
||||
if errors.Is(err, redis.Nil) || perr != nil {
|
||||
fail(c, http.StatusGone, "verification_expired")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var u store.User
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
u, err = q.MarkEmailVerified(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusGone, "verification_expired")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auditActor(c, u.ID)
|
||||
if u.DisabledAt != nil {
|
||||
fail(c, http.StatusForbidden, "account_suspended")
|
||||
return
|
||||
}
|
||||
s.finishLogin(c, u.ID, auth.MethodPassword)
|
||||
}
|
||||
|
||||
type resendRequest struct {
|
||||
Email string `json:"email" binding:"required,email,max=320"`
|
||||
}
|
||||
|
||||
// resendVerification mails a new link to an unconfirmed account. It
|
||||
// answers the same whether or not such an account exists.
|
||||
func (s *Server) resendVerification(c *gin.Context) {
|
||||
var req resendRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
email := normalizeEmail(req.Email)
|
||||
if !s.limit(c, "resend:ip:"+c.ClientIP(), 10, time.Hour) || !s.limit(c, "resend:email:"+email, 3, time.Hour) {
|
||||
return
|
||||
}
|
||||
var u store.User
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
u, err = q.GetUserByEmail(ctx, email)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
case u.EmailVerifiedAt == nil && u.DisabledAt == nil:
|
||||
if err := s.sendVerification(ctx, u); err != nil {
|
||||
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
|
||||
}
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type createOrgRequest struct {
|
||||
Name string `json:"name" binding:"required,max=200"`
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
}
|
||||
|
||||
// createOrg creates an organization owned by the signed-in account and
|
||||
// makes it the active one.
|
||||
func (s *Server) createOrg(c *gin.Context) {
|
||||
var req createOrgRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
sess := auth.Current(c)
|
||||
ctx := c.Request.Context()
|
||||
u, err := s.loadUser(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
max := s.platformLimits(ctx).OrgsPerAccount
|
||||
if u.LimitOrgs != nil {
|
||||
max = int(*u.LimitOrgs)
|
||||
}
|
||||
orgID := uuid.New()
|
||||
err = s.db.Tx(ctx, tenant.Org(orgID, sess.UserID), func(q *store.Queries) error {
|
||||
if max > 0 {
|
||||
// Serialize the account's creations to count them reliably.
|
||||
if err := q.LockOrgUsage(ctx, u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := q.CountOwnedOrgs(ctx, u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n >= int64(max) {
|
||||
return limitError{"org_limit", max}
|
||||
}
|
||||
}
|
||||
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(strings.TrimSpace(req.Slug)), Name: strings.TrimSpace(req.Name)}); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: u.ID, IsOwner: true})
|
||||
})
|
||||
switch {
|
||||
case failLimit(c, err):
|
||||
return
|
||||
case isUniqueViolation(err, "orgs_slug_key"):
|
||||
fail(c, http.StatusConflict, "slug_taken")
|
||||
return
|
||||
case isCheckViolation(err):
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
|
||||
return
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auditOrg(c, orgID)
|
||||
if err := s.sessions.SwitchOrg(ctx, sess, orgID); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"id": orgID, "slug": strings.ToLower(strings.TrimSpace(req.Slug)), "redirect": "/"})
|
||||
}
|
||||
|
||||
// signupClosedWithoutMail tells whether sign-up must wait for a mail
|
||||
// server: accounts need confirming but no link could be sent.
|
||||
func (s *Server) signupClosedWithoutMail() bool {
|
||||
return s.verificationRequired() && s.smtp == nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
var verifyLink = regexp.MustCompile(`/verify\?token=([A-Za-z0-9_\-]+)`)
|
||||
|
||||
func TestVerifiedSignup(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.SMTPURL, c.SignupVerify, c.SignupsPerIP = mail.URL(), "auto", 2
|
||||
})
|
||||
// mailFor waits for the n-th mail and returns its confirmation token.
|
||||
tokenOf := func(n int, to string) string {
|
||||
t.Helper()
|
||||
waitFor(t, 5*time.Second, "the confirmation mail", func() bool { return len(mail.Messages()) >= n })
|
||||
msg := mail.Messages()[n-1]
|
||||
if !strings.Contains(strings.Join(msg.To, ","), to) {
|
||||
t.Fatalf("mail %d went to %v, want %s", n, msg.To, to)
|
||||
}
|
||||
m := verifyLink.FindStringSubmatch(msg.Data)
|
||||
if m == nil {
|
||||
t.Fatalf("mail lacks the link: %s", msg.Data)
|
||||
}
|
||||
return m[1]
|
||||
}
|
||||
box := uniq("max.power")
|
||||
email := strings.ToUpper(box[:1]) + box[1:] + "+uptime@googlemail.com"
|
||||
lower := strings.ToLower(email)
|
||||
|
||||
// Signing up mails a link instead of signing in.
|
||||
b := e.browser(t)
|
||||
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{"email": email, "password": testPassword, "display_name": "Max"})
|
||||
if st != http.StatusOK || body["status"] != "verification_sent" {
|
||||
t.Fatalf("signup = %d %v", st, body)
|
||||
}
|
||||
if st, _ := b.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
|
||||
t.Errorf("signed in before confirming: %d", st)
|
||||
}
|
||||
token := tokenOf(1, lower)
|
||||
|
||||
// Unconfirmed accounts cannot sign in; only the right password says why.
|
||||
st, body = e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": testPassword})
|
||||
expect(t, "sign-in before confirming", st, body, http.StatusForbidden, "email_unverified")
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "wrong password"}); st != http.StatusUnauthorized {
|
||||
t.Error("a wrong password reveals the missing confirmation")
|
||||
}
|
||||
|
||||
// The same mailbox under another address is refused.
|
||||
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": strings.ReplaceAll(box, ".", "") + "@gmail.com", "password": testPassword})
|
||||
expect(t, "alias of an existing account", st, body, http.StatusConflict, "email_taken")
|
||||
|
||||
// Resending answers alike for unknown addresses and mails only real ones.
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": "nobody@" + uniq("x") + ".test"}); st != http.StatusNoContent {
|
||||
t.Errorf("resend for unknown = %d", st)
|
||||
}
|
||||
if st, _ := e.browser(t).do("POST", "/api/v1/auth/verify/resend", map[string]any{"email": email}); st != http.StatusNoContent {
|
||||
t.Errorf("resend = %d", st)
|
||||
}
|
||||
tokenOf(2, lower)
|
||||
if n := len(mail.Messages()); n != 2 {
|
||||
t.Errorf("%d mails, want 2", n)
|
||||
}
|
||||
|
||||
// The link page asks before confirming; confirming signs in once.
|
||||
if _, _, html := b.page("/verify?token=" + token); !strings.Contains(html, `name="token"`) {
|
||||
t.Error("the link page lacks its form")
|
||||
}
|
||||
if st, body := b.do("POST", "/api/v1/auth/verify", map[string]any{"token": token}); st != http.StatusOK {
|
||||
t.Fatalf("verify = %d %v", st, body)
|
||||
}
|
||||
st, body = e.browser(t).do("POST", "/api/v1/auth/verify", map[string]any{"token": token})
|
||||
expect(t, "token used twice", st, body, http.StatusGone, "verification_expired")
|
||||
|
||||
// Without an organization, the console asks for one.
|
||||
if got := b.visit("/"); got.Path != "/orgs/new" {
|
||||
t.Errorf("dashboard leads to %s, want /orgs/new", got.Path)
|
||||
}
|
||||
slug := uniq("max-")
|
||||
if st, body := b.do("POST", "/api/v1/orgs", map[string]any{"name": "Max Corp", "slug": slug}); st != http.StatusCreated {
|
||||
t.Fatalf("create org = %d %v", st, body)
|
||||
}
|
||||
if got := b.visit("/"); got.Path != "/" {
|
||||
t.Errorf("dashboard leads to %s after creating an organization", got.Path)
|
||||
}
|
||||
_, me := b.do("GET", "/api/v1/me", nil)
|
||||
if !strings.Contains(mustJSON(me), slug) {
|
||||
t.Errorf("me lacks the new organization: %v", me)
|
||||
}
|
||||
|
||||
// The account limit on organizations.
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(context.Background(), `UPDATE users SET limit_orgs = 1 WHERE email = $1`, lower)
|
||||
return err
|
||||
})
|
||||
st, body = b.do("POST", "/api/v1/orgs", map[string]any{"name": "Second", "slug": uniq("max2-")})
|
||||
expect(t, "second organization", st, body, http.StatusUnprocessableEntity, "org_limit")
|
||||
|
||||
// Two accounts per client address and day; refused sign-ups do not count.
|
||||
if st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "two@" + uniq("x") + ".test", "password": testPassword}); st != http.StatusOK {
|
||||
t.Fatalf("second account = %d %v", st, body)
|
||||
}
|
||||
st, body = e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "three@" + uniq("x") + ".test", "password": testPassword})
|
||||
expect(t, "third account", st, body, http.StatusTooManyRequests, "signup_limit")
|
||||
|
||||
// Unconfirmed accounts go after a week.
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(context.Background(), `UPDATE users SET created_at = now() - interval '8 days' WHERE email_verified_at IS NULL AND email LIKE 'two@%'`)
|
||||
return err
|
||||
})
|
||||
if err := e.api.Housekeep(context.Background(), time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var left int
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
return tx.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE email LIKE 'two@%' AND created_at < now() - interval '7 days'`).Scan(&left)
|
||||
})
|
||||
if left != 0 {
|
||||
t.Error("an unconfirmed account outlived its week")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupNeedsMail(t *testing.T) {
|
||||
e := newEnvWith(t, func(c *config.API) { c.SignupVerify = "required" })
|
||||
st, body := e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{"email": "a@" + uniq("x") + ".test", "password": testPassword})
|
||||
expect(t, "sign-up without a mail server", st, body, http.StatusForbidden, "signup_closed")
|
||||
}
|
||||
+18
-1
@@ -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 {
|
||||
@@ -255,7 +262,7 @@ func (s *Server) ssoCallback(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if user.DisabledAt != nil {
|
||||
s.ssoAbort(c, uuid.Nil, "invalid_credentials")
|
||||
s.ssoAbort(c, uuid.Nil, "account_suspended")
|
||||
return
|
||||
}
|
||||
if old := auth.Current(c); old != nil {
|
||||
@@ -273,6 +280,9 @@ func (s *Server) ssoCallback(c *gin.Context) {
|
||||
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, "/")
|
||||
}
|
||||
|
||||
@@ -316,10 +326,17 @@ func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl s
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
// Another address of the same mailbox has an account.
|
||||
if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken {
|
||||
code = "sso_link_required"
|
||||
return err
|
||||
}
|
||||
// The identity provider confirmed the address.
|
||||
u, err := q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: email,
|
||||
DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
|
||||
Locale: ptr(i18n.Lang(ctx)),
|
||||
EmailKey: ptr(emailKey(email)), EmailVerifiedAt: ptr(time.Now()),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
// pageGroupTree organizes one status page's nested groups in display order.
|
||||
type pageGroupTree struct {
|
||||
byID map[uuid.UUID]store.StatusPageGroup
|
||||
children map[uuid.UUID][]uuid.UUID
|
||||
roots []uuid.UUID
|
||||
}
|
||||
|
||||
func newPageGroupTree(groups []store.StatusPageGroup) pageGroupTree {
|
||||
t := pageGroupTree{
|
||||
byID: make(map[uuid.UUID]store.StatusPageGroup, len(groups)),
|
||||
children: map[uuid.UUID][]uuid.UUID{},
|
||||
}
|
||||
for _, g := range groups {
|
||||
t.byID[g.ID] = g
|
||||
}
|
||||
for _, g := range groups {
|
||||
if g.ParentID != nil {
|
||||
if _, ok := t.byID[*g.ParentID]; ok {
|
||||
t.children[*g.ParentID] = append(t.children[*g.ParentID], g.ID)
|
||||
continue
|
||||
}
|
||||
}
|
||||
t.roots = append(t.roots, g.ID)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (t pageGroupTree) walk(fn func(g store.StatusPageGroup, depth int)) {
|
||||
var visit func(ids []uuid.UUID, depth int)
|
||||
visit = func(ids []uuid.UUID, depth int) {
|
||||
for _, id := range ids {
|
||||
fn(t.byID[id], depth)
|
||||
visit(t.children[id], depth+1)
|
||||
}
|
||||
}
|
||||
visit(t.roots, 0)
|
||||
}
|
||||
|
||||
type pageGroupView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ParentID *uuid.UUID `json:"parent_id"`
|
||||
Position int32 `json:"position"`
|
||||
}
|
||||
|
||||
type pageGroupRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
ParentID *uuid.UUID `json:"parent_id"`
|
||||
Position int32 `json:"position"`
|
||||
}
|
||||
|
||||
func pageGroupError(c *gin.Context, err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if !errors.As(err, &pgErr) {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case pgErr.ConstraintName == "status_page_groups_cycle", pgErr.ConstraintName == "status_page_groups_check":
|
||||
fail(c, http.StatusUnprocessableEntity, "group_cycle")
|
||||
case pgErr.ConstraintName == "status_page_groups_depth":
|
||||
fail(c, http.StatusUnprocessableEntity, "group_too_deep")
|
||||
case pgErr.Code == "23503":
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) listStatusPageGroups(c *gin.Context) {
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var groups []store.StatusPageGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
groups, err = q.ListStatusPageGroups(ctx, pageID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]pageGroupView, 0, len(groups))
|
||||
newPageGroupTree(groups).walk(func(g store.StatusPageGroup, _ int) {
|
||||
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{"groups": out})
|
||||
}
|
||||
|
||||
func (s *Server) createStatusPageGroup(c *gin.Context) {
|
||||
var req pageGroupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var g store.StatusPageGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
g, err = q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
||||
PageID: pageID,
|
||||
OrgID: p.Org.ID,
|
||||
ParentID: req.ParentID,
|
||||
Name: req.Name,
|
||||
Position: req.Position,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if pageGroupError(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
}
|
||||
|
||||
func (s *Server) updateStatusPageGroup(c *gin.Context) {
|
||||
groupID, err := uuid.Parse(c.Param("group_id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req pageGroupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var g store.StatusPageGroup
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
g, err = q.UpdateStatusPageGroup(ctx, store.UpdateStatusPageGroupParams{
|
||||
ID: groupID,
|
||||
PageID: pageID,
|
||||
Name: req.Name,
|
||||
ParentID: req.ParentID,
|
||||
Position: req.Position,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if pageGroupError(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
}
|
||||
|
||||
// deleteStatusPageGroup moves child groups and monitors up to the deleted
|
||||
// group's parent before removing the group.
|
||||
func (s *Server) deleteStatusPageGroup(c *gin.Context) {
|
||||
groupID, err := uuid.Parse(c.Param("group_id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
groups, err := q.ListStatusPageGroups(ctx, pageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target, ok := newPageGroupTree(groups).byID[groupID]
|
||||
if !ok {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
if err := q.ReparentStatusPageGroupChildren(ctx, store.ReparentStatusPageGroupChildrenParams{
|
||||
PageID: pageID, ParentID: &groupID, ParentID_2: target.ParentID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.ReparentStatusPageGroupMonitors(ctx, store.ReparentStatusPageGroupMonitorsParams{
|
||||
PageID: pageID, GroupID: &groupID, GroupID_2: target.ParentID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := q.DeleteStatusPageGroup(ctx, store.DeleteStatusPageGroupParams{ID: groupID, PageID: pageID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// importStatusPageGroups copies the organization's monitor group hierarchy
|
||||
// onto the status page and maps the page's monitors into those groups. When
|
||||
// the page already lists monitors, only groups containing those monitors (and
|
||||
// their ancestors) are imported; otherwise the full monitor group tree is
|
||||
// copied as a starting layout.
|
||||
func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var created []store.StatusPageGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
orgGroups, err := q.ListGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listed, err := q.StatusPageMonitors(ctx, pageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tree := newGroupTree(orgGroups)
|
||||
needed := map[uuid.UUID]bool{}
|
||||
if len(listed) == 0 {
|
||||
for id := range tree.byID {
|
||||
needed[id] = true
|
||||
}
|
||||
} else {
|
||||
for _, m := range listed {
|
||||
for cur := m.MonitorGroupID; cur != nil; {
|
||||
g, ok := tree.byID[*cur]
|
||||
if !ok || needed[g.ID] {
|
||||
break
|
||||
}
|
||||
needed[g.ID] = true
|
||||
cur = g.ParentID
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
mapped := map[uuid.UUID]store.StatusPageGroup{}
|
||||
var createErr error
|
||||
posByParent := map[uuid.UUID]int32{}
|
||||
tree.walk(func(g store.MonitorGroup, _ int) {
|
||||
if createErr != nil || !needed[g.ID] {
|
||||
return
|
||||
}
|
||||
var parentKey uuid.UUID
|
||||
var parentID *uuid.UUID
|
||||
if g.ParentID != nil {
|
||||
if parent, ok := mapped[*g.ParentID]; ok {
|
||||
pid := parent.ID
|
||||
parentID = &pid
|
||||
parentKey = pid
|
||||
}
|
||||
}
|
||||
pos := posByParent[parentKey]
|
||||
posByParent[parentKey] = pos + 1
|
||||
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
||||
PageID: pageID,
|
||||
OrgID: p.Org.ID,
|
||||
ParentID: parentID,
|
||||
Name: g.Name,
|
||||
Position: pos,
|
||||
})
|
||||
if err != nil {
|
||||
createErr = err
|
||||
return
|
||||
}
|
||||
mapped[g.ID] = row
|
||||
created = append(created, row)
|
||||
})
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
}
|
||||
for _, m := range listed {
|
||||
var gid *uuid.UUID
|
||||
section := ""
|
||||
if m.MonitorGroupID != nil {
|
||||
if g, ok := mapped[*m.MonitorGroupID]; ok {
|
||||
id := g.ID
|
||||
gid = &id
|
||||
section = g.Name
|
||||
}
|
||||
}
|
||||
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
|
||||
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]pageGroupView, 0, len(created))
|
||||
for _, g := range created {
|
||||
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"groups": out})
|
||||
}
|
||||
|
||||
// resolvePageMonitorGroup returns the status page group ID and section label
|
||||
// for a component entry, creating a top-level group when a legacy caller passes
|
||||
// only section.
|
||||
func resolvePageMonitorGroup(
|
||||
ctx context.Context,
|
||||
q *store.Queries,
|
||||
pageID, orgID uuid.UUID,
|
||||
m pageMonitor,
|
||||
groupsByID map[uuid.UUID]store.StatusPageGroup,
|
||||
topByName map[string]store.StatusPageGroup,
|
||||
nextPos *int32,
|
||||
) (*uuid.UUID, string, error) {
|
||||
if m.GroupID != nil {
|
||||
if g, ok := groupsByID[*m.GroupID]; ok {
|
||||
return m.GroupID, g.Name, nil
|
||||
}
|
||||
// Let the database foreign key reject unknown or foreign group IDs.
|
||||
return m.GroupID, strings.TrimSpace(m.Section), nil
|
||||
}
|
||||
sec := strings.TrimSpace(m.Section)
|
||||
if sec == "" {
|
||||
return nil, "", nil
|
||||
}
|
||||
if g, ok := topByName[sec]; ok {
|
||||
id := g.ID
|
||||
return &id, g.Name, nil
|
||||
}
|
||||
g, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
||||
PageID: pageID,
|
||||
OrgID: orgID,
|
||||
Name: sec,
|
||||
Position: *nextPos,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
*nextPos++
|
||||
groupsByID[g.ID] = g
|
||||
topByName[sec] = g
|
||||
id := g.ID
|
||||
return &id, g.Name, nil
|
||||
}
|
||||
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user