Phase 16: Petal authenticates for itself
Petal is now an OIDC client in its own right rather than trusting a header from the proxy. The Phase-0 Resolver seam was the only integration point: main.go picks the session store when Authentik is configured and the static local user otherwise, and no handler or query moved for either. internal/auth gains three pieces. session.go issues an opaque cookie token and stores only its SHA-256, so a database copy yields nothing usable; the 30-day expiry slides on every request, throttled to one write an hour, and logout deletes the row rather than just the cookie. oidc.go runs the authorization-code flow with state, nonce and PKCE, and discovers the provider lazily and on retry — an Authentik outage should block new logins without stopping Petal booting or invalidating live sessions. users.go provisions accounts from the token's claims and gates them on an allowlist that matches emails as well as subject ids, since a subject is an opaque uuid that doesn't exist until someone has already logged in once. Migration 0010 lands sessions, images and users.pair_lang together. The images table closes the capability-URL hole the Phase-0 audit flagged: a hash was previously enough to fetch anyone's picture. Rows are keyed (name, user_id) so one file can have several owners and deduplication survives; a stranger gets 404 rather than 403, the cache header drops to private, and files already on disk are claimed at startup or every image already pasted into a document would 404. On the frontend a single 401 interceptor feeds a warm bilingual sign-in overlay, drawn over a still-visible editor because nothing has been taken away. Behind it is the part that matters: a save that comes back 401 stashes its body to localStorage before anything else and stops the auto-save loop, and reopening that document after signing in merges the draft back and saves it. An expired session must not cost writing. Writing the round-trip test against a stub identity provider turned up a real bug: the one-shot state/nonce/PKCE cookies were cleared in a defer, which runs after the redirect has written the response header, so the clearing Set-Cookie was silently dropped and they lingered for their full ten minutes. Also swaps the emoji favicon for a drawn sakura, which renders as Petal's own rose palette everywhere instead of whatever each platform's font decides, and doubles as the app tile in Authentik. Migration 0010 verified against a VACUUM INTO copy of the live millenia database: counts intact, FTS still matching, the one existing image claimed. Claude-Session: https://claude.ai/code/session_016y6gyuHkQXPiEuW8RGQyua
This commit is contained in:
+48
-8
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -53,6 +54,34 @@ func main() {
|
||||
defer database.Close()
|
||||
log.Printf("database ready at %s", cfg.DatabasePath)
|
||||
|
||||
// Identity. With Authentik configured, Petal is an OIDC client in its own
|
||||
// right: /auth/login starts a real login and the session cookie it issues is
|
||||
// what every API request is resolved from. Without it — local development,
|
||||
// and every deployment before auth landed — StaticResolver hands out the
|
||||
// single hardcoded local user, so nothing about running Petal on a laptop
|
||||
// changes.
|
||||
sessions := auth.NewSessionStore(database.DB)
|
||||
users := auth.NewUserStore(database.DB)
|
||||
|
||||
var resolver auth.Resolver = auth.StaticResolver(db.LocalUserID)
|
||||
var oidcClient *auth.OIDC
|
||||
if cfg.AuthEnabled() {
|
||||
oidcClient = auth.NewOIDC(context.Background(), auth.Options{
|
||||
IssuerURL: cfg.AuthentikURL,
|
||||
ClientID: cfg.AuthentikClientID,
|
||||
ClientSecret: cfg.AuthentikClientSecret,
|
||||
BaseURL: cfg.BaseURL,
|
||||
Allowed: auth.ParseAllowlist(cfg.AllowedSubs),
|
||||
}, sessions, users)
|
||||
resolver = sessions
|
||||
if n, err := sessions.Prune(); err == nil && n > 0 {
|
||||
log.Printf("auth: pruned %d expired session(s)", n)
|
||||
}
|
||||
log.Printf("auth: OIDC enabled (issuer=%s, redirect=%s)", cfg.AuthentikURL, oidcClient.RedirectURI())
|
||||
} else {
|
||||
log.Printf("auth: OIDC not configured — running as the single %q user", db.LocalUserID)
|
||||
}
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
@@ -90,13 +119,16 @@ func main() {
|
||||
// client's update poll) must not need a session to reach them.
|
||||
//
|
||||
// The middleware resolves the caller once and hands handlers the answer via
|
||||
// auth.UserID(r.Context()), replacing the db.LocalUserID constant those
|
||||
// queries used to name directly. Petal is still single-user — StaticResolver
|
||||
// returns that same local user for every request — but the identity now
|
||||
// travels the same path a real one will. Swapping this line for an Authentik
|
||||
// session resolver is the whole remaining change; no handler or query moves.
|
||||
// auth.UserID(r.Context()). Which resolver it runs is the only thing that
|
||||
// changed when auth landed: the session store in a deployment with
|
||||
// Authentik configured, the static local user otherwise. No handler or
|
||||
// query moved for either.
|
||||
api.Group(func(pr chi.Router) {
|
||||
pr.Use(auth.Middleware(auth.StaticResolver(db.LocalUserID)))
|
||||
pr.Use(auth.Middleware(resolver))
|
||||
|
||||
// Who am I? The frontend namespaces its per-account browser state by
|
||||
// this id and shows the signed-in writer.
|
||||
pr.Get("/me", users.MeHandler())
|
||||
|
||||
llmClient := llm.NewLLMClient(cfg)
|
||||
sug := suggestions.New(database, llmClient)
|
||||
@@ -128,8 +160,10 @@ func main() {
|
||||
// surfaced for gentle spaced-repetition review.
|
||||
pr.Mount("/vocab", vocab.New(database).Routes())
|
||||
|
||||
// Editor image uploads, stored on disk and served back by content hash.
|
||||
imgHandler, err := images.New(cfg.ImageDir)
|
||||
// Editor image uploads, stored on disk and served back by content hash
|
||||
// to whoever owns them. Files already on disk from before ownership
|
||||
// existed are claimed for the local user at startup.
|
||||
imgHandler, err := images.New(cfg.ImageDir, database.DB, db.LocalUserID)
|
||||
if err != nil {
|
||||
log.Fatalf("image store: %v", err)
|
||||
}
|
||||
@@ -145,6 +179,12 @@ func main() {
|
||||
})
|
||||
})
|
||||
|
||||
// Login lives outside /api: these are browser navigations, and they must be
|
||||
// reachable without a session — that is their entire job.
|
||||
if oidcClient != nil {
|
||||
r.Mount("/auth", oidcClient.Routes())
|
||||
}
|
||||
|
||||
// Everything else: serve the embedded SPA (with index.html fallback for client routing).
|
||||
r.NotFound(spaHandler())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user