diff --git a/Database/pb_migrations/1762800000_page_permissions.js b/Database/pb_migrations/1762800000_page_permissions.js new file mode 100644 index 0000000..3daa82d --- /dev/null +++ b/Database/pb_migrations/1762800000_page_permissions.js @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Page-level permissions. A grant gives a user or group a role on a page and +// its subtree (on top of their space role); pages.restricted makes a subtree +// ignore the space role, so only its own grants count (see +// Server/internal/access/pages.go). space is copied from the page so one +// query finds a caller's grants in a space. Invites can carry a page grant: +// sharing a page with someone outside the workspace invites them as a guest. + +migrate( + (app) => { + const pages = app.findCollectionByNameOrId("pages"); + const spaces = app.findCollectionByNameOrId("spaces"); + pages.fields.add(new BoolField({ name: "restricted" })); + app.save(pages); + + app.save( + new Collection({ + type: "base", + name: "page_permissions", + fields: [ + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "space", type: "relation", collectionId: spaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "principal_type", type: "select", values: ["user", "group"], maxSelect: 1, required: true }, + { name: "principal_id", type: "text", required: true }, + { name: "role", type: "select", values: ["editor", "commenter", "viewer"], maxSelect: 1, required: true }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_pp_unique ON page_permissions (page, principal_type, principal_id)", + "CREATE INDEX idx_pp_space ON page_permissions (space, principal_type, principal_id)", + ], + }), + ); + + const invites = app.findCollectionByNameOrId("invites"); + invites.fields.add(new RelationField({ name: "page", collectionId: pages.id, maxSelect: 1, cascadeDelete: true })); + invites.fields.add(new SelectField({ name: "page_role", values: ["editor", "commenter", "viewer"], maxSelect: 1 })); + app.save(invites); + }, + (app) => { + const invites = app.findCollectionByNameOrId("invites"); + invites.fields.removeByName("page_role"); + invites.fields.removeByName("page"); + app.save(invites); + try { + app.delete(app.findCollectionByNameOrId("page_permissions")); + } catch (_) {} + const pages = app.findCollectionByNameOrId("pages"); + pages.fields.removeByName("restricted"); + app.save(pages); + }, +); diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index b055f2f..2cbdaca 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -44,6 +44,11 @@ export type AdminHealth = Schemas["AdminHealth"]; export type Job = Schemas["Job"]; export type Backup = Schemas["Backup"]; export type SharedPage = Schemas["SharedPage"]; +export type PageGrantRole = Schemas["PageGrantRole"]; +export type PageGrant = Schemas["PageGrant"]; +export type PageInvite = Schemas["PageInvite"]; +export type PageAccess = Schemas["PageAccess"]; +export type SharePageResult = Schemas["SharePageResult"]; export type SearchResult = Schemas["SearchResult"]; export type GroupRequest = Schemas["GroupRequest"]; export type SpaceGroup = Schemas["SpaceGroup"]; @@ -339,6 +344,29 @@ export function createClient(opts: ClientOptions) { setShareLink: (id: string, includeSubpages: boolean) => request("PUT", `/api/v1/pages/${encodeURIComponent(id)}/share`, { includeSubpages }), deleteShareLink: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/share`), + /** Who has access beyond the space's members: grants and the restricted switch. */ + access: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/access`), + setRestricted: (id: string, restricted: boolean) => + request("PATCH", `/api/v1/pages/${encodeURIComponent(id)}/access`, { restricted }), + /** Shares with someone by email; people outside the workspace are invited as guests. */ + shareWithUser: (id: string, email: string, role: PageGrantRole) => + request("PUT", `/api/v1/pages/${encodeURIComponent(id)}/access/users`, { email, role }), + unshareUser: (id: string, userId: string) => + request( + "DELETE", + `/api/v1/pages/${encodeURIComponent(id)}/access/users/${encodeURIComponent(userId)}`, + ), + shareWithGroup: (id: string, groupId: string, role: PageGrantRole) => + request( + "PUT", + `/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`, + { role }, + ), + unshareGroup: (id: string, groupId: string) => + request( + "DELETE", + `/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`, + ), export: (id: string, format: "markdown" | "html") => download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`), /** Records that the user opened the page, for their recent list. */ diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index ae6d189..3e10ecd 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -1190,6 +1190,92 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/pages/{id}/access": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Who has access to the page beyond the space's members (viewer) */ + get: operations["getPageAccess"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + /** + * Restrict the page and its subpages to the people it is shared with, or lift that (editor) + * @description Space admins always keep access. An editor who restricts a page keeps editor on it through a grant. + */ + patch: operations["setPageRestricted"]; + trace?: never; + }; + "/api/v1/pages/{id}/access/users": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + /** + * Share the page and its subpages with someone by email (editor) + * @description A workspace member gets the role on the page. Someone from the workspace's organization who is not in the workspace joins it as a guest. Anyone else is invited as a guest (workspace members only). + */ + put: operations["sharePageWithUser"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/access/users/{userId}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + userId: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Remove someone's grant on the page (editor, or the person themselves) */ + delete: operations["unsharePageWithUser"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/access/groups/{groupId}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + groupId: string; + }; + cookie?: never; + }; + get?: never; + /** Share the page and its subpages with a group of the workspace (editor) */ + put: operations["sharePageWithGroup"]; + post?: never; + /** Remove a group's grant on the page (editor) */ + delete: operations["unsharePageWithGroup"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/pages/{id}/share": { parameters: { query?: never; @@ -1549,7 +1635,9 @@ export interface components { description: string; visibility: components["schemas"]["SpaceVisibility"]; defaultRole: components["schemas"]["SpaceDefaultRole"]; - role: components["schemas"]["SpaceRole"]; + role: components["schemas"]["SpaceCallerRole"]; + /** @description The caller cannot open the space itself and sees only pages shared with them */ + limited: boolean; created: string; }; SpaceMember: { @@ -1562,12 +1650,14 @@ export interface components { }; PageNode: { id: string; - /** @description Parent page id; empty at the top level */ + /** @description Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor. */ parent: string; title: string; icon: string; /** @description Fractional sort key among siblings */ position: string; + /** @description This page itself is restricted */ + restricted: boolean; updated: string; }; PageRef: { @@ -1588,12 +1678,61 @@ export interface components { deletedAt: string; /** @description The page or one of its ancestors is in the trash */ inTrash: boolean; - /** @description Root first */ + /** @description Root first; pages the caller cannot open are left out */ ancestors: components["schemas"]["PageRef"][]; + /** @description The caller's role on this page */ role: components["schemas"]["SpaceRole"]; + /** @description The page or one of its ancestors is restricted */ + restricted: boolean; /** @description In the caller's favorites */ favorite: boolean; }; + /** @enum {string} */ + PageGrantRole: "editor" | "commenter" | "viewer"; + /** + * @description The caller's space role; empty when they see only pages shared with them + * @enum {string} + */ + SpaceCallerRole: "admin" | "editor" | "commenter" | "viewer" | ""; + PageGrant: { + /** @enum {string} */ + type: "user" | "group"; + id: string; + name: string; + /** @description Empty for groups */ + email: string; + role: components["schemas"]["PageGrantRole"]; + /** @description Where the grant was made */ + page: components["schemas"]["PageRef"]; + /** @description Granted on an ancestor */ + inherited: boolean; + }; + PageInvite: { + id: string; + email: string; + role: components["schemas"]["PageGrantRole"]; + expires: string; + }; + PageAccess: { + /** @description The page or an ancestor is restricted; space members then see it only through grants */ + restricted: boolean; + /** @description The restricted ancestor, when the restriction comes from one */ + inheritedFrom: components["schemas"]["PageRef"] | null; + /** @description This page's grants first */ + grants: components["schemas"]["PageGrant"][]; + /** @description Pending guest invites for this page (editors only) */ + invites: components["schemas"]["PageInvite"][]; + /** @description The caller's role on this page */ + role: components["schemas"]["SpaceRole"]; + canManage: boolean; + /** @description May share with people outside the workspace */ + canInvite: boolean; + }; + SharePageResult: { + access: components["schemas"]["PageAccess"]; + /** @description Set when the person was invited as a guest; the grant is made when they accept */ + invite: components["schemas"]["Invite"] | null; + }; PageContent: { /** @description Tiptap JSON with type "doc"; null for a page that was never edited */ content: { @@ -4045,6 +4184,175 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + getPageAccess: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAccess"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + setPageRestricted: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + restricted: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAccess"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + sharePageWithUser: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: email */ + email: string; + role: components["schemas"]["PageGrantRole"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["SharePageResult"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + 409: components["responses"]["Error"]; + }; + }; + unsharePageWithUser: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + userId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The page's access afterwards */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAccess"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + sharePageWithGroup: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + groupId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + role: components["schemas"]["PageGrantRole"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAccess"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + unsharePageWithGroup: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + groupId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The page's access afterwards */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageAccess"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; getShareLink: { parameters: { query?: never; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 5411f53..c013016 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -469,6 +469,7 @@ class Space { required this.visibility, required this.defaultRole, required this.role, + required this.limited, required this.created, }); @@ -481,7 +482,8 @@ class Space { description: json['description'] as String, visibility: SpaceVisibility.fromJson(json['visibility'] as String), defaultRole: SpaceDefaultRole.fromJson(json['defaultRole'] as String), - role: SpaceRole.fromJson(json['role'] as String), + role: SpaceCallerRole.fromJson(json['role'] as String), + limited: json['limited'] as bool, created: json['created'] as String, ); @@ -501,7 +503,10 @@ class Space { final SpaceDefaultRole defaultRole; - final SpaceRole role; + final SpaceCallerRole role; + + /// The caller cannot open the space itself and sees only pages shared with them + final bool limited; final String created; @@ -515,6 +520,7 @@ class Space { 'visibility': visibility.toJson(), 'defaultRole': defaultRole.toJson(), 'role': role.toJson(), + 'limited': limited, 'created': created, }; } @@ -567,6 +573,7 @@ class PageNode { required this.title, required this.icon, required this.position, + required this.restricted, required this.updated, }); @@ -576,12 +583,13 @@ class PageNode { title: json['title'] as String, icon: json['icon'] as String, position: json['position'] as String, + restricted: json['restricted'] as bool, updated: json['updated'] as String, ); final String id; - /// Parent page id; empty at the top level + /// Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor. final String parent; final String title; @@ -591,6 +599,9 @@ class PageNode { /// Fractional sort key among siblings final String position; + /// This page itself is restricted + final bool restricted; + final String updated; Map toJson() => { @@ -599,6 +610,7 @@ class PageNode { 'title': title, 'icon': icon, 'position': position, + 'restricted': restricted, 'updated': updated, }; } @@ -635,6 +647,7 @@ class Page { required this.inTrash, required this.ancestors, required this.role, + required this.restricted, required this.favorite, }); @@ -653,6 +666,7 @@ class Page { .map((e) => PageRef.fromJson(e as Map)) .toList(), role: SpaceRole.fromJson(json['role'] as String), + restricted: json['restricted'] as bool, favorite: json['favorite'] as bool, ); @@ -678,11 +692,15 @@ class Page { /// The page or one of its ancestors is in the trash final bool inTrash; - /// Root first + /// Root first; pages the caller cannot open are left out final List ancestors; + /// The caller's role on this page final SpaceRole role; + /// The page or one of its ancestors is restricted + final bool restricted; + /// In the caller's favorites final bool favorite; @@ -699,10 +717,221 @@ class Page { 'inTrash': inTrash, 'ancestors': ancestors.map((e) => e.toJson()).toList(), 'role': role.toJson(), + 'restricted': restricted, 'favorite': favorite, }; } +enum PageGrantRole { + editor('editor'), + commenter('commenter'), + viewer('viewer'); + + const PageGrantRole(this.value); + final String value; + + static PageGrantRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown PageGrantRole', value), + ); + + String toJson() => value; +} + +/// The caller's space role; empty when they see only pages shared with them +enum SpaceCallerRole { + admin('admin'), + editor('editor'), + commenter('commenter'), + viewer('viewer'), + none(''); + + const SpaceCallerRole(this.value); + final String value; + + static SpaceCallerRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown SpaceCallerRole', value), + ); + + String toJson() => value; +} + +enum PageGrantType { + user('user'), + group('group'); + + const PageGrantType(this.value); + final String value; + + static PageGrantType fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown PageGrantType', value), + ); + + String toJson() => value; +} + +class PageGrant { + const PageGrant({ + required this.type, + required this.id, + required this.name, + required this.email, + required this.role, + required this.page, + required this.inherited, + }); + + factory PageGrant.fromJson(Map json) => PageGrant( + type: PageGrantType.fromJson(json['type'] as String), + id: json['id'] as String, + name: json['name'] as String, + email: json['email'] as String, + role: PageGrantRole.fromJson(json['role'] as String), + page: PageRef.fromJson(json['page'] as Map), + inherited: json['inherited'] as bool, + ); + + final PageGrantType type; + + final String id; + + final String name; + + /// Empty for groups + final String email; + + final PageGrantRole role; + + /// Where the grant was made + final PageRef page; + + /// Granted on an ancestor + final bool inherited; + + Map toJson() => { + 'type': type.toJson(), + 'id': id, + 'name': name, + 'email': email, + 'role': role.toJson(), + 'page': page.toJson(), + 'inherited': inherited, + }; +} + +class PageInvite { + const PageInvite({ + required this.id, + required this.email, + required this.role, + required this.expires, + }); + + factory PageInvite.fromJson(Map json) => PageInvite( + id: json['id'] as String, + email: json['email'] as String, + role: PageGrantRole.fromJson(json['role'] as String), + expires: json['expires'] as String, + ); + + final String id; + + final String email; + + final PageGrantRole role; + + final String expires; + + Map toJson() => { + 'id': id, + 'email': email, + 'role': role.toJson(), + 'expires': expires, + }; +} + +class PageAccess { + const PageAccess({ + required this.restricted, + required this.inheritedFrom, + required this.grants, + required this.invites, + required this.role, + required this.canManage, + required this.canInvite, + }); + + factory PageAccess.fromJson(Map json) => PageAccess( + restricted: json['restricted'] as bool, + inheritedFrom: json['inheritedFrom'] == null + ? null + : PageRef.fromJson(json['inheritedFrom'] as Map), + grants: (json['grants'] as List) + .map((e) => PageGrant.fromJson(e as Map)) + .toList(), + invites: (json['invites'] as List) + .map((e) => PageInvite.fromJson(e as Map)) + .toList(), + role: SpaceRole.fromJson(json['role'] as String), + canManage: json['canManage'] as bool, + canInvite: json['canInvite'] as bool, + ); + + /// The page or an ancestor is restricted; space members then see it only through grants + final bool restricted; + + /// The restricted ancestor, when the restriction comes from one + final PageRef? inheritedFrom; + + /// This page's grants first + final List grants; + + /// Pending guest invites for this page (editors only) + final List invites; + + /// The caller's role on this page + final SpaceRole role; + + final bool canManage; + + /// May share with people outside the workspace + final bool canInvite; + + Map toJson() => { + 'restricted': restricted, + 'inheritedFrom': inheritedFrom?.toJson(), + 'grants': grants.map((e) => e.toJson()).toList(), + 'invites': invites.map((e) => e.toJson()).toList(), + 'role': role.toJson(), + 'canManage': canManage, + 'canInvite': canInvite, + }; +} + +class SharePageResult { + const SharePageResult({required this.access, required this.invite}); + + factory SharePageResult.fromJson(Map json) => + SharePageResult( + access: PageAccess.fromJson(json['access'] as Map), + invite: json['invite'] == null + ? null + : Invite.fromJson(json['invite'] as Map), + ); + + final PageAccess access; + + /// Set when the person was invited as a guest; the grant is made when they accept + final Invite? invite; + + Map toJson() => { + 'access': access.toJson(), + 'invite': invite?.toJson(), + }; +} + class PageContent { const PageContent({required this.content, required this.updated}); diff --git a/Phone-App/tool/generate_api.dart b/Phone-App/tool/generate_api.dart index a3e33ec..cdf7e2e 100644 --- a/Phone-App/tool/generate_api.dart +++ b/Phone-App/tool/generate_api.dart @@ -101,7 +101,8 @@ class _Generator { _doc(b, s['description'] as String?, ''); b.writeln('enum $name {'); for (final v in values) { - b.writeln(" ${_ident(v)}('$v'),"); + // An empty value means "none" (e.g. SpaceCallerRole). + b.writeln(" ${v.isEmpty ? 'none' : _ident(v)}('$v'),"); } b.writeln(' ;'); b.writeln(); diff --git a/Server/internal/access/pages.go b/Server/internal/access/pages.go new file mode 100644 index 0000000..3da6bb6 --- /dev/null +++ b/Server/internal/access/pages.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package access + +import "docwell/server/internal/apperr" + +// ---- Page permissions ------------------------------------------------------ +// +// Pages inherit their space's rights, and two things refine them per page: +// +// grant a user or group gets editor, commenter or viewer on a page and +// everything under it, on top of their space role. This is how a +// page is shared with a guest who cannot open the space. +// restricted a restricted page and its subtree ignore the space role and +// the grants above it: only grants on the restricted page or +// below it count. Space admins always keep admin. +// +// Page roles use the space role names; grants never give admin. + +// PageNode is one step from a page up to its space root, as seen by one +// caller: whether the page is restricted and the caller's best grant on it +// ("" when none). +type PageNode struct { + Restricted bool + Grant string +} + +// ValidPageGrant reports whether role can be granted on a page. +func ValidPageGrant(role string) bool { return ValidDefaultRole(role) } + +// PageRole is the effective role on a page for someone with space role +// spaceRole ("" when they cannot open the space), given the chain from the +// page itself up to its top-level ancestor. "" = no access. +func PageRole(spaceRole string, chain []PageNode) string { + if SpaceAtLeast(spaceRole, SpaceAdmin) { + return SpaceAdmin + } + best := "" + for _, n := range chain { + if ValidPageGrant(n.Grant) { + best = HigherSpaceRole(best, n.Grant) + } + if n.Restricted { + return best + } + } + return HigherSpaceRole(spaceRole, best) +} + +// ManagePageAccess (grants and the restricted switch) needs editor on the page. +func ManagePageAccess(pageRole string) error { + if err := ViewSpace(pageRole); err != nil { + return apperr.NotFound("page not found") + } + if !SpaceAtLeast(pageRole, SpaceEditor) { + return apperr.Forbidden("editor role required") + } + return nil +} + +// SetPageGrant checks granting role on a page to a user whose workspace role +// is targetWsRole ("" for a group). Workspace admins already manage every +// page, so granting them anything is pointless. +func SetPageGrant(actorPageRole, targetWsRole string, isGroup bool, role string) error { + if !ValidPageGrant(role) { + return apperr.Invalid("role must be editor, commenter or viewer") + } + if err := ManagePageAccess(actorPageRole); err != nil { + return err + } + if isGroup { + return nil + } + if targetWsRole == "" { + return apperr.Invalid("that user is not a member of this workspace") + } + if AtLeast(targetWsRole, WorkspaceAdmin) { + return apperr.Invalid("workspace admins already manage every page") + } + return nil +} + +// InvitePageGuest checks sharing a page with someone outside the workspace, +// who joins it as a guest. Workspace members and above may; guests may not +// bring in more people. +func InvitePageGuest(actorWsRole, actorPageRole string) error { + if err := ManagePageAccess(actorPageRole); err != nil { + return err + } + if !AtLeast(actorWsRole, WorkspaceMember) { + return apperr.Forbidden("guests cannot invite people") + } + return nil +} + +// CreatePageUnder checks creating a page: under a parent it needs editor on +// the parent; at the top level, editor on the space. +func CreatePageUnder(spaceRole, parentRole string, topLevel bool) error { + if topLevel { + if spaceRole == "" { + // Someone who sees only shared pages still sees the space. + return apperr.Forbidden("only people with access to the whole space can add top-level pages") + } + return EditPages(spaceRole) + } + return EditPages(parentRole) +} diff --git a/Server/internal/access/pages_test.go b/Server/internal/access/pages_test.go new file mode 100644 index 0000000..4ab7b58 --- /dev/null +++ b/Server/internal/access/pages_test.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package access + +import ( + "testing" + + "docwell/server/internal/apperr" +) + +func TestPageRole(t *testing.T) { + open := PageNode{} + locked := PageNode{Restricted: true} + grant := func(role string, restricted bool) PageNode { return PageNode{Grant: role, Restricted: restricted} } + cases := []struct { + name string + space string + chain []PageNode + want string + }{ + {"plain page follows the space", SpaceEditor, []PageNode{open, open}, SpaceEditor}, + {"no space access, no grant", "", []PageNode{open}, ""}, + {"guest grant on the page", "", []PageNode{grant(SpaceViewer, false)}, SpaceViewer}, + {"guest grant on an ancestor", "", []PageNode{open, open, grant(SpaceCommenter, false)}, SpaceCommenter}, + {"grant raises a space viewer", SpaceViewer, []PageNode{grant(SpaceEditor, false)}, SpaceEditor}, + {"grant never lowers", SpaceEditor, []PageNode{grant(SpaceViewer, false)}, SpaceEditor}, + {"restricted hides from space members", SpaceEditor, []PageNode{open, locked}, ""}, + {"grant on the restricted page", SpaceEditor, []PageNode{open, grant(SpaceViewer, true)}, SpaceViewer}, + {"grant below the restriction", SpaceEditor, []PageNode{grant(SpaceCommenter, false), locked}, SpaceCommenter}, + {"grant above the restriction is ignored", SpaceEditor, []PageNode{locked, grant(SpaceEditor, false)}, ""}, + {"space admin sees restricted pages", SpaceAdmin, []PageNode{locked}, SpaceAdmin}, + {"admin grant is ignored", "", []PageNode{grant(SpaceAdmin, false)}, ""}, + } + for _, c := range cases { + if got := PageRole(c.space, c.chain); got != c.want { + t.Errorf("%s: got %q, want %q", c.name, got, c.want) + } + } +} + +func TestPageAccessActions(t *testing.T) { + cases := []struct { + name string + err error + want apperr.Kind + }{ + {"commenter cannot share", ManagePageAccess(SpaceCommenter), forbidden}, + {"no access hides the page", ManagePageAccess(""), notFound}, + {"editor shares", ManagePageAccess(SpaceEditor), ok}, + {"admin grant refused", SetPageGrant(SpaceAdmin, WorkspaceMember, false, SpaceAdmin), invalid}, + {"grant to a member", SetPageGrant(SpaceEditor, WorkspaceMember, false, SpaceViewer), ok}, + {"grant to a guest", SetPageGrant(SpaceEditor, WorkspaceGuest, false, SpaceEditor), ok}, + {"grant to an outsider", SetPageGrant(SpaceEditor, "", false, SpaceViewer), invalid}, + {"grant to a workspace admin", SetPageGrant(SpaceEditor, WorkspaceAdmin, false, SpaceViewer), invalid}, + {"grant to a group", SetPageGrant(SpaceEditor, "", true, SpaceCommenter), ok}, + {"viewer cannot grant", SetPageGrant(SpaceViewer, WorkspaceMember, false, SpaceViewer), forbidden}, + {"member invites a guest", InvitePageGuest(WorkspaceMember, SpaceEditor), ok}, + {"guest cannot invite", InvitePageGuest(WorkspaceGuest, SpaceEditor), forbidden}, + {"top-level page needs space editor", CreatePageUnder(SpaceViewer, SpaceEditor, true), forbidden}, + {"guest cannot add a top-level page", CreatePageUnder("", SpaceEditor, true), forbidden}, + {"subpage needs parent editor", CreatePageUnder("", SpaceEditor, false), ok}, + {"subpage of a viewed page", CreatePageUnder(SpaceEditor, SpaceViewer, false), forbidden}, + } + for _, c := range cases { + if got := kind(c.err); got != c.want { + t.Errorf("%s: got kind %v, want %v (%v)", c.name, got, c.want, c.err) + } + } +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index caf2dc6..9897708 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -48,6 +48,45 @@ func (e InviteStatus) Valid() bool { } } +// Defines values for PageGrantType. +const ( + PageGrantTypeGroup PageGrantType = "group" + PageGrantTypeUser PageGrantType = "user" +) + +// Valid indicates whether the value is a known member of the PageGrantType enum. +func (e PageGrantType) Valid() bool { + switch e { + case PageGrantTypeGroup: + return true + case PageGrantTypeUser: + return true + default: + return false + } +} + +// Defines values for PageGrantRole. +const ( + PageGrantRoleCommenter PageGrantRole = "commenter" + PageGrantRoleEditor PageGrantRole = "editor" + PageGrantRoleViewer PageGrantRole = "viewer" +) + +// Valid indicates whether the value is a known member of the PageGrantRole enum. +func (e PageGrantRole) Valid() bool { + switch e { + case PageGrantRoleCommenter: + return true + case PageGrantRoleEditor: + return true + case PageGrantRoleViewer: + return true + default: + return false + } +} + // Defines values for Role. const ( RoleAdmin Role = "admin" @@ -69,6 +108,33 @@ func (e Role) Valid() bool { } } +// Defines values for SpaceCallerRole. +const ( + SpaceCallerRoleAdmin SpaceCallerRole = "admin" + SpaceCallerRoleCommenter SpaceCallerRole = "commenter" + SpaceCallerRoleEditor SpaceCallerRole = "editor" + SpaceCallerRoleEmpty SpaceCallerRole = "" + SpaceCallerRoleViewer SpaceCallerRole = "viewer" +) + +// Valid indicates whether the value is a known member of the SpaceCallerRole enum. +func (e SpaceCallerRole) Valid() bool { + switch e { + case SpaceCallerRoleAdmin: + return true + case SpaceCallerRoleCommenter: + return true + case SpaceCallerRoleEditor: + return true + case SpaceCallerRoleEmpty: + return true + case SpaceCallerRoleViewer: + return true + default: + return false + } +} + // Defines values for SpaceDefaultRole. const ( SpaceDefaultRoleCommenter SpaceDefaultRole = "commenter" @@ -513,7 +579,7 @@ type Organization struct { // Page defines model for Page. type Page struct { - // Ancestors Root first + // Ancestors Root first; pages the caller cannot open are left out Ancestors []PageRef `json:"ancestors"` Created string `json:"created"` @@ -526,8 +592,13 @@ type Page struct { Id string `json:"id"` // InTrash The page or one of its ancestors is in the trash - InTrash bool `json:"inTrash"` - Parent string `json:"parent"` + InTrash bool `json:"inTrash"` + Parent string `json:"parent"` + + // Restricted The page or one of its ancestors is restricted + Restricted bool `json:"restricted"` + + // Role The caller's role on this page Role SpaceRole `json:"role"` Space string `json:"space"` Title string `json:"title"` @@ -535,6 +606,28 @@ type Page struct { Workspace string `json:"workspace"` } +// PageAccess defines model for PageAccess. +type PageAccess struct { + // CanInvite May share with people outside the workspace + CanInvite bool `json:"canInvite"` + CanManage bool `json:"canManage"` + + // Grants This page's grants first + Grants []PageGrant `json:"grants"` + + // InheritedFrom The restricted ancestor, when the restriction comes from one + InheritedFrom *PageRef `json:"inheritedFrom"` + + // Invites Pending guest invites for this page (editors only) + Invites []PageInvite `json:"invites"` + + // Restricted The page or an ancestor is restricted; space members then see it only through grants + Restricted bool `json:"restricted"` + + // Role The caller's role on this page + Role SpaceRole `json:"role"` +} + // PageContent defines model for PageContent. type PageContent struct { // Content Tiptap JSON with type "doc"; null for a page that was never edited @@ -542,6 +635,36 @@ type PageContent struct { Updated string `json:"updated"` } +// PageGrant defines model for PageGrant. +type PageGrant struct { + // Email Empty for groups + Email string `json:"email"` + Id string `json:"id"` + + // Inherited Granted on an ancestor + Inherited bool `json:"inherited"` + Name string `json:"name"` + + // Page Where the grant was made + Page PageRef `json:"page"` + Role PageGrantRole `json:"role"` + Type PageGrantType `json:"type"` +} + +// PageGrantType defines model for PageGrant.Type. +type PageGrantType string + +// PageGrantRole defines model for PageGrantRole. +type PageGrantRole string + +// PageInvite defines model for PageInvite. +type PageInvite struct { + Email string `json:"email"` + Expires string `json:"expires"` + Id string `json:"id"` + Role PageGrantRole `json:"role"` +} + // PageItem defines model for PageItem. type PageItem struct { // At When it was favorited @@ -558,13 +681,16 @@ type PageNode struct { Icon string `json:"icon"` Id string `json:"id"` - // Parent Parent page id; empty at the top level + // Parent Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor. Parent string `json:"parent"` // Position Fractional sort key among siblings Position string `json:"position"` - Title string `json:"title"` - Updated string `json:"updated"` + + // Restricted This page itself is restricted + Restricted bool `json:"restricted"` + Title string `json:"title"` + Updated string `json:"updated"` } // PageRef defines model for PageRef. @@ -639,6 +765,14 @@ type ShareLink struct { Url string `json:"url"` } +// SharePageResult defines model for SharePageResult. +type SharePageResult struct { + Access PageAccess `json:"access"` + + // Invite Set when the person was invited as a guest; the grant is made when they accept + Invite *Invite `json:"invite"` +} + // SharedPage defines model for SharedPage. type SharedPage struct { // Content Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId} @@ -691,15 +825,23 @@ type Space struct { Description string `json:"description"` Icon string `json:"icon"` Id string `json:"id"` - Name string `json:"name"` - Role SpaceRole `json:"role"` - Slug string `json:"slug"` + + // Limited The caller cannot open the space itself and sees only pages shared with them + Limited bool `json:"limited"` + Name string `json:"name"` + + // Role The caller's space role; empty when they see only pages shared with them + Role SpaceCallerRole `json:"role"` + Slug string `json:"slug"` // Visibility open - every workspace member gets the default role; private - explicit members only. Visibility SpaceVisibility `json:"visibility"` Workspace string `json:"workspace"` } +// SpaceCallerRole The caller's space role; empty when they see only pages shared with them +type SpaceCallerRole string + // SpaceDefaultRole Role that workspace members (not guests) get in an open space without an explicit role. type SpaceDefaultRole string @@ -894,6 +1036,22 @@ type UpdatePageJSONBody struct { Title *string `json:"title,omitempty"` } +// SetPageRestrictedJSONBody defines parameters for SetPageRestricted. +type SetPageRestrictedJSONBody struct { + Restricted bool `json:"restricted"` +} + +// SharePageWithGroupJSONBody defines parameters for SharePageWithGroup. +type SharePageWithGroupJSONBody struct { + Role PageGrantRole `json:"role"` +} + +// SharePageWithUserJSONBody defines parameters for SharePageWithUser. +type SharePageWithUserJSONBody struct { + Email openapi_types.Email `json:"email"` + Role PageGrantRole `json:"role"` +} + // UploadAttachmentMultipartBody defines parameters for UploadAttachment. type UploadAttachmentMultipartBody struct { File openapi_types.File `json:"file"` @@ -1081,6 +1239,15 @@ type RenameOrgJSONRequestBody = NameRequest // UpdatePageJSONRequestBody defines body for UpdatePage for application/json ContentType. type UpdatePageJSONRequestBody UpdatePageJSONBody +// SetPageRestrictedJSONRequestBody defines body for SetPageRestricted for application/json ContentType. +type SetPageRestrictedJSONRequestBody SetPageRestrictedJSONBody + +// SharePageWithGroupJSONRequestBody defines body for SharePageWithGroup for application/json ContentType. +type SharePageWithGroupJSONRequestBody SharePageWithGroupJSONBody + +// SharePageWithUserJSONRequestBody defines body for SharePageWithUser for application/json ContentType. +type SharePageWithUserJSONRequestBody SharePageWithUserJSONBody + // UploadAttachmentMultipartRequestBody defines body for UploadAttachment for multipart/form-data ContentType. type UploadAttachmentMultipartRequestBody UploadAttachmentMultipartBody diff --git a/Server/internal/directory/directory.go b/Server/internal/directory/directory.go index d2c92f5..2ad14c4 100644 --- a/Server/internal/directory/directory.go +++ b/Server/internal/directory/directory.go @@ -846,6 +846,7 @@ func (s *Service) RemoveMember(ctx context.Context, c access.Caller, wsID, userI } } s.dropGroupMemberships(ctx, userID, ws.ID) + s.dropPageGrants(ctx, "user", userID, ws.ID) return nil } @@ -861,6 +862,7 @@ func (s *Service) dropMemberships(ctx context.Context, userID string) { _ = s.pb.Delete(ctx, "workspace_members", m.ID) } s.dropGroupMemberships(ctx, userID, "") + s.dropPageGrants(ctx, "user", userID, "") spaceMembers, err := s.userSpaceMemberships(ctx, userID, "") if err != nil { return diff --git a/Server/internal/directory/favorites.go b/Server/internal/directory/favorites.go index 9ced30a..0f4ad5f 100644 --- a/Server/internal/directory/favorites.go +++ b/Server/internal/directory/favorites.go @@ -47,21 +47,26 @@ const userPageFields = "id,page,created,visited," + // visibleItems keeps the rows whose page c can still open, with space names. func (s *Service) visibleItems(ctx context.Context, c access.Caller, rows []userPageRecord, at func(userPageRecord) string) []PageItem { - spaceNames := map[string]string{} // space id → name, "" = no access + type reach struct { + name string // "" = no access to the space + rules pageRules + } + spaces := map[string]reach{} out := []PageItem{} for _, r := range rows { p := r.Expand.Page if p == nil || p.DeletedAt != "" { continue } - name, seen := spaceNames[p.Space] + sp, seen := spaces[p.Space] if !seen { - if a, err := s.spaceFor(ctx, c, p.Space); err == nil { - name = a.space.Name + if a, rules, err := s.spaceRules(ctx, c, p.Space); err == nil { + sp = reach{name: a.space.Name, rules: rules} } - spaceNames[p.Space] = name + spaces[p.Space] = sp } - if name == "" { + name := sp.name + if name == "" || sp.rules.role(p.ID) == "" { continue } out = append(out, PageItem{ID: p.ID, Title: p.Title, Icon: p.Icon, Space: p.Space, SpaceName: name, At: at(r)}) diff --git a/Server/internal/directory/groups.go b/Server/internal/directory/groups.go index 67987b6..cc9dc35 100644 --- a/Server/internal/directory/groups.go +++ b/Server/internal/directory/groups.go @@ -264,6 +264,7 @@ func (s *Service) DeleteGroup(ctx context.Context, c access.Caller, id string) e return err } } + s.dropPageGrants(ctx, "group", g.ID, "") return mapPB(s.pb.Delete(ctx, "groups", g.ID), "group not found") } diff --git a/Server/internal/directory/invites.go b/Server/internal/directory/invites.go index 6ec8b35..153b28d 100644 --- a/Server/internal/directory/invites.go +++ b/Server/internal/directory/invites.go @@ -72,6 +72,8 @@ type inviteRecord struct { Role string `json:"role"` Workspace string `json:"workspace"` WorkspaceRole string `json:"workspace_role"` + Page string `json:"page"` + PageRole string `json:"page_role"` InvitedBy string `json:"invited_by"` Expires string `json:"expires"` Accepted string `json:"accepted"` @@ -135,6 +137,9 @@ type CreateInviteInput struct { // workspace admin, and the organization is the workspace's. Workspace string `json:"workspace"` WorkspaceRole string `json:"workspaceRole"` + // page and pageRole make a guest invite that shares one page + // (SharePageWithUser, which has checked the inviter's rights). + page, pageRole string } // CreateInvite invites someone by email. Inviting a person who already has @@ -160,11 +165,16 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn if role == "" { role = access.WorkspaceMember } - if err := access.InviteToWorkspace(actorRole, role); err != nil { - return Invite{}, err + if in.page == "" { + if err := access.InviteToWorkspace(actorRole, role); err != nil { + return Invite{}, err + } } org = ws.Organization body["role"], body["workspace"], body["workspace_role"] = access.RoleUser, ws.ID, role + if in.page != "" { + body["page"], body["page_role"] = in.page, in.pageRole + } } else { role, ok := access.NormalizeRole(in.Role) if !ok { @@ -187,7 +197,7 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn switch { case err == nil && existing.Role == access.RoleSuperadmin: return Invite{}, apperr.Conflict("that person is a superadmin and already has access everywhere") - case err == nil && existing.Organization == org && org != "" && ws.ID != "": + case err == nil && existing.Organization == org && org != "" && ws.ID != "" && in.page == "": // Already in the organization: no invite needed. m, err := s.SetMember(ctx, c, ws.ID, email, body["workspace_role"].(string)) if err != nil { @@ -214,7 +224,8 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn body["expires"] = pbTime(time.Now().Add(inviteTTL)) // Inviting the same person to the same place again refreshes the invite. - filter := fmt.Sprintf("email = '%s' && organization = '%s' && workspace = '%s' && accepted = ''", filterValue(email), org, ws.ID) + filter := fmt.Sprintf("email = '%s' && organization = '%s' && workspace = '%s' && page = '%s' && accepted = ''", + filterValue(email), org, ws.ID, in.page) prev, err := pocketbase.List[inviteRecord](ctx, s.pb, "invites", pocketbase.ListOptions{PerPage: 1, Filter: filter}) if err != nil { return Invite{}, err @@ -509,6 +520,14 @@ func (s *Service) AcceptInvite(ctx context.Context, me *auth.User, in AcceptInvi } } } + if rec.Page != "" && access.ValidPageGrant(rec.PageRole) { + // The page may have gone since; the workspace membership still stands. + if p, err := s.getPage(ctx, rec.Page); err == nil { + if err := s.upsertGrant(ctx, p, "user", userID, rec.PageRole); err != nil { + return "", err + } + } + } if _, err := pocketbase.Update[inviteRecord](ctx, s.pb, "invites", rec.ID, map[string]any{ "accepted": pbTime(time.Now()), }); err != nil { diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go index a747876..8687f90 100644 --- a/Server/internal/directory/pages.go +++ b/Server/internal/directory/pages.go @@ -22,7 +22,7 @@ import ( // Purging deletes the record, and PocketBase cascades to the subtree. // pageFields skips the large content columns. -const pageFields = "id,workspace,space,parent,title,icon,position,creator,last_editor,deleted_at,created,updated" +const pageFields = "id,workspace,space,parent,title,icon,position,restricted,creator,last_editor,deleted_at,created,updated" type pageRecord struct { ID string `json:"id"` @@ -32,6 +32,7 @@ type pageRecord struct { Title string `json:"title"` Icon string `json:"icon"` Position string `json:"position"` + Restricted bool `json:"restricted"` Creator string `json:"creator"` LastEditor string `json:"last_editor"` DeletedAt string `json:"deleted_at"` @@ -46,11 +47,13 @@ type PageNode struct { Title string `json:"title"` Icon string `json:"icon"` Position string `json:"position"` - Updated string `json:"updated"` + // Restricted is set on the page that is restricted itself (not its subtree). + Restricted bool `json:"restricted"` + Updated string `json:"updated"` } func (r pageRecord) node() PageNode { - return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Updated: r.Updated} + return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Restricted: r.Restricted, Updated: r.Updated} } type PageRef struct { @@ -74,6 +77,8 @@ type Page struct { InTrash bool `json:"inTrash"` Ancestors []PageRef `json:"ancestors"` Role string `json:"role"` + // Restricted is true when the page or an ancestor is restricted. + Restricted bool `json:"restricted"` // Favorite is whether the caller has the page in their favorites. Favorite bool `json:"favorite"` } @@ -101,17 +106,11 @@ func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) { return res.Items[0], nil } -// pageFor loads a page and c's access to its space. +// pageFor loads a page and c's access to it; a.role is c's role on the page +// (see pageAccess). func (s *Service) pageFor(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, error) { - p, err := s.getPage(ctx, id) - if err != nil { - return p, spaceAccess{}, err - } - a, err := s.spaceFor(ctx, c, p.Space) - if err != nil { - return p, a, apperr.NotFound("page not found") - } - return p, a, nil + p, a, _, err := s.pageAccess(ctx, c, id) + return p, a, err } // tree is every page of one space, live or trashed. @@ -170,9 +169,23 @@ func (t tree) within(id, ancestor string) bool { return false } -// ListPages returns a space's live pages, siblings in order; clients build the tree. +// restrictedBelow reports whether page id, or an ancestor of it below +// ancestor, is restricted. +func (t tree) restrictedBelow(id, ancestor string) bool { + for depth := 0; id != "" && id != ancestor && depth < 1000; depth++ { + if t.byID[id].Restricted { + return true + } + id = t.byID[id].Parent + } + return false +} + +// ListPages returns the space's live pages c can open, siblings in order; +// clients build the tree. A visible page under hidden ones hangs from its +// nearest visible ancestor (the top level when there is none). func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string) ([]PageNode, error) { - a, err := s.spaceFor(ctx, c, spaceID) + a, rules, err := s.spaceRules(ctx, c, spaceID) if err != nil { return nil, err } @@ -181,27 +194,33 @@ func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string return nil, err } out := []PageNode{} - var walk func(parent string) - walk = func(parent string) { + var walk func(parent, shownParent string) + walk = func(parent, shownParent string) { for _, p := range t.children[parent] { - out = append(out, p.node()) - walk(p.ID) + under := shownParent + if rules.role(p.ID) != "" { + n := p.node() + n.Parent = shownParent + out = append(out, n) + under = p.ID + } + walk(p.ID, under) } } - walk("") + walk("", "") return out, nil } // GetPage returns a page with its breadcrumbs. func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page, error) { - p, a, err := s.pageFor(ctx, c, id) + p, a, rules, err := s.pageAccess(ctx, c, id) if err != nil { return Page{}, err } page := Page{ ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon, Created: p.Created, Updated: p.Updated, DeletedAt: p.DeletedAt, InTrash: p.DeletedAt != "", - Ancestors: []PageRef{}, Role: a.role, Favorite: s.isFavorite(ctx, c.ID, p.ID), + Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, Favorite: s.isFavorite(ctx, c.ID, p.ID), } parent := p.Parent for depth := 0; parent != "" && depth < 100; depth++ { @@ -210,7 +229,11 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page break } page.InTrash = page.InTrash || anc.DeletedAt != "" - page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...) + page.Restricted = page.Restricted || anc.Restricted + // Breadcrumbs leave out pages the caller cannot open. + if rules.role(anc.ID) != "" { + page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...) + } parent = anc.Parent } return page, nil @@ -286,13 +309,14 @@ type CreatePageInput struct { Index *int `json:"index"` } -// CreatePage adds a page to a space (editor). +// CreatePage adds a page to a space (editor of the parent page, or of the +// space for a top-level page). func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID string, in CreatePageInput) (Page, error) { - a, err := s.spaceFor(ctx, c, spaceID) + a, rules, err := s.spaceRules(ctx, c, spaceID) if err != nil { return Page{}, err } - if err := access.EditPages(a.role); err != nil { + if err := access.CreatePageUnder(a.role, rules.role(in.Parent), in.Parent == ""); err != nil { return Page{}, err } title, err := cleanTitle(in.Title) @@ -374,15 +398,19 @@ type MovePageInput struct { Index int `json:"index"` } -// MovePage moves a page (with its subtree) within its space (editor). +// MovePage moves a page (with its subtree) within its space (editor of the +// page and of where it goes). func (s *Service) MovePage(ctx context.Context, c access.Caller, id string, in MovePageInput) (Page, error) { - p, a, err := s.pageFor(ctx, c, id) + p, a, rules, err := s.pageAccess(ctx, c, id) if err != nil { return Page{}, err } if err := access.EditPages(a.role); err != nil { return Page{}, err } + if err := access.CreatePageUnder(a.spaceRole, rules.role(in.Parent), in.Parent == ""); err != nil { + return Page{}, err + } t, err := s.loadTree(ctx, a.space.ID) if err != nil { return Page{}, err @@ -467,10 +495,10 @@ func (s *Service) RestorePage(ctx context.Context, c access.Caller, id string) ( return s.GetPage(ctx, c, p.ID) } -// ListTrash lists a space's trashed pages, newest first. Pages inside a -// trashed page are not listed separately: they come back with it. +// ListTrash lists a space's trashed pages c can open, newest first. Pages +// inside a trashed page are not listed separately: they come back with it. func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]TrashedPage, error) { - a, err := s.spaceFor(ctx, c, spaceID) + a, rules, err := s.spaceRules(ctx, c, spaceID) if err != nil { return nil, err } @@ -480,7 +508,7 @@ func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string } out := []TrashedPage{} for _, p := range t.byID { - if p.DeletedAt != "" && t.live(p.Parent) { + if p.DeletedAt != "" && t.live(p.Parent) && rules.role(p.ID) != "" { out = append(out, TrashedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, DeletedAt: p.DeletedAt}) } } diff --git a/Server/internal/directory/permissions.go b/Server/internal/directory/permissions.go new file mode 100644 index 0000000..7d3ecfc --- /dev/null +++ b/Server/internal/directory/permissions.go @@ -0,0 +1,526 @@ +// 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) +} + +// restrictedAt is the page itself or its nearest restricted ancestor ("" when none). +func (r pageRules) restrictedAt(id string) string { + if len(r.restricted) == 0 { + return "" + } + for depth := 0; id != "" && depth < 1000; depth++ { + if r.restricted[id] { + return id + } + id = r.parent[id] + } + return "" +} + +// 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) + 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) + } +} diff --git a/Server/internal/directory/search.go b/Server/internal/directory/search.go index c14258f..3d8f194 100644 --- a/Server/internal/directory/search.go +++ b/Server/internal/directory/search.go @@ -27,7 +27,7 @@ type SearchResult struct { Total int `json:"total"` } -// Search finds pages in a workspace, only in the spaces c can open. +// Search finds pages in a workspace, only the ones c can open. func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (SearchResult, error) { spaces, err := s.ListSpaces(ctx, c, wsID) if err != nil { @@ -39,19 +39,40 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string } ids := make([]string, len(spaces)) names := make(map[string]string, len(spaces)) + rules := make(map[string]pageRules, len(spaces)) + filtered := false // some pages of these spaces are hidden from c for i, sp := range spaces { ids[i], names[sp.ID] = sp.ID, sp.Name + _, r, err := s.spaceRules(ctx, c, sp.ID) + if err != nil { + return SearchResult{}, err + } + rules[sp.ID] = r + filtered = filtered || (!r.plain() && r.spaceRole != access.SpaceAdmin) } if limit <= 0 { limit = 20 } - hits, total, err := s.search.Query(ctx, wsID, ids, text, limit) + // Hidden pages are dropped after the query, so ask for more to keep + // the page of results full. + want := limit + if filtered { + want = limit*3 + 20 + } + hits, total, err := s.search.Query(ctx, wsID, ids, text, want) if err != nil { return SearchResult{}, err } + dropped := 0 for _, h := range hits { - out.Items = append(out.Items, SearchHit{Hit: h, SpaceName: names[h.Space]}) + if rules[h.Space].role(h.ID) == "" { + dropped++ + continue + } + if len(out.Items) < limit { + out.Items = append(out.Items, SearchHit{Hit: h, SpaceName: names[h.Space]}) + } } - out.Total = total + out.Total = max(total-dropped, len(out.Items)) return out, nil } diff --git a/Server/internal/directory/shares.go b/Server/internal/directory/shares.go index 2e6c9ff..79f54d9 100644 --- a/Server/internal/directory/shares.go +++ b/Server/internal/directory/shares.go @@ -162,7 +162,7 @@ func (s *Service) sharedScope(ctx context.Context, token, pageID string) (shareR return link, root, t, nil } p, ok := t.byID[pageID] - if !ok || !link.IncludeSubpages || !t.live(p.ID) || !t.within(p.ID, root.ID) { + if !ok || !link.IncludeSubpages || !t.live(p.ID) || !t.within(p.ID, root.ID) || t.restrictedBelow(p.ID, root.ID) { return link, pageRecord{}, tree{}, apperr.NotFound("page not found") } return link, p, t, nil @@ -188,6 +188,9 @@ func (s *Service) GetSharedPage(ctx context.Context, token, pageID string) (Shar var walk func(parent string) walk = func(parent string) { for _, c := range t.children[parent] { + if c.Restricted { + continue + } out.Pages = append(out.Pages, c.node()) walk(c.ID) } diff --git a/Server/internal/directory/spaces.go b/Server/internal/directory/spaces.go index 0af85e5..51ee494 100644 --- a/Server/internal/directory/spaces.go +++ b/Server/internal/directory/spaces.go @@ -26,7 +26,10 @@ type Space struct { Visibility string `json:"visibility"` DefaultRole string `json:"defaultRole"` // Role is the caller's effective space role after the cascade. - Role string `json:"role"` + Role string `json:"role"` + // Limited is true when the caller cannot open the space itself and sees + // only the pages shared with them (Role is then ""). + Limited bool `json:"limited"` Created string `json:"created"` } @@ -49,7 +52,7 @@ func (r spaceRecord) view(role string) Space { } return Space{ ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description, - Visibility: r.Visibility, DefaultRole: def, Role: role, Created: r.Created, + Visibility: r.Visibility, DefaultRole: def, Role: role, Limited: role == "", Created: r.Created, } } @@ -96,17 +99,19 @@ func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) ( return res.Items[0], nil } -// spaceAccess is a space with the caller's workspace and space roles. +// spaceAccess is a space with the caller's workspace and space roles. From +// pageFor, role is the caller's role on that page (see pageRules) and +// spaceRole stays the role in the space itself. type spaceAccess struct { - space spaceRecord - ws workspaceRecord - wsRole string - role string + space spaceRecord + ws workspaceRecord + wsRole string + spaceRole string + role string } -// spaceFor loads a space with c's roles. A space c cannot open is reported as -// not found, like a workspace. -func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) { +// loadSpace loads a space with c's roles, without checking that c may open it. +func (s *Service) loadSpace(ctx context.Context, c access.Caller, id string) (spaceAccess, error) { if !validID(id) { return spaceAccess{}, apperr.NotFound("space not found") } @@ -128,13 +133,43 @@ func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spa return spaceAccess{}, err } } - a := spaceAccess{space: sp, ws: ws, wsRole: wsRole, role: access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)} + role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit) + return spaceAccess{space: sp, ws: ws, wsRole: wsRole, spaceRole: role, role: role}, nil +} + +// spaceFor loads a space with c's roles. A space c cannot open is reported as +// not found, like a workspace. +func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) { + a, err := s.loadSpace(ctx, c, id) + if err != nil { + return spaceAccess{}, err + } if err := access.ViewSpace(a.role); err != nil { return spaceAccess{}, err } return a, nil } +// spaceReach is spaceFor that also lets in a workspace member who cannot +// open the space but holds page grants in it (a guest a page was shared +// with). Their role stays "": only pageRules gives them anything. +func (s *Service) spaceReach(ctx context.Context, c access.Caller, id string) (spaceAccess, error) { + a, err := s.loadSpace(ctx, c, id) + if err != nil || a.role != "" { + return a, err + } + if a.wsRole != "" { + has, err := s.hasPageGrants(ctx, c, a.space) + if err != nil { + return spaceAccess{}, err + } + if has { + return a, nil + } + } + return spaceAccess{}, apperr.NotFound("space not found") +} + // ListSpaces lists the spaces of a workspace that c can open. func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) { ws, wsRole, err := s.workspaceFor(ctx, c, wsID) @@ -168,9 +203,15 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) explicit[g.Space] = access.HigherSpaceRole(explicit[g.Space], g.Role) } } + var shared map[string]bool + if !access.AtLeast(wsRole, access.WorkspaceAdmin) { + if shared, err = s.grantedSpaces(ctx, c, ws.ID); err != nil { + return nil, err + } + } out := []Space{} for _, sp := range spaces { - if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" { + if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" || shared[sp.ID] { out = append(out, sp.view(role)) } } @@ -178,9 +219,10 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) return out, nil } -// GetSpace returns one space with c's role. +// GetSpace returns one space with c's role (Limited for someone who sees +// only pages shared with them). func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) { - a, err := s.spaceFor(ctx, c, id) + a, err := s.spaceReach(ctx, c, id) if err != nil { return Space{}, err } diff --git a/Server/internal/directory/transfer.go b/Server/internal/directory/transfer.go index 5210ab3..18f6dfb 100644 --- a/Server/internal/directory/transfer.go +++ b/Server/internal/directory/transfer.go @@ -84,11 +84,11 @@ type ImportFile struct { // Markdown (.md, .markdown, .txt) and HTML (.html, .htm) are understood; a // leading level-1 heading becomes the title, otherwise the file name does. func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []ImportFile) ([]Page, error) { - a, err := s.spaceFor(ctx, c, spaceID) + a, rules, err := s.spaceRules(ctx, c, spaceID) if err != nil { return nil, err } - if err := access.EditPages(a.role); err != nil { + if err := access.CreatePageUnder(a.role, rules.role(parent), parent == ""); err != nil { return nil, err } if len(files) == 0 { diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index 6fa4d52..8430237 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -151,6 +151,7 @@ func (a *api) routes(mux *routeMux) { a.searchRoutes(mux) a.transferRoutes(mux) a.shareRoutes(mux) + a.permissionRoutes(mux) a.commentRoutes(mux) a.adminRoutes(mux) } diff --git a/Server/internal/httpapi/directory.go b/Server/internal/httpapi/directory.go index 3161291..251c5f7 100644 --- a/Server/internal/httpapi/directory.go +++ b/Server/internal/httpapi/directory.go @@ -41,6 +41,7 @@ type DirectoryService interface { SearchService TransferService ShareService + PermissionService CommentService } diff --git a/Server/internal/httpapi/permissions.go b/Server/internal/httpapi/permissions.go new file mode 100644 index 0000000..45a166b --- /dev/null +++ b/Server/internal/httpapi/permissions.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "net/http" + + "docwell/server/internal/access" + "docwell/server/internal/directory" +) + +// PermissionService is the part of directory.Service for page-level access. +type PermissionService interface { + GetPageAccess(ctx context.Context, c access.Caller, id string) (directory.PageAccess, error) + SetPageRestricted(ctx context.Context, c access.Caller, id string, on bool) (directory.PageAccess, error) + SharePageWithUser(ctx context.Context, c access.Caller, id, email, role string) (directory.SharePageResult, error) + SharePageWithGroup(ctx context.Context, c access.Caller, id, groupID, role string) (directory.PageAccess, error) + UnsharePage(ctx context.Context, c access.Caller, id, principalType, principalID string) (directory.PageAccess, error) +} + +func (a *api) permissionRoutes(mux *routeMux) { + mux.HandleFunc("GET /api/v1/pages/{id}/access", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + pa, err := a.dir.GetPageAccess(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, pa, err) + })) + mux.HandleFunc("PATCH /api/v1/pages/{id}/access", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in struct{ Restricted bool } + if !a.decode(w, r, &in) { + return + } + pa, err := a.dir.SetPageRestricted(r.Context(), caller(r), r.PathValue("id"), in.Restricted) + a.respond(w, pa, err) + })) + mux.HandleFunc("PUT /api/v1/pages/{id}/access/users", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in struct{ Email, Role string } + if !a.decode(w, r, &in) { + return + } + res, err := a.dir.SharePageWithUser(r.Context(), caller(r), r.PathValue("id"), in.Email, in.Role) + a.respond(w, res, err) + })) + mux.HandleFunc("DELETE /api/v1/pages/{id}/access/users/{userId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + pa, err := a.dir.UnsharePage(r.Context(), caller(r), r.PathValue("id"), "user", r.PathValue("userId")) + a.respond(w, pa, err) + })) + mux.HandleFunc("PUT /api/v1/pages/{id}/access/groups/{groupId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in struct{ Role string } + if !a.decode(w, r, &in) { + return + } + pa, err := a.dir.SharePageWithGroup(r.Context(), caller(r), r.PathValue("id"), r.PathValue("groupId"), in.Role) + a.respond(w, pa, err) + })) + mux.HandleFunc("DELETE /api/v1/pages/{id}/access/groups/{groupId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + pa, err := a.dir.UnsharePage(r.Context(), caller(r), r.PathValue("id"), "group", r.PathValue("groupId")) + a.respond(w, pa, err) + })) +} diff --git a/Web-App/frontend/src/components/PageTreeNode.vue b/Web-App/frontend/src/components/PageTreeNode.vue index e00aacf..b8757ab 100644 --- a/Web-App/frontend/src/components/PageTreeNode.vue +++ b/Web-App/frontend/src/components/PageTreeNode.vue @@ -1,7 +1,7 @@