mirror of
https://github.com/usememos/memos.git
synced 2026-11-19 10:29:11 +01:00
chore: unify user permissions
An active application ADMIN now passes every memo-local authorization check on named operations: authorship, audience, Space membership and participation, attachment and reaction ownership. Structural validity still applies, an archived admin holds no privilege, and collection listings keep the audience predicate so feeds never surface other users' private memos. - core/access: admin bypass in the read policy; CanManageMemo and CanManageAttachment as the shared author-level predicates. - store: drivers read the actor's role alongside its lifecycle state in the mutation transaction; validators accept an admin where they required the author or a member; shared attachment binding and removal predicates. - api: handlers use the shared predicates; admins may place memos in any existing Space and see a memo's Space by name. - web: one canManageMemo helper replaces the ad hoc creator checks. - docs: multi-spaces design revised in place; share RPC comments updated.
This commit is contained in:
+42
-4
@@ -52,6 +52,38 @@ func (d MemoReadDecision) Allowed() bool {
|
||||
return d.Denial == MemoReadDenialNone
|
||||
}
|
||||
|
||||
// IsActiveUser reports whether the user exists and is in the normal lifecycle
|
||||
// state, which every authenticated authorization decision requires.
|
||||
func IsActiveUser(user *store.User) bool {
|
||||
return user != nil && user.RowStatus == store.Normal
|
||||
}
|
||||
|
||||
// IsInstanceAdmin reports whether the user is an active application ADMIN.
|
||||
// An instance administrator is the superuser for named memo operations: every
|
||||
// memo-local authorization check (authorship, audience, Space membership and
|
||||
// participation, attachment and reaction ownership) passes. Structural
|
||||
// validity still applies, and collection listings keep the audience predicate
|
||||
// so feeds never surface other users' private memos.
|
||||
func IsInstanceAdmin(user *store.User) bool {
|
||||
return IsActiveUser(user) && user.Role == store.RoleAdmin
|
||||
}
|
||||
|
||||
// CanManageMemo reports whether the actor may perform author-level operations
|
||||
// on the memo: the active author, or an instance administrator.
|
||||
func CanManageMemo(actor *store.User, memo *store.Memo) bool {
|
||||
return memo != nil && ownsOrAdministers(actor, memo.CreatorID)
|
||||
}
|
||||
|
||||
// CanManageAttachment reports whether the actor may mutate an attachment row
|
||||
// directly: the active owner, or an instance administrator.
|
||||
func CanManageAttachment(actor *store.User, attachment *store.Attachment) bool {
|
||||
return attachment != nil && ownsOrAdministers(actor, attachment.CreatorID)
|
||||
}
|
||||
|
||||
func ownsOrAdministers(actor *store.User, creatorID int32) bool {
|
||||
return IsActiveUser(actor) && (actor.ID == creatorID || actor.Role == store.RoleAdmin)
|
||||
}
|
||||
|
||||
// CheckMemoReadContext evaluates access to exactly one memo. Unknown audience,
|
||||
// invalid lifecycle state, and a missing or invalid creator fail closed. A
|
||||
// dangling placement only invalidates SPACE reads; other audiences
|
||||
@@ -69,12 +101,18 @@ func CheckMemoReadContext(ctx MemoReadContext) MemoReadDecision {
|
||||
return MemoReadDecision{Denial: MemoReadDenialNotFound}
|
||||
}
|
||||
|
||||
viewerActive := ctx.Viewer != nil && ctx.Viewer.RowStatus == store.Normal
|
||||
viewerIsAuthor := viewerActive && ctx.Viewer.ID == memo.CreatorID
|
||||
if memo.RowStatus == store.Archived && !viewerIsAuthor {
|
||||
if memo.RowStatus != store.Normal && memo.RowStatus != store.Archived {
|
||||
return MemoReadDecision{Denial: MemoReadDenialNotFound}
|
||||
}
|
||||
if memo.RowStatus != store.Normal && memo.RowStatus != store.Archived {
|
||||
// A structurally valid memo is readable by name to an instance
|
||||
// administrator regardless of audience, placement, or lifecycle state.
|
||||
if IsInstanceAdmin(ctx.Viewer) {
|
||||
return MemoReadDecision{Class: MemoReadClassPrivate}
|
||||
}
|
||||
|
||||
viewerActive := IsActiveUser(ctx.Viewer)
|
||||
viewerIsAuthor := viewerActive && ctx.Viewer.ID == memo.CreatorID
|
||||
if memo.RowStatus == store.Archived && !viewerIsAuthor {
|
||||
return MemoReadDecision{Denial: MemoReadDenialNotFound}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,9 @@ func (f MemoReadFacts) WithViewer(ctx context.Context, s MemoReadStore, viewer *
|
||||
if f.Memo == nil || f.Memo.SpaceID == nil || !f.SpaceValid {
|
||||
return readContext, nil
|
||||
}
|
||||
if viewer == nil || viewer.RowStatus != store.Normal {
|
||||
// Membership never changes the outcome for an inactive viewer or for an
|
||||
// instance administrator, so skip the lookup for both.
|
||||
if !IsActiveUser(viewer) || IsInstanceAdmin(viewer) {
|
||||
return readContext, nil
|
||||
}
|
||||
membership, err := s.GetSpaceMember(ctx, &store.FindSpaceMember{SpaceID: f.Memo.SpaceID, UserID: &viewer.ID})
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
func TestCheckMemoReadMemoLocalAudiences(t *testing.T) {
|
||||
owner := &store.User{ID: 1, RowStatus: store.Normal}
|
||||
other := &store.User{ID: 2, RowStatus: store.Normal, Role: store.RoleAdmin}
|
||||
other := &store.User{ID: 2, RowStatus: store.Normal, Role: store.RoleUser}
|
||||
public := &store.Memo{ID: 1, CreatorID: owner.ID, RowStatus: store.Normal, Visibility: store.Public}
|
||||
protected := &store.Memo{ID: 2, CreatorID: owner.ID, RowStatus: store.Normal, Visibility: store.Protected}
|
||||
private := &store.Memo{ID: 3, CreatorID: owner.ID, RowStatus: store.Normal, Visibility: store.Private}
|
||||
@@ -66,7 +66,7 @@ func TestCheckMemoReadSpaceAudience(t *testing.T) {
|
||||
|
||||
base.Viewer = appAdmin
|
||||
base.ViewerSpaceMember = false
|
||||
require.Equal(t, MemoReadDenialPermission, CheckMemoReadContext(base).Denial)
|
||||
require.True(t, CheckMemoReadContext(base).Allowed(), "an instance administrator reads any memo by name")
|
||||
|
||||
shareID := memo.ID
|
||||
base.Viewer = nil
|
||||
@@ -79,6 +79,42 @@ func TestCheckMemoReadSpaceAudience(t *testing.T) {
|
||||
require.Equal(t, MemoReadDenialNotFound, CheckMemoReadContext(base).Denial)
|
||||
}
|
||||
|
||||
func TestInstanceAdminIsMemoSuperuser(t *testing.T) {
|
||||
owner := &store.User{ID: 1, RowStatus: store.Normal, Role: store.RoleUser}
|
||||
admin := &store.User{ID: 2, RowStatus: store.Normal, Role: store.RoleAdmin}
|
||||
archivedAdmin := &store.User{ID: 3, RowStatus: store.Archived, Role: store.RoleAdmin}
|
||||
spaceID := int32(7)
|
||||
|
||||
private := &store.Memo{ID: 1, CreatorID: owner.ID, RowStatus: store.Normal, Visibility: store.Private}
|
||||
archived := &store.Memo{ID: 2, CreatorID: owner.ID, RowStatus: store.Archived, Visibility: store.Public}
|
||||
spaceMemo := &store.Memo{ID: 3, CreatorID: owner.ID, RowStatus: store.Normal, Visibility: store.SpaceAudience, SpaceID: &spaceID}
|
||||
for _, memo := range []*store.Memo{private, archived, spaceMemo} {
|
||||
require.Equal(t, MemoReadDecision{Class: MemoReadClassPrivate}, CheckMemoReadContext(MemoReadContext{
|
||||
Memo: memo, Viewer: admin, CreatorValid: true, SpaceValid: true,
|
||||
}), "admin reads memo %d by name", memo.ID)
|
||||
require.False(t, CheckMemoReadContext(MemoReadContext{
|
||||
Memo: memo, Viewer: archivedAdmin, CreatorValid: true, SpaceValid: true,
|
||||
}).Allowed(), "an archived administrator holds no privilege")
|
||||
require.True(t, CanManageMemo(admin, memo))
|
||||
require.False(t, CanManageMemo(archivedAdmin, memo))
|
||||
}
|
||||
|
||||
// Structural validity still applies.
|
||||
require.Equal(t, MemoReadDenialNotFound, CheckMemoReadContext(MemoReadContext{
|
||||
Memo: spaceMemo, Viewer: admin, CreatorValid: true, SpaceValid: false,
|
||||
}).Denial, "a dangling SPACE placement is not readable, even by an administrator")
|
||||
require.Equal(t, MemoReadDenialNotFound, CheckMemoReadContext(MemoReadContext{
|
||||
Memo: private, Viewer: admin, CreatorValid: false, SpaceValid: true,
|
||||
}).Denial)
|
||||
|
||||
require.True(t, CanManageMemo(owner, private))
|
||||
require.False(t, CanManageMemo(&store.User{ID: 4, RowStatus: store.Normal, Role: store.RoleUser}, private))
|
||||
attachment := &store.Attachment{ID: 1, CreatorID: owner.ID}
|
||||
require.True(t, CanManageAttachment(owner, attachment))
|
||||
require.True(t, CanManageAttachment(admin, attachment))
|
||||
require.False(t, CanManageAttachment(archivedAdmin, attachment))
|
||||
}
|
||||
|
||||
func TestCheckMemoReadInvalidStateFailsClosed(t *testing.T) {
|
||||
owner := &store.User{ID: 1, RowStatus: store.Normal}
|
||||
spaceID := int32(7)
|
||||
|
||||
@@ -70,7 +70,7 @@ These sources establish product mechanics, not demand or prevalence. This resear
|
||||
- A reaction belongs to one memo and has no independent audience.
|
||||
- A Space invitation is a pending offer to one existing active registered user with a selected `ADMIN` or `USER` role. It grants no Space access before that user accepts it.
|
||||
- A Space membership is an accepted relationship between one active registered user and one Space with role `ADMIN` or `USER`. The creator becomes the first `ADMIN`; there is no permanent owner.
|
||||
- Application `ADMIN` is a control-plane role and is not an implicit Space member or memo reader.
|
||||
- Application `ADMIN` is the instance superuser. On any named memo operation it passes every memo-local authorization check: authorship, audience, Space membership and participation, attachment and reaction ownership. Structural validity still applies, and collection listings keep the audience predicate, so an administrator's feeds never surface other users' private memos. It is not an implicit Space member for Space browsing or governance.
|
||||
|
||||
### Read access and distribution
|
||||
|
||||
@@ -87,6 +87,8 @@ Space placement adds no additional read gate. In particular, an active non-membe
|
||||
|
||||
An unexpired bearer share is an explicit capability exception for one exact memo. It does not grant list, feed, Space, or related-memo access.
|
||||
|
||||
An application `ADMIN` may read any structurally valid memo by name, including archived memos and memos with the `SPACE` audience in Spaces they do not belong to. This bypass applies to point reads and their child resources (files, reactions, relations, comment creation) only. Lists, counts, feeds, and the Space filter keep the ordinary predicate, so an administrator's Explore and Space feeds show exactly what a regular user with the same memberships would see.
|
||||
|
||||
Distribution is derived rather than separately configured:
|
||||
|
||||
- Global feeds return readable memos that do not have a `COMMENT` relation.
|
||||
@@ -115,6 +117,7 @@ Reading and participation are separate. A caller may read an assigned `PUBLIC` o
|
||||
| Edit content or audience; manage attachments, references, or shares | Memo author; if assigned, the author is also an active member of its Space. |
|
||||
| Delete one memo | Memo author. This does not delete another memo. |
|
||||
| Withdraw or move a memo | Memo author. Source membership is unnecessary; target membership is required. |
|
||||
| Any named memo operation above, on any memo | Application `ADMIN`, as superuser. Membership is not required; the placement and any target Space must still exist. An attachment a superuser adds stays owned by the administrator; because removal deletes the file, only its owner or an administrator removes it, and memo deletion still removes it. |
|
||||
| Hard-delete a Space | Space `ADMIN`. |
|
||||
|
||||
Any membership change or user archival that would leave a Space without an active `ADMIN` is rejected.
|
||||
@@ -176,7 +179,7 @@ Creating an invitation also delivers a `SPACE_INVITATION` inbox notification to
|
||||
|
||||
### Security invariants
|
||||
|
||||
Before `SPACE` can be stored, one shared, memo-local, fail-closed policy must cover point reads, lists and counts, files, reactions, relations, notifications, email, webhooks, shares, search, statistics, public feeds, and MCP. Child resources resolve the memo they directly belong to. Application `ADMIN` receives no implicit bypass.
|
||||
Before `SPACE` can be stored, one shared, memo-local, fail-closed policy must cover point reads, lists and counts, files, reactions, relations, notifications, email, webhooks, shares, search, statistics, public feeds, and MCP. Child resources resolve the memo they directly belong to. Application `ADMIN` bypasses only the memo-local checks on named operations; drivers resolve the actor's role inside the mutation transaction alongside the actor's lifecycle state, and an archived administrator holds no privilege.
|
||||
|
||||
Unknown visibility denies access. A missing or invalid placement denies `SPACE` reads and placement-dependent operations. Other audiences continue to govern ordinary reads, but an invalid Space identity is omitted. Inactive users, pending invitations, unknown relationship states, and invalid membership roles deny any access that depends on them. Every membership authorization requires `status = ACTIVE` and role `ADMIN` or `USER`. Where the database supports row locks, relationship creation and activation serialize against user deletion, and invitation creation serializes against Space deletion. Database list and count authorization is applied before pagination:
|
||||
|
||||
@@ -208,11 +211,11 @@ Files for `PRIVATE`, `PROTECTED`, and `SPACE` memos use `private, no-store`; pub
|
||||
| Follow relations during Space deletion | Rejected; relations cannot extend deletion into other Spaces or Unassigned content. |
|
||||
| Move or delete a member's memos when membership ends | Rejected; historical contributions remain until an author lifecycle action or Space deletion. |
|
||||
| Give a Space `ADMIN` a separate operation to evict or otherwise mutate one memo | Rejected; placement belongs to the memo author's lifecycle, while Space governance is limited to Space metadata, membership, and aggregate hard deletion. |
|
||||
| Give application `ADMIN` implicit Space or memo access | Rejected; moderation and recovery require separate control-plane design. |
|
||||
| Give application `ADMIN` implicit Space or memo access | Revised on 2026-09-17: application `ADMIN` is the superuser for named memo operations, without becoming an implicit Space member for browsing or governance. Collection listings are unchanged. |
|
||||
| Let a Space `ADMIN` directly create an active membership | Rejected; only the invited user can turn a pending offer into membership. |
|
||||
| Add a separate invitation table now | Rejected for this iteration because the relationship state fits the unique Space-user slot and the design intentionally omits history, expiration, and delivery credentials. Revisit when those requirements appear. |
|
||||
| Rename v1 `visibility` to `audience`, or expose both fields | Rejected; the domain term is Audience, while one legacy v1 field remains the compatibility representation. |
|
||||
|
||||
## Deferred design
|
||||
|
||||
Email and external-user invitations, invitation expiration, inviter attribution, invitation history, open enrollment, account erasure beyond the membership guard, notification retention policy and per-user notification preferences, application-admin moderation and recovery, audit history, soft deletion, restoration, retryable external-object cleanup, delivery-time cancellation of queued email/webhooks, broader concurrent-mutation hardening, and asynchronous deletion of very large Spaces remain deferred. Later work must preserve invitee consent, independent memo authorization, non-propagating relations, and explicit Space aggregate deletion unless this design is revisited.
|
||||
Email and external-user invitations, invitation expiration, inviter attribution, invitation history, open enrollment, account erasure beyond the membership guard, notification retention policy and per-user notification preferences, collaborative editing by Space members, audit history, soft deletion, restoration, retryable external-object cleanup, delivery-time cancellation of queued email/webhooks, broader concurrent-mutation hardening, and asynchronous deletion of very large Spaces remain deferred. Later work must preserve invitee consent, independent memo authorization, non-propagating relations, and explicit Space aggregate deletion unless this design is revisited.
|
||||
|
||||
@@ -113,7 +113,7 @@ service MemoService {
|
||||
option (google.api.http) = {delete: "/api/v1/{name=memos/*/reactions/*}"};
|
||||
option (google.api.method_signature) = "name";
|
||||
}
|
||||
// CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
// CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
rpc CreateMemoShare(CreateMemoShareRequest) returns (MemoShare) {
|
||||
option (google.api.http) = {
|
||||
post: "/api/v1/{parent=memos/*}/shares"
|
||||
@@ -121,12 +121,12 @@ service MemoService {
|
||||
};
|
||||
option (google.api.method_signature) = "parent,memo_share";
|
||||
}
|
||||
// ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
// ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
rpc ListMemoShares(ListMemoSharesRequest) returns (ListMemoSharesResponse) {
|
||||
option (google.api.http) = {get: "/api/v1/{parent=memos/*}/shares"};
|
||||
option (google.api.method_signature) = "parent";
|
||||
}
|
||||
// DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
// DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
rpc DeleteMemoShare(DeleteMemoShareRequest) returns (google.protobuf.Empty) {
|
||||
option (google.api.http) = {delete: "/api/v1/{name=memos/*/shares/*}"};
|
||||
option (google.api.method_signature) = "name";
|
||||
|
||||
@@ -131,11 +131,11 @@ type MemoServiceClient interface {
|
||||
UpsertMemoReaction(context.Context, *connect.Request[v1.UpsertMemoReactionRequest]) (*connect.Response[v1.Reaction], error)
|
||||
// DeleteMemoReaction deletes a reaction for a memo.
|
||||
DeleteMemoReaction(context.Context, *connect.Request[v1.DeleteMemoReactionRequest]) (*connect.Response[emptypb.Empty], error)
|
||||
// CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
// CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
CreateMemoShare(context.Context, *connect.Request[v1.CreateMemoShareRequest]) (*connect.Response[v1.MemoShare], error)
|
||||
// ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
// ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
ListMemoShares(context.Context, *connect.Request[v1.ListMemoSharesRequest]) (*connect.Response[v1.ListMemoSharesResponse], error)
|
||||
// DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
// DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
DeleteMemoShare(context.Context, *connect.Request[v1.DeleteMemoShareRequest]) (*connect.Response[emptypb.Empty], error)
|
||||
// GetSharedMemo resolves a share token to its memo. No authentication required.
|
||||
// Returns NOT_FOUND if the token is invalid or expired.
|
||||
@@ -444,11 +444,11 @@ type MemoServiceHandler interface {
|
||||
UpsertMemoReaction(context.Context, *connect.Request[v1.UpsertMemoReactionRequest]) (*connect.Response[v1.Reaction], error)
|
||||
// DeleteMemoReaction deletes a reaction for a memo.
|
||||
DeleteMemoReaction(context.Context, *connect.Request[v1.DeleteMemoReactionRequest]) (*connect.Response[emptypb.Empty], error)
|
||||
// CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
// CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
CreateMemoShare(context.Context, *connect.Request[v1.CreateMemoShareRequest]) (*connect.Response[v1.MemoShare], error)
|
||||
// ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
// ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
ListMemoShares(context.Context, *connect.Request[v1.ListMemoSharesRequest]) (*connect.Response[v1.ListMemoSharesResponse], error)
|
||||
// DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
// DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
DeleteMemoShare(context.Context, *connect.Request[v1.DeleteMemoShareRequest]) (*connect.Response[emptypb.Empty], error)
|
||||
// GetSharedMemo resolves a share token to its memo. No authentication required.
|
||||
// Returns NOT_FOUND if the token is invalid or expired.
|
||||
|
||||
@@ -84,11 +84,11 @@ type MemoServiceClient interface {
|
||||
UpsertMemoReaction(ctx context.Context, in *UpsertMemoReactionRequest, opts ...grpc.CallOption) (*Reaction, error)
|
||||
// DeleteMemoReaction deletes a reaction for a memo.
|
||||
DeleteMemoReaction(ctx context.Context, in *DeleteMemoReactionRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
// CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
// CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
CreateMemoShare(ctx context.Context, in *CreateMemoShareRequest, opts ...grpc.CallOption) (*MemoShare, error)
|
||||
// ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
// ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
ListMemoShares(ctx context.Context, in *ListMemoSharesRequest, opts ...grpc.CallOption) (*ListMemoSharesResponse, error)
|
||||
// DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
// DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
DeleteMemoShare(ctx context.Context, in *DeleteMemoShareRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
// GetSharedMemo resolves a share token to its memo. No authentication required.
|
||||
// Returns NOT_FOUND if the token is invalid or expired.
|
||||
@@ -349,11 +349,11 @@ type MemoServiceServer interface {
|
||||
UpsertMemoReaction(context.Context, *UpsertMemoReactionRequest) (*Reaction, error)
|
||||
// DeleteMemoReaction deletes a reaction for a memo.
|
||||
DeleteMemoReaction(context.Context, *DeleteMemoReactionRequest) (*emptypb.Empty, error)
|
||||
// CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
// CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
CreateMemoShare(context.Context, *CreateMemoShareRequest) (*MemoShare, error)
|
||||
// ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
// ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
ListMemoShares(context.Context, *ListMemoSharesRequest) (*ListMemoSharesResponse, error)
|
||||
// DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
// DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
DeleteMemoShare(context.Context, *DeleteMemoShareRequest) (*emptypb.Empty, error)
|
||||
// GetSharedMemo resolves a share token to its memo. No authentication required.
|
||||
// Returns NOT_FOUND if the token is invalid or expired.
|
||||
|
||||
@@ -1225,7 +1225,7 @@ paths:
|
||||
get:
|
||||
tags:
|
||||
- MemoService
|
||||
description: ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
description: ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
operationId: MemoService_ListMemoShares
|
||||
parameters:
|
||||
- name: memo
|
||||
@@ -1250,7 +1250,7 @@ paths:
|
||||
post:
|
||||
tags:
|
||||
- MemoService
|
||||
description: CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
description: CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
operationId: MemoService_CreateMemoShare
|
||||
parameters:
|
||||
- name: memo
|
||||
@@ -1282,7 +1282,7 @@ paths:
|
||||
delete:
|
||||
tags:
|
||||
- MemoService
|
||||
description: DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
description: DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
operationId: MemoService_DeleteMemoShare
|
||||
parameters:
|
||||
- name: memo
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/usememos/memos/core/access"
|
||||
"github.com/usememos/memos/internal/motionphoto"
|
||||
"github.com/usememos/memos/internal/ratelimit"
|
||||
v1pb "github.com/usememos/memos/proto/gen/api/v1"
|
||||
@@ -149,10 +150,10 @@ func (s *APIV1Service) prepareAttachment(ctx context.Context, request *v1pb.Crea
|
||||
if memo == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "memo not found: %s", *request.Attachment.Memo)
|
||||
}
|
||||
if !canModifyMemo(user, memo) {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
if err := s.requireAssignedMemoWritable(ctx, memo, user.ID); err != nil {
|
||||
if err := s.requireAssignedMemoWritable(ctx, memo, user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
create.MemoID = &memo.ID
|
||||
@@ -384,8 +385,7 @@ func (s *APIV1Service) UpdateAttachment(ctx context.Context, request *v1pb.Updat
|
||||
if attachment == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "attachment not found")
|
||||
}
|
||||
// Only the creator can update the attachment.
|
||||
if attachment.CreatorID != user.ID {
|
||||
if !access.CanManageAttachment(user, attachment) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
|
||||
@@ -490,7 +490,7 @@ func (s *APIV1Service) BatchDeleteAttachments(ctx context.Context, request *v1pb
|
||||
if attachment == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "attachment not found")
|
||||
}
|
||||
if attachment.CreatorID != user.ID {
|
||||
if !access.CanManageAttachment(user, attachment) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
attachments = append(attachments, attachment)
|
||||
@@ -525,7 +525,7 @@ func (s *APIV1Service) validateAttachmentDeletionPreflight(ctx context.Context,
|
||||
}
|
||||
memos[memo.ID] = memo
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Error(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
}
|
||||
@@ -560,7 +560,7 @@ func (s *APIV1Service) validateAttachmentMotionGroupDeletion(
|
||||
if attachment == nil || attachment.ID <= 0 || attachment.UID == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "invalid attachment")
|
||||
}
|
||||
if attachment.CreatorID != user.ID {
|
||||
if !access.CanManageAttachment(user, attachment) {
|
||||
return nil, status.Error(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
deletingUIDs[attachment.UID] = struct{}{}
|
||||
@@ -637,7 +637,7 @@ func (s *APIV1Service) checkAttachmentAccess(ctx context.Context, attachment *st
|
||||
if user == nil {
|
||||
return status.Errorf(codes.Unauthenticated, "user not authenticated")
|
||||
}
|
||||
if attachment.CreatorID != user.ID {
|
||||
if !access.CanManageAttachment(user, attachment) {
|
||||
return status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -73,7 +73,3 @@ func unmarshalPageToken(s string, pageToken *v1pb.PageToken) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func canModifyMemo(user *store.User, memo *store.Memo) bool {
|
||||
return user != nil && memo != nil && memo.CreatorID == user.ID
|
||||
}
|
||||
|
||||
@@ -91,11 +91,9 @@ func (s *APIV1Service) resolveMemoAccessScope(ctx context.Context) (*store.MemoA
|
||||
return newMemoAccessScope(currentUser, allowPublic), currentUser, nil
|
||||
}
|
||||
|
||||
// resolveWritableSpaceByName resolves a space resource name and requires the
|
||||
// caller to be an active member of it. A non-member receives NotFound so that
|
||||
// an existing collaboration boundary stays indistinguishable from a missing
|
||||
// resource.
|
||||
func (s *APIV1Service) resolveWritableSpaceByName(ctx context.Context, name string, userID int32) (*store.Space, error) {
|
||||
// resolveSpaceByName resolves a space resource name to an existing Space
|
||||
// without any membership check.
|
||||
func (s *APIV1Service) resolveSpaceByName(ctx context.Context, name string) (*store.Space, error) {
|
||||
spaceUID, err := ExtractSpaceUIDFromName(name)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "invalid space name: %v", err)
|
||||
@@ -107,6 +105,18 @@ func (s *APIV1Service) resolveWritableSpaceByName(ctx context.Context, name stri
|
||||
if space == nil {
|
||||
return nil, status.Error(codes.NotFound, "space not found")
|
||||
}
|
||||
return space, nil
|
||||
}
|
||||
|
||||
// resolveWritableSpaceByName resolves a space resource name and requires the
|
||||
// caller to be an active member of it. A non-member receives NotFound so that
|
||||
// an existing collaboration boundary stays indistinguishable from a missing
|
||||
// resource.
|
||||
func (s *APIV1Service) resolveWritableSpaceByName(ctx context.Context, name string, userID int32) (*store.Space, error) {
|
||||
space, err := s.resolveSpaceByName(ctx, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
active, err := s.isActiveSpaceMember(ctx, space.ID, userID)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to resolve space membership")
|
||||
@@ -117,6 +127,17 @@ func (s *APIV1Service) resolveWritableSpaceByName(ctx context.Context, name stri
|
||||
return space, nil
|
||||
}
|
||||
|
||||
// resolveSpaceForMemoPlacement resolves the Space a memo is being placed in.
|
||||
// An instance administrator may place memos in any existing Space; every
|
||||
// other caller must be an active member. Collection scopes such as the space
|
||||
// filter keep using resolveWritableSpaceByName, so feeds stay membership-only.
|
||||
func (s *APIV1Service) resolveSpaceForMemoPlacement(ctx context.Context, name string, user *store.User) (*store.Space, error) {
|
||||
if access.IsInstanceAdmin(user) {
|
||||
return s.resolveSpaceByName(ctx, name)
|
||||
}
|
||||
return s.resolveWritableSpaceByName(ctx, name, user.ID)
|
||||
}
|
||||
|
||||
func (s *APIV1Service) isActiveSpaceMember(ctx context.Context, spaceID, userID int32) (bool, error) {
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{ID: &userID})
|
||||
if err != nil {
|
||||
@@ -161,7 +182,10 @@ func mapMemoWriteError(err error, operation string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *APIV1Service) requireAssignedMemoWritable(ctx context.Context, memo *store.Memo, userID int32) error {
|
||||
// requireAssignedMemoWritable requires the placement of an assigned memo to be
|
||||
// valid and the actor to be an active member of it. An instance administrator
|
||||
// is exempt from membership but not from placement validity.
|
||||
func (s *APIV1Service) requireAssignedMemoWritable(ctx context.Context, memo *store.Memo, user *store.User) error {
|
||||
if memo.SpaceID == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -172,7 +196,10 @@ func (s *APIV1Service) requireAssignedMemoWritable(ctx context.Context, memo *st
|
||||
if space == nil {
|
||||
return status.Errorf(codes.FailedPrecondition, "memo has invalid space placement")
|
||||
}
|
||||
active, err := s.isActiveSpaceMember(ctx, space.ID, userID)
|
||||
if access.IsInstanceAdmin(user) {
|
||||
return nil
|
||||
}
|
||||
active, err := s.isActiveSpaceMember(ctx, space.ID, user.ID)
|
||||
if err != nil {
|
||||
return status.Errorf(codes.Internal, "failed to resolve space membership")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/usememos/memos/core/access"
|
||||
"github.com/usememos/memos/markdown"
|
||||
v1pb "github.com/usememos/memos/proto/gen/api/v1"
|
||||
storepb "github.com/usememos/memos/proto/gen/store"
|
||||
@@ -36,7 +37,7 @@ func (s *APIV1Service) SetMemoAttachments(ctx context.Context, request *v1pb.Set
|
||||
if memo == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "memo not found")
|
||||
}
|
||||
if !canModifyMemo(user, memo) {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
prepared, err := s.prepareMemoAttachments(ctx, user, memo, request.Attachments)
|
||||
@@ -83,7 +84,7 @@ func (s *APIV1Service) prepareMemoAttachments(
|
||||
}
|
||||
}
|
||||
|
||||
normalizedAttachments, err := s.normalizeMemoAttachmentRequest(ctx, memo, currentAttachments, requestAttachments)
|
||||
normalizedAttachments, err := s.normalizeMemoAttachmentRequest(ctx, user, memo, currentAttachments, requestAttachments)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -93,13 +94,11 @@ func (s *APIV1Service) prepareMemoAttachments(
|
||||
requestedIDs[attachment.ID] = true
|
||||
}
|
||||
|
||||
// The same removal rule is revalidated by the driver in the transaction.
|
||||
removedAttachments := make([]*store.Attachment, 0)
|
||||
for _, attachment := range currentAttachments {
|
||||
if !requestedIDs[attachment.ID] {
|
||||
if attachment.CreatorID != memo.CreatorID {
|
||||
return nil, status.Errorf(codes.FailedPrecondition, "cannot remove another user's attachment from this memo")
|
||||
}
|
||||
if attachment.CreatorID != user.ID {
|
||||
if !store.MemoAttachmentRemovalAllowed(attachment, memo.ID, user.ID, access.IsInstanceAdmin(user)) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "cannot remove another user's attachment")
|
||||
}
|
||||
removedAttachments = append(removedAttachments, attachment)
|
||||
@@ -204,7 +203,7 @@ func (s *APIV1Service) applyMemoMutation(
|
||||
if user == nil {
|
||||
return status.Error(codes.Unauthenticated, "user not authenticated")
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return status.Error(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
policy := memoWritePolicy(user.ID, false)
|
||||
@@ -258,6 +257,7 @@ func (s *APIV1Service) applyMemoMutation(
|
||||
|
||||
func (s *APIV1Service) normalizeMemoAttachmentRequest(
|
||||
ctx context.Context,
|
||||
user *store.User,
|
||||
memo *store.Memo,
|
||||
currentAttachments []*store.Attachment,
|
||||
requestAttachments []*v1pb.Attachment,
|
||||
@@ -284,10 +284,11 @@ func (s *APIV1Service) normalizeMemoAttachmentRequest(
|
||||
return nil, status.Errorf(codes.NotFound, "attachment not found: %s", attachmentUID)
|
||||
}
|
||||
_, alreadyInTarget := currentByID[attachment.ID]
|
||||
if attachment.CreatorID != memo.CreatorID && !alreadyInTarget {
|
||||
if !alreadyInTarget && !store.MemoAttachmentBindingOwnerAllowed(attachment.CreatorID, memo.CreatorID, user.ID, access.IsInstanceAdmin(user)) {
|
||||
// Hide another user's unlinked or foreign-memo attachment from the
|
||||
// caller. Admin status grants memo maintenance privileges, not the
|
||||
// right to transfer attachment ownership into a different account.
|
||||
// caller. A new binding must be owned by the memo author or by the
|
||||
// acting administrator; ownership is never transferred between
|
||||
// accounts.
|
||||
return nil, status.Errorf(codes.NotFound, "attachment not found: %s", attachmentUID)
|
||||
}
|
||||
if attachment.MemoID != nil && !alreadyInTarget {
|
||||
|
||||
@@ -46,7 +46,7 @@ func (s *APIV1Service) prepareMemoCreate(ctx context.Context, user *store.User,
|
||||
Visibility: visibility,
|
||||
}
|
||||
if input.Space != nil && input.GetSpace() != "" {
|
||||
space, err := s.resolveWritableSpaceByName(ctx, input.GetSpace(), user.ID)
|
||||
space, err := s.resolveSpaceForMemoPlacement(ctx, input.GetSpace(), user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/usememos/memos/core/access"
|
||||
v1pb "github.com/usememos/memos/proto/gen/api/v1"
|
||||
"github.com/usememos/memos/store"
|
||||
)
|
||||
@@ -31,7 +32,7 @@ func (s *APIV1Service) SetMemoRelations(ctx context.Context, request *v1pb.SetMe
|
||||
if memo == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "memo not found")
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
relations, err := s.prepareMemoRelations(ctx, memo, request.Relations)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/usememos/memos/core/access"
|
||||
"github.com/usememos/memos/core/memopayload"
|
||||
"github.com/usememos/memos/internal/ratelimit"
|
||||
v1pb "github.com/usememos/memos/proto/gen/api/v1"
|
||||
@@ -307,9 +308,7 @@ func (s *APIV1Service) UpdateMemo(ctx context.Context, request *v1pb.UpdateMemoR
|
||||
if user == nil {
|
||||
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
|
||||
}
|
||||
// Application administrators are not implicit memo collaborators. Ordinary
|
||||
// content updates remain author-controlled.
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
|
||||
@@ -332,7 +331,7 @@ func (s *APIV1Service) UpdateMemo(ctx context.Context, request *v1pb.UpdateMemoR
|
||||
nextSpaceID = nil
|
||||
update.ClearSpace = true
|
||||
} else {
|
||||
target, err := s.resolveWritableSpaceByName(ctx, request.Memo.GetSpace(), user.ID)
|
||||
target, err := s.resolveSpaceForMemoPlacement(ctx, request.Memo.GetSpace(), user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -510,15 +509,13 @@ func (s *APIV1Service) DeleteMemo(ctx context.Context, request *v1pb.DeleteMemoR
|
||||
if user == nil {
|
||||
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
|
||||
}
|
||||
// Application administrators do not receive ordinary content-deletion
|
||||
// authority merely from their instance role.
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
var deletedMemoMessage *v1pb.Memo
|
||||
// Deletion is a narrow author lifecycle capability and may remain available
|
||||
// after the author loses read access to a memo with the SPACE audience. Only
|
||||
// build a content-bearing webhook payload when the author can still read the
|
||||
// Deletion is a narrow lifecycle capability and may remain available after
|
||||
// the author loses read access to a memo with the SPACE audience. Only
|
||||
// build a content-bearing webhook payload when the actor can still read the
|
||||
// memo immediately before deletion.
|
||||
if s.checkMemoReadAccess(ctx, memo) == nil {
|
||||
reactions, err := s.Store.ListReactions(ctx, &store.FindReaction{MemoID: &memo.ID})
|
||||
|
||||
@@ -115,10 +115,11 @@ func (s *APIV1Service) projectMemoCollaborationContext(ctx context.Context, memo
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Placement is visible to the author and to active members only; a
|
||||
// non-member reading an assigned PUBLIC memo learns nothing about its Space.
|
||||
// Placement is visible to the author, to active members, and to an
|
||||
// instance administrator; a non-member reading an assigned PUBLIC memo
|
||||
// learns nothing about its Space.
|
||||
viewer := readContext.Viewer
|
||||
if viewer == nil || (viewer.ID != memo.CreatorID && !readContext.ViewerSpaceMember) {
|
||||
if viewer == nil || (viewer.ID != memo.CreatorID && !readContext.ViewerSpaceMember && !access.IsInstanceAdmin(viewer)) {
|
||||
return nil
|
||||
}
|
||||
space, err := s.Store.GetSpace(ctx, &store.FindSpace{ID: memo.SpaceID})
|
||||
|
||||
@@ -48,7 +48,7 @@ func (s *APIV1Service) CreateMemoShare(ctx context.Context, request *v1pb.Create
|
||||
if memo.RowStatus != store.Normal {
|
||||
return nil, status.Errorf(codes.FailedPrecondition, "only active memos can be shared")
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
if memo.Visibility == store.SpaceAudience {
|
||||
@@ -102,10 +102,10 @@ func (s *APIV1Service) ListMemoShares(ctx context.Context, request *v1pb.ListMem
|
||||
if memo == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "memo not found")
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
if err := s.requireAssignedMemoWritable(ctx, memo, user.ID); err != nil {
|
||||
if err := s.requireAssignedMemoWritable(ctx, memo, user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ func (s *APIV1Service) DeleteMemoShare(ctx context.Context, request *v1pb.Delete
|
||||
if memo == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "memo not found")
|
||||
}
|
||||
if memo.CreatorID != user.ID {
|
||||
if !access.CanManageMemo(user, memo) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
ms, err := s.Store.GetMemoShare(ctx, &store.FindMemoShare{UID: &shareToken})
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/usememos/memos/core/access"
|
||||
"github.com/usememos/memos/internal/ratelimit"
|
||||
v1pb "github.com/usememos/memos/proto/gen/api/v1"
|
||||
"github.com/usememos/memos/store"
|
||||
@@ -127,7 +128,7 @@ func (s *APIV1Service) DeleteMemoReaction(ctx context.Context, request *v1pb.Del
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
|
||||
if reaction.CreatorID != user.ID {
|
||||
if reaction.CreatorID != user.ID && !access.IsInstanceAdmin(user) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{ID: &reaction.MemoID})
|
||||
|
||||
@@ -323,7 +323,7 @@ func TestCreateAttachmentMemoPermission(t *testing.T) {
|
||||
require.Equal(t, memoIDFromName(ctx, t, ts, memo.Name), *stored.MemoID)
|
||||
})
|
||||
|
||||
t.Run("admin cannot create an admin-owned attachment linked to another user's memo", func(t *testing.T) {
|
||||
t.Run("admin creates an admin-owned attachment linked to another user's memo", func(t *testing.T) {
|
||||
ts := NewTestService(t)
|
||||
defer ts.Cleanup()
|
||||
|
||||
@@ -341,7 +341,7 @@ func TestCreateAttachmentMemoPermission(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = ts.Service.CreateAttachment(adminCtx, &v1pb.CreateAttachmentRequest{
|
||||
created, err := ts.Service.CreateAttachment(adminCtx, &v1pb.CreateAttachmentRequest{
|
||||
Attachment: &v1pb.Attachment{
|
||||
Filename: "admin.txt",
|
||||
Type: "text/plain",
|
||||
@@ -349,10 +349,27 @@ func TestCreateAttachmentMemoPermission(t *testing.T) {
|
||||
Memo: &memo.Name,
|
||||
},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
require.NoError(t, err, "an instance administrator is the superuser for named memo operations")
|
||||
attachments, err := ts.Store.ListAttachments(ctx, &store.FindAttachment{CreatorID: &admin.ID})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, attachments)
|
||||
require.Len(t, attachments, 1, "the attachment stays owned by the administrator")
|
||||
require.NotNil(t, attachments[0].MemoID)
|
||||
|
||||
// Removal deletes the attachment, so the memo author cannot remove a
|
||||
// file the administrator owns; the administrator can.
|
||||
_, err = ts.Service.SetMemoAttachments(ownerCtx, &v1pb.SetMemoAttachmentsRequest{
|
||||
Name: memo.Name,
|
||||
Attachments: []*v1pb.Attachment{},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
_, err = ts.Service.SetMemoAttachments(adminCtx, &v1pb.SetMemoAttachmentsRequest{
|
||||
Name: memo.Name,
|
||||
Attachments: []*v1pb.Attachment{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
attachments, err = ts.Store.ListAttachments(ctx, &store.FindAttachment{CreatorID: &admin.ID})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, attachments, "removal deletes the bound attachment: %s", created.Name)
|
||||
})
|
||||
|
||||
t.Run("non-owner cannot create attachment directly linked to memo", func(t *testing.T) {
|
||||
|
||||
@@ -81,12 +81,12 @@ func TestSetMemoAttachments(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, memo)
|
||||
|
||||
// Application ADMIN is an instance role, not memo authorship.
|
||||
// Application ADMIN is the superuser and manages any memo's attachments.
|
||||
_, err = ts.Service.SetMemoAttachments(hostCtx, &apiv1.SetMemoAttachmentsRequest{
|
||||
Name: memo.Name,
|
||||
Attachments: []*apiv1.Attachment{},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("SetMemoAttachments permission denied for non-owner", func(t *testing.T) {
|
||||
|
||||
@@ -83,12 +83,12 @@ func TestSetMemoRelations(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, memo)
|
||||
|
||||
// Application ADMIN is an instance role, not memo authorship.
|
||||
// Application ADMIN is the superuser and manages any memo's relations.
|
||||
_, err = ts.Service.SetMemoRelations(hostCtx, &apiv1.SetMemoRelationsRequest{
|
||||
Name: memo.Name,
|
||||
Relations: []*apiv1.MemoRelation{},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("SetMemoRelations permission denied for non-owner", func(t *testing.T) {
|
||||
|
||||
@@ -51,6 +51,104 @@ func TestAnonymousMemoAccessFollowsInstanceAccessSetting(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestInstanceAdminIsSuperuserForNamedMemoOperations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ts := NewTestService(t)
|
||||
defer ts.Cleanup()
|
||||
|
||||
owner, err := ts.CreateRegularUser(ctx, "superuser-owner")
|
||||
require.NoError(t, err)
|
||||
ownerCtx := ts.CreateUserContext(ctx, owner.ID)
|
||||
admin, err := ts.CreateHostUser(ctx, "superuser-admin")
|
||||
require.NoError(t, err)
|
||||
adminCtx := ts.CreateUserContext(ctx, admin.ID)
|
||||
other, err := ts.CreateRegularUser(ctx, "superuser-other")
|
||||
require.NoError(t, err)
|
||||
otherCtx := ts.CreateUserContext(ctx, other.ID)
|
||||
|
||||
space, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "superuser-space", Title: "Superuser"}, owner.ID)
|
||||
require.NoError(t, err)
|
||||
private, err := ts.Service.CreateMemo(ownerCtx, &apiv1.CreateMemoRequest{Memo: &apiv1.Memo{
|
||||
Content: "private memo",
|
||||
Visibility: apiv1.Visibility_PRIVATE,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
spaceMemo, err := ts.Service.CreateMemo(ownerCtx, &apiv1.CreateMemoRequest{Memo: &apiv1.Memo{
|
||||
Content: "members only",
|
||||
Visibility: apiv1.Visibility_SPACE,
|
||||
Space: ptr("spaces/" + space.UID),
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Point reads bypass audience and membership for the administrator only.
|
||||
_, err = ts.Service.GetMemo(otherCtx, &apiv1.GetMemoRequest{Name: private.Name})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
got, err := ts.Service.GetMemo(adminCtx, &apiv1.GetMemoRequest{Name: private.Name})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "private memo", got.Content)
|
||||
got, err = ts.Service.GetMemo(adminCtx, &apiv1.GetMemoRequest{Name: spaceMemo.Name})
|
||||
require.NoError(t, err, "a SPACE memo is readable by name without membership")
|
||||
require.Equal(t, "spaces/"+space.UID, got.GetSpace())
|
||||
|
||||
// Collections keep the audience predicate.
|
||||
feed, err := ts.Service.ListMemos(adminCtx, &apiv1.ListMemosRequest{PageSize: 50})
|
||||
require.NoError(t, err)
|
||||
for _, candidate := range feed.Memos {
|
||||
require.NotEqual(t, private.Name, candidate.Name, "another user's PRIVATE memo must not surface in the administrator's feed")
|
||||
require.NotEqual(t, spaceMemo.Name, candidate.Name, "a SPACE memo must not surface without membership")
|
||||
}
|
||||
_, err = ts.Service.ListMemos(adminCtx, &apiv1.ListMemosRequest{Filter: `space == "spaces/` + space.UID + `"`})
|
||||
require.Equal(t, codes.NotFound, status.Code(err), "the Space feed stays membership-only")
|
||||
|
||||
// Named mutations: content, audience, placement, comments, and deletion.
|
||||
_, err = ts.Service.UpdateMemo(otherCtx, &apiv1.UpdateMemoRequest{
|
||||
Memo: &apiv1.Memo{Name: private.Name, Content: "hijacked"},
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"content"}},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
updated, err := ts.Service.UpdateMemo(adminCtx, &apiv1.UpdateMemoRequest{
|
||||
Memo: &apiv1.Memo{Name: private.Name, Content: "edited by admin"},
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"content"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "edited by admin", updated.Content)
|
||||
require.Equal(t, "users/"+owner.Username, updated.Creator, "authorship is unchanged")
|
||||
_, err = ts.Service.UpdateMemo(adminCtx, &apiv1.UpdateMemoRequest{
|
||||
Memo: &apiv1.Memo{Name: spaceMemo.Name, Content: "edited without membership"},
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"content"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = ts.Service.UpdateMemo(adminCtx, &apiv1.UpdateMemoRequest{
|
||||
Memo: &apiv1.Memo{Name: private.Name, Visibility: apiv1.Visibility_SPACE, Space: ptr("spaces/" + space.UID)},
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"visibility", "space"}},
|
||||
})
|
||||
require.NoError(t, err, "an administrator places memos in a Space they are not a member of")
|
||||
_, err = ts.Service.UpdateMemo(adminCtx, &apiv1.UpdateMemoRequest{
|
||||
Memo: &apiv1.Memo{Name: private.Name, Space: ptr("spaces/does-not-exist")},
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"space"}},
|
||||
})
|
||||
require.Equal(t, codes.NotFound, status.Code(err), "structural validity still applies")
|
||||
_, err = ts.Service.CreateMemoComment(adminCtx, &apiv1.CreateMemoCommentRequest{
|
||||
Name: spaceMemo.Name,
|
||||
Comment: &apiv1.Memo{Content: "admin comment"},
|
||||
})
|
||||
require.NoError(t, err, "participation does not require membership")
|
||||
|
||||
_, err = ts.Service.DeleteMemo(otherCtx, &apiv1.DeleteMemoRequest{Name: private.Name})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
_, err = ts.Service.DeleteMemo(adminCtx, &apiv1.DeleteMemoRequest{Name: private.Name})
|
||||
require.NoError(t, err)
|
||||
_, err = ts.Service.GetMemo(ownerCtx, &apiv1.GetMemoRequest{Name: private.Name})
|
||||
require.Equal(t, codes.NotFound, status.Code(err))
|
||||
|
||||
// An archived administrator holds no privilege.
|
||||
archived := store.Archived
|
||||
_, err = ts.Store.UpdateUser(ctx, &store.UpdateUser{ID: admin.ID, RowStatus: &archived})
|
||||
require.NoError(t, err)
|
||||
_, err = ts.Service.GetMemo(adminCtx, &apiv1.GetMemoRequest{Name: spaceMemo.Name})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestMemoReadAllowsArchivedCreatorAccordingToAudience(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ts := NewTestService(t)
|
||||
|
||||
@@ -140,12 +140,14 @@ func TestUpsertMemoReactionRevalidatesSpaceParticipation(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// An application ADMIN has no Space participation bypass.
|
||||
_, err = ts.Service.UpsertMemoReaction(adminCtx, &apiv1.UpsertMemoReactionRequest{
|
||||
// An application ADMIN is the superuser and participates without membership.
|
||||
adminReaction, err := ts.Service.UpsertMemoReaction(adminCtx, &apiv1.UpsertMemoReactionRequest{
|
||||
Name: memoName,
|
||||
Reaction: &apiv1.Reaction{ReactionType: "🔥"},
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
require.NoError(t, err)
|
||||
_, err = ts.Service.DeleteMemoReaction(adminCtx, &apiv1.DeleteMemoReactionRequest{Name: adminReaction.Name})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, ts.Store.DeleteSpaceMember(ctx, &store.DeleteSpaceMember{SpaceID: space.ID, UserID: member.ID}, owner.ID))
|
||||
_, err = ts.Service.DeleteMemoReaction(memberCtx, &apiv1.DeleteMemoReactionRequest{Name: memberReaction.Name})
|
||||
@@ -183,7 +185,7 @@ func TestAssignedMemoReactionsFollowMemoReadAccess(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
member, err := ts.CreateRegularUser(ctx, "assigned-reaction-member")
|
||||
require.NoError(t, err)
|
||||
outsider, err := ts.CreateHostUser(ctx, "assigned-reaction-app-admin")
|
||||
outsider, err := ts.CreateRegularUser(ctx, "assigned-reaction-outsider")
|
||||
require.NoError(t, err)
|
||||
ownerCtx := ts.CreateUserContext(ctx, owner.ID)
|
||||
memberCtx := ts.CreateUserContext(ctx, member.ID)
|
||||
@@ -355,15 +357,15 @@ func TestDeleteMemoReaction(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, reaction)
|
||||
|
||||
// Application ADMIN is an instance role, not reaction ownership.
|
||||
// Application ADMIN is the superuser and may withdraw any reaction.
|
||||
_, err = ts.Service.DeleteMemoReaction(hostCtx, &apiv1.DeleteMemoReactionRequest{
|
||||
Name: reaction.Name,
|
||||
})
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
require.NoError(t, err)
|
||||
memoID := parseMemoIDFromNameForTest(t, ts, memo.Name)
|
||||
remainingReaction, err := ts.Store.GetReaction(ctx, &store.FindReaction{MemoID: &memoID, CreatorID: ®ularUser.ID})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, remainingReaction)
|
||||
require.Nil(t, remainingReaction)
|
||||
})
|
||||
|
||||
t.Run("DeleteMemoReaction permission denied for non-owner", func(t *testing.T) {
|
||||
|
||||
@@ -69,8 +69,9 @@ func ValidateAttachmentDeletionMemoSnapshots(memoIDs []int32, expectedMemoConten
|
||||
|
||||
// ValidateAttachmentMutationTargets verifies attachment rows used by a
|
||||
// transport-facing mutation and returns their distinct memo bindings in
|
||||
// ascending order.
|
||||
func ValidateAttachmentMutationTargets(actorUserID int32, attachmentIDs []int32, attachments []*Attachment) ([]int32, error) {
|
||||
// ascending order. Every attachment must be owned by the actor unless the
|
||||
// actor is an instance administrator.
|
||||
func ValidateAttachmentMutationTargets(actorUserID int32, actorIsAdmin bool, attachmentIDs []int32, attachments []*Attachment) ([]int32, error) {
|
||||
if actorUserID <= 0 || len(attachmentIDs) == 0 || len(attachments) != len(attachmentIDs) {
|
||||
return nil, ErrMemoMutationConflict
|
||||
}
|
||||
@@ -94,7 +95,7 @@ func ValidateAttachmentMutationTargets(actorUserID int32, attachmentIDs []int32,
|
||||
return nil, ErrMemoMutationConflict
|
||||
}
|
||||
seen[attachment.ID] = struct{}{}
|
||||
if attachment.CreatorID != actorUserID {
|
||||
if !actorIsAdmin && attachment.CreatorID != actorUserID {
|
||||
return nil, ErrMemoPermissionDenied
|
||||
}
|
||||
if attachment.MemoID != nil {
|
||||
|
||||
@@ -30,7 +30,7 @@ func (d *DB) CreateAttachment(ctx context.Context, create *store.Attachment) (*s
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateMySQLMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validateMySQLMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := insertMySQLAttachment(ctx, tx, create)
|
||||
@@ -239,15 +239,19 @@ func (d *DB) UpdateAttachment(ctx context.Context, update *store.UpdateAttachmen
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actor, err := requireMySQLActiveMemoActor(ctx, tx, update.Policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listMySQLAttachmentsByIDs(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizeMySQLAttachmentMutation(ctx, tx, update.Policy.ActorUserID, memoIDs, nil); err != nil {
|
||||
if err := authorizeMySQLAttachmentMutation(ctx, tx, update.Policy.ActorUserID, actor.Admin, memoIDs, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyMySQLAttachmentUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -19,18 +19,22 @@ func (d *DB) DeleteAttachmentsWithPolicy(ctx context.Context, policy *store.Atta
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
actor, err := requireMySQLActiveMemoActor(ctx, tx, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listMySQLAttachmentsByIDs(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment delete targets")
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.ValidateAttachmentDeletionMemoSnapshots(memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizeMySQLAttachmentMutation(ctx, tx, policy.ActorUserID, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
if err := authorizeMySQLAttachmentMutation(ctx, tx, policy.ActorUserID, actor.Admin, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -55,23 +59,13 @@ func authorizeMySQLAttachmentMutation(
|
||||
ctx context.Context,
|
||||
tx *sql.Tx,
|
||||
actorUserID int32,
|
||||
actorIsAdmin bool,
|
||||
memoIDs []int32,
|
||||
expectedMemoContents map[int32]string,
|
||||
) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", actorUserID).Scan(&actorStatus); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
return errors.Wrap(err, "failed to read attachment actor")
|
||||
}
|
||||
if actorStatus != store.Normal {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
|
||||
policy := &store.MemoWritePolicy{ActorUserID: actorUserID}
|
||||
for _, memoID := range memoIDs {
|
||||
snapshot := &store.MemoWriteSnapshot{}
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actorIsAdmin}
|
||||
var spaceID sql.NullInt64
|
||||
var content string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility, content
|
||||
@@ -90,7 +84,7 @@ func authorizeMySQLAttachmentMutation(
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment memo space")
|
||||
}
|
||||
if snapshot.SourceSpaceExists {
|
||||
if snapshot.SourceSpaceExists && !actorIsAdmin {
|
||||
snapshot.SourceMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *snapshot.SpaceID, actorUserID)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment memo membership")
|
||||
|
||||
+18
-7
@@ -86,17 +86,28 @@ func insertMySQLMemo(ctx context.Context, tx *sql.Tx, create *store.Memo) (*stor
|
||||
}
|
||||
|
||||
func validateMySQLMemoCreate(ctx context.Context, tx *sql.Tx, create *store.Memo) error {
|
||||
var actorStatus store.RowStatus
|
||||
err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", create.CreatorID).Scan(&actorStatus)
|
||||
if errors.Is(err, sql.ErrNoRows) || (err == nil && actorStatus != store.Normal) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
actor, err := readMySQLMemoActor(ctx, tx, create.CreatorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if create.SpaceID != nil {
|
||||
if !actor.Active {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
if create.SpaceID == nil {
|
||||
return nil
|
||||
}
|
||||
if !actor.Admin {
|
||||
return validateMySQLMemoSpaceMember(ctx, tx, *create.SpaceID, create.CreatorID)
|
||||
}
|
||||
// An instance administrator places memos without membership; the target
|
||||
// Space must still exist.
|
||||
exists, err := mysqlSpaceExists(ctx, tx, *create.SpaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return store.ErrMemoSpaceNotWritable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -303,7 +314,7 @@ func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateMySQLMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
if _, err := validateMySQLMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyMemoUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -51,14 +51,15 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
}
|
||||
}
|
||||
}
|
||||
policy := mutation.Policy
|
||||
if policy == nil && mutation.MemoUpdate != nil {
|
||||
policy = mutation.MemoUpdate.Policy
|
||||
}
|
||||
policy := mutation.WritePolicy()
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actorIsAdmin := false
|
||||
if policy != nil {
|
||||
if err := validateMySQLMemoWritePolicy(ctx, tx, mutation.MemoID, policy, mutation.MemoUpdate); err != nil {
|
||||
snapshot, err := validateMySQLMemoWritePolicy(ctx, tx, mutation.MemoID, policy, mutation.MemoUpdate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = snapshot.ActorIsAdmin
|
||||
}
|
||||
|
||||
var creatorID int32
|
||||
@@ -80,7 +81,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "removed attachment no longer exists")
|
||||
}
|
||||
for _, attachment := range removedAttachments {
|
||||
if attachment.CreatorID != mutation.MemoCreatorID || attachment.MemoID == nil || *attachment.MemoID != mutation.MemoID {
|
||||
if !store.MemoAttachmentRemovalAllowed(attachment, mutation.MemoID, actorUserID, actorIsAdmin) {
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "attachment is no longer removable from the memo")
|
||||
}
|
||||
}
|
||||
@@ -98,7 +99,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
if !memoID.Valid || memoID.Int32 != mutation.MemoID {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer bound to the memo", binding.UID)
|
||||
}
|
||||
} else if attachmentCreatorID != mutation.MemoCreatorID || memoID.Valid {
|
||||
} else if !store.MemoAttachmentBindingOwnerAllowed(attachmentCreatorID, mutation.MemoCreatorID, actorUserID, actorIsAdmin) || memoID.Valid {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer available", binding.UID)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE `attachment` SET `memo_id` = ?, `updated_ts` = FROM_UNIXTIME(?) WHERE `id` = ?", mutation.MemoID, binding.UpdatedTs, binding.ID); err != nil {
|
||||
|
||||
@@ -22,18 +22,17 @@ func authorizeMySQLMemoComment(ctx context.Context, tx *sql.Tx, contextMemoID, a
|
||||
// loadMySQLMemoParticipation resolves the current actor, Space, membership,
|
||||
// and memo state shared by comment and reaction participation.
|
||||
func loadMySQLMemoParticipation(ctx context.Context, tx *sql.Tx, memoID, actorUserID int32) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
var actorStatus store.RowStatus
|
||||
actorErr := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", actorUserID).Scan(&actorStatus)
|
||||
if actorErr != nil && !stderrors.Is(actorErr, sql.ErrNoRows) {
|
||||
return nil, actorErr
|
||||
actor, err := readMySQLMemoActor(ctx, tx, actorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snapshot := &store.MemoCommentAuthorizationSnapshot{
|
||||
ActorUserID: actorUserID,
|
||||
ActorActive: actorErr == nil && actorStatus == store.Normal,
|
||||
Actor: actor,
|
||||
ContextID: memoID,
|
||||
}
|
||||
var contextSpace sql.NullInt64
|
||||
err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, visibility, space_id
|
||||
err = tx.QueryRowContext(ctx, `SELECT creator_id, row_status, visibility, space_id
|
||||
FROM memo WHERE id = ?`, memoID).Scan(
|
||||
&snapshot.ContextCreatorID, &snapshot.ContextRowStatus, &snapshot.ContextVisibility, &contextSpace,
|
||||
)
|
||||
@@ -46,7 +45,7 @@ func loadMySQLMemoParticipation(ctx context.Context, tx *sql.Tx, memoID, actorUs
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if snapshot.ContextSpaceExists {
|
||||
if snapshot.ContextSpaceExists && !actor.Admin {
|
||||
snapshot.ContextMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *snapshot.ContextSpaceID, actorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -16,13 +16,9 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", delete.ActorUserID).Scan(&actorStatus); errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo deletion actor")
|
||||
} else if actorStatus != store.Normal {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
actor, err := requireMySQLActiveMemoActor(ctx, tx, delete.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var creatorID int32
|
||||
@@ -36,7 +32,7 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo")
|
||||
}
|
||||
if creatorID != delete.ActorUserID {
|
||||
if creatorID != delete.ActorUserID && !actor.Admin {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
}
|
||||
spaceID := store.NullInt32Pointer(space)
|
||||
@@ -48,13 +44,13 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
return nil, errors.Wrap(err, "failed to read memo space")
|
||||
}
|
||||
}
|
||||
if spaceID != nil && spaceExists {
|
||||
if spaceID != nil && spaceExists && !actor.Admin {
|
||||
actorMember, err = mysqlSpaceMemberActive(ctx, tx, *spaceID, delete.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo membership")
|
||||
}
|
||||
}
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, spaceID, spaceExists, actorMember)
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, spaceID, spaceExists, actorMember || actor.Admin)
|
||||
|
||||
attachments, err := deleteMySQLMemoSetTx(ctx, tx, []int32{delete.MemoID})
|
||||
if err != nil {
|
||||
|
||||
@@ -8,51 +8,68 @@ import (
|
||||
"github.com/usememos/memos/store"
|
||||
)
|
||||
|
||||
func validateMySQLMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", policy.ActorUserID).Scan(&actorStatus); stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if actorStatus != store.Normal {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
// readMySQLMemoActor reads the actor's lifecycle state and instance role
|
||||
// inside the mutation transaction. A missing user is the zero state.
|
||||
func readMySQLMemoActor(ctx context.Context, tx *sql.Tx, userID int32) (store.MemoActorState, error) {
|
||||
var rowStatus store.RowStatus
|
||||
var role store.Role
|
||||
err := tx.QueryRowContext(ctx, "SELECT row_status, role FROM user WHERE id = ?", userID).Scan(&rowStatus, &role)
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.MemoActorState{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
return store.NewMemoActorState(rowStatus, role), nil
|
||||
}
|
||||
|
||||
// requireMySQLActiveMemoActor resolves an actor that must be active; anything
|
||||
// else is a permission denial.
|
||||
func requireMySQLActiveMemoActor(ctx context.Context, tx *sql.Tx, userID int32) (store.MemoActorState, error) {
|
||||
actor, err := readMySQLMemoActor(ctx, tx, userID)
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return store.MemoActorState{}, store.ErrMemoPermissionDenied
|
||||
}
|
||||
return actor, nil
|
||||
}
|
||||
|
||||
// validateMySQLMemoWritePolicy authorizes a transport-facing memo mutation
|
||||
// against current database state and returns the validated snapshot.
|
||||
func validateMySQLMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) (*store.MemoWriteSnapshot, error) {
|
||||
actor, err := readMySQLMemoActor(ctx, tx, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return nil, store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
|
||||
snapshot := new(store.MemoWriteSnapshot)
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actor.Admin}
|
||||
var spaceID sql.NullInt64
|
||||
if err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility FROM memo WHERE id = ?`, memoID).Scan(
|
||||
&snapshot.CreatorID, &snapshot.RowStatus, &spaceID, &snapshot.Visibility,
|
||||
); err != nil {
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoMutationConflict
|
||||
return nil, store.ErrMemoMutationConflict
|
||||
}
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
snapshot.SpaceID = store.NullInt32Pointer(spaceID)
|
||||
if snapshot.SpaceID != nil {
|
||||
var err error
|
||||
snapshot.SourceSpaceExists, err = mysqlSpaceExists(ctx, tx, *snapshot.SpaceID)
|
||||
snapshot.SourceSpaceExists, snapshot.SourceMemberActive, err = mysqlMemoPolicySpaceState(ctx, tx, *snapshot.SpaceID, policy.ActorUserID, actor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshot.SourceSpaceExists {
|
||||
snapshot.SourceMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *snapshot.SpaceID, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if update != nil && update.SpaceID != nil {
|
||||
var err error
|
||||
snapshot.TargetSpaceExists, err = mysqlSpaceExists(ctx, tx, *update.SpaceID)
|
||||
snapshot.TargetSpaceExists, snapshot.TargetMemberActive, err = mysqlMemoPolicySpaceState(ctx, tx, *update.SpaceID, policy.ActorUserID, actor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshot.TargetSpaceExists {
|
||||
snapshot.TargetMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *update.SpaceID, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,10 +80,25 @@ func validateMySQLMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int32,
|
||||
LIMIT 1`, memoID).Scan(&shareID)
|
||||
snapshot.HasActiveShare = err == nil
|
||||
if err != nil && !stderrors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return store.ValidateMemoWriteSnapshot(policy, update, snapshot)
|
||||
if err := store.ValidateMemoWriteSnapshot(policy, update, snapshot); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// mysqlMemoPolicySpaceState reports whether the Space exists and whether the
|
||||
// actor is an active member. Membership is not consulted for an instance
|
||||
// administrator, so it is not queried.
|
||||
func mysqlMemoPolicySpaceState(ctx context.Context, tx *sql.Tx, spaceID, actorUserID int32, actor store.MemoActorState) (bool, bool, error) {
|
||||
exists, err := mysqlSpaceExists(ctx, tx, spaceID)
|
||||
if err != nil || !exists || actor.Admin {
|
||||
return exists, false, err
|
||||
}
|
||||
member, err := mysqlSpaceMemberActive(ctx, tx, spaceID, actorUserID)
|
||||
return true, member, err
|
||||
}
|
||||
|
||||
func mysqlSpaceExists(ctx context.Context, tx *sql.Tx, spaceID int32) (bool, error) {
|
||||
|
||||
@@ -21,12 +21,11 @@ func validateMySQLMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, mutatio
|
||||
return nil
|
||||
}
|
||||
|
||||
var actorStatus store.RowStatus
|
||||
actorErr := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", mutation.MemoCreatorID).Scan(&actorStatus)
|
||||
if actorErr != nil && !stderrors.Is(actorErr, sql.ErrNoRows) {
|
||||
return actorErr
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actor, err := readMySQLMemoActor(ctx, tx, actorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorActive := actorErr == nil && actorStatus == store.Normal
|
||||
|
||||
endpointIDs := mysqlRelationAuthorizationEndpointIDs(mutation)
|
||||
for _, endpointID := range endpointIDs {
|
||||
@@ -38,8 +37,8 @@ func validateMySQLMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, mutatio
|
||||
return err
|
||||
}
|
||||
snapshot := &store.MemoRelationEndpointSnapshot{
|
||||
ActorUserID: mutation.MemoCreatorID,
|
||||
ActorActive: actorActive,
|
||||
ActorUserID: actorUserID,
|
||||
Actor: actor,
|
||||
EndpointID: state.id,
|
||||
EndpointCreatorID: state.creatorID,
|
||||
EndpointRowStatus: state.rowStatus,
|
||||
@@ -51,8 +50,8 @@ func validateMySQLMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, mutatio
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshot.EndpointSpaceExists {
|
||||
snapshot.EndpointMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *state.spaceID, mutation.MemoCreatorID)
|
||||
if snapshot.EndpointSpaceExists && !actor.Admin {
|
||||
snapshot.EndpointMemberActive, err = mysqlSpaceMemberActive(ctx, tx, *state.spaceID, actorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ func (d *DB) CreateMemoShare(ctx context.Context, create *store.MemoShare) (*sto
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateMySQLMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validateMySQLMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := createMySQLMemoShare(ctx, tx, create)
|
||||
@@ -142,7 +142,7 @@ func (d *DB) DeleteMemoShare(ctx context.Context, delete *store.DeleteMemoShare)
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateMySQLMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
if _, err := validateMySQLMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
where, args := mysqlMemoShareDeleteWhere(delete)
|
||||
|
||||
@@ -156,14 +156,17 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
return errors.Wrap(err, "failed to begin authorized reaction delete transaction")
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actorIsAdmin := false
|
||||
if delete.Policy != nil {
|
||||
if err := validateMySQLReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
participation, err := validateMySQLReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
CreatorID: *delete.ActorUserID,
|
||||
MemoID: *delete.MemoID,
|
||||
Policy: delete.Policy,
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = participation.Actor.Admin
|
||||
}
|
||||
|
||||
var creatorID, memoID int32
|
||||
@@ -173,7 +176,8 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction for deletion")
|
||||
}
|
||||
if creatorID != *delete.ActorUserID || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
// An instance administrator may withdraw any reaction on the named memo.
|
||||
if (creatorID != *delete.ActorUserID && !actorIsAdmin) || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
return store.ErrReactionPermissionDenied
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM reaction WHERE id = ?", *delete.ID); err != nil {
|
||||
|
||||
@@ -21,16 +21,21 @@ func validateMySQLReactionWritePolicy(ctx context.Context, tx *sql.Tx, reaction
|
||||
return store.ValidateReactionWriteParticipation(reaction, participation)
|
||||
}
|
||||
|
||||
func validateMySQLReactionDeletePolicy(ctx context.Context, tx *sql.Tx, reaction *store.Reaction) error {
|
||||
// validateMySQLReactionDeletePolicy authorizes a withdrawal and returns the
|
||||
// participation snapshot so the caller can honour an administrator actor.
|
||||
func validateMySQLReactionDeletePolicy(ctx context.Context, tx *sql.Tx, reaction *store.Reaction) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
policy := reaction.Policy
|
||||
participation, err := loadMySQLMemoParticipation(ctx, tx, reaction.MemoID, policy.ActorUserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrReactionMemoNotFound
|
||||
return nil, store.ErrReactionMemoNotFound
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction participation")
|
||||
return nil, errors.Wrap(err, "failed to read reaction participation")
|
||||
}
|
||||
return store.ValidateReactionWithdrawal(reaction, participation)
|
||||
if err := store.ValidateReactionWithdrawal(reaction, participation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return participation, nil
|
||||
}
|
||||
|
||||
func mysqlSpaceMemberActive(ctx context.Context, tx *sql.Tx, spaceID, userID int32) (bool, error) {
|
||||
|
||||
@@ -26,7 +26,7 @@ func (d *DB) CreateAttachment(ctx context.Context, create *store.Attachment) (*s
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validatePostgresMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validatePostgresMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attachment, err := insertPostgresAttachment(ctx, tx, create)
|
||||
@@ -225,15 +225,19 @@ func (d *DB) UpdateAttachment(ctx context.Context, update *store.UpdateAttachmen
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actor, err := requirePostgresActiveMemoActor(ctx, tx, update.Policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listPostgresAttachmentSnapshots(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizePostgresAttachmentMutation(ctx, tx, update.Policy.ActorUserID, memoIDs, nil); err != nil {
|
||||
if err := authorizePostgresAttachmentMutation(ctx, tx, update.Policy.ActorUserID, actor.Admin, memoIDs, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyPostgresAttachmentUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -19,18 +19,22 @@ func (d *DB) DeleteAttachmentsWithPolicy(ctx context.Context, policy *store.Atta
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
actor, err := requirePostgresActiveMemoActor(ctx, tx, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listPostgresAttachmentSnapshots(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment delete targets")
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.ValidateAttachmentDeletionMemoSnapshots(memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizePostgresAttachmentMutation(ctx, tx, policy.ActorUserID, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
if err := authorizePostgresAttachmentMutation(ctx, tx, policy.ActorUserID, actor.Admin, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -68,23 +72,13 @@ func authorizePostgresAttachmentMutation(
|
||||
ctx context.Context,
|
||||
tx *sql.Tx,
|
||||
actorUserID int32,
|
||||
actorIsAdmin bool,
|
||||
memoIDs []int32,
|
||||
expectedMemoContents map[int32]string,
|
||||
) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, `SELECT row_status FROM "user" WHERE id = $1`, actorUserID).Scan(&actorStatus); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
return errors.Wrap(err, "failed to read attachment actor")
|
||||
}
|
||||
if actorStatus != store.Normal {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
|
||||
writePolicy := &store.MemoWritePolicy{ActorUserID: actorUserID}
|
||||
for _, memoID := range memoIDs {
|
||||
snapshot := &store.MemoWriteSnapshot{}
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actorIsAdmin}
|
||||
var memoSpace sql.NullInt64
|
||||
var content string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility, content
|
||||
|
||||
@@ -67,17 +67,28 @@ func insertPostgresMemo(ctx context.Context, tx *sql.Tx, create *store.Memo) err
|
||||
}
|
||||
|
||||
func validatePostgresMemoCreate(ctx context.Context, tx *sql.Tx, create *store.Memo) error {
|
||||
var actorStatus store.RowStatus
|
||||
err := tx.QueryRowContext(ctx, `SELECT row_status FROM "user" WHERE id = $1`, create.CreatorID).Scan(&actorStatus)
|
||||
if errors.Is(err, sql.ErrNoRows) || (err == nil && actorStatus != store.Normal) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
actor, err := readPostgresMemoActor(ctx, tx, create.CreatorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if create.SpaceID != nil {
|
||||
if !actor.Active {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
if create.SpaceID == nil {
|
||||
return nil
|
||||
}
|
||||
if !actor.Admin {
|
||||
return validatePostgresMemoSpaceMember(ctx, tx, *create.SpaceID, create.CreatorID)
|
||||
}
|
||||
// An instance administrator places memos without membership; the target
|
||||
// Space must still exist.
|
||||
exists, err := postgresSpaceExists(ctx, tx, *create.SpaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return store.ErrMemoSpaceNotWritable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -282,7 +293,7 @@ func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validatePostgresMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
if _, err := validatePostgresMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyMemoUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -49,14 +49,15 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
}
|
||||
}
|
||||
}
|
||||
policy := mutation.Policy
|
||||
if policy == nil && mutation.MemoUpdate != nil {
|
||||
policy = mutation.MemoUpdate.Policy
|
||||
}
|
||||
policy := mutation.WritePolicy()
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actorIsAdmin := false
|
||||
if policy != nil {
|
||||
if err := validatePostgresMemoWritePolicy(ctx, tx, mutation.MemoID, policy, mutation.MemoUpdate); err != nil {
|
||||
snapshot, err := validatePostgresMemoWritePolicy(ctx, tx, mutation.MemoID, policy, mutation.MemoUpdate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = snapshot.ActorIsAdmin
|
||||
}
|
||||
|
||||
var creatorID int32
|
||||
@@ -78,7 +79,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "removed attachment no longer exists")
|
||||
}
|
||||
for _, attachment := range removedAttachments {
|
||||
if attachment.CreatorID != mutation.MemoCreatorID || attachment.MemoID == nil || *attachment.MemoID != mutation.MemoID {
|
||||
if !store.MemoAttachmentRemovalAllowed(attachment, mutation.MemoID, actorUserID, actorIsAdmin) {
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "attachment is no longer removable from the memo")
|
||||
}
|
||||
}
|
||||
@@ -96,7 +97,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
if !memoID.Valid || memoID.Int32 != mutation.MemoID {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer bound to the memo", binding.UID)
|
||||
}
|
||||
} else if attachmentCreatorID != mutation.MemoCreatorID || memoID.Valid {
|
||||
} else if !store.MemoAttachmentBindingOwnerAllowed(attachmentCreatorID, mutation.MemoCreatorID, actorUserID, actorIsAdmin) || memoID.Valid {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer available", binding.UID)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE attachment SET memo_id = $1, updated_ts = $2 WHERE id = $3`, mutation.MemoID, binding.UpdatedTs, binding.ID); err != nil {
|
||||
|
||||
@@ -22,14 +22,14 @@ func authorizePostgresMemoComment(ctx context.Context, tx *sql.Tx, contextMemoID
|
||||
// readPostgresMemoParticipation resolves the current actor, Space, membership,
|
||||
// and memo state shared by comment and reaction participation.
|
||||
func readPostgresMemoParticipation(ctx context.Context, tx *sql.Tx, memoID, actorUserID int32) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
userStatuses, err := readPostgresUserStatuses(ctx, tx, actorUserID)
|
||||
actor, err := readPostgresMemoActor(ctx, tx, actorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
snapshot := &store.MemoCommentAuthorizationSnapshot{
|
||||
ActorUserID: actorUserID,
|
||||
ActorActive: userStatuses[actorUserID] == store.Normal,
|
||||
Actor: actor,
|
||||
ContextID: memoID,
|
||||
}
|
||||
var contextSpace sql.NullInt64
|
||||
|
||||
@@ -16,13 +16,9 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, `SELECT row_status FROM "user" WHERE id = $1`, delete.ActorUserID).Scan(&actorStatus); errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo deletion actor")
|
||||
} else if actorStatus != store.Normal {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
actor, err := requirePostgresActiveMemoActor(ctx, tx, delete.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var creatorID int32
|
||||
@@ -36,7 +32,7 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo")
|
||||
}
|
||||
if creatorID != delete.ActorUserID {
|
||||
if creatorID != delete.ActorUserID && !actor.Admin {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
}
|
||||
memoSpaceID := store.NullInt32Pointer(memoSpace)
|
||||
@@ -47,7 +43,7 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
return nil, errors.Wrap(err, "failed to read memo space state")
|
||||
}
|
||||
}
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, memoSpaceID, spaceExists, actorMember)
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, memoSpaceID, spaceExists, actorMember || actor.Admin)
|
||||
|
||||
attachments, err := deletePostgresMemoSetTx(ctx, tx, []int32{delete.MemoID})
|
||||
if err != nil {
|
||||
|
||||
@@ -8,29 +8,58 @@ import (
|
||||
"github.com/usememos/memos/store"
|
||||
)
|
||||
|
||||
func validatePostgresMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, `SELECT row_status FROM "user" WHERE id = $1`, policy.ActorUserID).Scan(&actorStatus); stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if actorStatus != store.Normal {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
// readPostgresMemoActor reads the actor's lifecycle state and instance role
|
||||
// inside the mutation transaction. A missing user is the zero state.
|
||||
func readPostgresMemoActor(ctx context.Context, tx *sql.Tx, userID int32) (store.MemoActorState, error) {
|
||||
var rowStatus store.RowStatus
|
||||
var role store.Role
|
||||
err := tx.QueryRowContext(ctx, `SELECT row_status, role FROM "user" WHERE id = $1`, userID).Scan(&rowStatus, &role)
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.MemoActorState{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
return store.NewMemoActorState(rowStatus, role), nil
|
||||
}
|
||||
|
||||
// requirePostgresActiveMemoActor resolves an actor that must be active;
|
||||
// anything else is a permission denial.
|
||||
func requirePostgresActiveMemoActor(ctx context.Context, tx *sql.Tx, userID int32) (store.MemoActorState, error) {
|
||||
actor, err := readPostgresMemoActor(ctx, tx, userID)
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return store.MemoActorState{}, store.ErrMemoPermissionDenied
|
||||
}
|
||||
return actor, nil
|
||||
}
|
||||
|
||||
// validatePostgresMemoWritePolicy authorizes a transport-facing memo mutation
|
||||
// against current database state and returns the validated snapshot.
|
||||
func validatePostgresMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) (*store.MemoWriteSnapshot, error) {
|
||||
actor, err := readPostgresMemoActor(ctx, tx, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return nil, store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
|
||||
snapshot := new(store.MemoWriteSnapshot)
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actor.Admin}
|
||||
var sourceSpace sql.NullInt64
|
||||
if err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility FROM memo WHERE id = $1`, memoID).Scan(
|
||||
&snapshot.CreatorID, &snapshot.RowStatus, &sourceSpace, &snapshot.Visibility,
|
||||
); err != nil {
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoMutationConflict
|
||||
return nil, store.ErrMemoMutationConflict
|
||||
}
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
snapshot.SpaceID = store.NullInt32Pointer(sourceSpace)
|
||||
if err := populatePostgresMemoPolicySpaceState(ctx, tx, policy.ActorUserID, update, snapshot); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if update != nil && update.Visibility != nil && *update.Visibility == store.SpaceAudience {
|
||||
@@ -40,10 +69,13 @@ func validatePostgresMemoWritePolicy(ctx context.Context, tx *sql.Tx, memoID int
|
||||
LIMIT 1`, memoID).Scan(&shareID)
|
||||
snapshot.HasActiveShare = err == nil
|
||||
if err != nil && !stderrors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return store.ValidateMemoWriteSnapshot(policy, update, snapshot)
|
||||
if err := store.ValidateMemoWriteSnapshot(policy, update, snapshot); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func populatePostgresMemoPolicySpaceState(
|
||||
@@ -75,6 +107,8 @@ func populatePostgresMemoPolicySpaceState(
|
||||
return nil
|
||||
}
|
||||
|
||||
// readPostgresMemoSpaceState reports whether the Space exists and whether the
|
||||
// actor is an active member, in one round trip.
|
||||
func readPostgresMemoSpaceState(ctx context.Context, tx *sql.Tx, spaceID, actorUserID int32) (bool, bool, error) {
|
||||
var spaceExists, memberActive bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT
|
||||
@@ -86,3 +120,11 @@ func readPostgresMemoSpaceState(ctx context.Context, tx *sql.Tx, spaceID, actorU
|
||||
}
|
||||
return spaceExists, memberActive, nil
|
||||
}
|
||||
|
||||
func postgresSpaceExists(ctx context.Context, tx *sql.Tx, spaceID int32) (bool, error) {
|
||||
var exists bool
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM space WHERE id = $1)", spaceID).Scan(&exists); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ func validatePostgresMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, muta
|
||||
return nil
|
||||
}
|
||||
|
||||
userStatuses, err := readPostgresUserStatuses(ctx, tx, mutation.MemoCreatorID)
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actor, err := readPostgresMemoActor(ctx, tx, actorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorActive := userStatuses[mutation.MemoCreatorID] == store.Normal
|
||||
|
||||
endpointIDs := postgresRelationAuthorizationEndpointIDs(mutation)
|
||||
for _, endpointID := range endpointIDs {
|
||||
@@ -37,8 +37,8 @@ func validatePostgresMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, muta
|
||||
return err
|
||||
}
|
||||
snapshot := &store.MemoRelationEndpointSnapshot{
|
||||
ActorUserID: mutation.MemoCreatorID,
|
||||
ActorActive: actorActive,
|
||||
ActorUserID: actorUserID,
|
||||
Actor: actor,
|
||||
EndpointID: state.id,
|
||||
EndpointCreatorID: state.creatorID,
|
||||
EndpointRowStatus: state.rowStatus,
|
||||
@@ -47,7 +47,7 @@ func validatePostgresMemoRelationEndpoints(ctx context.Context, tx *sql.Tx, muta
|
||||
}
|
||||
if state.spaceID != nil {
|
||||
snapshot.EndpointSpaceExists, snapshot.EndpointMemberActive, err = readPostgresMemoSpaceState(
|
||||
ctx, tx, *state.spaceID, mutation.MemoCreatorID,
|
||||
ctx, tx, *state.spaceID, actorUserID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -18,7 +18,7 @@ func (d *DB) CreateMemoShare(ctx context.Context, create *store.MemoShare) (*sto
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validatePostgresMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validatePostgresMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := createPostgresMemoShare(ctx, tx, create)
|
||||
@@ -162,7 +162,7 @@ func (d *DB) DeleteMemoShare(ctx context.Context, delete *store.DeleteMemoShare)
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validatePostgresMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
if _, err := validatePostgresMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
where, args := postgresMemoShareDeleteWhere(delete)
|
||||
|
||||
@@ -155,14 +155,17 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
return errors.Wrap(err, "failed to begin authorized reaction delete transaction")
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actorIsAdmin := false
|
||||
if delete.Policy != nil {
|
||||
if err := validatePostgresReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
participation, err := validatePostgresReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
CreatorID: *delete.ActorUserID,
|
||||
MemoID: *delete.MemoID,
|
||||
Policy: delete.Policy,
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = participation.Actor.Admin
|
||||
}
|
||||
|
||||
var creatorID, memoID int32
|
||||
@@ -172,7 +175,8 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction for deletion")
|
||||
}
|
||||
if creatorID != *delete.ActorUserID || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
// An instance administrator may withdraw any reaction on the named memo.
|
||||
if (creatorID != *delete.ActorUserID && !actorIsAdmin) || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
return store.ErrReactionPermissionDenied
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM reaction WHERE id = $1", *delete.ID); err != nil {
|
||||
|
||||
@@ -21,14 +21,19 @@ func validatePostgresReactionWritePolicy(ctx context.Context, tx *sql.Tx, reacti
|
||||
return store.ValidateReactionWriteParticipation(reaction, participation)
|
||||
}
|
||||
|
||||
func validatePostgresReactionDeletePolicy(ctx context.Context, tx *sql.Tx, reaction *store.Reaction) error {
|
||||
// validatePostgresReactionDeletePolicy authorizes a withdrawal and returns the
|
||||
// participation snapshot so the caller can honour an administrator actor.
|
||||
func validatePostgresReactionDeletePolicy(ctx context.Context, tx *sql.Tx, reaction *store.Reaction) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
policy := reaction.Policy
|
||||
participation, err := readPostgresMemoParticipation(ctx, tx, reaction.MemoID, policy.ActorUserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrReactionMemoNotFound
|
||||
return nil, store.ErrReactionMemoNotFound
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction participation")
|
||||
return nil, errors.Wrap(err, "failed to read reaction participation")
|
||||
}
|
||||
return store.ValidateReactionWithdrawal(reaction, participation)
|
||||
if err := store.ValidateReactionWithdrawal(reaction, participation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return participation, nil
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func (d *DB) CreateAttachment(ctx context.Context, create *store.Attachment) (*s
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateSQLiteMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validateSQLiteMemoWritePolicy(ctx, tx, *create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attachment, err := insertSQLiteAttachment(ctx, tx, create)
|
||||
@@ -218,15 +218,19 @@ func (d *DB) UpdateAttachment(ctx context.Context, update *store.UpdateAttachmen
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actor, err := requireSQLiteActiveMemoActor(ctx, tx, update.Policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listSQLiteAttachmentSnapshots(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(update.Policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizeSQLiteAttachmentMutation(ctx, tx, update.Policy.ActorUserID, memoIDs, nil); err != nil {
|
||||
if err := authorizeSQLiteAttachmentMutation(ctx, tx, update.Policy.ActorUserID, actor.Admin, memoIDs, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applySQLiteAttachmentUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -18,18 +18,22 @@ func (d *DB) DeleteAttachmentsWithPolicy(ctx context.Context, policy *store.Atta
|
||||
return errors.Wrap(err, "failed to begin attachment delete transaction")
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actor, err := requireSQLiteActiveMemoActor(ctx, tx, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attachments, err := listSQLiteAttachmentSnapshots(ctx, tx, attachmentIDs)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment delete targets")
|
||||
}
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, attachmentIDs, attachments)
|
||||
memoIDs, err := store.ValidateAttachmentMutationTargets(policy.ActorUserID, actor.Admin, attachmentIDs, attachments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.ValidateAttachmentDeletionMemoSnapshots(memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := authorizeSQLiteAttachmentMutation(ctx, tx, policy.ActorUserID, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
if err := authorizeSQLiteAttachmentMutation(ctx, tx, policy.ActorUserID, actor.Admin, memoIDs, policy.ExpectedMemoContents); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -67,22 +71,12 @@ func authorizeSQLiteAttachmentMutation(
|
||||
ctx context.Context,
|
||||
tx dbExecutor,
|
||||
actorUserID int32,
|
||||
actorIsAdmin bool,
|
||||
memoIDs []int32,
|
||||
expectedMemoContents map[int32]string,
|
||||
) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", actorUserID).Scan(&actorStatus); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
return errors.Wrap(err, "failed to read attachment actor")
|
||||
}
|
||||
if actorStatus != store.Normal {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
|
||||
for _, memoID := range memoIDs {
|
||||
snapshot := &store.MemoWriteSnapshot{}
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actorIsAdmin}
|
||||
var currentSpace sql.NullInt64
|
||||
var content string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility, content
|
||||
@@ -104,7 +98,7 @@ func authorizeSQLiteAttachmentMutation(
|
||||
return errors.Wrap(err, "failed to read attachment memo space")
|
||||
}
|
||||
snapshot.SourceSpaceExists = exists
|
||||
if exists {
|
||||
if exists && !actorIsAdmin {
|
||||
active, err := sqliteSpaceMemberActive(ctx, tx, *snapshot.SpaceID, actorUserID)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read attachment memo membership")
|
||||
|
||||
+25
-15
@@ -2,7 +2,6 @@ package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -70,29 +69,40 @@ func insertSQLiteMemo(ctx context.Context, tx dbExecutor, create *store.Memo) er
|
||||
}
|
||||
|
||||
func validateSQLiteMemoCreate(ctx context.Context, tx dbExecutor, create *store.Memo) error {
|
||||
var actorStatus store.RowStatus
|
||||
err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", create.CreatorID).Scan(&actorStatus)
|
||||
if errors.Is(err, sql.ErrNoRows) || (err == nil && actorStatus != store.Normal) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
actor, err := readSQLiteMemoActor(ctx, tx, create.CreatorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if create.SpaceID != nil {
|
||||
if !actor.Active {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
if create.SpaceID == nil {
|
||||
return nil
|
||||
}
|
||||
if !actor.Admin {
|
||||
return validateSQLiteMemoSpaceMember(ctx, tx, *create.SpaceID, create.CreatorID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSQLiteMemoSpaceMember(ctx context.Context, tx dbExecutor, spaceID, userID int32) error {
|
||||
var exists bool
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM space WHERE id = ?)", spaceID).Scan(&exists); err != nil {
|
||||
// An instance administrator places memos without membership; the target
|
||||
// Space must still exist.
|
||||
exists, err := sqliteSpaceExists(ctx, tx, *create.SpaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return store.ErrMemoSpaceNotWritable
|
||||
}
|
||||
err := tx.QueryRowContext(ctx, `SELECT EXISTS(
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSQLiteMemoSpaceMember(ctx context.Context, tx dbExecutor, spaceID, userID int32) error {
|
||||
exists, err := sqliteSpaceExists(ctx, tx, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return store.ErrMemoSpaceNotWritable
|
||||
}
|
||||
err = tx.QueryRowContext(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM space_member sm JOIN user u ON u.id = sm.user_id
|
||||
WHERE sm.space_id = ? AND sm.user_id = ? AND sm.status = 'ACTIVE'
|
||||
AND sm.role IN ('ADMIN', 'USER') AND u.row_status = 'NORMAL')`, spaceID, userID).Scan(&exists)
|
||||
@@ -274,7 +284,7 @@ func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateSQLiteMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
if _, err := validateSQLiteMemoWritePolicy(ctx, tx, update.ID, update.Policy, update); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyMemoUpdate(ctx, tx, update); err != nil {
|
||||
|
||||
@@ -57,14 +57,15 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
}
|
||||
}
|
||||
}
|
||||
policy := mutation.Policy
|
||||
if policy == nil && mutation.MemoUpdate != nil {
|
||||
policy = mutation.MemoUpdate.Policy
|
||||
}
|
||||
policy := mutation.WritePolicy()
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actorIsAdmin := false
|
||||
if policy != nil {
|
||||
if err := validateSQLiteMemoWritePolicy(ctx, conn, mutation.MemoID, policy, mutation.MemoUpdate); err != nil {
|
||||
snapshot, err := validateSQLiteMemoWritePolicy(ctx, conn, mutation.MemoID, policy, mutation.MemoUpdate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = snapshot.ActorIsAdmin
|
||||
}
|
||||
|
||||
var creatorID int32
|
||||
@@ -86,7 +87,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "removed attachment no longer exists")
|
||||
}
|
||||
for _, attachment := range removedAttachments {
|
||||
if attachment.CreatorID != mutation.MemoCreatorID || attachment.MemoID == nil || *attachment.MemoID != mutation.MemoID {
|
||||
if !store.MemoAttachmentRemovalAllowed(attachment, mutation.MemoID, actorUserID, actorIsAdmin) {
|
||||
return errors.Wrap(store.ErrMemoMutationConflict, "attachment is no longer removable from the memo")
|
||||
}
|
||||
}
|
||||
@@ -104,7 +105,7 @@ func (d *DB) ApplyMemoMutation(ctx context.Context, mutation *store.MemoMutation
|
||||
if !memoID.Valid || memoID.Int32 != mutation.MemoID {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer bound to the memo", binding.UID)
|
||||
}
|
||||
} else if attachmentCreatorID != mutation.MemoCreatorID || memoID.Valid {
|
||||
} else if !store.MemoAttachmentBindingOwnerAllowed(attachmentCreatorID, mutation.MemoCreatorID, actorUserID, actorIsAdmin) || memoID.Valid {
|
||||
return errors.Wrapf(store.ErrMemoMutationConflict, "attachment %s is no longer available", binding.UID)
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, `UPDATE attachment SET memo_id = ?, updated_ts = ? WHERE id = ?`, mutation.MemoID, binding.UpdatedTs, binding.ID); err != nil {
|
||||
|
||||
@@ -22,18 +22,14 @@ func authorizeSQLiteMemoComment(ctx context.Context, tx dbExecutor, contextMemoI
|
||||
// loadSQLiteMemoParticipation resolves the current actor, Space, membership,
|
||||
// and memo state shared by comment and reaction participation.
|
||||
func loadSQLiteMemoParticipation(ctx context.Context, tx dbExecutor, memoID, actorUserID int32) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
snapshot := &store.MemoCommentAuthorizationSnapshot{ActorUserID: actorUserID, ContextID: memoID}
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", actorUserID).Scan(&actorStatus); err != nil {
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
}
|
||||
actor, err := readSQLiteMemoActor(ctx, tx, actorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snapshot.ActorActive = actorStatus == store.Normal
|
||||
snapshot := &store.MemoCommentAuthorizationSnapshot{ActorUserID: actorUserID, Actor: actor, ContextID: memoID}
|
||||
|
||||
var contextSpace sql.NullInt64
|
||||
err := tx.QueryRowContext(ctx, `SELECT creator_id, row_status, visibility, space_id FROM memo WHERE id = ?`, memoID).Scan(
|
||||
err = tx.QueryRowContext(ctx, `SELECT creator_id, row_status, visibility, space_id FROM memo WHERE id = ?`, memoID).Scan(
|
||||
&snapshot.ContextCreatorID, &snapshot.ContextRowStatus, &snapshot.ContextVisibility, &contextSpace,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -48,6 +44,9 @@ func loadSQLiteMemoParticipation(ctx context.Context, tx dbExecutor, memoID, act
|
||||
} else if !stderrors.Is(err, sql.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
if actor.Admin {
|
||||
return snapshot, nil
|
||||
}
|
||||
if snapshot.ContextMemberActive, err = sqliteSpaceMemberActive(ctx, tx, *snapshot.ContextSpaceID, actorUserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -16,13 +16,9 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var actorStatus store.RowStatus
|
||||
if err := tx.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", delete.ActorUserID).Scan(&actorStatus); errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo deletion actor")
|
||||
} else if actorStatus != store.Normal {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
actor, err := requireSQLiteActiveMemoActor(ctx, tx, delete.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var creatorID int32
|
||||
var rowStatus store.RowStatus
|
||||
@@ -34,7 +30,7 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
return nil, store.ErrMemoMutationConflict
|
||||
} else if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo")
|
||||
} else if creatorID != delete.ActorUserID {
|
||||
} else if creatorID != delete.ActorUserID && !actor.Admin {
|
||||
return nil, store.ErrMemoPermissionDenied
|
||||
}
|
||||
spaceID := store.NullInt32Pointer(space)
|
||||
@@ -47,14 +43,14 @@ func (d *DB) DeleteMemoWithPolicy(ctx context.Context, delete *store.DeleteMemoW
|
||||
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, errors.Wrap(err, "failed to read memo space")
|
||||
}
|
||||
if spaceExists {
|
||||
if spaceExists && !actor.Admin {
|
||||
actorMember, err = sqliteSpaceMemberActive(ctx, tx, *spaceID, delete.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read memo membership")
|
||||
}
|
||||
}
|
||||
}
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, spaceID, spaceExists, actorMember)
|
||||
actorCanRead := store.MemoDeleteActorCanRead(rowStatus, visibility, spaceID, spaceExists, actorMember || actor.Admin)
|
||||
|
||||
attachments, err := deleteSQLiteMemoSetTx(ctx, tx, []int32{delete.MemoID})
|
||||
if err != nil {
|
||||
|
||||
@@ -8,29 +8,58 @@ import (
|
||||
"github.com/usememos/memos/store"
|
||||
)
|
||||
|
||||
func validateSQLiteMemoWritePolicy(ctx context.Context, executor dbExecutor, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) error {
|
||||
var actorStatus store.RowStatus
|
||||
if err := executor.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", policy.ActorUserID).Scan(&actorStatus); stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if actorStatus != store.Normal {
|
||||
return store.ErrMemoSpaceMembershipRequired
|
||||
// readSQLiteMemoActor reads the actor's lifecycle state and instance role
|
||||
// inside the mutation transaction. A missing user is the zero state.
|
||||
func readSQLiteMemoActor(ctx context.Context, executor dbExecutor, userID int32) (store.MemoActorState, error) {
|
||||
var rowStatus store.RowStatus
|
||||
var role store.Role
|
||||
err := executor.QueryRowContext(ctx, "SELECT row_status, role FROM user WHERE id = ?", userID).Scan(&rowStatus, &role)
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.MemoActorState{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
return store.NewMemoActorState(rowStatus, role), nil
|
||||
}
|
||||
|
||||
// requireSQLiteActiveMemoActor resolves an actor that must be active;
|
||||
// anything else is a permission denial.
|
||||
func requireSQLiteActiveMemoActor(ctx context.Context, executor dbExecutor, userID int32) (store.MemoActorState, error) {
|
||||
actor, err := readSQLiteMemoActor(ctx, executor, userID)
|
||||
if err != nil {
|
||||
return store.MemoActorState{}, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return store.MemoActorState{}, store.ErrMemoPermissionDenied
|
||||
}
|
||||
return actor, nil
|
||||
}
|
||||
|
||||
// validateSQLiteMemoWritePolicy authorizes a transport-facing memo mutation
|
||||
// against current database state and returns the validated snapshot.
|
||||
func validateSQLiteMemoWritePolicy(ctx context.Context, executor dbExecutor, memoID int32, policy *store.MemoWritePolicy, update *store.UpdateMemo) (*store.MemoWriteSnapshot, error) {
|
||||
actor, err := readSQLiteMemoActor(ctx, executor, policy.ActorUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !actor.Active {
|
||||
return nil, store.ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
|
||||
snapshot := new(store.MemoWriteSnapshot)
|
||||
snapshot := &store.MemoWriteSnapshot{ActorIsAdmin: actor.Admin}
|
||||
var spaceID sql.NullInt64
|
||||
if err := executor.QueryRowContext(ctx, `SELECT creator_id, row_status, space_id, visibility FROM memo WHERE id = ?`, memoID).Scan(
|
||||
&snapshot.CreatorID, &snapshot.RowStatus, &spaceID, &snapshot.Visibility,
|
||||
); err != nil {
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoMutationConflict
|
||||
return nil, store.ErrMemoMutationConflict
|
||||
}
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
snapshot.SpaceID = store.NullInt32Pointer(spaceID)
|
||||
if err := populateSQLiteMemoPolicySpaceState(ctx, executor, policy.ActorUserID, update, snapshot); err != nil {
|
||||
return err
|
||||
if err := populateSQLiteMemoPolicySpaceState(ctx, executor, policy.ActorUserID, actor, update, snapshot); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if update != nil && update.Visibility != nil && *update.Visibility == store.SpaceAudience {
|
||||
@@ -40,21 +69,25 @@ func validateSQLiteMemoWritePolicy(ctx context.Context, executor dbExecutor, mem
|
||||
LIMIT 1`, memoID).Scan(&shareID)
|
||||
snapshot.HasActiveShare = err == nil
|
||||
if err != nil && !stderrors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return store.ValidateMemoWriteSnapshot(policy, update, snapshot)
|
||||
if err := store.ValidateMemoWriteSnapshot(policy, update, snapshot); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func populateSQLiteMemoPolicySpaceState(
|
||||
ctx context.Context,
|
||||
executor dbExecutor,
|
||||
actorUserID int32,
|
||||
actor store.MemoActorState,
|
||||
update *store.UpdateMemo,
|
||||
snapshot *store.MemoWriteSnapshot,
|
||||
) error {
|
||||
if snapshot.SpaceID != nil {
|
||||
exists, member, err := sqliteMemoPolicySpaceState(ctx, executor, *snapshot.SpaceID, actorUserID)
|
||||
exists, member, err := sqliteMemoPolicySpaceState(ctx, executor, *snapshot.SpaceID, actorUserID, actor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -62,7 +95,7 @@ func populateSQLiteMemoPolicySpaceState(
|
||||
snapshot.SourceMemberActive = member
|
||||
}
|
||||
if update != nil && update.SpaceID != nil {
|
||||
exists, member, err := sqliteMemoPolicySpaceState(ctx, executor, *update.SpaceID, actorUserID)
|
||||
exists, member, err := sqliteMemoPolicySpaceState(ctx, executor, *update.SpaceID, actorUserID, actor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -72,14 +105,22 @@ func populateSQLiteMemoPolicySpaceState(
|
||||
return nil
|
||||
}
|
||||
|
||||
func sqliteMemoPolicySpaceState(ctx context.Context, executor dbExecutor, spaceID, actorUserID int32) (bool, bool, error) {
|
||||
var exists bool
|
||||
if err := executor.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM space WHERE id = ?)", spaceID).Scan(&exists); err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
if !exists {
|
||||
return false, false, nil
|
||||
// sqliteMemoPolicySpaceState reports whether the Space exists and whether the
|
||||
// actor is an active member. Membership is not consulted for an instance
|
||||
// administrator, so it is not queried.
|
||||
func sqliteMemoPolicySpaceState(ctx context.Context, executor dbExecutor, spaceID, actorUserID int32, actor store.MemoActorState) (bool, bool, error) {
|
||||
exists, err := sqliteSpaceExists(ctx, executor, spaceID)
|
||||
if err != nil || !exists || actor.Admin {
|
||||
return exists, false, err
|
||||
}
|
||||
member, err := sqliteSpaceMemberActive(ctx, executor, spaceID, actorUserID)
|
||||
return true, member, err
|
||||
}
|
||||
|
||||
func sqliteSpaceExists(ctx context.Context, executor dbExecutor, spaceID int32) (bool, error) {
|
||||
var exists bool
|
||||
if err := executor.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM space WHERE id = ?)", spaceID).Scan(&exists); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
@@ -22,11 +22,9 @@ func validateSQLiteMemoRelationEndpoints(ctx context.Context, executor dbExecuto
|
||||
return nil
|
||||
}
|
||||
|
||||
var actorStatus store.RowStatus
|
||||
if err := executor.QueryRowContext(ctx, "SELECT row_status FROM user WHERE id = ?", mutation.MemoCreatorID).Scan(&actorStatus); err != nil {
|
||||
if stderrors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrMemoPermissionDenied
|
||||
}
|
||||
actorUserID := mutation.ActorUserID()
|
||||
actor, err := readSQLiteMemoActor(ctx, executor, actorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -40,8 +38,8 @@ func validateSQLiteMemoRelationEndpoints(ctx context.Context, executor dbExecuto
|
||||
return err
|
||||
}
|
||||
snapshot := &store.MemoRelationEndpointSnapshot{
|
||||
ActorUserID: mutation.MemoCreatorID,
|
||||
ActorActive: actorStatus == store.Normal,
|
||||
ActorUserID: actorUserID,
|
||||
Actor: actor,
|
||||
EndpointID: state.id,
|
||||
EndpointCreatorID: state.creatorID,
|
||||
EndpointRowStatus: state.rowStatus,
|
||||
@@ -52,8 +50,8 @@ func validateSQLiteMemoRelationEndpoints(ctx context.Context, executor dbExecuto
|
||||
if err := executor.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM space WHERE id = ?)", *state.spaceID).Scan(&snapshot.EndpointSpaceExists); err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshot.EndpointSpaceExists {
|
||||
active, err := sqliteSpaceMemberActive(ctx, executor, *state.spaceID, mutation.MemoCreatorID)
|
||||
if snapshot.EndpointSpaceExists && !actor.Admin {
|
||||
active, err := sqliteSpaceMemberActive(ctx, executor, *state.spaceID, actorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func (d *DB) CreateMemoShare(ctx context.Context, create *store.MemoShare) (*sto
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateSQLiteMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
if _, err := validateSQLiteMemoWritePolicy(ctx, tx, create.MemoID, create.Policy, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := createSQLiteMemoShare(ctx, tx, create)
|
||||
@@ -164,7 +164,7 @@ func (d *DB) DeleteMemoShare(ctx context.Context, delete *store.DeleteMemoShare)
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := validateSQLiteMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
if _, err := validateSQLiteMemoWritePolicy(ctx, tx, *delete.MemoID, delete.Policy, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
where, args := sqliteMemoShareDeleteWhere(delete)
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestValidateSQLiteMemoCreatePreservesQueryErrors(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, db.Close()) })
|
||||
_, err = db.Exec(`
|
||||
CREATE TABLE user (id INTEGER PRIMARY KEY, row_status TEXT NOT NULL);
|
||||
CREATE TABLE user (id INTEGER PRIMARY KEY, row_status TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'USER');
|
||||
CREATE TABLE space (id INTEGER PRIMARY KEY);
|
||||
CREATE TABLE space_member (space_id INTEGER, user_id INTEGER, status TEXT, role TEXT);
|
||||
INSERT INTO user (id, row_status) VALUES (1, 'NORMAL'), (2, 'ARCHIVED');
|
||||
|
||||
@@ -153,14 +153,17 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
return errors.Wrap(err, "failed to begin authorized reaction delete transaction")
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
actorIsAdmin := false
|
||||
if delete.Policy != nil {
|
||||
if err := validateSQLiteReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
participation, err := validateSQLiteReactionDeletePolicy(ctx, tx, &store.Reaction{
|
||||
CreatorID: *delete.ActorUserID,
|
||||
MemoID: *delete.MemoID,
|
||||
Policy: delete.Policy,
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actorIsAdmin = participation.Actor.Admin
|
||||
}
|
||||
|
||||
var creatorID, memoID int32
|
||||
@@ -170,7 +173,8 @@ func (d *DB) deleteReactionAsCreator(ctx context.Context, delete *store.DeleteRe
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction for deletion")
|
||||
}
|
||||
if creatorID != *delete.ActorUserID || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
// An instance administrator may withdraw any reaction on the named memo.
|
||||
if (creatorID != *delete.ActorUserID && !actorIsAdmin) || (delete.MemoID != nil && memoID != *delete.MemoID) {
|
||||
return store.ErrReactionPermissionDenied
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM reaction WHERE id = ?", *delete.ID); err != nil {
|
||||
|
||||
@@ -21,16 +21,21 @@ func validateSQLiteReactionWritePolicy(ctx context.Context, tx dbExecutor, react
|
||||
return store.ValidateReactionWriteParticipation(reaction, participation)
|
||||
}
|
||||
|
||||
func validateSQLiteReactionDeletePolicy(ctx context.Context, tx dbExecutor, reaction *store.Reaction) error {
|
||||
// validateSQLiteReactionDeletePolicy authorizes a withdrawal and returns the
|
||||
// participation snapshot so the caller can honour an administrator actor.
|
||||
func validateSQLiteReactionDeletePolicy(ctx context.Context, tx dbExecutor, reaction *store.Reaction) (*store.MemoCommentAuthorizationSnapshot, error) {
|
||||
policy := reaction.Policy
|
||||
participation, err := loadSQLiteMemoParticipation(ctx, tx, reaction.MemoID, policy.ActorUserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return store.ErrReactionMemoNotFound
|
||||
return nil, store.ErrReactionMemoNotFound
|
||||
}
|
||||
return errors.Wrap(err, "failed to read reaction participation")
|
||||
return nil, errors.Wrap(err, "failed to read reaction participation")
|
||||
}
|
||||
return store.ValidateReactionWithdrawal(reaction, participation)
|
||||
if err := store.ValidateReactionWithdrawal(reaction, participation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return participation, nil
|
||||
}
|
||||
|
||||
func sqliteSpaceMemberActive(ctx context.Context, tx dbExecutor, spaceID, userID int32) (bool, error) {
|
||||
|
||||
+25
-3
@@ -137,9 +137,28 @@ type MemoWritePolicy struct {
|
||||
CreatingShare bool
|
||||
}
|
||||
|
||||
// MemoActorState is the actor's user row state as read inside a mutation
|
||||
// transaction. Admin marks an active instance administrator; see
|
||||
// access.IsInstanceAdmin for what that grants. A missing user is the zero
|
||||
// value.
|
||||
type MemoActorState struct {
|
||||
Active bool
|
||||
Admin bool
|
||||
}
|
||||
|
||||
// NewMemoActorState derives the actor state from a user row. An archived
|
||||
// administrator is neither active nor privileged.
|
||||
func NewMemoActorState(rowStatus RowStatus, role Role) MemoActorState {
|
||||
active := rowStatus == Normal
|
||||
return MemoActorState{Active: active, Admin: active && role == RoleAdmin}
|
||||
}
|
||||
|
||||
// MemoWriteSnapshot is the current database state used to validate a
|
||||
// MemoWritePolicy. Driver packages populate it in the mutation transaction.
|
||||
type MemoWriteSnapshot struct {
|
||||
// ActorIsAdmin is true when the policy actor is an active instance
|
||||
// administrator. It bypasses authorship and membership checks only.
|
||||
ActorIsAdmin bool
|
||||
CreatorID int32
|
||||
RowStatus RowStatus
|
||||
SpaceID *int32
|
||||
@@ -264,7 +283,10 @@ func ValidateMemoWriteSnapshot(policy *MemoWritePolicy, update *UpdateMemo, snap
|
||||
if policy == nil || snapshot == nil {
|
||||
return errors.New("memo write policy snapshot is required")
|
||||
}
|
||||
if snapshot.CreatorID != policy.ActorUserID {
|
||||
// An instance administrator is the superuser for named memo operations and
|
||||
// is not held to authorship or Space membership. Structural validity below
|
||||
// still applies to every actor.
|
||||
if !snapshot.ActorIsAdmin && snapshot.CreatorID != policy.ActorUserID {
|
||||
return ErrMemoPermissionDenied
|
||||
}
|
||||
if snapshot.RowStatus != Normal && snapshot.RowStatus != Archived {
|
||||
@@ -286,7 +308,7 @@ func ValidateMemoWriteSnapshot(policy *MemoWritePolicy, update *UpdateMemo, snap
|
||||
if !snapshot.SourceSpaceExists {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
if !policy.LifecycleOnly && !snapshot.SourceMemberActive {
|
||||
if !policy.LifecycleOnly && !snapshot.ActorIsAdmin && !snapshot.SourceMemberActive {
|
||||
return ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
}
|
||||
@@ -298,7 +320,7 @@ func ValidateMemoWriteSnapshot(policy *MemoWritePolicy, update *UpdateMemo, snap
|
||||
if !snapshot.TargetSpaceExists {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
if !snapshot.TargetMemberActive {
|
||||
if !snapshot.ActorIsAdmin && !snapshot.TargetMemberActive {
|
||||
return ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
resultSpaceID = update.SpaceID
|
||||
|
||||
@@ -13,7 +13,8 @@ var ErrMemoMutationConflict = errors.New("memo state changed")
|
||||
// MemoAttachmentBinding describes one attachment that should be bound to a
|
||||
// memo. WasBoundToMemo distinguishes an existing binding from a new one so the
|
||||
// driver can reject ownership transfers while preserving legacy rows already
|
||||
// attached to the memo.
|
||||
// attached to the memo. A new binding must be owned by the memo author, or by
|
||||
// the acting instance administrator.
|
||||
type MemoAttachmentBinding struct {
|
||||
ID int32
|
||||
UID string
|
||||
@@ -42,6 +43,48 @@ type MemoMutation struct {
|
||||
Policy *MemoWritePolicy
|
||||
}
|
||||
|
||||
// MemoAttachmentBindingOwnerAllowed reports whether an unbound attachment may
|
||||
// be bound to a memo: it must be owned by the memo author, or by the acting
|
||||
// instance administrator. Ownership is never transferred between accounts.
|
||||
func MemoAttachmentBindingOwnerAllowed(attachmentCreatorID, memoCreatorID, actorUserID int32, actorIsAdmin bool) bool {
|
||||
if attachmentCreatorID == memoCreatorID {
|
||||
return true
|
||||
}
|
||||
return actorIsAdmin && attachmentCreatorID == actorUserID
|
||||
}
|
||||
|
||||
// MemoAttachmentRemovalAllowed reports whether an attachment may be removed
|
||||
// from a memo. Removal deletes the attachment, so it must be bound to that
|
||||
// memo and owned by the actor unless the actor is an instance administrator.
|
||||
func MemoAttachmentRemovalAllowed(attachment *Attachment, memoID, actorUserID int32, actorIsAdmin bool) bool {
|
||||
if attachment == nil || attachment.MemoID == nil || *attachment.MemoID != memoID {
|
||||
return false
|
||||
}
|
||||
return actorIsAdmin || attachment.CreatorID == actorUserID
|
||||
}
|
||||
|
||||
// WritePolicy returns the transport-facing policy governing the mutation, if
|
||||
// any: the mutation's own policy, else the one carried by its memo update.
|
||||
func (m *MemoMutation) WritePolicy() *MemoWritePolicy {
|
||||
if m.Policy != nil {
|
||||
return m.Policy
|
||||
}
|
||||
if m.MemoUpdate != nil {
|
||||
return m.MemoUpdate.Policy
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActorUserID returns the user performing the mutation. Transport-facing
|
||||
// updates carry the actor in their policy, which may differ from the memo
|
||||
// author when an instance administrator acts; creations act as the author.
|
||||
func (m *MemoMutation) ActorUserID() int32 {
|
||||
if policy := m.WritePolicy(); policy != nil {
|
||||
return policy.ActorUserID
|
||||
}
|
||||
return m.MemoCreatorID
|
||||
}
|
||||
|
||||
// ApplyMemoMutation atomically applies memo fields, attachment bindings, and
|
||||
// reference relations after rechecking the state used by API validation.
|
||||
func (s *Store) ApplyMemoMutation(ctx context.Context, mutation *MemoMutation) error {
|
||||
|
||||
+16
-15
@@ -4,7 +4,7 @@ package store
|
||||
// driver before it creates an immutable COMMENT relation.
|
||||
type MemoCommentAuthorizationSnapshot struct {
|
||||
ActorUserID int32
|
||||
ActorActive bool
|
||||
Actor MemoActorState
|
||||
|
||||
ContextID int32
|
||||
ContextCreatorID int32
|
||||
@@ -20,25 +20,26 @@ type MemoCommentAuthorizationSnapshot struct {
|
||||
// memo. The replying memo is authorized independently by the normal memo-create
|
||||
// policy; no placement or audience is inherited from this snapshot.
|
||||
func ValidateMemoCommentAuthorization(snapshot *MemoCommentAuthorizationSnapshot) error {
|
||||
if snapshot == nil || snapshot.ActorUserID <= 0 || !snapshot.ActorActive {
|
||||
if snapshot == nil || snapshot.ActorUserID <= 0 || !snapshot.Actor.Active {
|
||||
return ErrMemoPermissionDenied
|
||||
}
|
||||
if snapshot.ContextID <= 0 || snapshot.ContextRowStatus != Normal || !isValidVisibility(snapshot.ContextVisibility) {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
if snapshot.ContextSpaceID == nil {
|
||||
if snapshot.ContextVisibility == SpaceAudience {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
} else {
|
||||
if !snapshot.ContextSpaceExists {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
// Participation in an assigned memo is narrower than reading it: active
|
||||
// membership is required even for PUBLIC and PROTECTED audiences.
|
||||
if !snapshot.ContextMemberActive {
|
||||
return ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
if snapshot.ContextSpaceID == nil && snapshot.ContextVisibility == SpaceAudience {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
if snapshot.ContextSpaceID != nil && !snapshot.ContextSpaceExists {
|
||||
return ErrMemoSpaceNotWritable
|
||||
}
|
||||
// An instance administrator participates in any structurally valid memo.
|
||||
if snapshot.Actor.Admin {
|
||||
return nil
|
||||
}
|
||||
// Participation in an assigned memo is narrower than reading it: active
|
||||
// membership is required even for PUBLIC and PROTECTED audiences.
|
||||
if snapshot.ContextSpaceID != nil && !snapshot.ContextMemberActive {
|
||||
return ErrMemoSpaceMembershipRequired
|
||||
}
|
||||
|
||||
switch snapshot.ContextVisibility {
|
||||
|
||||
@@ -6,8 +6,9 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// DeleteMemoWithPolicy identifies one author-owned memo to delete atomically.
|
||||
// Relations do not confer lifecycle authority, so no related memo is deleted.
|
||||
// DeleteMemoWithPolicy identifies one memo to delete atomically on behalf of
|
||||
// its author or an instance administrator. Relations do not confer lifecycle
|
||||
// authority, so no related memo is deleted.
|
||||
type DeleteMemoWithPolicy struct {
|
||||
MemoID int32
|
||||
ActorUserID int32
|
||||
@@ -21,9 +22,10 @@ type DeleteMemoWithPolicyResult struct {
|
||||
}
|
||||
|
||||
// MemoDeleteActorCanRead applies the memo-local audience matrix after the
|
||||
// deletion transaction has established that the actor is the active author.
|
||||
// Invalid lifecycle or audience state fails closed. Placement validity matters
|
||||
// only for the Space audience; it is not an extra read gate for other values.
|
||||
// deletion transaction has established that the actor is the active author or
|
||||
// an instance administrator, who counts as a member everywhere. Invalid
|
||||
// lifecycle or audience state fails closed. Placement validity matters only
|
||||
// for the Space audience; it is not an extra read gate for other values.
|
||||
func MemoDeleteActorCanRead(rowStatus RowStatus, visibility Visibility, spaceID *int32, spaceExists, actorMember bool) bool {
|
||||
if rowStatus != Normal && rowStatus != Archived {
|
||||
return false
|
||||
|
||||
+10
-7
@@ -24,7 +24,7 @@ type MemoRelation struct {
|
||||
// authorize one endpoint during a reference-relation mutation.
|
||||
type MemoRelationEndpointSnapshot struct {
|
||||
ActorUserID int32
|
||||
ActorActive bool
|
||||
Actor MemoActorState
|
||||
|
||||
EndpointID int32
|
||||
EndpointCreatorID int32
|
||||
@@ -37,10 +37,10 @@ type MemoRelationEndpointSnapshot struct {
|
||||
}
|
||||
|
||||
// ValidateMemoRelationEndpointRead applies authenticated memo-local read
|
||||
// policy to an endpoint. Application roles are deliberately absent: an
|
||||
// instance administrator has no relation-specific read bypass.
|
||||
// policy to an endpoint. An active instance administrator passes the audience
|
||||
// checks; structural validity still applies.
|
||||
func ValidateMemoRelationEndpointRead(snapshot *MemoRelationEndpointSnapshot) error {
|
||||
if snapshot == nil || !snapshot.ActorActive {
|
||||
if snapshot == nil || !snapshot.Actor.Active {
|
||||
return ErrMemoPermissionDenied
|
||||
}
|
||||
if snapshot.EndpointID <= 0 {
|
||||
@@ -49,9 +49,6 @@ func ValidateMemoRelationEndpointRead(snapshot *MemoRelationEndpointSnapshot) er
|
||||
if snapshot.EndpointRowStatus != Normal && snapshot.EndpointRowStatus != Archived {
|
||||
return ErrMemoMutationConflict
|
||||
}
|
||||
if snapshot.EndpointRowStatus == Archived && snapshot.EndpointCreatorID != snapshot.ActorUserID {
|
||||
return ErrMemoPermissionDenied
|
||||
}
|
||||
if !isValidVisibility(snapshot.EndpointVisibility) {
|
||||
return ErrMemoMutationConflict
|
||||
}
|
||||
@@ -59,6 +56,12 @@ func ValidateMemoRelationEndpointRead(snapshot *MemoRelationEndpointSnapshot) er
|
||||
(snapshot.EndpointSpaceID == nil || !snapshot.EndpointSpaceExists) {
|
||||
return ErrMemoMutationConflict
|
||||
}
|
||||
if snapshot.Actor.Admin {
|
||||
return nil
|
||||
}
|
||||
if snapshot.EndpointRowStatus == Archived && snapshot.EndpointCreatorID != snapshot.ActorUserID {
|
||||
return ErrMemoPermissionDenied
|
||||
}
|
||||
|
||||
switch snapshot.EndpointVisibility {
|
||||
case Public, Protected:
|
||||
|
||||
@@ -14,7 +14,7 @@ func TestValidateMemoRelationEndpointReadDanglingPlacement(t *testing.T) {
|
||||
t.Run(string(visibility), func(t *testing.T) {
|
||||
err := store.ValidateMemoRelationEndpointRead(&store.MemoRelationEndpointSnapshot{
|
||||
ActorUserID: 1,
|
||||
ActorActive: true,
|
||||
Actor: store.MemoActorState{Active: true},
|
||||
EndpointID: 2,
|
||||
EndpointCreatorID: 1,
|
||||
EndpointRowStatus: store.Normal,
|
||||
@@ -29,7 +29,7 @@ func TestValidateMemoRelationEndpointReadDanglingPlacement(t *testing.T) {
|
||||
|
||||
err := store.ValidateMemoRelationEndpointRead(&store.MemoRelationEndpointSnapshot{
|
||||
ActorUserID: 1,
|
||||
ActorActive: true,
|
||||
Actor: store.MemoActorState{Active: true},
|
||||
EndpointID: 2,
|
||||
EndpointCreatorID: 2,
|
||||
EndpointRowStatus: store.Normal,
|
||||
|
||||
@@ -44,7 +44,7 @@ func ValidateReactionWithdrawal(reaction *Reaction, snapshot *MemoCommentAuthori
|
||||
if snapshot.ActorUserID != reaction.Policy.ActorUserID {
|
||||
return ErrReactionPermissionDenied
|
||||
}
|
||||
if !snapshot.ActorActive {
|
||||
if !snapshot.Actor.Active {
|
||||
return ErrReactionPermissionDenied
|
||||
}
|
||||
if snapshot.ContextID != reaction.MemoID {
|
||||
|
||||
@@ -18,9 +18,9 @@ func TestMemoRelationMutationRevalidatesRelatedMemo(t *testing.T) {
|
||||
|
||||
spaceOwner, err := ts.CreateUser(ctx, &store.User{Username: "relation-space-owner", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
// An application ADMIN deliberately acts as the source author. The instance
|
||||
// role must not bypass the related memo's current Space audience.
|
||||
actor, err := ts.CreateUser(ctx, &store.User{Username: "relation-app-admin", Role: store.RoleAdmin, PasswordHash: "hash"})
|
||||
// A regular user acts as the source author, so the related memo's current
|
||||
// Space audience is revalidated on every mutation.
|
||||
actor, err := ts.CreateUser(ctx, &store.User{Username: "relation-space-user", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
space, err := ts.CreateSpace(ctx, &store.Space{UID: shortuuid.New(), Title: "Relations"}, spaceOwner.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -70,7 +70,9 @@ func TestReactionWritePolicySpaceParticipationIsMemoLocal(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
member, err := ts.CreateUser(ctx, &store.User{Username: "reaction-space-member", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
outsider, err := ts.CreateUser(ctx, &store.User{Username: "reaction-space-outsider", Role: store.RoleAdmin, PasswordHash: "hash"})
|
||||
outsider, err := ts.CreateUser(ctx, &store.User{Username: "reaction-space-outsider", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
applicationAdmin, err := ts.CreateUser(ctx, &store.User{Username: "reaction-space-app-admin", Role: store.RoleAdmin, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
|
||||
space, err := ts.CreateSpace(ctx, &store.Space{UID: "reaction-space", Title: "Reaction Space"}, owner.ID)
|
||||
@@ -87,9 +89,13 @@ func TestReactionWritePolicySpaceParticipationIsMemoLocal(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = ts.UpsertReaction(ctx, &store.Reaction{
|
||||
CreatorID: outsider.ID, MemoID: spaceMemo.ID, ReactionType: "application-admin", Policy: reactionWritePolicy(outsider.ID),
|
||||
CreatorID: outsider.ID, MemoID: spaceMemo.ID, ReactionType: "outsider", Policy: reactionWritePolicy(outsider.ID),
|
||||
})
|
||||
require.ErrorIs(t, err, store.ErrMemoSpaceMembershipRequired, "application ADMIN must not bypass Space membership")
|
||||
require.ErrorIs(t, err, store.ErrMemoSpaceMembershipRequired, "a non-member must not participate")
|
||||
_, err = ts.UpsertReaction(ctx, &store.Reaction{
|
||||
CreatorID: applicationAdmin.ID, MemoID: spaceMemo.ID, ReactionType: "application-admin", Policy: reactionWritePolicy(applicationAdmin.ID),
|
||||
})
|
||||
require.NoError(t, err, "an instance administrator participates without membership")
|
||||
|
||||
require.NoError(t, ts.DeleteSpaceMember(ctx, &store.DeleteSpaceMember{SpaceID: space.ID, UserID: member.ID}, owner.ID))
|
||||
_, err = ts.UpsertReaction(ctx, &store.Reaction{
|
||||
|
||||
@@ -264,7 +264,7 @@ func TestSpaceMemoAccessDoesNotFlowAcrossCommentRelation(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
member, err := ts.CreateUser(ctx, &store.User{Username: "memo-space-member", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
outsider, err := ts.CreateUser(ctx, &store.User{Username: "memo-space-outsider", Role: store.RoleAdmin, PasswordHash: "hash"})
|
||||
outsider, err := ts.CreateUser(ctx, &store.User{Username: "memo-space-outsider", Role: store.RoleUser, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
|
||||
space, err := ts.CreateSpace(ctx, &store.Space{UID: "memo-space", Title: "Memo Space"}, owner.ID)
|
||||
@@ -280,6 +280,17 @@ func TestSpaceMemoAccessDoesNotFlowAcrossCommentRelation(t *testing.T) {
|
||||
UID: "outsider-assigned", CreatorID: outsider.ID, Content: "no", Visibility: store.Public, SpaceID: &space.ID,
|
||||
})
|
||||
require.ErrorIs(t, err, store.ErrMemoSpaceMembershipRequired)
|
||||
applicationAdmin, err := ts.CreateUser(ctx, &store.User{Username: "memo-space-app-admin", Role: store.RoleAdmin, PasswordHash: "hash"})
|
||||
require.NoError(t, err)
|
||||
_, err = ts.CreateMemo(ctx, &store.Memo{
|
||||
UID: "admin-assigned", CreatorID: applicationAdmin.ID, Content: "superuser", Visibility: store.Private, SpaceID: &space.ID,
|
||||
})
|
||||
require.NoError(t, err, "an instance administrator places memos without membership")
|
||||
missingSpaceID := space.ID + 1000
|
||||
_, err = ts.CreateMemo(ctx, &store.Memo{
|
||||
UID: "admin-dangling", CreatorID: applicationAdmin.ID, Content: "no", Visibility: store.Public, SpaceID: &missingSpaceID,
|
||||
})
|
||||
require.ErrorIs(t, err, store.ErrMemoSpaceNotWritable, "structural validity still applies to an administrator")
|
||||
|
||||
comment, err := ts.CreateMemoComment(ctx, &store.Memo{
|
||||
UID: "space-public-comment", CreatorID: owner.ID, Content: "public comment", Visibility: store.Public,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { extractSpaceUidFromName, getDuplicateSpaceTitles } from "@/lib/space-di
|
||||
import { type Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { getAssignableVisibilityOptions, getVisibilityOption } from "@/utils/memo";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
|
||||
const UNASSIGNED = "unassigned";
|
||||
|
||||
@@ -35,7 +36,7 @@ export default function MemoMoveDialog({ memo, onOpenChange }: { memo: Memo; onO
|
||||
: t("memo.move.unassigned");
|
||||
const visibilityOption = getVisibilityOption(visibility);
|
||||
const canSubmit =
|
||||
currentUser?.name === memo.creator && (memo.space || undefined) !== nextSpace && (!nextSpace || !!selectedSpace) && !isPending;
|
||||
canManageMemo(memo, currentUser) && (memo.space || undefined) !== nextSpace && (!nextSpace || !!selectedSpace) && !isPending;
|
||||
|
||||
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -14,6 +14,7 @@ import { State } from "@/types/proto/api/v1/common_pb";
|
||||
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { checkAllTasks, uncheckAllTasks } from "@/utils/markdown-task-actions";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
import { isMemoDetailPath } from "../MemoView/navigation";
|
||||
|
||||
interface UseMemoActionHandlersOptions {
|
||||
@@ -27,7 +28,7 @@ export const useMemoActionHandlers = ({ memo, parentPage, onEdit, setDeleteDialo
|
||||
const t = useTranslate();
|
||||
const location = useLocation();
|
||||
const currentUser = useCurrentUser();
|
||||
const canMove = memo.creator === currentUser?.name && !location.pathname.startsWith(ROUTES.SHARED_MEMO);
|
||||
const canMove = canManageMemo(memo, currentUser) && !location.pathname.startsWith(ROUTES.SHARED_MEMO);
|
||||
const navigateTo = useNavigateTo();
|
||||
const queryClient = useQueryClient();
|
||||
const { profile } = useInstance();
|
||||
|
||||
@@ -30,7 +30,7 @@ import { cn } from "@/lib/utils";
|
||||
import { State } from "@/types/proto/api/v1/common_pb";
|
||||
import { Memo, type MemoRelation, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { isSuperUser } from "@/utils/user";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
import MemoOutline from "./MemoOutline";
|
||||
import MemoSharePanel from "./MemoSharePanel";
|
||||
|
||||
@@ -107,13 +107,13 @@ const MemoDetailSidebar = ({
|
||||
const { profile } = useInstance();
|
||||
const [sharePanelOpen, setSharePanelOpen] = useState(false);
|
||||
|
||||
const readonly = forceReadonly || (memo.creator !== currentUser?.name && !isSuperUser(currentUser));
|
||||
const readonly = forceReadonly || !canManageMemo(memo, currentUser);
|
||||
const canEdit = !!onEdit && !readonly && memo.state === State.NORMAL;
|
||||
const canComment = !!onCommentCreate && !forceReadonly && !!currentUser && memo.state === State.NORMAL;
|
||||
const canManageShares =
|
||||
!forceReadonly &&
|
||||
!memo.parent &&
|
||||
memo.creator === currentUser?.name &&
|
||||
canManageMemo(memo, currentUser) &&
|
||||
memo.state === State.NORMAL &&
|
||||
memo.visibility !== Visibility.SPACE;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import { isMemoBlurred } from "@/lib/tag";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { State } from "@/types/proto/api/v1/common_pb";
|
||||
import { lazyWithReload } from "@/utils/lazy";
|
||||
import { isSuperUser } from "@/utils/user";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
import { MemoBody, MemoCommentListView, MemoHeader } from "./components";
|
||||
import { MEMO_CARD_BASE_CLASSES } from "./constants";
|
||||
import { useImagePreview } from "./hooks";
|
||||
@@ -54,7 +54,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
const { userTagsSetting } = useAuth();
|
||||
const creator = useResolvedUser(memoData.creator, { enabled: Boolean(showCreator || props.shareImageDialogOpen) });
|
||||
const isArchived = memoData.state === State.ARCHIVED;
|
||||
const readonly = memoData.creator !== currentUser?.name && !isSuperUser(currentUser);
|
||||
const readonly = !canManageMemo(memoData, currentUser);
|
||||
const location = useLocation();
|
||||
const parentPage = resolveMemoParentPage({
|
||||
explicitParentPage: parentPageProp,
|
||||
|
||||
@@ -1403,7 +1403,7 @@ export const MemoService: GenService<{
|
||||
output: typeof EmptySchema;
|
||||
},
|
||||
/**
|
||||
* CreateMemoShare creates a share link for a memo. Requires authentication as the memo creator.
|
||||
* CreateMemoShare creates a share link for a memo. Requires the memo creator or an instance administrator.
|
||||
*
|
||||
* @generated from rpc memos.api.v1.MemoService.CreateMemoShare
|
||||
*/
|
||||
@@ -1413,7 +1413,7 @@ export const MemoService: GenService<{
|
||||
output: typeof MemoShareSchema;
|
||||
},
|
||||
/**
|
||||
* ListMemoShares lists all share links for a memo. Requires authentication as the memo creator.
|
||||
* ListMemoShares lists all share links for a memo. Requires the memo creator or an instance administrator.
|
||||
*
|
||||
* @generated from rpc memos.api.v1.MemoService.ListMemoShares
|
||||
*/
|
||||
@@ -1423,7 +1423,7 @@ export const MemoService: GenService<{
|
||||
output: typeof ListMemoSharesResponseSchema;
|
||||
},
|
||||
/**
|
||||
* DeleteMemoShare revokes a share link. Requires authentication as the memo creator.
|
||||
* DeleteMemoShare revokes a share link. Requires the memo creator or an instance administrator.
|
||||
*
|
||||
* @generated from rpc memos.api.v1.MemoService.DeleteMemoShare
|
||||
*/
|
||||
|
||||
@@ -3,3 +3,11 @@ import { User, User_Role } from "@/types/proto/api/v1/user_service_pb";
|
||||
export const isSuperUser = (user: User | undefined) => {
|
||||
return user && user.role === User_Role.ADMIN;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the user holds author-level authority over a memo: its creator, or an
|
||||
* instance admin, who is the superuser for named memo operations on the server.
|
||||
*/
|
||||
export const canManageMemo = (memo: { creator: string }, user: User | undefined): boolean => {
|
||||
return !!user && (memo.creator === user.name || !!isSuperUser(user));
|
||||
};
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { User, User_Role } from "@/types/proto/api/v1/user_service_pb";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
|
||||
const user = (name: string, role: User_Role) => ({ name, role }) as User;
|
||||
|
||||
describe("canManageMemo", () => {
|
||||
const memo = { creator: "users/alice" };
|
||||
|
||||
it("allows the creator", () => {
|
||||
expect(canManageMemo(memo, user("users/alice", User_Role.USER))).toBe(true);
|
||||
});
|
||||
|
||||
it("allows an instance admin as superuser", () => {
|
||||
expect(canManageMemo(memo, user("users/root", User_Role.ADMIN))).toBe(true);
|
||||
});
|
||||
|
||||
it("denies other users and anonymous viewers", () => {
|
||||
expect(canManageMemo(memo, user("users/bob", User_Role.USER))).toBe(false);
|
||||
expect(canManageMemo(memo, undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user