feat(api): REST API for lists and members

- Add /api/v1 JSON endpoints: lists CRUD, members add/list/remove, health
- Protect routes with a constant-time bearer token check
- Reject unknown JSON fields and invalid names or addresses
- Map store errors to 404 and 409
This commit is contained in:
tgiachi 2026-11-09 14:57:43 +01:00
commit 7ce6a1c98e
2 changed files with 467 additions and 0 deletions

271
internal/api/api.go Normal file
View file

@ -0,0 +1,271 @@
// Package api exposes the administration REST API.
package api
import (
"crypto/subtle"
"encoding/json"
"errors"
"net/http"
"net/mail"
"strconv"
"strings"
"codeberg.org/squidd/parsimony/internal/store"
)
type server struct {
store *store.Store
token string
}
// New returns the API handler. Every route except /api/v1/health needs
// "Authorization: Bearer <token>". An empty token rejects all requests.
func New(s *store.Store, token string) http.Handler {
srv := &server{store: s, token: token}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/health", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.Handle("GET /api/v1/lists", srv.auth(srv.listLists))
mux.Handle("POST /api/v1/lists", srv.auth(srv.createList))
mux.Handle("GET /api/v1/lists/{id}", srv.auth(srv.getList))
mux.Handle("PATCH /api/v1/lists/{id}", srv.auth(srv.updateList))
mux.Handle("DELETE /api/v1/lists/{id}", srv.auth(srv.deleteList))
mux.Handle("GET /api/v1/lists/{id}/members", srv.auth(srv.listMembers))
mux.Handle("POST /api/v1/lists/{id}/members", srv.auth(srv.addMember))
mux.Handle("DELETE /api/v1/lists/{id}/members/{address}", srv.auth(srv.removeMember))
return mux
}
func (s *server) auth(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || s.token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(s.token)) != 1 {
w.Header().Set("WWW-Authenticate", `Bearer realm="parsimony"`)
writeError(w, http.StatusUnauthorized, "invalid or missing token")
return
}
next(w, r)
})
}
// JSON shapes.
type listDTO struct {
ID int64 `json:"id"`
Name string `json:"name"`
Domain string `json:"domain"`
Title string `json:"title"`
Address string `json:"address"`
}
func toListDTO(l store.List) listDTO {
return listDTO{ID: l.ID, Name: l.Name, Domain: l.Domain, Title: l.Title, Address: l.Address()}
}
type memberDTO struct {
Address string `json:"address"`
DisplayName string `json:"display_name"`
}
// Helpers.
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"error": msg})
}
// storeError maps store errors to HTTP responses.
func storeError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrNotFound):
writeError(w, http.StatusNotFound, "not found")
case errors.Is(err, store.ErrExists):
writeError(w, http.StatusConflict, "already exists")
default:
writeError(w, http.StatusInternalServerError, "internal error")
}
}
func decodeBody(w http.ResponseWriter, r *http.Request, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return false
}
return true
}
// listID parses the {id} path value. Anything unusable is a 404.
func listID(w http.ResponseWriter, r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusNotFound, "not found")
return 0, false
}
return id, true
}
// Handlers: lists.
func (s *server) listLists(w http.ResponseWriter, _ *http.Request) {
ls, err := s.store.ListLists()
if err != nil {
storeError(w, err)
return
}
out := make([]listDTO, 0, len(ls))
for _, l := range ls {
out = append(out, toListDTO(l))
}
writeJSON(w, http.StatusOK, out)
}
func (s *server) createList(w http.ResponseWriter, r *http.Request) {
var in struct {
Name string `json:"name"`
Domain string `json:"domain"`
Title string `json:"title"`
}
if !decodeBody(w, r, &in) {
return
}
in.Name, in.Domain = strings.TrimSpace(in.Name), strings.TrimSpace(in.Domain)
if in.Name == "" || in.Domain == "" || strings.ContainsAny(in.Name+in.Domain, "@ \r\n") {
writeError(w, http.StatusBadRequest, "name and domain are required and must not contain '@' or spaces")
return
}
if in.Title == "" {
in.Title = in.Name
}
l, err := s.store.CreateList(in.Name, in.Domain, in.Title)
if err != nil {
storeError(w, err)
return
}
writeJSON(w, http.StatusCreated, toListDTO(l))
}
func (s *server) getList(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
l, err := s.store.GetList(id)
if err != nil {
storeError(w, err)
return
}
writeJSON(w, http.StatusOK, toListDTO(l))
}
func (s *server) updateList(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
var in struct {
Title string `json:"title"`
}
if !decodeBody(w, r, &in) {
return
}
title := strings.TrimSpace(in.Title)
if title == "" || strings.ContainsAny(title, "\r\n") {
writeError(w, http.StatusBadRequest, "title is required and must be a single line")
return
}
if err := s.store.UpdateList(id, title); err != nil {
storeError(w, err)
return
}
l, err := s.store.GetList(id)
if err != nil {
storeError(w, err)
return
}
writeJSON(w, http.StatusOK, toListDTO(l))
}
func (s *server) deleteList(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
if err := s.store.DeleteList(id); err != nil {
storeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// Handlers: members.
func (s *server) listMembers(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
if _, err := s.store.GetList(id); err != nil {
storeError(w, err)
return
}
ms, err := s.store.Members(id)
if err != nil {
storeError(w, err)
return
}
out := make([]memberDTO, 0, len(ms))
for _, m := range ms {
out = append(out, memberDTO{Address: m.Address, DisplayName: m.DisplayName})
}
writeJSON(w, http.StatusOK, out)
}
func (s *server) addMember(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
var in memberDTO
if !decodeBody(w, r, &in) {
return
}
a, err := mail.ParseAddress(strings.TrimSpace(in.Address))
if err != nil || a.Name != "" {
writeError(w, http.StatusBadRequest, "a valid email address is required")
return
}
if strings.ContainsAny(in.DisplayName, "\r\n") {
writeError(w, http.StatusBadRequest, "display_name must be a single line")
return
}
if _, err := s.store.GetList(id); err != nil {
storeError(w, err)
return
}
if err := s.store.AddMember(id, a.Address, in.DisplayName); err != nil {
storeError(w, err)
return
}
writeJSON(w, http.StatusCreated, memberDTO{Address: strings.ToLower(a.Address), DisplayName: in.DisplayName})
}
func (s *server) removeMember(w http.ResponseWriter, r *http.Request) {
id, ok := listID(w, r)
if !ok {
return
}
if err := s.store.RemoveMember(id, r.PathValue("address")); err != nil {
storeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}

196
internal/api/api_test.go Normal file
View file

@ -0,0 +1,196 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"codeberg.org/squidd/parsimony/internal/store"
)
const token = "s3cret"
func newServer(t *testing.T) http.Handler {
t.Helper()
s, err := store.Open(":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
return New(s, token)
}
func do(t *testing.T, h http.Handler, method, path, body string, auth bool) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if auth {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func decode(t *testing.T, rec *httptest.ResponseRecorder, v any) {
t.Helper()
if err := json.Unmarshal(rec.Body.Bytes(), v); err != nil {
t.Fatalf("decode %q: %v", rec.Body.String(), err)
}
}
func expect(t *testing.T, rec *httptest.ResponseRecorder, code int) {
t.Helper()
if rec.Code != code {
t.Fatalf("status = %d, want %d, body %s", rec.Code, code, rec.Body.String())
}
}
func TestHealthNoAuth(t *testing.T) {
h := newServer(t)
expect(t, do(t, h, "GET", "/api/v1/health", "", false), 200)
}
func TestAuthRequired(t *testing.T) {
h := newServer(t)
expect(t, do(t, h, "GET", "/api/v1/lists", "", false), 401)
req := httptest.NewRequest("GET", "/api/v1/lists", nil)
req.Header.Set("Authorization", "Bearer wrong")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
expect(t, rec, 401)
if rec.Header().Get("WWW-Authenticate") == "" {
t.Error("missing WWW-Authenticate")
}
}
func TestEmptyTokenRejectsEverything(t *testing.T) {
s, _ := store.Open(":memory:")
defer s.Close()
h := New(s, "")
req := httptest.NewRequest("GET", "/api/v1/lists", nil)
req.Header.Set("Authorization", "Bearer ")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
expect(t, rec, 401)
}
type listJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
Domain string `json:"domain"`
Title string `json:"title"`
Address string `json:"address"`
}
func createList(t *testing.T, h http.Handler) listJSON {
t.Helper()
rec := do(t, h, "POST", "/api/v1/lists", `{"name":"dev","domain":"example.org","title":"Dev"}`, true)
expect(t, rec, 201)
var l listJSON
decode(t, rec, &l)
return l
}
func TestListsCRUD(t *testing.T) {
h := newServer(t)
rec := do(t, h, "GET", "/api/v1/lists", "", true)
expect(t, rec, 200)
if strings.TrimSpace(rec.Body.String()) != "[]" {
t.Fatalf("empty list should be [], got %s", rec.Body.String())
}
l := createList(t, h)
if l.ID == 0 || l.Address != "dev@example.org" || l.Title != "Dev" {
t.Fatalf("created: %+v", l)
}
expect(t, do(t, h, "POST", "/api/v1/lists", `{"name":"dev","domain":"example.org"}`, true), 409)
rec = do(t, h, "GET", "/api/v1/lists", "", true)
var all []listJSON
decode(t, rec, &all)
if len(all) != 1 {
t.Fatalf("lists: %+v", all)
}
rec = do(t, h, "GET", "/api/v1/lists/1", "", true)
expect(t, rec, 200)
expect(t, do(t, h, "GET", "/api/v1/lists/99", "", true), 404)
expect(t, do(t, h, "GET", "/api/v1/lists/abc", "", true), 404)
rec = do(t, h, "PATCH", "/api/v1/lists/1", `{"title":"Renamed"}`, true)
expect(t, rec, 200)
var u listJSON
decode(t, rec, &u)
if u.Title != "Renamed" {
t.Fatalf("patched: %+v", u)
}
expect(t, do(t, h, "PATCH", "/api/v1/lists/99", `{"title":"x"}`, true), 404)
expect(t, do(t, h, "PATCH", "/api/v1/lists/1", `{}`, true), 400)
expect(t, do(t, h, "DELETE", "/api/v1/lists/1", "", true), 204)
expect(t, do(t, h, "DELETE", "/api/v1/lists/1", "", true), 404)
}
func TestCreateListValidation(t *testing.T) {
h := newServer(t)
for _, body := range []string{
`not json`,
`{}`,
`{"name":"","domain":"example.org"}`,
`{"name":"a@b","domain":"example.org"}`,
`{"name":"dev","domain":""}`,
`{"name":"dev","domain":"example.org","bogus":1}`,
} {
rec := do(t, h, "POST", "/api/v1/lists", body, true)
if rec.Code != 400 {
t.Errorf("%q: status %d, want 400", body, rec.Code)
}
var e struct{ Error string }
decode(t, rec, &e)
if e.Error == "" {
t.Errorf("%q: missing error message", body)
}
}
}
type memberJSON struct {
Address string `json:"address"`
DisplayName string `json:"display_name"`
}
func TestMembers(t *testing.T) {
h := newServer(t)
createList(t, h)
rec := do(t, h, "GET", "/api/v1/lists/1/members", "", true)
expect(t, rec, 200)
if strings.TrimSpace(rec.Body.String()) != "[]" {
t.Fatalf("want [], got %s", rec.Body.String())
}
rec = do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"Alice@Example.com","display_name":"Alice"}`, true)
expect(t, rec, 201)
var m memberJSON
decode(t, rec, &m)
if m.Address != "alice@example.com" || m.DisplayName != "Alice" {
t.Fatalf("member: %+v", m)
}
rec = do(t, h, "GET", "/api/v1/lists/1/members", "", true)
var ms []memberJSON
decode(t, rec, &ms)
if len(ms) != 1 {
t.Fatalf("members: %+v", ms)
}
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"not-an-address"}`, true), 400)
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{}`, true), 400)
expect(t, do(t, h, "POST", "/api/v1/lists/99/members", `{"address":"a@b.com"}`, true), 404)
expect(t, do(t, h, "GET", "/api/v1/lists/99/members", "", true), 404)
expect(t, do(t, h, "DELETE", "/api/v1/lists/1/members/alice%40example.com", "", true), 204)
expect(t, do(t, h, "DELETE", "/api/v1/lists/1/members/alice%40example.com", "", true), 404)
}