Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(dss): generic entity permissions endpoint + utils (#1417)

teo04d0ca91b18c
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index cba9ccf66a..e25e86f2d2 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -1,5 +1,6 @@
import { useBlockId } from '@core/block';
import { useChannelName } from '@core/context/channels';
+import { EntityPermissionsGate } from '@core/component/EntityPermissionsGate';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { type JSXElement, onMount, Suspense } from 'solid-js';
import { Channel } from './Channel';
@@ -41,12 +42,14 @@ export default function BlockChannel(props: BlockChannelProps) {
};
return (
- <Suspense fallback={<ChannelBlockSuspenseFallback />}>
- <DocumentBlockContainer title={channelName() ?? 'Channel'}>
- <ChannelContextProvider query={channelQuery}>
- <Channel channelId={channelId} target={targetMessage()} />
- </ChannelContextProvider>
- </DocumentBlockContainer>
- </Suspense>
+ <EntityPermissionsGate entityType="channel" entityId={channelId}>
+ <Suspense fallback={<ChannelBlockSuspenseFallback />}>
+ <DocumentBlockContainer title={channelName() ?? 'Channel'}>
+ <ChannelContextProvider query={channelQuery}>
+ <Channel channelId={channelId} target={targetMessage()} />
+ </ChannelContextProvider>
+ </DocumentBlockContainer>
+ </Suspense>
+ </EntityPermissionsGate>
);
}
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index 31259637ce..eb16231c64 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -1,7 +1,7 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
-import { fetchAndCacheChannel } from '@queries/channel/channel';
+import { ok } from '@core/util/maybeResult';
import ChannelBlock from './component/Block';
+import { fetchAndCacheChannel } from '@queries/channel/channel';
export const definition = defineBlock({
name: 'channel',
@@ -10,27 +10,9 @@ export const definition = defineBlock({
liveTrackingEnabled: true,
async load(source, _intent) {
if (source.type === 'dss') {
- const channel = await fetchAndCacheChannel(source.id);
-
- if (isErr(channel)) {
- if (isErr(channel, 'MISSING')) {
- return LoadErrors.MISSING;
- } else if (isErr(channel, 'UNAUTHORIZED')) {
- return LoadErrors.UNAUTHORIZED;
- } else if (isErr(channel, 'GONE')) {
- return LoadErrors.GONE;
- } else {
- return LoadErrors.INVALID;
- }
- }
-
- const [, channelData] = channel;
-
- return ok({
- ...channelData.channel,
- });
+ await fetchAndCacheChannel(source.id);
+ return ok({ id: source.id });
}
-
return LoadErrors.MISSING;
},
accepted: {},
diff --git a/js/app/packages/core/component/EntityPermissionsGate.tsx b/js/app/packages/core/component/EntityPermissionsGate.tsx
new file mode 100644
index 0000000000..e62f934c40
--- /dev/null
+++ b/js/app/packages/core/component/EntityPermissionsGate.tsx
@@ -0,0 +1,64 @@
+import { useEntityPermissions } from '@queries/entity/permissions';
+import { hasEntityAccess } from '@queries/entity/permissionUtils';
+import { MaybeResultError } from '@core/util/maybeResult';
+import { type FlowProps, Match, Show, Suspense, Switch } from 'solid-js';
+import { LoadingBlock } from './LoadingBlock';
+import Gone from './AccessErrorViews/Gone';
+import NotFound from './AccessErrorViews/NotFound';
+import Unauthorized from './AccessErrorViews/Unauthorized';
+
+function getErrorCode(error: Error | null): string | null {
+ if (error instanceof MaybeResultError) {
+ return error.errors[0]?.code ?? null;
+ }
+ return null;
+}
+
+function PermissionGateInner(
+ props: FlowProps<{ entityType: string; entityId: string }>
+) {
+ const query = useEntityPermissions(
+ () => props.entityType,
+ () => props.entityId
+ );
+
+ const errorCode = () => getErrorCode(query.error);
+
+ return (
+ <Switch
+ fallback={
+ <Show
+ when={query.data && hasEntityAccess(query.data)}
+ fallback={<Unauthorized />}
+ >
+ {props.children}
+ </Show>
+ }
+ >
+ <Match when={errorCode() === 'UNAUTHORIZED'}>
+ <Unauthorized />
+ </Match>
+ <Match when={errorCode() === 'NOT_FOUND'}>
+ <NotFound />
+ </Match>
+ <Match when={errorCode() === 'GONE'}>
+ <Gone />
+ </Match>
+ <Match when={query.error}>
+ <div class="flex flex-col items-center justify-center h-full text-lg">
+ Sorry, an unexpected error has occurred.
+ </div>
+ </Match>
+ </Switch>
+ );
+}
+
+export function EntityPermissionsGate(
+ props: FlowProps<{ entityType: string; entityId: string }>
+) {
+ return (
+ <Suspense fallback={<LoadingBlock />}>
+ <PermissionGateInner {...props} />
+ </Suspense>
+ );
+}
diff --git a/js/app/packages/queries/entity/keys.ts b/js/app/packages/queries/entity/keys.ts
new file mode 100644
index 0000000000..c24b31bfa9
--- /dev/null
+++ b/js/app/packages/queries/entity/keys.ts
@@ -0,0 +1,7 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const entityKeys = createQueryKeys('entity', {
+ permissions: (entityType: string, entityId: string) => ({
+ queryKey: [entityType, entityId],
+ }),
+});
diff --git a/js/app/packages/queries/entity/permissionUtils.ts b/js/app/packages/queries/entity/permissionUtils.ts
new file mode 100644
index 0000000000..3ba1b38da6
--- /dev/null
+++ b/js/app/packages/queries/entity/permissionUtils.ts
@@ -0,0 +1,62 @@
+import type {
+ AccessLevel,
+ EntityPermission,
+ EntityPermissionResponse,
+ ParticipantRole,
+} from '@service-storage/generated/schemas';
+
+type AccessResponse = Extract<EntityPermissionResponse, { status: 'access' }>;
+type AccessLevelPermission = Extract<
+ EntityPermission,
+ { type: 'access_level' }
+>;
+type ChannelRolePermission = Extract<
+ EntityPermission,
+ { type: 'channel_role' }
+>;
+
+export function hasEntityAccess(
+ response: EntityPermissionResponse
+): response is AccessResponse {
+ return response.status === 'access';
+}
+
+export function isAccessLevelPermission(
+ permission: EntityPermission
+): permission is AccessLevelPermission {
+ return permission.type === 'access_level';
+}
+
+export function isChannelRolePermission(
+ permission: EntityPermission
+): permission is ChannelRolePermission {
+ return permission.type === 'channel_role';
+}
+
+export function getEntityAccessLevel(
+ response: EntityPermissionResponse
+): AccessLevel | null {
+ if (!hasEntityAccess(response)) {
+ return null;
+ }
+
+ if (!isAccessLevelPermission(response.permission)) {
+ return null;
+ }
+
+ return response.permission.access_level;
+}
+
+export function getEntityChannelRole(
+ response: EntityPermissionResponse
+): ParticipantRole | null {
+ if (!hasEntityAccess(response)) {
+ return null;
+ }
+
+ if (!isChannelRolePermission(response.permission)) {
+ return null;
+ }
+
+ return response.permission.role;
+}
diff --git a/js/app/packages/queries/entity/permissions.ts b/js/app/packages/queries/entity/permissions.ts
new file mode 100644
index 0000000000..30264de448
--- /dev/null
+++ b/js/app/packages/queries/entity/permissions.ts
@@ -0,0 +1,45 @@
+import {
+ catchToResult,
+ type MaybeResult,
+ throwOnErr,
+} from '@core/util/maybeResult';
+import { dssFetch } from '@service-storage/client';
+import type { EntityPermissionResponse } from '@service-storage/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { entityKeys } from './keys';
+
+function entityPermissionsQueryOptions(entityType: string, entityId: string) {
+ return {
+ queryKey: entityKeys.permissions(entityType, entityId).queryKey,
+ queryFn: async () =>
+ await throwOnErr(
+ async () =>
+ await dssFetch<EntityPermissionResponse>(
+ `/entity/${entityType}/${entityId}/permissions`
+ )
+ ),
+ };
+}
+
+export function useEntityPermissions(
+ entityType: Accessor<string>,
+ entityId: Accessor<string>
+) {
+ return useQuery(() =>
+ entityPermissionsQueryOptions(entityType(), entityId())
+ );
+}
+
+export async function fetchEntityPermissions(
+ entityType: string,
+ entityId: string
+): Promise<MaybeResult<string, EntityPermissionResponse>> {
+ return await catchToResult(
+ async () =>
+ await queryClient.ensureQueryData(
+ entityPermissionsQueryOptions(entityType, entityId)
+ )
+ );
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts
new file mode 100644
index 0000000000..f03596d02f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPermissionOneOf } from './entityPermissionOneOf';
+import type { EntityPermissionOneOfThree } from './entityPermissionOneOfThree';
+
+/**
+ * A user's permission for an entity, discriminated by entity kind.
+
+Items (documents, chats, projects, threads) use access levels.
+Channels use participant roles.
+ */
+export type EntityPermission =
+ | EntityPermissionOneOf
+ | EntityPermissionOneOfThree;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOf.ts
new file mode 100644
index 0000000000..c40c97dd48
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOf.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+import type { EntityPermissionOneOfType } from './entityPermissionOneOfType';
+
+/**
+ * Permission for item-based entities (document, chat, project, thread).
+ */
+export type EntityPermissionOneOf = {
+ /** The access level the user has. */
+ access_level: AccessLevel;
+ type: EntityPermissionOneOfType;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThree.ts
new file mode 100644
index 0000000000..f45c48a0ac
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThree.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { EntityPermissionOneOfThreeType } from './entityPermissionOneOfThreeType';
+import type { ParticipantRole } from './participantRole';
+
+/**
+ * Permission for channel-based entities.
+ */
+export type EntityPermissionOneOfThree = {
+ /** The role the user has in the channel. */
+ role: ParticipantRole;
+ type: EntityPermissionOneOfThreeType;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThreeType.ts
new file mode 100644
index 0000000000..a249195c16
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfThreeType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EntityPermissionOneOfThreeType =
+ (typeof EntityPermissionOneOfThreeType)[keyof typeof EntityPermissionOneOfThreeType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EntityPermissionOneOfThreeType = {
+ channel_role: 'channel_role',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfType.ts
new file mode 100644
index 0000000000..58d1629486
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EntityPermissionOneOfType =
+ (typeof EntityPermissionOneOfType)[keyof typeof EntityPermissionOneOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EntityPermissionOneOfType = {
+ access_level: 'access_level',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponse.ts
new file mode 100644
index 0000000000..14c5a0de4e
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponse.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPermissionResponseOneOf } from './entityPermissionResponseOneOf';
+import type { EntityPermissionResponseOneOfThree } from './entityPermissionResponseOneOfThree';
+
+/**
+ * API response envelope for entity permissions.
+ */
+export type EntityPermissionResponse =
+ | EntityPermissionResponseOneOf
+ | EntityPermissionResponseOneOfThree;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOf.ts
new file mode 100644
index 0000000000..3f0256ea40
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOf.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPermission } from './entityPermission';
+import type { EntityPermissionResponseOneOfStatus } from './entityPermissionResponseOneOfStatus';
+
+export type EntityPermissionResponseOneOf = {
+ permission: EntityPermission;
+ status: EntityPermissionResponseOneOfStatus;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfStatus.ts
new file mode 100644
index 0000000000..0382619e0f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfStatus.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EntityPermissionResponseOneOfStatus =
+ (typeof EntityPermissionResponseOneOfStatus)[keyof typeof EntityPermissionResponseOneOfStatus];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EntityPermissionResponseOneOfStatus = {
+ access: 'access',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThree.ts
new file mode 100644
index 0000000000..2bf6586c32
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThree.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPermissionResponseOneOfThreeStatus } from './entityPermissionResponseOneOfThreeStatus';
+
+export type EntityPermissionResponseOneOfThree = {
+ status: EntityPermissionResponseOneOfThreeStatus;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThreeStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThreeStatus.ts
new file mode 100644
index 0000000000..a56be24aa6
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionResponseOneOfThreeStatus.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EntityPermissionResponseOneOfThreeStatus =
+ (typeof EntityPermissionResponseOneOfThreeStatus)[keyof typeof EntityPermissionResponseOneOfThreeStatus];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EntityPermissionResponseOneOfThreeStatus = {
+ no_access: 'no_access',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index a3f3377ddc..12a2e8e29c 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -236,6 +236,16 @@ export * from './emailFilters';
export * from './emailFiltersImportance';
export * from './emptyResponse';
export * from './entityFilters';
+export * from './entityPermission';
+export * from './entityPermissionOneOf';
+export * from './entityPermissionOneOfThree';
+export * from './entityPermissionOneOfThreeType';
+export * from './entityPermissionOneOfType';
+export * from './entityPermissionResponse';
+export * from './entityPermissionResponseOneOf';
+export * from './entityPermissionResponseOneOfStatus';
+export * from './entityPermissionResponseOneOfThree';
+export * from './entityPermissionResponseOneOfThreeStatus';
export * from './entityReference';
export * from './entityReferenceSpecificMessageId';
export * from './entityType';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts b/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
index c1dd0595a7..0d03c96e96 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
@@ -5,6 +5,9 @@
* OpenAPI spec version: 0.1.0
*/
+/**
+ * The role a user has within a channel.
+ */
export type ParticipantRole =
(typeof ParticipantRole)[keyof typeof ParticipantRole];
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index a8d464920f..85fb90bce5 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -2144,6 +2144,53 @@ export const getDocumentVersionResponse = zod.object({
error: zod.boolean().describe('Indicates if an error occurred'),
});
+/**
+ * @summary Get the current user's permission for a given entity.
+ */
+export const getEntityPermissionParams = zod.object({
+ entity_type: zod
+ .string()
+ .describe(
+ 'Entity type (document, chat, project, thread, email_thread, channel)'
+ ),
+ entity_id: zod.string().describe('Entity ID'),
+});
+
+export const getEntityPermissionResponse = zod
+ .union([
+ zod.object({
+ permission: zod
+ .union([
+ zod
+ .object({
+ access_level: zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ type: zod.enum(['access_level']),
+ })
+ .describe(
+ 'Permission for item-based entities (document, chat, project, thread).'
+ ),
+ zod
+ .object({
+ role: zod
+ .enum(['owner', 'admin', 'member'])
+ .describe('The role a user has within a channel.'),
+ type: zod.enum(['channel_role']),
+ })
+ .describe('Permission for channel-based entities.'),
+ ])
+ .describe(
+ "A user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use participant roles."
+ ),
+ status: zod.enum(['access']),
+ }),
+ zod.object({
+ status: zod.enum(['no_access']),
+ }),
+ ])
+ .describe('API response envelope for entity permissions.');
+
/**
* @summary Gets the users history
*/
@@ -3446,7 +3493,9 @@ export const getItemsSoupResponse = zod.object({
channel_id: zod.string().uuid(),
joined_at: zod.string().datetime({}),
left_at: zod.string().datetime({}).nullish(),
- role: zod.enum(['owner', 'admin', 'member']),
+ role: zod
+ .enum(['owner', 'admin', 'member'])
+ .describe('The role a user has within a channel.'),
user_id: zod.string(),
})
),
@@ -4851,7 +4900,9 @@ export const postItemsSoupResponse = zod.object({
channel_id: zod.string().uuid(),
joined_at: zod.string().datetime({}),
left_at: zod.string().datetime({}).nullish(),
- role: zod.enum(['owner', 'admin', 'member']),
+ role: zod
+ .enum(['owner', 'admin', 'member'])
+ .describe('The role a user has within a channel.'),
user_id: zod.string(),
})
),
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index ed18272508..9248e076a7 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -2095,6 +2095,54 @@
}
}
},
+ "/entity/{entity_type}/{entity_id}/permissions": {
+ "get": {
+ "tags": ["entity::get_entity_permission"],
+ "summary": "Get the current user's permission for a given entity.",
+ "operationId": "get_entity_permission",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Entity type (document, chat, project, thread, email_thread, channel)",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "Entity ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EntityPermissionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request"
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "404": {
+ "description": "Entity not found"
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["health"],
@@ -6089,6 +6137,69 @@
}
}
},
+ "EntityPermission": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Permission for item-based entities (document, chat, project, thread).",
+ "required": ["access_level", "type"],
+ "properties": {
+ "access_level": {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The access level the user has."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["access_level"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Permission for channel-based entities.",
+ "required": ["role", "type"],
+ "properties": {
+ "role": {
+ "$ref": "#/components/schemas/ParticipantRole",
+ "description": "The role the user has in the channel."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["channel_role"]
+ }
+ }
+ }
+ ],
+ "description": "A user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use participant roles."
+ },
+ "EntityPermissionResponse": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": ["permission", "status"],
+ "properties": {
+ "permission": {
+ "$ref": "#/components/schemas/EntityPermission"
+ },
+ "status": {
+ "type": "string",
+ "enum": ["access"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": ["status"],
+ "properties": {
+ "status": {
+ "type": "string",
+ "enum": ["no_access"]
+ }
+ }
+ }
+ ],
+ "description": "API response envelope for entity permissions."
+ },
"EntityReference": {
"type": "object",
"description": "Entity reference for entity-type property values.",
@@ -6891,6 +7002,7 @@
},
"ParticipantRole": {
"type": "string",
+ "description": "The role a user has within a channel.",
"enum": ["owner", "admin", "member"]
},
"PatchProjectRequestV2": {
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index ec765a3771..983f441153 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2707,6 +2707,7 @@ dependencies = [
"document_sub_type",
"dynamodb_client",
"email",
+ "entity_access",
"frecency",
"futures",
"hex",
@@ -3304,6 +3305,7 @@ dependencies = [
"thiserror 2.0.17",
"tokio",
"tracing",
+ "utoipa",
"uuid",
]
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 52dd57e508..b7b513b0d8 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -48,6 +48,7 @@ comms = { path = "../comms", features = ["outbound"] }
connection_gateway = { path = "../connection_gateway" }
document_sub_type = { path = "../document_sub_type" }
dynamodb_client = { path = "../dynamodb_client" }
+entity_access = { path = "../entity_access", features = ["schema"] }
email = { path = "../email", features = ["outbound", "ports"] }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 67234e6896..82e3f22495 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -9,6 +9,7 @@ use comms_service::CommsHandlerState;
use connection_gateway_client::client::ConnectionGatewayClient;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_env_var::env_var;
@@ -55,6 +56,9 @@ type PropertiesService = PropertiesServiceImpl<
NotificationServiceImpl<NotificationIngressType>,
>;
+/// Type alias for the entity access service.
+pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+
/// Type alias for the ChannelServiceImpl used by comms
pub(crate) type CommsChannelService =
ChannelServiceImpl<PgCommsRepo, UserRepoImpl, FrecencyPgStorage>;
@@ -85,6 +89,7 @@ pub(crate) struct ApiContext {
pub comms_state: CommsState,
pub permissions_token_secret:
LocalOrRemoteSecret<comms_service::DocumentPermissionJwtSecretKey>,
+ pub entity_access_service: Arc<EntityAccessService>,
}
env_var! {
diff --git a/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs b/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs
new file mode 100644
index 0000000000..b5f952b245
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs
@@ -0,0 +1,50 @@
+use crate::api::context::EntityAccessService;
+use axum::{Json, http::StatusCode, response::IntoResponse};
+use entity_access::{
+ domain::models::EntityPermission,
+ inbound::axum_extractors::{EntityPermissionExtractor, ExtractorError},
+};
+use serde::Serialize;
+use utoipa::ToSchema;
+
+/// API response envelope for entity permissions.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(tag = "status", rename_all = "snake_case")]
+pub enum EntityPermissionResponse {
+ Access { permission: EntityPermission },
+ NoAccess,
+}
+
+/// Get the current user's permission for a given entity.
+#[utoipa::path(
+ get,
+ path = "/entity/{entity_type}/{entity_id}/permissions",
+ operation_id = "get_entity_permission",
+ params(
+ ("entity_type" = String, Path, description = "Entity type (document, chat, project, thread, email_thread, channel)"),
+ ("entity_id" = String, Path, description = "Entity ID"),
+ ),
+ responses(
+ (status = 200, body = EntityPermissionResponse),
+ (status = 400, description = "Bad request"),
+ (status = 401, description = "Unauthorized"),
+ (status = 404, description = "Entity not found"),
+ )
+)]
+pub async fn handler(
+ result: Result<EntityPermissionExtractor<EntityAccessService>, ExtractorError>,
+) -> impl IntoResponse {
+ match result {
+ Ok(ext) => (
+ StatusCode::OK,
+ Json(EntityPermissionResponse::Access {
+ permission: ext.permission,
+ }),
+ )
+ .into_response(),
+ Err(ExtractorError::Unauthorized | ExtractorError::UnauthorizedWithMessage(_)) => {
+ (StatusCode::OK, Json(EntityPermissionResponse::NoAccess)).into_response()
+ }
+ Err(e) => e.into_response(),
+ }
+}
diff --git a/rust/cloud-storage/document_storage_service/src/api/entity/mod.rs b/rust/cloud-storage/document_storage_service/src/api/entity/mod.rs
new file mode 100644
index 0000000000..5f8b031a26
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/api/entity/mod.rs
@@ -0,0 +1,11 @@
+pub mod get_entity_permission;
+
+use crate::api::context::ApiContext;
+use axum::{Router, routing::get};
+
+pub fn router() -> Router<ApiContext> {
+ Router::new().route(
+ "/:entity_type/:entity_id/permissions",
+ get(get_entity_permission::handler),
+ )
+}
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 553f687a0b..00e1483043 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -40,6 +40,7 @@ mod recents;
mod user;
mod user_document_view_location;
+mod entity;
mod items;
mod permissions;
pub(crate) mod swagger;
@@ -165,6 +166,7 @@ fn api_router(state: ApiContext) -> Router {
comms_service::comms_router(&CommsHandlerState::from_ref(&state))
.with_state(CommsHandlerState::from_ref(&state)),
)
+ .nest("/entity", entity::router())
.layer(
ServiceBuilder::new()
.layer(axum::middleware::from_fn(
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 718cf6a682..1671ee78d1 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -18,7 +18,7 @@ use crate::{
validate_permissions_token::DocumentPermissionsTokenRequest,
},
},
- health, history, instructions, pins,
+ entity, health, history, instructions, pins,
projects::{
self,
delete_project::{ProjectDeleteResponse, ProjectDeleteResponseData},
@@ -203,6 +203,8 @@ use utoipa::OpenApi;
// threads
threads::edit_thread::edit_thread_handler,
+ entity::get_entity_permission::handler,
+
// /recents
recents::recently_deleted::handler,
saved_views::create_view_handler,
@@ -305,6 +307,9 @@ use utoipa::OpenApi;
models_permissions::share_permission::UpdateSharePermissionRequestV2, // Share permission
models_permissions::share_permission::channel_share_permission::ChannelSharePermission,
models_permissions::share_permission::channel_share_permission::UpdateChannelSharePermission, // Channel share permissions
+ entity::get_entity_permission::EntityPermissionResponse,
+ entity_access::domain::models::EntityPermission,
+ entity_access::domain::models::ParticipantRole,
// Chat
Chat,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 7b7725a851..77f6e43c5d 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -274,6 +274,11 @@ async fn main() -> anyhow::Result<()> {
frecency_storage,
comms_state,
permissions_token_secret: comms_permissions_token_secret,
+ entity_access_service: Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(db.clone()),
+ ),
+ ),
};
api::setup_and_serve(api_context).await?;
diff --git a/rust/cloud-storage/entity_access/Cargo.toml b/rust/cloud-storage/entity_access/Cargo.toml
index e905175d51..0f3305e8f5 100644
--- a/rust/cloud-storage/entity_access/Cargo.toml
+++ b/rust/cloud-storage/entity_access/Cargo.toml
@@ -9,6 +9,7 @@ default = ["ports", "inbound", "outbound", "axum"]
ports = ["dep:tokio"]
inbound = ["axum", "ports"]
outbound = ["ports"]
+schema = ["dep:utoipa"]
axum = [
"dep:axum",
"dep:axum-extra",
@@ -41,6 +42,9 @@ model = { path = "../model", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
model-error-response = { path = "../model-error-response", optional = true }
+# OpenAPI schema (optional)
+utoipa = { workspace = true, optional = true }
+
# Database
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index dfb11ccc3f..43b760eb75 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -1,8 +1,58 @@
//! Domain models for entity access.
+use serde::{Deserialize, Serialize};
+
pub use model_entity::EntityType;
pub use models_permissions::share_permission::access_level::AccessLevel;
+/// The role a user has within a channel.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum ParticipantRole {
+ /// Channel owner with full control.
+ Owner,
+ /// Channel administrator.
+ Admin,
+ /// Regular channel member.
+ #[default]
+ Member,
+}
+
+/// A user's permission for an entity, discriminated by entity kind.
+///
+/// Items (documents, chats, projects, threads) use access levels.
+/// Channels use participant roles.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum EntityPermission {
+ /// Permission for item-based entities (document, chat, project, thread).
+ AccessLevel {
+ /// The access level the user has.
+ access_level: AccessLevel,
+ },
+ /// Permission for channel-based entities.
+ ChannelRole {
+ /// The role the user has in the channel.
+ role: ParticipantRole,
+ },
+}
+
+/// Result of resolving a user's role in a channel.
+///
+/// Distinguishes between "user has a role", "channel exists but user
+/// has no access", and "channel does not exist" — all from a single query.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ChannelRoleResult {
+ /// User has a role in the channel.
+ Role(ParticipantRole),
+ /// Channel exists but user has no access.
+ NoAccess,
+ /// Channel does not exist.
+ NotFound,
+}
+
/// Errors that can occur during access checking.
#[derive(Debug, thiserror::Error)]
pub enum AccessError {
@@ -22,6 +72,10 @@ pub enum AccessError {
#[error("Bad request: {0}")]
BadRequest(&'static str),
+ /// Requested resource was not found.
+ #[error("Not found: {0}")]
+ NotFound(&'static str),
+
/// Internal server error.
#[error("Internal error")]
Internal,
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index e137dffadb..c41037f434 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -3,7 +3,7 @@
//! These traits define the contracts that adapters must implement.
use super::models::EntityType;
-use crate::domain::models::{AccessError, AccessLevel};
+use crate::domain::models::{AccessError, AccessLevel, ChannelRoleResult, EntityPermission};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use std::future::Future;
use uuid::Uuid;
@@ -61,6 +61,19 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'_>>,
channel_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;
+
+ /// Get the user's role in a channel.
+ ///
+ /// Returns a [`ChannelRoleResult`] that distinguishes between:
+ /// - User has a role (considering channel type rules)
+ /// - Channel exists but user has no access
+ /// - Channel does not exist
+ fn get_channel_role(
+ &self,
+ channel_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ ) -> impl Future<Output = Result<ChannelRoleResult, AccessError>> + Send;
}
/// Service for checking entity access levels.
@@ -88,4 +101,18 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
entity_type: EntityType,
required_level: AccessLevel,
) -> impl Future<Output = Result<AccessLevel, AccessError>> + Send;
+
+ /// Get the user's permission for an entity.
+ ///
+ /// Returns `EntityPermission::AccessLevel` for items (documents, chats, projects, threads)
+ /// and `EntityPermission::ChannelRole` for channels.
+ ///
+ /// Returns `AccessError::Unauthorized` if the user has no access.
+ fn get_entity_permission(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ user_org_id: Option<i64>,
+ ) -> impl Future<Output = Result<EntityPermission, AccessError>> + Send;
}
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 2a7669a93d..d7be83b1f1 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -1,7 +1,7 @@
//! Entity access service implementation.
use crate::domain::{
- models::{AccessError, AccessLevel, EntityType},
+ models::{AccessError, AccessLevel, ChannelRoleResult, EntityPermission, EntityType},
ports::{AccessRepository, EntityAccessService},
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
@@ -112,6 +112,47 @@ where
None => Err(AccessError::Unauthorized),
}
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_entity_permission(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ match entity_type {
+ EntityType::Document
+ | EntityType::Chat
+ | EntityType::Project
+ | EntityType::EmailThread => {
+ let access = self
+ .get_optimized_access(entity_id, user_id, entity_type)
+ .await?;
+ match access {
+ Some(level) => Ok(EntityPermission::AccessLevel {
+ access_level: level,
+ }),
+ None => Err(AccessError::Unauthorized),
+ }
+ }
+ EntityType::Channel => {
+ let channel_uuid = Uuid::from_str(entity_id)
+ .map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
+
+ match self
+ .repo
+ .get_channel_role(&channel_uuid, user_id, user_org_id)
+ .await?
+ {
+ ChannelRoleResult::Role(role) => Ok(EntityPermission::ChannelRole { role }),
+ ChannelRoleResult::NoAccess => Err(AccessError::Unauthorized),
+ ChannelRoleResult::NotFound => Err(AccessError::NotFound("Channel not found")),
+ }
+ }
+ _ => Err(AccessError::BadRequest("Unsupported entity type")),
+ }
+ }
}
#[cfg(test)]
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
index a65c984d63..9d9cf0d881 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -1,6 +1,7 @@
//! Unit tests for the EntityAccessService.
use super::*;
+use crate::domain::models::ParticipantRole;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
use tokio::sync::Mutex;
@@ -13,6 +14,7 @@ struct MockRepo {
project_access: Arc<Mutex<Option<AccessLevel>>>,
thread_access: Arc<Mutex<Option<AccessLevel>>>,
channel_membership: Arc<Mutex<Vec<Uuid>>>,
+ channel_role: Arc<Mutex<ChannelRoleResult>>,
}
impl MockRepo {
@@ -23,6 +25,7 @@ impl MockRepo {
project_access: Arc::new(Mutex::new(None)),
thread_access: Arc::new(Mutex::new(None)),
channel_membership: Arc::new(Mutex::new(vec![])),
+ channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
}
}
@@ -50,6 +53,11 @@ impl MockRepo {
self.channel_membership = Arc::new(Mutex::new(channels));
self
}
+
+ fn with_channel_role(mut self, result: ChannelRoleResult) -> Self {
+ self.channel_role = Arc::new(Mutex::new(result));
+ self
+ }
}
impl AccessRepository for MockRepo {
@@ -92,6 +100,15 @@ impl AccessRepository for MockRepo {
) -> Result<Vec<Uuid>, AccessError> {
Ok(self.channel_membership.lock().await.clone())
}
+
+ async fn get_channel_role(
+ &self,
+ _channel_id: &Uuid,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ ) -> Result<ChannelRoleResult, AccessError> {
+ Ok(*self.channel_role.lock().await)
+ }
}
fn test_user_id() -> MacroUserIdStr<'static> {
@@ -259,3 +276,123 @@ async fn test_unsupported_entity_type_returns_none() {
.await;
assert_eq!(result.unwrap(), None);
}
+
+// --- get_entity_permission tests ---
+
+#[tokio::test]
+async fn test_get_entity_permission_document_returns_access_level() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(&user_id, "doc-1", EntityType::Document, None)
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ result,
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ ));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_document_no_access_returns_unauthorized() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(&user_id, "doc-1", EntityType::Document, None)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_channel_returns_role() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(
+ &user_id,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ result,
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Admin
+ }
+ ));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_channel_no_access_returns_unauthorized() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NoAccess);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(
+ &user_id,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ None,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_channel_not_found_returns_not_found() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NotFound);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(
+ &user_id,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ None,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::NotFound(_))));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_invalid_channel_uuid_returns_bad_request() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(&user_id, "not-a-uuid", EntityType::Channel, None)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_unsupported_type_returns_bad_request() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(&user_id, "email-1", EntityType::Email, None)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs
new file mode 100644
index 0000000000..d33e117b9e
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs
@@ -0,0 +1,88 @@
+//! Generic entity permission extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+
+use super::ExtractorError;
+use crate::domain::{
+ models::{EntityPermission, EntityType},
+ ports::EntityAccessService,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Path parameters for entity permission routes.
+#[derive(serde::Deserialize)]
+struct EntityPermissionParams {
+ entity_type: String,
+ entity_id: String,
+}
+
+/// Extracts the user's [`EntityPermission`] for a given entity.
+///
+/// Reads `{entity_type}` and `{entity_id}` from path parameters and resolves
+/// the user's permission via `EntityAccessService::get_entity_permission`.
+#[derive(Debug)]
+pub struct EntityPermissionExtractor<Svc> {
+ /// The resolved permission.
+ pub permission: EntityPermission,
+ _marker: PhantomData<Svc>,
+}
+
+#[async_trait]
+impl<S, Svc> FromRequestParts<S> for EntityPermissionExtractor<Svc>
+where
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(parts, state))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let Path(EntityPermissionParams {
+ entity_type,
+ entity_id,
+ }) = <Path<EntityPermissionParams>>::from_request_parts(parts, state)
+ .await
+ .map_err(|_| ExtractorError::BadRequest("Missing entity_type or entity_id in path"))?;
+
+ let parsed_type = parse_entity_type(&entity_type)?;
+ let user_org_id = user_context.organization_id.map(|id| id as i64);
+
+ let permission = service
+ .get_entity_permission(&macro_user_id, &entity_id, parsed_type, user_org_id)
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ permission,
+ _marker: PhantomData,
+ })
+ }
+}
+
+/// Parse entity type string to [`EntityType`], handling the "email_thread" → "thread" alias.
+fn parse_entity_type(s: &str) -> Result<EntityType, ExtractorError> {
+ // "thread" in the API maps to EmailThread
+ let normalized = if s == "thread" { "email_thread" } else { s };
+ normalized
+ .parse()
+ .map_err(|_| ExtractorError::BadRequest("Invalid entity type"))
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
index f2ce993bc5..9c582f5f31 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -5,12 +5,14 @@
mod chat;
mod document;
+mod entity_permission;
mod history;
mod project;
mod thread;
pub use chat::ChatAccessLevelExtractor;
pub use document::DocumentAccessExtractor;
+pub use entity_permission::EntityPermissionExtractor;
pub use history::HistoryAccessExtractor;
pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractor};
pub use thread::ThreadAccessLevelExtractor;
@@ -70,6 +72,10 @@ pub enum ExtractorError {
#[error("Bad request: {0}")]
BadRequest(&'static str),
+ /// Requested resource was not found.
+ #[error("Not found: {0}")]
+ NotFound(&'static str),
+
/// Internal server error.
#[error("Internal server error")]
Internal,
@@ -87,6 +93,7 @@ impl From<AccessError> for ExtractorError {
ExtractorError::UnauthorizedWithMessage(msg)
}
AccessError::BadRequest(msg) => ExtractorError::BadRequest(msg),
+ AccessError::NotFound(msg) => ExtractorError::NotFound(msg),
AccessError::DatabaseError(_) => ExtractorError::Database,
AccessError::Internal => ExtractorError::Internal,
}
@@ -101,6 +108,7 @@ impl IntoResponse for ExtractorError {
(StatusCode::UNAUTHORIZED, self.to_string())
}
ExtractorError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
+ ExtractorError::NotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
ExtractorError::Internal | ExtractorError::Database => {
(StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
index bf0b901872..533ee8b8bb 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -3,7 +3,7 @@
mod queries;
use crate::domain::{
- models::{AccessError, AccessLevel},
+ models::{AccessError, AccessLevel, ChannelRoleResult},
ports::AccessRepository,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
@@ -75,4 +75,20 @@ impl AccessRepository for PgAccessRepository {
)
.await?)
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_channel_role(
+ &self,
+ channel_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ ) -> Result<ChannelRoleResult, AccessError> {
+ Ok(queries::channel_role::get_channel_role(
+ &self.pool,
+ channel_id,
+ user_id.as_ref(),
+ user_org_id,
+ )
+ .await?)
+ }
}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
new file mode 100644
index 0000000000..dc552ce68a
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
@@ -0,0 +1,91 @@
+//! Queries for channel role resolution.
+
+use crate::domain::models::{ChannelRoleResult, ParticipantRole};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Row returned from the channel role query.
+#[derive(sqlx::FromRow)]
+struct ChannelRoleRow {
+ role: Option<String>,
+ channel_type: String,
+ org_id: Option<i64>,
+}
+
+/// Parse a participant role string from the database.
+fn parse_role(s: &str) -> ParticipantRole {
+ match s {
+ "owner" => ParticipantRole::Owner,
+ "admin" => ParticipantRole::Admin,
+ _ => ParticipantRole::Member,
+ }
+}
+
+/// Get the user's role in a channel, considering channel type rules.
+///
+/// Returns a [`ChannelRoleResult`] that distinguishes between:
+/// - `Role(role)`: user has access with this role
+/// - `NoAccess`: channel exists but user has no access
+/// - `NotFound`: channel does not exist
+///
+/// Channel type rules:
+/// - Public channels: non-participants default to Member
+/// - Organization channels: default to Member only if user's org matches
+/// - Private/DM: require explicit participation
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_channel_role(
+ pool: &PgPool,
+ channel_id: &Uuid,
+ user_id: &str,
+ user_org_id: Option<i64>,
+) -> Result<ChannelRoleResult, sqlx::Error> {
+ let row = sqlx::query_as::<_, ChannelRoleRow>(
+ r#"
+ SELECT
+ cp.role::text as role,
+ c.channel_type::text as channel_type,
+ c.org_id
+ FROM comms_channels c
+ LEFT JOIN comms_channel_participants cp
+ ON cp.channel_id = c.id AND cp.user_id = $2 AND cp.left_at IS NULL
+ WHERE c.id = $1
+ "#,
+ )
+ .bind(channel_id)
+ .bind(user_id)
+ .fetch_optional(pool)
+ .await?;
+
+ let Some(row) = row else {
+ return Ok(ChannelRoleResult::NotFound);
+ };
+
+ let role = match row.channel_type.as_str() {
+ "public" => Some(
+ row.role
+ .as_deref()
+ .map_or(ParticipantRole::Member, parse_role),
+ ),
+ "organization" => {
+ let org_match = user_org_id
+ .zip(row.org_id)
+ .is_some_and(|(user_org, ch_org)| user_org == ch_org);
+
+ if org_match {
+ Some(
+ row.role
+ .as_deref()
+ .map_or(ParticipantRole::Member, parse_role),
+ )
+ } else {
+ row.role.as_deref().map(parse_role)
+ }
+ }
+ _ => row.role.as_deref().map(parse_role),
+ };
+
+ Ok(match role {
+ Some(role) => ChannelRoleResult::Role(role),
+ None => ChannelRoleResult::NoAccess,
+ })
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
index 0e27fa840a..a3a087e361 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
@@ -3,6 +3,7 @@
//! Each module contains a single query function for checking access to a specific entity type.
pub mod channel_membership;
+pub mod channel_role;
pub mod chat_access;
pub mod document_access;
pub mod project_access;