diff --git a/README.md b/README.md index de2f36f..042171c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,22 @@ # parsimony A modern, single-binary mailing list manager: an evolution of Mailman. + +- Postfix delivers to parsimony over LMTP; parsimony relays through SMTP. +- Discussion lists with member-only posting, `List-*` headers, one-click unsubscribe + and DMARC-safe `From` rewriting. +- SQLite storage, one YAML config file. +- Admin REST API under `/api/v1` (see `docs/openapi.yaml`). + +## Run + +``` +cp parsimony.example.yaml parsimony.yaml +PARSIMONY_API_TOKEN= go run ./cmd/parsimony -config parsimony.yaml +``` + +The API is disabled when `PARSIMONY_API_TOKEN` is not set. + +``` +curl -H "Authorization: Bearer $PARSIMONY_API_TOKEN" -d '{"name":"dev","domain":"example.org","title":"Dev"}' localhost:8080/api/v1/lists +``` diff --git a/docs/openapi.yaml b/docs/openapi.yaml new file mode 100644 index 0000000..ad0a4db --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,151 @@ +openapi: 3.0.3 +info: + title: Parsimony admin API + version: 1.0.0 +servers: + - url: /api/v1 +security: + - bearer: [] +components: + securitySchemes: + bearer: + type: http + scheme: bearer + schemas: + List: + type: object + properties: + id: {type: integer} + name: {type: string} + domain: {type: string} + title: {type: string} + address: {type: string} + Member: + type: object + properties: + address: {type: string} + display_name: {type: string} + Error: + type: object + properties: + error: {type: string} + responses: + Error: + description: Error + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} +paths: + /health: + get: + security: [] + summary: Liveness check + responses: + '200': {description: OK} + /lists: + get: + summary: List all lists + responses: + '200': + description: OK + content: + application/json: + schema: {type: array, items: {$ref: '#/components/schemas/List'}} + post: + summary: Create a list + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name, domain] + properties: + name: {type: string} + domain: {type: string} + title: {type: string} + responses: + '201': + description: Created + content: + application/json: + schema: {$ref: '#/components/schemas/List'} + '400': {$ref: '#/components/responses/Error'} + '409': {$ref: '#/components/responses/Error'} + /lists/{id}: + parameters: + - {name: id, in: path, required: true, schema: {type: integer}} + get: + summary: Get a list + responses: + '200': + description: OK + content: + application/json: + schema: {$ref: '#/components/schemas/List'} + '404': {$ref: '#/components/responses/Error'} + patch: + summary: Update the list title + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [title] + properties: + title: {type: string} + responses: + '200': + description: OK + content: + application/json: + schema: {$ref: '#/components/schemas/List'} + '400': {$ref: '#/components/responses/Error'} + '404': {$ref: '#/components/responses/Error'} + delete: + summary: Delete a list and its members + responses: + '204': {description: Deleted} + '404': {$ref: '#/components/responses/Error'} + /lists/{id}/members: + parameters: + - {name: id, in: path, required: true, schema: {type: integer}} + get: + summary: List members + responses: + '200': + description: OK + content: + application/json: + schema: {type: array, items: {$ref: '#/components/schemas/Member'}} + '404': {$ref: '#/components/responses/Error'} + post: + summary: Add a member (idempotent) + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [address] + properties: + address: {type: string} + display_name: {type: string} + responses: + '201': + description: Created + content: + application/json: + schema: {$ref: '#/components/schemas/Member'} + '400': {$ref: '#/components/responses/Error'} + '404': {$ref: '#/components/responses/Error'} + /lists/{id}/members/{address}: + parameters: + - {name: id, in: path, required: true, schema: {type: integer}} + - {name: address, in: path, required: true, schema: {type: string}} + delete: + summary: Remove a member + responses: + '204': {description: Removed} + '404': {$ref: '#/components/responses/Error'} diff --git a/internal/api/api.go b/internal/api/api.go new file mode 100644 index 0000000..9dbb9d8 --- /dev/null +++ b/internal/api/api.go @@ -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 ". 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) +} diff --git a/internal/api/api_test.go b/internal/api/api_test.go new file mode 100644 index 0000000..5d583e4 --- /dev/null +++ b/internal/api/api_test.go @@ -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) +} diff --git a/internal/config/config.go b/internal/config/config.go index 6693b08..83027b5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -17,6 +17,9 @@ type Config struct { Network string `yaml:"network"` // tcp or unix Addr string `yaml:"addr"` } `yaml:"lmtp"` + API struct { + Listen string `yaml:"listen"` // HTTP listen address; the bearer token comes from PARSIMONY_API_TOKEN + } `yaml:"api"` Relay struct { Addr string `yaml:"addr"` // host:port of the outgoing SMTP relay } `yaml:"relay"` @@ -29,6 +32,7 @@ func Load(path string) (Config, error) { c.LMTP.Network = "tcp" c.LMTP.Addr = "127.0.0.1:2424" c.Relay.Addr = "127.0.0.1:25" + c.API.Listen = "127.0.0.1:8080" b, err := os.ReadFile(path) if err != nil { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index d8721a0..99d0729 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -20,17 +20,17 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if c.DB != "parsimony.db" || c.LMTP.Network != "tcp" || c.LMTP.Addr != "127.0.0.1:2424" || c.Relay.Addr != "127.0.0.1:25" { + if c.DB != "parsimony.db" || c.LMTP.Network != "tcp" || c.LMTP.Addr != "127.0.0.1:2424" || c.Relay.Addr != "127.0.0.1:25" || c.API.Listen != "127.0.0.1:8080" { t.Fatalf("defaults: %+v", c) } } func TestLoadValues(t *testing.T) { - c, err := Load(write(t, "db: /var/lib/p.db\nbase_url: https://l.example.org\nlmtp:\n network: unix\n addr: /run/p.sock\nrelay:\n addr: mx:587\n")) + c, err := Load(write(t, "db: /var/lib/p.db\nbase_url: https://l.example.org\nlmtp:\n network: unix\n addr: /run/p.sock\nrelay:\n addr: mx:587\napi:\n listen: 0.0.0.0:9000\n")) if err != nil { t.Fatal(err) } - if c.DB != "/var/lib/p.db" || c.BaseURL != "https://l.example.org" || c.LMTP.Network != "unix" || c.LMTP.Addr != "/run/p.sock" || c.Relay.Addr != "mx:587" { + if c.DB != "/var/lib/p.db" || c.BaseURL != "https://l.example.org" || c.LMTP.Network != "unix" || c.LMTP.Addr != "/run/p.sock" || c.Relay.Addr != "mx:587" || c.API.Listen != "0.0.0.0:9000" { t.Fatalf("values: %+v", c) } } diff --git a/internal/store/store.go b/internal/store/store.go index 3884cd4..9bf527f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -13,6 +13,9 @@ import ( // ErrNotFound is returned when a list or member does not exist. var ErrNotFound = errors.New("not found") +// ErrExists is returned when creating something that already exists. +var ErrExists = errors.New("already exists") + // List is a mailing list. type List struct { ID int64 @@ -75,6 +78,9 @@ func (s *Store) CreateList(name, domain, title string) (List, error) { l := List{Name: strings.ToLower(name), Domain: strings.ToLower(domain), Title: title} res, err := s.db.Exec(`INSERT INTO lists(name, domain, title) VALUES(?,?,?)`, l.Name, l.Domain, l.Title) if err != nil { + if strings.Contains(err.Error(), "UNIQUE") { + return List{}, ErrExists + } return List{}, err } l.ID, _ = res.LastInsertId() @@ -128,3 +134,58 @@ func (s *Store) Members(listID int64) ([]Member, error) { } return out, rows.Err() } + +// ListLists returns every list ordered by address. +func (s *Store) ListLists() ([]List, error) { + rows, err := s.db.Query(`SELECT id, name, domain, title FROM lists ORDER BY domain, name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []List + for rows.Next() { + var l List + if err := rows.Scan(&l.ID, &l.Name, &l.Domain, &l.Title); err != nil { + return nil, err + } + out = append(out, l) + } + return out, rows.Err() +} + +// GetList returns a list by id. +func (s *Store) GetList(id int64) (List, error) { + var l List + err := s.db.QueryRow(`SELECT id, name, domain, title FROM lists WHERE id=?`, id). + Scan(&l.ID, &l.Name, &l.Domain, &l.Title) + if errors.Is(err, sql.ErrNoRows) { + return List{}, ErrNotFound + } + return l, err +} + +func affected(res sql.Result, err error) error { + if err != nil { + return err + } + if n, _ := res.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +// UpdateList changes the title of a list. +func (s *Store) UpdateList(id int64, title string) error { + return affected(s.db.Exec(`UPDATE lists SET title=? WHERE id=?`, title, id)) +} + +// DeleteList removes a list and its members. +func (s *Store) DeleteList(id int64) error { + return affected(s.db.Exec(`DELETE FROM lists WHERE id=?`, id)) +} + +// RemoveMember unsubscribes an address from a list. +func (s *Store) RemoveMember(listID int64, addr string) error { + return affected(s.db.Exec(`DELETE FROM members WHERE list_id=? AND address=?`, + listID, strings.ToLower(strings.TrimSpace(addr)))) +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go index afecaf1..3aa8483 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -63,3 +63,64 @@ func TestMembers(t *testing.T) { t.Fatalf("members: %+v %v", ms, err) } } + +func TestListLifecycle(t *testing.T) { + s := newTestStore(t) + a, _ := s.CreateList("a", "example.org", "A") + s.CreateList("b", "example.org", "B") + + ls, err := s.ListLists() + if err != nil || len(ls) != 2 { + t.Fatalf("lists: %+v %v", ls, err) + } + got, err := s.GetList(a.ID) + if err != nil || got.Name != "a" { + t.Fatalf("get: %+v %v", got, err) + } + if _, err := s.GetList(999); !errors.Is(err, ErrNotFound) { + t.Fatalf("want ErrNotFound, got %v", err) + } + if err := s.UpdateList(a.ID, "New title"); err != nil { + t.Fatal(err) + } + got, _ = s.GetList(a.ID) + if got.Title != "New title" { + t.Fatalf("title = %q", got.Title) + } + if err := s.UpdateList(999, "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("want ErrNotFound, got %v", err) + } + s.AddMember(a.ID, "x@y.com", "") + if err := s.DeleteList(a.ID); err != nil { + t.Fatal(err) + } + if _, err := s.GetList(a.ID); !errors.Is(err, ErrNotFound) { + t.Fatal("list should be gone") + } + if err := s.DeleteList(a.ID); !errors.Is(err, ErrNotFound) { + t.Fatalf("want ErrNotFound, got %v", err) + } +} + +func TestDuplicateList(t *testing.T) { + s := newTestStore(t) + s.CreateList("a", "example.org", "A") + if _, err := s.CreateList("A", "Example.org", "again"); !errors.Is(err, ErrExists) { + t.Fatalf("want ErrExists, got %v", err) + } +} + +func TestRemoveMember(t *testing.T) { + s := newTestStore(t) + l, _ := s.CreateList("a", "example.org", "A") + s.AddMember(l.ID, "x@y.com", "") + if err := s.RemoveMember(l.ID, "X@y.com"); err != nil { + t.Fatal(err) + } + if ok, _ := s.IsMember(l.ID, "x@y.com"); ok { + t.Fatal("still a member") + } + if err := s.RemoveMember(l.ID, "x@y.com"); !errors.Is(err, ErrNotFound) { + t.Fatalf("want ErrNotFound, got %v", err) + } +} diff --git a/parsimony.example.yaml b/parsimony.example.yaml index 1475d39..7240253 100644 --- a/parsimony.example.yaml +++ b/parsimony.example.yaml @@ -5,3 +5,6 @@ lmtp: addr: 0.0.0.0:2424 relay: addr: postfix:25 +api: + listen: 0.0.0.0:8080 +# The API token is read from the PARSIMONY_API_TOKEN environment variable.