Serve a web UI for the incident queue, built for phones
Whoever is on call gets paged on a phone, and until now the only ways to
act on a page were the notification's Acknowledge button or a terminal.
Tapping the notification itself opened /api/incidents/{id}, which a
browser can only answer with a 401 in JSON. The server now serves a web
UI at / covering the incident queue, each incident's alerts and timeline
with every action on it, who is on call, the alert feed, and changing
your own password. The notification link now points at /incidents/{id}
in that UI.
It is embedded in the binary and has no build step: plain HTML, CSS and
ES modules under internal/web/static, served with an ETag per file and a
CSP that allows nothing from any other origin. That is how rd-web is
built. It avoids adding a node toolchain to the Dockerfile and the
pipeline for a page this size, and it keeps the page on the same origin
as the API, so no CORS is needed and nothing else has to be deployed.
Paths without a file extension fall back to index.html, so a deep link
survives a reload. An unknown path under /api/ still gets a JSON 404
rather than the page.
Signing in uses a username and password, because pasting a 64-character
API key into a phone at 3am is not a sign-in flow. Users have no
password until one is set through PUT /api/users/{id}/password, or
optionally at bootstrap. A user without a password is exactly where they
were before this commit and can only use API keys. A login sets an
HttpOnly, SameSite=Lax session cookie. It lasts 30 days and slides
forward while in use, so an on-call phone does not sign itself out.
Only the token's hash is stored, as for API keys.
The cookie needs a CSRF guard where a bearer header does not, because
browsers attach cookies to requests other sites make. So cookie-
authenticated requests go through Go 1.25's http.CrossOriginProtection,
and bearer requests do not. A request carrying an Authorization header
is judged on that header alone and never falls back to the cookie.
Changing a password ends every other session of that user. Changing
your own requires the current password, so a phone left signed in
cannot be used to take the account over.
Failed logins are counted per username and per client address. Ten
failures for one username in 15 minutes refuse that username for the
rest of the window, even with the right password. That makes locking
somebody out possible for anyone who knows their username. It was
accepted because the alternative is unlimited guessing, and during a
lockout the notification's Acknowledge button and API keys keep
working. The address limit reads the first X-Forwarded-For hop, since
behind the gateway RemoteAddr is Envoy. It is looser, because a whole
office behind one NAT shares it.
The Secure flag follows TERDUT_PUBLIC_URL, since TLS terminates at the
gateway and the server itself only ever sees plain HTTP. The chart
already defaults that variable to https://<hostname>.
Schedule editing, statistics and user management stay in terdut-tui for
now. The API they use is unchanged, and bearer authentication behaves
exactly as before.
This commit is contained in:
@@ -51,6 +51,7 @@ func Sweep(ctx context.Context, db *sql.DB, archiveAfter, staleAfter time.Durati
|
||||
archiveResolved(ctx, db, archiveAfter)
|
||||
archiveResolvedIncidents(ctx, db, archiveAfter)
|
||||
purgeAckTokens(ctx, db)
|
||||
purgeSessions(ctx, db)
|
||||
}
|
||||
|
||||
// expireStale resolves firing alerts that Alertmanager has stopped refreshing.
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
// sessionCookie carries a web UI session. It is HttpOnly, so page script
|
||||
// never sees the token; the page learns who it is from GET /api/me.
|
||||
sessionCookie = "terdut_session"
|
||||
|
||||
// sessionTTL is how long a session lives without being used. It slides, so
|
||||
// a phone that opens the UI now and then stays signed in indefinitely.
|
||||
sessionTTL = 30 * 24 * time.Hour
|
||||
|
||||
// sessionTouchEvery bounds how often a request may slide the expiry.
|
||||
sessionTouchEvery = time.Hour
|
||||
|
||||
minPasswordLen = 10
|
||||
// maxPasswordLen is bcrypt's limit; it rejects longer input outright.
|
||||
maxPasswordLen = 72
|
||||
|
||||
loginWindow = 15 * time.Minute
|
||||
loginMaxPerUser = 10
|
||||
loginMaxPerAddr = 30
|
||||
passwordHashCost = bcrypt.DefaultCost
|
||||
)
|
||||
|
||||
// dummyHash is compared against when the username is unknown or has no
|
||||
// password, so a failed login takes as long whichever way it failed.
|
||||
var dummyHash = sync.OnceValue(func() []byte {
|
||||
h, _ := bcrypt.GenerateFromPassword([]byte("terdut-dummy-password"), passwordHashCost)
|
||||
return h
|
||||
})
|
||||
|
||||
// loginLimiter counts failed logins in a fixed window, per username and per
|
||||
// client address. The username limit is what stops guessing one account; the
|
||||
// address limit is looser because every user behind the same gateway or NAT
|
||||
// shares it.
|
||||
type loginLimiter struct {
|
||||
mu sync.Mutex
|
||||
failures map[string]*loginWindowCount
|
||||
}
|
||||
|
||||
type loginWindowCount struct {
|
||||
start time.Time
|
||||
n int
|
||||
}
|
||||
|
||||
func newLoginLimiter() *loginLimiter {
|
||||
return &loginLimiter{failures: map[string]*loginWindowCount{}}
|
||||
}
|
||||
|
||||
func (l *loginLimiter) blocked(key string, max int) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
c, ok := l.failures[key]
|
||||
if !ok || time.Since(c.start) > loginWindow {
|
||||
return false
|
||||
}
|
||||
return c.n >= max
|
||||
}
|
||||
|
||||
func (l *loginLimiter) fail(keys ...string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
for k, c := range l.failures {
|
||||
if now.Sub(c.start) > loginWindow {
|
||||
delete(l.failures, k)
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
c, ok := l.failures[key]
|
||||
if !ok {
|
||||
c = &loginWindowCount{start: now}
|
||||
l.failures[key] = c
|
||||
}
|
||||
c.n++
|
||||
}
|
||||
}
|
||||
|
||||
func (l *loginLimiter) clear(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.failures, key)
|
||||
}
|
||||
|
||||
// clientAddr is the address a login is counted against. Behind the gateway
|
||||
// RemoteAddr is the gateway itself, so the first X-Forwarded-For hop is used
|
||||
// when present. It can be forged, but only to dodge the address limit; the
|
||||
// per-username limit does not depend on it.
|
||||
func clientAddr(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
first, _, _ := strings.Cut(xff, ",")
|
||||
return strings.TrimSpace(first)
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// cookieSecure decides the cookie's Secure flag. TLS terminates at the gateway,
|
||||
// so the server usually sees plain HTTP; the public URL is what says whether
|
||||
// browsers reach it over HTTPS.
|
||||
func cookieSecure(publicURL string, r *http.Request) bool {
|
||||
return strings.HasPrefix(publicURL, "https://") ||
|
||||
r.TLS != nil ||
|
||||
r.Header.Get("X-Forwarded-Proto") == "https"
|
||||
}
|
||||
|
||||
// validatePassword returns a message for the client, or "" when acceptable.
|
||||
func validatePassword(pw string) string {
|
||||
switch {
|
||||
case len(pw) < minPasswordLen:
|
||||
return "password must be at least " + strconv.Itoa(minPasswordLen) + " characters"
|
||||
case len(pw) > maxPasswordLen:
|
||||
return "password must be at most " + strconv.Itoa(maxPasswordLen) + " bytes"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func hashPassword(pw string) (string, error) {
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(pw), passwordHashCost)
|
||||
return string(h), err
|
||||
}
|
||||
|
||||
// handleLogin exchanges a username and password for a session cookie.
|
||||
func handleLogin(db *sql.DB, limiter *loginLimiter, publicURL string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
||||
return
|
||||
}
|
||||
username := strings.TrimSpace(req.Username)
|
||||
userKey := "user:" + strings.ToLower(username)
|
||||
addrKey := "addr:" + clientAddr(r)
|
||||
|
||||
if limiter.blocked(userKey, loginMaxPerUser) || limiter.blocked(addrKey, loginMaxPerAddr) {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(loginWindow.Seconds())))
|
||||
respond(w, http.StatusTooManyRequests, errResp("too many failed attempts, try again later"))
|
||||
return
|
||||
}
|
||||
|
||||
var userID int64
|
||||
var hash sql.NullString
|
||||
err := db.QueryRowContext(r.Context(),
|
||||
"SELECT id, password_hash FROM users WHERE username = ?", username,
|
||||
).Scan(&userID, &hash)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
|
||||
stored := dummyHash()
|
||||
if hash.Valid {
|
||||
stored = []byte(hash.String)
|
||||
}
|
||||
match := bcrypt.CompareHashAndPassword(stored, []byte(req.Password)) == nil
|
||||
if !match || !hash.Valid {
|
||||
limiter.fail(userKey, addrKey)
|
||||
respond(w, http.StatusUnauthorized, errResp("invalid username or password"))
|
||||
return
|
||||
}
|
||||
limiter.clear(userKey)
|
||||
|
||||
raw, tokenHash, err := randomToken()
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if _, err := db.ExecContext(r.Context(), `
|
||||
INSERT INTO sessions (token_hash, user_id, created_at, last_seen_at, expires_at, user_agent)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
tokenHash, userID, now.Unix(), now.Unix(), now.Add(sessionTTL).Unix(), r.UserAgent()); err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: raw,
|
||||
Path: "/",
|
||||
MaxAge: int(sessionTTL.Seconds()),
|
||||
HttpOnly: true,
|
||||
Secure: cookieSecure(publicURL, r),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
|
||||
user, err := fetchUser(r.Context(), db, userID)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
respond(w, http.StatusOK, meResponse{User: user, HasPassword: true})
|
||||
}
|
||||
}
|
||||
|
||||
// handleLogout ends the browser's session. It sits outside AuthMiddleware so
|
||||
// that a browser holding an already-expired cookie can still clear it.
|
||||
func handleLogout(db *sql.DB, publicURL string) http.HandlerFunc {
|
||||
crossOrigin := http.NewCrossOriginProtection()
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := crossOrigin.Check(r); err != nil {
|
||||
respond(w, http.StatusForbidden, errResp("cross-origin request rejected"))
|
||||
return
|
||||
}
|
||||
if c, err := r.Cookie(sessionCookie); err == nil && c.Value != "" {
|
||||
db.ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash = ?", hashToken(c.Value))
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
Secure: cookieSecure(publicURL, r),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
type meResponse struct {
|
||||
User any `json:"user"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
}
|
||||
|
||||
// handleMe says who the caller is. The web UI calls it on load to decide
|
||||
// between the login form and the app, since it cannot read its own cookie.
|
||||
func handleMe(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
caller, _ := userFromContext(r.Context())
|
||||
user, err := fetchUser(r.Context(), db, caller.ID)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
var hash sql.NullString
|
||||
db.QueryRowContext(r.Context(),
|
||||
"SELECT password_hash FROM users WHERE id = ?", caller.ID).Scan(&hash)
|
||||
respond(w, http.StatusOK, meResponse{User: user, HasPassword: hash.Valid})
|
||||
}
|
||||
}
|
||||
|
||||
// handleSetPassword sets a user's web UI password.
|
||||
//
|
||||
// Changing your own password takes the current one, when there is one, so an
|
||||
// unattended signed-in browser cannot be used to take the account over. Setting
|
||||
// somebody else's is how an admin gives a user their first password, and like
|
||||
// the other user endpoints it is open to any authenticated caller.
|
||||
//
|
||||
// Every other session of the target is ended: a password change is what you
|
||||
// do when you think someone else is signed in.
|
||||
func handleSetPassword(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond(w, http.StatusBadRequest, errResp("invalid user id"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Password string `json:"password"`
|
||||
CurrentPassword string `json:"current_password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
||||
return
|
||||
}
|
||||
if msg := validatePassword(req.Password); msg != "" {
|
||||
respond(w, http.StatusBadRequest, errResp(msg))
|
||||
return
|
||||
}
|
||||
|
||||
var existing sql.NullString
|
||||
err = db.QueryRowContext(r.Context(),
|
||||
"SELECT password_hash FROM users WHERE id = ?", id).Scan(&existing)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
respond(w, http.StatusNotFound, errResp("user not found"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
|
||||
caller, _ := userFromContext(r.Context())
|
||||
if caller.ID == id && existing.Valid &&
|
||||
bcrypt.CompareHashAndPassword([]byte(existing.String), []byte(req.CurrentPassword)) != nil {
|
||||
respond(w, http.StatusForbidden, errResp("current password is incorrect"))
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
|
||||
tx, err := db.BeginTx(r.Context(), nil)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.ExecContext(r.Context(),
|
||||
"UPDATE users SET password_hash = ? WHERE id = ?", hash, id); err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
keep, _ := sessionFromContext(r.Context()) // zero when changed with an API key
|
||||
if _, err := tx.ExecContext(r.Context(),
|
||||
"DELETE FROM sessions WHERE user_id = ? AND id != ?", id, keep); err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// purgeSessions deletes sessions that have expired, from the sweeper.
|
||||
func purgeSessions(ctx context.Context, db *sql.DB) {
|
||||
res, err := db.ExecContext(ctx,
|
||||
"DELETE FROM sessions WHERE expires_at < ?", time.Now().Unix())
|
||||
if err != nil {
|
||||
log.Printf("sweeper: purge sessions: %v", err)
|
||||
return
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n > 0 {
|
||||
log.Printf("sweeper: purged %d expired session(s)", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ryuvia.com/niklas/terdut-server/internal/api"
|
||||
"git.ryuvia.com/niklas/terdut-server/internal/db"
|
||||
)
|
||||
|
||||
const adminPassword = "correct horse battery"
|
||||
|
||||
// browser is an HTTP client with its own cookie jar, standing in for one
|
||||
// signed-in browser.
|
||||
type browser struct {
|
||||
*http.Client
|
||||
base string
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, base string) *browser {
|
||||
t.Helper()
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return &browser{Client: &http.Client{Jar: jar}, base: base}
|
||||
}
|
||||
|
||||
// do sends a request the way the web UI's own fetch would: same-origin, with
|
||||
// the cookie from the jar.
|
||||
func (b *browser) do(t *testing.T, method, path string, body any, header ...string) *http.Response {
|
||||
t.Helper()
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
data, _ := json.Marshal(body)
|
||||
r = bytes.NewReader(data)
|
||||
}
|
||||
req, _ := http.NewRequest(method, b.base+path, r)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
for i := 0; i+1 < len(header); i += 2 {
|
||||
req.Header.Set(header[i], header[i+1])
|
||||
}
|
||||
resp, err := b.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v", method, path, err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func (b *browser) login(t *testing.T, username, password string) *http.Response {
|
||||
t.Helper()
|
||||
return b.do(t, http.MethodPost, "/api/login", map[string]string{"username": username, "password": password})
|
||||
}
|
||||
|
||||
// setAdminPassword gives the bootstrapped admin a password over its API key.
|
||||
func setAdminPassword(t *testing.T, s *ts) {
|
||||
t.Helper()
|
||||
resp := s.req(t, http.MethodPut, "/api/users/1/password", map[string]string{"password": adminPassword})
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("set password: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func signedIn(t *testing.T, s *ts) *browser {
|
||||
t.Helper()
|
||||
setAdminPassword(t, s)
|
||||
b := newBrowser(t, s.URL)
|
||||
resp := b.login(t, "admin", adminPassword)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("login: %d", resp.StatusCode)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func status(t *testing.T, resp *http.Response) int {
|
||||
t.Helper()
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
func TestLogin_SetsSessionCookie(t *testing.T) {
|
||||
s := newTS(t)
|
||||
setAdminPassword(t, s)
|
||||
b := newBrowser(t, s.URL)
|
||||
|
||||
resp := b.login(t, "admin", adminPassword)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("login: %d", resp.StatusCode)
|
||||
}
|
||||
var cookie *http.Cookie
|
||||
for _, c := range resp.Cookies() {
|
||||
if c.Name == "terdut_session" {
|
||||
cookie = c
|
||||
}
|
||||
}
|
||||
if cookie == nil || !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode {
|
||||
t.Fatalf("expected an HttpOnly, SameSite=Lax session cookie, got %+v", cookie)
|
||||
}
|
||||
if cookie.Secure {
|
||||
t.Error("cookie is Secure on a plain-HTTP server with no https public URL")
|
||||
}
|
||||
var me struct {
|
||||
User struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"user"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
}
|
||||
decode(t, resp, &me)
|
||||
if me.User.Username != "admin" || !me.HasPassword {
|
||||
t.Errorf("unexpected login response %+v", me)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_CookieAuthenticatesAPI(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := signedIn(t, s)
|
||||
|
||||
if code := status(t, b.do(t, http.MethodGet, "/api/incidents", nil)); code != http.StatusOK {
|
||||
t.Errorf("GET /api/incidents with cookie: %d", code)
|
||||
}
|
||||
resp := b.do(t, http.MethodGet, "/api/me", nil)
|
||||
var me struct {
|
||||
User struct {
|
||||
ID int64 `json:"id"`
|
||||
} `json:"user"`
|
||||
}
|
||||
decode(t, resp, &me)
|
||||
if me.User.ID != 1 {
|
||||
t.Errorf("/api/me returned user %d", me.User.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_SecureCookieBehindHTTPSPublicURL(t *testing.T) {
|
||||
s := newTS(t, api.NotifyConfig{PublicURL: "https://terdut.example.com"})
|
||||
setAdminPassword(t, s)
|
||||
resp := newBrowser(t, s.URL).login(t, "admin", adminPassword)
|
||||
resp.Body.Close()
|
||||
for _, c := range resp.Cookies() {
|
||||
if c.Name == "terdut_session" && !c.Secure {
|
||||
t.Error("cookie should be Secure when the public URL is https")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_WrongPasswordAndUnknownUser(t *testing.T) {
|
||||
s := newTS(t)
|
||||
setAdminPassword(t, s)
|
||||
b := newBrowser(t, s.URL)
|
||||
|
||||
if code := status(t, b.login(t, "admin", "not the password")); code != http.StatusUnauthorized {
|
||||
t.Errorf("wrong password: %d", code)
|
||||
}
|
||||
if code := status(t, b.login(t, "nobody", adminPassword)); code != http.StatusUnauthorized {
|
||||
t.Errorf("unknown user: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_UserWithoutPasswordCannotSignIn(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := newBrowser(t, s.URL)
|
||||
// The empty password must not match a user that has none.
|
||||
if code := status(t, b.login(t, "admin", "")); code != http.StatusUnauthorized {
|
||||
t.Errorf("login without a password set: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_RateLimitedPerUsername(t *testing.T) {
|
||||
s := newTS(t)
|
||||
setAdminPassword(t, s)
|
||||
b := newBrowser(t, s.URL)
|
||||
|
||||
for i := range 10 {
|
||||
if code := status(t, b.login(t, "admin", "wrong")); code != http.StatusUnauthorized {
|
||||
t.Fatalf("attempt %d: %d", i+1, code)
|
||||
}
|
||||
}
|
||||
// Even the right password is refused once the limit is reached.
|
||||
resp := b.login(t, "admin", adminPassword)
|
||||
if resp.StatusCode != http.StatusTooManyRequests {
|
||||
t.Fatalf("expected 429, got %d", resp.StatusCode)
|
||||
}
|
||||
if resp.Header.Get("Retry-After") == "" {
|
||||
t.Error("429 without Retry-After")
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestSession_CrossOriginWriteRejected(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := signedIn(t, s)
|
||||
|
||||
code := status(t, b.do(t, http.MethodPost, "/api/incidents/999/acknowledge", nil,
|
||||
"Sec-Fetch-Site", "cross-site", "Origin", "https://evil.example"))
|
||||
if code != http.StatusForbidden {
|
||||
t.Errorf("cross-origin POST with cookie: %d, want 403", code)
|
||||
}
|
||||
|
||||
// The same request from the page itself gets through to the handler.
|
||||
code = status(t, b.do(t, http.MethodPost, "/api/incidents/999/acknowledge", nil))
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("same-origin POST with cookie: %d, want 404 from the handler", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_BearerIgnoresOriginChecks(t *testing.T) {
|
||||
s := newTS(t)
|
||||
req, _ := http.NewRequest(http.MethodPost, s.URL+"/api/incidents/999/acknowledge", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+s.key)
|
||||
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := status(t, resp); code != http.StatusNotFound {
|
||||
t.Errorf("Bearer request: %d, want 404 from the handler", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogout_EndsSession(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := signedIn(t, s)
|
||||
|
||||
if code := status(t, b.do(t, http.MethodPost, "/api/logout", nil)); code != http.StatusNoContent {
|
||||
t.Fatalf("logout: %d", code)
|
||||
}
|
||||
if code := status(t, b.do(t, http.MethodGet, "/api/me", nil)); code != http.StatusUnauthorized {
|
||||
t.Errorf("after logout: %d", code)
|
||||
}
|
||||
var n int
|
||||
s.db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&n)
|
||||
if n != 0 {
|
||||
t.Errorf("%d session(s) left after logout", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSession_ExpiredIsRejected(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := signedIn(t, s)
|
||||
s.exec(t, "UPDATE sessions SET expires_at = 1")
|
||||
|
||||
if code := status(t, b.do(t, http.MethodGet, "/api/me", nil)); code != http.StatusUnauthorized {
|
||||
t.Errorf("expired session: %d", code)
|
||||
}
|
||||
api.Sweep(t.Context(), s.db, 0, 0, api.DeadmanConfig{}, api.NotifyConfig{})
|
||||
var n int
|
||||
s.db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&n)
|
||||
if n != 0 {
|
||||
t.Errorf("sweep left %d expired session(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPassword_OwnNeedsCurrent(t *testing.T) {
|
||||
s := newTS(t)
|
||||
b := signedIn(t, s)
|
||||
|
||||
code := status(t, b.do(t, http.MethodPut, "/api/users/1/password",
|
||||
map[string]string{"password": "a brand new secret", "current_password": "wrong"}))
|
||||
if code != http.StatusForbidden {
|
||||
t.Errorf("wrong current password: %d", code)
|
||||
}
|
||||
code = status(t, b.do(t, http.MethodPut, "/api/users/1/password",
|
||||
map[string]string{"password": "short", "current_password": adminPassword}))
|
||||
if code != http.StatusBadRequest {
|
||||
t.Errorf("too-short password: %d", code)
|
||||
}
|
||||
code = status(t, b.do(t, http.MethodPut, "/api/users/1/password",
|
||||
map[string]string{"password": "a brand new secret", "current_password": adminPassword}))
|
||||
if code != http.StatusNoContent {
|
||||
t.Fatalf("change password: %d", code)
|
||||
}
|
||||
if code := status(t, newBrowser(t, s.URL).login(t, "admin", "a brand new secret")); code != http.StatusOK {
|
||||
t.Errorf("login with the new password: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPassword_EndsOtherSessionsButNotThisOne(t *testing.T) {
|
||||
s := newTS(t)
|
||||
phone := signedIn(t, s)
|
||||
laptop := newBrowser(t, s.URL)
|
||||
status(t, laptop.login(t, "admin", adminPassword))
|
||||
|
||||
code := status(t, phone.do(t, http.MethodPut, "/api/users/1/password",
|
||||
map[string]string{"password": "a brand new secret", "current_password": adminPassword}))
|
||||
if code != http.StatusNoContent {
|
||||
t.Fatalf("change password: %d", code)
|
||||
}
|
||||
if code := status(t, phone.do(t, http.MethodGet, "/api/me", nil)); code != http.StatusOK {
|
||||
t.Errorf("the session that changed the password: %d", code)
|
||||
}
|
||||
if code := status(t, laptop.do(t, http.MethodGet, "/api/me", nil)); code != http.StatusUnauthorized {
|
||||
t.Errorf("the other session: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrap_WithPassword(t *testing.T) {
|
||||
database, err := db.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(api.NewRouter(database, api.NotifyConfig{}, api.DeadmanConfig{}))
|
||||
t.Cleanup(func() { srv.Close(); database.Close() })
|
||||
|
||||
body := `{"username":"admin","email":"a@test.com","password":"` + adminPassword + `"}`
|
||||
resp, err := http.Post(srv.URL+"/api/bootstrap", "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := status(t, resp); code != http.StatusCreated {
|
||||
t.Fatalf("bootstrap: %d", code)
|
||||
}
|
||||
if code := status(t, newBrowser(t, srv.URL).login(t, "admin", adminPassword)); code != http.StatusOK {
|
||||
t.Errorf("login after bootstrap: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouter_UnknownAPIPathIsJSON404(t *testing.T) {
|
||||
s := newTS(t)
|
||||
resp, err := http.Get(s.URL + "/api/nope")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNotFound || !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
|
||||
t.Errorf("GET /api/nope: %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouter_DeepLinkServesWebUI(t *testing.T) {
|
||||
s := newTS(t)
|
||||
resp, err := http.Get(s.URL + "/incidents/1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") {
|
||||
t.Errorf("GET /incidents/1: %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
|
||||
}
|
||||
if resp.Header.Get("Content-Security-Policy") == "" {
|
||||
t.Error("web UI served without a CSP")
|
||||
}
|
||||
|
||||
resp2, err := http.Get(s.URL + "/js/missing.js")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := status(t, resp2); code != http.StatusNotFound {
|
||||
t.Errorf("missing asset: %d", code)
|
||||
}
|
||||
}
|
||||
+106
-26
@@ -14,50 +14,130 @@ import (
|
||||
|
||||
type contextKey string
|
||||
|
||||
const ctxUser contextKey = "user"
|
||||
const (
|
||||
ctxUser contextKey = "user"
|
||||
ctxSession contextKey = "session"
|
||||
)
|
||||
|
||||
// AuthMiddleware accepts either of the two credentials the server issues: an
|
||||
// API key in an Authorization header (the TUI, scripts) or a session cookie
|
||||
// (the web UI). A request carrying a Bearer header is judged on that alone and
|
||||
// never falls back to the cookie.
|
||||
//
|
||||
// Only the cookie needs a CSRF guard. A browser attaches it to requests other
|
||||
// sites make, whereas an Authorization header is only ever set by the client
|
||||
// that holds the key.
|
||||
func AuthMiddleware(db *sql.DB) func(http.Handler) http.Handler {
|
||||
crossOrigin := http.NewCrossOriginProtection()
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if !ok || token == "" {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
if header := r.Header.Get("Authorization"); header != "" {
|
||||
token, ok := strings.CutPrefix(header, "Bearer ")
|
||||
if !ok || token == "" {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
return
|
||||
}
|
||||
userID, ok := apiKeyUser(r.Context(), db, token)
|
||||
if !ok {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
return
|
||||
}
|
||||
serveAs(w, r, next, db, userID, 0)
|
||||
return
|
||||
}
|
||||
|
||||
h := sha256.Sum256([]byte(token))
|
||||
hash := hex.EncodeToString(h[:])
|
||||
|
||||
var keyID, userID int64
|
||||
err := db.QueryRowContext(r.Context(),
|
||||
"SELECT id, user_id FROM api_keys WHERE key_hash = ?", hash,
|
||||
).Scan(&keyID, &userID)
|
||||
if err != nil {
|
||||
c, err := r.Cookie(sessionCookie)
|
||||
if err != nil || c.Value == "" {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
return
|
||||
}
|
||||
|
||||
// best-effort; don't fail the request if this update fails
|
||||
db.ExecContext(r.Context(),
|
||||
"UPDATE api_keys SET last_used_at = ? WHERE id = ?",
|
||||
time.Now().Unix(), keyID)
|
||||
|
||||
var u models.User
|
||||
var createdUnix int64
|
||||
if err := db.QueryRowContext(r.Context(),
|
||||
"SELECT id, username, email, created_at FROM users WHERE id = ?", userID,
|
||||
).Scan(&u.ID, &u.Username, &u.Email, &createdUnix); err != nil {
|
||||
sessionID, userID, ok := sessionUser(r.Context(), db, c.Value)
|
||||
if !ok {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
return
|
||||
}
|
||||
u.CreatedAt = time.Unix(createdUnix, 0).UTC()
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxUser, u)))
|
||||
if err := crossOrigin.Check(r); err != nil {
|
||||
respond(w, http.StatusForbidden, errResp("cross-origin request rejected"))
|
||||
return
|
||||
}
|
||||
serveAs(w, r, next, db, userID, sessionID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// apiKeyUser resolves an API key to its user and stamps its last use.
|
||||
func apiKeyUser(ctx context.Context, db *sql.DB, token string) (int64, bool) {
|
||||
var keyID, userID int64
|
||||
err := db.QueryRowContext(ctx,
|
||||
"SELECT id, user_id FROM api_keys WHERE key_hash = ?", hashToken(token),
|
||||
).Scan(&keyID, &userID)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// best-effort; don't fail the request if this update fails
|
||||
db.ExecContext(ctx,
|
||||
"UPDATE api_keys SET last_used_at = ? WHERE id = ?",
|
||||
time.Now().Unix(), keyID)
|
||||
return userID, true
|
||||
}
|
||||
|
||||
// sessionUser resolves a session token to its session and user. The expiry
|
||||
// slides forward with use, but at most once per sessionTouchEvery, so a page
|
||||
// that polls does not write to the database on every request.
|
||||
func sessionUser(ctx context.Context, db *sql.DB, token string) (sessionID, userID int64, ok bool) {
|
||||
now := time.Now()
|
||||
var lastSeen int64
|
||||
err := db.QueryRowContext(ctx, `
|
||||
SELECT id, user_id, last_seen_at FROM sessions
|
||||
WHERE token_hash = ? AND expires_at > ?`,
|
||||
hashToken(token), now.Unix()).Scan(&sessionID, &userID, &lastSeen)
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
if now.Sub(time.Unix(lastSeen, 0)) > sessionTouchEvery {
|
||||
db.ExecContext(ctx,
|
||||
"UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE id = ?",
|
||||
now.Unix(), now.Add(sessionTTL).Unix(), sessionID)
|
||||
}
|
||||
return sessionID, userID, true
|
||||
}
|
||||
|
||||
// serveAs loads the user and hands the request on with it in the context.
|
||||
// sessionID is zero for API-key requests.
|
||||
func serveAs(w http.ResponseWriter, r *http.Request, next http.Handler, db *sql.DB, userID, sessionID int64) {
|
||||
var u models.User
|
||||
var createdUnix int64
|
||||
if err := db.QueryRowContext(r.Context(),
|
||||
"SELECT id, username, email, created_at FROM users WHERE id = ?", userID,
|
||||
).Scan(&u.ID, &u.Username, &u.Email, &createdUnix); err != nil {
|
||||
respond(w, http.StatusUnauthorized, errResp("unauthorized"))
|
||||
return
|
||||
}
|
||||
u.CreatedAt = time.Unix(createdUnix, 0).UTC()
|
||||
|
||||
ctx := context.WithValue(r.Context(), ctxUser, u)
|
||||
if sessionID != 0 {
|
||||
ctx = context.WithValue(ctx, ctxSession, sessionID)
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
|
||||
func hashToken(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func userFromContext(ctx context.Context) (models.User, bool) {
|
||||
u, ok := ctx.Value(ctxUser).(models.User)
|
||||
return u, ok
|
||||
}
|
||||
|
||||
// sessionFromContext returns the id of the session a request was authenticated
|
||||
// with, or false for an API-key request.
|
||||
func sessionFromContext(ctx context.Context) (int64, bool) {
|
||||
id, ok := ctx.Value(ctxSession).(int64)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
@@ -359,7 +359,9 @@ func renderNotification(inc models.Incident, n outboxRow, firing int, cfg Notify
|
||||
msg := ntfyMessage{Topic: n.topic}
|
||||
|
||||
if cfg.PublicURL != "" {
|
||||
msg.Click = fmt.Sprintf("%s/api/incidents/%d",
|
||||
// The web UI's page for the incident, so tapping the notification
|
||||
// opens something a browser can use.
|
||||
msg.Click = fmt.Sprintf("%s/incidents/%d",
|
||||
strings.TrimSuffix(cfg.PublicURL, "/"), inc.ID)
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ func TestNotify_TriggeredIncidentPagesOnCall(t *testing.T) {
|
||||
if !strings.Contains(m.Message, "severity critical") {
|
||||
t.Errorf("expected the severity in %q", m.Message)
|
||||
}
|
||||
if m.Click != "https://terdut.example.com/api/incidents/1" {
|
||||
if m.Click != "https://terdut.example.com/incidents/1" {
|
||||
t.Errorf("unexpected click target %q", m.Click)
|
||||
}
|
||||
if len(m.Actions) != 1 || m.Actions[0].Label != "Acknowledge" {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
|
||||
"git.ryuvia.com/niklas/terdut-server/internal/web"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
@@ -29,14 +30,21 @@ func NewRouter(db *sql.DB, notify NotifyConfig, deadman DeadmanConfig) http.Hand
|
||||
r.Post("/api/alertmanager/webhook", handleAlertmanagerWebhook(db, notify, deadman))
|
||||
r.Post("/api/notify/ack/{token}", handleNotifyAck(db))
|
||||
|
||||
// Signing in to the web UI. Login trades a password for a session cookie,
|
||||
// which AuthMiddleware accepts in place of an API key.
|
||||
r.Post("/api/login", handleLogin(db, newLoginLimiter(), notify.PublicURL))
|
||||
r.Post("/api/logout", handleLogout(db, notify.PublicURL))
|
||||
|
||||
// All other /api routes require a valid API key.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(AuthMiddleware(db))
|
||||
|
||||
r.Get("/api/me", handleMe(db))
|
||||
r.Get("/api/users", handleListUsers(db))
|
||||
r.Post("/api/users", handleCreateUser(db))
|
||||
r.Delete("/api/users/{id}", handleDeleteUser(db))
|
||||
r.Put("/api/users/{id}/notify", handleSetNotifyTarget(db))
|
||||
r.Put("/api/users/{id}/password", handleSetPassword(db))
|
||||
r.Post("/api/users/{id}/api-keys", handleCreateAPIKey(db))
|
||||
r.Delete("/api/users/{id}/api-keys/{keyID}", handleDeleteAPIKey(db))
|
||||
|
||||
@@ -72,5 +80,18 @@ func NewRouter(db *sql.DB, notify NotifyConfig, deadman DeadmanConfig) http.Hand
|
||||
r.Get("/api/stats/alerts/by-day", handleStatsByDay(db))
|
||||
})
|
||||
|
||||
// Anything else under /api is a mistake in a client, and should say so in
|
||||
// JSON rather than get the web UI's HTML.
|
||||
r.Handle("/api/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
respond(w, http.StatusNotFound, errResp("not found"))
|
||||
}))
|
||||
|
||||
// Everything outside /api is the web UI.
|
||||
site, err := web.Handler()
|
||||
if err != nil {
|
||||
panic(err) // the site is embedded at build time; this cannot fail at runtime
|
||||
}
|
||||
r.Handle("/*", site)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
+18
-1
@@ -20,6 +20,9 @@ func handleBootstrap(db *sql.DB) http.HandlerFunc {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
// Password is optional; without one the first user can only use the
|
||||
// API key until somebody sets it.
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
||||
@@ -29,6 +32,19 @@ func handleBootstrap(db *sql.DB) http.HandlerFunc {
|
||||
respond(w, http.StatusBadRequest, errResp("username and email are required"))
|
||||
return
|
||||
}
|
||||
var passwordHash *string
|
||||
if req.Password != "" {
|
||||
if msg := validatePassword(req.Password); msg != "" {
|
||||
respond(w, http.StatusBadRequest, errResp(msg))
|
||||
return
|
||||
}
|
||||
h, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
}
|
||||
passwordHash = &h
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := db.QueryRowContext(r.Context(), "SELECT COUNT(*) FROM users").Scan(&count); err != nil {
|
||||
@@ -41,7 +57,8 @@ func handleBootstrap(db *sql.DB) http.HandlerFunc {
|
||||
}
|
||||
|
||||
res, err := db.ExecContext(r.Context(),
|
||||
"INSERT INTO users (username, email) VALUES (?, ?)", req.Username, req.Email)
|
||||
"INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)",
|
||||
req.Username, req.Email, passwordHash)
|
||||
if err != nil {
|
||||
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user