// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "fmt" "sort" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" ) // ---- Page permissions ------------------------------------------------------ // // A page's role refines the space role through grants and restricted // subtrees (access.PageRole). Most spaces have neither, so pageRules only // loads the space's page tree when the caller has a grant there or some page // is restricted. type pageGrantRecord struct { ID string `json:"id"` Page string `json:"page"` Space string `json:"space"` PrincipalType string `json:"principal_type"` PrincipalID string `json:"principal_id"` Role string `json:"role"` } // principalFilter matches rows granted to userID or one of their groups. func principalFilter(userID string, groups []string) string { f := fmt.Sprintf("(principal_type = 'user' && principal_id = '%s')", userID) if len(groups) == 0 { return f } ors := make([]string, len(groups)) for i, g := range groups { ors[i] = fmt.Sprintf("principal_id = '%s'", g) } return "(" + f + " || (principal_type = 'group' && (" + strings.Join(ors, " || ") + ")))" } // callerGrants lists the page grants of c and their groups, in one space or // (spaceID "") the whole workspace wsID. func (s *Service) callerGrants(ctx context.Context, c access.Caller, wsID, spaceID string) ([]pageGrantRecord, error) { groups, err := s.userGroups(ctx, c.ID, wsID) if err != nil { return nil, err } filter := principalFilter(c.ID, groups) if spaceID != "" { filter = fmt.Sprintf("space = '%s' && ", spaceID) + filter } else { filter = fmt.Sprintf("space.workspace = '%s' && ", wsID) + filter } return listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{Filter: filter}) } // hasPageGrants reports whether c holds any page grant in space sp. func (s *Service) hasPageGrants(ctx context.Context, c access.Caller, sp spaceRecord) (bool, error) { grants, err := s.callerGrants(ctx, c, sp.Workspace, sp.ID) return len(grants) > 0, err } // grantedSpaces is the set of spaces of workspace wsID where c holds page grants. func (s *Service) grantedSpaces(ctx context.Context, c access.Caller, wsID string) (map[string]bool, error) { grants, err := s.callerGrants(ctx, c, wsID, "") if err != nil { return nil, err } out := make(map[string]bool, len(grants)) for _, g := range grants { out[g.Space] = true } return out, nil } // pageRules resolves one caller's role on the pages of one space. type pageRules struct { spaceRole string restricted map[string]bool grants map[string]string // page → the caller's best grant parent map[string]string // nil when no page needs more than the space role } func (s *Service) rulesFor(ctx context.Context, c access.Caller, a spaceAccess) (pageRules, error) { r := pageRules{spaceRole: a.spaceRole, restricted: map[string]bool{}, grants: map[string]string{}} locked, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{ Filter: fmt.Sprintf("space = '%s' && restricted = true", a.space.ID), Fields: "id", }) if err != nil { return r, err } for _, p := range locked { r.restricted[p.ID] = true } if !access.SpaceAtLeast(a.spaceRole, access.SpaceAdmin) { grants, err := s.callerGrants(ctx, c, a.space.Workspace, a.space.ID) if err != nil { return r, err } for _, g := range grants { r.grants[g.Page] = access.HigherSpaceRole(r.grants[g.Page], g.Role) } } if len(r.restricted) == 0 && len(r.grants) == 0 { return r, nil } all, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{ Filter: fmt.Sprintf("space = '%s'", a.space.ID), Fields: "id,parent", }) if err != nil { return r, err } r.parent = make(map[string]string, len(all)) for _, p := range all { r.parent[p.ID] = p.Parent } return r, nil } // plain reports whether every page simply has the space role. func (r pageRules) plain() bool { return r.parent == nil } func (r pageRules) role(id string) string { if r.plain() { return access.PageRole(r.spaceRole, nil) } var chain []access.PageNode for depth := 0; id != "" && depth < 1000; depth++ { chain = append(chain, access.PageNode{Restricted: r.restricted[id], Grant: r.grants[id]}) id = r.parent[id] } return access.PageRole(r.spaceRole, chain) } // pageAccess loads a page with c's rights on it: a.role is the page role. // A page c cannot open is reported as not found. func (s *Service) pageAccess(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, pageRules, error) { p, err := s.getPage(ctx, id) if err != nil { return p, spaceAccess{}, pageRules{}, err } a, err := s.spaceReach(ctx, c, p.Space) if err != nil { return p, a, pageRules{}, apperr.NotFound("page not found") } rules, err := s.rulesFor(ctx, c, a) if err != nil { return p, a, rules, err } a.role = rules.role(p.ID) if a.role == "" { return p, a, rules, apperr.NotFound("page not found") } return p, a, rules, nil } // spaceRules loads a space c can reach (see spaceReach) with its page rules. func (s *Service) spaceRules(ctx context.Context, c access.Caller, spaceID string) (spaceAccess, pageRules, error) { a, err := s.spaceReach(ctx, c, spaceID) if err != nil { return a, pageRules{}, err } rules, err := s.rulesFor(ctx, c, a) return a, rules, err } // ---- Sharing a page with people and groups --------------------------------- // PageGrant is one person or group with a role on a page. type PageGrant struct { // Type is "user" or "group". Type string `json:"type"` ID string `json:"id"` Name string `json:"name"` Email string `json:"email"` Role string `json:"role"` // Page is where the grant was made: this page, or an ancestor it inherits from. Page PageRef `json:"page"` Inherited bool `json:"inherited"` } // PageInvite is a pending invite that shares this page with a new guest. type PageInvite struct { ID string `json:"id"` Email string `json:"email"` Role string `json:"role"` Expires string `json:"expires"` } // PageAccess is who can reach a page beyond its space's members. type PageAccess struct { // Restricted is true when the page or an ancestor is restricted: the // space's members then see it only through grants. Restricted bool `json:"restricted"` // InheritedFrom is the restricted ancestor when the page is restricted // through it (nil when the page itself is restricted, or nothing is). InheritedFrom *PageRef `json:"inheritedFrom"` Grants []PageGrant `json:"grants"` Invites []PageInvite `json:"invites"` // Role is the caller's role on the page. Role string `json:"role"` CanManage bool `json:"canManage"` // CanInvite is whether the caller may share the page with people // outside the workspace (who join it as guests). CanInvite bool `json:"canInvite"` } // GetPageAccess lists a page's grants, its own and inherited (viewer). func (s *Service) GetPageAccess(ctx context.Context, c access.Caller, id string) (PageAccess, error) { p, a, _, err := s.pageAccess(ctx, c, id) if err != nil { return PageAccess{}, err } out := PageAccess{ Grants: []PageGrant{}, Invites: []PageInvite{}, Role: a.role, CanManage: access.ManagePageAccess(a.role) == nil, CanInvite: access.InvitePageGuest(a.wsRole, a.role) == nil, } // The pages whose grants apply: this one and its ancestors up to the // nearest restriction. chain := []pageRecord{p} for cur, depth := p, 0; !cur.Restricted && cur.Parent != "" && depth < 100; depth++ { if cur, err = s.getPage(ctx, cur.Parent); err != nil { break } chain = append(chain, cur) } if last := chain[len(chain)-1]; last.Restricted { out.Restricted = true if last.ID != p.ID { out.InheritedFrom = &PageRef{ID: last.ID, Title: last.Title, Icon: last.Icon} } } ors := make([]string, len(chain)) refs := make(map[string]PageRef, len(chain)) for i, cp := range chain { ors[i] = fmt.Sprintf("page = '%s'", cp.ID) refs[cp.ID] = PageRef{ID: cp.ID, Title: cp.Title, Icon: cp.Icon} } grants, err := listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{ Filter: strings.Join(ors, " || "), }) if err != nil { return PageAccess{}, err } for _, g := range grants { pg := PageGrant{Type: g.PrincipalType, ID: g.PrincipalID, Role: g.Role, Page: refs[g.Page], Inherited: g.Page != p.ID} if g.PrincipalType == "group" { grp, err := pocketbase.Get[groupRecord](ctx, s.pb, "groups", g.PrincipalID) if err != nil { continue // a deleted group's leftover row } pg.Name = grp.Name } else { u, err := s.getUser(ctx, g.PrincipalID) if err != nil { continue } pg.Name, pg.Email = u.Name, u.Email } out.Grants = append(out.Grants, pg) } sort.SliceStable(out.Grants, func(i, j int) bool { gi, gj := out.Grants[i], out.Grants[j] if gi.Inherited != gj.Inherited { return !gi.Inherited } if gi.Type != gj.Type { return gi.Type == "group" } return strings.ToLower(gi.Name+gi.Email) < strings.ToLower(gj.Name+gj.Email) }) if out.CanManage { invites, err := listAll[inviteRecord](ctx, s, "invites", pocketbase.ListOptions{ Filter: fmt.Sprintf("page = '%s' && accepted = ''", p.ID), Sort: "email", }) if err != nil { return PageAccess{}, err } now := time.Now() for _, inv := range invites { if inv.view(now).Status == "pending" { out.Invites = append(out.Invites, PageInvite{ID: inv.ID, Email: inv.Email, Role: inv.PageRole, Expires: inv.Expires}) } } } return out, nil } // SetPageRestricted turns a page's restriction on or off (editor). Someone // who restricts a page without being a space admin keeps editor on it // through a grant, so they cannot lock themselves out. func (s *Service) SetPageRestricted(ctx context.Context, c access.Caller, id string, on bool) (PageAccess, error) { p, a, _, err := s.pageAccess(ctx, c, id) if err != nil { return PageAccess{}, err } if err := access.ManagePageAccess(a.role); err != nil { return PageAccess{}, err } if p.Restricted == on { return s.GetPageAccess(ctx, c, p.ID) } if on && !access.SpaceAtLeast(a.spaceRole, access.SpaceAdmin) { if err := s.upsertGrant(ctx, p, "user", c.ID, access.SpaceEditor); err != nil { return PageAccess{}, err } } if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"restricted": on}); err != nil { return PageAccess{}, mapPB(err, "page not found") } s.kickSubtree(ctx, p) return s.GetPageAccess(ctx, c, p.ID) } // SharePageResult is a page's access after sharing it, with the invite sent // when the person had no way into the workspace yet. type SharePageResult struct { Access PageAccess `json:"access"` Invite *Invite `json:"invite"` } // SharePageWithUser gives someone (by email) role on a page (editor). A // workspace member gets a grant; someone from the workspace's organization // who is not in the workspace joins it as a guest; anyone else is invited as // a guest, and the grant is made when they accept. func (s *Service) SharePageWithUser(ctx context.Context, c access.Caller, id, email, role string) (SharePageResult, error) { p, a, _, err := s.pageAccess(ctx, c, id) if err != nil { return SharePageResult{}, err } if err := access.ManagePageAccess(a.role); err != nil { return SharePageResult{}, err } if !access.ValidPageGrant(role) { return SharePageResult{}, apperr.Invalid("role must be editor, commenter or viewer") } email = strings.ToLower(strings.TrimSpace(email)) if !strings.Contains(email, "@") || len(email) > 255 { return SharePageResult{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."}) } u, err := s.findUserByEmail(ctx, email) if err != nil && !isNotFound(err) { return SharePageResult{}, err } if err == nil { targetWs, err := s.effective(ctx, u.Caller(), a.ws) if err != nil { return SharePageResult{}, err } if targetWs == "" && u.Organization == a.ws.Organization && u.Role != access.RoleSuperadmin { if err := access.InvitePageGuest(a.wsRole, a.role); err != nil { return SharePageResult{}, err } if _, err := pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{ "workspace": a.ws.ID, "user": u.ID, "role": access.WorkspaceGuest, }); err != nil { return SharePageResult{}, mapPB(err, "workspace not found") } s.forget(u.ID) targetWs = access.WorkspaceGuest } if targetWs != "" { if err := access.SetPageGrant(a.role, targetWs, false, role); err != nil { return SharePageResult{}, err } if err := s.upsertGrant(ctx, p, "user", u.ID, role); err != nil { return SharePageResult{}, err } s.kickSubtree(ctx, p) s.notifyShare(ctx, c, p, u.ID) pa, err := s.GetPageAccess(ctx, c, p.ID) return SharePageResult{Access: pa}, err } // No way into this organization yet: fall through to an invite, // which refuses accounts that belong to another organization. } if err := access.InvitePageGuest(a.wsRole, a.role); err != nil { return SharePageResult{}, err } inv, err := s.CreateInvite(ctx, c, CreateInviteInput{ Email: email, Workspace: a.ws.ID, WorkspaceRole: access.WorkspaceGuest, page: p.ID, pageRole: role, }) if err != nil { return SharePageResult{}, err } pa, err := s.GetPageAccess(ctx, c, p.ID) return SharePageResult{Access: pa, Invite: &inv}, err } // SharePageWithGroup gives a group of the page's workspace role on it (editor). func (s *Service) SharePageWithGroup(ctx context.Context, c access.Caller, id, groupID, role string) (PageAccess, error) { p, a, _, err := s.pageAccess(ctx, c, id) if err != nil { return PageAccess{}, err } if err := access.ViewGroups(a.wsRole); err != nil { return PageAccess{}, err } if err := access.SetPageGrant(a.role, "", true, role); err != nil { return PageAccess{}, err } if !validID(groupID) { return PageAccess{}, apperr.NotFound("group not found") } g, err := pocketbase.Get[groupRecord](ctx, s.pb, "groups", groupID) if err != nil || g.Workspace != p.Workspace { return PageAccess{}, apperr.NotFound("group not found") } if err := s.upsertGrant(ctx, p, "group", g.ID, role); err != nil { return PageAccess{}, err } s.kickSubtree(ctx, p) return s.GetPageAccess(ctx, c, p.ID) } // UnsharePage removes a user's or group's grant on a page (idempotent). // Anyone may drop their own grant; removing others needs editor. func (s *Service) UnsharePage(ctx context.Context, c access.Caller, id, principalType, principalID string) (PageAccess, error) { p, a, _, err := s.pageAccess(ctx, c, id) if err != nil { return PageAccess{}, err } if principalType != "user" || principalID != c.ID { if err := access.ManagePageAccess(a.role); err != nil { return PageAccess{}, err } } if !validID(principalID) { return PageAccess{}, apperr.NotFound("grant not found") } cur, err := s.grantOf(ctx, p.ID, principalType, principalID) if err != nil { return PageAccess{}, err } if cur.ID != "" { if err := s.pb.Delete(ctx, "page_permissions", cur.ID); err != nil && !pocketbase.IsNotFound(err) { return PageAccess{}, err } s.kickSubtree(ctx, p) } pa, err := s.GetPageAccess(ctx, c, p.ID) if e, ok := apperr.As(err); ok && e.Kind == apperr.KindNotFound { // They removed their own last way in. return PageAccess{Grants: []PageGrant{}, Invites: []PageInvite{}}, nil } return pa, err } func (s *Service) grantOf(ctx context.Context, pageID, principalType, principalID string) (pageGrantRecord, error) { res, err := pocketbase.List[pageGrantRecord](ctx, s.pb, "page_permissions", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("page = '%s' && principal_type = '%s' && principal_id = '%s'", pageID, filterValue(principalType), principalID), }) if err != nil || len(res.Items) == 0 { return pageGrantRecord{}, err } return res.Items[0], nil } func (s *Service) upsertGrant(ctx context.Context, p pageRecord, principalType, principalID, role string) error { cur, err := s.grantOf(ctx, p.ID, principalType, principalID) if err != nil { return err } if cur.ID != "" { if cur.Role == role { return nil } _, err = pocketbase.Update[pageGrantRecord](ctx, s.pb, "page_permissions", cur.ID, map[string]any{"role": role}) } else { _, err = pocketbase.Create[pageGrantRecord](ctx, s.pb, "page_permissions", map[string]any{ "page": p.ID, "space": p.Space, "principal_type": principalType, "principal_id": principalID, "role": role, }) } return mapPB(err, "page not found") } // kickSubtree reconnects the editors of a page and every page under it, so // they pick up changed rights. func (s *Service) kickSubtree(ctx context.Context, p pageRecord) { t, err := s.loadTree(ctx, p.Space) if err != nil { s.docs.Kick(p.ID) return } for id := range t.byID { if t.within(id, p.ID) { s.docs.Kick(id) } } } // dropPageGrants deletes grants (best effort): a user's in one workspace // ("" = all), or a group's. func (s *Service) dropPageGrants(ctx context.Context, principalType, principalID, wsID string) { filter := fmt.Sprintf("principal_type = '%s' && principal_id = '%s'", principalType, principalID) if wsID != "" { filter += fmt.Sprintf(" && space.workspace = '%s'", wsID) } grants, err := listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{Filter: filter}) if err != nil { return } for _, g := range grants { _ = s.pb.Delete(ctx, "page_permissions", g.ID) } }