Files
pansy/internal/api/errors.go
T
steveandClaude Opus 4.8 a615de633f
Build image / build-and-push (push) Successful in 5s
Gadfly review (reusable) / review (pull_request) Successful in 10m11s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m11s
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
2026-07-18 23:32:35 -04:00

82 lines
4.0 KiB
Go

package api
import (
"errors"
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// writeServiceError maps a service-layer sentinel error to pansy's JSON error
// envelope ({"error":{"code","message"}}). One mapper serves every handler
// (auth and resources) so the status/code for a given sentinel is defined once.
//
// ErrNotFound covers both a genuinely missing row and one the actor may not see
// (existence is masked). ErrVersionConflict here is a fallback that omits the
// current row — handlers that can produce one special-case it with
// writeVersionConflict before falling through here. Login failures never leak
// which of email/password was wrong.
func writeServiceError(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.ErrVersionConflict):
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):
writeAPIError(c, http.StatusConflict, "EMAIL_TAKEN", "an account with that email already exists")
case errors.Is(err, domain.ErrRegistrationClosed):
writeAPIError(c, http.StatusForbidden, "REGISTRATION_CLOSED", "registration is closed")
case errors.Is(err, domain.ErrLocalAuthDisabled):
writeAPIError(c, http.StatusForbidden, "LOCAL_AUTH_DISABLED", "local authentication is disabled")
case errors.Is(err, domain.ErrOIDCNoEmail):
writeAPIError(c, http.StatusBadRequest, "OIDC_NO_EMAIL", "the identity provider returned no email")
case errors.Is(err, domain.ErrOIDCEmailUnverified):
writeAPIError(c, http.StatusForbidden, "OIDC_EMAIL_UNVERIFIED", "the identity provider's email is not verified")
case errors.Is(err, domain.ErrOIDCIdentityConflict):
writeAPIError(c, http.StatusConflict, "OIDC_IDENTITY_CONFLICT", "this identity conflicts with an existing account")
case errors.Is(err, domain.ErrInvalidInput):
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid input")
default:
slog.Error("api: unhandled service error", "error", err)
writeAPIError(c, http.StatusInternalServerError, "INTERNAL", "internal error")
}
}
// 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,
})
}
// 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
}