Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

documents - add public links (#64630)

Jeff Bruemmer4d14b02aa2e6
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index c9d49012652..b305e20df38 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1754,8 +1754,10 @@
events
models
premium-features
+ public-sharing
queries
query-permissions
+ query-processor
revisions
search
util
@@ -1887,7 +1889,17 @@
:uses #{premium-features
util}}
- enterprise/remote-sync
+ enterprise/public-sharing
+ {:team "UX West"
+ :api #{metabase-enterprise.public-sharing.api}
+ :uses #{api
+ events
+ premium-features
+ public-sharing
+ query-processor
+ util}}
+
+ enterprise/remote-sync
{:team "UX West"
:api #{metabase-enterprise.remote-sync.api
metabase-enterprise.remote-sync.core
diff --git a/e2e/support/helpers/e2e-embedding-helpers.js b/e2e/support/helpers/e2e-embedding-helpers.js
index 6c1881d0954..628557fd090 100644
--- a/e2e/support/helpers/e2e-embedding-helpers.js
+++ b/e2e/support/helpers/e2e-embedding-helpers.js
@@ -299,6 +299,10 @@ export function createPublicDashboardLink(dashboardId) {
return cy.request("POST", `/api/dashboard/${dashboardId}/public_link`, {});
}
+export function createPublicDocumentLink(documentId) {
+ return cy.request("POST", `/api/ee/document/${documentId}/public-link`, {});
+}
+
/**
* @param {Object} options
* @param {string} options.url
diff --git a/e2e/test/scenarios/documents/document-downloads.cy.spec.ts b/e2e/test/scenarios/documents/document-downloads.cy.spec.ts
new file mode 100644
index 00000000000..4aaef0fdfc4
--- /dev/null
+++ b/e2e/test/scenarios/documents/document-downloads.cy.spec.ts
@@ -0,0 +1,200 @@
+import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";
+import { DOCUMENT_WITH_TWO_CARDS } from "e2e/support/document-initial-data";
+import { DataPermissionValue } from "metabase/admin/permissions/types";
+
+const { H } = cy;
+
+describe("scenarios > documents > downloads", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ it("shows Download results for read-only document access", () => {
+ H.createDocument({
+ name: "Download Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for card to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Sign in as read-only user
+ cy.signIn("readonly");
+ H.visitDocument("@documentId");
+
+ // Wait for card to load as readonly user
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Open card menu
+ H.openDocumentCardMenu("Orders");
+
+ // Verify menu shows only "Download results" and it's enabled
+ H.popover().within(() => {
+ cy.findByRole("menuitem", { name: /Download results/i }).should(
+ "be.visible",
+ );
+ // Verify all menu items: only Download results should be enabled
+ cy.findAllByRole("menuitem").each(($item) => {
+ const text = $item.text();
+ if (text.includes("Download results")) {
+ cy.wrap($item).should("not.be.disabled");
+ } else {
+ cy.wrap($item).should("be.disabled");
+ }
+ });
+ });
+
+ // Click Download results
+ cy.findByRole("menuitem", { name: /Download results/i }).click();
+
+ // Verify format options appear
+ H.popover().within(() => {
+ cy.findByText(".csv").should("be.visible");
+ cy.findByText(".xlsx").should("be.visible");
+ cy.findByText(".json").should("be.visible");
+ });
+ });
+
+ it("shows full menu including Download results for write access", () => {
+ H.createDocument({
+ name: "Admin Download Test Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for card to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Open card menu
+ H.openDocumentCardMenu("Orders");
+
+ // Verify menu shows all options with Download results
+ H.popover().within(() => {
+ cy.findByRole("menuitem", { name: /Edit Query/i }).should("be.visible");
+ cy.findByRole("menuitem", { name: /Edit Visualization/i }).should(
+ "be.visible",
+ );
+ cy.findByRole("menuitem", { name: /Replace/i }).should("be.visible");
+ cy.findByRole("menuitem", { name: /Download results/i }).should(
+ "be.visible",
+ );
+ cy.findByRole("menuitem", { name: /Remove Chart/i }).should("be.visible");
+ });
+
+ // Click Download results
+ cy.findByRole("menuitem", { name: /Download results/i }).click();
+
+ // Verify format options appear
+ H.popover().within(() => {
+ cy.findByText(".csv").should("be.visible");
+ cy.findByText(".xlsx").should("be.visible");
+ cy.findByText(".json").should("be.visible");
+ });
+ });
+
+ it("does not show download when permissions are 'none'", () => {
+ H.createDocument({
+ name: "No Access Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for card to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Sign in as user with no collection access
+ cy.signIn("nocollection");
+ H.visitDocument("@documentId");
+
+ // Should see permission denied message
+ cy.findByRole("status").should(
+ "contain.text",
+ "Sorry, you don’t have permission to see that.",
+ );
+
+ // Document content should not render and no card menu should be visible
+ H.documentContent().should("not.exist");
+ cy.findByRole("button", { name: /ellipsis/ }).should("not.exist");
+ });
+
+ it("hides Download results when the person lacks download permission but can view the collection", () => {
+ H.createDocument({
+ name: "No Download Permission Document",
+ document: DOCUMENT_WITH_TWO_CARDS,
+ collection_id: null,
+ alias: "document",
+ idAlias: "documentId",
+ });
+
+ H.visitDocument("@documentId");
+
+ // Wait for card to load
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Remove download permission but keep view-data unrestricted
+ const { READONLY_GROUP, ALL_USERS_GROUP } = USER_GROUPS;
+ cy.updatePermissionsGraph({
+ [READONLY_GROUP]: {
+ [SAMPLE_DB_ID]: {
+ download: { schemas: DataPermissionValue.NONE },
+ "view-data": DataPermissionValue.UNRESTRICTED,
+ },
+ },
+ [ALL_USERS_GROUP]: {
+ [SAMPLE_DB_ID]: {
+ download: { schemas: DataPermissionValue.NONE },
+ },
+ },
+ });
+
+ // Sign in as read-only user who can view the collection but cannot download
+ cy.signIn("readonly");
+ H.visitDocument("@documentId");
+
+ // Wait for card to load as readonly user
+ H.getDocumentCard("Orders")
+ .should("be.visible")
+ .findByTestId("table-root")
+ .should("exist");
+
+ // Open card menu
+ H.openDocumentCardMenu("Orders");
+
+ // Verify that Download results is not shown
+ H.popover().within(() => {
+ cy.findByRole("menuitem", { name: /Download results/i }).should(
+ "not.exist",
+ );
+ });
+ });
+});
diff --git a/e2e/test/scenarios/documents/public-documents.cy.spec.ts b/e2e/test/scenarios/documents/public-documents.cy.spec.ts
new file mode 100644
index 00000000000..c71472859a0
--- /dev/null
+++ b/e2e/test/scenarios/documents/public-documents.cy.spec.ts
@@ -0,0 +1,345 @@
+import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+
+const { H } = cy;
+
+// Helper function to create a test document with embedded card
+function createTestDocumentWithCard(name = "Test Document") {
+ return H.createDocument({
+ name,
+ document: {
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Test content" }],
+ attrs: { _id: "1" },
+ },
+ {
+ type: "resizeNode",
+ attrs: { height: 400, minHeight: 280 },
+ content: [
+ {
+ type: "cardEmbed",
+ attrs: { id: ORDERS_QUESTION_ID, name: null, _id: "2" },
+ },
+ ],
+ },
+ { type: "paragraph", attrs: { _id: "3" } },
+ ],
+ type: "doc",
+ },
+ collection_id: null,
+ idAlias: "documentId",
+ });
+}
+
+// Helper function to create a test document with custom content
+function createTestDocument(name: string, content: string) {
+ return H.createDocument({
+ name,
+ document: {
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: content }],
+ attrs: { _id: "1" },
+ },
+ ],
+ type: "doc",
+ },
+ collection_id: null,
+ idAlias: "documentId",
+ });
+}
+
+// Helper function to visit a public document
+function visitPublicDocument(
+ documentIdAlias = "@documentId",
+ options?: { signOut?: boolean },
+) {
+ cy.get(documentIdAlias)
+ .then((documentId) => {
+ return H.createPublicDocumentLink(documentId);
+ })
+ .then(({ body: { uuid } }) => {
+ if (options?.signOut) {
+ cy.signOut();
+ }
+ cy.visit(`/public/document/${uuid}`);
+ });
+}
+
+// Helper function to verify document is read-only
+function verifyDocumentIsReadOnly() {
+ H.documentContent()
+ .findByRole("textbox")
+ .should("have.attr", "contenteditable", "false");
+ cy.findByRole("button", { name: "Save" }).should("not.exist");
+}
+
+// Helper function to verify comments are hidden
+function verifyCommentsAreHidden() {
+ H.Comments.getDocumentNodeButtons().should("not.exist");
+ cy.findByTestId("comments-sidebar").should("not.exist");
+ cy.findByRole("link", { name: "Show all comments" }).should("not.exist");
+}
+
+// Helper function to verify error message is displayed
+function verifyErrorMessage(expectedMessage: string) {
+ // PublicError and PublicNotFound render messages in error pages
+ cy.contains(expectedMessage).should("be.visible");
+ H.documentContent().should("not.exist");
+}
+
+describe("scenarios > documents > public", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.updateSetting("enable-public-sharing", true);
+ });
+
+ it("should not show comments in public documents", () => {
+ // Create a document with content and an embedded card
+ createTestDocument("Test Public Document", "This is a test paragraph");
+
+ cy.log("Visit the document as admin to verify comments exist");
+ H.visitDocument("@documentId");
+
+ // Verify the document content loaded
+ H.documentContent().should("contain", "This is a test paragraph");
+
+ // Verify comment buttons exist for authenticated users
+ H.Comments.getDocumentNodeButtons().should("exist");
+
+ cy.log("Create public link and visit public document");
+ visitPublicDocument();
+
+ cy.log("Verify document content is visible");
+ H.documentContent().should("contain", "This is a test paragraph");
+
+ cy.log("Verify comment buttons do not exist in public view");
+ verifyCommentsAreHidden();
+ });
+
+ it("should only show 'Download results' in card menu for public documents", () => {
+ // Create a document with an embedded card
+ createTestDocumentWithCard("Test Document with Card");
+
+ cy.log("Visit document as admin to verify full menu exists");
+ H.visitDocument("@documentId");
+
+ // Wait for card to load
+ H.getDocumentCard("Orders").should("exist");
+
+ // Open card menu as admin and verify multiple options exist
+ H.openDocumentCardMenu("Orders");
+ H.popover().within(() => {
+ cy.findByText("Edit Visualization").should("exist");
+ cy.findByText("Edit Query").should("exist");
+ cy.findByText("Replace").should("exist");
+ });
+
+ // Close the popover by clicking outside
+ H.documentContent().click();
+
+ cy.log("Create public link and visit public document");
+ visitPublicDocument();
+
+ cy.log("Verify card is visible in public view");
+ H.getDocumentCard("Orders").should("exist");
+
+ cy.log("Open card menu in public view");
+ H.openDocumentCardMenu("Orders");
+
+ cy.log("Verify only 'Download results' option is present");
+ H.popover().within(() => {
+ cy.findByText("Download results").should("exist");
+ cy.findByText("Edit Visualization").should("not.exist");
+ cy.findByText("Edit Query").should("not.exist");
+ cy.findByText("Replace").should("not.exist");
+
+ // Verify there's only one menu item
+ cy.findAllByRole("menuitem").should("have.length", 1);
+ });
+ });
+
+ it("should restrict document header menu in public view", () => {
+ // Create a document
+ createTestDocument(
+ "Test Document Header",
+ "Testing header menu restrictions",
+ );
+
+ cy.log("Visit document as admin to verify full menu exists");
+ H.visitDocument("@documentId");
+
+ // Verify the document content loaded
+ H.documentContent().should("contain", "Testing header menu restrictions");
+
+ // Check that "More options" menu exists with admin options
+ cy.findByRole("button", { name: "More options" }).click();
+ H.popover().within(() => {
+ cy.findByText("Bookmark").should("exist");
+ cy.findByText("Move to trash").should("exist");
+ cy.findByText("Print Document").should("exist");
+ });
+
+ // Close the popover
+ H.documentContent().click();
+
+ cy.log("Create public link and visit public document");
+ visitPublicDocument();
+
+ cy.log("Verify document content is visible in public view");
+ H.documentContent().should("contain", "Testing header menu restrictions");
+
+ cy.log("Verify 'More options' menu is either hidden or restricted");
+ // In public view, the "More options" button should not exist or should have limited options
+ cy.findByRole("button", { name: "More options" }).should("not.exist");
+ });
+
+ it("should be read-only in public view", () => {
+ // Create a document
+ createTestDocument(
+ "Read-only Test Document",
+ "This content should not be editable",
+ );
+
+ cy.log("Visit document as admin to verify it's editable");
+ H.visitDocument("@documentId");
+
+ // Verify the document content is editable
+ H.documentContent()
+ .findByRole("textbox")
+ .should("have.attr", "contenteditable", "true");
+
+ cy.log("Create public link and visit public document");
+ visitPublicDocument();
+
+ cy.log("Verify document content is visible");
+ H.documentContent().should(
+ "contain",
+ "This content should not be editable",
+ );
+
+ cy.log("Verify document is read-only");
+ verifyDocumentIsReadOnly();
+ });
+
+ it("should allow downloading results from embedded cards", () => {
+ // Create a document with an embedded card
+ createTestDocumentWithCard("Download Test Document");
+
+ cy.log("Create public link and visit public document");
+ visitPublicDocument();
+
+ cy.log("Verify card is visible");
+ H.getDocumentCard("Orders").should("exist");
+
+ cy.log("Open card menu and verify download option");
+ H.openDocumentCardMenu("Orders");
+ H.popover().within(() => {
+ cy.findByText("Download results").should("exist");
+ });
+
+ cy.log("Click 'Download results' to show format options");
+ H.popover().findByText("Download results").click();
+
+ cy.log("Verify all download format options are available");
+ H.popover().within(() => {
+ cy.findByText(".csv").should("exist");
+ cy.findByText(".xlsx").should("exist");
+ cy.findByText(".json").should("exist");
+ cy.findByTestId("download-results-button").should("exist");
+ });
+ });
+
+ it("should be accessible without authentication", () => {
+ // Create a document with public link
+ createTestDocumentWithCard("Public Anonymous Document");
+
+ cy.log("Sign out and visit public document as anonymous user");
+ visitPublicDocument("@documentId", { signOut: true });
+
+ cy.log("Verify document content is visible without authentication");
+ H.documentContent().should("contain", "Test content");
+ H.getDocumentCard("Orders").should("exist");
+
+ cy.log("Verify document is read-only");
+ verifyDocumentIsReadOnly();
+
+ cy.log("Verify no authentication UI is shown");
+ cy.findByRole("button", { name: "Sign in" }).should("not.exist");
+ });
+
+ it("should become inaccessible when public sharing is disabled", () => {
+ // Create a document with public link
+ createTestDocumentWithCard("Document for Disabling Test");
+
+ cy.log("Create public link while sharing is enabled");
+ cy.get("@documentId")
+ .then((documentId) => {
+ return H.createPublicDocumentLink(documentId);
+ })
+ .then(({ body: { uuid } }) => {
+ cy.wrap(uuid).as("publicUuid");
+
+ cy.log("Verify document is accessible with sharing enabled");
+ cy.signOut();
+ cy.visit(`/public/document/${uuid}`);
+ H.documentContent().should("contain", "Test content");
+ });
+
+ cy.log("Disable public sharing");
+ cy.signInAsAdmin();
+ H.updateSetting("enable-public-sharing", false);
+ cy.signOut();
+
+ cy.log("Try to access public document after disabling sharing");
+ cy.get("@publicUuid").then((uuid) => {
+ cy.visit(`/public/document/${uuid}`);
+
+ cy.log("Verify document is no longer accessible");
+ verifyErrorMessage("An error occurred.");
+ });
+
+ // Cleanup: Re-enable public sharing for subsequent tests
+ cy.signInAsAdmin();
+ H.updateSetting("enable-public-sharing", true);
+ });
+
+ it("should show error when accessing public link of deleted document", () => {
+ // Create a document with public link
+ createTestDocumentWithCard("Document to be Deleted");
+
+ cy.log("Create public link");
+ cy.get("@documentId")
+ .then((documentId) => {
+ return H.createPublicDocumentLink(documentId);
+ })
+ .then(({ body: { uuid } }) => {
+ cy.wrap(uuid).as("publicUuid");
+
+ cy.log("Verify document is accessible before deletion");
+ cy.visit(`/public/document/${uuid}`);
+ H.documentContent().should("contain", "Test content");
+ });
+
+ cy.log("Delete the document");
+ cy.get("@documentId").then((documentId) => {
+ H.visitDocument(documentId);
+ });
+
+ // Move document to trash
+ cy.findByRole("button", { name: "More options" }).click();
+ H.popover().findByText("Move to trash").click();
+
+ cy.log("Try to access public link after document deletion");
+ cy.get("@publicUuid").then((uuid) => {
+ cy.visit(`/public/document/${uuid}`);
+
+ cy.log("Verify error message is shown");
+ verifyErrorMessage("Not found");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/sharing/public-sharing.cy.spec.js b/e2e/test/scenarios/sharing/public-sharing.cy.spec.js
index 62dbafb786d..6d9c78186d6 100644
--- a/e2e/test/scenarios/sharing/public-sharing.cy.spec.js
+++ b/e2e/test/scenarios/sharing/public-sharing.cy.spec.js
@@ -143,6 +143,7 @@ describe("scenarios > admin > settings > public sharing", () => {
});
cy.findByTestId("admin-layout-content")
.findByText("No dashboards have been publicly shared yet.")
+ .scrollIntoView()
.should("be.visible");
});
@@ -203,6 +204,7 @@ describe("scenarios > admin > settings > public sharing", () => {
});
cy.findByTestId("admin-layout-content")
.findByText("No questions have been publicly shared yet.")
+ .scrollIntoView()
.should("be.visible");
});
@@ -282,6 +284,7 @@ describe("scenarios > admin > settings > public sharing", () => {
});
cy.findByTestId("admin-layout-content")
.findByText("No actions have been publicly shared yet.")
+ .scrollIntoView()
.should("be.visible");
});
});
diff --git a/enterprise/backend/src/metabase_enterprise/api/routes.clj b/enterprise/backend/src/metabase_enterprise/api/routes.clj
index 1ba302ae473..1f66db3a0f9 100644
--- a/enterprise/backend/src/metabase_enterprise/api/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api/routes.clj
@@ -29,6 +29,7 @@
[metabase-enterprise.metabot-v3.api]
[metabase-enterprise.metabot-v3.tools.api]
[metabase-enterprise.permission-debug.api]
+ [metabase-enterprise.public-sharing.api]
[metabase-enterprise.remote-sync.api]
[metabase-enterprise.sandbox.api.routes]
[metabase-enterprise.scim.routes]
@@ -39,6 +40,7 @@
[metabase-enterprise.transforms.api]
[metabase-enterprise.upload-management.api]
[metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :as api.routes.common]
[metabase.api.util.handlers :as handlers]
[metabase.util.i18n :refer [deferred-tru]]))
@@ -120,6 +122,7 @@
"/metabot-tools" metabase-enterprise.metabot-v3.tools.api/routes
"/metabot-v3" (premium-handler metabase-enterprise.metabot-v3.api/routes :metabot-v3)
"/permission_debug" (premium-handler metabase-enterprise.permission-debug.api/routes :advanced-permissions)
+ "/public" (api.routes.common/+public-exceptions metabase-enterprise.public-sharing.api/routes)
"/transforms-python" (premium-handler metabase-enterprise.transforms-python.api/routes :transforms-python)
"/scim" (premium-handler metabase-enterprise.scim.routes/routes :scim)
"/semantic-search" (premium-handler metabase-enterprise.semantic-search.api/routes :semantic-search)
diff --git a/enterprise/backend/src/metabase_enterprise/documents/api/document.clj b/enterprise/backend/src/metabase_enterprise/documents/api/document.clj
index ce263666b2a..e68b0711556 100644
--- a/enterprise/backend/src/metabase_enterprise/documents/api/document.clj
+++ b/enterprise/backend/src/metabase_enterprise/documents/api/document.clj
@@ -9,10 +9,14 @@
[metabase.collections.core :as collections]
[metabase.collections.models.collection :as collection]
[metabase.events.core :as events]
+ [metabase.public-sharing.validation :as public-sharing.validation]
[metabase.queries.core :as card]
[metabase.query-permissions.core :as query-perms]
+ [metabase.query-processor.api :as api.dataset]
+ [metabase.query-processor.card :as qp.card]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -241,6 +245,129 @@
:user-id api/*current-user-id*})
api/generic-204-no-content))
+;;; ----------------------------------------------- Sharing is Caring ------------------------------------------------
+
+(api.macros/defendpoint :post "/:document-id/public-link" :- [:map [:uuid ms/UUIDString]]
+ "Generate a publicly-accessible UUID for a Document.
+
+ Creates a public link that allows viewing the Document without authentication. If the Document already has
+ a public UUID, returns the existing one rather than generating a new one. This enables sharing the Document
+ via `GET /api/ee/public/document/:uuid`.
+
+ Returns a map containing `:uuid` (the public UUID string).
+
+ Requires superuser permissions. Public sharing must be enabled via the `enable-public-sharing` setting."
+ [{:keys [document-id]} :- [:map
+ [:document-id ms/PositiveInt]]]
+ (api/check-superuser)
+ (public-sharing.validation/check-public-sharing-enabled)
+ (api/check-exists? :model/Document :id document-id, :archived false)
+ ;; Use a transaction to prevent race conditions when two requests arrive simultaneously.
+ ;; Only one request will successfully create the UUID; both will return the same value.
+ (t2/with-transaction [_conn]
+ (if-let [existing-uuid (t2/select-one-fn :public_uuid :model/Document :id document-id)]
+ {:uuid existing-uuid}
+ (do
+ (t2/update! :model/Document document-id
+ {:public_uuid (str (random-uuid))
+ :made_public_by_id api/*current-user-id*})
+ ;; Always select after update to ensure we return what's actually stored
+ {:uuid (t2/select-one-fn :public_uuid :model/Document :id document-id)}))))
+
+(api.macros/defendpoint :delete "/:document-id/public-link"
+ "Remove the public link for a Document.
+
+ Deletes the public UUID from the Document, making it no longer accessible via the public sharing endpoint.
+ This revokes public access to the Document - the existing public link will no longer work.
+
+ Returns a 204 No Content response on success.
+
+ Requires superuser permissions. Public sharing must be enabled via the `enable-public-sharing` setting.
+ Throws a 404 if the Document doesn't exist, is archived, or doesn't have a public link."
+ [{:keys [document-id]} :- [:map
+ [:document-id ms/PositiveInt]]]
+ (api/check-superuser)
+ (public-sharing.validation/check-public-sharing-enabled)
+ (api/check-exists? :model/Document :id document-id, :public_uuid [:not= nil], :archived false)
+ (t2/update! :model/Document document-id
+ {:public_uuid nil
+ :made_public_by_id nil})
+ api/generic-204-no-content)
+
+(api.macros/defendpoint :get "/public" :- [:sequential [:map
+ [:name :string]
+ [:id ms/PositiveInt]
+ [:public_uuid ms/UUIDString]]]
+ "List all Documents that have public links.
+
+ Returns a sequence of Documents that have been publicly shared. Each Document includes its `:id`, `:name`,
+ and `:public_uuid`. Documents are only actually accessible via the public endpoint if public sharing is
+ currently enabled. Archived Documents are excluded from the results.
+
+ This endpoint is used to populate the public links listing in the Admin settings UI.
+
+ Requires superuser permissions. Public sharing must be enabled via the `enable-public-sharing` setting."
+ []
+ (api/check-superuser)
+ (public-sharing.validation/check-public-sharing-enabled)
+ (t2/select [:model/Document :name :id :public_uuid], :public_uuid [:not= nil], :archived false))
+
+;;; ------------------------------------------------ Card Downloads --------------------------------------------------
+
+(defn- validate-card-in-document
+ "Validates that the document and card exist, are not archived, and that the card belongs to the document.
+ Also checks that the current user has read access to the document.
+
+ Throws a 404 exception via `api/check-404` if any validation fails. Returns card-id on success."
+ [document-id card-id]
+ (let [document (api/check-404 (t2/select-one :model/Document :id document-id :archived false))]
+ (api/read-check document)
+ (api/check-404 (t2/exists? :model/Card :id card-id :document_id document-id :archived false))))
+
+(api.macros/defendpoint :post "/:document-id/card/:card-id/query/:export-format"
+ "Download query results for a Card embedded in a Document.
+
+ Returns query results in the requested format. The user must have read access to the document
+ to download results. If the card's query fails, standard query error responses are returned.
+
+ Route parameters:
+ - document-id: ID of the document containing the card
+ - card-id: ID of the card to download results from
+ - export-format: Output format (csv, xlsx, json)
+
+ Body parameters (snake_case):
+ - parameters: Optional query parameters (array of maps or JSON string)
+ - format_rows: Whether to apply formatting to results (boolean, default false)
+ - pivot_results: Whether to pivot results (boolean, default false)"
+ [{:keys [document-id card-id export-format]} :- [:map
+ [:document-id ms/PositiveInt]
+ [:card-id ms/PositiveInt]
+ [:export-format :keyword]]
+ _query-params
+ {:keys [parameters]
+ pivot-results? :pivot_results
+ format-rows? :format_rows
+ :as _body}
+ :- [:map
+ [:parameters {:optional true} [:maybe [:or
+ [:sequential ms/Map]
+ ms/JSONString]]]
+ [:format_rows {:default false} ms/BooleanValue]
+ [:pivot_results {:default false} ms/BooleanValue]]]
+ (validate-card-in-document document-id card-id)
+ (qp.card/process-query-for-card
+ card-id export-format
+ :parameters (cond-> parameters
+ (string? parameters) json/decode+kw)
+ :constraints nil
+ :context (api.dataset/export-format->context export-format)
+ :middleware {:process-viz-settings? true
+ :skip-results-metadata? true
+ :ignore-cached-results? true
+ :format-rows? format-rows?
+ :pivot? pivot-results?
+ :js-int-to-string? false}))
+
(def ^{:arglists '([request respond raise])} routes
"`/api/ee/document/` routes."
(api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/documents/models/document.clj b/enterprise/backend/src/metabase_enterprise/documents/models/document.clj
index 3d34b361958..906f9bb4805 100644
--- a/enterprise/backend/src/metabase_enterprise/documents/models/document.clj
+++ b/enterprise/backend/src/metabase_enterprise/documents/models/document.clj
@@ -5,6 +5,7 @@
[metabase.api.common :as api]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
+ [metabase.public-sharing.core :as public-sharing]
[metabase.search.spec :as search.spec]
[metabase.util :as u]
[metabase.util.i18n :refer [deferred-tru]]
@@ -57,6 +58,24 @@
(into {}))
:creator_id {:default {}}))
+(methodical/defmethod t2/batched-hydrate [:model/Document :cards]
+ "Hydrate cards associated with documents via document_id FK, returning as a map keyed by card ID.
+ Fetches all cards for all documents in a single batched query to avoid N+1 queries."
+ [_model k documents]
+ (let [document-ids (keep :id documents)
+ ;; Fetch all cards for all documents in one batched query
+ all-cards (when (seq document-ids)
+ (t2/select :model/Card
+ :document_id [:in document-ids]
+ :archived false))
+ ;; Group cards by document_id, then convert each group to a map keyed by card ID
+ cards-by-doc-id (group-by :document_id all-cards)
+ cards-maps-by-doc-id (update-vals cards-by-doc-id
+ (fn [cards]
+ (zipmap (map :id cards) cards)))]
+ (for [doc documents]
+ (assoc doc k (get cards-maps-by-doc-id (:id doc) {})))))
+
(defn sync-document-cards-collection!
"Updates all cards associated with a document to match the document's collection.
If the document is archived, also archives all associated cards. "
@@ -75,6 +94,10 @@
:archived-directly archived_directly)
instance)
+(t2/define-after-select :model/Document
+ [document]
+ (public-sharing/remove-public-uuid-if-public-sharing-is-disabled document))
+
;;; ------------------------------------------------ Serdes Hashing -------------------------------------------------
(defmethod serdes/hash-fields :model/Document
@@ -155,7 +178,7 @@
(defmethod serdes/make-spec "Document"
[_model-name _opts]
{:copy [:archived :archived_directly :content_type :entity_id :name :collection_position]
- :skip [:view_count :last_viewed_at :dependency_analysis_version]
+ :skip [:view_count :last_viewed_at :public_uuid :made_public_by_id :dependency_analysis_version]
:transform {:created_at (serdes/date)
:updated_at (serdes/date)
:document {:export-with-context export-document-content
diff --git a/enterprise/backend/src/metabase_enterprise/public_sharing/api.clj b/enterprise/backend/src/metabase_enterprise/public_sharing/api.clj
new file mode 100644
index 00000000000..1c1c74f74b7
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/public_sharing/api.clj
@@ -0,0 +1,125 @@
+(ns metabase-enterprise.public-sharing.api
+ "`/api/ee/public/*` routes for Enterprise Edition entities (Documents, etc.).
+
+ These routes handle public sharing of EE-only features. They require premium features but do not require
+ authentication, allowing public access to shared documents."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.events.core :as events]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.public-sharing.api :as public-sharing.api]
+ [metabase.public-sharing.validation :as public-sharing.validation]
+ [metabase.query-processor.middleware.constraints :as qp.constraints]
+ [metabase.query-processor.schema :as qp.schema]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; ----------------------------------------------- Public Documents -------------------------------------------------
+
+(defn- remove-document-non-public-columns
+ "Remove sensitive fields from a document before exposing it publicly.
+
+ We filter out collection_id, creator_id, public_uuid, and other sensitive fields to prevent unauthenticated users
+ from discovering internal organizational structure, permissions boundaries, or who created the document. Only the
+ document content itself, basic metadata, and embedded cards are safe to expose publicly."
+ [document]
+ (select-keys document [:id :name :document :created_at :updated_at :cards]))
+
+(defn- public-document
+ "Fetch a public document with all embedded cards hydrated upfront.
+
+ We hydrate cards eagerly (rather than requiring separate requests per card) to avoid N+1 queries and provide a
+ consistent experience with public dashboards. This also allows us to filter sensitive fields from all cards at
+ once before exposing them to unauthenticated users. The document and all cards must not be archived to be
+ accessible publicly."
+ [& conditions]
+ (let [document (-> (api/check-404 (apply t2/select-one [:model/Document :id :name :document :content_type :created_at :updated_at]
+ :archived false, conditions))
+ ;; Hydrate cards via Toucan batched hydration to avoid N+1 queries
+ (t2/hydrate :cards))]
+ (-> document
+ ;; Filter sensitive fields from all cards before exposing publicly
+ (update :cards #(update-vals % public-sharing.api/remove-card-non-public-columns))
+ (dissoc :content_type)
+ remove-document-non-public-columns)))
+
+(defn- validate-card-in-public-document
+ "Ensure a card is actually embedded in the specified public document before running queries.
+
+ We validate the document-card association to prevent users from querying arbitrary cards by guessing IDs. Only
+ cards explicitly embedded in the public document (via document_id FK) are accessible through public document
+ endpoints. This prevents bypassing collection permissions by accessing cards through public document routes."
+ [uuid card-id]
+ (let [document-id (api/check-404 (t2/select-one-pk :model/Document :public_uuid uuid :archived false))]
+ (api/check-404 (t2/select-one-pk :model/Card :id card-id :document_id document-id :archived false))))
+
+(api.macros/defendpoint :get "/document/:uuid"
+ "Fetch a publicly-accessible Document. Does not require auth credentials. Public sharing must be enabled.
+
+ Returns a Document with sensitive fields removed (excludes collection_id, permissions, creator details, etc.).
+ Includes all embedded Cards with their metadata hydrated so the frontend doesn't need to make separate
+ requests for each card — just like public Dashboards do."
+ [{:keys [uuid]} :- [:map
+ [:uuid ms/UUIDString]]]
+ (premium-features/assert-has-feature :documents (tru "Documents"))
+ (public-sharing.validation/check-public-sharing-enabled)
+ (let [document (public-document :public_uuid uuid)]
+ (events/publish-event! :event/document-read {:object-id (:id document), :user-id api/*current-user-id*})
+ document))
+
+(api.macros/defendpoint :get "/document/:uuid/card/:card-id"
+ "Run a query for a Card that's embedded in a public Document. Doesn't require auth credentials. Public sharing must
+ be enabled."
+ [{:keys [uuid card-id]} :- [:map
+ [:uuid ms/UUIDString]
+ [:card-id ms/PositiveInt]]
+ {:keys [parameters]} :- [:map
+ [:parameters {:optional true} [:maybe ms/JSONString]]]]
+ (premium-features/assert-has-feature :documents (tru "Documents"))
+ (public-sharing.validation/check-public-sharing-enabled)
+ (validate-card-in-public-document uuid card-id)
+ ;; Run the query as admin since public documents are available to everyone anyway
+ (u/prog1 (public-sharing.api/process-query-for-card-with-id
+ card-id
+ :api
+ (json/decode+kw parameters)
+ :constraints (qp.constraints/default-query-constraints))
+ (events/publish-event! :event/card-read {:object-id card-id :user-id api/*current-user-id* :context :question})))
+
+(api.macros/defendpoint :post "/document/:uuid/card/:card-id/:export-format"
+ "Fetch a Card embedded in a public Document and return query results in the specified format.
+ Does not require auth credentials. Public sharing must be enabled."
+ [{:keys [uuid card-id export-format]} :- [:map
+ [:uuid ms/UUIDString]
+ [:card-id ms/PositiveInt]
+ [:export-format ::qp.schema/export-format]]
+ _query-params
+ {:keys [parameters format_rows pivot_results]} :- [:map
+ [:parameters {:optional true} [:maybe [:or
+ [:sequential ms/Map]
+ ms/JSONString]]]
+ [:format_rows {:default false} ms/BooleanValue]
+ [:pivot_results {:default false} ms/BooleanValue]]]
+ (premium-features/assert-has-feature :documents (tru "Documents"))
+ (public-sharing.validation/check-public-sharing-enabled)
+ (validate-card-in-public-document uuid card-id)
+ (public-sharing.api/process-query-for-card-with-id
+ card-id
+ export-format
+ (cond-> parameters
+ (string? parameters) json/decode+kw)
+ :constraints nil
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false
+ :format-rows? format_rows
+ :pivot? pivot_results}))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/public/*` routes for Enterprise Edition entities."
+ (api.macros/ns-handler *ns*))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj b/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj
index 5ad4e0fafe0..29a8ba98aa0 100644
--- a/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/documents/api/document_test.clj
@@ -2,32 +2,27 @@
(:require
[clojure.set :as set]
[clojure.test :refer :all]
+ [medley.core :as m]
+ [metabase-enterprise.documents.test-util :as documents.test-util]
[metabase.collections.models.collection :as collection]
[metabase.events.core :as events]
[metabase.permissions.core :as perms]
+ [metabase.permissions.models.data-permissions :as data-perms]
[metabase.test :as mt]
[toucan2.core :as t2]))
(use-fixtures :each (fn [f] (mt/with-premium-features #{:documents} (f))))
-(defn- text->prose-mirror-ast
- "Convert plain text to a ProseMirror AST structure."
- [text]
- {:type "doc"
- :content [{:type "paragraph"
- :content [{:type "text"
- :text text}]}]})
-
(deftest post-document-basic-creation-test
(testing "POST /api/ee/document/ - basic document creation"
(mt/with-model-cleanup [:model/Document]
(let [result (mt/user-http-request :crowberto
:post 200 "ee/document/" {:name "Document 1"
- :document (text->prose-mirror-ast "Doc 1")})
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")})
document-row (t2/select-one :model/Document :id (:id result))]
- (is (partial= {:name "Document 1" :document (text->prose-mirror-ast "Doc 1")} result))
+ (is (partial= {:name "Document 1" :document (documents.test-util/text->prose-mirror-ast "Doc 1")} result))
(is (pos? (:id result)))
- (is (partial= {:name "Document 1" :document (text->prose-mirror-ast "Doc 1")} document-row))))))
+ (is (partial= {:name "Document 1" :document (documents.test-util/text->prose-mirror-ast "Doc 1")} document-row))))))
(deftest post-document-creation-non-blank-name-test
(testing "POST /api/ee/document/ - basic document creation"
@@ -35,7 +30,7 @@
(is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
(mt/user-http-request :crowberto
:post 400 "ee/document/" {:name ""
- :document (text->prose-mirror-ast "Doc 1")}))))))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}))))))
(deftest post-document-creation-long-name-test
(testing "POST /api/ee/document/id - basic document update"
@@ -43,47 +38,47 @@
(mt/user-http-request :crowberto
:post 400 "ee/document"
{:name (apply str (repeat 255 "c"))
- :document (text->prose-mirror-ast "Doc 1")})))))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")})))))
(deftest put-document-basic-update-test
(testing "PUT /api/ee/document/id - basic document update"
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")}]
(let [result (mt/user-http-request :crowberto
- :put 200 (format "ee/document/%s" document-id) {:name "Document 2" :document (text->prose-mirror-ast "Doc 2")})]
+ :put 200 (format "ee/document/%s" document-id) {:name "Document 2" :document (documents.test-util/text->prose-mirror-ast "Doc 2")})]
(is (partial= {:name "Document 2"
- :document (text->prose-mirror-ast "Doc 2")} result))))))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 2")} result))))))
(deftest put-document-update-non-blank-name-test
(testing "PUT /api/ee/document/id - basic document update"
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")}]
(is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
(mt/user-http-request :crowberto
:put 400 (format "ee/document/%s" document-id)
{:name ""
- :document (text->prose-mirror-ast "Doc 1")}))))))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}))))))
(deftest put-document-update-long-name-test
(testing "PUT /api/ee/document/id - basic document update"
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")}]
(is (=? {:errors {:name "value must be a non-blank string between 1 and 254 characters."}}
(mt/user-http-request :crowberto
:put 400 (format "ee/document/%s" document-id)
{:name (apply str (repeat 255 "c"))
- :document (text->prose-mirror-ast "Doc 1")}))))))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}))))))
(deftest put-document-nonexistent-document-test
(testing "PUT /api/ee/document/id - should return 404 for non-existent document"
(mt/user-http-request :crowberto
- :put 404 "ee/document/99999" {:name "Non-existent Document" :document (text->prose-mirror-ast "Doc")})))
+ :put 404 "ee/document/99999" {:name "Non-existent Document" :document (documents.test-util/text->prose-mirror-ast "Doc")})))
(deftest put-document-with-no-perms-test
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {document-id :id} {:collection_id coll-id
:name "Test Document"
- :document (text->prose-mirror-ast "Doc 1")}]
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}]
(mt/with-non-admin-groups-no-collection-perms coll-id
(mt/user-http-request :rasta :put 403 (str "ee/document/" document-id)
{:name "Meow"}))))
@@ -93,14 +88,14 @@
(mt/with-non-admin-groups-no-collection-perms coll-id
(mt/user-http-request :rasta :post 403 "ee/document/"
{:name "Foo"
- :document (text->prose-mirror-ast "Bar")
+ :document (documents.test-util/text->prose-mirror-ast "Bar")
:collection_id coll-id}))))
(deftest get-document-test-requires-documents-feature
(testing "GET /api/ee/document/id"
(mt/with-premium-features #{}
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Doc 1")}]
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}]
(testing "should not get the document"
(mt/user-http-request :crowberto
:get 402 (format "ee/document/%s" document-id)))))))
@@ -108,12 +103,12 @@
(deftest get-document-test
(testing "GET /api/ee/document/id"
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Doc 1")}]
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")}]
(testing "should get the document"
(let [result (mt/user-http-request :crowberto
:get 200 (format "ee/document/%s" document-id))]
(is (partial= {:name "Test Document"
- :document (text->prose-mirror-ast "Doc 1")} result))
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")} result))
result))
(testing "should return 404 for non-existent document"
(mt/user-http-request :crowberto
@@ -122,14 +117,14 @@
(deftest get-documents-test
(testing "GET /api/ee/document"
(mt/with-temp [:model/Document _ {:name "Document 1"
- :document (text->prose-mirror-ast "Initial Doc 1")}
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc 1")}
:model/Document _ {:name "Document 2"
- :document (text->prose-mirror-ast "Initial Doc 2")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc 2")}]
(testing "should get existing documents"
(let [result (:items (mt/user-http-request :crowberto
:get 200 "ee/document/"))]
(is (set/subset? #{"Document 1" "Document 2"} (set (map :name result))))
- (is (set/subset? #{(text->prose-mirror-ast "Initial Doc 1") (text->prose-mirror-ast "Initial Doc 2")} (set (map :document result))))
+ (is (set/subset? #{(documents.test-util/text->prose-mirror-ast "Initial Doc 1") (documents.test-util/text->prose-mirror-ast "Initial Doc 2")} (set (map :document result))))
result))))
(testing "should return 404 for non-existent document"
(mt/user-http-request :crowberto
@@ -141,7 +136,7 @@
:model/Collection {new-collection-id :id} {:name "New Collection"}
:model/Document {document-id :id} {:collection_id old-collection-id
:name "Integration Test Document"
- :document (text->prose-mirror-ast "Integration test doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Integration test doc")}]
;; Create cards associated with the document
(mt/with-temp [:model/Card {card1-id :id} {:name "Integration Card 1"
:document_id document-id
@@ -194,7 +189,7 @@
:model/Collection {collection2-id :id} {:name "Permission Collection 2"}
:model/Document {document-id :id} {:collection_id collection1-id
:name "Permission Test Document"
- :document (text->prose-mirror-ast "Permission test doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Permission test doc")}]
;; Create cards in the original collection
(mt/with-temp [:model/Card {card-id :id} {:name "Permission Test Card"
:document_id document-id
@@ -316,7 +311,7 @@
(let [result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Document with Empty Cards To Create"
- :document (text->prose-mirror-ast "Doc with empty cards")
+ :document (documents.test-util/text->prose-mirror-ast "Doc with empty cards")
:cards {}})]
(is (pos? (:id result)))))))
@@ -326,7 +321,7 @@
(let [result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Document with Nil Cards To Create"
- :document (text->prose-mirror-ast "Doc with nil cards")
+ :document (documents.test-util/text->prose-mirror-ast "Doc with nil cards")
:cards nil})]
(is (pos? (:id result)))))))
@@ -334,7 +329,7 @@
(testing "PUT /api/ee/document/:id - update document with new cards via cards"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}]
(let [cards-to-create {-10 {:name "Updated Generated Card 1"
:type :question
@@ -406,7 +401,7 @@
(mt/user-http-request :crowberto
:post 400 "ee/document/"
{:name "Document with Invalid Keys"
- :document (text->prose-mirror-ast "Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Doc")
:cards {1 {:name "Invalid Key Card"
:type :question
:dataset_query (mt/mbql-query venues)
@@ -417,14 +412,14 @@
(mt/user-http-request :crowberto
:post 400 "ee/document/"
{:name "Document with Invalid Card"
- :document (text->prose-mirror-ast "Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Doc")
:cards {-1 {:name "Incomplete Card"}}})) ; missing required fields
(testing "should reject non-map card data"
(mt/user-http-request :crowberto
:post 400 "ee/document/"
{:name "Document with Invalid Card Data"
- :document (text->prose-mirror-ast "Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Doc")
:cards {-1 "not a map"}})))))
(deftest cards-to-create-transaction-rollback-test
@@ -438,7 +433,7 @@
(mt/user-http-request :crowberto
:post 403 "ee/document/"
{:name "Document That Should Rollback"
- :document (text->prose-mirror-ast "Doc that should rollback")
+ :document (documents.test-util/text->prose-mirror-ast "Doc that should rollback")
:cards invalid-cards})
;; Verify no document was created
@@ -447,7 +442,7 @@
(deftest put-document-cards-to-create-transaction-rollback-test
(testing "PUT /api/ee/document/:id - transaction rollback on card creation failure"
(mt/with-temp [:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")}]
(let [initial-document (t2/select-one :model/Document :id document-id)
invalid-cards {-1 {:name "Card with Invalid Query"
:type :question
@@ -458,7 +453,7 @@
(mt/user-http-request :crowberto
:put 403 (format "ee/document/%s" document-id)
{:name "Document That Should Rollback"
- :document (text->prose-mirror-ast "Doc that should rollback")
+ :document (documents.test-util/text->prose-mirror-ast "Doc that should rollback")
:cards invalid-cards})
;; Verify document wasn't updated
@@ -478,7 +473,7 @@
result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Root Collection Document"
- :document (text->prose-mirror-ast "Doc in root collection")
+ :document (documents.test-util/text->prose-mirror-ast "Doc in root collection")
:collection_id nil
:cards cards-to-create})
created-cards (t2/select :model/Card :document_id (:id result))
@@ -533,7 +528,7 @@
(testing "PUT /api/ee/document/:id - normalizes card type from :model to :question and removes dashboard_id"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}
:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
(let [cards-to-create {-10 {:name "Updated Model Card"
@@ -741,7 +736,7 @@
(mt/with-model-cleanup [:model/Document :model/Card]
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {other-doc-id :id} {:name "Other Document"
- :document (text->prose-mirror-ast "Other Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Other Doc")
:collection_id col-id}
:model/Card {associated-card :id} {:name "Already Associated Card"
:type :question
@@ -791,7 +786,7 @@
(testing "Cards already belonging to the current document are not cloned"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}
:model/Card {existing-card-in-doc :id} {:name "Card Already in Document"
:type :question
@@ -844,7 +839,7 @@
(testing "PUT /api/ee/document/:id - clones existing cards and substitutes IDs in AST"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}
:model/Card {existing-card-1 :id} {:name "Existing Card 1"
:type :question
@@ -905,7 +900,7 @@
(testing "PUT /api/ee/document/:id - handles both cloned existing cards and new cards"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}
:model/Card {existing-card :id} {:name "Existing Card"
:type :question
@@ -1091,7 +1086,7 @@
(testing "Multiple updates with same cards don't create duplicate clones"
(mt/with-temp [:model/Collection {col-id :id} {}
:model/Document {document-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Initial Doc")
+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")
:collection_id col-id}
:model/Card {existing-card :id} {:name "Existing Card"
:type :question
@@ -1148,7 +1143,7 @@
(let [result (mt/user-http-request :rasta
:post 200 "ee/document/"
{:name "Rasta's Document"
- :document (text->prose-mirror-ast "Created by Rasta")
+ :document (documents.test-util/text->prose-mirror-ast "Created by Rasta")
:collection_id write-col})]
(is (pos? (:id result)))
(is (= "Rasta's Document" (:name result)))
@@ -1158,14 +1153,14 @@
(mt/user-http-request :rasta
:post 403 "ee/document/"
{:name "Should Fail"
- :document (text->prose-mirror-ast "Should not be created")
+ :document (documents.test-util/text->prose-mirror-ast "Should not be created")
:collection_id read-only-col}))
(testing "POST /api/ee/document/ - :rasta cannot create documents in no-access collections"
(mt/user-http-request :rasta
:post 403 "ee/document/"
{:name "Should Fail"
- :document (text->prose-mirror-ast "Should not be created")
+ :document (documents.test-util/text->prose-mirror-ast "Should not be created")
:collection_id no-access-col})))))))
(deftest rasta-document-update-permissions-test
@@ -1185,19 +1180,19 @@
(testing "PUT /api/ee/document/:id - :rasta can update documents in collections with write access"
(mt/with-temp [:model/Document {doc-id :id} {:name "Original Document"
- :document (text->prose-mirror-ast "Original content")
+ :document (documents.test-util/text->prose-mirror-ast "Original content")
:collection_id write-col}]
(let [result (mt/user-http-request :rasta
:put 200 (format "ee/document/%s" doc-id)
{:name "Updated by Rasta"
- :document (text->prose-mirror-ast "Updated content")})]
+ :document (documents.test-util/text->prose-mirror-ast "Updated content")})]
(is (= doc-id (:id result)))
(is (= "Updated by Rasta" (:name result)))
- (is (= (text->prose-mirror-ast "Updated content") (:document result))))))
+ (is (= (documents.test-util/text->prose-mirror-ast "Updated content") (:document result))))))
(testing "PUT /api/ee/document/:id - :rasta cannot update documents in read-only collections"
(mt/with-temp [:model/Document {doc-id :id} {:name "Read Only Document"
- :document (text->prose-mirror-ast "Read only content")
+ :document (documents.test-util/text->prose-mirror-ast "Read only content")
:collection_id read-only-col}]
(mt/user-http-request :rasta
:put 403 (format "ee/document/%s" doc-id)
@@ -1205,7 +1200,7 @@
(testing "PUT /api/ee/document/:id - :rasta cannot update documents in no-access collections"
(mt/with-temp [:model/Document {doc-id :id} {:name "No Access Document"
- :document (text->prose-mirror-ast "No access content")
+ :document (documents.test-util/text->prose-mirror-ast "No access content")
:collection_id no-access-col}]
(mt/user-http-request :rasta
:put 403 (format "ee/document/%s" doc-id)
@@ -1229,7 +1224,7 @@
(testing "PUT /api/ee/document/:id - :rasta can move documents between collections with write access to both"
(mt/with-temp [:model/Document {doc-id :id} {:name "Document to Move"
- :document (text->prose-mirror-ast "Moving document")
+ :document (documents.test-util/text->prose-mirror-ast "Moving document")
:collection_id write-col}]
(let [result (mt/user-http-request :rasta
:put 200 (format "ee/document/%s" doc-id)
@@ -1241,7 +1236,7 @@
(testing "PUT /api/ee/document/:id - :rasta cannot move documents from collections without write access"
(mt/with-temp [:model/Document {doc-id :id} {:name "Cannot Move From Here"
- :document (text->prose-mirror-ast "No permission to move")
+ :document (documents.test-util/text->prose-mirror-ast "No permission to move")
:collection_id read-only-col}]
(mt/user-http-request :rasta
:put 403 (format "ee/document/%s" doc-id)
@@ -1251,7 +1246,7 @@
(testing "PUT /api/ee/document/:id - :rasta cannot move documents to collections without write access"
(mt/with-temp [:model/Document {doc-id :id} {:name "Cannot Move To There"
- :document (text->prose-mirror-ast "No permission for destination")
+ :document (documents.test-util/text->prose-mirror-ast "No permission for destination")
:collection_id write-col}]
(mt/user-http-request :rasta
:put 403 (format "ee/document/%s" doc-id)
@@ -1276,29 +1271,29 @@
(testing "GET /api/ee/document/:id - :rasta can read documents from collections with write access"
(mt/with-temp [:model/Document {doc-id :id} {:name "Write Access Document"
- :document (text->prose-mirror-ast "Can read with write access")
+ :document (documents.test-util/text->prose-mirror-ast "Can read with write access")
:collection_id write-col}]
(let [result (mt/user-http-request :rasta
:get 200 (format "ee/document/%s" doc-id))]
(is (= "Write Access Document" (:name result)))
- (is (= (text->prose-mirror-ast "Can read with write access") (:document result)))
+ (is (= (documents.test-util/text->prose-mirror-ast "Can read with write access") (:document result)))
(testing "includes can_write=true for collections with write access"
(is (true? (get result :can_write)))))))
(testing "GET /api/ee/document/:id - :rasta can read documents from collections with read access"
(mt/with-temp [:model/Document {doc-id :id} {:name "Read Access Document"
- :document (text->prose-mirror-ast "Can read with read access")
+ :document (documents.test-util/text->prose-mirror-ast "Can read with read access")
:collection_id read-only-col}]
(let [result (mt/user-http-request :rasta
:get 200 (format "ee/document/%s" doc-id))]
(is (= "Read Access Document" (:name result)))
- (is (= (text->prose-mirror-ast "Can read with read access") (:document result)))
+ (is (= (documents.test-util/text->prose-mirror-ast "Can read with read access") (:document result)))
(testing "includes can_write=false for collections with only read access"
(is (false? (get result :can_write)))))))
(testing "GET /api/ee/document/:id - :rasta cannot read documents from collections without access"
(mt/with-temp [:model/Document {doc-id :id} {:name "No Access Document"
- :document (text->prose-mirror-ast "Cannot read this")
+ :document (documents.test-util/text->prose-mirror-ast "Cannot read this")
:collection_id no-access-col}]
(mt/user-http-request :rasta
:get 403 (format "ee/document/%s" doc-id)))))))))
@@ -1320,13 +1315,13 @@
(testing "GET /api/ee/document - :rasta only sees documents from accessible collections"
(mt/with-temp [:model/Document _ {:name "Doc in Write Collection"
- :document (text->prose-mirror-ast "In write collection")
+ :document (documents.test-util/text->prose-mirror-ast "In write collection")
:collection_id write-col}
:model/Document _ {:name "Doc in Read Collection"
- :document (text->prose-mirror-ast "In read collection")
+ :document (documents.test-util/text->prose-mirror-ast "In read collection")
:collection_id read-only-col}
:model/Document _ {:name "Doc in No Access Collection"
- :document (text->prose-mirror-ast "In no access collection")
+ :document (documents.test-util/text->prose-mirror-ast "In no access collection")
:collection_id no-access-col}]
(let [result (mt/user-http-request :rasta :get 200 "ee/document/")
doc-names (set (map :name (:items result)))]
@@ -1347,7 +1342,7 @@
(testing "PUT /api/ee/document/:id - basic document archiving"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {doc-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Test content")
+ :document (documents.test-util/text->prose-mirror-ast "Test content")
:collection_id coll-id}]
(testing "can archive document with archived=true"
(let [result (mt/user-http-request :crowberto
@@ -1375,7 +1370,7 @@
(testing "Document archiving includes associated cards"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {doc-id :id} {:name "Document with Cards"
- :document (text->prose-mirror-ast "Doc with cards")
+ :document (documents.test-util/text->prose-mirror-ast "Doc with cards")
:collection_id coll-id}
:model/Card {card1-id :id} {:name "Associated Card 1"
:document_id doc-id
@@ -1425,10 +1420,10 @@
(mt/with-temp [:model/Collection {read-only-col :id} {}
:model/Collection {write-col :id} {}
:model/Document {read-only-doc-id :id} {:name "Read Only Document"
- :document (text->prose-mirror-ast "Read only")
+ :document (documents.test-util/text->prose-mirror-ast "Read only")
:collection_id read-only-col}
:model/Document {write-doc-id :id} {:name "Write Document"
- :document (text->prose-mirror-ast "Writable")
+ :document (documents.test-util/text->prose-mirror-ast "Writable")
:collection_id write-col}]
(mt/with-group-for-user [group :rasta]
@@ -1461,10 +1456,10 @@
(testing "Collection archiving includes documents and associated cards"
(mt/with-temp [:model/Collection {coll-id :id} {:name "Collection to Archive"}
:model/Document {doc1-id :id} {:name "Document 1"
- :document (text->prose-mirror-ast "Doc 1")
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")
:collection_id coll-id}
:model/Document {doc2-id :id} {:name "Document 2"
- :document (text->prose-mirror-ast "Doc 2")
+ :document (documents.test-util/text->prose-mirror-ast "Doc 2")
:collection_id coll-id}
:model/Card {card1-id :id} {:name "Associated Card 1"
:document_id doc1-id
@@ -1521,7 +1516,7 @@
(testing "Document archived_directly flag behavior"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {doc-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Test")
+ :document (documents.test-util/text->prose-mirror-ast "Test")
:collection_id coll-id}
:model/Card {card-id :id} {:name "Associated Card"
:document_id doc-id
@@ -1591,10 +1586,10 @@
(testing "Archived documents are properly filtered from various endpoints"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {active-doc-id :id} {:name "Active Document"
- :document (text->prose-mirror-ast "Active")
+ :document (documents.test-util/text->prose-mirror-ast "Active")
:collection_id coll-id}
:model/Document {archived-doc-id :id} {:name "Archived Document"
- :document (text->prose-mirror-ast "Archived")
+ :document (documents.test-util/text->prose-mirror-ast "Archived")
:collection_id coll-id
:archived true}]
@@ -1620,7 +1615,7 @@
(deftest document-archive-events-test
(testing "Document archiving publishes appropriate events"
(mt/with-temp [:model/Document {doc-id :id} {:name "Event Test Document"
- :document (text->prose-mirror-ast "Event test")}]
+ :document (documents.test-util/text->prose-mirror-ast "Event test")}]
(testing "archiving document publishes archive event"
(mt/with-model-cleanup [:model/Document]
@@ -1650,7 +1645,7 @@
(deftest document-archive-transaction-rollback-test
(testing "Document archiving transaction rollback on failure"
(mt/with-temp [:model/Document {doc-id :id} {:name "Transaction Test Document"
- :document (text->prose-mirror-ast "Transaction test")}
+ :document (documents.test-util/text->prose-mirror-ast "Transaction test")}
:model/Card {card-id :id} {:name "Associated Card"
:document_id doc-id
:dataset_query (mt/mbql-query venues)}]
@@ -1673,17 +1668,17 @@
(testing "Mixed archiving scenarios - documents with different archival states"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {directly-archived-doc :id} {:name "Directly Archived Document"
- :document (text->prose-mirror-ast "Direct")
+ :document (documents.test-util/text->prose-mirror-ast "Direct")
:collection_id coll-id
:archived true
:archived_directly true}
:model/Document {collection-archived-doc :id} {:name "Collection Archived Document"
- :document (text->prose-mirror-ast "Collection")
+ :document (documents.test-util/text->prose-mirror-ast "Collection")
:collection_id coll-id
:archived false
:archived_directly false}
:model/Document {active-doc :id} {:name "Active Document"
- :document (text->prose-mirror-ast "Active")
+ :document (documents.test-util/text->prose-mirror-ast "Active")
:collection_id coll-id}]
(testing "unarchiving collection only restores collection-archived documents"
@@ -1710,7 +1705,7 @@
(testing "archiving already archived document is idempotent"
(mt/with-temp [:model/Document {doc-id :id} {:name "Already Archived"
- :document (text->prose-mirror-ast "Already archived")
+ :document (documents.test-util/text->prose-mirror-ast "Already archived")
:archived true
:archived_directly true}]
(let [result (mt/user-http-request :crowberto
@@ -1721,7 +1716,7 @@
(testing "unarchiving already active document is idempotent"
(mt/with-temp [:model/Document {doc-id :id} {:name "Already Active"
- :document (text->prose-mirror-ast "Already active")}]
+ :document (documents.test-util/text->prose-mirror-ast "Already active")}]
(let [result (mt/user-http-request :crowberto
:put 200 (format "ee/document/%s" doc-id)
{:archived false})]
@@ -1730,7 +1725,7 @@
(testing "archiving document in trash collection"
(let [trash-collection-id (collection/trash-collection-id)]
(mt/with-temp [:model/Document {doc-id :id} {:name "Document in Trash"
- :document (text->prose-mirror-ast "In trash")
+ :document (documents.test-util/text->prose-mirror-ast "In trash")
:collection_id trash-collection-id}]
;; Should be able to archive document in trash
(let [result (mt/user-http-request :crowberto
@@ -1740,7 +1735,7 @@
(testing "document with no associated cards"
(mt/with-temp [:model/Document {doc-id :id} {:name "No Cards Document"
- :document (text->prose-mirror-ast "No cards")}]
+ :document (documents.test-util/text->prose-mirror-ast "No cards")}]
(let [result (mt/user-http-request :crowberto
:put 200 (format "ee/document/%s" doc-id)
{:archived true})]
@@ -1750,20 +1745,20 @@
(testing "archiving and updating other fields simultaneously"
(mt/with-temp [:model/Document {doc-id :id} {:name "Original Name"
- :document (text->prose-mirror-ast "Original")}]
+ :document (documents.test-util/text->prose-mirror-ast "Original")}]
(let [result (mt/user-http-request :crowberto
:put 200 (format "ee/document/%s" doc-id)
{:archived true
:name "Updated Name"
- :document (text->prose-mirror-ast "Updated content")})]
+ :document (documents.test-util/text->prose-mirror-ast "Updated content")})]
(is (true? (:archived result)))
(is (= "Updated Name" (:name result)))
- (is (= (text->prose-mirror-ast "Updated content") (:document result))))))))
+ (is (= (documents.test-util/text->prose-mirror-ast "Updated content") (:document result))))))))
(deftest delete-document-basic-test
(testing "DELETE /api/ee/document/:id - basic document deletion"
(mt/with-temp [:model/Document {doc-id :id} {:name "Test Document"
- :document (text->prose-mirror-ast "Test content")
+ :document (documents.test-util/text->prose-mirror-ast "Test content")
:archived true}]
(testing "can delete archived document"
(mt/user-http-request :crowberto :delete (format "ee/document/%s" doc-id))
@@ -1777,7 +1772,7 @@
(deftest delete-document-not-archived-test
(testing "DELETE /api/ee/document/:id - cannot delete non-archived document"
(mt/with-temp [:model/Document {doc-id :id} {:name "Active Document"
- :document (text->prose-mirror-ast "Active content")
+ :document (documents.test-util/text->prose-mirror-ast "Active content")
:archived false}]
(testing "returns 400 error when trying to delete non-archived document"
(mt/user-http-request :crowberto :delete 400 (format "ee/document/%s" doc-id))
@@ -1791,11 +1786,11 @@
(mt/with-temp [:model/Collection {read-only-col :id} {}
:model/Collection {write-col :id} {}
:model/Document {read-only-doc-id :id} {:name "Read Only Document"
- :document (text->prose-mirror-ast "Read only")
+ :document (documents.test-util/text->prose-mirror-ast "Read only")
:collection_id read-only-col
:archived true}
:model/Document {write-doc-id :id} {:name "Write Document"
- :document (text->prose-mirror-ast "Writable")
+ :document (documents.test-util/text->prose-mirror-ast "Writable")
:collection_id write-col
:archived true}]
@@ -1821,7 +1816,7 @@
(testing "DELETE /api/ee/document/:id - deletes document with associated cards"
(mt/with-temp [:model/Collection {coll-id :id} {}
:model/Document {doc-id :id} {:name "Document with Cards"
- :document (text->prose-mirror-ast "Doc with cards")
+ :document (documents.test-util/text->prose-mirror-ast "Doc with cards")
:collection_id coll-id
:archived true}
:model/Card {card1-id :id} {:name "Associated Card 1"
@@ -1858,7 +1853,7 @@
(deftest delete-document-events-test
(testing "DELETE /api/ee/document/:id - publishes delete event"
(mt/with-temp [:model/Document {doc-id :id} {:name "Event Test Document"
- :document (text->prose-mirror-ast "Event test")
+ :document (documents.test-util/text->prose-mirror-ast "Event test")
:archived true}]
(let [events (atom [])]
(with-redefs [events/publish-event! (fn [topic event]
@@ -1878,7 +1873,7 @@
(let [existing-doc-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Existing Document"
- :document (text->prose-mirror-ast "Existing doc")
+ :document (documents.test-util/text->prose-mirror-ast "Existing doc")
:collection_id collection-id
:collection_position 3})
existing-doc-id (:id existing-doc-result)]
@@ -1888,7 +1883,7 @@
(let [new-doc-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "New Document"
- :document (text->prose-mirror-ast "New doc")
+ :document (documents.test-util/text->prose-mirror-ast "New doc")
:collection_id collection-id
:collection_position 3})]
;; New document should have position 3
@@ -1902,7 +1897,7 @@
(let [no-position-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "No Position Document"
- :document (text->prose-mirror-ast "No position doc")
+ :document (documents.test-util/text->prose-mirror-ast "No position doc")
:collection_id collection-id})]
(is (nil? (:collection_position no-position-result)))))))))
@@ -1913,19 +1908,19 @@
(let [doc1-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Document 1"
- :document (text->prose-mirror-ast "Doc 1")
+ :document (documents.test-util/text->prose-mirror-ast "Doc 1")
:collection_id collection-id
:collection_position 1})
doc2-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Document 2"
- :document (text->prose-mirror-ast "Doc 2")
+ :document (documents.test-util/text->prose-mirror-ast "Doc 2")
:collection_id collection-id
:collection_position 2})
doc3-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Document 3"
- :document (text->prose-mirror-ast "Doc 3")
+ :document (documents.test-util/text->prose-mirror-ast "Doc 3")
:collection_id collection-id
:collection_position 3})
doc1-id (:id doc1-result)
@@ -1969,7 +1964,7 @@
(let [document-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Positioned Document"
- :document (text->prose-mirror-ast "Positioned doc")
+ :document (documents.test-util/text->prose-mirror-ast "Positioned doc")
:collection_id collection-id
:collection_position 5})]
(is (= 5 (:collection_position document-result)))))
@@ -1978,7 +1973,7 @@
(let [document-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Update Position Document"
- :document (text->prose-mirror-ast "Update position doc")
+ :document (documents.test-util/text->prose-mirror-ast "Update position doc")
:collection_id collection-id
:collection_position 5})
document-id (:id document-result)
@@ -1991,7 +1986,7 @@
(let [document-result (mt/user-http-request :crowberto
:post 200 "ee/document/"
{:name "Nil Position Document"
- :document (text->prose-mirror-ast "Nil position doc")
+ :document (documents.test-util/text->prose-mirror-ast "Nil position doc")
:collection_id collection-id
:collection_position 5})
document-id (:id document-result)
@@ -2000,6 +1995,298 @@
{:collection_position nil})]
(is (nil? (:collection_position updated-result))))))))
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | PUBLIC SHARING ENDPOINTS |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defn- shared-document []
+ {:public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)})
+
+(defn- document-with-public-link
+ "Create test Document data including a public UUID and made_public_by_id.
+
+ Accepts an `overrides` map to customize the returned Document attributes. Base attributes include
+ `:name`, `:document` (ProseMirror AST), `:public_uuid`, and `:made_public_by_id`."
+ [overrides]
+ (merge {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")}
+ (shared-document)
+ overrides))
+
+;;; -------------------------------------- POST /api/ee/document/:id/public-link ---------------------------------------
+
+(deftest share-document-test
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (testing "Test that we can share a Document"
+ (mt/with-temp [:model/Document document {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")}]
+ (let [{uuid :uuid} (mt/user-http-request :crowberto :post 200
+ (format "ee/document/%d/public-link" (:id document)))]
+ (is (t2/exists? :model/Document :id (:id document), :public_uuid uuid))
+ (testing "Test that if a Document has already been shared we reuse the existing UUID"
+ (is (= uuid
+ (:uuid (mt/user-http-request :crowberto :post 200
+ (format "ee/document/%d/public-link" (:id document))))))))))
+
+ (mt/with-temp [:model/Document document {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")}]
+ (testing "Test that we *cannot* share a Document if we aren't admins"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 (format "ee/document/%d/public-link" (:id document))))))
+
+ (testing "Test that we *cannot* share a Document if the setting is disabled"
+ (mt/with-temporary-setting-values [enable-public-sharing false]
+ (is (= "Public sharing is not enabled."
+ (mt/user-http-request :crowberto :post 400 (format "ee/document/%d/public-link" (:id document))))))))
+
+ (testing "Test that we get a 404 if the Document doesn't exist"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :post 404 (format "ee/document/%d/public-link" Integer/MAX_VALUE)))))))
+
+(deftest delete-public-link-test
+ (testing "DELETE /api/ee/document/:id/public-link"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (testing "Test that we can unshare a Document"
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (mt/user-http-request :crowberto :delete 204 (format "ee/document/%d/public-link" (:id document)))
+ (is (not (t2/exists? :model/Document :id (:id document), :public_uuid (:public_uuid document))))))
+
+ (testing "Test that we *cannot* unshare a Document if we are not admins"
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 (format "ee/document/%d/public-link" (:id document)))))))
+
+ (testing "Test that we get a 404 if Document isn't shared"
+ (mt/with-temp [:model/Document document {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")}]
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :delete 404 (format "ee/document/%d/public-link" (:id document)))))))
+
+ (testing "Test that we get a 404 if Document doesn't exist"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :delete 404 (format "ee/document/%d/public-link" Integer/MAX_VALUE))))))))
+
+(deftest fetch-public-documents-test
+ (testing "GET /api/ee/document/public"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document _document (document-with-public-link {:name "Public Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public content")})]
+ (testing "Test that it requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/document/public"))))
+ (testing "Test that superusers can fetch a list of publicly-accessible documents"
+ (is (= [{:name true, :id true, :public_uuid true}]
+ (for [doc (mt/user-http-request :crowberto :get 200 "ee/document/public")]
+ (m/map-vals boolean doc)))))))))
+
+;;; ---------------------------------------- GET /api/ee/public/document/:uuid ----------------------------------------------
+
+(deftest fetch-public-document-test
+ (testing "GET /api/ee/public/document/:uuid"
+ (testing "Test that we can fetch a public Document"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")})]
+ (is (partial= {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")
+ :id (:id document)}
+ (mt/client :get 200 (str "ee/public/document/" (:public_uuid document))))))))))
+
+(deftest public-document-returns-only-safe-fields-test
+ (testing "GET /api/ee/public/document/:uuid should only return safe fields"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")})]
+ (let [result (mt/client :get 200 (str "ee/public/document/" (:public_uuid document)))]
+ (testing "Should include safe fields"
+ (is (contains? result :id))
+ (is (contains? result :name))
+ (is (contains? result :document))
+ (is (contains? result :created_at))
+ (is (contains? result :updated_at)))
+ (testing "Should not include sensitive fields"
+ (is (not (contains? result :public_uuid)))
+ (is (not (contains? result :made_public_by_id)))
+ (is (not (contains? result :collection_id)))
+ (is (not (contains? result :description)))))))))
+
+(deftest get-public-document-errors-test
+ (testing "GET /api/ee/public/document/:uuid"
+ (testing "Shouldn't be able to fetch a public Document if public sharing is disabled"
+ (mt/with-temporary-setting-values [enable-public-sharing false]
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (is (= "API endpoint does not exist."
+ (mt/client :get 404 (str "ee/public/document/" (:public_uuid document))))))))
+
+ (testing "Should get a 404 if the Document doesn't exist"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (is (= "Not found."
+ (mt/client :get 404 (str "ee/public/document/" (random-uuid)))))))))
+
+(deftest share-archived-document-test
+ (testing "POST /api/ee/document/:id/public-link should not work for archived documents"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document {:name "Archived Document"
+ :document (documents.test-util/text->prose-mirror-ast "Archived content")
+ :archived true}]
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :post 404 (format "ee/document/%d/public-link" (:id document)))))))))
+
+(deftest unshare-archived-document-test
+ (testing "DELETE /api/ee/document/:id/public-link should not work for archived documents"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Archived Shared Document"
+ :document (documents.test-util/text->prose-mirror-ast "Archived shared content")
+ :archived true})]
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :delete 404 (format "ee/document/%d/public-link" (:id document)))))))))
+
+(deftest public-document-not-accessible-when-archived-test
+ (testing "GET /api/ee/public/document/:uuid should not work for archived documents"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (let [uuid (:public_uuid document)]
+ (testing "Document is accessible when not archived"
+ (is (= 200
+ (:status (mt/client-full-response :get (str "ee/public/document/" uuid))))))
+ (testing "Document is not accessible after archiving"
+ (t2/update! :model/Document (:id document) {:archived true})
+ (is (= "Not found."
+ (mt/client :get 404 (str "ee/public/document/" uuid))))))))))
+
+(deftest public-document-listing-excludes-archived-test
+ (testing "GET /api/ee/document/public should not include archived documents"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document active-doc (document-with-public-link {:name "Active Public Document"
+ :document (documents.test-util/text->prose-mirror-ast "Active content")})
+ :model/Document _archived-doc (document-with-public-link {:name "Archived Public Document"
+ :document (documents.test-util/text->prose-mirror-ast "Archived content")
+ :archived true})]
+ (let [public-docs (mt/user-http-request :crowberto :get 200 "ee/document/public")
+ public-doc-ids (set (map :id public-docs))]
+ (testing "Active document should be in the list"
+ (is (contains? public-doc-ids (:id active-doc))))
+ (testing "Archived document should not be in the list"
+ (is (= 1 (count public-docs)))))))))
+
+(deftest download-document-card-test
+ (testing "POST /api/ee/document/:document-id/card/:card-id/query/:export-format"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:name "Test Card"
+ :dataset_query (mt/mbql-query venues {:limit 10})
+ :display :table
+ :collection_id coll-id}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :collection_id coll-id
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id card-id}}]}}]
+ (t2/update! :model/Card card-id {:document_id doc-id})
+
+ (mt/with-group-for-user [group :rasta {:name "Rasta Group"}]
+ (testing "Read-only users can download"
+ (perms/grant-collection-read-permissions! group coll-id)
+ (let [response (mt/user-http-request :rasta
+ :post 200
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false})]
+ (is (some? response))
+ (is (string? response))))
+
+ (testing "No access returns 403"
+ (perms/revoke-collection-permissions! group coll-id)
+ (mt/user-http-request :rasta
+ :post 403
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false}))
+
+ (testing "Card not in document returns 404"
+ (perms/grant-collection-read-permissions! group coll-id)
+ (mt/with-temp [:model/Card {other-card-id :id} {:name "Other Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :display :table
+ :collection_id coll-id}]
+ (mt/user-http-request :rasta
+ :post 404
+ (format "ee/document/%s/card/%s/query/csv" doc-id other-card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false})))
+
+ (testing "Archived document returns 404"
+ (t2/update! :model/Document doc-id {:archived true})
+ (mt/user-http-request :rasta
+ :post 404
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false})))))))
+
+(deftest download-document-card-respects-download-permissions-test
+ (testing "POST /api/ee/document/:document-id/card/:card-id/query/:export-format respects database download permissions"
+ (mt/with-premium-features #{:documents :advanced-permissions}
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:name "Test Card"
+ :dataset_query (mt/mbql-query venues {:limit 10})
+ :display :table
+ :collection_id coll-id}
+ :model/Document {doc-id :id} {:name "Test Document"
+ :collection_id coll-id
+ :document {:type "doc"
+ :content [{:type "cardEmbed"
+ :attrs {:id card-id}}]}}]
+ (t2/update! :model/Card card-id {:document_id doc-id})
+
+ (let [all-users-group (perms/all-users-group)]
+ ;; Grant collection read permissions so user can access the document
+ (perms/grant-collection-read-permissions! all-users-group coll-id)
+
+ (testing "User without download permissions yields permissions error in body (streaming uses 200)"
+ ;; Set download permissions to :no (no downloads allowed) for All Users group
+ (data-perms/set-database-permission! all-users-group (mt/id) :perms/download-results :no)
+
+ (is (malli= [:map
+ [:status [:= "failed"]]
+ [:error_type [:= "missing-required-permissions"]]
+ [:ex-data [:map
+ [:permissions-error? [:= true]]]]]
+ (mt/user-http-request :rasta
+ :post 200
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false}))))
+
+ (testing "User with limited download permissions (10k rows) can download"
+ (data-perms/set-database-permission! all-users-group (mt/id) :perms/download-results :ten-thousand-rows)
+
+ (let [response (mt/user-http-request :rasta
+ :post 200
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false})]
+ (is (some? response))
+ (is (string? response))))
+
+ (testing "User with full download permissions can download"
+ (data-perms/set-database-permission! all-users-group (mt/id) :perms/download-results :one-million-rows)
+
+ (let [response (mt/user-http-request :rasta
+ :post 200
+ (format "ee/document/%s/card/%s/query/csv" doc-id card-id)
+ {:parameters []
+ :format_rows false
+ :pivot_results false})]
+ (is (some? response))
+ (is (string? response))))))))))
(defn- prose-mirror-with-smartlink
"Create a ProseMirror AST with a smartlink to a card."
[text card-id]
@@ -2098,7 +2385,7 @@
:type nil}
:model/Document {doc-id :id} {:name "Test Document"
:collection_id remote-synced-id
- :document (text->prose-mirror-ast "Initial")}
+ :document (documents.test-util/text->prose-mirror-ast "Initial")}
:model/Card {card-id :id} {:name "Regular Card"
:collection_id regular-id
:dataset_query (mt/mbql-query venues)}]
@@ -2117,7 +2404,7 @@
:type "remote-synced"}
:model/Document {doc-id :id} {:name "Test Document"
:collection_id remote-synced-id
- :document (text->prose-mirror-ast "Initial")}
+ :document (documents.test-util/text->prose-mirror-ast "Initial")}
:model/Card {card-id :id} {:name "Remote-Synced Card"
:collection_id remote-synced-id
:dataset_query (mt/mbql-query venues)}]
@@ -2183,7 +2470,7 @@
:type nil}
:model/Document {doc-id :id} {:name "Doc without refs"
:collection_id remote-synced-id
- :document (text->prose-mirror-ast "No references")}]
+ :document (documents.test-util/text->prose-mirror-ast "No references")}]
(testing "Successfully moves when document has no remote-synced references"
(let [response (mt/user-http-request :crowberto
@@ -2235,7 +2522,7 @@
:dataset_query (mt/mbql-query venues)}
:model/Document {doc-id :id} {:name "Test Doc"
:collection_id remote-synced-id
- :document (text->prose-mirror-ast "Initial")}]
+ :document (documents.test-util/text->prose-mirror-ast "Initial")}]
(testing "Throws exception when adding non-remote-synced ref and staying in remote-synced collection"
(let [response (mt/user-http-request :crowberto
diff --git a/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj b/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj
index 2000c79fb1a..62e70c74d7c 100644
--- a/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/documents/models/document_test.clj
@@ -7,10 +7,25 @@
[metabase.permissions.core :as perms]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
+ [metabase.test.util :as tu]
+ [metabase.util :as u]
[toucan2.core :as t2]))
(use-fixtures :once (fixtures/initialize :db :test-users))
+(deftest public-sharing-test
+ (testing "Document's :public_uuid visibility based on public sharing setting"
+ (testing "comes back if public sharing is enabled"
+ (tu/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document {:public_uuid (str (random-uuid))}]
+ (is (=? u/uuid-regex
+ (:public_uuid document))))))
+ (testing "comes back as nil if public sharing is disabled"
+ (tu/with-temporary-setting-values [enable-public-sharing false]
+ (mt/with-temp [:model/Document document {:public_uuid (str (random-uuid))}]
+ (is (= nil
+ (:public_uuid document))))))))
+
(deftest sync-document-cards-collection-matching-cards-test
(testing "should only update cards with matching document_id"
(mt/with-temp [:model/Collection {collection-id :id} {:name "Target Collection"}
@@ -340,6 +355,82 @@
(is (= user1-id (get-in doc3 [:creator :id])))
(is (= "Alice" (get-in doc3 [:creator :first_name])))))))))
+(deftest hydrate-document-cards-test
+ (testing "hydrates document cards correctly"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"}
+ :model/Card {card1-id :id} {:name "Card 1"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id document-id}
+ :model/Card {card2-id :id} {:name "Card 2"
+ :dataset_query (mt/mbql-query venues {:limit 10})
+ :document_id document-id}]
+ (let [hydrated-doc (t2/hydrate (t2/select-one :model/Document :id document-id) :cards)]
+ (testing "cards are hydrated as a map keyed by card ID"
+ (is (map? (:cards hydrated-doc)))
+ (is (= 2 (count (:cards hydrated-doc))))
+ (is (contains? (:cards hydrated-doc) card1-id))
+ (is (contains? (:cards hydrated-doc) card2-id)))
+
+ (testing "cards contain correct data"
+ (is (= "Card 1" (get-in hydrated-doc [:cards card1-id :name])))
+ (is (= "Card 2" (get-in hydrated-doc [:cards card2-id :name])))
+ (is (= document-id (get-in hydrated-doc [:cards card1-id :document_id])))
+ (is (= document-id (get-in hydrated-doc [:cards card2-id :document_id]))))))))
+
+(deftest hydrate-document-cards-excludes-archived-test
+ (testing "hydrated cards exclude archived cards"
+ (mt/with-temp [:model/Document {document-id :id} {:name "Test Document"}
+ :model/Card {active-card-id :id} {:name "Active Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id document-id
+ :archived false}
+ :model/Card {archived-card-id :id} {:name "Archived Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id document-id
+ :archived true}]
+ (let [hydrated-doc (t2/hydrate (t2/select-one :model/Document :id document-id) :cards)]
+ (testing "only active cards are included"
+ (is (= 1 (count (:cards hydrated-doc))))
+ (is (contains? (:cards hydrated-doc) active-card-id))
+ (is (not (contains? (:cards hydrated-doc) archived-card-id))))))))
+
+(deftest hydrate-multiple-documents-cards-test
+ (testing "hydrates cards for multiple documents efficiently"
+ (mt/with-temp [:model/Document {doc1-id :id} {:name "Document 1"}
+ :model/Document {doc2-id :id} {:name "Document 2"}
+ :model/Document {doc3-id :id} {:name "Document 3"}
+ :model/Card {card1-id :id} {:name "Card 1"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id doc1-id}
+ :model/Card {card2-id :id} {:name "Card 2"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id doc1-id}
+ :model/Card {card3-id :id} {:name "Card 3"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id doc2-id}]
+ (let [documents (t2/select :model/Document :id [:in [doc1-id doc2-id doc3-id]])
+ hydrated-docs (t2/hydrate documents :cards)]
+ (testing "all documents have cards field"
+ (is (= 3 (count hydrated-docs)))
+ (doseq [doc hydrated-docs]
+ (is (map? (:cards doc)))))
+
+ (testing "cards are correctly matched to documents"
+ (let [doc1 (first (filter #(= doc1-id (:id %)) hydrated-docs))
+ doc2 (first (filter #(= doc2-id (:id %)) hydrated-docs))
+ doc3 (first (filter #(= doc3-id (:id %)) hydrated-docs))]
+ (testing "document 1 has two cards"
+ (is (= 2 (count (:cards doc1))))
+ (is (contains? (:cards doc1) card1-id))
+ (is (contains? (:cards doc1) card2-id)))
+
+ (testing "document 2 has one card"
+ (is (= 1 (count (:cards doc2))))
+ (is (contains? (:cards doc2) card3-id)))
+
+ (testing "document 3 has no cards"
+ (is (empty? (:cards doc3))))))))))
+
(deftest document-collection-position-field-handling-test
(testing "Document model supports collection_position field"
(mt/with-temp [:model/Collection {collection-id :id} {:name "Test Collection"}
@@ -367,7 +458,7 @@
(let [spec (serdes/make-spec "Document" {})]
(is (= [:archived :archived_directly :content_type :entity_id :name :collection_position]
(:copy spec)))
- (is (= [:view_count :last_viewed_at :dependency_analysis_version] (:skip spec)))
+ (is (= [:view_count :last_viewed_at :public_uuid :made_public_by_id :dependency_analysis_version] (:skip spec)))
(is (contains? (:transform spec) :created_at))
(is (contains? (:transform spec) :document))
(is (contains? (:transform spec) :updated_at))
diff --git a/enterprise/backend/test/metabase_enterprise/documents/test_util.clj b/enterprise/backend/test/metabase_enterprise/documents/test_util.clj
new file mode 100644
index 00000000000..686af8e1a02
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/documents/test_util.clj
@@ -0,0 +1,10 @@
+(ns metabase-enterprise.documents.test-util
+ "Shared test utilities for document tests.")
+
+(defn text->prose-mirror-ast
+ "Convert plain text to a ProseMirror AST structure."
+ [text]
+ {:type "doc"
+ :content [{:type "paragraph"
+ :content [{:type "text"
+ :text text}]}]})
diff --git a/enterprise/backend/test/metabase_enterprise/public_sharing/api_test.clj b/enterprise/backend/test/metabase_enterprise/public_sharing/api_test.clj
new file mode 100644
index 00000000000..634cccc09e6
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/public_sharing/api_test.clj
@@ -0,0 +1,211 @@
+(ns metabase-enterprise.public-sharing.api-test
+ "Tests for public sharing endpoints for EE-only entities (Documents).
+
+ These tests verify that public document endpoints work correctly when routed through the EE module."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.documents.test-util :as documents.test-util]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- document-with-public-link
+ "Create test Document data including a public UUID and made_public_by_id."
+ [overrides]
+ (merge {:name "Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")
+ :public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)}
+ overrides))
+
+;;; ---------------------------------------- Unauthenticated Access -------------------------------------------------------
+
+(deftest unauthenticated-public-document-access-test
+ (testing "EE public document endpoints should work without authentication when feature is enabled"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Unauthenticated Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public content")})]
+ (testing "Can access public document without authentication at /api/ee/public/document"
+ (let [response (mt/client-full-response :get (str "ee/public/document/" (:public_uuid document)))]
+ (is (= 200 (:status response))
+ "Should return 200 OK for public document without auth")
+ (is (contains? (:body response) :name)
+ "Should return document data in response body"))))))))
+
+;;; ---------------------------------------- Premium Feature Requirement -------------------------------------------------
+
+(deftest public-document-requires-documents-feature-test
+ (testing "Public document endpoints should require :documents premium feature"
+ (mt/with-premium-features #{}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Feature Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Test content")})]
+ (testing "Should return generic error when :documents feature is not enabled"
+ (let [response (mt/client-full-response :get (str "ee/public/document/" (:public_uuid document)))]
+ (is (= 400 (:status response))
+ "Should return 400 when feature is not enabled to avoid leaking premium feature information")
+ (is (= "An error occurred." (:body response))))))))))
+
+;;; ---------------------------------------- GET /api/ee/public/document/:uuid ----------------------------------------------
+
+(deftest public-document-card-requires-documents-feature-test
+ (testing "Card query and export endpoints should require :documents premium feature"
+ (mt/with-premium-features #{}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})
+ :model/Card card {:name "Feature Test Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id (:id document)}]
+ (testing "Card query endpoint returns error without feature"
+ (let [response (mt/client-full-response :get (format "ee/public/document/%s/card/%d"
+ (:public_uuid document)
+ (:id card)))]
+ (is (= 400 (:status response))
+ "Should return 400 when feature is not enabled to avoid leaking premium feature information")))
+ (testing "Card export endpoint returns error without feature"
+ (let [response (mt/client-full-response :post (format "ee/public/document/%s/card/%d/csv"
+ (:public_uuid document)
+ (:id card))
+ {})]
+ (is (= 400 (:status response))
+ "Should return 400 when feature is not enabled to avoid leaking premium feature information"))))))))
+
+(deftest fetch-public-document-test
+ (testing "GET /api/ee/public/document/:uuid"
+ (testing "Can fetch a public Document via EE public sharing routes"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")})]
+ (is (partial= {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")
+ :id (:id document)}
+ (mt/client :get 200 (str "ee/public/document/" (:public_uuid document)))))))))))
+
+(deftest public-document-returns-only-safe-fields-test
+ (testing "GET /api/ee/public/document/:uuid should only return safe fields"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Public Test Document"
+ :document (documents.test-util/text->prose-mirror-ast "Public test content")})]
+ (let [result (mt/client :get 200 (str "ee/public/document/" (:public_uuid document)))]
+ (testing "Should include safe fields"
+ (is (contains? result :id))
+ (is (contains? result :name))
+ (is (contains? result :document))
+ (is (contains? result :created_at))
+ (is (contains? result :updated_at)))
+ (testing "Should not include sensitive fields"
+ (is (not (contains? result :public_uuid)))
+ (is (not (contains? result :made_public_by_id)))
+ (is (not (contains? result :collection_id))))))))))
+
+(deftest public-document-hydrates-cards-test
+ (testing "GET /api/ee/public/document/:uuid hydrates cards for public access"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {:name "Document with Cards"})
+ :model/Card {card1-id :id} {:name "Card 1"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id (:id document)}
+ :model/Card {card2-id :id} {:name "Card 2"
+ :dataset_query (mt/mbql-query venues {:limit 10})
+ :document_id (:id document)}]
+ (let [result (mt/client :get 200 (str "ee/public/document/" (:public_uuid document)))]
+ (testing "response includes cards field"
+ (is (contains? result :cards)))
+
+ (testing "cards are returned as a map keyed by card ID"
+ (is (map? (:cards result)))
+ (is (= 2 (count (:cards result))))
+ (is (contains? (:cards result) card1-id))
+ (is (contains? (:cards result) card2-id)))
+
+ (testing "cards contain expected metadata"
+ (is (= "Card 1" (get-in result [:cards card1-id :name])))
+ (is (= "Card 2" (get-in result [:cards card2-id :name])))
+ (is (= card1-id (get-in result [:cards card1-id :id])))
+ (is (= card2-id (get-in result [:cards card2-id :id]))))
+
+ (testing "cards do not include sensitive fields"
+ (is (not (contains? (get-in result [:cards card1-id]) :collection_id)))
+ (is (not (contains? (get-in result [:cards card1-id]) :creator_id))))))))))
+
+(deftest get-public-document-errors-test
+ (testing "GET /api/ee/public/document/:uuid"
+ (testing "Cannot fetch a public Document if public sharing is disabled"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing false]
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (is (= "API endpoint does not exist."
+ (mt/client :get 404 (str "ee/public/document/" (:public_uuid document)))))))))
+
+ (testing "Returns 404 if the Document doesn't exist"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (is (= "Not found."
+ (mt/client :get 404 (str "ee/public/document/" (random-uuid))))))))))
+
+(deftest public-document-not-accessible-when-archived-test
+ (testing "GET /api/ee/public/document/:uuid should not work for archived documents"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (let [uuid (:public_uuid document)]
+ (testing "Document is accessible when not archived"
+ (is (= 200
+ (:status (mt/client-full-response :get (str "ee/public/document/" uuid))))))
+ (testing "Document is not accessible after archiving"
+ (t2/update! :model/Document (:id document) {:archived true})
+ (is (= "Not found."
+ (mt/client :get 404 (str "ee/public/document/" uuid)))))))))))
+
+;;; ------------------------------ GET /api/ee/public/document/:uuid/card/:card-id ---------------------------------------
+
+(deftest fetch-public-document-card-test
+ (testing "GET /api/ee/public/document/:uuid/card/:card-id"
+ (testing "Can run query for card embedded in public document"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})
+ :model/Card card {:name "Test Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id (:id document)}]
+ (let [result (mt/client :get 202 (format "ee/public/document/%s/card/%d" (:public_uuid document) (:id card)))]
+ (is (some? result))
+ (is (= "completed" (:status result))))))))))
+
+(deftest public-document-card-validates-association-test
+ (testing "GET /api/ee/public/document/:uuid/card/:card-id validates card is associated with document"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})
+ :model/Card card {:name "Unassociated Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})}]
+ (is (= "Not found."
+ (mt/client :get 404 (format "ee/public/document/%s/card/%d" (:public_uuid document) (:id card))))))))))
+
+;;; ----------------------- POST /api/ee/public/document/:uuid/card/:card-id/:export-format -------------------------------
+
+(deftest export-public-document-card-test
+ (testing "POST /api/ee/public/document/:uuid/card/:card-id/:export-format"
+ (mt/with-premium-features #{:documents}
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})
+ :model/Card card {:name "Export Test Card"
+ :dataset_query (mt/mbql-query venues {:limit 5})
+ :document_id (:id document)}]
+ (testing "Can export card results as CSV"
+ (let [response (mt/client-full-response :post (format "ee/public/document/%s/card/%d/csv"
+ (:public_uuid document)
+ (:id card))
+ {})]
+ (is (= 200 (:status response)))
+ (is (= "text/csv" (get-in response [:headers "Content-Type"])))))
+
+ (testing "Can export card results as JSON"
+ (let [response (mt/client-full-response :post (format "ee/public/document/%s/card/%d/json"
+ (:public_uuid document)
+ (:id card))
+ {})]
+ (is (= 200 (:status response))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/admin/settings/components/widgets/PublicLinksListing/PublicDocumentResources.tsx b/enterprise/frontend/src/metabase-enterprise/admin/settings/components/widgets/PublicLinksListing/PublicDocumentResources.tsx
new file mode 100644
index 00000000000..8f6e27c00cd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/admin/settings/components/widgets/PublicLinksListing/PublicDocumentResources.tsx
@@ -0,0 +1,29 @@
+import { t } from "ttag";
+
+import { PublicLinksListing } from "metabase/admin/settings/components/widgets/PublicLinksListing";
+import * as Urls from "metabase/lib/urls";
+import {
+ useDeleteDocumentPublicLinkMutation,
+ useListPublicDocumentsQuery,
+} from "metabase-enterprise/api";
+import type { Document } from "metabase-types/api";
+
+export const PublicLinksDocumentListing = () => {
+ const query = useListPublicDocumentsQuery();
+ const [revoke] = useDeleteDocumentPublicLinkMutation();
+
+ return (
+ <PublicLinksListing<Pick<Document, "id" | "name" | "public_uuid">>
+ revoke={revoke}
+ getUrl={(document) => Urls.document(document)}
+ getPublicUrl={({ public_uuid }) => {
+ if (public_uuid) {
+ return Urls.publicDocument(public_uuid);
+ }
+ return null;
+ }}
+ noLinksMessage={t`No documents have been publicly shared yet.`}
+ {...query}
+ />
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/api/document.ts b/enterprise/frontend/src/metabase-enterprise/api/document.ts
index 3d66ed491eb..a4d457a8438 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/document.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/document.ts
@@ -54,6 +54,52 @@ export const documentApi = EnterpriseApi.injectEndpoints({
invalidatesTags: (_, error, { id }) =>
!error ? [listTag("document"), idTag("document", id)] : [],
}),
+ listPublicDocuments: builder.query<
+ Array<Pick<Document, "id" | "name" | "public_uuid">>,
+ void
+ >({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/document/public",
+ }),
+ providesTags: (result = []) => [
+ ...result.map((res) => idTag("public-document", res.id)),
+ listTag("public-document"),
+ ],
+ }),
+ createDocumentPublicLink: builder.mutation<
+ Pick<Document, "id"> & { uuid: Document["public_uuid"] },
+ Pick<Document, "id">
+ >({
+ query: ({ id }) => ({
+ method: "POST",
+ url: `/api/ee/document/${id}/public-link`,
+ }),
+ invalidatesTags: (_, error, { id }) =>
+ !error ? [listTag("public-document"), idTag("document", id)] : [],
+ transformResponse: ({ uuid }, _meta, { id }) => ({
+ id,
+ uuid,
+ }),
+ }),
+ deleteDocumentPublicLink: builder.mutation<
+ Pick<Document, "id">,
+ Pick<Document, "id">
+ >({
+ query: ({ id }) => ({
+ method: "DELETE",
+ url: `/api/ee/document/${id}/public-link`,
+ }),
+ transformResponse: (_baseQueryReturnValue, _meta, { id }) => ({ id }),
+ invalidatesTags: (_, error, { id }) =>
+ !error
+ ? [
+ listTag("public-document"),
+ idTag("public-document", id),
+ idTag("document", id),
+ ]
+ : [],
+ }),
}),
});
@@ -61,4 +107,7 @@ export const {
useGetDocumentQuery,
useCreateDocumentMutation,
useUpdateDocumentMutation,
+ useListPublicDocumentsQuery,
+ useCreateDocumentPublicLinkMutation,
+ useDeleteDocumentPublicLinkMutation,
} = documentApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 1e57e13f869..77b012e22c6 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -34,6 +34,7 @@ export const ENTERPRISE_TAG_TYPES = [
"metabot-prompt-suggestions",
"gsheets-status",
"document",
+ "public-document",
"comment",
"sandbox",
"transform-tag",
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx
index 346ab2b7044..0b3bc1314cc 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx
@@ -1,11 +1,15 @@
-import { useCallback } from "react";
+import { useCallback, useState } from "react";
import { Link } from "react-router";
import { t } from "ttag";
import DateTime, {
getFormattedTime,
} from "metabase/common/components/DateTime";
+import { useHasTokenFeature, useSetting } from "metabase/common/hooks";
+import CS from "metabase/css/core/index.css";
import { isWithinIframe } from "metabase/lib/dom";
+import { useSelector } from "metabase/lib/redux";
+import { getUserIsAdmin } from "metabase/selectors/user";
import {
ActionIcon,
Box,
@@ -19,6 +23,7 @@ import {
Transition,
type TransitionProps,
} from "metabase/ui";
+import { DocumentPublicLinkPopover } from "metabase-enterprise/embedding/components/PublicLinkPopover";
import type { Document } from "metabase-types/api";
import { trackDocumentPrint } from "../analytics";
@@ -61,6 +66,14 @@ export const DocumentHeader = ({
onArchive,
hasComments = false,
}: DocumentHeaderProps) => {
+ const isPublicSharingEnabled = useSetting("enable-public-sharing");
+ const hasDocumentsFeature = useHasTokenFeature("documents");
+ const isAdmin = useSelector(getUserIsAdmin);
+ const [isPublicLinkPopoverOpen, setIsPublicLinkPopoverOpen] = useState(false);
+
+ const hasPublicLink = !!document?.public_uuid;
+ const canUsePublicSharing = isPublicSharingEnabled && hasDocumentsFeature;
+
const handlePrint = useCallback(() => {
window.print();
trackDocumentPrint(document);
@@ -171,6 +184,43 @@ export const DocumentHeader = ({
</Menu.Item>
{!isNewDocument && (
<>
+ {isAdmin && (
+ <Menu.Item
+ leftSection={<Icon name="link" />}
+ onClick={() => setIsPublicLinkPopoverOpen(true)}
+ {...(!canUsePublicSharing && {
+ onClick: undefined,
+ component: "div",
+ disabled: true,
+ })}
+ >
+ {canUsePublicSharing ? (
+ hasPublicLink ? (
+ t`Public link`
+ ) : (
+ t`Create a public link`
+ )
+ ) : (
+ <>
+ {t`Public link`}
+ <Button
+ component={Link}
+ to="/admin/settings/public-sharing"
+ target="_blank"
+ variant="subtle"
+ h="auto"
+ lh="inherit"
+ ml="sm"
+ p={0}
+ bd={0}
+ className={CS.floatRight}
+ >
+ {t`Enable`}
+ </Button>
+ </>
+ )}
+ </Menu.Item>
+ )}
{canWrite && (
<Menu.Item
leftSection={<Icon name="move" />}
@@ -201,6 +251,13 @@ export const DocumentHeader = ({
</Menu.Dropdown>
</Menu>
)}
+ {document && isAdmin && (
+ <DocumentPublicLinkPopover
+ document={document}
+ isOpen={isPublicLinkPopoverOpen}
+ onClose={() => setIsPublicLinkPopoverOpen(false)}
+ />
+ )}
</Flex>
</Flex>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx
index e1f0e0aeea8..59e91a6fa55 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.unit.spec.tsx
@@ -1,7 +1,11 @@
import userEvent from "@testing-library/user-event";
-import { render, screen } from "__support__/ui";
-import { createMockDocument, createMockUser } from "metabase-types/api/mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ createMockDocument,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";
@@ -19,6 +23,8 @@ const setup = ({
canWrite = true,
showSaveButton = false,
isBookmarked = false,
+ isAdmin = false,
+ isPublicSharingEnabled = false,
onTitleChange = jest.fn(),
onSave = jest.fn(),
onMove = jest.fn(),
@@ -41,7 +47,18 @@ const setup = ({
onToggleComments,
};
- render(<DocumentHeader {...props} />);
+ renderWithProviders(<DocumentHeader {...props} />, {
+ storeInitialState: {
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ settings: {
+ values: {
+ "enable-public-sharing": isPublicSharingEnabled,
+ "token-features": createMockTokenFeatures({ documents: true }),
+ } as any,
+ loading: false,
+ },
+ },
+ });
return props;
};
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopover.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopover.tsx
new file mode 100644
index 00000000000..5851aada398
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopover.tsx
@@ -0,0 +1,98 @@
+import { useAsync } from "react-use";
+import { t } from "ttag";
+
+import { publicDocument as getPublicDocumentUrl } from "metabase/lib/urls/documents";
+import {
+ trackPublicEmbedCodeCopied,
+ trackPublicLinkCopied,
+ trackPublicLinkRemoved,
+} from "metabase/public/lib/analytics";
+import { Box, Popover, Title } from "metabase/ui";
+import {
+ useCreateDocumentPublicLinkMutation,
+ useDeleteDocumentPublicLinkMutation,
+} from "metabase-enterprise/api";
+import type { Document } from "metabase-types/api";
+
+import { DocumentPublicLinkPopoverContent } from "./DocumentPublicLinkPopoverContent";
+
+export const DocumentPublicLinkPopover = ({
+ document,
+ isOpen,
+ onClose,
+}: {
+ document: Document;
+ isOpen: boolean;
+ onClose: () => void;
+}) => {
+ const uuid = document.public_uuid;
+
+ const url = uuid ? getPublicDocumentUrl(uuid) : null;
+
+ const [createPublicDocumentLink] = useCreateDocumentPublicLinkMutation();
+ const [deletePublicDocumentLink] = useDeleteDocumentPublicLinkMutation();
+
+ const { loading } = useAsync(async () => {
+ if (isOpen && !url) {
+ return createPublicDocumentLink({
+ id: document.id,
+ });
+ }
+ return null;
+ }, [url, isOpen]);
+
+ const handleDeletePublicDocumentLink = () => {
+ trackPublicLinkRemoved({
+ artifact: "document",
+ source: "public-share",
+ });
+ deletePublicDocumentLink({
+ id: document.id,
+ });
+ onClose();
+ };
+
+ const onCopyLink = () => {
+ trackPublicLinkCopied({
+ artifact: "document",
+ });
+ };
+
+ const onCopyEmbed = () => {
+ trackPublicEmbedCodeCopied({
+ artifact: "document",
+ source: "public-share",
+ });
+ };
+
+ return (
+ <Popover
+ opened={isOpen}
+ onChange={isOpen ? onClose : undefined}
+ position="bottom-end"
+ >
+ <Popover.Target>
+ <Box onClick={isOpen ? onClose : undefined}>
+ <span />
+ </Box>
+ </Popover.Target>
+ <Popover.Dropdown>
+ <Box
+ p="lg"
+ w="32rem"
+ data-testid="public-link-popover-content"
+ mih="10rem"
+ >
+ <Title c="text-medium" order={4} mb="md">{t`Public sharing`}</Title>
+ <DocumentPublicLinkPopoverContent
+ url={url}
+ loading={loading}
+ onRemoveLink={handleDeletePublicDocumentLink}
+ onCopyLink={onCopyLink}
+ onCopyEmbed={onCopyEmbed}
+ />
+ </Box>
+ </Popover.Dropdown>
+ </Popover>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.module.css b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.module.css
new file mode 100644
index 00000000000..8f974210447
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.module.css
@@ -0,0 +1,26 @@
+.removeLinkAnchor {
+ cursor: pointer;
+}
+
+.removeLinkAnchor:hover {
+ text-decoration: underline;
+}
+
+.embedCodeContainer {
+ position: relative;
+ background-color: var(--mb-color-bg-light);
+ border-radius: 4px;
+ padding: 0.5rem;
+}
+
+.copyButtonContainer {
+ position: absolute;
+ top: 0.5rem;
+ right: 0.5rem;
+}
+
+.embedCode {
+ white-space: pre;
+ font-size: 12px;
+ background-color: transparent;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.tsx b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.tsx
new file mode 100644
index 00000000000..85dc778b8a0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/DocumentPublicLinkPopoverContent.tsx
@@ -0,0 +1,141 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import { CopyButton } from "metabase/common/components/CopyButton";
+import { useSelector } from "metabase/lib/redux";
+import { getPublicEmbedHTMLWithResizer } from "metabase/public/lib/code-templates";
+import { getUserIsAdmin } from "metabase/selectors/user";
+import {
+ Anchor,
+ Box,
+ Code,
+ Group,
+ ScrollArea,
+ Stack,
+ Tabs,
+ Text,
+ TextInput,
+ Tooltip,
+} from "metabase/ui";
+
+import S from "./DocumentPublicLinkPopoverContent.module.css";
+
+interface DocumentPublicLinkPopoverContentProps {
+ url: string | null;
+ loading?: boolean;
+ onRemoveLink?: () => void;
+ onCopyLink?: () => void;
+ onCopyEmbed?: () => void;
+}
+
+export const DocumentPublicLinkPopoverContent = ({
+ url,
+ loading = false,
+ onRemoveLink,
+ onCopyLink,
+ onCopyEmbed,
+}: DocumentPublicLinkPopoverContentProps) => {
+ const isAdmin = useSelector(getUserIsAdmin);
+ const [activeTab, setActiveTab] = useState<string | null>("link");
+
+ const iframeCode = url
+ ? getPublicEmbedHTMLWithResizer(JSON.stringify(url))
+ : "";
+
+ return (
+ <Stack gap="md">
+ <Box>
+ <Text size="sm" c="text-medium" mb="xs">
+ {t`Anyone can view this if you give them the link or embed it.`}
+ </Text>
+ </Box>
+
+ <Tabs value={activeTab} onChange={setActiveTab}>
+ <Tabs.List>
+ <Tabs.Tab value="link">{t`Public link`}</Tabs.Tab>
+ <Tabs.Tab value="embed">{t`Embed code`}</Tabs.Tab>
+ </Tabs.List>
+
+ <Tabs.Panel value="link" pt="md">
+ <Stack gap="sm">
+ <TextInput
+ readOnly
+ data-testid="public-link-input"
+ placeholder={loading ? t`Loading…` : undefined}
+ value={url ?? undefined}
+ rightSection={
+ url && (
+ <CopyButton
+ value={url}
+ onCopy={onCopyLink}
+ aria-label={t`Copy link`}
+ />
+ )
+ }
+ />
+ </Stack>
+ </Tabs.Panel>
+
+ <Tabs.Panel value="embed" pt="md">
+ <Stack gap="sm">
+ <Box>
+ <Text size="sm" c="text-medium" mb="xs">
+ {t`Paste this code in your website or blog to embed the document. The iframe will automatically adjust to the document's height.`}
+ </Text>
+ </Box>
+ <Box className={S.embedCodeContainer}>
+ <ScrollArea
+ mah={200}
+ type="auto"
+ offsetScrollbars
+ styles={{
+ viewport: {
+ "& > div": {
+ display: "block !important",
+ },
+ },
+ }}
+ >
+ <Code block className={S.embedCode}>
+ {iframeCode}
+ </Code>
+ </ScrollArea>
+ <Box className={S.copyButtonContainer}>
+ {iframeCode && (
+ <CopyButton
+ value={iframeCode}
+ onCopy={onCopyEmbed}
+ aria-label={t`Copy embed code`}
+ />
+ )}
+ </Box>
+ </Box>
+ </Stack>
+ </Tabs.Panel>
+ </Tabs>
+
+ {isAdmin && onRemoveLink && (
+ <Group justify="flex-start" mt="sm">
+ <Tooltip
+ label={
+ <Text fw={700} c="inherit">
+ {t`Affects both public link and embed code for this document`}
+ </Text>
+ }
+ >
+ <Anchor
+ component="button"
+ fz="sm"
+ c="error"
+ fw={700}
+ onClick={onRemoveLink}
+ className={S.removeLinkAnchor}
+ >
+ {t`Remove public link`}
+ </Anchor>
+ </Tooltip>
+ </Group>
+ )}
+ </Stack>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/index.ts
new file mode 100644
index 00000000000..419298278d6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/embedding/components/PublicLinkPopover/index.ts
@@ -0,0 +1 @@
+export { DocumentPublicLinkPopover } from "./DocumentPublicLinkPopover";
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.js
index 3b1d47014c9..7853b40f21f 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js
@@ -45,3 +45,4 @@ import "./documents";
import "./semantic_search";
import "./transforms";
import "./transforms-python";
+import "./public-sharing";
diff --git a/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts b/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts
new file mode 100644
index 00000000000..4a1d6081f88
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts
@@ -0,0 +1,7 @@
+import { PLUGIN_PUBLIC_SHARING } from "metabase/plugins";
+
+import { PublicLinksDocumentListing } from "../admin/settings/components/widgets/PublicLinksListing/PublicDocumentResources";
+import { PublicDocument } from "../public/containers/PublicDocument";
+
+PLUGIN_PUBLIC_SHARING.PublicDocumentRoute = PublicDocument;
+PLUGIN_PUBLIC_SHARING.PublicLinksDocumentListing = PublicLinksDocumentListing;
diff --git a/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.module.css b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.module.css
new file mode 100644
index 00000000000..bacab086b7b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.module.css
@@ -0,0 +1,172 @@
+.editorContent :global(.ProseMirror) {
+ padding: 1.5rem 0 2rem 0;
+ outline: none;
+ color: var(--mb-color-text-dark);
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
+/* Apply typography styles only to elements NOT inside .editor-style-boundary */
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(h1), :global(h2), :global(h3)):not(
+ :global(.editor-style-boundary) *
+ ) {
+ font-weight: 700;
+ color: var(--mb-color-text-dark);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h1):not(:global(.editor-style-boundary) *) {
+ font-size: 1.75rem;
+ margin: 1.5rem 0 1rem;
+ line-height: 1.3;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h2):not(:global(.editor-style-boundary) *) {
+ font-size: 1.375rem;
+ margin: 1.25rem 0 0.75rem;
+ line-height: 1.3;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(h3):not(:global(.editor-style-boundary) *) {
+ font-size: 1.125rem;
+ margin: 1rem 0 0.5rem;
+ line-height: 1.4;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(p):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 1rem 0;
+ line-height: 1.5;
+ font-size: 1rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(ul), :global(ol)):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 1rem 0;
+ padding-left: 1.5rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: disc;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ol):not(:global(.editor-style-boundary) *) {
+ list-style-type: decimal;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(li):not(:global(.editor-style-boundary) *) {
+ margin: 0 0 0.25rem 0;
+ line-height: 1.5;
+ display: list-item;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: circle;
+ margin-top: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(ul ul ul):not(:global(.editor-style-boundary) *) {
+ list-style-type: square;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :where(:global(li > ul), :global(li > ol)):not(
+ :global(.editor-style-boundary) *
+ ) {
+ margin-top: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(li p):not(:global(.editor-style-boundary) *) {
+ line-height: 1.5;
+ margin-bottom: 0.25rem;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(code):not(:global(.editor-style-boundary) *) {
+ background-color: var(--mb-color-bg-light);
+ padding: 0.125rem 0.375rem;
+ border-radius: var(--mantine-radius-xs);
+ font-family: var(--mb-default-monospace-font-family, monospace);
+ font-size: 0.875rem;
+ color: var(--mb-color-text-dark);
+ border: 1px solid var(--mb-color-border);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(pre):not(:global(.editor-style-boundary) *) {
+ background-color: var(--mb-color-bg-light);
+ color: var(--mb-color-text-dark);
+ padding: 1rem;
+ border-radius: var(--mantine-radius-sm);
+ overflow-x: auto;
+ margin: 0 0 1rem 0;
+ font-size: 0.875rem;
+ border: 1px solid var(--mb-color-border);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(pre code):not(:global(.editor-style-boundary) *) {
+ background: none;
+ padding: 0;
+ color: inherit;
+ font-size: inherit;
+ border: none;
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(blockquote):not(:global(.editor-style-boundary) *) {
+ border-left: 3px solid var(--mb-color-border);
+ margin: 0 0 1rem 0;
+ color: var(--mb-color-text-medium);
+ font-style: italic;
+ background-color: var(--mb-color-bg-light);
+ padding: 1rem;
+ padding-left: 1.25rem;
+ border-radius: var(--mantine-radius-xs);
+}
+
+.editorContent
+ :global(.ProseMirror)
+ :global(hr):not(:global(.editor-style-boundary) *) {
+ border: none;
+ border-top: 1px solid var(--mb-color-border);
+ margin: 1.5rem 0;
+}
+
+.img {
+ max-width: 80%;
+ height: auto;
+ display: block;
+ margin: 1rem auto;
+
+ &:global(.ProseMirror-selectednode) {
+ box-shadow: 0 0 0 1px var(--mb-color-brand);
+ border-radius: var(--mantine-radius-xs);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx
new file mode 100644
index 00000000000..bcdc74ec873
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/PublicDocument.tsx
@@ -0,0 +1,140 @@
+import Image from "@tiptap/extension-image";
+import Link from "@tiptap/extension-link";
+import type { JSONContent } from "@tiptap/react";
+import { EditorContent, useEditor } from "@tiptap/react";
+import { useEffect, useMemo } from "react";
+import { useAsync, useMount } from "react-use";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import CS from "metabase/css/core/index.css";
+import { initializeIframeResizer } from "metabase/lib/dom";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import { setErrorPage } from "metabase/redux/app";
+import { getSetting } from "metabase/selectors/settings";
+import { PublicApi } from "metabase/services";
+import { Box } from "metabase/ui";
+import { PublicDocumentProvider } from "metabase-enterprise/public/contexts/PublicDocumentContext";
+import {
+ CardEmbed,
+ DROP_ZONE_COLOR,
+} from "metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode";
+import { CustomStarterKit } from "metabase-enterprise/rich_text_editing/tiptap/extensions/CustomStarterKit/CustomStarterKit";
+import { FlexContainer } from "metabase-enterprise/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer";
+import { ResizeNode } from "metabase-enterprise/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode";
+import { SmartLink } from "metabase-enterprise/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";
+import type { Document } from "metabase-types/api";
+
+import S from "./PublicDocument.module.css";
+
+interface PublicDocumentProps {
+ params: {
+ uuid: string;
+ };
+}
+
+export const PublicDocument = ({ params }: PublicDocumentProps) => {
+ const { uuid } = params;
+ const dispatch = useDispatch();
+ const siteUrl = useSelector((state) => getSetting(state, "site-url"));
+
+ const {
+ value: document,
+ loading,
+ error,
+ } = useAsync(async () => {
+ const doc = await PublicApi.document({ uuid });
+ return doc as Document;
+ }, [uuid]);
+
+ useEffect(() => {
+ if (error) {
+ dispatch(setErrorPage(error));
+ }
+ }, [dispatch, error]);
+
+ const extensions = useMemo(
+ () => [
+ CustomStarterKit.configure({
+ dropcursor: {
+ color: DROP_ZONE_COLOR,
+ width: 2,
+ },
+ }),
+ Image.configure({
+ inline: false,
+ }),
+ SmartLink.configure({
+ HTMLAttributes: {
+ class: "smart-link",
+ },
+ siteUrl,
+ }),
+ Link.configure({
+ HTMLAttributes: {
+ class: CS.link,
+ },
+ }),
+ CardEmbed,
+ FlexContainer,
+ ResizeNode,
+ ],
+ [siteUrl],
+ );
+
+ const editor = useEditor(
+ {
+ extensions,
+ content: (document?.document as JSONContent) || "",
+ editable: false,
+ immediatelyRender: false,
+ },
+ [document?.document],
+ );
+
+ useEffect(() => {
+ if (editor && document?.document) {
+ editor.commands.setContent(document.document as JSONContent);
+ }
+ }, [editor, document?.document]);
+
+ useEffect(() => {
+ if (document) {
+ // Set the page title for the browser tab
+ window.document.title = document.name;
+ }
+ }, [document]);
+
+ useMount(() => {
+ // Initialize iframe resizer for dynamic height adjustment when embedded
+ initializeIframeResizer();
+ });
+
+ return (
+ <LoadingAndErrorWrapper
+ loading={loading}
+ noBackground
+ style={{
+ display: "flex",
+ flex: 1,
+ flexDirection: "column",
+ }}
+ >
+ {document && editor && (
+ <PublicDocumentProvider
+ value={{
+ publicDocumentUuid: uuid,
+ publicDocument: document,
+ publicDocumentCards: document.cards,
+ }}
+ >
+ <Box maw={900} mx="auto" p="xl" w="100%">
+ <h1 style={{ marginBottom: "1rem" }}>{document.name}</h1>
+ <div className={S.editorContent}>
+ <EditorContent data-testid="document-content" editor={editor} />
+ </div>
+ </Box>
+ </PublicDocumentProvider>
+ )}
+ </LoadingAndErrorWrapper>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/index.ts b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/index.ts
new file mode 100644
index 00000000000..69257f57670
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public/containers/PublicDocument/index.ts
@@ -0,0 +1 @@
+export { PublicDocument } from "./PublicDocument";
diff --git a/enterprise/frontend/src/metabase-enterprise/public/contexts/PublicDocumentContext.tsx b/enterprise/frontend/src/metabase-enterprise/public/contexts/PublicDocumentContext.tsx
new file mode 100644
index 00000000000..2e651f703dc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public/contexts/PublicDocumentContext.tsx
@@ -0,0 +1,17 @@
+import { createContext, useContext } from "react";
+
+import type { Card, Document } from "metabase-types/api";
+
+interface PublicDocumentContextValue {
+ publicDocumentUuid?: string;
+ publicDocument?: Document;
+ publicDocumentCards?: Record<number, Card>;
+}
+
+const PublicDocumentContext = createContext<PublicDocumentContextValue>({});
+
+export const PublicDocumentProvider = PublicDocumentContext.Provider;
+
+export function usePublicDocumentContext() {
+ return useContext(PublicDocumentContext);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/public/hooks/use-public-document-card-data.ts b/enterprise/frontend/src/metabase-enterprise/public/hooks/use-public-document-card-data.ts
new file mode 100644
index 00000000000..a2ab46498b0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/public/hooks/use-public-document-card-data.ts
@@ -0,0 +1,87 @@
+import { useMemo } from "react";
+import { useAsync } from "react-use";
+
+import { useSelector } from "metabase/lib/redux";
+import { getMetadata } from "metabase/selectors/metadata";
+import { PublicApi } from "metabase/services";
+import { usePublicDocumentContext } from "metabase-enterprise/public/contexts/PublicDocumentContext";
+import Question from "metabase-lib/v1/Question";
+import type { Card, Dataset, RawSeries } from "metabase-types/api";
+
+interface UsePublicDocumentCardDataProps {
+ cardId: number;
+ documentUuid: string;
+}
+
+interface UsePublicDocumentCardDataResult {
+ card?: Card;
+ dataset?: Dataset;
+ isLoading: boolean;
+ series: RawSeries | null;
+ question?: Question;
+ error?: "not found" | "unknown" | null;
+}
+
+function buildSeries(card: Card, dataset: Dataset): RawSeries {
+ return [
+ {
+ card,
+ started_at: dataset.started_at,
+ data: dataset.data,
+ },
+ ];
+}
+
+export function usePublicDocumentCardData({
+ cardId,
+ documentUuid,
+}: UsePublicDocumentCardDataProps): UsePublicDocumentCardDataResult {
+ const { publicDocumentCards } = usePublicDocumentContext();
+ const metadata = useSelector(getMetadata);
+
+ // Get the card metadata from the document response — we hydrate all cards upfront so the frontend
+ // doesn't have to make authenticated requests to fetch them individually
+ const card = publicDocumentCards?.[cardId];
+
+ const {
+ value: dataset,
+ loading: isLoadingDataset,
+ error: datasetError,
+ } = useAsync(async () => {
+ if (!cardId || !documentUuid || !card) {
+ return undefined;
+ }
+
+ try {
+ const result = await PublicApi.documentCardQuery({
+ uuid: documentUuid,
+ cardId,
+ });
+ return result as Dataset;
+ } catch (error) {
+ console.error("Failed to load public document card data:", error);
+ throw error;
+ }
+ }, [cardId, documentUuid, card]);
+
+ const isLoading = !card || isLoadingDataset;
+
+ const hasDataForVisualization = card && dataset?.data;
+ const series = hasDataForVisualization ? buildSeries(card, dataset) : null;
+
+ const question = useMemo(
+ () => (card ? new Question(card, metadata) : undefined),
+ [card, metadata],
+ );
+
+ const error = datasetError ? "not found" : !card ? "not found" : null;
+
+ return {
+ card,
+ dataset,
+ isLoading,
+ series,
+ question,
+ error,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
index c89e85d5dc0..b206f67e284 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
@@ -14,8 +14,11 @@ import { Ellipsified } from "metabase/common/components/Ellipsified";
import { ForwardRefLink } from "metabase/common/components/Link";
import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal";
import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";
+import { canDownloadResults } from "metabase/dashboard/components/DashCard/DashCardMenu/utils";
import { isWithinIframe } from "metabase/lib/dom";
import { useDispatch, useSelector } from "metabase/lib/redux";
+import { QuestionDownloadWidget } from "metabase/query_builder/components/QuestionDownloadWidget";
+import { useDownloadData } from "metabase/query_builder/components/QuestionDownloadWidget/use-download-data";
import { getMetadata } from "metabase/selectors/metadata";
import { Box, Flex, Icon, Loader, Menu, Text, TextInput } from "metabase/ui";
import Visualization from "metabase/visualizations/components/Visualization";
@@ -40,6 +43,8 @@ import {
getHoveredChildTargetId,
} from "metabase-enterprise/documents/selectors";
import { getListCommentsQuery } from "metabase-enterprise/documents/utils/api";
+import { usePublicDocumentContext } from "metabase-enterprise/public/contexts/PublicDocumentContext";
+import { usePublicDocumentCardData } from "metabase-enterprise/public/hooks/use-public-document-card-data";
import Question from "metabase-lib/v1/Question";
import { getUrl } from "metabase-lib/v1/urls";
import type { Card, CardDisplayType, Dataset } from "metabase-types/api";
@@ -55,6 +60,140 @@ import CS from "../extensions.module.css";
import styles from "./CardEmbedNode.module.css";
import { ModifyQuestionModal } from "./ModifyQuestionModal";
import { NativeQueryModal } from "./NativeQueryModal";
+import { PublicDocumentCardMenu } from "./PublicDocumentCardMenu";
+
+interface CardEmbedMenuContext {
+ canWrite: boolean;
+ dataset: Dataset | undefined;
+ question: Question | undefined;
+ isNativeQuestion: boolean | undefined;
+ commentsPath: string;
+ hasUnsavedChanges: boolean;
+ unresolvedCommentsCount: number;
+}
+
+interface CardEmbedMenuActions {
+ handleDownload: (opts: {
+ type: string;
+ enableFormatting: boolean;
+ enablePivot: boolean;
+ }) => void;
+ handleEditVisualizationSettings: () => void;
+ setIsModifyModalOpen: (open: boolean) => void;
+ handleReplaceQuestion: () => void;
+ handleRemoveNode: () => void;
+}
+
+interface CardEmbedMenuState {
+ menuView: string | null;
+ setMenuView: (view: string | null) => void;
+ isDownloadingData: boolean;
+}
+
+type CardEmbedMenuDropdownProps = CardEmbedMenuContext &
+ CardEmbedMenuActions &
+ CardEmbedMenuState;
+
+const CardEmbedMenuDropdown = ({
+ // Context
+ canWrite,
+ dataset,
+ question,
+ isNativeQuestion,
+ commentsPath,
+ hasUnsavedChanges,
+ unresolvedCommentsCount,
+ // Actions
+ handleDownload,
+ handleEditVisualizationSettings,
+ setIsModifyModalOpen,
+ handleReplaceQuestion,
+ handleRemoveNode,
+ // State
+ menuView,
+ setMenuView,
+ isDownloadingData,
+}: CardEmbedMenuDropdownProps) => {
+ if (menuView === "downloads" && question && dataset) {
+ return (
+ <QuestionDownloadWidget
+ question={question}
+ result={dataset}
+ onDownload={(opts) => {
+ setMenuView(null);
+ handleDownload(opts);
+ }}
+ />
+ );
+ }
+
+ return (
+ <>
+ {!isWithinIframe() && canWrite && (
+ <Menu.Item
+ leftSection={<Icon name="add_comment" size={14} />}
+ component={ForwardRefLink}
+ to={
+ unresolvedCommentsCount > 0
+ ? commentsPath
+ : `${commentsPath}?new=true`
+ }
+ onClick={(e) => {
+ if (!commentsPath || hasUnsavedChanges) {
+ e.preventDefault();
+ }
+ }}
+ disabled={!commentsPath || hasUnsavedChanges}
+ >
+ {t`Comment`}
+ </Menu.Item>
+ )}
+ <Menu.Item
+ onClick={handleEditVisualizationSettings}
+ leftSection={<Icon name="palette" size={14} />}
+ disabled={!canWrite}
+ >
+ {t`Edit Visualization`}
+ </Menu.Item>
+ <Menu.Item
+ onClick={() => setIsModifyModalOpen(true)}
+ leftSection={
+ <Icon name={isNativeQuestion ? "sql" : "notebook"} size={14} />
+ }
+ disabled={!canWrite}
+ >
+ {t`Edit Query`}
+ </Menu.Item>
+ <Menu.Item
+ onClick={handleReplaceQuestion}
+ leftSection={<Icon name="refresh" size={14} />}
+ disabled={!canWrite}
+ >
+ {t`Replace`}
+ </Menu.Item>
+ {canDownloadResults(dataset) && (
+ <Menu.Item
+ leftSection={<Icon name="download" aria-hidden />}
+ aria-label={isDownloadingData ? t`Downloading…` : t`Download results`}
+ disabled={isDownloadingData}
+ closeMenuOnClick={false}
+ onClick={() => {
+ setMenuView("downloads");
+ }}
+ >
+ {isDownloadingData ? t`Downloading…` : t`Download results`}
+ </Menu.Item>
+ )}
+ <Menu.Item
+ onClick={handleRemoveNode}
+ leftSection={<Icon name="trash" size={14} />}
+ disabled={!canWrite}
+ >
+ {t`Remove Chart`}
+ </Menu.Item>
+ </>
+ );
+};
export const DROP_ZONE_COLOR = "var(--mb-color-brand)";
const DRAG_LEAVE_TIMEOUT = 300;
@@ -188,6 +327,7 @@ export const CardEmbedComponent = memo(
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
+ const { publicDocumentUuid } = usePublicDocumentContext();
const { data: commentsData } = useListCommentsQuery(
getListCommentsQuery(document),
);
@@ -233,7 +373,17 @@ export const CardEmbedComponent = memo(
});
}
- const { card, dataset, isLoading, series, error } = useCardData({ id });
+ // Use public hook when viewing a public document, otherwise use regular hook
+ const isPublicDocument = Boolean(publicDocumentUuid);
+ const regularCardData = useCardData({ id });
+ const publicCardData = usePublicDocumentCardData({
+ cardId: id,
+ documentUuid: publicDocumentUuid || "",
+ });
+
+ const { card, dataset, isLoading, series, error } = isPublicDocument
+ ? publicCardData
+ : regularCardData;
const metadata = useSelector(getMetadata);
const datasetError = dataset && getDatasetError(dataset);
@@ -242,6 +392,7 @@ export const CardEmbedComponent = memo(
const titleInputRef = useRef<HTMLInputElement>(null);
const [isModifyModalOpen, setIsModifyModalOpen] = useState(false);
const [isReplaceModalOpen, setIsReplaceModalOpen] = useState(false);
+ const [menuView, setMenuView] = useState<string | null>(null);
const [dragState, setDragState] = useState<{
isDraggedOver: boolean;
side: "left" | "right" | null;
@@ -252,9 +403,18 @@ export const CardEmbedComponent = memo(
const isBeingDragged = editor.view.draggingNode === node;
const displayName = name || card?.name;
- const question = card != null ? new Question(card) : undefined;
+ const question = useMemo(
+ () => (card != null ? new Question(card, metadata) : undefined),
+ [card, metadata],
+ );
const isNativeQuestion = question?.isNative();
+ const [{ loading: isDownloadingData }, handleDownload] = useDownloadData({
+ question: question!,
+ result: dataset!,
+ documentId: document?.id,
+ });
+
useEffect(() => {
if (isEditingTitle && titleInputRef.current) {
titleInputRef.current.focus();
@@ -591,9 +751,11 @@ export const CardEmbedComponent = memo(
size="md"
color="text-dark"
fw={700}
- c="pointer"
+ c={isPublicDocument ? undefined : "pointer"}
truncate="end"
- onClick={handleTitleClick}
+ onClick={
+ isPublicDocument ? undefined : handleTitleClick
+ }
>
{displayName}
</Text>
@@ -629,83 +791,58 @@ export const CardEmbedComponent = memo(
/>
</Box>
)}
- {!isEditingTitle && (
- <Menu withinPortal position="bottom-end" data-hide-on-print>
- <Menu.Target>
- <Flex
- component="button"
- p="0.25rem"
- align="center"
- justify="center"
- className={styles.menuButton}
- onClick={(e: React.MouseEvent) => e.stopPropagation()}
- >
- <Icon
- name="ellipsis"
- size={16}
- color="var(--mb-color-text-medium)"
- />
- </Flex>
- </Menu.Target>
- <Menu.Dropdown>
- {!isWithinIframe() && (
- <Menu.Item
- leftSection={<Icon name="add_comment" size={14} />}
- component={ForwardRefLink}
- to={
- // If no existing unresolved comments comments, add query param to auto-open new comment form
- unresolvedCommentsCount > 0
- ? commentsPath
- : `${commentsPath}?new=true`
+ {!isEditingTitle &&
+ (isPublicDocument && dataset && !canWrite ? (
+ <PublicDocumentCardMenu card={card} dataset={dataset} />
+ ) : !isPublicDocument && (canWrite || dataset) ? (
+ <Menu
+ withinPortal
+ position="bottom-end"
+ data-hide-on-print
+ opened={menuView !== null ? true : undefined}
+ onClose={() => setMenuView(null)}
+ >
+ <Menu.Target>
+ <Flex
+ component="button"
+ p="0.25rem"
+ align="center"
+ justify="center"
+ className={styles.menuButton}
+ onClick={(e: React.MouseEvent) =>
+ e.stopPropagation()
}
- // actually stop the navigation from happening
- onClick={(e) => {
- if (!commentsPath || hasUnsavedChanges) {
- e.preventDefault();
- }
- }}
- // purely for presentation
- disabled={!commentsPath || hasUnsavedChanges}
>
- {t`Comment`}
- </Menu.Item>
- )}
- <Menu.Item
- onClick={handleEditVisualizationSettings}
- disabled={!canWrite}
- leftSection={<Icon name="palette" size={14} />}
- >
- {t`Edit Visualization`}
- </Menu.Item>
- <Menu.Item
- onClick={() => setIsModifyModalOpen(true)}
- disabled={!canWrite}
- leftSection={
<Icon
- name={isNativeQuestion ? "sql" : "notebook"}
- size={14}
+ name="ellipsis"
+ size={16}
+ color="var(--mb-color-text-medium)"
/>
- }
- >
- {t`Edit Query`}
- </Menu.Item>
- <Menu.Item
- onClick={handleReplaceQuestion}
- disabled={!canWrite}
- leftSection={<Icon name="refresh" size={14} />}
- >
- {t`Replace`}
- </Menu.Item>
- <Menu.Item
- onClick={handleRemoveNode}
- disabled={!canWrite}
- leftSection={<Icon name="trash" size={14} />}
- >
- {t`Remove Chart`}
- </Menu.Item>
- </Menu.Dropdown>
- </Menu>
- )}
+ </Flex>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <CardEmbedMenuDropdown
+ menuView={menuView}
+ setMenuView={setMenuView}
+ canWrite={canWrite}
+ dataset={dataset}
+ question={question}
+ isNativeQuestion={isNativeQuestion}
+ isDownloadingData={isDownloadingData}
+ handleDownload={handleDownload}
+ handleEditVisualizationSettings={
+ handleEditVisualizationSettings
+ }
+ setIsModifyModalOpen={setIsModifyModalOpen}
+ handleReplaceQuestion={handleReplaceQuestion}
+ handleRemoveNode={handleRemoveNode}
+ commentsPath={commentsPath}
+ hasUnsavedChanges={hasUnsavedChanges}
+ unresolvedCommentsCount={unresolvedCommentsCount}
+ />
+ </Menu.Dropdown>
+ </Menu>
+ ) : null)}
</Flex>
</Box>
)}
@@ -715,7 +852,9 @@ export const CardEmbedComponent = memo(
<Visualization
rawSeries={series}
metadata={metadata}
- onChangeCardAndRun={handleChangeCardAndRun}
+ onChangeCardAndRun={
+ isPublicDocument ? undefined : handleChangeCardAndRun
+ }
getExtraDataForClick={() => ({})}
isEditing={false}
isDashboard={false}
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/PublicDocumentCardMenu.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/PublicDocumentCardMenu.tsx
new file mode 100644
index 00000000000..29460c385a2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/CardEmbed/PublicDocumentCardMenu.tsx
@@ -0,0 +1,97 @@
+import { useDisclosure } from "@mantine/hooks";
+import cx from "classnames";
+import { useMemo, useState } from "react";
+import { t } from "ttag";
+
+import { useSelector } from "metabase/lib/redux";
+import { checkNotNull } from "metabase/lib/types";
+import { QuestionDownloadWidget } from "metabase/query_builder/components/QuestionDownloadWidget";
+import { useDownloadData } from "metabase/query_builder/components/QuestionDownloadWidget/use-download-data";
+import { getMetadata } from "metabase/selectors/metadata";
+import { ActionIcon, Icon, Menu } from "metabase/ui";
+import { SAVING_DOM_IMAGE_HIDDEN_CLASS } from "metabase/visualizations/lib/save-chart-image";
+import { usePublicDocumentContext } from "metabase-enterprise/public/contexts/PublicDocumentContext";
+import Question from "metabase-lib/v1/Question";
+import type { Card, Dataset } from "metabase-types/api";
+
+type PublicDocumentCardMenuProps = {
+ card: Card;
+ dataset: Dataset;
+};
+
+export const PublicDocumentCardMenu = ({
+ card,
+ dataset,
+}: PublicDocumentCardMenuProps) => {
+ const { publicDocumentUuid } = usePublicDocumentContext();
+ const [menuView, setMenuView] = useState<string | null>(null);
+ const [isOpen, { close, toggle }] = useDisclosure(false, {
+ onClose: () => {
+ setMenuView(null);
+ },
+ });
+
+ const metadata = useSelector(getMetadata);
+ const question = useMemo(
+ () => new Question(card, metadata),
+ [card, metadata],
+ );
+
+ const [{ loading: isDownloadingData }, handleDownload] = useDownloadData({
+ question: question,
+ result: dataset,
+ documentUuid: checkNotNull(publicDocumentUuid),
+ });
+
+ return (
+ <Menu
+ withinPortal
+ offset={4}
+ position="bottom-end"
+ opened={isOpen}
+ onClose={close}
+ >
+ <Menu.Target>
+ <ActionIcon
+ size="xs"
+ className={cx({
+ [SAVING_DOM_IMAGE_HIDDEN_CLASS]: true,
+ })}
+ onClick={toggle}
+ data-testid="public-document-card-menu"
+ aria-label="ellipsis"
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+
+ <Menu.Dropdown>
+ {menuView === "downloads" ? (
+ <QuestionDownloadWidget
+ question={question}
+ result={dataset}
+ onDownload={(opts) => {
+ close();
+ handleDownload(opts);
+ }}
+ />
+ ) : (
+ <Menu.Item
+ fw="bold"
+ leftSection={<Icon name="download" aria-hidden />}
+ aria-label={
+ isDownloadingData ? t`Downloading…` : t`Download results`
+ }
+ disabled={isDownloadingData}
+ closeMenuOnClick={false}
+ onClick={() => {
+ setMenuView("downloads");
+ }}
+ >
+ {isDownloadingData ? t`Downloading…` : t`Download results`}
+ </Menu.Item>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ );
+};
diff --git a/frontend/src/metabase-types/analytics/embed-flow.ts b/frontend/src/metabase-types/analytics/embed-flow.ts
index d0a23099f27..a546248a9d8 100644
--- a/frontend/src/metabase-types/analytics/embed-flow.ts
+++ b/frontend/src/metabase-types/analytics/embed-flow.ts
@@ -38,7 +38,7 @@ type ValidateEvent<
Record<Exclude<keyof T, keyof EmbedFlowEventSchema>, never>,
> = T;
-type EmbedFlowArtifact = "dashboard" | "question";
+type EmbedFlowArtifact = "dashboard" | "question" | "document";
export type StaticEmbedDiscardedEvent = ValidateEvent<{
event: "static_embed_discarded";
diff --git a/frontend/src/metabase-types/api/document.ts b/frontend/src/metabase-types/api/document.ts
index c09f25c14d9..03a8880cc18 100644
--- a/frontend/src/metabase-types/api/document.ts
+++ b/frontend/src/metabase-types/api/document.ts
@@ -23,6 +23,9 @@ export type Document = {
can_restore: boolean;
can_write: boolean;
creator_id: UserId;
+ public_uuid?: string | null;
+ made_public_by_id?: UserId | null;
+ cards?: Record<number, Card>; // Map of card ID -> card metadata, hydrated for public documents
};
export type GetDocumentRequest = { id: DocumentId };
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/PublicSharingSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/PublicSharingSettingsPage.tsx
index b9590ef8c83..4ca2f20af7e 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/PublicSharingSettingsPage.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/PublicSharingSettingsPage.tsx
@@ -4,7 +4,8 @@ import {
SettingsPageWrapper,
SettingsSection,
} from "metabase/admin/components/SettingsSection";
-import { useSetting } from "metabase/common/hooks";
+import { useHasTokenFeature, useSetting } from "metabase/common/hooks";
+import { PLUGIN_PUBLIC_SHARING } from "metabase/plugins";
import { AdminSettingInput } from "../widgets/AdminSettingInput";
import {
@@ -15,6 +16,7 @@ import {
export function PublicSharingSettingsPage() {
const publicSharingEnabled = useSetting("enable-public-sharing");
+ const hasDocumentsFeature = useHasTokenFeature("documents");
return (
<SettingsPageWrapper title={t`Public sharing`}>
<SettingsSection>
@@ -32,6 +34,12 @@ export function PublicSharingSettingsPage() {
<SettingsSection title={t`Shared questions`}>
<PublicLinksQuestionListing />
</SettingsSection>
+ {hasDocumentsFeature &&
+ PLUGIN_PUBLIC_SHARING.PublicLinksDocumentListing && (
+ <SettingsSection title={t`Shared documents`}>
+ <PLUGIN_PUBLIC_SHARING.PublicLinksDocumentListing />
+ </SettingsSection>
+ )}
<SettingsSection title={t`Shared action forms`}>
<PublicLinksActionListing />
</SettingsSection>
diff --git a/frontend/src/metabase/lib/urls/documents.ts b/frontend/src/metabase/lib/urls/documents.ts
index c4179455cc5..0a7bdbfba6d 100644
--- a/frontend/src/metabase/lib/urls/documents.ts
+++ b/frontend/src/metabase/lib/urls/documents.ts
@@ -1,3 +1,4 @@
+import MetabaseSettings from "metabase/lib/settings";
import type { Document } from "metabase-types/api";
export function newDocument() {
@@ -7,3 +8,8 @@ export function newDocument() {
export function document(document: Pick<Document, "id">) {
return `/document/${document.id}`;
}
+
+export function publicDocument(uuid: string) {
+ const siteUrl = MetabaseSettings.get("site-url");
+ return `${siteUrl}/public/document/${uuid}`;
+}
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 2039513ca0b..5dc0d5e3daa 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -861,6 +861,11 @@ export const PLUGIN_DOCUMENTS = {
DocumentCopyForm: (_props: any) => null as React.ReactElement | null,
};
+export const PLUGIN_PUBLIC_SHARING = {
+ PublicDocumentRoute: (_props: any) => null as React.ReactElement | null,
+ PublicLinksDocumentListing: () => null as React.ReactElement | null,
+};
+
export const PLUGIN_ENTITIES = {
entities: {} as Record<string, any>,
};
diff --git a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/LookAndFeelSettings.tsx b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/LookAndFeelSettings.tsx
index 88eba6c3a1d..8cd9711d2f3 100644
--- a/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/LookAndFeelSettings.tsx
+++ b/frontend/src/metabase/public/components/EmbedModal/StaticEmbedSetupPane/LookAndFeelSettings.tsx
@@ -219,6 +219,7 @@ function getBorderLabel(resourceType: EmbedResourceType) {
.returnType<string>()
.with("dashboard", () => t`Dashboard border`)
.with("question", () => t`Question border`)
+ .with("document", () => t`Document border`)
.exhaustive();
}
diff --git a/frontend/src/metabase/public/lib/code-templates.ts b/frontend/src/metabase/public/lib/code-templates.ts
index 79a841c5c15..f1a6dde79ca 100644
--- a/frontend/src/metabase/public/lib/code-templates.ts
+++ b/frontend/src/metabase/public/lib/code-templates.ts
@@ -243,3 +243,21 @@ export const getPugSource = ({ iframeUrl }: { iframeUrl: string }) =>
height="600"
allowtransparency
)`;
+
+export const getPublicEmbedHTMLWithResizer = (iframeUrl: string): string => {
+ // Extract the site URL (origin) from the iframe URL
+ // iframeUrl is typically a JSON string like "\"https://metabase.example.com/public/document/uuid\""
+ const urlMatch = iframeUrl.match(/https?:\/\/[^/]+/);
+ const siteUrl = urlMatch ? urlMatch[0] : "";
+
+ return `<iframe
+ src=${iframeUrl}
+ frameborder="0"
+ width="800"
+ allowtransparency
+></iframe>
+<script src="${siteUrl}/app/iframeResizer.js"></script>
+<script>
+ iFrameResize({}, 'iframe');
+</script>`;
+};
diff --git a/frontend/src/metabase/public/lib/types.ts b/frontend/src/metabase/public/lib/types.ts
index 13205145629..49267b202d8 100644
--- a/frontend/src/metabase/public/lib/types.ts
+++ b/frontend/src/metabase/public/lib/types.ts
@@ -13,7 +13,7 @@ export type EmbedResource = (Card | Dashboard) & {
embedding_params?: EmbeddingParameters | null;
};
-export type EmbedResourceType = "dashboard" | "question";
+export type EmbedResourceType = "dashboard" | "question" | "document";
export type EmbedResourceParameter = {
id: string;
diff --git a/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/use-download-data.ts b/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/use-download-data.ts
index c2a5ff4042f..03c552a8e36 100644
--- a/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/use-download-data.ts
+++ b/frontend/src/metabase/query_builder/components/QuestionDownloadWidget/use-download-data.ts
@@ -15,6 +15,8 @@ export type UseDownloadDataParams = Pick<
| "dashcardId"
| "uuid"
| "token"
+ | "documentUuid"
+ | "documentId"
| "params"
| "visualizationSettings"
>;
@@ -31,6 +33,8 @@ export const useDownloadData = ({
dashcardId,
uuid,
token,
+ documentUuid,
+ documentId,
params,
visualizationSettings,
}: UseDownloadDataParams): AsyncFnReturn<
@@ -55,6 +59,8 @@ export const useDownloadData = ({
dashcardId,
uuid,
token,
+ documentUuid,
+ documentId,
params,
visualizationSettings,
}),
@@ -63,6 +69,8 @@ export const useDownloadData = ({
[
dashboardId,
dashcardId,
+ documentUuid,
+ documentId,
params,
question,
result,
diff --git a/frontend/src/metabase/redux/downloads-analytics.ts b/frontend/src/metabase/redux/downloads-analytics.ts
index 4d080e581d1..5be9ffb6e13 100644
--- a/frontend/src/metabase/redux/downloads-analytics.ts
+++ b/frontend/src/metabase/redux/downloads-analytics.ts
@@ -13,9 +13,14 @@ export const trackDownloadResults = ({
accessedVia: ResourceAccessedVia;
exportType: string;
}) => {
+ // Map document-card to dashcard for analytics tracking since the schema
+ // doesn't have a separate document-card type
+ const analyticsResourceType =
+ resourceType === "document-card" ? "dashcard" : resourceType;
+
trackSchemaEvent(SCHEMA, {
event: "download_results_clicked",
- resource_type: resourceType,
+ resource_type: analyticsResourceType,
accessed_via: accessedVia,
export_type: exportType as any,
});
diff --git a/frontend/src/metabase/redux/downloads.ts b/frontend/src/metabase/redux/downloads.ts
index 3c9308abff2..5bb243380f9 100644
--- a/frontend/src/metabase/redux/downloads.ts
+++ b/frontend/src/metabase/redux/downloads.ts
@@ -32,6 +32,8 @@ export interface DownloadQueryResultsOpts {
dashcardId?: DashCardId;
uuid?: string;
token?: string | null;
+ documentUuid?: string;
+ documentId?: number;
params?: Record<string, unknown>;
visualizationSettings?: VisualizationSettings;
}
@@ -43,7 +45,11 @@ interface DownloadQueryResultsParams {
params?: URLSearchParams | string;
}
-export type ResourceType = "question" | "dashcard" | "ad-hoc-question";
+export type ResourceType =
+ | "question"
+ | "dashcard"
+ | "document-card"
+ | "ad-hoc-question";
export type ResourceAccessedVia =
| "internal"
| "public-link"
@@ -56,56 +62,78 @@ export type DownloadedResourceInfo = {
accessedVia: ResourceAccessedVia;
};
-const getDownloadedResourceType = ({
- dashboardId,
- dashcardId,
- uuid,
- token,
- question,
-}: Partial<DownloadQueryResultsOpts>): DownloadedResourceInfo => {
- const cardId = question?.id();
-
- const isInIframe = isWithinIframe();
-
- const defaultAccessedVia = isEmbeddingSdk()
- ? "sdk-embed"
- : isInIframe
- ? "interactive-iframe-embed"
- : "internal";
-
- if (dashcardId != null && token != null) {
- return { resourceType: "dashcard", accessedVia: "static-embed" };
+/**
+ * Determine how the resource is being accessed (public link, embed, etc.)
+ */
+const getAccessedVia = (
+ hasUuid: boolean,
+ hasToken: boolean,
+): ResourceAccessedVia => {
+ if (hasToken) {
+ return "static-embed";
}
-
- if (dashboardId != null && uuid != null) {
- return { resourceType: "dashcard", accessedVia: "public-link" };
+ if (hasUuid) {
+ return "public-link";
}
-
- if (dashboardId != null && dashcardId != null) {
- return {
- resourceType: "dashcard",
- accessedVia: defaultAccessedVia,
- };
+ if (isEmbeddingSdk()) {
+ return "sdk-embed";
}
-
- if (uuid != null) {
- return { resourceType: "question", accessedVia: "public-link" };
+ if (isWithinIframe()) {
+ return "interactive-iframe-embed";
}
+ return "internal";
+};
- if (token != null) {
- return { resourceType: "question", accessedVia: "static-embed" };
+/**
+ * Determine the type of resource being downloaded (dashcard, question, etc.)
+ */
+const getResourceType = ({
+ dashboardId,
+ dashcardId,
+ documentId,
+ documentUuid,
+ cardId,
+}: {
+ dashboardId?: DashboardId;
+ dashcardId?: DashCardId;
+ documentId?: number;
+ documentUuid?: string;
+ cardId?: number | null;
+}): ResourceType => {
+ if (dashcardId != null && dashboardId != null) {
+ return "dashcard";
+ }
+ if (documentId != null || documentUuid != null) {
+ return "document-card";
}
-
if (cardId != null) {
- return {
- resourceType: "question",
- accessedVia: defaultAccessedVia,
- };
+ return "question";
}
+ return "ad-hoc-question";
+};
+
+const getDownloadedResourceType = ({
+ dashboardId,
+ dashcardId,
+ uuid,
+ token,
+ documentUuid,
+ documentId,
+ question,
+}: Partial<DownloadQueryResultsOpts>): DownloadedResourceInfo => {
+ const cardId = question?.id();
+ const hasUuid = uuid != null || documentUuid != null;
+ const hasToken = token != null;
return {
- resourceType: "ad-hoc-question",
- accessedVia: defaultAccessedVia,
+ resourceType: getResourceType({
+ dashboardId,
+ dashcardId,
+ documentId,
+ documentUuid,
+ cardId,
+ }),
+ accessedVia: getAccessedVia(hasUuid, hasToken),
};
};
@@ -162,6 +190,170 @@ export const downloadDataset = createAsyncThunk(
},
);
+type ExportParams = {
+ format_rows: boolean;
+ pivot_results: boolean;
+};
+
+const getPublicDashcardParams = (
+ cardId: number,
+ dashboardId: DashboardId,
+ dashcardId: DashCardId,
+ type: string,
+ result: Dataset,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/public/dashboard/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/${type}`,
+ body: {
+ parameters: result?.json_query?.parameters ?? [],
+ ...exportParams,
+ },
+});
+
+const getPublicDocumentCardParams = (
+ cardId: number,
+ documentUuid: string,
+ type: string,
+ result: Dataset,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/ee/public/document/${documentUuid}/card/${cardId}/${type}`,
+ body: {
+ parameters: result?.json_query?.parameters ?? [],
+ ...exportParams,
+ },
+});
+
+const getPublicQuestionParams = (
+ uuid: string,
+ type: string,
+ result: Dataset,
+): DownloadQueryResultsParams => {
+ const parameters = (result?.json_query?.parameters ?? []).map((param) => ({
+ id: param.id,
+ value: param.value,
+ }));
+
+ return {
+ method: "GET",
+ url: Urls.publicQuestion({ uuid, type, includeSiteUrl: false }),
+ params: new URLSearchParams({
+ parameters: JSON.stringify(parameters),
+ }),
+ };
+};
+
+const getEmbedDashcardParams = (
+ token: string,
+ cardId: number,
+ dashcardId: DashCardId,
+ type: string,
+ params: Record<string, unknown>,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "GET",
+ url: `/api/embed/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}/${type}`,
+ params: new URLSearchParams({
+ parameters: JSON.stringify(params),
+ ..._.mapObject(exportParams, (value) => String(value)),
+ }),
+});
+
+const getEmbedQuestionParams = (
+ token: string,
+ type: string,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => {
+ const params = new URLSearchParams(window.location.search);
+
+ const convertSearchParamsToObject = (params: URLSearchParams) => {
+ const object: Record<string, string | string[]> = {};
+ for (const [key, value] of params.entries()) {
+ if (object[key]) {
+ object[key] = ([] as string[]).concat(
+ object[key] as string | string[],
+ value,
+ );
+ } else {
+ object[key] = value;
+ }
+ }
+
+ return object;
+ };
+
+ return {
+ method: "GET",
+ url: Urls.embedCard(token, type),
+ params: new URLSearchParams({
+ parameters: JSON.stringify(convertSearchParamsToObject(params)),
+ ..._.mapObject(exportParams, (value) => String(value)),
+ }),
+ };
+};
+
+const getInternalDashcardParams = (
+ cardId: number,
+ dashboardId: DashboardId,
+ dashcardId: DashCardId,
+ type: string,
+ result: Dataset,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/dashboard/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/query/${type}`,
+ body: {
+ parameters: result?.json_query?.parameters ?? [],
+ ...exportParams,
+ },
+});
+
+const getInternalDocumentCardParams = (
+ cardId: number,
+ documentId: number,
+ type: string,
+ result: Dataset,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/ee/document/${documentId}/card/${cardId}/query/${type}`,
+ body: {
+ parameters: result?.json_query?.parameters ?? [],
+ ...exportParams,
+ },
+});
+
+const getInternalQuestionParams = (
+ cardId: number,
+ type: string,
+ result: Dataset,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/card/${cardId}/query/${type}`,
+ body: {
+ parameters: result?.json_query?.parameters ?? [],
+ ...exportParams,
+ },
+});
+
+const getAdHocQuestionParams = (
+ type: string,
+ result: Dataset,
+ visualizationSettings: VisualizationSettings | undefined,
+ exportParams: ExportParams,
+): DownloadQueryResultsParams => ({
+ method: "POST",
+ url: `/api/dataset/${type}`,
+ body: {
+ query: _.omit(result?.json_query ?? {}, "constraints"),
+ visualization_settings: visualizationSettings ?? {},
+ ...exportParams,
+ },
+});
+
const getDatasetParams = ({
type,
question,
@@ -171,134 +363,110 @@ const getDatasetParams = ({
enablePivot = false,
uuid,
token,
+ documentUuid,
+ documentId,
params = {},
result,
visualizationSettings,
}: DownloadQueryResultsOpts): DownloadQueryResultsParams => {
const cardId = question.id();
- const exportParams = {
+ const exportParams: ExportParams = {
format_rows: enableFormatting,
pivot_results: enablePivot,
};
- const { accessedVia, resourceType: resource } = getDownloadedResourceType({
+ const { accessedVia, resourceType } = getDownloadedResourceType({
dashboardId,
dashcardId,
uuid,
token,
+ documentUuid,
+ documentId,
question,
});
// Public links use special endpoints that use uuids instead of ids
if (accessedVia === "public-link") {
- if (resource === "dashcard") {
- return {
- method: "POST",
- url: `/api/public/dashboard/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/${type}`,
- body: {
- parameters: result?.json_query?.parameters ?? [],
- ...exportParams,
- },
- };
+ if (resourceType === "dashcard") {
+ return getPublicDashcardParams(
+ cardId,
+ checkNotNull(dashboardId),
+ checkNotNull(dashcardId),
+ type,
+ result,
+ exportParams,
+ );
}
- if (resource === "question" && uuid) {
- const parameters = (result?.json_query?.parameters ?? []).map(
- (param) => ({
- id: param.id,
- value: param.value,
- }),
+ if (resourceType === "document-card" && documentUuid) {
+ return getPublicDocumentCardParams(
+ cardId,
+ documentUuid,
+ type,
+ result,
+ exportParams,
);
-
- return {
- method: "GET",
- url: Urls.publicQuestion({ uuid, type, includeSiteUrl: false }),
- params: new URLSearchParams({
- parameters: JSON.stringify(parameters),
- }),
- };
+ }
+ if (resourceType === "question" && uuid) {
+ return getPublicQuestionParams(uuid, type, result);
}
}
// Static embeds use special endpoints that use signed tokens instead of ids
if (accessedVia === "static-embed") {
- if (resource === "dashcard") {
- return {
- method: "GET",
- url: `/api/embed/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}/${type}`,
- params: new URLSearchParams({
- parameters: JSON.stringify(params),
- ..._.mapObject(exportParams, (value) => String(value)),
- }),
- };
+ if (resourceType === "dashcard") {
+ return getEmbedDashcardParams(
+ checkNotNull(token),
+ cardId,
+ checkNotNull(dashcardId),
+ type,
+ params,
+ exportParams,
+ );
}
-
- if (resource === "question" && token) {
- const params = new URLSearchParams(window.location.search);
-
- const convertSearchParamsToObject = (params: URLSearchParams) => {
- const object: Record<string, string | string[]> = {};
- for (const [key, value] of params.entries()) {
- if (object[key]) {
- object[key] = ([] as string[]).concat(
- object[key] as string | string[],
- value,
- );
- } else {
- object[key] = value;
- }
- }
-
- return object;
- };
-
- return {
- method: "GET",
- url: Urls.embedCard(token, type),
- params: new URLSearchParams({
- parameters: JSON.stringify(convertSearchParamsToObject(params)),
- ..._.mapObject(exportParams, (value) => String(value)),
- }),
- };
+ if (resourceType === "question" && token) {
+ return getEmbedQuestionParams(token, type, exportParams);
}
}
// Normal endpoints used by internal, interactive embedding, and SDK
+ if (resourceType === "dashcard") {
+ return getInternalDashcardParams(
+ cardId,
+ checkNotNull(dashboardId),
+ checkNotNull(dashcardId),
+ type,
+ result,
+ exportParams,
+ );
+ }
- if (resource === "dashcard") {
- return {
- method: "POST",
- url: `/api/dashboard/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/query/${type}`,
- body: {
- parameters: result?.json_query?.parameters ?? [],
- ...exportParams,
- },
- };
+ if (resourceType === "document-card" && documentId) {
+ return getInternalDocumentCardParams(
+ cardId,
+ documentId,
+ type,
+ result,
+ exportParams,
+ );
}
- if (resource === "question") {
- return {
- method: "POST",
- url: `/api/card/${cardId}/query/${type}`,
- body: {
- parameters: result?.json_query?.parameters ?? [],
- ...exportParams,
- },
- };
+ if (resourceType === "question") {
+ return getInternalQuestionParams(cardId, type, result, exportParams);
}
- if (resource === "ad-hoc-question") {
- return {
- method: "POST",
- url: `/api/dataset/${type}`,
- body: {
- query: _.omit(result?.json_query ?? {}, "constraints"),
- visualization_settings: visualizationSettings ?? {},
- ...exportParams,
- },
- };
+
+ if (resourceType === "ad-hoc-question") {
+ return getAdHocQuestionParams(
+ type,
+ result,
+ visualizationSettings,
+ exportParams,
+ );
}
- throw new Error("Unknown resource type");
+ throw new Error(
+ `Unsupported download type: ${resourceType} via ${accessedVia}`,
+ );
};
export function getDatasetDownloadUrl(
diff --git a/frontend/src/metabase/routes-public.jsx b/frontend/src/metabase/routes-public.jsx
index 2e85f39a2df..b33002ac7fd 100644
--- a/frontend/src/metabase/routes-public.jsx
+++ b/frontend/src/metabase/routes-public.jsx
@@ -1,4 +1,5 @@
import { Route } from "metabase/hoc/Title";
+import { PLUGIN_PUBLIC_SHARING } from "metabase/plugins";
import { PublicNotFound } from "metabase/public/components/PublicNotFound";
import PublicAction from "metabase/public/containers/PublicAction";
import PublicApp from "metabase/public/containers/PublicApp";
@@ -18,6 +19,10 @@ export const getRoutes = (store) => {
path="dashboard/:uuid(/:tabSlug)"
component={PublicOrEmbeddedDashboardPage}
/>
+ <Route
+ path="document/:uuid"
+ component={PLUGIN_PUBLIC_SHARING.PublicDocumentRoute}
+ />
<Route path="*" component={PublicNotFound} />
</Route>
<Route path="*" component={PublicNotFound} />
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 473e82ae679..b6c3a54cd1d 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -198,6 +198,8 @@ export const PublicApi = {
prefetchDashcardValues: GET(
`${publicBase}/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
),
+ document: GET(`/api/ee/public/document/:uuid`),
+ documentCardQuery: GET(`/api/ee/public/document/:uuid/card/:cardId`),
};
export const EmbedApi = {
diff --git a/resources/migrations/057_update_migrations.yaml b/resources/migrations/057_update_migrations.yaml
index ebe2c809038..93e7c3fd31b 100644
--- a/resources/migrations/057_update_migrations.yaml
+++ b/resources/migrations/057_update_migrations.yaml
@@ -2170,6 +2170,105 @@ databaseChangeLog:
SET dataset_query = legacy_query
WHERE legacy_query IS NOT NULL;
+ - changeSet:
+ id: v57.2025-10-09T00:00:00
+ author: jeff-bruemmer
+ comment: Add public_uuid column to document table for public sharing
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - columnExists:
+ tableName: document
+ columnName: public_uuid
+ changes:
+ - addColumn:
+ tableName: document
+ columns:
+ - column:
+ name: public_uuid
+ type: char(36)
+ remarks: UUID for publicly-accessible version of this document
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v57.2025-10-09T00:00:01
+ author: jeff-bruemmer
+ comment: Add made_public_by_id column to document table for public sharing
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - columnExists:
+ tableName: document
+ columnName: made_public_by_id
+ changes:
+ - addColumn:
+ tableName: document
+ columns:
+ - column:
+ name: made_public_by_id
+ type: int
+ remarks: ID of the user who made this document public
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v57.2025-10-09T00:00:02
+ author: jeff-bruemmer
+ comment: Add index on document.public_uuid
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: document
+ indexName: idx_document_public_uuid
+ changes:
+ - createIndex:
+ tableName: document
+ indexName: idx_document_public_uuid
+ unique: true
+ columns:
+ - column:
+ name: public_uuid
+
+ - changeSet:
+ id: v57.2025-10-09T00:00:03
+ author: jeff-bruemmer
+ comment: Add foreign key constraint for document.made_public_by_id
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_document_made_public_by_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: document
+ baseColumnNames: made_public_by_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ constraintName: fk_document_made_public_by_id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v57.2025-10-09T00:00:04
+ author: jeff-bruemmer
+ comment: Add index on document.made_public_by_id
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: document
+ indexName: idx_document_made_public_by_id
+ changes:
+ - createIndex:
+ tableName: document
+ indexName: idx_document_made_public_by_id
+ columns:
+ - column:
+ name: made_public_by_id
+ rollback:
+ - empty
+
- changeSet:
id: v57.2025-10-21T14:14:22
author: wotbrew
diff --git a/src/metabase/public_sharing/api.clj b/src/metabase/public_sharing/api.clj
index c5c8cfe99f8..82c042ef2c2 100644
--- a/src/metabase/public_sharing/api.clj
+++ b/src/metabase/public_sharing/api.clj
@@ -60,8 +60,11 @@
[card]
(assoc card :parameters (qp.card/combined-parameters-and-template-tags card)))
-(defn- remove-card-non-public-columns
- "Remove everyting from public `card` that shouldn't be visible to the general public."
+(defn remove-card-non-public-columns
+ "Remove everything from public `card` that shouldn't be visible to the general public.
+
+ This function is used by both OSS (for public cards) and EE (for cards in public documents) to ensure
+ consistent filtering of sensitive fields across all public sharing endpoints."
[card]
;; We need to check this to resolve params - we set `request/as-admin` there
(if qp.perms/*param-values-query*