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.

fix(permissions): fix public link sharing of docs (#1200)

teob9f58e91091f
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index 3df71310f1..78bbea4e21 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -37,6 +37,7 @@ import { invalidateEntityNotifications } from '@queries/notification/user-notifi
import { storageServiceClient } from '@service-storage/client';
import { createElementSize } from '@solid-primitives/resize-observer';
import { Navigate } from '@solidjs/router';
+import { globalSplitManager } from '@app/signal/splitLayout';
import { useMutation, useQueryClient } from '@tanstack/solid-query';
import { registerHotkey } from 'core/hotkey/hotkeys';
import {
@@ -614,6 +615,13 @@ const ViewWithSearch: Component<{
export function Soup() {
const isAuthenticated = useIsAuthenticated();
+ // NOTE: if trying to access a split in which we are looking at a document, we shouldn't redirect away.
+ const hasDocumentSplit = createMemo(() => {
+ const manager = globalSplitManager();
+ if (!manager) return false;
+ return manager.splits().some((split) => split.content.type !== 'component');
+ });
+
const splitPanelContext = useSplitPanelOrThrow();
const {
handle,
@@ -704,7 +712,10 @@ export function Soup() {
});
return (
- <Show when={isAuthenticated() !== false} fallback={<Navigate href="/" />}>
+ <Show
+ when={isAuthenticated() !== false || hasDocumentSplit()}
+ fallback={<Navigate href="/" />}
+ >
<div
class="relative flex flex-col bg-panel size-full"
use:fileFolderDrop={{
diff --git a/js/app/packages/block-unknown/component/Block.tsx b/js/app/packages/block-unknown/component/Block.tsx
index a0c052c568..08d78d0e8e 100644
--- a/js/app/packages/block-unknown/component/Block.tsx
+++ b/js/app/packages/block-unknown/component/Block.tsx
@@ -1,4 +1,4 @@
-import { useBlockId } from '@core/block';
+import { useBlockAliasedName, useBlockId } from '@core/block';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { getPermissions, Permissions } from '@core/component/SharePermissions';
@@ -35,6 +35,7 @@ const Unknown = () => {
const documentId = useBlockId();
const fileName = useBlockDocumentName();
const downloadName = useBlockDocumentDownloadName();
+ const blockAlias = useBlockAliasedName();
const [isSharePermOpen, setIsSharePermOpen] = createSignal(false);
const getBlob = useGetFileBlob();
@@ -85,6 +86,7 @@ const Unknown = () => {
userPermissions={userPermissions()}
itemType="document"
isSharePermOpen={isSharePermOpen()}
+ blockAlias={blockAlias}
setIsSharePermOpen={setIsSharePermOpen}
/>
</div>
diff --git a/js/app/packages/core/component/TopBar/ShareButton.tsx b/js/app/packages/core/component/TopBar/ShareButton.tsx
index 0f7fa124bd..7e828c3f53 100644
--- a/js/app/packages/core/component/TopBar/ShareButton.tsx
+++ b/js/app/packages/core/component/TopBar/ShareButton.tsx
@@ -2,6 +2,8 @@ import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { useIsAuthenticated } from '@core/auth';
import {
+ type BlockAlias,
+ type BlockName,
createBlockEffect,
createBlockResource,
useBlockAliasedName,
@@ -135,6 +137,7 @@ interface ShareModalProps {
setIsSharePermOpen: (value: boolean) => void;
userPermissions: Permissions;
isSharePermOpen: boolean;
+ blockAlias: BlockName | BlockAlias;
itemType: ItemType;
owner?: string;
name: string;
@@ -150,7 +153,7 @@ export function ShareModal(props: ShareModalProps) {
const copyPublicLink = createCallback(() => {
const url = buildSimpleEntityUrl(
{
- type: props.itemType,
+ type: props.blockAlias,
id: props.id,
},
{}
@@ -769,6 +772,7 @@ export function ShareButton(props: ShareButtonProps) {
itemType={props.itemType}
owner={props.owner}
name={props.name}
+ blockAlias={blockType}
id={props.id}
/>
</>
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a5ae819da3..5d8c1157e2 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5076,6 +5076,7 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"model",
+ "model-entity",
"model_user",
"models_permissions",
"permission",
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json b/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json
index a1c4c0d402..aa9502aa59 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json
@@ -37,9 +37,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json b/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json
index 6c17e2c89d..4860ae3ec1 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json
@@ -22,9 +22,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json b/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json
index 602ce4228d..69cb81d4c7 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json
@@ -15,9 +15,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json b/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json
index 51a42b64cb..daf0b4f790 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json
@@ -37,9 +37,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-5abca30105f179742a58a602030a033a255c6eb5c9ba657c4038072f974aaeaa.json b/rust/cloud-storage/macro_db_client/.sqlx/query-5abca30105f179742a58a602030a033a255c6eb5c9ba657c4038072f974aaeaa.json
new file mode 100644
index 0000000000..ba88817811
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-5abca30105f179742a58a602030a033a255c6eb5c9ba657c4038072f974aaeaa.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id\n AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "5abca30105f179742a58a602030a033a255c6eb5c9ba657c4038072f974aaeaa"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-87877cda339e72a128639a459295ce165cd096206e1f17f3fa5e98c27508095f.json b/rust/cloud-storage/macro_db_client/.sqlx/query-87877cda339e72a128639a459295ce165cd096206e1f17f3fa5e98c27508095f.json
new file mode 100644
index 0000000000..388063d666
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-87877cda339e72a128639a459295ce165cd096206e1f17f3fa5e98c27508095f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id\n AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "87877cda339e72a128639a459295ce165cd096206e1f17f3fa5e98c27508095f"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-aeaa28037abd84dfb5393969479d30335566b4207d7e9af61c00d31abea4a790.json b/rust/cloud-storage/macro_db_client/.sqlx/query-aeaa28037abd84dfb5393969479d30335566b4207d7e9af61c00d31abea4a790.json
new file mode 100644
index 0000000000..b41f112c69
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-aeaa28037abd84dfb5393969479d30335566b4207d7e9af61c00d31abea4a790.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id\n AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "aeaa28037abd84dfb5393969479d30335566b4207d7e9af61c00d31abea4a790"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json b/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json
index 4235a97747..78eac67010 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json
@@ -37,9 +37,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json b/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json
index 12ed677b43..a427d7bdea 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json
@@ -13,9 +13,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-d5f7d33eed11e9b58ca5b830b806700d28c3d345b03bddf1e5a290f84072571d.json b/rust/cloud-storage/macro_db_client/.sqlx/query-d5f7d33eed11e9b58ca5b830b806700d28c3d345b03bddf1e5a290f84072571d.json
new file mode 100644
index 0000000000..32802bab4c
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-d5f7d33eed11e9b58ca5b830b806700d28c3d345b03bddf1e5a290f84072571d.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id\n AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "d5f7d33eed11e9b58ca5b830b806700d28c3d345b03bddf1e5a290f84072571d"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json b/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json
index 02598512d9..6c9131a493 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json
@@ -37,9 +37,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json b/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json
index 055f08f556..a3c1720287 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json
@@ -13,9 +13,9 @@
"kind": {
"Enum": [
"view",
- "comment",
"edit",
- "owner"
+ "owner",
+ "comment"
]
}
}
diff --git a/rust/cloud-storage/macro_db_client/justfile b/rust/cloud-storage/macro_db_client/justfile
index 7dc72ce2e2..3f5fe03ce1 100644
--- a/rust/cloud-storage/macro_db_client/justfile
+++ b/rust/cloud-storage/macro_db_client/justfile
@@ -18,6 +18,10 @@ create_db:
prepare_db:
just sqlx::prepare_db {{ DATABASE_URL }}
+# Prepare DB for offline cache against dev database
+prepare_db_dev:
+ just sqlx::prepare_db $(../scripts/rds_database_url.sh macro-db-dev macrodb-password-dev macrodb)
+
migrate_db:
just sqlx::migrate_db {{ DATABASE_URL }}
diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs
index 2422e3b186..534c2408c0 100644
--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs
+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs
@@ -2,6 +2,65 @@ use models_permissions::share_permission::access_level::AccessLevel;
use std::collections::HashMap;
use std::str::FromStr;
+/// Gets the public access level for a chat (no user required).
+///
+/// This function checks only public `SharePermission` records (where `isPublic=true`),
+/// applied either directly to the chat or inherited from its project hierarchy.
+/// It does NOT check user-specific `UserItemAccess` records.
+///
+/// Use this for unauthenticated access to publicly shared chats.
+///
+/// # Arguments
+/// * `db` - A reference to the `sqlx` database connection pool.
+/// * `chat_id` - The ID of the chat to check.
+///
+/// # Returns
+/// A `Result` containing an `Option<AccessLevel>`:
+/// - `Ok(Some(AccessLevel))` if there is public access.
+/// - `Ok(None)` if there is no public access.
+/// - `Err(_)` if a database error occurs.
+#[tracing::instrument(skip(db), err)]
+pub async fn get_public_access_level_for_chat(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ chat_id: &str,
+) -> anyhow::Result<Option<AccessLevel>> {
+ let public_levels: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ WITH RECURSIVE project_hierarchy AS (
+ SELECT p.id as project_id
+ FROM "Chat" c
+ JOIN "Project" p ON c."projectId" = p.id AND p."deletedAt" IS NULL
+ WHERE c.id = $1 AND c."deletedAt" IS NULL
+ UNION ALL
+ SELECT parent.id as project_id
+ FROM project_hierarchy ph
+ JOIN "Project" parent ON parent.id = (
+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id
+ AND "parentId" IS NOT NULL AND "deletedAt" IS NULL
+ )
+ )
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission"
+ WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ "#,
+ chat_id
+ )
+ .fetch_all(db)
+ .await?;
+
+ let highest_level = public_levels
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
+
/// Calculates the highest effective access level a user has for a chat.
///
/// This function determines the best possible permission by considering two sources:
diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs
index 639ee773cd..018157ffe9 100644
--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs
+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs
@@ -1,6 +1,65 @@
use models_permissions::share_permission::access_level::AccessLevel;
use std::str::FromStr;
+/// Gets the public access level for a document (no user required).
+///
+/// This function checks only public `SharePermission` records (where `isPublic=true`),
+/// applied either directly to the document or inherited from its project hierarchy.
+/// It does NOT check user-specific `UserItemAccess` records.
+///
+/// Use this for unauthenticated access to publicly shared documents.
+///
+/// # Arguments
+/// * `db` - A reference to the `sqlx` database connection pool.
+/// * `document_id` - The ID of the document to check.
+///
+/// # Returns
+/// A `Result` containing an `Option<AccessLevel>`:
+/// - `Ok(Some(AccessLevel))` if there is public access.
+/// - `Ok(None)` if there is no public access.
+/// - `Err(_)` if a database error occurs.
+#[tracing::instrument(skip(db), err)]
+pub async fn get_public_access_level_for_document(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ document_id: &str,
+) -> anyhow::Result<Option<AccessLevel>> {
+ let public_levels: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ WITH RECURSIVE project_hierarchy AS (
+ SELECT p.id as project_id
+ FROM "Document" d
+ JOIN "Project" p ON d."projectId" = p.id AND p."deletedAt" IS NULL
+ WHERE d.id = $1 AND d."deletedAt" IS NULL
+ UNION ALL
+ SELECT parent.id as project_id
+ FROM project_hierarchy ph
+ JOIN "Project" parent ON parent.id = (
+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id
+ AND "parentId" IS NOT NULL AND "deletedAt" IS NULL
+ )
+ )
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "DocumentPermission" WHERE "documentId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission"
+ WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ "#,
+ document_id
+ )
+ .fetch_all(db)
+ .await?;
+
+ let highest_level = public_levels
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
+
/// Calculates the highest effective access level a user has for a document.
///
/// This function determines the best possible permission by considering two sources:
diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs
index 8525b0b8b8..6ff75f3075 100644
--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs
+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs
@@ -1,6 +1,62 @@
use models_permissions::share_permission::access_level::AccessLevel;
use std::str::FromStr;
+/// Gets the public access level for a project (no user required).
+///
+/// This function checks only public `SharePermission` records (where `isPublic=true`),
+/// applied either directly to the project or inherited from its parent hierarchy.
+/// It does NOT check user-specific `UserItemAccess` records.
+///
+/// Use this for unauthenticated access to publicly shared projects.
+///
+/// # Arguments
+/// * `db` - A reference to the `sqlx` database connection pool.
+/// * `project_id` - The ID of the project to check.
+///
+/// # Returns
+/// A `Result` containing an `Option<AccessLevel>`:
+/// - `Ok(Some(AccessLevel))` if there is public access.
+/// - `Ok(None)` if there is no public access.
+/// - `Err(_)` if a database error occurs.
+#[tracing::instrument(skip(db), err)]
+pub async fn get_public_access_level_for_project(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ project_id: &str,
+) -> anyhow::Result<Option<AccessLevel>> {
+ let public_levels: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ WITH RECURSIVE project_hierarchy AS (
+ SELECT id as project_id
+ FROM "Project"
+ WHERE id = $1 AND "deletedAt" IS NULL
+ UNION ALL
+ SELECT parent.id as project_id
+ FROM project_hierarchy ph
+ JOIN "Project" parent ON parent.id = (
+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id
+ AND "parentId" IS NOT NULL AND "deletedAt" IS NULL
+ )
+ )
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "ProjectPermission"
+ WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ "#,
+ project_id
+ )
+ .fetch_all(db)
+ .await?;
+
+ let highest_level = public_levels
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
+
/// Calculates the highest effective access level a user has for a project.
///
/// This function determines the best possible permission by considering two sources:
@@ -23,7 +79,6 @@ use std::str::FromStr;
/// - `Ok(None)` if the user has no access at all.
/// - `Err(_)` if a database error occurs.
#[tracing::instrument(skip(db))]
-#[tracing::instrument(skip(db))]
pub async fn get_highest_access_level_for_project(
db: &sqlx::Pool<sqlx::Postgres>,
project_id: &str,
diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs
index a1717a7fe2..c6c90d440f 100644
--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs
+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs
@@ -1,6 +1,65 @@
use models_permissions::share_permission::access_level::AccessLevel;
use std::str::FromStr;
+/// Gets the public access level for a thread (no user required).
+///
+/// This function checks only public `SharePermission` records (where `isPublic=true`),
+/// applied either directly to the thread or inherited from its project hierarchy.
+/// It does NOT check user-specific `UserItemAccess` records.
+///
+/// Use this for unauthenticated access to publicly shared threads.
+///
+/// # Arguments
+/// * `db` - A reference to the `sqlx` database connection pool.
+/// * `thread_id` - The ID of the thread to check.
+///
+/// # Returns
+/// A `Result` containing an `Option<AccessLevel>`:
+/// - `Ok(Some(AccessLevel))` if there is public access.
+/// - `Ok(None)` if there is no public access.
+/// - `Err(_)` if a database error occurs.
+#[tracing::instrument(skip(db), err)]
+pub async fn get_public_access_level_for_thread(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ thread_id: &str,
+) -> anyhow::Result<Option<AccessLevel>> {
+ let public_levels: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ WITH RECURSIVE project_hierarchy AS (
+ SELECT p.id as project_id
+ FROM "EmailThreadPermission" etp
+ JOIN "Project" p ON etp."projectId" = p.id AND p."deletedAt" IS NULL
+ WHERE etp."threadId" = $1
+ UNION ALL
+ SELECT parent.id as project_id
+ FROM project_hierarchy ph
+ JOIN "Project" parent ON parent.id = (
+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id
+ AND "parentId" IS NOT NULL AND "deletedAt" IS NULL
+ )
+ )
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission"
+ WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ "#,
+ thread_id
+ )
+ .fetch_all(db)
+ .await?;
+
+ let highest_level = public_levels
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
+
/// Calculates the highest effective access level a user has for a thread.
///
/// This function determines the best possible permission by considering two sources:
diff --git a/rust/cloud-storage/macro_middleware/Cargo.toml b/rust/cloud-storage/macro_middleware/Cargo.toml
index fd9bfb6583..573e49d1fc 100644
--- a/rust/cloud-storage/macro_middleware/Cargo.toml
+++ b/rust/cloud-storage/macro_middleware/Cargo.toml
@@ -31,6 +31,7 @@ macro_share_permissions = { path = "../macro_share_permissions", optional = true
macro_user_id = { path = "../macro_user_id", optional = true }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+model-entity = { path = "../model-entity" }
model_user = { path = "../model_user", features = ["axum"], optional = true }
models_permissions = { path = "../models_permissions" }
permission = { path = "../permission", optional = true }
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
index 606f379356..477fad8078 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
@@ -7,10 +7,10 @@ use axum::{
};
use sqlx::PgPool;
-use super::get_users_access_level_v2;
+use super::{EntityType, get_public_access_level, get_users_access_level_v2};
use crate::cloud_storage::ensure_access::{AccessLevelErr, BuildAccessLevel};
use model::document::DocumentBasic;
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
use models_permissions::share_permission::access_level::AccessLevel;
#[derive(Debug)]
@@ -32,41 +32,57 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let db = PgPool::from_ref(state);
- let MacroUserExtractor {
+ let OptionalMacroUserExtractor {
macro_user_id,
user_context,
..
} = parts
.extract()
.await
- .map_err(|_| AccessLevelErr::UnAuthorized)?;
+ .map_err(|_| AccessLevelErr::InternalErr)?;
+
let document_context: Extension<DocumentBasic> =
<Extension<DocumentBasic>>::from_request_parts(parts, state)
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
- if document_context.owner == macro_user_id {
+ // Check ownership only if authenticated
+ if let Some(ref user_id) = macro_user_id
+ && document_context.owner == *user_id
+ {
return Ok(Self {
access_level: AccessLevel::Owner,
desired: PhantomData,
});
}
- // If the was deleted and you are not the owner, you can't access it
+ // If the document was deleted and you are not the owner, you can't access it
if document_context.deleted_at.is_some() {
return Err(AccessLevelErr::UnAuthorizedWithMsg(
"only owner can access deleted resource",
));
}
- let access_level: Option<AccessLevel> = get_users_access_level_v2(
- &db,
- &user_context.user_id,
- &document_context.document_id,
- "document",
- )
- .await
- .map_err(AccessLevelErr::DbErr)?;
+ // Check access based on auth state
+ let access_level: Option<AccessLevel> = match macro_user_id {
+ Some(_) => {
+ // Authenticated user: check user-specific and public access
+ get_users_access_level_v2(
+ &db,
+ &user_context.user_id,
+ &document_context.document_id,
+ "document",
+ )
+ .await
+ .map_err(AccessLevelErr::DbErr)?
+ }
+ None => {
+ // Unauthenticated user: check public access only
+ get_public_access_level(&db, &document_context.document_id, EntityType::Document)
+ .await
+ .map_err(AccessLevelErr::DbErr)?
+ }
+ };
let desired = T::into_access_level();
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/mod.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/mod.rs
index 4bbd24d9fe..56c3ed6ed3 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/mod.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/mod.rs
@@ -7,6 +7,7 @@ pub mod thread;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
+pub use model_entity::EntityType;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use models_permissions::share_permission::access_level::{
AccessLevel, CommentAccessLevel, EditAccessLevel, OwnerAccessLevel,
@@ -129,6 +130,59 @@ pub async fn get_users_access_level_v2(
}
}
+/// Gets public access level for an entity (no user required).
+#[tracing::instrument(skip(db))]
+pub async fn get_public_access_level(
+ db: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+) -> Result<Option<AccessLevel>, (StatusCode, String)> {
+ let result = match entity_type {
+ EntityType::Document => {
+ macro_db_client::share_permission::access_level::document::get_public_access_level_for_document(
+ db,
+ entity_id,
+ )
+ .await
+ }
+ EntityType::Chat => {
+ macro_db_client::share_permission::access_level::chat::get_public_access_level_for_chat(
+ db,
+ entity_id,
+ )
+ .await
+ }
+ EntityType::Project => {
+ macro_db_client::share_permission::access_level::project::get_public_access_level_for_project(
+ db,
+ entity_id,
+ )
+ .await
+ }
+ EntityType::EmailThread => {
+ macro_db_client::share_permission::access_level::thread::get_public_access_level_for_thread(
+ db,
+ entity_id,
+ )
+ .await
+ }
+ _ => {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unsupported entity type {entity_type}"),
+ ));
+ }
+ };
+
+ result.map_err(|e| {
+ tracing::error!(error=?e, "failed to get public access level");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to get public access level".to_string(),
+ )
+ })
+}
+
/// Gets the users AccessLevel for a given item using UserItemAccess and SharePermissions
#[tracing::instrument(skip(db))]
pub async fn get_highest_access_level(
diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.toml
index 08525ab6b6..74f08e8f25 100644
--- a/rust/cloud-storage/model/Cargo.toml
+++ b/rust/cloud-storage/model/Cargo.toml
@@ -16,7 +16,7 @@ doppleganger = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response" }
model_file_type = { path = "../model_file_type", features = ["utoipa"] }
-model_user = { path = "../model_user" }
+model_user = { path = "../model_user", features = ["axum"] }
models_bulk_upload = { path = "../models_bulk_upload" }
models_comms = { path = "../models_comms" }
models_email = { path = "../models_email" }
diff --git a/rust/cloud-storage/model_user/src/axum_extractor.rs b/rust/cloud-storage/model_user/src/axum_extractor.rs
index ead0c946c8..df0572b959 100644
--- a/rust/cloud-storage/model_user/src/axum_extractor.rs
+++ b/rust/cloud-storage/model_user/src/axum_extractor.rs
@@ -26,6 +26,8 @@ impl IntoResponse for UserExtractorErr {
}
}
+/// Extractor that requires an authenticated user.
+/// Fails with `UserContextEmpty` if the user_id is empty.
#[non_exhaustive]
#[derive(Clone)]
pub struct MacroUserExtractor {
@@ -56,3 +58,39 @@ where
})
}
}
+
+/// Extractor that succeeds even for unauthenticated users.
+/// Returns `None` for `macro_user_id` if the user_id is empty.
+#[non_exhaustive]
+#[derive(Clone)]
+pub struct OptionalMacroUserExtractor {
+ pub macro_user_id: Option<MacroUserIdStr<'static>>,
+ pub user_context: UserContext,
+}
+
+#[axum::async_trait]
+impl<S> FromRequestParts<S> for OptionalMacroUserExtractor
+where
+ S: Send + Sync,
+{
+ type Rejection = UserExtractorErr;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let ext: Extension<UserContext> = parts.extract_with_state(state).await?;
+
+ if ext.0.user_id.is_empty() {
+ return Ok(OptionalMacroUserExtractor {
+ macro_user_id: None,
+ user_context: ext.0,
+ });
+ }
+
+ let macro_user_id =
+ MacroUserIdStr::parse_from_str(&ext.0.user_id).map(CowLike::into_owned)?;
+
+ Ok(OptionalMacroUserExtractor {
+ macro_user_id: Some(macro_user_id),
+ user_context: ext.0,
+ })
+ }
+}