Sharing backend: shares CRUD + ACL enforcement everywhere (#16)
Build image / build-and-push (push) Successful in 4s

Co-authored-by: Steve Dudenhoeffer <[email protected]>
This commit was merged in pull request #35.
This commit is contained in:
2026-07-19 03:49:54 +00:00
committed by steve
parent 48ba08e8f2
commit 2a86f87b50
11 changed files with 733 additions and 24 deletions
+6
View File
@@ -84,6 +84,12 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
gardens.GET("/:id/full", h.getGardenFull) // one-shot editor load
gardens.POST("/:id/objects", h.createObject)
// Sharing (owner-managed; a recipient may remove their own share).
gardens.GET("/:id/shares", h.listShares)
gardens.POST("/:id/shares", h.addShare)
gardens.PATCH("/:id/shares/:userId", h.updateShare)
gardens.DELETE("/:id/shares/:userId", h.removeShare)
// Objects are addressed by their own id; the service resolves the owning
// garden for the permission check.
objects := v1.Group("/objects", h.requireAuth())
+6
View File
@@ -30,6 +30,12 @@ func writeServiceError(c *gin.Context, err error) {
writeAPIError(c, http.StatusConflict, "VERSION_CONFLICT", "the resource was modified; refetch and retry")
case errors.Is(err, domain.ErrPlantInUse):
writeAPIError(c, http.StatusConflict, "PLANT_IN_USE", "this plant is used by plantings and can't be deleted")
case errors.Is(err, domain.ErrShareUserNotFound):
writeAPIError(c, http.StatusNotFound, "SHARE_USER_NOT_FOUND", "no account with that email")
case errors.Is(err, domain.ErrCannotShareWithSelf):
writeAPIError(c, http.StatusBadRequest, "CANNOT_SHARE_WITH_SELF", "you can't share a garden with yourself")
case errors.Is(err, domain.ErrShareExists):
writeAPIError(c, http.StatusConflict, "SHARE_EXISTS", "this garden is already shared with that user")
case errors.Is(err, domain.ErrInvalidCredentials):
writeAPIError(c, http.StatusUnauthorized, "INVALID_CREDENTIALS", "invalid email or password")
case errors.Is(err, domain.ErrEmailTaken):
+88
View File
@@ -0,0 +1,88 @@
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
// shareCreateRequest is the body for POST /gardens/:id/shares: the recipient's
// exact account email and the role to grant (viewer|editor).
type shareCreateRequest struct {
Email string `json:"email" binding:"required"`
Role string `json:"role" binding:"required"`
}
// shareUpdateRequest is the body for PATCH /gardens/:id/shares/:userId.
type shareUpdateRequest struct {
Role string `json:"role" binding:"required"`
}
func (h *handlers) listShares(c *gin.Context) {
gardenID, ok := parseIDParam(c, "id")
if !ok {
return
}
shares, err := h.svc.ListShares(c.Request.Context(), mustActor(c).ID, gardenID)
if err != nil {
writeServiceError(c, err)
return
}
c.JSON(http.StatusOK, shares)
}
func (h *handlers) addShare(c *gin.Context) {
gardenID, ok := parseIDParam(c, "id")
if !ok {
return
}
var req shareCreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "an email and a role are required")
return
}
sh, err := h.svc.AddShare(c.Request.Context(), mustActor(c).ID, gardenID, req.Email, req.Role)
if err != nil {
writeServiceError(c, err)
return
}
c.JSON(http.StatusCreated, sh)
}
func (h *handlers) updateShare(c *gin.Context) {
gardenID, ok := parseIDParam(c, "id")
if !ok {
return
}
userID, ok := parseIDParam(c, "userId")
if !ok {
return
}
var req shareUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a role is required")
return
}
sh, err := h.svc.UpdateShareRole(c.Request.Context(), mustActor(c).ID, gardenID, userID, req.Role)
if err != nil {
writeServiceError(c, err)
return
}
c.JSON(http.StatusOK, sh)
}
func (h *handlers) removeShare(c *gin.Context) {
gardenID, ok := parseIDParam(c, "id")
if !ok {
return
}
userID, ok := parseIDParam(c, "userId")
if !ok {
return
}
if err := h.svc.RemoveShare(c.Request.Context(), mustActor(c).ID, gardenID, userID); err != nil {
writeServiceError(c, err)
return
}
c.Status(http.StatusNoContent)
}
+91
View File
@@ -0,0 +1,91 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"testing"
)
func sharesPath(gid int64) string { return "/api/v1/gardens/" + strconv.FormatInt(gid, 10) + "/shares" }
func sharePath(gid, userID int64) string {
return sharesPath(gid) + "/" + strconv.FormatInt(userID, 10)
}
func TestSharingFlowAPI(t *testing.T) {
r := authEngine(t, localCfg())
a := registerAndCookie(t, r, "[email protected]")
b := registerAndCookie(t, r, "[email protected]")
gid := createGardenAPI(t, r, a, "A's yard")
// A bed to mutate later.
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
map[string]any{"kind": "bed", "xCm": 500, "yCm": 500, "widthCm": 200, "heightCm": 200}, a)
oid := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
// Unknown email → 404 SHARE_USER_NOT_FOUND.
w = doJSON(t, r, http.MethodPost, sharesPath(gid), map[string]any{"email": "[email protected]", "role": "viewer"}, a)
if w.Code != http.StatusNotFound {
t.Fatalf("share unknown email = %d, want 404 (body %s)", w.Code, w.Body.String())
}
// Share with B as viewer → 201.
w = doJSON(t, r, http.MethodPost, sharesPath(gid), map[string]any{"email": "[email protected]", "role": "viewer"}, a)
if w.Code != http.StatusCreated {
t.Fatalf("share viewer = %d, body %s", w.Code, w.Body.String())
}
bID := int64(decodeMap(t, w.Body.Bytes())["userId"].(float64))
// B lists → the garden with myRole viewer.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, b)
var list []map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("decode b list: %v", err)
}
if len(list) != 1 || list[0]["myRole"] != "viewer" {
t.Fatalf("b list = %+v, want one garden with myRole viewer", list)
}
// B reads /full (200) but can't mutate (403) or manage shares (403).
if w := doJSON(t, r, http.MethodGet, fullPath(gid), nil, b); w.Code != http.StatusOK {
t.Errorf("b read full = %d, want 200", w.Code)
}
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), map[string]any{"xCm": 100, "version": 1}, b); w.Code != http.StatusForbidden {
t.Errorf("viewer mutate object = %d, want 403", w.Code)
}
if w := doJSON(t, r, http.MethodGet, sharesPath(gid), nil, b); w.Code != http.StatusForbidden {
t.Errorf("viewer list shares = %d, want 403", w.Code)
}
// A upgrades B to editor.
if w := doJSON(t, r, http.MethodPatch, sharePath(gid, bID), map[string]any{"role": "editor"}, a); w.Code != http.StatusOK {
t.Fatalf("upgrade role = %d, body %s", w.Code, w.Body.String())
}
// B can now move the object, but still can't rename the garden (owner-only).
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), map[string]any{"xCm": 100, "version": 1}, b); w.Code != http.StatusOK {
t.Errorf("editor move object = %d, want 200 (body %s)", w.Code, w.Body.String())
}
if w := doJSON(t, r, http.MethodPatch, gardenPath(gid),
map[string]any{"name": "hijack", "widthCm": 100, "heightCm": 100, "unitPref": "metric", "version": 1}, b); w.Code != http.StatusForbidden {
t.Errorf("editor rename garden = %d, want 403", w.Code)
}
// A removes the share → B loses access.
if w := doJSON(t, r, http.MethodDelete, sharePath(gid, bID), nil, a); w.Code != http.StatusNoContent {
t.Fatalf("remove share = %d", w.Code)
}
if w := doJSON(t, r, http.MethodGet, fullPath(gid), nil, b); w.Code != http.StatusNotFound {
t.Errorf("b read after unshare = %d, want 404", w.Code)
}
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, b); w.Body.String() != "[]" {
t.Errorf("b list after unshare = %s, want []", w.Body.String())
}
}
func TestSharesRequireAuth(t *testing.T) {
r := authEngine(t, localCfg())
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens/1/shares", nil, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated list shares = %d, want 401", w.Code)
}
}