Add gardens CRUD + service-layer conventions (#7)
Build image / build-and-push (push) Successful in 4s
Gadfly review (reusable) / review (pull_request) Successful in 9m56s
Adversarial Review (Gadfly) / review (pull_request) Successful in 9m56s

Establishes the patterns every later backend issue copies: the actor
parameter, centralized role checks, and the version-guard/409 sync
protocol. The service layer is the seam both REST handlers and future
agent tools call, so permissions live here, not in handlers.

- service/gardens.go: Service methods take (ctx, actorID, args).
  requireGardenRole(ctx, actor, gardenID, min) is THE authorization point
  — owner is implicit via owner_id now; #16 extends it to consult
  garden_shares. A user with no role gets ErrNotFound (existence masked),
  not ErrForbidden. Create/Get/List/Update/Delete with input validation
  (name required, 0 dims default to 10 m on create / rejected on update,
  negatives always rejected, unit metric|imperial, 100 m cap).
- store/gardens.go: version-guarded UPDATE ... WHERE id=? AND version=?
  RETURNING; a no-match re-reads to return (current row,
  ErrVersionConflict) vs ErrNotFound. ListGardensForOwner returns a
  non-nil slice.
- api/gardens.go: GET,POST /gardens and GET,PATCH,DELETE /gardens/:id
  behind requireAuth. writeVersionConflict documents the 409 envelope
  ({error:{code,message}, current:{...}}) — the contract for every
  mutable resource. writeResourceError maps ErrNotFound/Forbidden/
  InvalidInput/VersionConflict; parseIDParam guards path ids.

Tests: service (defaults, validation, owned-only list, version
conflict returns current + retry, cross-user ErrNotFound, delete) and
api (full CRUD flow, 409 envelope shape, cross-user 404, auth required,
create validation). Verified against the running binary: create stores
imperial 122x244 cm and list returns it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
2026-07-18 18:20:39 -04:00
co-authored by Claude Opus 4.8
parent 03f2eb2d5c
commit f39ed52868
6 changed files with 814 additions and 0 deletions
+9
View File
@@ -73,6 +73,15 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
slog.Warn("api: OIDC is configured but PANSY_BASE_URL is unset; OIDC disabled (an absolute redirect URI is required)")
}
// Feature resources sit behind requireAuth, which resolves the session cookie
// to the actor the service layer's permission checks key off.
gardens := v1.Group("/gardens", h.requireAuth())
gardens.GET("", h.listGardens)
gardens.POST("", h.createGarden)
gardens.GET("/:id", h.getGarden)
gardens.PATCH("/:id", h.updateGarden)
gardens.DELETE("/:id", h.deleteGarden)
return r
}
+158
View File
@@ -0,0 +1,158 @@
package api
import (
"errors"
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
)
// gardenCreateRequest / gardenUpdateRequest are the JSON bodies for the gardens
// endpoints. Dimensions are centimeters (the API is metric-only; imperial is a
// display concern). On create, omitted dimensions default server-side; on
// update, version is required and every field is replaced.
type gardenCreateRequest struct {
Name string `json:"name" binding:"required"`
WidthCM float64 `json:"widthCm"`
HeightCM float64 `json:"heightCm"`
UnitPref string `json:"unitPref"`
Notes string `json:"notes"`
}
type gardenUpdateRequest struct {
Name string `json:"name" binding:"required"`
WidthCM float64 `json:"widthCm"`
HeightCM float64 `json:"heightCm"`
UnitPref string `json:"unitPref"`
Notes string `json:"notes"`
Version int64 `json:"version" binding:"required"`
}
func (r gardenCreateRequest) toInput() service.GardenInput {
return service.GardenInput{Name: r.Name, WidthCM: r.WidthCM, HeightCM: r.HeightCM, UnitPref: r.UnitPref, Notes: r.Notes}
}
func (r gardenUpdateRequest) toInput() service.GardenInput {
return service.GardenInput{Name: r.Name, WidthCM: r.WidthCM, HeightCM: r.HeightCM, UnitPref: r.UnitPref, Notes: r.Notes}
}
// listGardens returns the actor's gardens as a JSON array (always an array,
// never null).
func (h *handlers) listGardens(c *gin.Context) {
gardens, err := h.svc.ListGardens(c.Request.Context(), mustActor(c).ID)
if err != nil {
writeResourceError(c, err)
return
}
c.JSON(http.StatusOK, gardens)
}
func (h *handlers) createGarden(c *gin.Context) {
var req gardenCreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a garden name is required")
return
}
g, err := h.svc.CreateGarden(c.Request.Context(), mustActor(c).ID, req.toInput())
if err != nil {
writeResourceError(c, err)
return
}
c.JSON(http.StatusCreated, g)
}
func (h *handlers) getGarden(c *gin.Context) {
id, ok := parseIDParam(c, "id")
if !ok {
return
}
g, err := h.svc.GetGarden(c.Request.Context(), mustActor(c).ID, id)
if err != nil {
writeResourceError(c, err)
return
}
c.JSON(http.StatusOK, g)
}
func (h *handlers) updateGarden(c *gin.Context) {
id, ok := parseIDParam(c, "id")
if !ok {
return
}
var req gardenUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "name and a current version are required")
return
}
g, err := h.svc.UpdateGarden(c.Request.Context(), mustActor(c).ID, id, req.toInput(), req.Version)
if err != nil {
// On a version conflict the service returns the current row so the client
// can rebase; everything else is a plain error.
if errors.Is(err, domain.ErrVersionConflict) {
writeVersionConflict(c, g)
return
}
writeResourceError(c, err)
return
}
c.JSON(http.StatusOK, g)
}
func (h *handlers) deleteGarden(c *gin.Context) {
id, ok := parseIDParam(c, "id")
if !ok {
return
}
if err := h.svc.DeleteGarden(c.Request.Context(), mustActor(c).ID, id); err != nil {
writeResourceError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// parseIDParam reads a positive int64 path parameter, writing a 400 and
// returning ok=false on a malformed value.
func parseIDParam(c *gin.Context, name string) (int64, bool) {
id, err := strconv.ParseInt(c.Param(name), 10, 64)
if err != nil || id < 1 {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid id")
return 0, false
}
return id, true
}
// writeVersionConflict writes the 409 envelope for an optimistic-concurrency
// failure: the standard error object plus the current server row under
// "current", so the client can rebase its edit onto the fresh version and retry.
// This shape is the contract for every version-guarded (mutable) resource.
func writeVersionConflict(c *gin.Context, current any) {
c.JSON(http.StatusConflict, gin.H{
"error": gin.H{"code": "VERSION_CONFLICT", "message": "the resource was modified; refetch and retry"},
"current": current,
})
}
// writeResourceError maps the service-layer sentinel errors shared by every
// resource to pansy's JSON error envelope. ErrNotFound is used both for a
// genuinely missing row and for one the actor may not see (existence is masked).
func writeResourceError(c *gin.Context, err error) {
switch {
case errors.Is(err, domain.ErrNotFound):
writeAPIError(c, http.StatusNotFound, "NOT_FOUND", "not found")
case errors.Is(err, domain.ErrForbidden):
writeAPIError(c, http.StatusForbidden, "FORBIDDEN", "you don't have access")
case errors.Is(err, domain.ErrInvalidInput):
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid input")
case errors.Is(err, domain.ErrVersionConflict):
// Reached only if a caller forgot to special-case the conflict (which
// needs the current row); still return a coherent 409.
writeAPIError(c, http.StatusConflict, "VERSION_CONFLICT", "the resource was modified; refetch and retry")
default:
slog.Error("api: unhandled service error", "error", err)
writeAPIError(c, http.StatusInternalServerError, "INTERNAL", "internal error")
}
}
+167
View File
@@ -0,0 +1,167 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"testing"
"github.com/gin-gonic/gin"
)
// registerAndCookie creates a user via the API and returns its session cookie.
func registerAndCookie(t *testing.T, r *gin.Engine, email string) *http.Cookie {
t.Helper()
w := doJSON(t, r, http.MethodPost, "/api/v1/auth/register",
map[string]string{"email": email, "displayName": email, "password": "password123"}, nil)
if w.Code != http.StatusOK {
t.Fatalf("register %s: status %d, body %s", email, w.Code, w.Body.String())
}
return sessionCookieFrom(t, w)
}
func decodeGarden(t *testing.T, body []byte) map[string]any {
t.Helper()
var g map[string]any
if err := json.Unmarshal(body, &g); err != nil {
t.Fatalf("decode garden: %v (body %s)", err, body)
}
return g
}
func TestGardenCRUDFlow(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
// Create (defaults applied) → 201.
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Backyard"}, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
}
created := decodeGarden(t, w.Body.Bytes())
id := int64(created["id"].(float64))
if created["widthCm"].(float64) != 1000 || created["unitPref"].(string) != "metric" {
t.Errorf("defaults not applied: %+v", created)
}
// List → array with one garden.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, cookie)
if w.Code != http.StatusOK {
t.Fatalf("list status = %d", w.Code)
}
var list []map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("decode list: %v (body %s)", err, w.Body.String())
}
if len(list) != 1 {
t.Errorf("list len = %d, want 1", len(list))
}
// Get → 200.
w = doJSON(t, r, http.MethodGet, gardenPath(id), nil, cookie)
if w.Code != http.StatusOK {
t.Fatalf("get status = %d", w.Code)
}
// Patch with the current version → 200, version bumped.
w = doJSON(t, r, http.MethodPatch, gardenPath(id),
map[string]any{"name": "Front", "widthCm": 200, "heightCm": 400, "unitPref": "imperial", "version": 1}, cookie)
if w.Code != http.StatusOK {
t.Fatalf("patch status = %d, body %s", w.Code, w.Body.String())
}
patched := decodeGarden(t, w.Body.Bytes())
if patched["name"].(string) != "Front" || patched["version"].(float64) != 2 {
t.Errorf("patch didn't persist/bump: %+v", patched)
}
// Delete → 204, then get → 404.
w = doJSON(t, r, http.MethodDelete, gardenPath(id), nil, cookie)
if w.Code != http.StatusNoContent {
t.Fatalf("delete status = %d", w.Code)
}
w = doJSON(t, r, http.MethodGet, gardenPath(id), nil, cookie)
if w.Code != http.StatusNotFound {
t.Errorf("get after delete = %d, want 404", w.Code)
}
}
func TestGardenVersionConflictEnvelope(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
id := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
body := map[string]any{"name": "Yard2", "widthCm": 1000, "heightCm": 1000, "unitPref": "metric", "version": 1}
// First patch at version 1 succeeds (→ version 2).
if w := doJSON(t, r, http.MethodPatch, gardenPath(id), body, cookie); w.Code != http.StatusOK {
t.Fatalf("first patch status = %d", w.Code)
}
// Second patch still at version 1 conflicts.
w = doJSON(t, r, http.MethodPatch, gardenPath(id), body, cookie)
if w.Code != http.StatusConflict {
t.Fatalf("stale patch status = %d, want 409", w.Code)
}
var env struct {
Error struct{ Code string } `json:"error"`
Current map[string]any `json:"current"`
}
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode conflict envelope: %v (body %s)", err, w.Body.String())
}
if env.Error.Code != "VERSION_CONFLICT" {
t.Errorf("error code = %q, want VERSION_CONFLICT", env.Error.Code)
}
if env.Current == nil || env.Current["version"].(float64) != 2 {
t.Errorf("conflict body missing current row at version 2: %+v", env.Current)
}
}
func TestGardenCrossUserIsNotFound(t *testing.T) {
r := authEngine(t, localCfg())
alice := registerAndCookie(t, r, "[email protected]")
bob := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Alice's"}, alice)
id := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
// Bob sees a 404 (existence masked), not a 403.
if w := doJSON(t, r, http.MethodGet, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
t.Errorf("bob get = %d, want 404", w.Code)
}
if w := doJSON(t, r, http.MethodDelete, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
t.Errorf("bob delete = %d, want 404", w.Code)
}
// Bob's own list is empty.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, bob)
if w.Body.String() != "[]" {
t.Errorf("bob list = %s, want []", w.Body.String())
}
}
func TestGardenRequiresAuth(t *testing.T) {
r := authEngine(t, localCfg())
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated list = %d, want 401", w.Code)
}
if w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "X"}, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated create = %d, want 401", w.Code)
}
}
func TestGardenCreateValidation(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
// Missing name → 400.
if w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"widthCm": 100}, cookie); w.Code != http.StatusBadRequest {
t.Errorf("no-name create = %d, want 400", w.Code)
}
// Bad id path → 400.
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens/not-a-number", nil, cookie); w.Code != http.StatusBadRequest {
t.Errorf("bad id get = %d, want 400", w.Code)
}
}
func gardenPath(id int64) string {
return "/api/v1/gardens/" + strconv.FormatInt(id, 10)
}