Files
petal/internal/docs/handlers_test.go
T
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

114 lines
3.7 KiB
Go

package docs
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"gitea.parodia.dev/drwily/petal/internal/auth"
"gitea.parodia.dev/drwily/petal/internal/db"
)
// newTestServer spins up an isolated on-disk database and the docs router,
// behind the same auth middleware main.go installs. Tests must go through it:
// handlers read the caller from the request context, so a router mounted bare
// would see an empty user id and match no rows.
func newTestServer(t *testing.T) http.Handler {
t.Helper()
database, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { database.Close() })
return withAuth(New(database).Routes())
}
// withAuth wraps a router so every test request arrives authenticated as the
// seeded local user — the stand-in for a real session until Authentik lands.
func withAuth(h http.Handler) http.Handler {
return auth.Middleware(auth.StaticResolver(db.LocalUserID))(h)
}
func do(t *testing.T, srv http.Handler, method, path, body string) *httptest.ResponseRecorder {
t.Helper()
var r *http.Request
if body != "" {
r = httptest.NewRequest(method, path, bytes.NewBufferString(body))
} else {
r = httptest.NewRequest(method, path, nil)
}
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, r)
return rec
}
func TestDocumentCRUD(t *testing.T) {
srv := newTestServer(t)
// Empty list serializes as [].
rec := do(t, srv, http.MethodGet, "/", "")
if rec.Code != http.StatusOK || bytes.TrimSpace(rec.Body.Bytes())[0] != '[' {
t.Fatalf("list empty: code=%d body=%s", rec.Code, rec.Body)
}
// Create.
rec = do(t, srv, http.MethodPost, "/", "")
if rec.Code != http.StatusCreated {
t.Fatalf("create: code=%d body=%s", rec.Code, rec.Body)
}
var created db.Document
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil {
t.Fatalf("decode create: %v", err)
}
if created.ID == "" || created.Title != "Untitled" {
t.Fatalf("unexpected created doc: %+v", created)
}
// Update (auto-save shape) keeps content + content_text + word count together.
body := `{"title":"My Essay","content":"{\"x\":1}","content_text":"hello world","word_count":2}`
rec = do(t, srv, http.MethodPut, "/"+created.ID, body)
if rec.Code != http.StatusOK {
t.Fatalf("update: code=%d body=%s", rec.Code, rec.Body)
}
var updated db.Document
_ = json.Unmarshal(rec.Body.Bytes(), &updated)
if updated.Title != "My Essay" || updated.ContentText != "hello world" || updated.WordCount != 2 {
t.Fatalf("update not applied: %+v", updated)
}
// Partial update (rename only) leaves other fields intact.
rec = do(t, srv, http.MethodPut, "/"+created.ID, `{"title":"Renamed"}`)
_ = json.Unmarshal(rec.Body.Bytes(), &updated)
if updated.Title != "Renamed" || updated.WordCount != 2 {
t.Fatalf("partial update clobbered fields: %+v", updated)
}
// Get.
rec = do(t, srv, http.MethodGet, "/"+created.ID, "")
if rec.Code != http.StatusOK {
t.Fatalf("get: code=%d", rec.Code)
}
// List now has one entry.
rec = do(t, srv, http.MethodGet, "/", "")
var summaries []docSummary
_ = json.Unmarshal(rec.Body.Bytes(), &summaries)
if len(summaries) != 1 || summaries[0].Title != "Renamed" {
t.Fatalf("list after create: %+v", summaries)
}
// Delete, then 404 on subsequent get/delete.
if rec = do(t, srv, http.MethodDelete, "/"+created.ID, ""); rec.Code != http.StatusNoContent {
t.Fatalf("delete: code=%d", rec.Code)
}
if rec = do(t, srv, http.MethodGet, "/"+created.ID, ""); rec.Code != http.StatusNotFound {
t.Fatalf("get after delete: code=%d", rec.Code)
}
if rec = do(t, srv, http.MethodPut, "/missing", `{"title":"x"}`); rec.Code != http.StatusNotFound {
t.Fatalf("update missing: code=%d", rec.Code)
}
}