Add sharing backend: shares CRUD + ACL enforcement everywhere (#16)
- domain: Garden gains a computed MyRole ("owner"/"editor"/"viewer"); new
ShareWithUser (share + recipient identity); sentinels ErrShareUserNotFound,
ErrCannotShareWithSelf, ErrShareExists.
- store/shares.go: GetShareRole, ListSharesForGarden (joined with users),
CreateShare (UNIQUE → ErrShareExists), UpdateShareRole, DeleteShare.
- store/gardens.go: ListGardensForActor returns owned + shared-with-me gardens,
each carrying my_role (replaces the owner-only list).
- service: requireGardenRole now consults garden_shares (owner implicit, else the
share's role, else masked ErrNotFound) and stamps MyRole on every read-through.
UpdateGarden tightened to OWNER-only (editors edit contents, not the garden).
UpdatePlanting only re-checks plant visibility when the plant is CHANGED, so a
shared editor can edit a plop that uses the owner's private plant.
- service/shares.go: ListShares/AddShare/UpdateShareRole (owner only), RemoveShare
(owner or a recipient leaving). AddShare targets an existing account by exact
email; unknown → 404, self → 400, duplicate → 409.
- api: GET,POST /gardens/:id/shares and PATCH,DELETE /gardens/:id/shares/:userId.
Tests: the full {owner, editor, viewer, stranger} × {read, mutate object, mutate
planting, edit garden, delete garden, manage shares} ACL matrix; shared gardens
carry my_role; AddShare error cases; role upgrade + self-leave; plus a two-user
HTTP flow. The matrix caught the editor-cannot-edit-owner's-plant bug above.
GOWORK=off go build/vet/test ./internal/... green.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -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())
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user