Files
prosolis 6901cdbbe4 Multi-user groundwork: request-scoped user identity
Petal ran as a single hardcoded user, with db.LocalUserID named directly
at ~35 query sites. That made the caller's identity a compile-time
constant scattered across every package — nothing a real login could
replace without touching all of them.

New internal/auth moves it into the request context:

  - Middleware(Resolver) resolves the caller once per API request
  - handlers read auth.UserID(r.Context()) instead of naming a user
  - Resolver is the seam an Authentik session check drops into
  - StaticResolver(db.LocalUserID) keeps Petal single-user today

Behavior is unchanged. UserID returns "" rather than panicking when the
middleware is absent, so a mis-wired route fails closed: every query is
WHERE user_id = ?, which then matches nothing.

main.go splits /api into a public group (/health, /version) and an
authenticated group for everything else — a monitoring probe must not
need a session.

Two pre-existing access-control gaps fixed while threading, both
harmless with one user and not with two:

  - setStatus (accept/dismiss) updated a suggestion by bare id with no
    ownership check at all
  - listForDoc/fetchPending read a document's suggestions by doc_id
    alone; a suggestion quotes the sentence it corrects, so that leaked
    the source prose

Both now scope through documents.user_id.

Tests: internal/auth covers the context round-trip, the absent-context
case, and both 401 paths. Two-user isolation suites in docs and
suggestions mount the same routers twice behind two resolvers over one
database and assert a stranger gets 404 on every id-taking path, sees
nothing in list/search, and leaves the owner's data untouched.

Those suites earned their keep immediately: docs.fetch gained a userID
parameter but kept binding db.LocalUserID in the query. Unused
parameters are legal Go, so it compiled clean, vet was silent, and every
existing test passed while the lookup stayed unscoped.

Still global, out of scope and flagged in BUILD_PLAN.md: the image store
has no per-user association, and frontend localStorage keys are
per-browser rather than per-account.
2026-07-26 21:42:37 -07:00

76 lines
2.3 KiB
Go

package auth
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
// errResolver rejects every request, standing in for a real resolver that finds
// no valid session.
type errResolver struct{ err error }
func (e errResolver) Resolve(*http.Request) (string, error) { return "", e.err }
func TestUserIDRoundTrip(t *testing.T) {
ctx := WithUser(context.Background(), "alice")
if got := UserID(ctx); got != "alice" {
t.Fatalf("UserID = %q, want alice", got)
}
}
// A request that never passed through the middleware must report no user rather
// than panicking — every query is `WHERE user_id = ?`, so an empty id fails
// closed (matches nothing) instead of falling back to some default account.
func TestUserIDAbsentIsEmpty(t *testing.T) {
if got := UserID(context.Background()); got != "" {
t.Fatalf("UserID on bare context = %q, want empty", got)
}
}
func TestMiddlewareInjectsResolvedUser(t *testing.T) {
var seen string
h := Middleware(StaticResolver("local"))(http.HandlerFunc(
func(_ http.ResponseWriter, r *http.Request) { seen = UserID(r.Context()) },
))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if seen != "local" {
t.Fatalf("handler saw user %q, want local", seen)
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
}
// Both rejection paths — an explicit error and a silent empty id — must 401
// without ever entering the handler. The empty case matters most: a resolver
// that returns ("", nil) by mistake would otherwise hand handlers an empty user
// id, and while that fails closed at the SQL layer, it should never get there.
func TestMiddlewareRejectsUnresolved(t *testing.T) {
for name, res := range map[string]Resolver{
"resolver error": errResolver{err: http.ErrNoCookie},
"empty user id": StaticResolver(""),
} {
t.Run(name, func(t *testing.T) {
called := false
h := Middleware(res)(http.HandlerFunc(
func(http.ResponseWriter, *http.Request) { called = true },
))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if called {
t.Fatal("handler ran for an unauthenticated request")
}
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
}
}