Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

feat(hub): add API keys settings page (#2786)

henrygd79ad5c83bf98
diff --git a/internal/hub/api.go b/internal/hub/api.go
index df79fe47b..976692fb6 100644
--- a/internal/hub/api.go
+++ b/internal/hub/api.go
@@ -205,6 +205,9 @@ func (h *Hub) registerApiRoutes(se *core.ServeEvent) error {
// get, create, or delete universal tokens (POST keeps tokens out of URLs; GET is kept for legacy clients)
apiAuth.GET("/universal-token", h.handleUniversalToken).BindFunc(excludeReadOnlyRole)
apiAuth.POST("/universal-token", h.handleUniversalToken).BindFunc(excludeReadOnlyRole)
+ // create static API keys for the current user, or revoke all of them
+ apiAuth.POST("/api-keys", createApiKey).BindFunc(requireSessionToken)
+ apiAuth.POST("/api-keys/revoke", revokeApiKeys).BindFunc(requireSessionToken)
// update / delete user alerts
apiAuth.POST("/user-alerts", alerts.UpsertUserAlerts)
apiAuth.DELETE("/user-alerts", alerts.DeleteUserAlerts)
diff --git a/internal/hub/api_keys.go b/internal/hub/api_keys.go
new file mode 100644
index 000000000..d433b220d
--- /dev/null
+++ b/internal/hub/api_keys.go
@@ -0,0 +1,102 @@
+package hub
+
+import (
+ "net/http"
+ "strings"
+ "time"
+
+ "ganigeorgiev.com/pocketbase/pocketbase/core"
+ "ganigeorgiev.com/pocketbase/pocketbase/tools/security"
+ "github.com/spf13/cast"
+)
+
+// Limits for the lifetime of user-generated API keys.
+const (
+ apiKeyMinDuration = time.Hour
+ apiKeyMaxDuration = 366 * 24 * time.Hour
+ // JWTs require an expiration, so keys that "never expire" get one far in the future
+ apiKeyNoExpiryDuration = 100 * 365 * 24 * time.Hour
+)
+
+// requireSessionToken allows only regular user login sessions, so a static
+// API key can't mint new keys (extending its own lifetime indefinitely) or
+// trade itself for a refreshable session token via revocation.
+//
+// Static tokens (from this API or PocketBase impersonation) carry
+// refreshable=false; tokens from a normal login carry refreshable=true.
+func requireSessionToken(e *core.RequestEvent) error {
+ if e.Auth == nil {
+ return e.UnauthorizedError("The request requires valid record authorization token.", nil)
+ }
+ if e.Auth.Collection().Name != "users" {
+ return e.ForbiddenError("Only users can manage API keys.", nil)
+ }
+ token := strings.TrimPrefix(e.Request.Header.Get("Authorization"), "Bearer ")
+ if token == "" {
+ return e.ForbiddenError("API keys can only be managed from a logged in session.", nil)
+ }
+ // verify the token itself rather than trusting e.Auth, which may have been
+ // set by AUTO_LOGIN or TRUSTED_AUTH_HEADER independently of the token
+ record, err := e.App.FindAuthRecordByToken(token, core.TokenTypeAuth)
+ if err != nil || record.Id != e.Auth.Id || record.Collection().Id != e.Auth.Collection().Id {
+ return e.ForbiddenError("API keys can only be managed from a logged in session.", nil)
+ }
+ claims, _ := security.ParseUnverifiedJWT(token)
+ if !cast.ToBool(claims[core.TokenClaimRefreshable]) {
+ return e.ForbiddenError("API keys can't be used to manage API keys.", nil)
+ }
+ return e.Next()
+}
+
+// createApiKey handles POST /api/beszel/api-keys. It returns a static,
+// non-refreshable auth token for the current user with the requested duration
+// (in seconds), or effectively no expiration if noExpiry is set. The token has
+// the same permissions as the user. The response's expires is empty for keys
+// that don't expire.
+func createApiKey(e *core.RequestEvent) error {
+ var body struct {
+ Duration int64 `json:"duration"`
+ NoExpiry bool `json:"noExpiry"`
+ }
+ if err := e.BindBody(&body); err != nil {
+ return e.BadRequestError("Invalid request body.", err)
+ }
+ duration := time.Duration(body.Duration) * time.Second
+ if body.NoExpiry {
+ duration = apiKeyNoExpiryDuration
+ } else if duration < apiKeyMinDuration || duration > apiKeyMaxDuration {
+ return e.BadRequestError("Duration must be between one hour and 366 days.", nil)
+ }
+ token, err := e.Auth.NewStaticAuthToken(duration)
+ if err != nil {
+ return e.InternalServerError("Failed to generate API key.", err)
+ }
+ expires := ""
+ if !body.NoExpiry {
+ expires = time.Now().Add(duration).UTC().Format(time.RFC3339)
+ }
+ return e.JSON(http.StatusOK, map[string]any{
+ "token": token,
+ "expires": expires,
+ })
+}
+
+// revokeApiKeys handles POST /api/beszel/api-keys/revoke. It rotates the
+// user's token key, which invalidates every token issued to the user (API keys
+// and login sessions alike), and returns a fresh session token so the caller
+// stays logged in.
+func revokeApiKeys(e *core.RequestEvent) error {
+ user, err := e.App.FindRecordById(e.Auth.Collection(), e.Auth.Id)
+ if err != nil {
+ return e.NotFoundError("", err)
+ }
+ user.RefreshTokenKey()
+ if err := e.App.Save(user); err != nil {
+ return e.InternalServerError("Failed to revoke API keys.", err)
+ }
+ token, err := user.NewAuthToken()
+ if err != nil {
+ return e.InternalServerError("Failed to generate auth token.", err)
+ }
+ return e.JSON(http.StatusOK, map[string]string{"token": token})
+}
diff --git a/internal/hub/api_keys_test.go b/internal/hub/api_keys_test.go
new file mode 100644
index 000000000..090254196
--- /dev/null
+++ b/internal/hub/api_keys_test.go
@@ -0,0 +1,161 @@
+//go:build testing
+
+package hub_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "ganigeorgiev.com/pocketbase/pocketbase/tools/security"
+ beszelTests "github.com/henrygd/beszel/internal/tests"
+ "github.com/stretchr/testify/require"
+)
+
+func apiKeysRequest(handler http.Handler, method, path, token string, body any) *httptest.ResponseRecorder {
+ var req *http.Request
+ if body != nil {
+ req = httptest.NewRequest(method, path, jsonReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ } else {
+ req = httptest.NewRequest(method, path, nil)
+ }
+ if token != "" {
+ req.Header.Set("Authorization", token)
+ }
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, req)
+ return recorder
+}
+
+func createApiKeyForTest(t *testing.T, handler http.Handler, sessionToken string, duration int64) string {
+ t.Helper()
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", sessionToken, map[string]any{"duration": duration})
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var data struct {
+ Token string `json:"token"`
+ Expires string `json:"expires"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &data))
+ require.NotEmpty(t, data.Token)
+ expires, err := time.Parse(time.RFC3339, data.Expires)
+ require.NoError(t, err)
+ require.WithinDuration(t, time.Now().Add(time.Duration(duration)*time.Second), expires, time.Minute)
+ return data.Token
+}
+
+func TestApiKeys(t *testing.T) {
+ hub, handler := firstUserTestMux(t)
+ t.Cleanup(hub.Cleanup)
+
+ user, err := beszelTests.CreateUserWithRole(hub, "[email protected]", "password123", "user")
+ require.NoError(t, err)
+ // the users authRule requires verified=true for auth-refresh
+ user.SetVerified(true)
+ require.NoError(t, hub.Save(user))
+ readonly, err := beszelTests.CreateUserWithRole(hub, "[email protected]", "password123", "readonly")
+ require.NoError(t, err)
+ superuser, err := beszelTests.CreateSuperuser(hub, "[email protected]", "password123")
+ require.NoError(t, err)
+
+ sessionToken, err := user.NewAuthToken()
+ require.NoError(t, err)
+
+ t.Run("requires auth", func(t *testing.T) {
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", "", map[string]any{"duration": 3600})
+ require.Equal(t, http.StatusUnauthorized, res.Code)
+ res = apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys/revoke", "", nil)
+ require.Equal(t, http.StatusUnauthorized, res.Code)
+ })
+
+ t.Run("rejects invalid durations", func(t *testing.T) {
+ for _, duration := range []int64{0, -1, 60, 367 * 24 * 3600} {
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", sessionToken, map[string]any{"duration": duration})
+ require.Equal(t, http.StatusBadRequest, res.Code, "duration %d", duration)
+ }
+ })
+
+ t.Run("no expiry", func(t *testing.T) {
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", sessionToken, map[string]any{"noExpiry": true})
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var data struct {
+ Token string `json:"token"`
+ Expires string `json:"expires"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &data))
+ require.Empty(t, data.Expires)
+
+ claims, err := security.ParseUnverifiedJWT(data.Token)
+ require.NoError(t, err)
+ exp, err := claims.GetExpirationTime()
+ require.NoError(t, err)
+ require.True(t, exp.After(time.Now().Add(99*365*24*time.Hour)), "exp %v", exp)
+
+ res = apiKeysRequest(handler, http.MethodGet, "/api/beszel/info", data.Token, nil)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ })
+
+ t.Run("rejects superusers", func(t *testing.T) {
+ superuserToken, err := superuser.NewAuthToken()
+ require.NoError(t, err)
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", superuserToken, map[string]any{"duration": 3600})
+ require.Equal(t, http.StatusForbidden, res.Code)
+ })
+
+ t.Run("readonly users can create keys", func(t *testing.T) {
+ readonlyToken, err := readonly.NewAuthToken()
+ require.NoError(t, err)
+ createApiKeyForTest(t, handler, readonlyToken, 3600)
+ })
+
+ t.Run("key authenticates as the user and can't be refreshed or mint keys", func(t *testing.T) {
+ apiKey := createApiKeyForTest(t, handler, sessionToken, 30*24*3600)
+
+ res := apiKeysRequest(handler, http.MethodGet, "/api/beszel/info", apiKey, nil)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+
+ // auth-refresh returns the same static token instead of a refreshable one
+ res = apiKeysRequest(handler, http.MethodPost, "/api/collections/users/auth-refresh", apiKey, nil)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var refreshed struct {
+ Token string `json:"token"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &refreshed))
+ require.Equal(t, apiKey, refreshed.Token)
+
+ res = apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", apiKey, map[string]any{"duration": 3600})
+ require.Equal(t, http.StatusForbidden, res.Code)
+ res = apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys/revoke", apiKey, nil)
+ require.Equal(t, http.StatusForbidden, res.Code)
+
+ // impersonation tokens are static too
+ impersonateToken, err := user.NewStaticAuthToken(time.Hour)
+ require.NoError(t, err)
+ res = apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys", impersonateToken, map[string]any{"duration": 3600})
+ require.Equal(t, http.StatusForbidden, res.Code)
+ })
+
+ t.Run("revoke invalidates existing tokens and returns a working session", func(t *testing.T) {
+ apiKey := createApiKeyForTest(t, handler, sessionToken, 3600)
+
+ res := apiKeysRequest(handler, http.MethodPost, "/api/beszel/api-keys/revoke", sessionToken, nil)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var data struct {
+ Token string `json:"token"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &data))
+ require.NotEmpty(t, data.Token)
+
+ for _, oldToken := range []string{apiKey, sessionToken} {
+ res = apiKeysRequest(handler, http.MethodGet, "/api/beszel/info", oldToken, nil)
+ require.Equal(t, http.StatusUnauthorized, res.Code)
+ }
+
+ res = apiKeysRequest(handler, http.MethodGet, "/api/beszel/info", data.Token, nil)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ // the new session token can create keys again
+ createApiKeyForTest(t, handler, data.Token, 3600)
+ })
+}
diff --git a/internal/site/src/components/routes/settings/api-keys.tsx b/internal/site/src/components/routes/settings/api-keys.tsx
new file mode 100644
index 000000000..8f0e309a9
--- /dev/null
+++ b/internal/site/src/components/routes/settings/api-keys.tsx
@@ -0,0 +1,220 @@
+import { t } from "@lingui/core/macro"
+import { Trans, useLingui } from "@lingui/react/macro"
+import { KeyRoundIcon, LoaderCircleIcon, ShieldXIcon } from "lucide-react"
+import { useState } from "react"
+import { TokenValue } from "@/components/token-value"
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog"
+import { Button, buttonVariants } from "@/components/ui/button"
+import { Label } from "@/components/ui/label"
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
+import { Separator } from "@/components/ui/separator"
+import { toast } from "@/components/ui/use-toast"
+import { pb } from "@/lib/api"
+import { cn, getHubURL } from "@/lib/utils"
+
+const DAY = 24 * 60 * 60
+const NEVER = "never"
+
+function showError(error: unknown) {
+ toast({
+ title: t`Error`,
+ description: (error as Error).message,
+ variant: "destructive",
+ })
+}
+
+export default function ApiKeysSettings() {
+ return (
+ <div>
+ <div>
+ <h3 className="text-xl font-medium mb-2">
+ <Trans>API Keys</Trans>
+ </h3>
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ <Trans>
+ API keys let scripts and integrations use the Beszel API as your user. A key has the same access as your
+ account and works until it expires or is revoked.
+ </Trans>
+ </p>
+ </div>
+ <Separator className="my-4" />
+ <SectionCreate />
+ <Separator className="my-5" />
+ <SectionRevoke />
+ </div>
+ )
+}
+
+function SectionCreate() {
+ const { t } = useLingui()
+ const [duration, setDuration] = useState(String(30 * DAY))
+ const [isLoading, setIsLoading] = useState(false)
+ const [created, setCreated] = useState<{ token: string; expires: string } | null>(null)
+
+ const durations = [
+ { value: DAY, label: t`1 day` },
+ { value: 7 * DAY, label: t`7 days` },
+ { value: 30 * DAY, label: t`30 days` },
+ { value: 90 * DAY, label: t`90 days` },
+ { value: 365 * DAY, label: t`1 year` },
+ { value: NEVER, label: t`Never` },
+ ]
+
+ async function createKey() {
+ setIsLoading(true)
+ try {
+ const data = await pb.send<{ token: string; expires: string }>("/api/beszel/api-keys", {
+ method: "POST",
+ body: duration === NEVER ? { noExpiry: true } : { duration: Number(duration) },
+ })
+ setCreated(data)
+ } catch (error) {
+ showError(error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const expires = created?.expires
+ ? new Date(created.expires).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })
+ : ""
+
+ return (
+ <div>
+ <h4 className="text-lg font-medium mb-2">
+ <Trans>Create API key</Trans>
+ </h4>
+ <div className="flex flex-wrap items-end gap-3">
+ <div className="grid gap-2">
+ <Label htmlFor="api-key-duration">
+ <Trans>Expires after</Trans>
+ </Label>
+ <Select value={duration} onValueChange={setDuration}>
+ <SelectTrigger id="api-key-duration" className="w-44">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {durations.map(({ value, label }) => (
+ <SelectItem key={value} value={String(value)}>
+ {label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <Button type="button" className="flex items-center gap-1" onClick={createKey} disabled={isLoading}>
+ {isLoading ? (
+ <LoaderCircleIcon className="size-4 me-0.5 animate-spin" />
+ ) : (
+ <KeyRoundIcon className="size-4 me-0.5" />
+ )}
+ <Trans>Create API key</Trans>
+ </Button>
+ </div>
+ {created && (
+ <div className="mt-4 border rounded-md px-4 py-3 max-w-full grid gap-2">
+ <p className="text-sm font-medium">
+ <Trans>Copy this key now. It won't be shown again.</Trans>
+ </p>
+ <TokenValue key={created.token} token={created.token} label={t`API key`} />
+ {expires && (
+ <p className="text-sm text-muted-foreground">
+ <Trans>Expires {expires}</Trans>
+ </p>
+ )}
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ <Trans>
+ Send the key in the <code className="bg-muted rounded-sm px-1 text-primary">Authorization</code> header of
+ each request:
+ </Trans>
+ </p>
+ <code
+ dir="ltr"
+ className="block bg-muted rounded-sm px-2 py-1.5 text-xs font-mono overflow-x-auto whitespace-nowrap"
+ >
+ curl -H "Authorization: $BESZEL_API_KEY" {getHubURL()}/api/collections/systems/records
+ </code>
+ </div>
+ )}
+ </div>
+ )
+}
+
+function SectionRevoke() {
+ const [open, setOpen] = useState(false)
+ const [isLoading, setIsLoading] = useState(false)
+
+ async function revokeKeys() {
+ setIsLoading(true)
+ try {
+ const { token } = await pb.send<{ token: string }>("/api/beszel/api-keys/revoke", { method: "POST" })
+ // the old session token is now invalid, so keep this tab logged in with the new one
+ pb.authStore.save(token, pb.authStore.record)
+ // reload so realtime subscriptions reconnect with the new token
+ window.location.reload()
+ } catch (error) {
+ showError(error)
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <div>
+ <h4 className="text-lg font-medium mb-2">
+ <Trans>Revoke API keys</Trans>
+ </h4>
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ <Trans>
+ Revoking invalidates all of your API keys and signs you out of other devices. Changing your password has the
+ same effect.
+ </Trans>
+ </p>
+ <Button
+ type="button"
+ variant="destructive"
+ className="mt-3 flex items-center gap-1"
+ onClick={() => setOpen(true)}
+ disabled={isLoading}
+ >
+ {isLoading ? (
+ <LoaderCircleIcon className="size-4 me-0.5 animate-spin" />
+ ) : (
+ <ShieldXIcon className="size-4 me-0.5" />
+ )}
+ <Trans>Revoke all API keys</Trans>
+ </Button>
+ <AlertDialog open={open} onOpenChange={setOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ <Trans>Revoke all API keys?</Trans>
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ <Trans>
+ Every API key you have created will stop working immediately, and you will be signed out of other
+ devices.
+ </Trans>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>
+ <Trans>Cancel</Trans>
+ </AlertDialogCancel>
+ <AlertDialogAction className={cn(buttonVariants({ variant: "destructive" }))} onClick={revokeKeys}>
+ <Trans>Revoke</Trans>
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ )
+}
diff --git a/internal/site/src/components/routes/settings/layout.tsx b/internal/site/src/components/routes/settings/layout.tsx
index 11bb89a63..f2f2589a0 100644
--- a/internal/site/src/components/routes/settings/layout.tsx
+++ b/internal/site/src/components/routes/settings/layout.tsx
@@ -8,6 +8,7 @@ import {
FileSlidersIcon,
FingerprintIcon,
HeartPulseIcon,
+ KeyRoundIcon,
SettingsIcon,
} from "lucide-react"
import { lazy, useEffect } from "react"
@@ -26,6 +27,7 @@ const configYamlSettingsImport = () => import("./config-yaml.tsx")
const fingerprintsSettingsImport = () => import("./tokens-fingerprints.tsx")
const alertsHistoryDataTableSettingsImport = () => import("./alerts-history-data-table.tsx")
const heartbeatSettingsImport = () => import("./heartbeat.tsx")
+const apiKeysSettingsImport = () => import("./api-keys.tsx")
const GeneralSettings = lazy(generalSettingsImport)
const NotificationsSettings = lazy(notificationsSettingsImport)
@@ -33,6 +35,7 @@ const ConfigYamlSettings = lazy(configYamlSettingsImport)
const FingerprintsSettings = lazy(fingerprintsSettingsImport)
const AlertsHistoryDataTableSettings = lazy(alertsHistoryDataTableSettingsImport)
const HeartbeatSettings = lazy(heartbeatSettingsImport)
+const ApiKeysSettings = lazy(apiKeysSettingsImport)
export async function saveSettings(newSettings: Partial<UserSettings>) {
try {
@@ -73,6 +76,12 @@ export default function SettingsLayout() {
noReadOnly: true,
preload: fingerprintsSettingsImport,
},
+ {
+ title: t`API Keys`,
+ href: getPagePath($router, "settings", { name: "api-keys" }),
+ icon: KeyRoundIcon,
+ preload: apiKeysSettingsImport,
+ },
{
title: t`Alert History`,
href: getPagePath($router, "settings", { name: "alert-history" }),
@@ -148,5 +157,7 @@ function SettingsContent({ name }: { name: string }) {
return <AlertsHistoryDataTableSettings />
case "heartbeat":
return <HeartbeatSettings />
+ case "api-keys":
+ return <ApiKeysSettings />
}
}