Skip to content

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

Workspace runtime setup (#74705)

Alexander Polyankin8a688591df56
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 83266562c9c..e25444a0f9b 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2222,8 +2222,7 @@
permissions
premium-features
search
- util
- workspaces}
+ util}
:model-imports #{:model/AiUsageLog
:model/Card
:model/Dashboard
@@ -2684,7 +2683,8 @@
enterprise/advanced-config
{:team "UX West"
- :api #{metabase-enterprise.advanced-config.api.logs
+ :api #{metabase-enterprise.advanced-config.api
+ metabase-enterprise.advanced-config.api.logs
metabase-enterprise.advanced-config.file
metabase-enterprise.advanced-config.init
metabase-enterprise.advanced-config.settings}
diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.ts
index cfbf4bd73c6..9a018c11418 100644
--- a/e2e/support/helpers/api/index.ts
+++ b/e2e/support/helpers/api/index.ts
@@ -54,7 +54,4 @@ export {
updateSetting,
} from "./updateSetting";
export { updateSnippet } from "./updateSnippet";
-export {
- clearWorkspaceInstanceConfig,
- setWorkspaceInstanceConfig,
-} from "./setWorkspaceInstanceConfig";
+export { clearWorkspaceInstanceConfig } from "./setWorkspaceInstanceConfig";
diff --git a/e2e/support/helpers/api/setWorkspaceInstanceConfig.ts b/e2e/support/helpers/api/setWorkspaceInstanceConfig.ts
index 3d9945d2f64..4c9a66c5610 100644
--- a/e2e/support/helpers/api/setWorkspaceInstanceConfig.ts
+++ b/e2e/support/helpers/api/setWorkspaceInstanceConfig.ts
@@ -1,9 +1,3 @@
-import type { WorkspaceInstance } from "metabase-types/api";
-
-export function setWorkspaceInstanceConfig(config: WorkspaceInstance) {
- return cy.request("POST", "/api/testing/workspace-instance", config);
-}
-
export function clearWorkspaceInstanceConfig() {
- return cy.request("DELETE", "/api/testing/workspace-instance");
+ return cy.request("DELETE", "/api/ee/workspace-instance/current");
}
diff --git a/e2e/support/helpers/e2e-workspace-helpers.ts b/e2e/support/helpers/e2e-workspace-helpers.ts
index c4c676b80dd..64f77d18908 100644
--- a/e2e/support/helpers/e2e-workspace-helpers.ts
+++ b/e2e/support/helpers/e2e-workspace-helpers.ts
@@ -1,4 +1,6 @@
-import type { WorkspaceId } from "metabase-types/api";
+import yaml from "js-yaml";
+
+import type { AdvancedConfig, WorkspaceId } from "metabase-types/api";
import { modal } from "./e2e-ui-elements-helpers";
@@ -26,6 +28,25 @@ export const NewWorkspaceModal = {
NewWorkspaceModal.get().findByRole("button", { name: "Cancel" }),
};
+export const SetupWorkspaceModal = {
+ get: () => modal(),
+ configInput: () => SetupWorkspaceModal.get().get('input[type="file"]'),
+ setupButton: () =>
+ SetupWorkspaceModal.get().findByRole("button", { name: "Set up" }),
+ cancelButton: () =>
+ SetupWorkspaceModal.get().findByRole("button", { name: "Cancel" }),
+ uploadConfig: (config: AdvancedConfig) => {
+ SetupWorkspaceModal.configInput().selectFile(
+ {
+ contents: Cypress.Buffer.from(yaml.dump(config)),
+ fileName: "config.yml",
+ mimeType: "application/yaml",
+ },
+ { force: true },
+ );
+ },
+};
+
export const WorkspacePage = {
get: () => cy.findByTestId("workspace-page"),
visit: (id: WorkspaceId) => {
@@ -72,8 +93,10 @@ export const NewWorkspaceDatabaseModal = {
get: () => modal(),
databaseRadio: (name: string) =>
NewWorkspaceDatabaseModal.get().findByRole("radio", { name }),
- schemasInput: () =>
- NewWorkspaceDatabaseModal.get().findByLabelText("Schemas to include"),
+ schemasGroup: () =>
+ NewWorkspaceDatabaseModal.get().findByText("Schemas to include"),
+ schemaCheckbox: (name: string) =>
+ NewWorkspaceDatabaseModal.get().findByRole("checkbox", { name }),
submitButton: () =>
NewWorkspaceDatabaseModal.get().findByRole("button", {
name: "Add database",
@@ -84,8 +107,10 @@ export const NewWorkspaceDatabaseModal = {
export const UpdateWorkspaceDatabaseModal = {
get: () => modal(),
- schemasInput: () =>
- UpdateWorkspaceDatabaseModal.get().findByLabelText("Schemas to include"),
+ schemasGroup: () =>
+ UpdateWorkspaceDatabaseModal.get().findByText("Schemas to include"),
+ schemaCheckbox: (name: string) =>
+ UpdateWorkspaceDatabaseModal.get().findByRole("checkbox", { name }),
saveButton: () =>
UpdateWorkspaceDatabaseModal.get().findByRole("button", {
name: "Save changes",
@@ -113,7 +138,7 @@ export const WorkspaceSetupSection = {
export const WorkspaceInstancePage = {
get: () => cy.findByTestId("workspace-instance-page"),
visit: () => {
- cy.visit("/data-studio/workspaces/instance");
+ cy.visit("/data-studio/workspaces");
WorkspaceInstancePage.get().should("be.visible");
},
database: (name: string) =>
@@ -124,4 +149,22 @@ export const WorkspaceInstancePage = {
),
remappingRow: (canonicalName: string) =>
WorkspaceInstancePage.get().findByText(canonicalName),
+ setupButton: () =>
+ WorkspaceInstancePage.get().findByRole("button", {
+ name: "Set up a workspace",
+ }),
+ exitButton: () =>
+ WorkspaceInstancePage.get().findByRole("button", {
+ name: "Leave workspace",
+ }),
+};
+
+export const ExitWorkspaceModal = {
+ get: () => modal(),
+ confirmButton: () =>
+ ExitWorkspaceModal.get().findByRole("button", {
+ name: "Leave workspace",
+ }),
+ cancelButton: () =>
+ ExitWorkspaceModal.get().findByRole("button", { name: "Cancel" }),
};
diff --git a/e2e/test/scenarios/workspaces/workspace-instance.cy.spec.ts b/e2e/test/scenarios/workspaces/workspace-instance.cy.spec.ts
index fdce85a41b5..e8195e522f8 100644
--- a/e2e/test/scenarios/workspaces/workspace-instance.cy.spec.ts
+++ b/e2e/test/scenarios/workspaces/workspace-instance.cy.spec.ts
@@ -1,161 +1,258 @@
-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import {
+ QA_DB_CREDENTIALS,
+ QA_MYSQL_PORT,
+ QA_POSTGRES_PORT,
+ WRITABLE_DB_ID,
+} from "e2e/support/cypress_data";
+import type { AdvancedConfig } from "metabase-types/api";
const { H } = cy;
const WORKSPACE_NAME = "E2E workspace instance";
const ROW_COUNT = 3;
+const POSTGRES_DB_NAME = "Writable Postgres12";
+const POSTGRES_INPUT_SCHEMA = "Domestic";
+const POSTGRES_OUTPUT_SCHEMA = "mb__isolation";
+const POSTGRES_SOURCE_TABLE = "Animals";
+const POSTGRES_TARGET_TABLE = "transform_table";
+const POSTGRES_TARGET_TABLE_DISPLAY_NAME = "Transform Table";
+
+const POSTGRES_CONFIG: AdvancedConfig = {
+ version: 1,
+ config: {
+ databases: [
+ {
+ name: POSTGRES_DB_NAME,
+ engine: "postgres",
+ details: {
+ host: QA_DB_CREDENTIALS.host,
+ port: QA_POSTGRES_PORT,
+ dbname: "writable_db",
+ user: QA_DB_CREDENTIALS.user,
+ password: QA_DB_CREDENTIALS.password,
+ ssl: false,
+ },
+ },
+ ],
+ workspace: {
+ name: WORKSPACE_NAME,
+ databases: {
+ [POSTGRES_DB_NAME]: {
+ input_schemas: [POSTGRES_INPUT_SCHEMA],
+ output: { schema: POSTGRES_OUTPUT_SCHEMA },
+ },
+ },
+ },
+ },
+};
+
+const MYSQL_DB_NAME = "Writable MySQL8";
+const MYSQL_OUTPUT_DATABASE = "mb__isolation";
+const MYSQL_SOURCE_TABLE = "scoreboard_actions";
+const MYSQL_TARGET_TABLE = "transform_table";
+const MYSQL_TARGET_TABLE_DISPLAY_NAME = "Transform Table";
+
+const MYSQL_CONFIG: AdvancedConfig = {
+ version: 1,
+ config: {
+ databases: [
+ {
+ name: MYSQL_DB_NAME,
+ engine: "mysql",
+ details: {
+ host: QA_DB_CREDENTIALS.host,
+ port: QA_MYSQL_PORT,
+ dbname: "writable_db",
+ user: "root",
+ password: QA_DB_CREDENTIALS.password,
+ ssl: false,
+ },
+ },
+ ],
+ workspace: {
+ name: WORKSPACE_NAME,
+ databases: {
+ [MYSQL_DB_NAME]: {
+ input_schemas: [],
+ output: { db: MYSQL_OUTPUT_DATABASE },
+ },
+ },
+ },
+ },
+};
+
describe("scenarios > workspaces > workspace instance", () => {
describe("postgres", () => {
- const databaseName = "Writable Postgres12";
- const inputSchema = "Domestic";
- const outputSchema = "mb__isolation";
- const sourceTable = "Animals";
- const targetTable = "transform_table";
- const targetTableDisplayName = "Transform Table";
-
beforeEach(() => {
H.restore("postgres-writable");
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
+ stubDevelopmentModeTokenFeature();
H.resetTestTable({ type: "postgres", table: "multi_schema" });
H.queryWritableDB(
- `CREATE SCHEMA IF NOT EXISTS ${outputSchema}`,
+ `CREATE SCHEMA IF NOT EXISTS ${POSTGRES_OUTPUT_SCHEMA}`,
"postgres",
);
H.resyncDatabase({ dbId: WRITABLE_DB_ID });
- H.setWorkspaceInstanceConfig({
- name: WORKSPACE_NAME,
- databases: {
- [WRITABLE_DB_ID]: {
- input_schemas: [inputSchema],
- output: { schema: outputSchema },
- },
- },
- });
});
afterEach(() => {
H.clearWorkspaceInstanceConfig();
H.queryWritableDB(
- `DROP SCHEMA IF EXISTS ${outputSchema} CASCADE`,
+ `DROP SCHEMA IF EXISTS ${POSTGRES_OUTPUT_SCHEMA} CASCADE`,
"postgres",
);
});
it("runs a transform, surfaces the remapping on the instance page, and queries the remapped table", () => {
+ cy.log("set up the workspace");
+ H.WorkspaceInstancePage.visit();
+ H.WorkspaceInstancePage.setupButton().click();
+ H.SetupWorkspaceModal.uploadConfig(POSTGRES_CONFIG);
+ H.SetupWorkspaceModal.setupButton().click();
+ H.WorkspaceInstancePage.get().should("be.visible");
+
cy.log("create and run a transform via the API");
createAndRunTransform({
- sourceTable,
- sourceSchema: inputSchema,
- targetTable,
- targetSchema: inputSchema,
+ sourceTable: POSTGRES_SOURCE_TABLE,
+ sourceSchema: POSTGRES_INPUT_SCHEMA,
+ targetTable: POSTGRES_TARGET_TABLE,
+ targetSchema: POSTGRES_INPUT_SCHEMA,
});
cy.log("instance page shows the remapping for the transform target");
H.WorkspaceInstancePage.visit();
- H.WorkspaceInstancePage.database(databaseName)
- .should("contain.text", `${inputSchema}/${targetTable}`)
- .and("contain.text", `${outputSchema}/${inputSchema}__${targetTable}`);
+ H.WorkspaceInstancePage.database(POSTGRES_DB_NAME)
+ .should(
+ "contain.text",
+ `${POSTGRES_INPUT_SCHEMA}/${POSTGRES_TARGET_TABLE}`,
+ )
+ .and(
+ "contain.text",
+ `${POSTGRES_OUTPUT_SCHEMA}/${POSTGRES_INPUT_SCHEMA}__${POSTGRES_TARGET_TABLE}`,
+ );
cy.log("native query is rewritten to workspace table");
H.startNewNativeQuestion({
database: WRITABLE_DB_ID,
- query: `SELECT * FROM "${inputSchema}"."${targetTable}"`,
+ query: `SELECT * FROM "${POSTGRES_INPUT_SCHEMA}"."${POSTGRES_TARGET_TABLE}"`,
});
H.runNativeQuery();
H.assertQueryBuilderRowCount(ROW_COUNT);
cy.log("mbql query is rewritten to workspace table");
H.startNewQuestion();
- H.miniPicker().findByText(databaseName).click();
- H.miniPicker().findByText(inputSchema).click();
- H.miniPicker().findByText(targetTableDisplayName).click();
+ H.miniPicker().findByText(POSTGRES_DB_NAME).click();
+ H.miniPicker().findByText(POSTGRES_INPUT_SCHEMA).click();
+ H.miniPicker().findByText(POSTGRES_TARGET_TABLE_DISPLAY_NAME).click();
H.visualize();
H.assertQueryBuilderRowCount(ROW_COUNT);
cy.log("the actual warehouse table lives under the workspace schema");
H.queryWritableDB(
- `SELECT COUNT(*) AS count FROM "${outputSchema}"."${inputSchema}__${targetTable}"`,
+ `SELECT COUNT(*) AS count FROM "${POSTGRES_OUTPUT_SCHEMA}"."${POSTGRES_INPUT_SCHEMA}__${POSTGRES_TARGET_TABLE}"`,
"postgres",
).then((result) => {
expect(Number(result.rows[0].count)).to.eq(ROW_COUNT);
});
+
+ cy.log("exit the workspace through the UI");
+ H.WorkspaceInstancePage.visit();
+ H.WorkspaceInstancePage.exitButton().click();
+ H.ExitWorkspaceModal.confirmButton().click();
+ H.WorkspaceInstancePage.setupButton().should("be.visible");
});
});
describe("mysql", () => {
- const databaseName = "Writable MySQL8";
- const outputDatabase = "mb__isolation";
- const sourceTable = "scoreboard_actions";
- const targetTable = "transform_table";
- const targetTableDisplayName = "Transform Table";
-
beforeEach(() => {
H.restore("mysql-writable");
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
- H.resetTestTable({ type: "mysql", table: sourceTable });
- H.queryWritableDB(`DROP DATABASE IF EXISTS ${outputDatabase}`, "mysql");
- H.queryWritableDB(`CREATE DATABASE ${outputDatabase}`, "mysql");
+ stubDevelopmentModeTokenFeature();
+ H.resetTestTable({ type: "mysql", table: MYSQL_SOURCE_TABLE });
+ H.queryWritableDB(
+ `DROP DATABASE IF EXISTS ${MYSQL_OUTPUT_DATABASE}`,
+ "mysql",
+ );
+ H.queryWritableDB(`CREATE DATABASE ${MYSQL_OUTPUT_DATABASE}`, "mysql");
H.resyncDatabase({ dbId: WRITABLE_DB_ID });
- H.setWorkspaceInstanceConfig({
- name: WORKSPACE_NAME,
- databases: {
- [WRITABLE_DB_ID]: {
- input_schemas: [],
- output: { db: outputDatabase },
- },
- },
- });
});
afterEach(() => {
H.clearWorkspaceInstanceConfig();
- H.queryWritableDB(`DROP DATABASE IF EXISTS ${outputDatabase}`, "mysql");
+ H.queryWritableDB(
+ `DROP DATABASE IF EXISTS ${MYSQL_OUTPUT_DATABASE}`,
+ "mysql",
+ );
});
it("runs a transform, surfaces the remapping on the instance page, and queries the remapped table", () => {
+ cy.log("set up the workspace");
+ H.WorkspaceInstancePage.visit();
+ H.WorkspaceInstancePage.setupButton().click();
+ H.SetupWorkspaceModal.uploadConfig(MYSQL_CONFIG);
+ H.SetupWorkspaceModal.setupButton().click();
+ H.WorkspaceInstancePage.get().should("be.visible");
+
cy.log("create and run a transform via the API");
createAndRunTransform({
- sourceTable,
+ sourceTable: MYSQL_SOURCE_TABLE,
sourceSchema: null,
- targetTable,
+ targetTable: MYSQL_TARGET_TABLE,
targetSchema: null,
});
cy.log("instance page shows the remapping for the transform target");
H.WorkspaceInstancePage.visit();
- H.WorkspaceInstancePage.database(databaseName)
- .should("contain.text", targetTable)
- .and("contain.text", `${outputDatabase}/__${targetTable}`);
+ H.WorkspaceInstancePage.database(MYSQL_DB_NAME)
+ .should("contain.text", MYSQL_TARGET_TABLE)
+ .and(
+ "contain.text",
+ `${MYSQL_OUTPUT_DATABASE}/__${MYSQL_TARGET_TABLE}`,
+ );
cy.log("native query is rewritten to workspace table");
H.startNewNativeQuestion({
database: WRITABLE_DB_ID,
- query: `SELECT * FROM \`${targetTable}\``,
+ query: `SELECT * FROM \`${MYSQL_TARGET_TABLE}\``,
});
H.runNativeQuery();
H.assertQueryBuilderRowCount(ROW_COUNT);
cy.log("mbql query is rewritten to workspace table");
H.startNewQuestion();
- H.miniPicker().findByText(databaseName).click();
- H.miniPicker().findByText(targetTableDisplayName).click();
+ H.miniPicker().findByText(MYSQL_DB_NAME).click();
+ H.miniPicker().findByText(MYSQL_TARGET_TABLE_DISPLAY_NAME).click();
H.visualize();
H.assertQueryBuilderRowCount(ROW_COUNT);
cy.log("the actual warehouse table lives under the workspace database");
H.queryWritableDB(
- `SELECT COUNT(*) AS count FROM \`${outputDatabase}\`.\`__${targetTable}\``,
+ `SELECT COUNT(*) AS count FROM \`${MYSQL_OUTPUT_DATABASE}\`.\`__${MYSQL_TARGET_TABLE}\``,
"mysql",
).then((result) => {
expect(Number(result.rows[0].count)).to.eq(ROW_COUNT);
});
+
+ cy.log("exit the workspace through the UI");
+ H.WorkspaceInstancePage.visit();
+ H.WorkspaceInstancePage.exitButton().click();
+ H.ExitWorkspaceModal.confirmButton().click();
+ H.WorkspaceInstancePage.setupButton().should("be.visible");
});
});
});
+function stubDevelopmentModeTokenFeature() {
+ cy.intercept("/api/session/properties", (req) => {
+ req.continue((res) => {
+ res.body["token-features"].development_mode = true;
+ });
+ });
+}
+
function createAndRunTransform({
sourceTable,
sourceSchema,
diff --git a/e2e/test/scenarios/workspaces/workspace-manager.cy.spec.ts b/e2e/test/scenarios/workspaces/workspace-manager.cy.spec.ts
index 5432d4ce6c9..f81d9adb1b1 100644
--- a/e2e/test/scenarios/workspaces/workspace-manager.cy.spec.ts
+++ b/e2e/test/scenarios/workspaces/workspace-manager.cy.spec.ts
@@ -86,9 +86,7 @@ describe("scenarios > workspaces > workspace manager", () => {
cy.log("add the writable Postgres database with one schema");
H.WorkspaceDatabaseSection.addDatabaseButton().click();
- H.NewWorkspaceDatabaseModal.schemasInput().click();
- H.popover().findByRole("option", { name: PG_SCHEMA_A }).click();
- H.NewWorkspaceDatabaseModal.get().click();
+ H.NewWorkspaceDatabaseModal.schemaCheckbox(PG_SCHEMA_A).click();
H.NewWorkspaceDatabaseModal.submitButton().click();
H.WorkspaceDatabaseSection.database(POSTGRES_DB_NAME)
@@ -98,9 +96,7 @@ describe("scenarios > workspaces > workspace manager", () => {
cy.log("edit the database to include a second schema");
H.WorkspaceDatabaseSection.databaseMenuButton(POSTGRES_DB_NAME).click();
H.WorkspaceDatabaseSection.editMenuItem().click();
- H.UpdateWorkspaceDatabaseModal.schemasInput().click();
- H.popover().findByRole("option", { name: PG_SCHEMA_B }).click();
- H.UpdateWorkspaceDatabaseModal.get().click();
+ H.UpdateWorkspaceDatabaseModal.schemaCheckbox(PG_SCHEMA_B).click();
H.UpdateWorkspaceDatabaseModal.saveButton().click();
H.WorkspaceDatabaseSection.database(POSTGRES_DB_NAME)
@@ -158,7 +154,7 @@ describe("scenarios > workspaces > workspace manager", () => {
cy.log("add the writable MySQL database (no schemas to pick)");
H.WorkspaceDatabaseSection.addDatabaseButton().click();
- H.NewWorkspaceDatabaseModal.schemasInput().should("not.exist");
+ H.NewWorkspaceDatabaseModal.schemasGroup().should("not.exist");
H.NewWorkspaceDatabaseModal.submitButton().click();
H.WorkspaceDatabaseSection.database(MYSQL_DB_NAME).should("be.visible");
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj
new file mode 100644
index 00000000000..c5abcdd0e9c
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj
@@ -0,0 +1,49 @@
+(ns metabase-enterprise.advanced-config.api
+ "HTTP surface for the EE advanced-config module — runtime apply of a
+ `config.yml` upload."
+ (:require
+ [clojure.java.io :as io]
+ [metabase-enterprise.advanced-config.file :as advanced-config.file]
+ [metabase-enterprise.advanced-config.file.api-keys]
+ [metabase-enterprise.advanced-config.file.databases]
+ [metabase-enterprise.advanced-config.file.settings]
+ [metabase-enterprise.advanced-config.file.users]
+ [metabase-enterprise.advanced-config.file.workspace]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.util.malli.schema :as ms]
+ [metabase.util.yaml :as yaml]))
+
+(comment
+ metabase-enterprise.advanced-config.file.api-keys/keep-me
+ metabase-enterprise.advanced-config.file.databases/keep-me
+ metabase-enterprise.advanced-config.file.settings/keep-me
+ metabase-enterprise.advanced-config.file.users/keep-me
+ metabase-enterprise.advanced-config.file.workspace/keep-me)
+
+(api.macros/defendpoint :post "/" :- :nil
+ "Apply an uploaded `config.yml` to this instance. Runs the same per-section
+ initializers (`settings`, `databases`, `users`, `api-keys`, `workspace`, ...)
+ the boot-time loader runs. Superuser-only.
+
+ Unlike the boot-time loader, `{{env VAR}}` templates are NOT expanded — the
+ file's values are inserted verbatim, so an admin's upload can't read
+ server-side environment variables it didn't intend to."
+ {:multipart true}
+ [_route-params
+ _query-params
+ _body
+ {{config "config"} :multipart-params, :as _request}
+ :- [:map
+ [:multipart-params
+ [:map
+ ["config" [:map
+ [:filename :string]
+ [:tempfile (ms/InstanceOfClass java.io.File)]]]]]]]
+ (api/check-superuser)
+ (let [tempfile (:tempfile config)]
+ (try
+ (advanced-config.file/initialize! (yaml/from-file tempfile))
+ (finally
+ (io/delete-file tempfile :silently))))
+ nil)
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file.clj
index 98f9c82cdcd..e947ffd6dbe 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file.clj
@@ -170,10 +170,6 @@
(log/info (u/format-color :yellow "No config file found at path %s" (pr-str (str path*)))))
path*))
-(def ^:private ^:dynamic *config*
- "Override the config contents as returned by [[config]], for test mocking purposes."
- nil)
-
(defmulti ^:private expand-parsed-template-form
{:arglists '([form])}
(fn [form]
@@ -234,13 +230,22 @@
(string? form) expand-templates-in-str))
m))
-(defn- config
- "Contents of the config file if it exists, otherwise `nil`. If config exists, it will be returned as a map."
+(defn- config-from-disk
+ "Read the config file from disk."
[]
- (when-let [m (or *config*
- (yaml/from-file (str (path))))]
- (s/assert* ::config m)
- (expand-templates m)))
+ (yaml/from-file (str (path))))
+
+(defn- config
+ "Spec-validate `parsed-config` and (optionally) expand `{{env VAR}}` templates.
+ `:expand-templates?` defaults to `false` — env-var expansion against the
+ running process's environment is dangerous, so callers must opt in. The
+ boot-time loader passes `true`; the runtime upload endpoint leaves it off."
+ ([parsed-config] (config parsed-config {}))
+ ([parsed-config {:keys [expand-templates?]
+ :or {expand-templates? false}}]
+ (when parsed-config
+ (s/assert* ::config parsed-config)
+ (cond-> parsed-config expand-templates? expand-templates))))
(defn- sort-by-initialization-order
"Sort the various config sections. The `:settings` section should always be applied first (important, since it can
@@ -251,49 +256,35 @@
config-sections)]
(concat settings-sections other-sections)))
-(defn- workspace-bring-up?
- "True iff the config file declares a *structurally-valid* `:workspace` section.
- Workspace bring-up is a fundamentally different mode of operation from normal
- `config-text-file` usage: the instance is being bootstrapped as a child of a parent
- Metabase, and workspace mode (table remapping, transform redirection, sync rewiring)
- is destructive enough to a normal Metabase that an instance carrying a `:workspace`
- config is committing to that mode regardless of token state. A non-workspace OSS
- instance reading this same config would not function correctly anyway, so the file's
- presence is itself the operator's declaration of intent.
-
- The validity check (delegated to `advanced-config.file.workspace/valid-workspace-section?`)
- is deliberate: we don't want a typo'd or empty `workspace:` key — `workspace: {}`,
- `workspace: foo` — to silently bypass the premium gate. Only a section that would
- actually drive workspace bring-up (has `:name` plus a non-empty `:databases` map of
- the correct shape) opens the gate."
- [m]
- (when-let [section (get-in m [:config :workspace])]
- (advanced-config.file.workspace/valid-workspace-section? section)))
-
(defn ^{:added "0.45.0"} initialize!
- "Initialize Metabase according to the directives in the config file, if it exists."
+ "Initialize Metabase according to the directives in `parsed-config` — a parsed
+ YAML map matching the [[::config]] spec. Opts:
+
+ - `:expand-templates?` (default `false`) — when true, walk the map and expand
+ `{{env VAR}}` templates against the running process's environment. Off by
+ default because reading server-side env vars from an uploaded YAML is
+ dangerous. The boot-time loader (see [[boot-initialize!]]) passes `true`
+ explicitly."
+ ([parsed-config]
+ (initialize! parsed-config {}))
+ ([parsed-config opts]
+ ;; TODO -- this should only do anything if we have an appropriate token (we should get a token for testing this before
+ ;; enabling that check tho)
+ (when-let [m (config parsed-config opts)]
+ (doseq [[section-name section-config] (sort-by-initialization-order (:config m))]
+ ;; You can only use the config-from-file stuff with an EE/Pro token with the `:config-text-file` feature.
+ ;; The `:settings` section is the lone carve-out — you may need it to *install* the token.
+ (when-not (= section-name :settings)
+ (when-not (premium-features/enable-config-text-file?)
+ (throw (ex-info (tru "Metabase config files require a Premium token with the :config-text-file feature.")
+ {}))))
+ (log/info (u/format-color :magenta "Initializing %s from config file..." section-name) (u/emoji "🗄️"))
+ (advanced-config.file.i/initialize-section! section-name section-config))
+ (log/info (u/colorize :magenta "Done initializing from file.") (u/emoji "🗄️")))
+ :ok))
+
+(defn boot-initialize!
+ "Boot-time entry point: read the config file from disk and run [[initialize!]]
+ with `{{env VAR}}` template expansion enabled. No-op when no file is present."
[]
- ;; TODO -- this should only do anything if we have an appropriate token (we should get a token for testing this before
- ;; enabling that check tho)
- (when-let [m (config)]
- (let [bring-up? (workspace-bring-up? m)]
- (doseq [[section-name section-config] (sort-by-initialization-order (:config m))]
- ;; You can only use the config-from-file stuff with an EE/Pro token with the `:config-text-file` feature. Two
- ;; carve-outs:
- ;;
- ;; 1. The `:settings` section is always allowed — you may need it to *install* the token.
- ;;
- ;; 2. If the file contains a `:workspace` section, the entire file is treated as a workspace bring-up
- ;; manifest and runs without the premium token. Workspace child instances bootstrap from a `config.yml`
- ;; *before* their token is installed; the file is the delivery mechanism for the token (and the
- ;; workspace itself). The `defenterprise` gates on workspace mode (`workspace-mode?`,
- ;; `db-workspace-namespace`) still keep non-EE builds from acting on the rows.
- (when-not (or (= section-name :settings)
- bring-up?)
- (when-not (premium-features/enable-config-text-file?)
- (throw (ex-info (tru "Metabase config files require a Premium token with the :config-text-file feature.")
- {}))))
- (log/info (u/format-color :magenta "Initializing %s from config file..." section-name) (u/emoji "🗄️"))
- (advanced-config.file.i/initialize-section! section-name section-config)))
- (log/info (u/colorize :magenta "Done initializing from file.") (u/emoji "🗄️")))
- :ok)
+ (initialize! (config-from-disk) {:expand-templates? true}))
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/workspace.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/workspace.clj
index 14abeaf919c..31be057e107 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/workspace.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/workspace.clj
@@ -1,21 +1,21 @@
(ns metabase-enterprise.advanced-config.file.workspace
"Loader for the `:workspace` section of `config.yml`.
- On boot, parses the section and stores it in the in-process atom:
- [[metabase-enterprise.workspaces.core/workspace-instance-config]].
- That atom is the instance-side source of truth for `db-workspace-namespace`.
-
- The atom is fresh per process, every boot re-reads `config.yml` and replaces the
- prior value. There is no durable storage of instance-side workspace state, by
- design: the file IS the source of truth, and a different file at boot means a
- different workspace, no questions asked."
+ On boot, parses the section and stores it in the `instance-workspace` setting
+ (see [[metabase-enterprise.workspaces.settings]]). That setting is the
+ instance-side source of truth for `db-workspace-namespace`.
+
+ Every boot re-reads `config.yml` and overwrites the prior value. The setting
+ persists across restarts in the instance's app DB, so a running workspace
+ survives a process bounce even without `config.yml` — but if `config.yml` is
+ present at boot, it wins."
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[clojure.walk :as walk]
[metabase-enterprise.advanced-config.file.interface :as advanced-config.file.i]
+ [metabase-enterprise.advanced-config.file.workspace.output :as-alias wkspc-output]
[metabase-enterprise.workspaces.core :as ws]
- [metabase.driver :as driver]
[metabase.util.log :as log]
[toucan2.core :as t2]))
@@ -33,12 +33,21 @@
(s/and string? (complement str/blank?)))
(s/def ::input_schemas
- (s/coll-of ::non-blank-string :min-count 1))
+ (s/coll-of ::non-blank-string))
-(s/def ::output_namespace ::non-blank-string)
+(s/def ::wkspc-output/db
+ (s/nilable string?))
+
+(s/def ::wkspc-output/schema
+ (s/nilable string?))
+
+(s/def ::output
+ (s/and (s/keys :opt-un [::wkspc-output/db
+ ::wkspc-output/schema])
+ (fn [m] (or (some? (:db m)) (some? (:schema m))))))
(s/def ::workspace-database-config
- (s/keys :req-un [::input_schemas ::output_namespace]))
+ (s/keys :req-un [::input_schemas ::output]))
(s/def ::databases
;; map of database-name -> per-database workspace config. Keys may be keywords or
@@ -51,13 +60,6 @@
(s/def ::config-file-spec
(s/keys :req-un [::name ::databases]))
-(defn valid-workspace-section?
- "Predicate used by the file-level loader to decide whether `(:workspace m)` is a
- structurally-valid bring-up manifest. Only a valid section opens the
- config-text-file gate for OSS instances — a typo or empty section must not."
- [section-config]
- (s/valid? ::config-file-spec section-config))
-
(defmethod advanced-config.file.i/section-spec :workspace
[_section-name]
(s/spec ::config-file-spec))
@@ -79,46 +81,23 @@
(throw (ex-info (str "Workspace config references unknown database: " (pr-str db-name))
{:database-name db-name}))))
-(defn- expand-output
- "Expand a driver-opaque `output_namespace` string into the `{:db ?, :schema ?}`
- atom shape that QP middleware, transform_hooks, and table_remapping consume.
-
- The atom contract is map-shaped on purpose: doing this expansion once at
- boot lets the per-query hot path read both slots without re-running the
- per-engine case. For 3-slot drivers (SQL Server, BigQuery) the
- `:db` slot is filled from `Database.details`. For 2-slot drivers the
- `output_namespace` string lands in the schema slot.
-
- `output_namespace` blank means the workspace database isn't provisioned yet —
- the atom carries `{:db ? :schema nil}` and QP/transform consumers treat the
- workspace as having no output mapping."
- [db output-namespace]
- (let [components (set (driver/qualified-name-components (:engine db)))
- positions (ws/engine-namespace-positions db)
- schema (when-not (str/blank? output-namespace) output-namespace)]
- (cond-> {}
- (:db components) (assoc :db (:db positions))
- (:schema components) (assoc :schema schema)
- ;; No-schema drivers (MySQL): the namespace name lands in the db slot.
- (and (:db components) (not (:schema components)))
- (assoc :db schema))))
-
(defn apply-workspace-section!
"Boot-time materialization of the parsed `:workspace` section.
Shape (post-`ordered->plain`):
{:name \"<workspace-name>\"
- :databases {\"<db-name>\" {:input_schemas [<schema-name>, ...]
- :output_namespace <ns-string>}
+ :databases {\"<db-name>\" {:input_schemas [<schema-name>, ...]
+ :output {:db ?, :schema ?}}
...}}
Resolves each database name to a `:model/Database` (rows are populated by the
- `:databases` section, which runs earlier — see [[metabase-enterprise.advanced-config.file/initialize!]])
- and stores the result in [[metabase-enterprise.workspaces.core/workspace-instance-config]] keyed by
- db-id. The atom carries `{:input_schemas [String], :output {:db ?, :schema ?}}`.
- `:output` is expanded once at boot via [[expand-output]] so the QP hot path
- doesn't re-run the per-engine case per query."
+ `:databases` section, which runs earlier — see
+ [[metabase-enterprise.advanced-config.file/initialize!]]) and stores the
+ result in the `instance-workspace` setting keyed by db-id.
+
+ The per-database `:output` map is taken verbatim — `workspaces.config/build-workspace-config`
+ on the manager side emits it already-expanded, so we don't re-derive it here."
[section-config]
(let [{:keys [name databases]} (ordered->plain section-config)
resolved-databases (into {}
@@ -126,7 +105,7 @@
(let [db-name (clojure.core/name db-name-kw)
db (resolve-db db-name)]
[(:id db) {:input_schemas (vec (:input_schemas wsd-config))
- :output (expand-output db (:output_namespace wsd-config))}])))
+ :output (:output wsd-config)}])))
databases)]
(ws/set-instance-workspace! {:name name
:databases resolved-databases})
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index e3e3d705374..a7ae892aa61 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -6,6 +6,7 @@
`enterprise/backend/README.md` for more details."
(:require
[metabase-enterprise.action-v2.api]
+ [metabase-enterprise.advanced-config.api]
[metabase-enterprise.advanced-config.api.logs]
[metabase-enterprise.advanced-permissions.api.routes]
[metabase-enterprise.api.core :as ee.api]
@@ -98,6 +99,7 @@
routes here and follow the convention."
;; Postponing a granular flag for :actions until it's used more widely.
{"/action-v2" (premium-handler metabase-enterprise.action-v2.api/routes :table-data-editing)
+ "/advanced-config" (api.macros/ns-handler 'metabase-enterprise.advanced-config.api)
"/advanced-permissions" (premium-handler metabase-enterprise.advanced-permissions.api.routes/routes :advanced-permissions)
"/ai-controls" (premium-handler metabase-enterprise.metabot.api.routes/routes :ai-controls)
"/audit-app" (premium-handler metabase-enterprise.audit-app.api.routes/routes :audit-app)
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/api/workspace_instance.clj b/enterprise/backend/src/metabase_enterprise/workspaces/api/workspace_instance.clj
index 9326963a5e9..55e1be3fe0c 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/api/workspace_instance.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/api/workspace_instance.clj
@@ -1,13 +1,14 @@
(ns metabase-enterprise.workspaces.api.workspace-instance
"EE API endpoints for the workspace loaded on this (child) instance, served under
- `/api/ee/workspace-instance`. Read-only — see [[metabase-enterprise.workspaces.api.workspace-manager]]
- for admin operations."
+ `/api/ee/workspace-instance`. See [[metabase-enterprise.workspaces.api.workspace-manager]]
+ for the manager-side admin operations."
(:require
[metabase-enterprise.workspaces.core :as ws]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.lib.schema.id :as lib.schema.id]
- [metabase.util.malli.schema :as ms]))
+ [metabase.util.malli.schema :as ms]
+ [metabase.workspaces.core :as ws.oss]))
;;; ----------------------------------------------- Schemas ----------------------------------------------------
@@ -55,16 +56,41 @@
;;; ---------------------------------------------- Endpoints ---------------------------------------------------
-(api.macros/defendpoint :get "/current" :- [:maybe WorkspaceInstance]
- "Read-only summary of the workspace loaded on this instance.
+(api.macros/defendpoint :get "/current" :- [:map [:data [:maybe WorkspaceInstance]]]
+ "Read-only summary of the workspace loaded on this instance, wrapped in a
+ `{:data ...}` envelope.
- Reads from the in-process atom populated at boot by the `:workspace` section of
- `config.yml`. Returns `nil` when no workspace was loaded — i.e. this is a manager-only
- instance, or no `config.yml` was present at boot."
+ Reads from the `instance-workspace` setting populated at boot by the `:workspace`
+ section of `config.yml`, or at runtime by `POST /current`. `:data` is `null`
+ when no workspace was loaded — i.e. this is a manager-only instance, or no
+ `config.yml` was present at boot and `POST /current` hasn't been called.
+ The envelope avoids an empty JSON body for the `nil` case."
[]
(api/check-superuser)
- (when-let [workspace (ws/instance-workspace)]
- (present-workspace-instance workspace)))
+ {:data (some-> (ws/instance-workspace) present-workspace-instance)})
+
+(api.macros/defendpoint :post "/current" :- WorkspaceInstance
+ "Install a workspace config on this instance at runtime. Accepts the same shape
+ `GET /current` returns and persists it via the `instance-workspace` setting so
+ it survives restarts. Use this on a running instance to enter workspace mode
+ without restarting from `config.yml`."
+ [_route-params
+ _query-params
+ body :- ::ws.oss/workspace-instance-config]
+ (api/check-superuser)
+ (ws/set-instance-workspace! body)
+ (present-workspace-instance (ws/instance-workspace)))
+
+(api.macros/defendpoint :delete "/current" :- :nil
+ "Clear the workspace config on this instance. After this returns, the instance
+ is no longer in workspace mode and `GET /current` returns `nil`. Also drops
+ every `TableRemapping` row, since stale mappings from the prior workspace
+ would otherwise keep rewriting queries on the now-unmanaged databases."
+ []
+ (api/check-superuser)
+ (ws/clear-instance-workspace!)
+ (ws/clear-all-remappings!)
+ nil)
(api.macros/defendpoint :get "/table-remappings" :- [:sequential TableRemapping]
"Return all table remappings, ordered by id."
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/config.clj b/enterprise/backend/src/metabase_enterprise/workspaces/config.clj
index c75fc6093dc..f8109d90df0 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/config.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/config.clj
@@ -1,8 +1,10 @@
(ns metabase-enterprise.workspaces.config
(:require
[clojure.string :as str]
+ [metabase-enterprise.workspaces.core :as ws]
[metabase-enterprise.workspaces.models.workspace :as workspace]
[metabase-enterprise.workspaces.models.workspace-database]
+ [metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.util.yaml :as yaml]
[toucan2.core :as t2]))
@@ -52,14 +54,30 @@
(:database_details wsd)
(schema-filter-entries db wsd))})
+(defn- expand-output
+ "Expand a driver-opaque `output_namespace` string into the `{:db ?, :schema ?}`
+ namespace map QP middleware, transform_hooks, and table_remapping consume.
+
+ For 3-slot drivers (SQL Server, BigQuery) the `:db` slot is filled from
+ `Database.details`. For 2-slot drivers the namespace string lands in the
+ schema slot. For no-schema drivers (MySQL) it lands in the db slot.
+
+ `output_namespace` blank → `:schema` is `nil`: the workspace database isn't
+ provisioned yet and QP/transform consumers treat it as having no output
+ mapping."
+ [db output-namespace]
+ (let [components (set (driver/qualified-name-components (:engine db)))
+ positions (ws/engine-namespace-positions db)
+ schema (when-not (str/blank? output-namespace) output-namespace)]
+ (cond-> {}
+ (:db components) (assoc :db (:db positions))
+ (:schema components) (assoc :schema schema)
+ (and (:db components) (not (:schema components)))
+ (assoc :db schema))))
+
(defn- workspace-database-entry [wsd db]
- ;; Emit the wire shape: `:output_namespace` is a driver-opaque string. The
- ;; loader (`advanced-config.file.workspace/expand-output`) expands it into the
- ;; `{:db ?, :schema ?}` runtime map at boot. Emitting the already-expanded
- ;; shape here makes the round-trip `build -> yaml -> initialize!` fail the
- ;; `::workspace-database-config` spec assertion.
- [(:name db) {:input_schemas (vec (:input_schemas wsd))
- :output_namespace (:output_namespace wsd)}])
+ [(:name db) {:input_schemas (vec (:input_schemas wsd))
+ :output (expand-output db (:output_namespace wsd))}])
(defn build-workspace-config
"Return a downloadable config.yml-shaped map for `workspace-id`:
@@ -67,18 +85,16 @@
{:version 1
:config {:databases [...]
:workspace {:name <ws-name>
- :databases {<db-name> {:input_schemas [<schema-name> ...]
- :output_namespace <ns-string>}}}}}
+ :databases {<db-name> {:input_schemas [<schema-name> ...]
+ :output {:db ? :schema ?}}}}}
Each database entry merges the underlying `metabase_database.details` with the
WorkspaceDatabase's override credentials and adds `schema-filters-*` keys
- derived from `:input_schemas`. Per-database workspace entries carry plain
- schema-name strings for `:input_schemas` (the 3-slot driver catalog is read
- from `Database.details` at use time, not duplicated on each row), and a
- driver-opaque string for `:output_namespace` (the loader expands it into the
- `{:db ?, :schema ?}` runtime map at boot). Returns nil when the workspace
- does not exist. Throws a 409 `ex-info` if any of the workspace's databases
- is not `:provisioned`."
+ derived from `:input_schemas`. Per-database workspace entries carry the
+ expanded `{:db ?, :schema ?}` namespace map directly — the same shape the
+ `instance-workspace` setting stores. Returns nil when the workspace does not
+ exist. Throws a 409 `ex-info` if any of the workspace's databases is not
+ `:provisioned`."
[workspace-id]
(when-let [ws (workspace/get-workspace workspace-id)]
(let [wsds (:databases ws)]
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/core.clj b/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
index d9514b86645..fb75ad84d6f 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
@@ -11,11 +11,13 @@
- **Instance-side state.** When a Metabase boots in workspace mode, the
`:workspace` section loader (`metabase-enterprise.advanced-config.file.workspace`)
- parses `config.yml` and stores the resulting workspace map in
- [[workspace-instance-config]]. Workspace-aware code (transform target
- rewriting, table-remapping QP middleware) reads from that atom via
- [[workspace-mode?]] / [[db-workspace-namespace]]. The atom is fresh per process
- — every boot re-reads `config.yml` and replaces the prior value.
+ parses `config.yml` and stores the resulting workspace map in the
+ `instance-workspace` setting. Workspace-aware code (transform target
+ rewriting, table-remapping QP middleware) reads from the setting via
+ [[workspace-mode?]] / [[db-workspace-namespace]]. The setting lives in the
+ instance's own application database — child instances have their own app DB,
+ so storing it there persists the workspace across restarts without leaking
+ between parent and child.
Per-database lifecycle for the manager-side rows:
@@ -32,9 +34,11 @@
(:require
[metabase-enterprise.workspaces.models.workspace :as workspace]
[metabase-enterprise.workspaces.provisioning :as provisioning]
+ [metabase-enterprise.workspaces.settings :as ws.settings]
[metabase.driver.sql :as driver.sql]
[metabase.driver.util :as driver.u]
- [metabase.premium-features.core :refer [defenterprise defenterprise-schema]]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.util.malli :as mu]
[metabase.workspaces.core :as ws]
[toucan2.core :as t2]))
@@ -70,52 +74,51 @@
{:db (driver.sql/db-slot-value (:engine database) database)
:schema (:schema table)})))
-(defonce ^{:dynamic true
- :doc "The single workspace loaded into this instance from `config.yml`, or nil
- when no workspace was loaded.
-
- Shape:
- {:name <workspace-name>
- :databases {<database-id> {:input_schemas [<schema-name>, ...]
- :output {:db ?, :schema ?}}
- ...}}
-
- `:input_schemas` is a vector of driver-opaque schema strings. For 3-slot
- drivers (SQL Server, BigQuery) the warehouse catalog/project is
- derived from the canonical `Database.details` at use time, not duplicated
- on each row.
-
- `:output` is a `::table-namespace` map — the loader expands the stored
- `output_namespace` string into `{:db (db-position-value db) :schema ns}`
- at boot so QP middleware can read both slots without a per-query case."}
- *workspace-instance-config*
- (atom nil))
-
-(defenterprise-schema set-instance-workspace! :- :any
- "EE impl: install the in-process workspace config atom. Replaces any prior
- value. The shape is validated against `::ws/workspace-instance-config`."
- :feature :none
+(defn- coerce-database-id-key
+ "JSON round-trips through the `instance-workspace` setting return integer
+ `Database.id` keys as keywords (e.g. `:1`). Coerce them back to ints."
+ [k]
+ (cond
+ (int? k) k
+ (keyword? k) (parse-long (name k))
+ (string? k) (parse-long k)))
+
+(defn- normalize-database-keys
+ "Coerce the `:databases` map keys to ints. See [[coerce-database-id-key]]."
+ [config]
+ (some-> config
+ (update :databases #(update-keys % coerce-database-id-key))))
+
+(mu/defn set-instance-workspace! :- :any
+ "Store the workspace config in the `instance-workspace` setting. Replaces any
+ prior value. The shape is validated against `::ws/workspace-instance-config`."
[config :- ::ws/workspace-instance-config]
- (reset! *workspace-instance-config* config)
+ (ws.settings/instance-workspace! config)
nil)
-(defenterprise clear-instance-workspace!
- "EE impl: clear the in-process workspace config atom."
- :feature :none
+(defn clear-instance-workspace!
+ "Clear the `instance-workspace` setting."
+ []
+ (ws.settings/instance-workspace! nil)
+ nil)
+
+(defn clear-all-remappings!
+ "Delete every `:model/TableRemapping` row across all databases."
[]
- (reset! *workspace-instance-config* nil)
+ (t2/delete! :model/TableRemapping)
nil)
(defn instance-workspace
"Return the workspace loaded on this instance, or nil if none."
[]
- @*workspace-instance-config*)
+ (normalize-database-keys (ws.settings/instance-workspace)))
(defenterprise workspace-mode?
- "EE impl: true iff this instance is running in workspace mode (a `:workspace`
- section was loaded from `config.yml` at boot). Single source of truth for
- gating features that conflict with workspace remapping (DB routing,
- impersonation, writeback, CSV upload, model persistence). Use
+ "EE impl: true iff this instance is running in workspace mode (the
+ `instance-workspace` setting is populated — either from a `:workspace` section
+ of `config.yml` at boot or by a `POST /api/ee/advanced-config`). Single
+ source of truth for gating features that conflict with workspace remapping
+ (DB routing, impersonation, writeback, CSV upload, model persistence). Use
[[db-workspace-namespace]] when you need per-database scoping.
Deliberately ungated on premium features: a workspace child instance bootstraps
@@ -123,17 +126,17 @@
loaded, we refuse incompatible features regardless of token state."
:feature :none
[]
- (some? @*workspace-instance-config*))
+ (some? (ws.settings/instance-workspace)))
(defn db-workspace-namespace
"Return the workspace-isolated output namespace map for `db-id` on this
instance, or `nil` when this instance is not running a workspace or the
workspace has no entry for `db-id`. The namespace map is
`{:db ?, :schema ?}` - either or both keys may be absent depending on
- the driver's `qualified-name-components`. Reads from the in-process atom
- populated by `config.yml`."
+ the driver's `qualified-name-components`. Reads from the `workspace-instance`
+ setting."
[db-id]
- (get-in @*workspace-instance-config* [:databases db-id :output]))
+ (get-in (instance-workspace) [:databases db-id :output]))
(defn list-remappings
"Return all TableRemapping rows, ordered by id."
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/settings.clj b/enterprise/backend/src/metabase_enterprise/workspaces/settings.clj
index 0bb4c9320bb..05cc5e0f99b 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/settings.clj
@@ -1,6 +1,5 @@
(ns metabase-enterprise.workspaces.settings
(:require
- [metabase-enterprise.workspaces.core :as ws]
[metabase.settings.core :refer [defsetting]]
[metabase.util.i18n :refer [deferred-tru]]))
@@ -8,12 +7,11 @@
"Marker so callers can `(comment ...keep-me)` to retain the require that registers the settings in this ns."
nil)
-(defsetting has-active-workspace
- (deferred-tru "True if a workspace is loaded on this instance from a config.yml :workspace section. Read-only projection of the in-process atom populated by the boot-time loader; false on parent and unconfigured instances.")
- :type :boolean
- :visibility :admin
+(defsetting instance-workspace
+ (deferred-tru "The workspace loaded on this instance. Populated at boot from a config.yml `:workspace` section or at runtime via `POST /api/ee/advanced-config`. `nil` on parent and unconfigured instances. Read by the QP, transform hooks, and the EE `workspace-mode?` predicate via `metabase-enterprise.workspaces.core/instance-workspace`.")
+ :type :json
+ :encryption :no
+ :visibility :internal
:export? false
- :setter :none
- :getter (fn [] (some? (ws/instance-workspace)))
:audit :never
:doc false)
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj
new file mode 100644
index 00000000000..047de3fdb53
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj
@@ -0,0 +1,77 @@
+(ns metabase-enterprise.advanced-config.api-test
+ (:require
+ [clojure.test :refer [deftest is testing use-fixtures]]
+ [metabase-enterprise.workspaces.core :as ws]
+ [metabase.driver.util]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util.yaml :as yaml]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db))
+
+(defn- yaml-bytes ^bytes [body]
+ (.getBytes ^String (yaml/generate-string body) "UTF-8"))
+
+(defn- multipart [bs]
+ [{:request-options {:headers {"content-type" "multipart/form-data"}}}
+ {:config bs}])
+
+(deftest superuser-only-test
+ (testing "POST /api/ee/advanced-config requires superuser"
+ (is (= "You don't have permissions to do that."
+ (apply mt/user-http-request :rasta :post 403 "ee/advanced-config/"
+ (multipart (yaml-bytes {:version 1 :config {}})))))))
+
+(deftest does-not-expand-templates-test
+ (testing "POST /api/ee/advanced-config does NOT expand `{{env VAR}}` templates"
+ ;; The literal template appears in the inserted database's name; if env
+ ;; expansion happened, the row would be created under a different name.
+ (let [db-name "advanced-config-literal-{{env SECRET}}"
+ payload {:version 1
+ :config {:databases [{:name db-name
+ :engine "postgres"
+ :details {}}]}}]
+ (try
+ (mt/with-premium-features #{:config-text-file}
+ (mt/with-temporary-setting-values [config-from-file-sync-databases false]
+ (with-redefs [metabase.driver.util/can-connect-with-details? (constantly true)]
+ (mt/user-http-request :crowberto :post 204 "ee/advanced-config/"
+ (first (multipart (yaml-bytes payload)))
+ (second (multipart (yaml-bytes payload)))))))
+ (is (some? (t2/select-one :model/Database :name db-name :engine "postgres"))
+ "Database row carries the LITERAL name with templates unexpanded")
+ (finally
+ (when-let [db-id (t2/select-one-pk :model/Database :name db-name :engine "postgres")]
+ (t2/delete! :model/Database db-id)))))))
+
+(deftest applies-workspace-section-test
+ (testing "POST /api/ee/advanced-config applies the :workspace section into the instance-workspace setting"
+ (let [db-name (str "advanced-config-ws-" (random-uuid))
+ payload {:version 1
+ :config {:databases [{:name db-name
+ :engine "postgres"
+ :details {}}]
+ :workspace {:name "Uploaded Workspace"
+ :databases {(keyword db-name) {:input_schemas ["public"]
+ :output {:schema "ws_uploaded"}}}}}}]
+ (try
+ (mt/with-premium-features #{:config-text-file}
+ (mt/with-temporary-setting-values [config-from-file-sync-databases false]
+ (with-redefs [metabase.driver.util/can-connect-with-details? (constantly true)]
+ (mt/user-http-request :crowberto :post 204 "ee/advanced-config/"
+ (first (multipart (yaml-bytes payload)))
+ (second (multipart (yaml-bytes payload)))))))
+ (testing "Database row was created"
+ (let [db (t2/select-one :model/Database :name db-name :engine "postgres")]
+ (is (some? db))
+ (testing "Workspace instance setting was set"
+ (let [stored (ws/instance-workspace)]
+ (is (= "Uploaded Workspace" (:name stored)))
+ (is (= {:schema "ws_uploaded"} (get-in stored [:databases (:id db) :output])))))))
+ (finally
+ (ws/clear-instance-workspace!)
+ (when-let [db-id (t2/select-one-pk :model/Database :name db-name :engine "postgres")]
+ (t2/delete! :model/Database db-id)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/api_keys_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/api_keys_test.clj
index c8e91b6a6b7..9163e3e89c9 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/api_keys_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/api_keys_test.clj
@@ -21,134 +21,136 @@
(t2/exists? :model/User :first_name name :type :api-key))
(deftest create-api-keys-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_testapikey123"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}
- {:name "All Users API Key"
- :key "mb_differentapikey456"
- :creator (:email (mt/fetch-user :crowberto))
- :group "all-users"}]}}]
- (is (= :ok (config.file/initialize!)))
- (testing "API keys should be created"
- (is (api-key-exists? "Test API Key"))
- (is (api-key-exists? "All Users API Key")))
- (testing "API key users should be created"
- (is (api-key-user-exists? "Test API Key"))
- (is (api-key-user-exists? "All Users API Key")))))
+ (is (= :ok (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_testapikey123"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}
+ {:name "All Users API Key"
+ :key "mb_differentapikey456"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "all-users"}]}})))
+ (testing "API keys should be created"
+ (is (api-key-exists? "Test API Key"))
+ (is (api-key-exists? "All Users API Key")))
+ (testing "API key users should be created"
+ (is (api-key-user-exists? "Test API Key"))
+ (is (api-key-user-exists? "All Users API Key"))))
(deftest duplicate-api-key-prefix-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "First API Key"
- :key "mb_sameprefix123"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}
- {:name "Second API Key"
- :key "mb_sameprefix456"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}]}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"API key with prefix 'mb_same' already exists\. Keys must have unique prefixes\."
- (config.file/initialize!)))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"API key with prefix 'mb_same' already exists\. Keys must have unique prefixes\."
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "First API Key"
+ :key "mb_sameprefix123"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}
+ {:name "Second API Key"
+ :key "mb_sameprefix456"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}]}}))))
(deftest non-admin-creator-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_1testapikey123"
- :creator (:email (mt/fetch-user :rasta))
- :group "admin"}]}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"User with email [email protected] is not an admin"
- (config.file/initialize!)))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"User with email [email protected] is not an admin"
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_1testapikey123"
+ :creator (:email (mt/fetch-user :rasta))
+ :group "admin"}]}}))))
(deftest nonexistent-creator-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_2testapikey123"
- :creator "[email protected]"
- :group "admin"}]}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"User with email [email protected] not found"
- (config.file/initialize!)))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"User with email [email protected] not found"
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_2testapikey123"
+ :creator "[email protected]"
+ :group "admin"}]}}))))
(deftest skip-existing-api-keys-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_3testapikey123"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}]}}]
- (config.file/initialize!)
- (let [first-key (t2/select-one :model/ApiKey :name "Test API Key")
- _ (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_4testapikey123"
- :creator "[email protected]"
- :group "admin"}]}}]
- (config.file/initialize!))
- second-key (t2/select-one :model/ApiKey :name "Test API Key")]
- (is (= (:id first-key) (:id second-key))))))
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_3testapikey123"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}]}})
+ (let [first-key (t2/select-one :model/ApiKey :name "Test API Key")
+ _ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_4testapikey123"
+ :creator "[email protected]"
+ :group "admin"}]}})
+ second-key (t2/select-one :model/ApiKey :name "Test API Key")]
+ (is (= (:id first-key) (:id second-key)))))
(deftest validate-group-values-test
(mt/with-temp [:model/User _ {:email "[email protected]"
:first_name "Admin"
:is_superuser true}]
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Test API Key"
- :key "mb_5testapikey123"
- :creator "[email protected]"
- :group "invalid-group"}]}}]
- (is (thrown? clojure.lang.ExceptionInfo
- (config.file/initialize!))))))
+ (is (thrown? clojure.lang.ExceptionInfo
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Test API Key"
+ :key "mb_5testapikey123"
+ :creator "[email protected]"
+ :group "invalid-group"}]}})))))
(deftest env-var-api-key-test
(mt/with-temp-env-var-value! ["MB_API_KEY_FROM_ENV" "mb_envvariablekey123"]
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "ENV API Key"
- :key "{{env API_KEY_FROM_ENV}}"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}]}}
- config.file/*env* (assoc @#'config.file/*env* :api-key-from-env "mb_envvariablekey123")]
- (is (= :ok (config.file/initialize!)))
+ (binding [config.file/*env* (assoc @#'config.file/*env* :api-key-from-env "mb_envvariablekey123")]
+ (is (= :ok (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "ENV API Key"
+ :key "{{env API_KEY_FROM_ENV}}"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}]}}
+ {:expand-templates? true})))
(testing "API key should be created from env var"
(is (api-key-exists? "ENV API Key"))))))
(deftest validate-env-var-api-key-format-test
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Invalid ENV API Key"
- :key "{{env INVALID_API_KEY}}"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}]}}
- config.file/*env* (assoc @#'config.file/*env* :invalid-api-key "invalid_key_format")]
+ (binding [config.file/*env* (assoc @#'config.file/*env* :invalid-api-key "invalid_key_format")]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Invalid API key format"
- (config.file/initialize!)))))
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Invalid ENV API Key"
+ :key "{{env INVALID_API_KEY}}"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}]}}
+ {:expand-templates? true})))))
(deftest skip-existing-api-keys-with-same-prefix-test
;; First, create an API key with a specific name
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Duplicate Name Key"
- :key "mb_original123"
- :creator (:email (mt/fetch-user :crowberto))
- :group "admin"}]}}]
- (config.file/initialize!)
- (testing "Original API key is created"
- (is (api-key-exists? "Duplicate Name Key"))
- (let [original-key (t2/select-one :model/ApiKey :name "Duplicate Name Key")
- original-key-prefix (:key_prefix original-key)]
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Duplicate Name Key"
+ :key "mb_original123"
+ :creator (:email (mt/fetch-user :crowberto))
+ :group "admin"}]}})
+ (testing "Original API key is created"
+ (is (api-key-exists? "Duplicate Name Key"))
+ (let [original-key (t2/select-one :model/ApiKey :name "Duplicate Name Key")
+ original-key-prefix (:key_prefix original-key)]
- ;; Now attempt to create another key with the same name but different prefix
- (binding [config.file/*config* {:version 1
- :config {:api-keys [{:name "Duplicate Name Key"
- :key "mb_different456" ;; different key with different prefix
- :creator "[email protected]"
- :group "admin"}]}}]
- (config.file/initialize!)
- (testing "Second key with same name is skipped (no error about duplicate prefix)"
- (let [key-after-attempt (t2/select-one :model/ApiKey :name "Duplicate Name Key")]
- (is (= (:id original-key) (:id key-after-attempt)))
- (is (= original-key-prefix (:key_prefix key-after-attempt))))))))))
+ ;; Now attempt to create another key with the same name but different prefix
+ (config.file/initialize!
+ {:version 1
+ :config {:api-keys [{:name "Duplicate Name Key"
+ :key "mb_different456" ;; different key with different prefix
+ :creator "[email protected]"
+ :group "admin"}]}})
+ (testing "Second key with same name is skipped (no error about duplicate prefix)"
+ (let [key-after-attempt (t2/select-one :model/ApiKey :name "Duplicate Name Key")]
+ (is (= (:id original-key) (:id key-after-attempt)))
+ (is (= original-key-prefix (:key_prefix key-after-attempt))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj
index 43ed64b095f..7186816e572 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj
@@ -29,56 +29,53 @@
:engine (name db-type)
:details (:details original-db)}]}}]
(try
- (binding [advanced-config.file/*config* config]
- (testing "Create a Database if it does not already exist"
- (is (= :ok
- (advanced-config.file/initialize!)))
- (let [db (t2/select-one :model/Database :name test-db-name)]
- (is (partial= {:engine db-type}
- db))
+ (testing "Create a Database if it does not already exist"
+ (is (= :ok
+ (advanced-config.file/initialize! config)))
+ (let [db (t2/select-one :model/Database :name test-db-name)]
+ (is (partial= {:engine db-type}
+ db))
+ (is (= 1
+ (t2/count :model/Database :name test-db-name)))
+ (testing "do not duplicate if Database already exists"
+ (is (= :ok
+ (advanced-config.file/initialize! config)))
(is (= 1
(t2/count :model/Database :name test-db-name)))
- (testing "do not duplicate if Database already exists"
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (= 1
- (t2/count :model/Database :name test-db-name)))
- (is (partial= {:engine db-type}
- (t2/select-one :model/Database :name test-db-name))))
- (testing "updates db"
- (is (= :ok
- (binding [advanced-config.file/*config*
- (assoc-in config [:config :databases 0 :description] "foo")]
- (advanced-config.file/initialize!))))
- (is (partial= {:description "foo"}
- (t2/select-one :model/Database :name test-db-name))))
- (testing "does not re-set attached dwh db keys on update"
- (is (= :ok
- (binding [advanced-config.file/*config*
- (update-in config [:config :databases 0] merge
- {:is_attached_dwh true
- :uploads_enabled true
- :uploads_schema_name "db_123"
- :uploads_table_prefix "upload_"})]
- (advanced-config.file/initialize!))))
- (is (partial= {:is_attached_dwh true
- :uploads_enabled false
- :uploads_schema_name nil
- :uploads_table_prefix nil}
- (t2/select-one :model/Database :name test-db-name)))))))
+ (is (partial= {:engine db-type}
+ (t2/select-one :model/Database :name test-db-name))))
+ (testing "updates db"
+ (is (= :ok
+ (advanced-config.file/initialize!
+ (assoc-in config [:config :databases 0 :description] "foo"))))
+ (is (partial= {:description "foo"}
+ (t2/select-one :model/Database :name test-db-name))))
+ (testing "does not re-set attached dwh db keys on update"
+ (is (= :ok
+ (advanced-config.file/initialize!
+ (update-in config [:config :databases 0] merge
+ {:is_attached_dwh true
+ :uploads_enabled true
+ :uploads_schema_name "db_123"
+ :uploads_table_prefix "upload_"}))))
+ (is (partial= {:is_attached_dwh true
+ :uploads_enabled false
+ :uploads_schema_name nil
+ :uploads_table_prefix nil}
+ (t2/select-one :model/Database :name test-db-name))))))
(finally
(t2/delete! :model/Database :name test-db-name))))))
(deftest init-from-config-file-connection-validation-test
(testing "Validate connection details when creating a Database from a config file, and error if they are invalid"
- (binding [advanced-config.file/*config* {:version 1
- :config {:databases [{:name (str test-db-name "-in-memory")
- :engine "h2"
- :details {:db "mem:some-in-memory-db"}}]}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"Database cannot be found\."
- (advanced-config.file/initialize!))))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Database cannot be found\."
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:databases [{:name (str test-db-name "-in-memory")
+ :engine "h2"
+ :details {:db "mem:some-in-memory-db"}}]}})))))
(deftest sync-test
(testing "`init-from-config-file!` returns syncs database in a separate thread by default"
@@ -174,19 +171,19 @@
;; make sure we're actually testing something if it was already set to false locally.
(mt/with-temporary-setting-values [config-from-file-sync-databases true]
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-sync-databases false}}}]
- (is (= :ok (advanced-config.file/initialize!)))
- (let [sync-future (@#'advanced-config.file.databases/init-from-config-file! {:name test-db-name
- :engine "h2"
- :details (:details (mt/db))})]
- (is (nil? sync-future))
- (let [db (t2/select-one :model/Database :name test-db-name)]
- (is (partial= {:engine :h2}
- db))
- (is (= 1 (t2/count :model/Database :name test-db-name)))
- (testing "Database should NOT have been synced"
- (is (zero? (t2/count :model/Table :db_id (u/the-id db))))))))
+ (is (= :ok (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-sync-databases false}}})))
+ (let [sync-future (@#'advanced-config.file.databases/init-from-config-file! {:name test-db-name
+ :engine "h2"
+ :details (:details (mt/db))})]
+ (is (nil? sync-future))
+ (let [db (t2/select-one :model/Database :name test-db-name)]
+ (is (partial= {:engine :h2}
+ db))
+ (is (= 1 (t2/count :model/Database :name test-db-name)))
+ (testing "Database should NOT have been synced"
+ (is (zero? (t2/count :model/Table :db_id (u/the-id db)))))))
(finally
(t2/delete! :model/Database :name test-db-name))))))
@@ -195,31 +192,31 @@
(mt/with-temp [:model/Database _ {:name test-db-name
:engine "h2"}]
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-sync-databases false}
- :databases [{:name test-db-name
- :engine "h2"
- :details {}
- :delete (format "DELETE_WITH_DEPENDENTS:%s" test-db-name)}]}}]
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (not (t2/exists? :model/Database :name test-db-name))))
+ (is (= :ok
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-sync-databases false}
+ :databases [{:name test-db-name
+ :engine "h2"
+ :details {}
+ :delete (format "DELETE_WITH_DEPENDENTS:%s" test-db-name)}]}})))
+ (is (not (t2/exists? :model/Database :name test-db-name)))
(finally
(t2/delete! :model/Database :name test-db-name)))))
(testing "We should not delete Databases from the config file if the confirmation string mismatches"
(mt/with-temp [:model/Database _ {:name test-db-name
:engine "h2"}]
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-sync-databases false}
- :databases [{:name test-db-name
- :engine "h2"
- :details {}
- :delete "DELETE_WITH_DEPENDENTS:copy-paste-mistake"}]}}]
- (is (thrown-with-msg?
- ExceptionInfo
- (re-pattern (format "To delete database \"%s\" set `delete` to \"DELETE_WITH_DEPENDENTS:%s\"" test-db-name test-db-name))
- (advanced-config.file/initialize!)))
- (is (t2/exists? :model/Database :name test-db-name)))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ (re-pattern (format "To delete database \"%s\" set `delete` to \"DELETE_WITH_DEPENDENTS:%s\"" test-db-name test-db-name))
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-sync-databases false}
+ :databases [{:name test-db-name
+ :engine "h2"
+ :details {}
+ :delete "DELETE_WITH_DEPENDENTS:copy-paste-mistake"}]}})))
+ (is (t2/exists? :model/Database :name test-db-name))
(finally
(t2/delete! :model/Database :name test-db-name))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/settings_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/settings_test.clj
index 44f7bd032e9..f9e80a76ef0 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/settings_test.clj
@@ -20,27 +20,26 @@
(testing "Should be able to set settings with config-from-file"
(config-from-file-settings-test-setting! nil)
(testing "happy path"
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-settings-test-setting "wow"}}}]
- (advanced-config.file/initialize!)
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-settings-test-setting "wow"}}})
+ (is (= "wow"
+ (config-from-file-settings-test-setting))))
+ (testing "Wrong value type should throw an error."
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid input: .*"
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-settings-test-setting 1000}}})))
+ (testing "value should not have been updated"
(is (= "wow"
(config-from-file-settings-test-setting)))))
- (testing "Wrong value type should throw an error."
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-settings-test-setting 1000}}}]
-
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"Invalid input: .*"
- (advanced-config.file/initialize!)))
- (testing "value should not have been updated"
- (is (= "wow"
- (config-from-file-settings-test-setting))))))
(testing "Invalid Setting (does not exist) should log a warning and continue."
- (binding [advanced-config.file/*config* {:version 1
- :config {:settings {:config-from-file-settings-test-setting-FAKE 1000}}}]
- (mt/with-log-messages-for-level [messages [metabase-enterprise.advanced-config.file.settings :warn]]
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (=? [{:level :warn, :message (u/colorize :yellow "Ignoring unknown setting in config: config-from-file-settings-test-setting-FAKE.")}]
- (messages))))))))
+ (mt/with-log-messages-for-level [messages [metabase-enterprise.advanced-config.file.settings :warn]]
+ (is (= :ok
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:settings {:config-from-file-settings-test-setting-FAKE 1000}}})))
+ (is (=? [{:level :warn, :message (u/colorize :yellow "Ignoring unknown setting in config: config-from-file-settings-test-setting-FAKE.")}]
+ (messages)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
index f8a5fcf5cc8..0a1713f85a2 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
@@ -16,53 +16,53 @@
(deftest init-from-config-file-test
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Era"
- :password "2cans"
- :login_attributes {"a" 1}}]}}]
- (testing "Create a User if it does not already exist"
+ (testing "Create a User if it does not already exist"
+ (is (= :ok
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Era"
+ :password "2cans"
+ :login_attributes {"a" 1}}]}})))
+ (is (partial= {:first_name "Cam"
+ :last_name "Era"
+ :login_attributes {"a" "1"}}
+ (t2/select-one [:model/User :first_name :last_name :email :login_attributes]
+ :email "[email protected]")))
+ (is (= 1
+ (t2/count :model/User :email "[email protected]"))))
+
+ (testing "upsert if User already exists, with merged login attributes"
+ (let [hashed-password (fn [] (t2/select-one-fn :password :model/User :email "[email protected]"))
+ salt (fn [] (t2/select-one-fn :password_salt :model/User :email "[email protected]"))
+ original-hashed-password (hashed-password)]
(is (= :ok
- (advanced-config.file/initialize!)))
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Saul"
+ :password "2cans"
+ :login_attributes {"b" 2}}]}})))
+ (is (= 1
+ (t2/count :model/User :email "[email protected]")))
(is (partial= {:first_name "Cam"
- :last_name "Era"
+ :last_name "Saul"
- :login_attributes {"a" "1"}}
+ :login_attributes {"a" "1" "b" "2"}}
(t2/select-one [:model/User :first_name :last_name :email :login_attributes]
:email "[email protected]")))
- (is (= 1
- (t2/count :model/User :email "[email protected]"))))
-
- (testing "upsert if User already exists, with merged login attributes"
- (let [hashed-password (fn [] (t2/select-one-fn :password :model/User :email "[email protected]"))
- salt (fn [] (t2/select-one-fn :password_salt :model/User :email "[email protected]"))
- original-hashed-password (hashed-password)]
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Saul"
- :password "2cans"
- :login_attributes {"b" 2}}]}}]
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (= 1
- (t2/count :model/User :email "[email protected]")))
- (is (partial= {:first_name "Cam"
- :last_name "Saul"
- :login_attributes {"a" "1" "b" "2"}}
- (t2/select-one [:model/User :first_name :last_name :email :login_attributes]
- :email "[email protected]")))
- (testing "Password should be hashed, but it should be a NEW HASH"
- (let [new-hashed-password (hashed-password)]
- (is (not= original-hashed-password
- new-hashed-password))
- (testing "Password should not be saved as plaintext"
- (is (not= "2cans"
- new-hashed-password)))
- (testing "Password should work correctly"
- (is (u.password/verify-password "2cans" (salt) new-hashed-password)))))))))
+ (testing "Password should be hashed, but it should be a NEW HASH"
+ (let [new-hashed-password (hashed-password)]
+ (is (not= original-hashed-password
+ new-hashed-password))
+ (testing "Password should not be saved as plaintext"
+ (is (not= "2cans"
+ new-hashed-password)))
+ (testing "Password should work correctly"
+ (is (u.password/verify-password "2cans" (salt) new-hashed-password)))))))
(finally
(t2/delete! :model/User :email "[email protected]"))))
@@ -70,53 +70,54 @@
(testing "If this is the first user being created, always make the user a superuser regardless of what is specified"
(try
(testing "Create the first User"
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Era"
- :password "2cans"
- :is_superuser false}]}}]
- (with-redefs [setup/has-user-setup (constantly false)]
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (partial= {:first_name "Cam"
- :last_name "Era"
- :is_superuser true}
- (t2/select-one :model/User :email "[email protected]")))
- (is (= 1
- (t2/count :model/User :email "[email protected]"))))))
- (testing "Create the another User, DO NOT force them to be an admin"
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Saul"
- :password "2cans"
- :is_superuser false}]}}]
+ (with-redefs [setup/has-user-setup (constantly false)]
(is (= :ok
- (advanced-config.file/initialize!)))
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Era"
+ :password "2cans"
+ :is_superuser false}]}})))
(is (partial= {:first_name "Cam"
- :last_name "Saul"
- :is_superuser false}
- (t2/select-one :model/User :email "[email protected]")))
+ :last_name "Era"
+ :is_superuser true}
+ (t2/select-one :model/User :email "[email protected]")))
(is (= 1
- (t2/count :model/User :email "[email protected]")))))
+ (t2/count :model/User :email "[email protected]")))))
+ (testing "Create the another User, DO NOT force them to be an admin"
+ (is (= :ok
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Saul"
+ :password "2cans"
+ :is_superuser false}]}})))
+ (is (partial= {:first_name "Cam"
+ :last_name "Saul"
+ :is_superuser false}
+ (t2/select-one :model/User :email "[email protected]")))
+ (is (= 1
+ (t2/count :model/User :email "[email protected]"))))
(finally (t2/delete! :model/User :email [:in #{"[email protected]"
(deftest init-from-config-file-env-var-for-password-test
(testing "Ensure that we can set User password using {{env ...}} templates"
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Era"
- :password "{{env USER_PASSWORD}}"}]}}
- advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :user-password "1234cans")]
+ (binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :user-password "1234cans")]
(testing "Create a User if it does not already exist"
(is (= :ok
- (advanced-config.file/initialize!)))
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Era"
+ :password "{{env USER_PASSWORD}}"}]}}
+ {:expand-templates? true})))
(let [user (t2/select-one [:model/User :first_name :last_name :email :password_salt :password]
:email "[email protected]")]
(is (partial= {:first_name "Cam"
@@ -131,9 +132,8 @@
(are [user error-pattern] (thrown-with-msg?
clojure.lang.ExceptionInfo
error-pattern
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [user]}}]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config {:version 1
+ :config {:users [user]}}))
;; missing email
{:first_name "Cam"
:last_name "Era"
@@ -161,17 +161,15 @@
(deftest email-case-irrelevant-test
(testing "Using any case in email still works #62894"
(try
- (binding [advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Era"
- :password "2cans"
- :login_attributes {"a" 1}}]}}]
- (is (= :ok
- (advanced-config.file/initialize!)))
+ (let [config {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Era"
+ :password "2cans"
+ :login_attributes {"a" 1}}]}}]
+ (is (= :ok (advanced-config.file/initialize! config)))
(testing "It should not fail with 'duplicate'"
- (is (= :ok
- (advanced-config.file/initialize!)))))
+ (is (= :ok (advanced-config.file/initialize! config)))))
(finally
(t2/delete! :model/User :email "[email protected]")
(t2/delete! :model/User :email "[email protected]")))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/workspace_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/workspace_test.clj
index 4fd55bc9602..5836d37c870 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/workspace_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/workspace_test.clj
@@ -6,19 +6,21 @@
[metabase-enterprise.advanced-config.file :as advanced-config.file]
[metabase-enterprise.advanced-config.file.workspace :as advanced-config.file.workspace]
[metabase-enterprise.workspaces.core :as ws]
- [metabase-enterprise.workspaces.test-util :as workspaces.tu]
[metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
[metabase.util.yaml :as yaml])
(:import
(clojure.lang ExceptionInfo)))
-(def default-workspace-instance-config nil)
+(use-fixtures :once (fixtures/initialize :db))
(use-fixtures :each
(fn [thunk]
- (binding [advanced-config.file/*supported-versions* {:min 1, :max 1}
- ws/*workspace-instance-config* (atom default-workspace-instance-config)]
- (thunk))))
+ (binding [advanced-config.file/*supported-versions* {:min 1, :max 1}]
+ (try
+ (thunk)
+ (finally
+ (ws/clear-instance-workspace!))))))
(defn- load-fixture-by-driver [driver]
(-> (str "metabase_enterprise/workspaces/resources/workspace_config_" (name driver) ".yml")
@@ -54,7 +56,7 @@
(is (= 1 (count dbs)))
(let [[_db-name wsd] (first dbs)]
(is (= ["public"] (:input_schemas wsd)))
- (is (= "mb__isolation_44490_1933" (:output_namespace wsd)))))))))
+ (is (= {:schema "mb__isolation_44490_1933"} (:output wsd)))))))))
(deftest non-blank-string-spec-test
(testing "::non-blank-string rejects nil, non-strings, and whitespace-only strings,
@@ -68,14 +70,14 @@
(str "must accept " (pr-str v)))))))
(deftest apply-workspace-section-populates-atom-test
- (testing "applying the :workspace section stores parsed config in the in-process atom keyed by db-id"
+ (testing "applying the :workspace section stores parsed config in the instance-workspace setting keyed by db-id"
(mt/with-empty-h2-app-db!
(mt/with-temp [:model/Database {db-id :id} {:name "ws-test-db" :engine :postgres}]
(let [section (workspace-section "ws-test-db")
{:keys [workspace-name database-count]} (advanced-config.file.workspace/apply-workspace-section! section)]
(is (= "New workspace" workspace-name))
(is (= 1 database-count))
- (testing "atom holds the parsed config"
+ (testing "setting holds the parsed config"
(let [stored (ws/instance-workspace)]
(is (= "New workspace" (:name stored)))
(is (= ["public"]
@@ -84,15 +86,15 @@
(get-in stored [:databases db-id :output]))))))))))
(deftest re-apply-replaces-atom-test
- (testing "re-applying with a different config replaces the atom — no mismatch detection, file is the truth"
+ (testing "re-applying with a different config replaces the setting — no mismatch detection, file is the truth"
(mt/with-empty-h2-app-db!
(mt/with-temp [:model/Database _ {:name "ws-test-db" :engine :postgres}
:model/Database _ {:name "ws-test-db-2" :engine :postgres}]
(let [section-1 (workspace-section "ws-test-db")
section-2 (assoc section-1
:name "Renamed Workspace"
- :databases {:ws-test-db-2 {:input_schemas ["public"]
- :output_namespace "different_schema"}})]
+ :databases {:ws-test-db-2 {:input_schemas ["public"]
+ :output {:schema "different_schema"}}})]
(advanced-config.file.workspace/apply-workspace-section! section-1)
(is (= "New workspace" (:name (ws/instance-workspace))))
(advanced-config.file.workspace/apply-workspace-section! section-2)
@@ -100,7 +102,7 @@
(is (= 1 (count (:databases (ws/instance-workspace)))))
(is (= {:schema "different_schema"}
(->> (ws/instance-workspace) :databases vals first :output))
- "atom reflects the new config, not the old one"))))))
+ "setting reflects the new config, not the old one"))))))
(deftest unknown-database-name-throws-test
(testing "referencing a database that doesn't exist in app-db throws ex-info"
@@ -121,128 +123,35 @@
(deftest db-workspace-namespace-returns-nil-when-no-load-test
(testing "without a config.yml load, db-workspace-namespace returns nil — manager-side rows are not consulted"
- ;; The atom is cleared in the use-fixtures :each tear-down, so this confirms
- ;; the read truly comes from the atom and not from any leftover rows.
+ ;; The setting is cleared in the use-fixtures :each tear-down, so this confirms
+ ;; the read truly comes from the setting and not from any leftover rows.
(mt/with-empty-h2-app-db!
(mt/with-temp [:model/Database {db-id :id} {:name "ws-test-db" :engine :postgres}]
(is (nil? (ws/db-workspace-namespace db-id)))))))
-(deftest oss-readable-no-premium-token-test
- (testing "the :workspace section loads on instances without the :config-text-file premium feature"
+(deftest oss-rejects-workspace-section-without-premium-token-test
+ (testing "OSS instances need the :config-text-file token to load a :workspace section (no special bring-up carve-out)"
(mt/with-empty-h2-app-db!
(mt/with-premium-features #{}
- (mt/with-temp [:model/Database {db-id :id} {:name "ws-test-db" :engine :postgres}]
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:workspace (workspace-section "ws-test-db")}}]
- (is (= :ok (advanced-config.file/initialize!)))
- (is (some? (ws/instance-workspace))
- "atom is populated even without :config-text-file token")
- (is (= {:schema "mb__isolation_44490_1933"} (ws/db-workspace-namespace db-id)))))))))
-
-(deftest oss-rejects-config-without-workspace-section-test
- (testing "OSS instance still gets the premium-token error when :workspace is absent"
- (mt/with-empty-h2-app-db!
- (mt/with-premium-features #{}
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:users [{:first_name "X" :last_name "Y"
- :email "[email protected]" :password "pw"}]}}]
+ (mt/with-temp [:model/Database _ {:name "ws-test-db" :engine :postgres}]
(is (thrown-with-msg?
ExceptionInfo
#"Premium token with the :config-text-file feature"
- (advanced-config.file/initialize!))
- "without :workspace, OSS still requires the premium token"))))))
-
-(deftest workspace-bring-up-opens-gate-for-other-sections-test
- (testing "presence of :workspace lets sibling sections (:databases, :users, :api-keys) load on OSS"
- (mt/with-empty-h2-app-db!
- (mt/with-premium-features #{}
- (mt/with-temp [:model/Database _ {:name "sibling-db"}]
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:users [{:first_name "Bring"
- :last_name "Up"
- :password "password1"}]
- :workspace (workspace-section "sibling-db")}}]
- (is (= :ok (advanced-config.file/initialize!)))
- (is (some? (ws/instance-workspace))
- ":workspace section ran")))))))
-
-(defn- try-initialize!
- "Run `initialize!` and report whether it returned `:ok` cleanly. Catches every
- Throwable so the OSS-bypass attack tests below can ask 'did anything block
- this?' without caring which layer (spec validation or the premium-token gate)
- did the blocking — both count as defense."
- []
- (try
- (= :ok (advanced-config.file/initialize!))
- (catch Throwable _
- false)))
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:workspace (workspace-section "ws-test-db")}}))))))))
-(deftest invalid-workspace-section-does-not-open-gate-test
- (testing "an empty or malformed :workspace section does NOT let the rest of the file load on OSS"
+(deftest oss-rejects-non-settings-sections-without-premium-token-test
+ (testing "OSS instances always need the :config-text-file token for non-:settings sections"
(mt/with-empty-h2-app-db!
(mt/with-premium-features #{}
- (testing "empty workspace map"
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:users [{:first_name "X" :last_name "Y"
- :email "[email protected]" :password "pw"}]
- :workspace {}}}]
- (is (false? (try-initialize!))
- "empty :workspace doesn't unlock the gate")))
- (testing "workspace missing :databases"
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:users [{:first_name "X" :last_name "Y"
- :email "[email protected]" :password "pw"}]
- :workspace {:name "Just a name"}}}]
- (is (false? (try-initialize!)))))
- (testing "workspace with empty :databases map"
- (binding [advanced-config.file/*config*
- {:version 1
- :config {:users [{:first_name "X" :last_name "Y"
- :email "[email protected]" :password "pw"}]
- :workspace {:name "n" :databases {}}}}]
- (is (false? (try-initialize!)))))))))
-
-(deftest valid-workspace-section?-test
- (testing "valid-workspace-section? matches the spec used by the gate"
- (testing "structurally-valid sections"
- (is (true? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws" :databases {:db1 {:input_schemas ["s1"]
- :output_namespace "out"}}}))
- "minimal: single schema string on input, output namespace is a single string")
- (is (true? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws" :databases {:db1 {:input_schemas ["PUBLIC" "ANALYTICS"]
- :output_namespace "WS_ALICE"}}}))
- "multiple input schemas allowed"))
- (testing "structural rejection"
- (is (false? (advanced-config.file.workspace/valid-workspace-section? {}))
- "empty map is invalid")
- (is (false? (advanced-config.file.workspace/valid-workspace-section? {:name "ws"}))
- ":databases is required")
- (is (false? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws" :databases {}}))
- "empty :databases map is invalid")
- (is (false? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws"
- :databases {:db1 {:input_schemas []
- :output_namespace "out"}}}))
- "empty :input_schemas is invalid - need at least one input schema"))
- (testing "schema-string rejection"
- (is (false? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws"
- :databases {:db1 {:input_schemas [""]
- :output_namespace "out"}}}))
- "empty-string in :input_schemas is invalid")
- (is (false? (advanced-config.file.workspace/valid-workspace-section?
- {:name "ws"
- :databases {:db1 {:input_schemas ["s1"]
- :output_namespace ""}}}))
- "empty-string :output_namespace is invalid"))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"Premium token with the :config-text-file feature"
+ (advanced-config.file/initialize!
+ {:version 1
+ :config {:users [{:first_name "X" :last_name "Y"
+ :email "[email protected]" :password "pw"}]}})))))))
;;; ----------------------------------------- per-driver shapes -----------------------------------------
;;;
@@ -250,35 +159,25 @@
;;; without modification.
(deftest mysql-cardinality-upgrade-section-test
- (testing "MySQL workspace: only `:db` slot is populated in the atom (no schema layer)"
- (let [section {:name "ws"
- :databases {:mysql-prod {:input_schemas ["prod_db"]
- :output_namespace "ws_alice"}}}]
- (is (true? (advanced-config.file.workspace/valid-workspace-section? section))
- "MySQL workspace passes validation"))
+ (testing "MySQL workspace: only `:db` slot is populated in the setting (no schema layer)"
(testing "loader stores MySQL output namespace in the :db slot"
(mt/with-empty-h2-app-db!
(mt/with-temp [:model/Database {db-id :id} {:name "mysql-prod" :engine :mysql :details {:db "prod_db"}}]
(advanced-config.file.workspace/apply-workspace-section!
{:name "ws"
- :databases {:mysql-prod {:input_schemas ["prod_db"]
- :output_namespace "ws_alice"}}})
+ :databases {:mysql-prod {:input_schemas ["prod_db"]
+ :output {:db "ws_alice"}}}})
(is (= {:db "ws_alice"} (ws/db-workspace-namespace db-id))))))))
(deftest bigquery-3-slot-section-test
- (testing "BigQuery workspace: project from details, dataset from output_namespace"
- ;; `apply-workspace-section!` -> `expand-output` -> `engine-namespace-positions`
- ;; -> `driver/qualified-name-components` triggers a driver-load. On the default
- ;; Enterprise classpath BigQuery isn't loaded; skip the round-trip half of this
- ;; test when the driver isn't on the test classpath.
- (when (workspaces.tu/driver-loadable? :bigquery-cloud-sdk)
- (mt/with-empty-h2-app-db!
- (mt/with-temp [:model/Database {db-id :id} {:name "bq-prod" :engine :bigquery-cloud-sdk :details {:project-id "metabase-prod"}}]
- (advanced-config.file.workspace/apply-workspace-section!
- {:name "ws"
- :databases {:bq-prod {:input_schemas ["core"]
- :output_namespace "ws_alice"}}})
- (is (= {:db "metabase-prod" :schema "ws_alice"} (ws/db-workspace-namespace db-id))))))))
+ (testing "BigQuery workspace: project + dataset in the :output map"
+ (mt/with-empty-h2-app-db!
+ (mt/with-temp [:model/Database {db-id :id} {:name "bq-prod" :engine :bigquery-cloud-sdk :details {:project-id "metabase-prod"}}]
+ (advanced-config.file.workspace/apply-workspace-section!
+ {:name "ws"
+ :databases {:bq-prod {:input_schemas ["core"]
+ :output {:db "metabase-prod" :schema "ws_alice"}}}})
+ (is (= {:db "metabase-prod" :schema "ws_alice"} (ws/db-workspace-namespace db-id)))))))
;;; ----------------------------------------- per-driver YAML fixtures -----------------------------------------
;;;
@@ -289,7 +188,7 @@
;;;
;;; - the YAML parses
;;; - the `:workspace` section validates against the spec
-;;; - the loader round-trips it into the atom with the per-driver expected
+;;; - the loader round-trips it into the setting with the per-driver expected
;;; output namespace
;;;
;;; If a driver's wire format drifts, the corresponding fixture and this test
@@ -297,47 +196,39 @@
(def ^:private per-driver-fixture-expectations
"Per-driver fixture metadata: db-name + engine + connection details from the fixture,
- the wire-shape `:input_schemas`, the wire-shape `:output_namespace`, and the
- expanded `:output` map the atom should hold after loading. The expanded `:output`
- reflects each engine's catalog source — `:db` comes from `Database.details` for
- 3-slot drivers, `nil` for 2-slot drivers; the schema slot holds the
- `output_namespace` string (or lands in `:db` for MySQL)."
- {:postgres {:db-name "test-data (postgres)"
- :engine :postgres
- :details {}
- :input_schemas ["public"]
- :output_namespace "mb__isolation_44490_1933"
- :expanded-output {:schema "mb__isolation_44490_1933"}}
- :redshift {:db-name "test-data (redshift)"
- :engine :redshift
- :details {}
- :input_schemas ["public"]
- :output_namespace "mb__isolation_44490_1933"
- :expanded-output {:schema "mb__isolation_44490_1933"}}
- :mysql {:db-name "test-data (mysql)"
- :engine :mysql
- :details {:db "prod_db"}
- :input_schemas ["prod_db"]
- :output_namespace "ws_alice"
- :expanded-output {:db "ws_alice"}}
- :clickhouse {:db-name "test-data (clickhouse)"
- :engine :clickhouse
- :details {}
- :input_schemas ["prod_events"]
- :output_namespace "ws_alice"
- :expanded-output {:schema "ws_alice"}}
- :sqlserver {:db-name "test-data (sqlserver)"
- :engine :sqlserver
- :details {:db "AnalyticsDB"}
- :input_schemas ["dbo"]
- :output_namespace "ws_alice"
- :expanded-output {:db "AnalyticsDB" :schema "ws_alice"}}
- :bigquery {:db-name "test-data (bigquery)"
- :engine :bigquery-cloud-sdk
- :details {:project-id "metabase-prod"}
- :input_schemas ["core"]
- :output_namespace "ws_alice"
- :expanded-output {:db "metabase-prod" :schema "ws_alice"}}})
+ the wire-shape `:input_schemas`, and the `:output` map (already expanded in the
+ YAML since `workspaces.config/build-workspace-config` emits the runtime shape
+ directly)."
+ {:postgres {:db-name "test-data (postgres)"
+ :engine :postgres
+ :details {}
+ :input_schemas ["public"]
+ :output {:schema "mb__isolation_44490_1933"}}
+ :redshift {:db-name "test-data (redshift)"
+ :engine :redshift
+ :details {}
+ :input_schemas ["public"]
+ :output {:schema "mb__isolation_44490_1933"}}
+ :mysql {:db-name "test-data (mysql)"
+ :engine :mysql
+ :details {:db "prod_db"}
+ :input_schemas ["prod_db"]
+ :output {:db "ws_alice"}}
+ :clickhouse {:db-name "test-data (clickhouse)"
+ :engine :clickhouse
+ :details {}
+ :input_schemas ["prod_events"]
+ :output {:schema "ws_alice"}}
+ :sqlserver {:db-name "test-data (sqlserver)"
+ :engine :sqlserver
+ :details {:db "AnalyticsDB"}
+ :input_schemas ["dbo"]
+ :output {:db "AnalyticsDB" :schema "ws_alice"}}
+ :bigquery {:db-name "test-data (bigquery)"
+ :engine :bigquery-cloud-sdk
+ :details {:project-id "metabase-prod"}
+ :input_schemas ["core"]
+ :output {:db "metabase-prod" :schema "ws_alice"}}})
(deftest per-driver-fixtures-parse-and-validate-test
(testing "Each per-driver fixture YAML parses, has the expected workspace section, and round-trips through the loader"
@@ -351,22 +242,16 @@
(is (= "New workspace" (:name section)))
(is (= (:input_schemas expectations) (:input_schemas wsd))
(str driver " input_schemas matches expectation"))
- (is (= (:output_namespace expectations) (:output_namespace wsd))
- (str driver " output_namespace matches expectation")))
- (testing "validates against the workspace spec"
- (is (true? (advanced-config.file.workspace/valid-workspace-section? section))
+ (is (= (:output expectations) (:output wsd))
+ (str driver " :output matches expectation")))
+ (testing "validates against the workspace section spec"
+ (is (true? (s/valid? :metabase-enterprise.advanced-config.file.workspace/config-file-spec section))
(str driver " fixture must satisfy the section spec")))
- (testing "round-trips through apply-workspace-section! into the atom"
- ;; The round-trip step requires the driver to be loadable because
- ;; `apply-workspace-section!` -> `expand-output` -> `engine-namespace-positions`
- ;; -> `driver/qualified-name-components` triggers driver-load. Skip drivers
- ;; absent from the current classpath (e.g. BigQuery on the
- ;; default Enterprise OSS run).
- (when (workspaces.tu/driver-loadable? (:engine expectations))
- (mt/with-empty-h2-app-db!
- (mt/with-temp [:model/Database {db-id :id} {:name (:db-name expectations)
- :engine (:engine expectations)
- :details (:details expectations)}]
- (advanced-config.file.workspace/apply-workspace-section! section)
- (is (= (:expanded-output expectations) (ws/db-workspace-namespace db-id))
- (str driver " atom output matches fixture")))))))))))
+ (testing "round-trips through apply-workspace-section! into the setting"
+ (mt/with-empty-h2-app-db!
+ (mt/with-temp [:model/Database {db-id :id} {:name (:db-name expectations)
+ :engine (:engine expectations)
+ :details (:details expectations)}]
+ (advanced-config.file.workspace/apply-workspace-section! section)
+ (is (= (:output expectations) (ws/db-workspace-namespace db-id))
+ (str driver " setting output matches fixture"))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file_test.clj
index 8053cf81031..52985704d84 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file_test.clj
@@ -28,47 +28,35 @@
(mt/with-temp-file [filename "temp-config-file.yml"]
(spit filename (yaml/generate-string mock-yaml))
(binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :mb-config-file-path filename)]
- (is (= {:version 1
- :config {:settings {:my-setting "abc123"}}}
- (#'advanced-config.file/config)))))))
-
-(deftest ^:parallel config-test-2
- (testing "Support overriding config with dynamic var for mocking purposes"
- (binding [advanced-config.file/*config* mock-yaml]
- (is (= {:version 1
- :config {:settings {:my-setting "abc123"}}}
- (#'advanced-config.file/config))))))
+ (is (= mock-yaml
+ (#'advanced-config.file/config-from-disk)))))))
(deftest ^:parallel validate-config-test
(testing "Config should throw an error"
(testing "if it is not a map"
- (binding [advanced-config.file/*config* [1 2 3 4]]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- (re-quote "failed: map?")
- (#'advanced-config.file/config)))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ (re-quote "failed: map?")
+ (#'advanced-config.file/config [1 2 3 4]))))
(testing "if version"
(testing "is not included"
- (binding [advanced-config.file/*config* {:config {:settings {}}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- (re-quote "failed: (contains? % :version)")
- (#'advanced-config.file/config)))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ (re-quote "failed: (contains? % :version)")
+ (#'advanced-config.file/config {:config {:settings {}}}))))
(testing "is unsupported"
(testing "because it is too old"
- (binding [advanced-config.file/*supported-versions* {:min 2.0, :max 3.0}
- advanced-config.file/*config* {:version 1.0, :config {}}]
+ (binding [advanced-config.file/*supported-versions* {:min 2.0, :max 3.0}]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
(re-quote "failed: supported-version?")
- (#'advanced-config.file/config)))))
+ (#'advanced-config.file/config {:version 1.0, :config {}})))))
(testing "because it is too new"
- (binding [advanced-config.file/*supported-versions* {:min 2.0, :max 3.0}
- advanced-config.file/*config* {:version 4.0, :config {}}]
+ (binding [advanced-config.file/*supported-versions* {:min 2.0, :max 3.0}]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
(re-quote "failed: supported-version?")
- (#'advanced-config.file/config)))))))))
+ (#'advanced-config.file/config {:version 4.0, :config {}})))))))))
(defn- mock-config-with-setting [s]
{:version 1.0, :config {:settings {:my-setting s}}})
@@ -76,8 +64,7 @@
(deftest ^:parallel expand-template-forms-test
(testing "Ignore single curly brackets, or brackets with spaces between them"
(are [s] (= (mock-config-with-setting s)
- (binding [advanced-config.file/*config* (mock-config-with-setting s)]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config (mock-config-with-setting s) {:expand-templates? true}))
"{}}"
"{}}"
"{ {}}")))
@@ -85,8 +72,7 @@
(deftest ^:parallel literal-value-test
(testing "Can specify literal values with {{{'s"
(are [input output] (= (mock-config-with-setting output)
- (binding [advanced-config.file/*config* (mock-config-with-setting input)]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config (mock-config-with-setting input) {:expand-templates? true}))
"{{{asdf}}}" "asdf"
"{{{ asdf }}}" "asdf"
"{{{ {{ asdf }} }}}" "{{ asdf }}"
@@ -97,8 +83,7 @@
(are [template error-pattern] (thrown-with-msg?
clojure.lang.ExceptionInfo
error-pattern
- (binding [advanced-config.file/*config* (mock-config-with-setting template)]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config (mock-config-with-setting template) {:expand-templates? true}))
;; {{ without a corresponding }}
"{{}" (re-quote "Invalid query: found '[[' or '{{' with no matching ']]' or '}}'")
"{{} }" (re-quote "Invalid query: found '[[' or '{{' with no matching ']]' or '}}'")
@@ -111,36 +96,30 @@
(deftest ^:parallel recursive-template-form-expansion-test
(testing "Recursive expansion is unsupported, for now."
- (binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :x "{{env Y}}", :y "Y")
- advanced-config.file/*config* (mock-config-with-setting "{{env X}}")]
+ (binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :x "{{env Y}}", :y "Y")]
(is (= (mock-config-with-setting "{{env Y}}")
- (#'advanced-config.file/config))))))
+ (#'advanced-config.file/config (mock-config-with-setting "{{env X}}") {:expand-templates? true}))))))
(deftest ^:parallel expand-template-env-var-values-test
(testing "env var values"
(binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :config-file-bird-name "Parrot Hilton")]
(testing "Nothing weird"
- (binding [advanced-config.file/*config* (mock-config-with-setting "{{env CONFIG_FILE_BIRD_NAME}}")]
- (is (= (mock-config-with-setting "Parrot Hilton")
- (#'advanced-config.file/config)))))
+ (is (= (mock-config-with-setting "Parrot Hilton")
+ (#'advanced-config.file/config (mock-config-with-setting "{{env CONFIG_FILE_BIRD_NAME}}") {:expand-templates? true}))))
(testing "Should handle multiple templates in one string"
- (binding [advanced-config.file/*config* (mock-config-with-setting "{{env CONFIG_FILE_BIRD_NAME}}-{{env CONFIG_FILE_BIRD_NAME}}")]
- (is (= (mock-config-with-setting "Parrot Hilton-Parrot Hilton")
- (#'advanced-config.file/config)))))
+ (is (= (mock-config-with-setting "Parrot Hilton-Parrot Hilton")
+ (#'advanced-config.file/config (mock-config-with-setting "{{env CONFIG_FILE_BIRD_NAME}}-{{env CONFIG_FILE_BIRD_NAME}}") {:expand-templates? true}))))
(testing "Ignore whitespace inside the template brackets"
- (binding [advanced-config.file/*config* (mock-config-with-setting "{{ env CONFIG_FILE_BIRD_NAME }}")]
- (is (= (mock-config-with-setting "Parrot Hilton")
- (#'advanced-config.file/config)))))
+ (is (= (mock-config-with-setting "Parrot Hilton")
+ (#'advanced-config.file/config (mock-config-with-setting "{{ env CONFIG_FILE_BIRD_NAME }}") {:expand-templates? true}))))
(testing "Ignore excess brackets"
(are [template expected] (= (mock-config-with-setting expected)
- (binding [advanced-config.file/*config* (mock-config-with-setting template)]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config (mock-config-with-setting template) {:expand-templates? true}))
"{{{env CONFIG_FILE_BIRD_NAME}}" "{Parrot Hilton"
"{{env CONFIG_FILE_BIRD_NAME}}}" "Parrot Hilton}"))
(testing "handle lisp-case/snake-case and case variations"
- (binding [advanced-config.file/*config* (mock-config-with-setting "{{env config-file-bird-name}}")]
- (is (= (mock-config-with-setting "Parrot Hilton")
- (#'advanced-config.file/config))))))))
+ (is (= (mock-config-with-setting "Parrot Hilton")
+ (#'advanced-config.file/config (mock-config-with-setting "{{env config-file-bird-name}}") {:expand-templates? true})))))))
(deftest ^:parallel expand-template-env-var-values-validation-test
(testing "(config) should walk the config map and expand {{template}} forms"
@@ -149,8 +128,7 @@
(are [template error-pattern] (thrown-with-msg?
clojure.lang.ExceptionInfo
error-pattern
- (binding [advanced-config.file/*config* (mock-config-with-setting template)]
- (#'advanced-config.file/config)))
+ (#'advanced-config.file/config (mock-config-with-setting template) {:expand-templates? true}))
;; missing env var name
"{{env}}" #"Insufficient input"
;; too many args
@@ -162,71 +140,63 @@
(testing "[[optional {{template}}]] values"
(binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :my-sensitive-password "~~~SeCrEt123~~~")]
(testing "env var exists"
- (binding [advanced-config.file/*config* (mock-config-with-setting "[[{{env MY_SENSITIVE_PASSWORD}}]]")]
- (is (= (mock-config-with-setting "~~~SeCrEt123~~~")
- (#'advanced-config.file/config))))
- (binding [advanced-config.file/*config* (mock-config-with-setting "password__[[{{env MY_SENSITIVE_PASSWORD}}]]")]
- (is (= (mock-config-with-setting "password__~~~SeCrEt123~~~")
- (#'advanced-config.file/config))))
+ (is (= (mock-config-with-setting "~~~SeCrEt123~~~")
+ (#'advanced-config.file/config (mock-config-with-setting "[[{{env MY_SENSITIVE_PASSWORD}}]]") {:expand-templates? true})))
+ (is (= (mock-config-with-setting "password__~~~SeCrEt123~~~")
+ (#'advanced-config.file/config (mock-config-with-setting "password__[[{{env MY_SENSITIVE_PASSWORD}}]]") {:expand-templates? true})))
(testing "with text inside optional brackets before/after the templated part"
- (binding [advanced-config.file/*config* (mock-config-with-setting "[[before__{{env MY_SENSITIVE_PASSWORD}}__after]]")]
- (is (= (mock-config-with-setting "before__~~~SeCrEt123~~~__after")
- (#'advanced-config.file/config))))))
+ (is (= (mock-config-with-setting "before__~~~SeCrEt123~~~__after")
+ (#'advanced-config.file/config (mock-config-with-setting "[[before__{{env MY_SENSITIVE_PASSWORD}}__after]]") {:expand-templates? true})))))
(testing "env var does not exist"
- (binding [advanced-config.file/*config* (mock-config-with-setting "[[{{env MY_OTHER_SENSITIVE_PASSWORD}}]]")]
- (is (= (mock-config-with-setting "")
- (#'advanced-config.file/config))))
- (binding [advanced-config.file/*config* (mock-config-with-setting "password__[[{{env MY_OTHER_SENSITIVE_PASSWORD}}]]")]
- (is (= (mock-config-with-setting "password__")
- (#'advanced-config.file/config))))
+ (is (= (mock-config-with-setting "")
+ (#'advanced-config.file/config (mock-config-with-setting "[[{{env MY_OTHER_SENSITIVE_PASSWORD}}]]") {:expand-templates? true})))
+ (is (= (mock-config-with-setting "password__")
+ (#'advanced-config.file/config (mock-config-with-setting "password__[[{{env MY_OTHER_SENSITIVE_PASSWORD}}]]") {:expand-templates? true})))
(testing "with text inside optional brackets before/after the templated part"
- (binding [advanced-config.file/*config* (mock-config-with-setting "[[before__{{env MY_OTHER_SENSITIVE_PASSWORD}}__after]]")]
- (is (= (mock-config-with-setting "")
- (#'advanced-config.file/config)))))))))
+ (is (= (mock-config-with-setting "")
+ (#'advanced-config.file/config (mock-config-with-setting "[[before__{{env MY_OTHER_SENSITIVE_PASSWORD}}__after]]") {:expand-templates? true}))))))))
(deftest initialize-section-test
(testing "Ignore unknown sections"
- (binding [advanced-config.file/*config* {:version 1.0, :config {:unknown-section {}}}]
- (mt/with-log-messages-for-level [messages [metabase-enterprise.advanced-config.file.interface :warn]]
- (is (= :ok
- (advanced-config.file/initialize!)))
- (is (=? [{:level :warn, :message (u/colorize :yellow "Ignoring unknown config section :unknown-section.")}]
- (messages)))))))
+ (mt/with-log-messages-for-level [messages [metabase-enterprise.advanced-config.file.interface :warn]]
+ (is (= :ok
+ (advanced-config.file/initialize! {:version 1.0, :config {:unknown-section {}}})))
+ (is (=? [{:level :warn, :message (u/colorize :yellow "Ignoring unknown config section :unknown-section.")}]
+ (messages))))))
(deftest require-advanced-config-test
(testing "Config files should require the `:config-text-file` token feature"
(mt/with-premium-features #{}
- (binding [advanced-config.file/*config* {:version 1.0, :config {:unknown-section {}}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"Metabase config files require a Premium token with the :config-text-file feature"
- (advanced-config.file/initialize!)))))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Metabase config files require a Premium token with the :config-text-file feature"
+ (advanced-config.file/initialize! {:version 1.0, :config {:unknown-section {}}}))))))
(deftest ^:parallel error-validation-do-not-leak-env-vars-test
(testing "spec errors should not include contents of env vars -- expand templates after spec validation."
- (binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :my-sensitive-password "~~~SeCrEt123~~~")
- advanced-config.file/*config* {:version 1
- :config {:users [{:first_name "Cam"
- :last_name "Era"
- :password "{{env MY_SENSITIVE_PASSWORD}}"}]}}]
- (is (thrown?
- clojure.lang.ExceptionInfo
- (#'advanced-config.file/config)))
- (try
- (#'advanced-config.file/config)
- (catch Throwable e
- (letfn [(contains-password? [form]
- (let [seen-password? (atom false)]
- (walk/postwalk
- (fn [form]
- (when (and (string? form)
- (str/includes? form "~~~SeCrEt123~~~"))
- (reset! seen-password? true))
+ (binding [advanced-config.file/*env* (assoc @#'advanced-config.file/*env* :my-sensitive-password "~~~SeCrEt123~~~")]
+ (let [bad-config {:version 1
+ :config {:users [{:first_name "Cam"
+ :last_name "Era"
+ :password "{{env MY_SENSITIVE_PASSWORD}}"}]}}]
+ (is (thrown?
+ clojure.lang.ExceptionInfo
+ (#'advanced-config.file/config bad-config {:expand-templates? true})))
+ (try
+ (#'advanced-config.file/config bad-config {:expand-templates? true})
+ (catch Throwable e
+ (letfn [(contains-password? [form]
+ (let [seen-password? (atom false)]
+ (walk/postwalk
+ (fn [form]
+ (when (and (string? form)
+ (str/includes? form "~~~SeCrEt123~~~"))
+ (reset! seen-password? true))
+ form)
form)
- form)
- @seen-password?))]
- (is (not (contains-password? (ex-message e))))
- (is (not (contains-password? (ex-data e))))))))))
+ @seen-password?))]
+ (is (not (contains-password? (ex-message e))))
+ (is (not (contains-password? (ex-data e)))))))))))
(deftest always-init-settings-first-test
(testing "Always apply the :settings section first regardless of the order the YAML file is in."
@@ -244,8 +214,7 @@
(let [initialized-sections (atom [])]
(with-redefs [advanced-config.file.i/initialize-section! (fn [section-name _section-config]
(swap! initialized-sections conj section-name))]
- (binding [advanced-config.file/*config* {:version 1, :config config}]
- (advanced-config.file/initialize!)
- (is (= [:settings
- :users]
- @initialized-sections)))))))))
+ (advanced-config.file/initialize! {:version 1, :config config})
+ (is (= [:settings
+ :users]
+ @initialized-sections))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_instance_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_instance_test.clj
index 7a145fa3d38..7575b90d4f6 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_instance_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_instance_test.clj
@@ -11,40 +11,87 @@
(use-fixtures :once (fixtures/initialize :db))
-(defn- with-premium-feature [f]
- (mt/with-premium-features #{:workspaces}
- (f)))
-
-(use-fixtures :each with-premium-feature)
+(use-fixtures :each
+ (fn [thunk]
+ (mt/with-premium-features #{:workspaces}
+ (try
+ (thunk)
+ (finally
+ (ws/clear-instance-workspace!))))))
(deftest current-superuser-only-test
- (testing "GET /ee/workspace-instance/current requires superuser"
+ (testing "GET /ee/workspace-instance/current requires data analyst or superuser"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "ee/workspace-instance/current")))))
(deftest current-empty-test
- (testing "GET /ee/workspace-instance/current returns nil body when no workspace is loaded"
+ (testing "GET /ee/workspace-instance/current returns {:data nil} when no workspace is loaded"
(with-redefs [ws/instance-workspace (constantly nil)]
- (is (nil? (mt/user-http-request :crowberto :get 204 "ee/workspace-instance/current"))))))
+ (is (= {:data nil}
+ (mt/user-http-request :crowberto :get 200 "ee/workspace-instance/current"))))))
(deftest current-with-workspace-test
- (testing "GET /ee/workspace-instance/current returns the atom shape — name + databases map keyed by id"
+ (testing "GET /ee/workspace-instance/current returns the workspace wrapped in {:data ...}"
(with-redefs [ws/instance-workspace (constantly {:name "Current Test"
:databases {(mt/id) {:input_schemas ["PUBLIC"]
:output {:schema "ws_alice"}}}})]
- (let [result (mt/user-http-request :crowberto :get 200 "ee/workspace-instance/current")]
- (is (= "Current Test" (:name result)))
+ (let [result (mt/user-http-request :crowberto :get 200 "ee/workspace-instance/current")
+ data (:data result)]
+ (is (= "Current Test" (:name data)))
(testing "databases is a map keyed by database id with input_schemas + output"
- (is (= 1 (count (:databases result))))
- (let [databases (:databases result)
+ (is (= 1 (count (:databases data))))
+ (let [databases (:databases data)
db (or (get databases (mt/id))
(get databases (keyword (str (mt/id))))
(get databases (str (mt/id))))]
(is (= ["PUBLIC"] (:input_schemas db)))
(is (= {:schema "ws_alice"} (:output db)))))))))
+(deftest post-current-superuser-only-test
+ (testing "POST /ee/workspace-instance/current requires data analyst or superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "ee/workspace-instance/current"
+ {:name "x" :databases {}})))))
+
+(deftest post-current-round-trip-test
+ (testing "POST /ee/workspace-instance/current installs the workspace and is readable via GET"
+ (let [payload {:name "Installed via API"
+ :databases {(mt/id) {:input_schemas ["PUBLIC"]
+ :output {:schema "ws_api_install"}}}}
+ posted (mt/user-http-request :crowberto :post 200 "ee/workspace-instance/current" payload)]
+ (is (= "Installed via API" (:name posted)))
+ (testing "GET reflects the workspace just installed"
+ (let [fetched (:data (mt/user-http-request :crowberto :get 200 "ee/workspace-instance/current"))]
+ (is (= "Installed via API" (:name fetched)))
+ (is (= 1 (count (:databases fetched)))))))))
+
+(deftest delete-current-superuser-only-test
+ (testing "DELETE /ee/workspace-instance/current requires data analyst or superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 "ee/workspace-instance/current")))))
+
+(deftest delete-current-clears-workspace-test
+ (testing "DELETE /ee/workspace-instance/current clears any installed workspace"
+ (ws/set-instance-workspace! {:name "to-clear" :databases {}})
+ (is (some? (ws/instance-workspace)))
+ (mt/user-http-request :crowberto :delete 204 "ee/workspace-instance/current")
+ (is (nil? (ws/instance-workspace)))))
+
+(deftest delete-current-drops-table-remappings-test
+ (testing "DELETE /ee/workspace-instance/current drops any TableRemapping rows"
+ (mt/with-model-cleanup [:model/TableRemapping]
+ (ws/set-instance-workspace! {:name "to-clear" :databases {}})
+ (t2/insert! :model/TableRemapping {:database_id (mt/id)
+ :from_schema "public"
+ :from_table_name "orders"
+ :to_schema "mb_iso"
+ :to_table_name "orders"})
+ (is (t2/exists? :model/TableRemapping :database_id (mt/id)))
+ (mt/user-http-request :crowberto :delete 204 "ee/workspace-instance/current")
+ (is (not (t2/exists? :model/TableRemapping :database_id (mt/id)))))))
+
(deftest table-remappings-superuser-only-test
- (testing "GET /ee/workspace-instance/table-remappings requires superuser"
+ (testing "GET /ee/workspace-instance/table-remappings requires data analyst or superuser"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "ee/workspace-instance/table-remappings")))))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
index 7e6a94fb87a..344d424ba94 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
@@ -44,11 +44,11 @@
:schema-filters-type "inclusion"
:schema-filters-patterns "raw_github"}
(:details db))))))
- (testing "workspace entry uses flat input_schemas + opaque output_namespace string"
+ (testing "workspace entry uses flat input_schemas + expanded :output map"
(is (= "github" (-> cfg :config :workspace :name)))
(is (= {"Analytics Data Warehouse"
- {:input_schemas ["raw_github"]
- :output_namespace "mb_isolation_github"}}
+ {:input_schemas ["raw_github"]
+ :output {:schema "mb_isolation_github"}}}
(-> cfg :config :workspace :databases))))))))
(deftest build-workspace-config-three-slot-engine-test
@@ -69,8 +69,8 @@
:status :provisioned}]
(let [cfg (config/build-workspace-config ws-id)]
(is (= {"MSSQL DW"
- {:input_schemas ["dbo"]
- :output_namespace "ws_alice"}}
+ {:input_schemas ["dbo"]
+ :output {:db "AnalyticsDB" :schema "ws_alice"}}}
(-> cfg :config :workspace :databases))))))))
(deftest build-workspace-config-joins-multiple-input-schemas-test
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj
index f4279e861af..8703cf9e382 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj
@@ -6,8 +6,8 @@
provisions an isolation schema + workspace user via
`workspaces.provisioning/*`, builds the canonical `config.yml` map via
`workspaces.config/build-workspace-config`, round-trips it through YAML,
- binds it to `advanced-config.file/*config*`, and calls `initialize!` —
- which runs the same `:databases` and `:workspace` section loaders the
+ and passes it to `advanced-config.file/initialize!` — which runs the same
+ `:databases` and `:workspace` section loaders the
child instance uses at boot. Then it runs a transform whose target gets
rewritten to the isolation schema, and verifies that visibility from
Metabase's perspective is confined to the input schema — neither the
@@ -239,8 +239,9 @@
(vec vs))))
set)))
-;; `^:synchronized` because `ws/workspace-instance-config` is a process-wide atom;
-;; running concurrently with other workspace-mode tests would cross-pollute.
+;; `^:synchronized` because the `instance-workspace` setting is process-wide state
+;; backed by the shared test app DB; running concurrently with other workspace-mode
+;; tests would cross-pollute.
#_{:clj-kondo/ignore [:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests]}
(defn- with-redshift-describe-filter-disabled
"Redshift test infra normally filters describe-database to only return tables
@@ -257,7 +258,7 @@
#_{:clj-kondo/ignore [:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests]}
(deftest ^:synchronized workspace-full-e2e-test
(mt/test-drivers workspaces-supported-drivers
- (mt/with-premium-features #{:workspaces}
+ (mt/with-premium-features #{:workspaces :config-text-file}
;; The default test-time `db-connection-timeout-ms` is 5s. BigQuery's
;; first call through a freshly-built impersonated client (cold gRPC
;; handshake + impersonation token mint + `listDatasets`) regularly
@@ -377,15 +378,14 @@
;;| Child below |
;;+---------------------------+
- ;; --- Stage 3: bind `*config*` and run the file loader. This invokes
+ ;; --- Stage 3: feed the parsed YAML to the file loader. This invokes
;; `init-from-config-file!` for the `:databases` section (updates the
;; existing Database row with merged workspace creds + schema-filters)
;; and `apply-workspace-section!` for the `:workspace` section (resolves
- ;; db names → ids and populates `ws/workspace-instance-config`).
- (binding [advanced-config.file/*config* (yaml/parse-string yaml-str)]
- (advanced-config.file/initialize!))
- ;; Diagnostic: the loader should have populated the in-process workspace
- ;; atom and rewritten the Database row's :details to workspace-user creds.
+ ;; db names → ids and writes the `instance-workspace` setting).
+ (advanced-config.file/initialize! (yaml/parse-string yaml-str))
+ ;; Diagnostic: the loader should have written the workspace-instance
+ ;; setting and rewritten the Database row's :details to workspace-user creds.
(is (ws/workspace-mode?)
"loader did not put the instance into workspace-mode (atom not populated)")
;; The Database row's `:details` was just rewritten by the loader. Re-read
@@ -647,7 +647,7 @@
(is (= [] (filter #(= iso-tbl-schema (:schema %)) (map #(select-keys % [:schema :name]) tables)))
"no app-db Table row points at the isolation schema")))))))))
(finally
- ;; Clear the in-process workspace atom (populated by `apply-workspace-section!`
+ ;; Clear the `instance-workspace` setting (populated by `apply-workspace-section!`
;; via `initialize!` above) and tear down the WorkspaceDatabase. The
;; `:databases` initializer rewrote the `Database.details` to the workspace
;; user's creds — but `destroy-workspace-isolation!` needs admin privileges
@@ -700,7 +700,7 @@
;; source table, so it inherits that failure mode. Investigation pending; unrelated
;; to the native-SQL-rewrite hook this test was written to cover.
(mt/test-drivers #{:postgres :mysql}
- (mt/with-premium-features #{:workspaces}
+ (mt/with-premium-features #{:workspaces :config-text-file}
(testing "a native transform whose SQL references a prior MBQL transform's canonical target succeeds via the workspace SQL rewriter"
(let [admin-driver driver/*driver*
admin-db (mt/db)
@@ -726,8 +726,7 @@
(let [cfg-map (ws.config/build-workspace-config ws-id)
yaml-str (ws.config/config->yaml cfg-map)
reparsed (yaml/parse-string yaml-str)]
- (binding [advanced-config.file/*config* reparsed]
- (advanced-config.file/initialize!))
+ (advanced-config.file/initialize! reparsed)
(let [ws-db (t2/select-one :model/Database :id (:id ws-db))]
(mt/with-db ws-db
(sync/sync-database! ws-db {:scan :schema})
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/query_processor/corpus_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/query_processor/corpus_test.clj
index a21f85b2e7c..73f49839b9e 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/query_processor/corpus_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/query_processor/corpus_test.clj
@@ -242,15 +242,15 @@
(defn- fixture-wsd
"Pull the single workspace-database entry from a fixture: returns
`[<db-name-string>, <wsd-config-map>]` where wsd-config has `:input_schemas`
- and `:output_namespace`."
+ and `:output` (the already-expanded `{:db ?, :schema ?}` map)."
[section]
(let [[db-name-kw wsd] (-> section :databases first)]
[(name db-name-kw) wsd]))
(def ^:private fixture-rewriter-test-cases
- "Per-driver chain test cases. The fixture YAML carries `:input_schemas` and
- `:output_namespace`; the catalog (SQL Server/BigQuery) is pulled from
- `Database.details`. Each test case adds the engine + details needed to drive
+ "Per-driver chain test cases. The fixture YAML carries `:input_schemas` and the
+ already-expanded `:output` map; the catalog (SQL Server/BigQuery) lives
+ inside that map. Each test case adds the engine + details needed to drive
the loader's expansion path, plus the SQL the QP would emit for a
representative source table."
[{:fixture-driver :postgres
@@ -296,18 +296,11 @@
(let [section (load-fixture-section fixture-driver)
[db-name wsd] (fixture-wsd section)
first-input (first (:input_schemas wsd))
- ;; Build expected `:output` map the same way the loader does — so the
- ;; assertions below test loader fidelity end-to-end.
+ ;; The fixture's `:output` is already the expanded `{:db ?, :schema ?}`
+ ;; map (`workspaces.config/build-workspace-config` emits the runtime
+ ;; shape directly), so the loader stores it verbatim.
+ expected-output (:output wsd)
fake-db {:engine engine :details details}
- expected-output (cond-> {}
- (some #{:schema} (driver/qualified-name-components driver))
- (assoc :schema (:output_namespace wsd))
- (and (some #{:db} (driver/qualified-name-components driver))
- (some #{:schema} (driver/qualified-name-components driver)))
- (assoc :db (:db (ws/engine-namespace-positions fake-db)))
- (and (some #{:db} (driver/qualified-name-components driver))
- (not (some #{:schema} (driver/qualified-name-components driver))))
- (assoc :db (:output_namespace wsd)))
;; The from-spec handed to the rewriter must match what the driver
;; actually *emits* in SQL, which is governed by qualified-name-components.
emitted-slots (set (driver/qualified-name-components driver))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_bigquery.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_bigquery.yml
index a8ee721266b..3fd283c4df4 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_bigquery.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_bigquery.yml
@@ -25,4 +25,6 @@ config:
test-data (bigquery):
input_schemas:
- core
- output_namespace: ws_alice
+ output:
+ db: metabase-prod
+ schema: ws_alice
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_clickhouse.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_clickhouse.yml
index fe415e943d4..0f5f5e17cc3 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_clickhouse.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_clickhouse.yml
@@ -27,4 +27,5 @@ config:
test-data (clickhouse):
input_schemas:
- prod_events
- output_namespace: ws_alice
+ output:
+ schema: ws_alice
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_mysql.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_mysql.yml
index eb8fbc6b163..502415f7617 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_mysql.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_mysql.yml
@@ -28,4 +28,5 @@ config:
test-data (mysql):
input_schemas:
- prod_db
- output_namespace: ws_alice
+ output:
+ db: ws_alice
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_postgres.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_postgres.yml
index f777284eb80..eb0535c9262 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_postgres.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_postgres.yml
@@ -28,4 +28,5 @@ config:
test-data (postgres):
input_schemas:
- public
- output_namespace: mb__isolation_44490_1933
+ output:
+ schema: mb__isolation_44490_1933
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_redshift.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_redshift.yml
index cb8d0fc261f..39df7054476 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_redshift.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_redshift.yml
@@ -32,4 +32,5 @@ config:
test-data (redshift):
input_schemas:
- public
- output_namespace: mb__isolation_44490_1933
+ output:
+ schema: mb__isolation_44490_1933
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_sqlserver.yml b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_sqlserver.yml
index cdfd757c89a..8f72a8ccfe3 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_sqlserver.yml
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/resources/workspace_config_sqlserver.yml
@@ -26,4 +26,6 @@ config:
test-data (sqlserver):
input_schemas:
- dbo
- output_namespace: ws_alice
+ output:
+ db: AnalyticsDB
+ schema: ws_alice
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/settings_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/settings_test.clj
index 69153c10530..b126ab64c5f 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/settings_test.clj
@@ -2,7 +2,9 @@
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
[metabase-enterprise.workspaces.core :as ws]
- [metabase-enterprise.workspaces.settings :as ws.settings]))
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db))
(use-fixtures :each (fn [thunk]
(try
@@ -10,21 +12,21 @@
(finally
(ws/clear-instance-workspace!)))))
-(deftest has-active-workspace-false-when-atom-empty-test
- (testing "has-active-workspace is false when no :workspace section has been loaded"
+(deftest workspace-mode?-false-when-setting-empty-test
+ (testing "workspace-mode? is false when no :workspace section has been loaded"
(ws/clear-instance-workspace!)
- (is (false? (ws.settings/has-active-workspace)))))
+ (is (false? (ws/workspace-mode?)))))
-(deftest has-active-workspace-true-when-atom-populated-test
- (testing "has-active-workspace flips to true once the loader populates the in-process atom"
+(deftest workspace-mode?-true-when-setting-populated-test
+ (testing "workspace-mode? flips to true once a workspace config has been set"
(ws/clear-instance-workspace!)
- (is (false? (ws.settings/has-active-workspace)))
+ (is (false? (ws/workspace-mode?)))
(ws/set-instance-workspace! {:name "Acme" :databases {}})
- (is (true? (ws.settings/has-active-workspace)))))
+ (is (true? (ws/workspace-mode?)))))
-(deftest has-active-workspace-flips-back-to-false-on-clear-test
- (testing "has-active-workspace returns to false after clear-instance-workspace!"
+(deftest workspace-mode?-flips-back-to-false-on-clear-test
+ (testing "workspace-mode? returns to false after clear-instance-workspace!"
(ws/set-instance-workspace! {:name "Acme" :databases {}})
- (is (true? (ws.settings/has-active-workspace)))
+ (is (true? (ws/workspace-mode?)))
(ws/clear-instance-workspace!)
- (is (false? (ws.settings/has-active-workspace)))))
+ (is (false? (ws/workspace-mode?)))))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/table_remapping_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/table_remapping_test.clj
index 1a221451a3c..d20df41f72c 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/table_remapping_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/table_remapping_test.clj
@@ -28,8 +28,8 @@
(t2/select-one :model/Database db-id)))))
(defn- with-provisioned-workspace-db!
- "Set the in-process workspace atom so `db-workspace-namespace` returns
- `{:schema output-schema}` for `db-id`, run `f`, clear the atom on the way out."
+ "Set the `instance-workspace` setting so `db-workspace-namespace` returns
+ `{:schema output-schema}` for `db-id`, run `f`, clear it on the way out."
[db-id output-schema f]
(try
(ws/set-instance-workspace! {:name "table-remapping-test-ws"
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/transform_hooks_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/transform_hooks_test.clj
index c7204a2f8ed..6e2e2494aa3 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/transform_hooks_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/transform_hooks_test.clj
@@ -52,7 +52,7 @@
"add-transform-target-mapping! receives the db-id and the canonical target map verbatim")))))
(defn- with-instance-workspace-for-db!
- "Set the in-process workspace atom so that `db-workspace-namespace` returns
+ "Set the `instance-workspace` setting so that `db-workspace-namespace` returns
`{:schema output-schema}` for the test database, run `body-fn`, clear it on
the way out."
[output-schema body-fn]
diff --git a/enterprise/frontend/src/metabase-enterprise/api/advanced-config.ts b/enterprise/frontend/src/metabase-enterprise/api/advanced-config.ts
new file mode 100644
index 00000000000..d4ef243efea
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/advanced-config.ts
@@ -0,0 +1,30 @@
+import type { ApplyAdvancedConfigRequest } from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import { invalidateTags, listTag, tag } from "./tags";
+
+export const advancedConfigApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ applyAdvancedConfig: builder.mutation<void, ApplyAdvancedConfigRequest>({
+ query: ({ config }) => {
+ const formData = new FormData();
+ formData.append("config", config);
+ return {
+ method: "POST",
+ url: "/api/ee/advanced-config",
+ body: { formData },
+ formData: true,
+ fetch: true,
+ };
+ },
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [
+ tag("workspace"),
+ listTag("workspace"),
+ listTag("database"),
+ ]),
+ }),
+ }),
+});
+
+export const { useApplyAdvancedConfigMutation } = advancedConfigApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index 25fe2795414..88a90d53f05 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -1,3 +1,4 @@
+export * from "./advanced-config";
export * from "./ai-controls";
export * from "./api";
export * from "./audit-info";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/workspace-instance.ts b/enterprise/frontend/src/metabase-enterprise/api/workspace-instance.ts
index a7236bf0540..da9417bbb23 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/workspace-instance.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/workspace-instance.ts
@@ -1,8 +1,12 @@
import { provideTableRemappingListTags } from "metabase/api/tags";
-import type { TableRemapping, WorkspaceInstance } from "metabase-types/api";
+import type {
+ GetCurrentWorkspaceResponse,
+ TableRemapping,
+ WorkspaceInstance,
+} from "metabase-types/api";
import { EnterpriseApi } from "./api";
-import { tag } from "./tags";
+import { invalidateTags, listTag, tag } from "./tags";
export const workspaceInstanceApi = EnterpriseApi.injectEndpoints({
endpoints: (builder) => ({
@@ -11,8 +15,18 @@ export const workspaceInstanceApi = EnterpriseApi.injectEndpoints({
method: "GET",
url: "/api/ee/workspace-instance/current",
}),
+ transformResponse: (response: GetCurrentWorkspaceResponse) =>
+ response.data,
providesTags: [tag("workspace")],
}),
+ deleteWorkspaceInstance: builder.mutation<void, void>({
+ query: () => ({
+ method: "DELETE",
+ url: "/api/ee/workspace-instance/current",
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [tag("workspace"), listTag("workspace")]),
+ }),
listTableRemappings: builder.query<TableRemapping[], void>({
query: () => ({
method: "GET",
@@ -24,5 +38,8 @@ export const workspaceInstanceApi = EnterpriseApi.injectEndpoints({
}),
});
-export const { useGetCurrentWorkspaceQuery, useListTableRemappingsQuery } =
- workspaceInstanceApi;
+export const {
+ useGetCurrentWorkspaceQuery,
+ useDeleteWorkspaceInstanceMutation,
+ useListTableRemappingsQuery,
+} = workspaceInstanceApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.module.css b/enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/WorkspaceEmptyState.module.css
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.module.css
rename to enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/WorkspaceEmptyState.module.css
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/WorkspaceEmptyState.tsx
similarity index 56%
rename from enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.tsx
rename to enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/WorkspaceEmptyState.tsx
index e3ad1b49c05..758519117ea 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/WorkspaceEmptyState.tsx
@@ -1,13 +1,10 @@
-import { useDisclosure } from "@mantine/hooks";
+import type { ReactNode } from "react";
import { Link } from "react-router";
-import { push } from "react-router-redux";
import { t } from "ttag";
import { useDocsUrl } from "metabase/common/hooks";
-import { useDispatch } from "metabase/redux";
import {
Box,
- Button,
Card,
FixedSizeIcon,
Group,
@@ -15,26 +12,23 @@ import {
Text,
Title,
} from "metabase/ui";
-import * as Urls from "metabase/urls";
-import type { Workspace } from "metabase-types/api";
-
-import { NewWorkspaceModal } from "../NewWorkspaceModal";
import S from "./WorkspaceEmptyState.module.css";
-export function WorkspaceEmptyState() {
- const [opened, { open, close }] = useDisclosure(false);
- const dispatch = useDispatch();
+type WorkspaceEmptyStateProps = {
+ description: ReactNode;
+ children?: ReactNode;
+};
+
+export function WorkspaceEmptyState({
+ description,
+ children,
+}: WorkspaceEmptyStateProps) {
const { url: fileBasedDevDocsUrl, showMetabaseLinks: showFileBasedDevLink } =
useDocsUrl("ai/file-based-development");
const { url: remoteSyncDocsUrl, showMetabaseLinks: showRemoteSyncLink } =
useDocsUrl("installation-and-operation/remote-sync");
- const handleCreate = (workspace: Workspace) => {
- close();
- dispatch(push(Urls.workspace(workspace.id)));
- };
-
return (
<Card p="xl" maw="40rem" mx="auto" shadow="none" withBorder>
<Box p="md">
@@ -42,20 +36,10 @@ export function WorkspaceEmptyState() {
order={3}
mb="sm"
>{t`Isolated spaces for agents and developers`}</Title>
- <Text c="text-secondary" mb="sm">
- {t`Develop and run transforms, and build your semantic layer without touching your production tables.`}
- </Text>
<Text c="text-secondary" mb="md">
- {
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- referring to the product name is intentional
- t`Create a workspace here, or with Metabase’s CLI. That will set up an isolated sandbox with a dedicated schema and database user in the data warehouse(s) you choose.`
- }
+ {description}
</Text>
- <Box pb="xl">
- <Button variant="filled" onClick={open}>
- {t`Create a workspace`}
- </Button>
- </Box>
+ {children}
{(showFileBasedDevLink || showRemoteSyncLink) && (
<Group pt="md" gap="sm" align="stretch">
{showFileBasedDevLink && (
@@ -68,21 +52,13 @@ export function WorkspaceEmptyState() {
{showRemoteSyncLink && (
<DocsLink
title={t`Using remote sync`}
- description={
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- referring to the product name is intentional
- t`How to sync and review Metabase content with git.`
- }
+ description={t`How to sync and review instance content with git.`}
link={remoteSyncDocsUrl}
/>
)}
</Group>
)}
</Box>
- <NewWorkspaceModal
- opened={opened}
- onCreate={handleCreate}
- onClose={close}
- />
</Card>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/index.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/index.ts
rename to enterprise/frontend/src/metabase-enterprise/workspaces/components/WorkspaceEmptyState/index.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/index.ts
index 830f2323b0b..98a4873dfd1 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/index.ts
@@ -3,12 +3,12 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { AdminConnectionInfoSection } from "./components/AdminConnectionInfoSection";
import { getAdminConnectionInfoRoutes, getDataStudioRoutes } from "./routes";
-import { canManageWorkspaces, hasActiveWorkspace } from "./selectors";
+import { canManageWorkspaceInstance, canManageWorkspaces } from "./selectors";
export function initializePlugin() {
if (hasPremiumFeature("workspaces")) {
PLUGIN_WORKSPACES.canManageWorkspaces = canManageWorkspaces;
- PLUGIN_WORKSPACES.hasActiveWorkspace = hasActiveWorkspace;
+ PLUGIN_WORKSPACES.canManageWorkspaceInstance = canManageWorkspaceInstance;
PLUGIN_WORKSPACES.getDataStudioRoutes = getDataStudioRoutes;
PLUGIN_WORKSPACES.getAdminConnectionInfoRoutes =
getAdminConnectionInfoRoutes;
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.tsx
new file mode 100644
index 00000000000..8ec465a55e3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.tsx
@@ -0,0 +1,31 @@
+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
+import { useSelector } from "metabase/redux";
+import { useGetCurrentWorkspaceQuery } from "metabase-enterprise/api";
+
+import {
+ canManageWorkspaceInstance,
+ getIsDevelopmentMode,
+} from "../../selectors";
+import { WorkspaceInstancePage } from "../WorkspaceInstancePage";
+import { WorkspaceListPage } from "../WorkspaceListPage";
+
+export function WorkspaceIndexPage() {
+ const canManageInstance = useSelector(canManageWorkspaceInstance);
+ const isDevelopmentMode = useSelector(getIsDevelopmentMode);
+
+ const {
+ data: workspace,
+ isLoading,
+ error,
+ } = useGetCurrentWorkspaceQuery(undefined, { skip: !canManageInstance });
+
+ if (isLoading || error != null) {
+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ if (workspace != null || isDevelopmentMode) {
+ return <WorkspaceInstancePage />;
+ }
+
+ return <WorkspaceListPage />;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.unit.spec.tsx
new file mode 100644
index 00000000000..f479bc6c183
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/WorkspaceIndexPage.unit.spec.tsx
@@ -0,0 +1,120 @@
+import { Route } from "react-router";
+
+import {
+ setupDatabasesEndpoints,
+ setupGetCurrentWorkspaceEndpoint,
+ setupListTableRemappingsEndpoint,
+ setupListWorkspacesEndpoint,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { WorkspaceInstance } from "metabase-types/api";
+import {
+ createMockDatabase,
+ createMockTokenFeatures,
+ createMockUser,
+ createMockWorkspaceInstance,
+ createMockWorkspaceInstanceDatabase,
+} from "metabase-types/api/mocks";
+
+import { WorkspaceIndexPage } from "./WorkspaceIndexPage";
+
+const POSTGRES = createMockDatabase({ id: 10, name: "Postgres" });
+
+const WORKSPACE = createMockWorkspaceInstance({
+ name: "Dev workspace",
+ databases: {
+ [POSTGRES.id]: createMockWorkspaceInstanceDatabase({
+ input_schemas: ["public"],
+ output: { schema: "ws_dev" },
+ }),
+ },
+});
+
+type SetupOpts = {
+ isAdmin?: boolean;
+ canManageWorkspaces?: boolean;
+ workspace?: WorkspaceInstance | null;
+ isDevelopmentMode?: boolean;
+};
+
+function setup({
+ isAdmin = true,
+ canManageWorkspaces = false,
+ workspace = null,
+ isDevelopmentMode = false,
+}: SetupOpts = {}) {
+ setupDatabasesEndpoints([POSTGRES]);
+ setupGetCurrentWorkspaceEndpoint(workspace);
+ setupListTableRemappingsEndpoint([]);
+ setupListWorkspacesEndpoint([]);
+
+ const state = createMockState({
+ currentUser: createMockUser({
+ is_superuser: isAdmin,
+ permissions: {
+ can_access_data_model: isAdmin,
+ can_access_db_details: false,
+ can_manage_workspaces: canManageWorkspaces,
+ },
+ }),
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({
+ workspaces: true,
+ development_mode: isDevelopmentMode,
+ }),
+ }),
+ });
+
+ renderWithProviders(<Route path="*" component={WorkspaceIndexPage} />, {
+ withRouter: true,
+ storeInitialState: state,
+ });
+}
+
+describe("WorkspaceIndexPage", () => {
+ it("admin with a workspace loaded sees the instance page", async () => {
+ setup({ isAdmin: true, workspace: WORKSPACE });
+
+ expect(
+ await screen.findByTestId("workspace-instance-page"),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("workspace-list-page")).not.toBeInTheDocument();
+ });
+
+ it("admin in development mode sees the instance page even without a workspace", async () => {
+ setup({ isAdmin: true, workspace: null, isDevelopmentMode: true });
+
+ expect(
+ await screen.findByTestId("workspace-instance-page"),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("workspace-list-page")).not.toBeInTheDocument();
+ });
+
+ it("admin without a workspace and not in development mode sees the list page", async () => {
+ setup({ isAdmin: true, workspace: null, isDevelopmentMode: false });
+
+ expect(
+ await screen.findByTestId("workspace-list-page"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("workspace-instance-page"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("non-admin with manage-workspaces permission skips the instance lookup and sees the list page", async () => {
+ setup({
+ isAdmin: false,
+ canManageWorkspaces: true,
+ workspace: WORKSPACE,
+ });
+
+ expect(
+ await screen.findByTestId("workspace-list-page"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("workspace-instance-page"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/index.ts
new file mode 100644
index 00000000000..38a9eebd632
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceIndexPage/index.ts
@@ -0,0 +1 @@
+export * from "./WorkspaceIndexPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.tsx
new file mode 100644
index 00000000000..28a2ec050ef
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.tsx
@@ -0,0 +1,46 @@
+import { jt, t } from "ttag";
+
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { TitleSection } from "metabase/data-studio/common/components/TitleSection";
+import { Button, Code, Group, Text } from "metabase/ui";
+import { useDeleteWorkspaceInstanceMutation } from "metabase-enterprise/api";
+
+const CONFIG_FILENAME = "config.yml";
+
+export function DeleteSection() {
+ const { modalContent, show } = useConfirmation();
+ const [deleteInstance] = useDeleteWorkspaceInstanceMutation();
+
+ const handleClick = () => {
+ show({
+ title: t`Leave workspace?`,
+ message: jt`This instance will stop remapping transform tables to the workspace's isolated schemas. The databases registered from the uploaded ${(
+ <Code key="config">{CONFIG_FILENAME}</Code>
+ )} will remain — you can re-enter the workspace at any time by uploading it again.`,
+ confirmButtonText: t`Leave workspace`,
+ confirmButtonProps: { color: "danger" },
+ onConfirm: async () => {
+ await deleteInstance().unwrap();
+ },
+ });
+ };
+
+ return (
+ <>
+ <TitleSection
+ data-testid="workspace-instance-delete-section"
+ label={t`Leave workspace`}
+ >
+ <Group p="lg" justify="space-between" align="center">
+ <Text maw="40rem">
+ {t`Stop remapping transform tables on this instance.`}
+ </Text>
+ <Button color="error" variant="filled" onClick={handleClick}>
+ {t`Leave workspace`}
+ </Button>
+ </Group>
+ </TitleSection>
+ {modalContent}
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.unit.spec.tsx
new file mode 100644
index 00000000000..00b591996e9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/DeleteSection.unit.spec.tsx
@@ -0,0 +1,39 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+import { Route } from "react-router";
+
+import { setupDeleteWorkspaceInstanceEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+
+import { DeleteSection } from "./DeleteSection";
+
+function setup() {
+ setupDeleteWorkspaceInstanceEndpoint();
+
+ renderWithProviders(<Route path="*" component={DeleteSection} />, {
+ withRouter: true,
+ });
+}
+
+describe("DeleteSection", () => {
+ it("calls DELETE /api/ee/workspace-instance/current after confirming", async () => {
+ setup();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Leave workspace" }),
+ );
+ const dialog = await screen.findByRole("dialog");
+ await userEvent.click(
+ within(dialog).getByRole("button", { name: "Leave workspace" }),
+ );
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called(
+ "path:/api/ee/workspace-instance/current",
+ { method: "DELETE" },
+ ),
+ ).toBe(true);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/index.ts
new file mode 100644
index 00000000000..50566513525
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/DeleteSection/index.ts
@@ -0,0 +1 @@
+export * from "./DeleteSection";
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/SetupWorkspaceModal.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/SetupWorkspaceModal.tsx
new file mode 100644
index 00000000000..99357826558
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/SetupWorkspaceModal.tsx
@@ -0,0 +1,105 @@
+import { push } from "react-router-redux";
+import { jt, t } from "ttag";
+
+import {
+ Form,
+ FormErrorMessage,
+ FormFileInput,
+ FormProvider,
+ FormSubmitButton,
+} from "metabase/forms";
+import { useDispatch } from "metabase/redux";
+import {
+ Button,
+ Code,
+ FixedSizeIcon,
+ FocusTrap,
+ Group,
+ Modal,
+ Stack,
+ Text,
+} from "metabase/ui";
+import * as Urls from "metabase/urls";
+import { useApplyAdvancedConfigMutation } from "metabase-enterprise/api";
+
+const CONFIG_FILENAME = "config.yml";
+
+type SetupWorkspaceModalProps = {
+ opened: boolean;
+ onClose: () => void;
+};
+
+export function SetupWorkspaceModal({
+ opened,
+ onClose,
+}: SetupWorkspaceModalProps) {
+ return (
+ <Modal
+ title={t`Set up a workspace`}
+ opened={opened}
+ padding="xl"
+ onClose={onClose}
+ >
+ <FocusTrap.InitialFocus />
+ <SetupWorkspaceForm onClose={onClose} />
+ </Modal>
+ );
+}
+
+type SetupWorkspaceFormValues = {
+ config: File | null;
+};
+
+const INITIAL_VALUES: SetupWorkspaceFormValues = {
+ config: null,
+};
+
+type SetupWorkspaceFormProps = {
+ onClose: () => void;
+};
+
+function SetupWorkspaceForm({ onClose }: SetupWorkspaceFormProps) {
+ const dispatch = useDispatch();
+ const [applyConfig] = useApplyAdvancedConfigMutation();
+
+ const handleSubmit = async ({ config }: SetupWorkspaceFormValues) => {
+ if (!config) {
+ return;
+ }
+ await applyConfig({ config }).unwrap();
+ onClose();
+ dispatch(push(Urls.workspaces()));
+ };
+
+ return (
+ <FormProvider initialValues={INITIAL_VALUES} onSubmit={handleSubmit}>
+ {({ values }) => (
+ <Form>
+ <Stack gap="lg">
+ <Text c="text-secondary">
+ {jt`Upload the ${(
+ <Code key="config">{CONFIG_FILENAME}</Code>
+ )} from the main instance's workspace page.`}
+ </Text>
+ <FormFileInput
+ name="config"
+ label={t`Config file`}
+ placeholder={t`Choose a ${CONFIG_FILENAME} file`}
+ accept=".yml,.yaml,application/yaml,text/yaml"
+ leftSection={<FixedSizeIcon name="attachment" aria-hidden />}
+ />
+ <FormErrorMessage />
+ <Group justify="flex-end">
+ <Button onClick={onClose}>{t`Cancel`}</Button>
+ <FormSubmitButton
+ label={t`Set up`}
+ variant="filled"
+ disabled={values.config == null}
+ />
+ </Group>
+ </Stack>
+ </Form>
+ )}
+ </FormProvider>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/index.ts
new file mode 100644
index 00000000000..9dbfa7cf650
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/SetupWorkspaceModal/index.ts
@@ -0,0 +1 @@
+export * from "./SetupWorkspaceModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingSection.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingSection.tsx
index c4fe41b9b8c..c0f3009e4af 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingSection.tsx
@@ -1,5 +1,7 @@
+import { t } from "ttag";
+
import { TitleSection } from "metabase/data-studio/common/components/TitleSection";
-import { Box, FixedSizeIcon, Group } from "metabase/ui";
+import { Box, FixedSizeIcon, Group, Text } from "metabase/ui";
import type { Database, TableRemapping } from "metabase-types/api";
import { TableRemappingTable } from "./TableRemappingTable";
@@ -23,7 +25,13 @@ export function TableRemappingSection({
</Group>
}
>
- <TableRemappingTable remappings={remappings} />
+ {remappings.length === 0 ? (
+ <Text p="lg">
+ {t`Tables will be remapped here the first time a transform runs in this workspace for this database.`}
+ </Text>
+ ) : (
+ <TableRemappingTable remappings={remappings} />
+ )}
</TitleSection>
</Box>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingTable/TableRemappingTable.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingTable/TableRemappingTable.tsx
index d232496b726..69de768bdc7 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingTable/TableRemappingTable.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/TableRemappingSection/TableRemappingTable/TableRemappingTable.tsx
@@ -1,7 +1,6 @@
import { useMemo } from "react";
-import { t } from "ttag";
-import { Text, TreeTable, useTreeTableInstance } from "metabase/ui";
+import { TreeTable, useTreeTableInstance } from "metabase/ui";
import type { TableRemapping } from "metabase-types/api";
import { getColumns } from "./utils";
@@ -19,14 +18,5 @@ export function TableRemappingTable({ remappings }: TableRemappingTableProps) {
getNodeId: (remapping) => String(remapping.id),
});
- return (
- <TreeTable
- instance={treeTableInstance}
- emptyState={
- <Text c="text-secondary">
- {t`Tables will be remapped here the first time a transform runs in this workspace for this database.`}
- </Text>
- }
- />
- );
+ return <TreeTable instance={treeTableInstance} />;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/WorkspaceInstanceEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/WorkspaceInstanceEmptyState.tsx
new file mode 100644
index 00000000000..56df91589a3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/WorkspaceInstanceEmptyState.tsx
@@ -0,0 +1,31 @@
+import { useDisclosure } from "@mantine/hooks";
+import { t } from "ttag";
+
+import { useSelector } from "metabase/redux";
+import { Box, Button } from "metabase/ui";
+
+import { WorkspaceEmptyState } from "../../../components/WorkspaceEmptyState";
+import { getIsDevelopmentMode } from "../../../selectors";
+import { SetupWorkspaceModal } from "../SetupWorkspaceModal";
+
+export function WorkspaceInstanceEmptyState() {
+ const [opened, { open, close }] = useDisclosure(false);
+ const isDevelopmentMode = useSelector(getIsDevelopmentMode);
+
+ return (
+ <>
+ <WorkspaceEmptyState
+ description={t`Set up this developer instance to remap transform tables into an isolated workspace schema, so you can develop and test transforms without affecting your production tables.`}
+ >
+ {isDevelopmentMode && (
+ <Box pb="xl">
+ <Button variant="filled" onClick={open}>
+ {t`Set up a workspace`}
+ </Button>
+ </Box>
+ )}
+ </WorkspaceEmptyState>
+ <SetupWorkspaceModal opened={opened} onClose={close} />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/index.ts
new file mode 100644
index 00000000000..c36b2e49103
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstanceEmptyState/index.ts
@@ -0,0 +1 @@
+export * from "./WorkspaceInstanceEmptyState";
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.tsx
index f3c6dfc64e5..abf1f8c891b 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.tsx
@@ -5,6 +5,7 @@ import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/Loadin
import { DataStudioBreadcrumbs } from "metabase/data-studio/common/components/DataStudioBreadcrumbs";
import { PageContainer } from "metabase/data-studio/common/components/PageContainer";
import { PaneHeader } from "metabase/data-studio/common/components/PaneHeader";
+import { useSelector } from "metabase/redux";
import { Stack, Title } from "metabase/ui";
import {
useGetCurrentWorkspaceQuery,
@@ -17,8 +18,11 @@ import type {
} from "metabase-types/api";
import { HelpMenu } from "../../components/HelpMenu";
+import { getIsDevelopmentMode } from "../../selectors";
+import { DeleteSection } from "./DeleteSection";
import { TableRemappingSection } from "./TableRemappingSection";
+import { WorkspaceInstanceEmptyState } from "./WorkspaceInstanceEmptyState";
import { getDatabasesInfo } from "./utils";
export function WorkspaceInstancePage() {
@@ -45,7 +49,6 @@ export function WorkspaceInstancePage() {
if (
isLoading ||
error != null ||
- workspace == null ||
remappings == null ||
databasesResponse == null
) {
@@ -54,7 +57,7 @@ export function WorkspaceInstancePage() {
return (
<WorkspaceInstancePageBody
- workspace={workspace}
+ workspace={workspace ?? null}
remappings={remappings}
databases={databasesResponse.data}
/>
@@ -62,7 +65,7 @@ export function WorkspaceInstancePage() {
}
type WorkspaceInstancePageBodyProps = {
- workspace: WorkspaceInstance;
+ workspace: WorkspaceInstance | null;
remappings: TableRemapping[];
databases: Database[];
};
@@ -72,27 +75,36 @@ function WorkspaceInstancePageBody({
remappings,
databases,
}: WorkspaceInstancePageBodyProps) {
- const databasesInfo = getDatabasesInfo(workspace, databases, remappings);
+ const databasesInfo =
+ workspace != null ? getDatabasesInfo(workspace, databases, remappings) : [];
+ const isDevelopmentMode = useSelector(getIsDevelopmentMode);
return (
<PageContainer data-testid="workspace-instance-page">
<PaneHeader
- title={<Title order={3}>{workspace.name}</Title>}
+ title={
+ workspace != null ? <Title order={3}>{workspace.name}</Title> : null
+ }
breadcrumbs={
- <DataStudioBreadcrumbs>{t`Workspace`}</DataStudioBreadcrumbs>
+ <DataStudioBreadcrumbs>{t`Workspaces`}</DataStudioBreadcrumbs>
}
- actions={<HelpMenu />}
+ actions={workspace != null ? <HelpMenu /> : null}
py={0}
/>
- <Stack gap="3.5rem">
- {databasesInfo.map(({ database, remappings }) => (
- <TableRemappingSection
- key={database.id}
- database={database}
- remappings={remappings}
- />
- ))}
- </Stack>
+ {workspace == null ? (
+ <WorkspaceInstanceEmptyState />
+ ) : (
+ <Stack gap="3.5rem">
+ {databasesInfo.map(({ database, remappings }) => (
+ <TableRemappingSection
+ key={database.id}
+ database={database}
+ remappings={remappings}
+ />
+ ))}
+ {isDevelopmentMode && <DeleteSection />}
+ </Stack>
+ )}
</PageContainer>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.unit.spec.tsx
index 5ad61f0b235..5227bf80c0a 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceInstancePage/WorkspaceInstancePage.unit.spec.tsx
@@ -6,10 +6,13 @@ import {
setupListTableRemappingsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
-import type { TableRemapping } from "metabase-types/api";
+import { createMockSettingsState } from "metabase/redux/store/mocks";
+import type { TableRemapping, WorkspaceInstance } from "metabase-types/api";
import {
createMockDatabase,
+ createMockSettings,
createMockTableRemapping,
+ createMockTokenFeatures,
createMockWorkspaceInstance,
createMockWorkspaceInstanceDatabase,
} from "metabase-types/api/mocks";
@@ -18,23 +21,34 @@ import { WorkspaceInstancePage } from "./WorkspaceInstancePage";
const POSTGRES = createMockDatabase({ id: 10, name: "Postgres" });
-function setup({ remappings = [] as TableRemapping[] } = {}) {
+function setup({
+ remappings = [] as TableRemapping[],
+ workspace = createMockWorkspaceInstance({
+ name: "Dev workspace",
+ databases: {
+ [POSTGRES.id]: createMockWorkspaceInstanceDatabase({
+ input_schemas: ["public"],
+ output: { schema: "ws_dev" },
+ }),
+ },
+ }) as WorkspaceInstance | null,
+ isDevelopmentMode = false,
+} = {}) {
setupDatabasesEndpoints([POSTGRES]);
- setupGetCurrentWorkspaceEndpoint(
- createMockWorkspaceInstance({
- name: "Dev workspace",
- databases: {
- [POSTGRES.id]: createMockWorkspaceInstanceDatabase({
- input_schemas: ["public"],
- output: { schema: "ws_dev" },
- }),
- },
- }),
- );
+ setupGetCurrentWorkspaceEndpoint(workspace);
setupListTableRemappingsEndpoint(remappings);
renderWithProviders(<Route path="*" component={WorkspaceInstancePage} />, {
withRouter: true,
+ storeInitialState: {
+ settings: createMockSettingsState(
+ createMockSettings({
+ "token-features": createMockTokenFeatures({
+ development_mode: isDevelopmentMode,
+ }),
+ }),
+ ),
+ },
});
}
@@ -66,4 +80,67 @@ describe("WorkspaceInstancePage", () => {
await screen.findByRole("region", { name: "Postgres" }),
).toBeInTheDocument();
});
+
+ it("renders the empty state when no workspace is set up", async () => {
+ setup({ workspace: null });
+
+ expect(
+ await screen.findByRole("heading", {
+ name: /Isolated spaces for agents and developers/,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Set up a workspace" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the set up button in the empty state on a developer instance", async () => {
+ setup({ workspace: null, isDevelopmentMode: true });
+
+ expect(
+ await screen.findByRole("button", {
+ name: "Set up a workspace",
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("hides the help menu in the empty state", async () => {
+ setup({ workspace: null });
+
+ expect(
+ await screen.findByRole("heading", {
+ name: /Isolated spaces for agents and developers/,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Help/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the help menu when a workspace is set up", async () => {
+ setup();
+
+ expect(await screen.findByText("Dev workspace")).toBeInTheDocument();
+ expect(
+ await screen.findByRole("button", { name: /Help/ }),
+ ).toBeInTheDocument();
+ });
+
+ it("does not render the delete section on the main instance", async () => {
+ setup({ isDevelopmentMode: false });
+
+ expect(await screen.findByText("Dev workspace")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("workspace-instance-delete-section"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders the delete section on a developer instance", async () => {
+ setup({ isDevelopmentMode: true });
+
+ expect(await screen.findByText("Dev workspace")).toBeInTheDocument();
+ expect(
+ await screen.findByTestId("workspace-instance-delete-section"),
+ ).toBeInTheDocument();
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.tsx
new file mode 100644
index 00000000000..9dbf2bfd6b7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.tsx
@@ -0,0 +1,40 @@
+import { useDisclosure } from "@mantine/hooks";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { useDispatch } from "metabase/redux";
+import { Box, Button } from "metabase/ui";
+import * as Urls from "metabase/urls";
+import type { Workspace } from "metabase-types/api";
+
+import { WorkspaceEmptyState } from "../../../components/WorkspaceEmptyState";
+import { NewWorkspaceModal } from "../NewWorkspaceModal";
+
+export function WorkspaceListEmptyState() {
+ const [opened, { open, close }] = useDisclosure(false);
+ const dispatch = useDispatch();
+
+ const handleCreate = (workspace: Workspace) => {
+ close();
+ dispatch(push(Urls.workspace(workspace.id)));
+ };
+
+ return (
+ <>
+ <WorkspaceEmptyState
+ description={t`Develop transforms and the semantic layer without touching production tables. Each workspace gets its own schema and database user in the warehouses you pick.`}
+ >
+ <Box pb="xl">
+ <Button variant="filled" onClick={open}>
+ {t`Create a workspace`}
+ </Button>
+ </Box>
+ </WorkspaceEmptyState>
+ <NewWorkspaceModal
+ opened={opened}
+ onCreate={handleCreate}
+ onClose={close}
+ />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.unit.spec.tsx
similarity index 65%
rename from enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.unit.spec.tsx
rename to enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.unit.spec.tsx
index e0d83928766..6e6997eba10 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceEmptyState/WorkspaceEmptyState.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/WorkspaceListEmptyState.unit.spec.tsx
@@ -4,10 +4,10 @@ import { renderWithProviders, screen } from "__support__/ui";
import { createMockSettingsState } from "metabase/redux/store/mocks";
import { createMockSettings } from "metabase-types/api/mocks";
-import { WorkspaceEmptyState } from "./WorkspaceEmptyState";
+import { WorkspaceListEmptyState } from "./WorkspaceListEmptyState";
function setup() {
- renderWithProviders(<Route path="*" component={WorkspaceEmptyState} />, {
+ renderWithProviders(<Route path="*" component={WorkspaceListEmptyState} />, {
withRouter: true,
storeInitialState: {
settings: createMockSettingsState(
@@ -17,7 +17,15 @@ function setup() {
});
}
-describe("WorkspaceEmptyState", () => {
+describe("WorkspaceListEmptyState", () => {
+ it("renders the create workspace button", () => {
+ setup();
+
+ expect(
+ screen.getByRole("button", { name: "Create a workspace" }),
+ ).toBeInTheDocument();
+ });
+
it("renders docs link buttons", () => {
setup();
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/index.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/index.ts
new file mode 100644
index 00000000000..6738debab8a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListEmptyState/index.ts
@@ -0,0 +1 @@
+export * from "./WorkspaceListEmptyState";
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListPage.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListPage.tsx
index fe6df262e28..a011ede3441 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspaceListPage/WorkspaceListPage.tsx
@@ -12,8 +12,8 @@ import type { Database, Workspace } from "metabase-types/api";
import { HelpMenu } from "../../components/HelpMenu";
import { NewWorkspaceButton } from "./NewWorkspaceButton";
-import { WorkspaceEmptyState } from "./WorkspaceEmptyState";
import { WorkspaceItem } from "./WorkspaceItem";
+import { WorkspaceListEmptyState } from "./WorkspaceListEmptyState";
export function WorkspaceListPage() {
const {
@@ -85,7 +85,7 @@ function WorkspaceListPageBody({
))}
</Stack>
) : (
- <WorkspaceEmptyState />
+ <WorkspaceListEmptyState />
)}
</PageContainer>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/DatabaseEmptyState/DatabaseEmptyState.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/DatabaseEmptyState/DatabaseEmptyState.unit.spec.tsx
index 9d648ee32b3..9925b67ee83 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/DatabaseEmptyState/DatabaseEmptyState.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/DatabaseEmptyState/DatabaseEmptyState.unit.spec.tsx
@@ -60,10 +60,7 @@ describe("DatabaseEmptyState", () => {
const dialog = await screen.findByRole("dialog");
await userEvent.click(
- await within(dialog).findByLabelText("Schemas to include"),
- );
- await userEvent.click(
- await screen.findByRole("option", { name: "public" }),
+ await within(dialog).findByRole("checkbox", { name: "public" }),
);
await userEvent.click(
within(dialog).getByRole("button", { name: "Add database" }),
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/NewDatabaseModal/NewDatabaseModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/NewDatabaseModal/NewDatabaseModal.unit.spec.tsx
index 79c69d180f2..947101807fe 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/NewDatabaseModal/NewDatabaseModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/NewDatabaseModal/NewDatabaseModal.unit.spec.tsx
@@ -79,9 +79,8 @@ describe("NewDatabaseModal", () => {
it("can create a workspace database", async () => {
const { onCreate, createdWorkspace } = setup();
- await userEvent.click(screen.getByLabelText("Schemas to include"));
await userEvent.click(
- await screen.findByRole("option", { name: "public" }),
+ await screen.findByRole("checkbox", { name: "public" }),
);
await userEvent.click(screen.getByRole("button", { name: "Add database" }));
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.tsx
index 59d4a03aa61..f432a301e75 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.tsx
@@ -1,7 +1,7 @@
import { t } from "ttag";
import { useListDatabaseSchemasQuery } from "metabase/api";
-import { MultiSelect } from "metabase/ui";
+import { Checkbox, Input, ScrollArea, Stack, Text } from "metabase/ui";
import type { DatabaseId } from "metabase-types/api";
export type SchemaMultiSelectProps = {
@@ -18,15 +18,40 @@ export function SchemaMultiSelect({
const { data: schemas = [] } = useListDatabaseSchemasQuery({
id: databaseId,
});
- const isAllSelected = schemas.length > 0 && value.length === schemas.length;
+
+ const isAll = schemas.length > 0 && value.length === schemas.length;
+ const isNone = value.length === 0;
+
+ const handleToggleAll = () => {
+ onChange(isAll ? [] : schemas);
+ };
return (
- <MultiSelect
- label={t`Schemas to include`}
- placeholder={isAllSelected ? t`All schemas selected` : t`Pick schemas`}
- data={schemas}
- value={value}
- onChange={onChange}
- />
+ <Input.Wrapper label={t`Schemas to include`}>
+ {schemas.length > 0 && (
+ <Stack gap="sm" mt="xs">
+ <Checkbox
+ variant="stacked"
+ label={
+ <Text c="text-secondary" lh="inherit">
+ {isAll ? t`Select none` : t`Select all`}
+ </Text>
+ }
+ checked={isAll}
+ indeterminate={!isAll && !isNone}
+ onChange={handleToggleAll}
+ />
+ <Checkbox.Group value={value} onChange={onChange}>
+ <ScrollArea.Autosize mah={200}>
+ <Stack gap="sm">
+ {schemas.map((schema) => (
+ <Checkbox key={schema} value={schema} label={schema} />
+ ))}
+ </Stack>
+ </ScrollArea.Autosize>
+ </Checkbox.Group>
+ </Stack>
+ )}
+ </Input.Wrapper>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.unit.spec.tsx
index ca6c4f438f3..a2011ab848a 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/SchemaMultiSelect/SchemaMultiSelect.unit.spec.tsx
@@ -38,9 +38,8 @@ describe("SchemaMultiSelect", () => {
it("can select the first schema", async () => {
const { onChange } = setup();
- await userEvent.click(screen.getByLabelText("Schemas to include"));
await userEvent.click(
- await screen.findByRole("option", { name: "public" }),
+ await screen.findByRole("checkbox", { name: "public" }),
);
expect(onChange).toHaveBeenCalledWith(["public"]);
@@ -49,11 +48,30 @@ describe("SchemaMultiSelect", () => {
it("can select the second schema", async () => {
const { onChange } = setup({ value: ["public"] });
- await userEvent.click(screen.getByLabelText("Schemas to include"));
await userEvent.click(
- await screen.findByRole("option", { name: "analytics" }),
+ await screen.findByRole("checkbox", { name: "analytics" }),
);
expect(onChange).toHaveBeenCalledWith(["public", "analytics"]);
});
+
+ it("selects all schemas via the top-level checkbox", async () => {
+ const { onChange } = setup({ value: ["public"] });
+
+ await userEvent.click(
+ await screen.findByRole("checkbox", { name: "Select all" }),
+ );
+
+ expect(onChange).toHaveBeenCalledWith(["public", "analytics"]);
+ });
+
+ it("clears all schemas when all are already selected", async () => {
+ const { onChange } = setup({ value: ["public", "analytics"] });
+
+ await userEvent.click(
+ await screen.findByRole("checkbox", { name: "Select none" }),
+ );
+
+ expect(onChange).toHaveBeenCalledWith([]);
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/UpdateDatabaseModal/UpdateDatabaseModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/UpdateDatabaseModal/UpdateDatabaseModal.unit.spec.tsx
index 52f48dbe389..eb07bf45543 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/UpdateDatabaseModal/UpdateDatabaseModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/DatabaseSection/UpdateDatabaseModal/UpdateDatabaseModal.unit.spec.tsx
@@ -81,9 +81,8 @@ describe("UpdateDatabaseModal", () => {
it("can update a workspace database", async () => {
const { onUpdate, updatedWorkspace } = setup();
- await userEvent.click(screen.getByLabelText("Schemas to include"));
await userEvent.click(
- await screen.findByRole("option", { name: "analytics" }),
+ await screen.findByRole("checkbox", { name: "analytics" }),
);
await userEvent.click(screen.getByRole("button", { name: "Save changes" }));
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.tsx
index 0a8e81077c1..034bb3267bf 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.tsx
@@ -1,7 +1,7 @@
import { jt, t } from "ttag";
import { TitleSection } from "metabase/data-studio/common/components/TitleSection";
-import { Button, Code, FixedSizeIcon, Group, Text } from "metabase/ui";
+import { Button, Code, FixedSizeIcon, Group, Text, Tooltip } from "metabase/ui";
import type { Workspace } from "metabase-types/api";
const CONFIG_FILENAME = "config.yml";
@@ -11,8 +11,8 @@ export type SetupSectionProps = {
};
export function SetupSection({ workspace }: SetupSectionProps) {
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- referring to the product name is intentional
- const description = jt`Run a local Metabase instance backed by this workspace's data so you can make changes safely. Pass this ${<Code key="config">{CONFIG_FILENAME}</Code>} file, containing the database credentials, when starting the instance.`;
+ const description = jt`Download this ${<Code key="config">{CONFIG_FILENAME}</Code>} and upload it on the developer instance to load this isolated workspace. The file carries the database credentials the developer instance needs.`;
+ const isDisabled = workspace.databases.length === 0;
return (
<TitleSection
@@ -21,14 +21,25 @@ export function SetupSection({ workspace }: SetupSectionProps) {
>
<Group p="lg" justify="space-between" align="center">
<Text maw="40rem">{description}</Text>
- <Button
- component="a"
- href={`/api/ee/workspace-manager/${workspace.id}/config`}
- download={CONFIG_FILENAME}
- leftSection={<FixedSizeIcon name="download" aria-hidden />}
- >
- {t`Download ${CONFIG_FILENAME}`}
- </Button>
+ {isDisabled ? (
+ <Tooltip label={t`You need to add at least one database.`}>
+ <Button
+ disabled
+ leftSection={<FixedSizeIcon name="download" aria-hidden />}
+ >
+ {t`Download ${CONFIG_FILENAME}`}
+ </Button>
+ </Tooltip>
+ ) : (
+ <Button
+ component="a"
+ href={`/api/ee/workspace-manager/${workspace.id}/config`}
+ download={CONFIG_FILENAME}
+ leftSection={<FixedSizeIcon name="download" aria-hidden />}
+ >
+ {t`Download ${CONFIG_FILENAME}`}
+ </Button>
+ )}
</Group>
</TitleSection>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.unit.spec.tsx
new file mode 100644
index 00000000000..0857a39035c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/SetupSection/SetupSection.unit.spec.tsx
@@ -0,0 +1,44 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ createMockWorkspace,
+ createMockWorkspaceDatabase,
+} from "metabase-types/api/mocks";
+
+import { SetupSection } from "./SetupSection";
+
+function setup({ workspace = createMockWorkspace() } = {}) {
+ renderWithProviders(<SetupSection workspace={workspace} />);
+}
+
+describe("SetupSection", () => {
+ it("renders an enabled download link when the workspace has databases", () => {
+ const workspace = createMockWorkspace({
+ databases: [createMockWorkspaceDatabase()],
+ });
+ setup({ workspace });
+
+ const button = screen.getByRole("link", { name: /Download config\.yml/ });
+ expect(button).toBeEnabled();
+ expect(button).toHaveAttribute(
+ "href",
+ `/api/ee/workspace-manager/${workspace.id}/config`,
+ );
+ });
+
+ it("disables the download button and shows a tooltip when the workspace has no databases", async () => {
+ setup({ workspace: createMockWorkspace({ databases: [] }) });
+
+ const button = screen.getByRole("button", { name: /Download config\.yml/ });
+ expect(button).toBeDisabled();
+ expect(
+ screen.queryByRole("link", { name: /Download config\.yml/ }),
+ ).not.toBeInTheDocument();
+
+ await userEvent.hover(button);
+ expect(
+ await screen.findByText("You need to add at least one database."),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspaceHeader/WorkspaceHeader.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspaceHeader/WorkspaceHeader.tsx
index 37710d8f589..0d952518670 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspaceHeader/WorkspaceHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspaceHeader/WorkspaceHeader.tsx
@@ -49,7 +49,7 @@ export function WorkspaceHeader({ workspace, actions }: WorkspaceHeaderProps) {
}
breadcrumbs={
<DataStudioBreadcrumbs>
- <Link key="workspace-list" to={Urls.workspaceList()}>
+ <Link key="workspace-list" to={Urls.workspaces()}>
{t`Workspaces`}
</Link>
{workspace.name}
@@ -69,7 +69,7 @@ type WorkspaceHeaderMenuProps = {
function WorkspaceHeaderMenu({ workspace }: WorkspaceHeaderMenuProps) {
const dispatch = useDispatch();
const { handleDelete, modalContent } = useDeleteWorkspace({
- onSuccess: () => dispatch(push(Urls.workspaceList())),
+ onSuccess: () => dispatch(push(Urls.workspaces())),
});
return (
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspacePage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspacePage.unit.spec.tsx
index 09c7d3b9bdb..0c2d9c0543d 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspacePage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/pages/WorkspacePage/WorkspacePage.unit.spec.tsx
@@ -66,10 +66,7 @@ describe("WorkspacePage", () => {
const dialog = await screen.findByRole("dialog");
await userEvent.click(
- await within(dialog).findByLabelText("Schemas to include"),
- );
- await userEvent.click(
- await screen.findByRole("option", { name: "public" }),
+ await within(dialog).findByRole("checkbox", { name: "public" }),
);
await userEvent.click(
within(dialog).getByRole("button", { name: "Add database" }),
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/routes.tsx b/enterprise/frontend/src/metabase-enterprise/workspaces/routes.tsx
index a99376268d6..72c87914d5a 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/routes.tsx
@@ -1,15 +1,13 @@
import { IndexRoute, Route, type RouteComponent } from "react-router";
import { AdminConnectionInfoPage } from "./pages/AdminConnectionInfoPage";
-import { WorkspaceInstancePage } from "./pages/WorkspaceInstancePage";
-import { WorkspaceListPage } from "./pages/WorkspaceListPage";
+import { WorkspaceIndexPage } from "./pages/WorkspaceIndexPage";
import { WorkspacePage } from "./pages/WorkspacePage";
export function getDataStudioRoutes() {
return (
<Route path="workspaces">
- <IndexRoute component={WorkspaceListPage} />
- <Route path="instance" component={WorkspaceInstancePage} />
+ <IndexRoute component={WorkspaceIndexPage} />
<Route path=":workspaceId" component={WorkspacePage} />
</Route>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/workspaces/selectors.ts b/enterprise/frontend/src/metabase-enterprise/workspaces/selectors.ts
index 41b37775acd..ac4016de307 100644
--- a/enterprise/frontend/src/metabase-enterprise/workspaces/selectors.ts
+++ b/enterprise/frontend/src/metabase-enterprise/workspaces/selectors.ts
@@ -1,14 +1,19 @@
import type { State } from "metabase/redux/store";
-import { getSetting } from "metabase/selectors/settings";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
+import { getTokenFeature } from "metabase/setup/selectors";
-export const canManageWorkspaces = (state: State): boolean => {
+export function canManageWorkspaces(state: State): boolean {
if (getUserIsAdmin(state)) {
return true;
}
const user = getUser(state);
return user?.permissions?.can_manage_workspaces ?? false;
-};
+}
-export const hasActiveWorkspace = (state: State): boolean =>
- getSetting(state, "has-active-workspace") ?? false;
+export function canManageWorkspaceInstance(state: State): boolean {
+ return getUserIsAdmin(state);
+}
+
+export function getIsDevelopmentMode(state: State): boolean {
+ return getTokenFeature(state, "development_mode");
+}
diff --git a/frontend/src/metabase-types/api/advanced-config.ts b/frontend/src/metabase-types/api/advanced-config.ts
new file mode 100644
index 00000000000..2c0bcfd7e7f
--- /dev/null
+++ b/frontend/src/metabase-types/api/advanced-config.ts
@@ -0,0 +1,26 @@
+import type { WorkspaceInstanceDatabase } from "./workspace-instance";
+
+export type AdvancedConfigDatabase = {
+ name: string;
+ engine: string;
+ details: Record<string, unknown>;
+};
+
+export type AdvancedConfigWorkspace = {
+ name: string;
+ databases: Record<string, WorkspaceInstanceDatabase>;
+};
+
+export type AdvancedConfigContent = {
+ databases?: AdvancedConfigDatabase[];
+ workspace?: AdvancedConfigWorkspace;
+};
+
+export type AdvancedConfig = {
+ version: number;
+ config: AdvancedConfigContent;
+};
+
+export type ApplyAdvancedConfigRequest = {
+ config: File;
+};
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 928e0b319f5..449b82c38a0 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -1,6 +1,7 @@
export * from "./actions";
export * from "./activity";
export * from "./admin";
+export * from "./advanced-config";
export * from "./advanced-permission";
export * from "./ai-entity-analysis";
export * from "./alert";
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index 88a8e7332ad..335cd5615a2 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -278,7 +278,6 @@ export const createMockSettings = (
* You probably don't want to set this directly in tests because it can get out
* of sync with the database state (which should be a source of truth).
*/
- "has-active-workspace": false,
"has-sample-database?": undefined,
"has-user-setup": true,
"hide-embed-branding?": true,
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index 2d2a118ed32..2c8f5931759 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -741,7 +741,6 @@ export interface EnterpriseSettings extends Settings {
"remote-sync-type"?: RemoteSyncType | null;
"remote-sync-auto-import"?: boolean | null;
"remote-sync-transforms"?: boolean | null;
- "has-active-workspace": boolean;
"login-page-illustration"?: IllustrationSettingValue;
"login-page-illustration-custom"?: string;
"landing-page-illustration"?: IllustrationSettingValue;
diff --git a/frontend/src/metabase-types/api/workspace-instance.ts b/frontend/src/metabase-types/api/workspace-instance.ts
index 3a9ad694001..8c5a6f5d207 100644
--- a/frontend/src/metabase-types/api/workspace-instance.ts
+++ b/frontend/src/metabase-types/api/workspace-instance.ts
@@ -15,6 +15,10 @@ export type WorkspaceInstance = {
databases: Record<DatabaseId, WorkspaceInstanceDatabase>;
};
+export type GetCurrentWorkspaceResponse = {
+ data: WorkspaceInstance | null;
+};
+
export type TableRemappingId = number;
export type TableRemapping = {
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
index 25d49ab68cd..26e2b5474bd 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
@@ -46,7 +46,7 @@ export function DataStudioLayout({ children }: DataStudioLayoutProps) {
const {
value: _isNavbarOpened,
setValue: setIsNavbarOpened,
- isLoading,
+ isLoading: isLoadingNavbarKey,
} = useUserKeyValue({
namespace: "data_studio",
key: "isNavbarOpened",
@@ -63,7 +63,7 @@ export function DataStudioLayout({ children }: DataStudioLayoutProps) {
[isNavbarOpened],
);
- return isLoading ? (
+ return isLoadingNavbarKey ? (
<Center h="100%">
<Loader />
</Center>
@@ -94,7 +94,6 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {
const canManageWorkspaces = useSelector(
PLUGIN_WORKSPACES.canManageWorkspaces,
);
- const hasActiveWorkspace = useSelector(PLUGIN_WORKSPACES.hasActiveWorkspace);
const hasDirtyChanges = PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges();
const hasTransformDirtyChanges =
PLUGIN_REMOTE_SYNC.useHasTransformDirtyChanges();
@@ -201,20 +200,11 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {
isGated
/>
)}
- {hasActiveWorkspace && (
- <DataStudioTab
- label={t`Workspace`}
- icon="folder"
- to={Urls.workspaceInstance()}
- isSelected={currentTab === "workspaces"}
- showLabel={isNavbarOpened}
- />
- )}
- {!hasActiveWorkspace && canManageWorkspaces && (
+ {canManageWorkspaces && (
<DataStudioTab
label={t`Workspaces`}
icon="folder"
- to={Urls.workspaceList()}
+ to={Urls.workspaces()}
isSelected={currentTab === "workspaces"}
showLabel={isNavbarOpened}
/>
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx
index 0ca6ba55350..5ebadca15cc 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/common.unit.spec.tsx
@@ -122,4 +122,13 @@ describe("DataStudioLayout", () => {
expect(transformsUpsellGems).toHaveLength(0);
});
});
+
+ describe("workspaces tab", () => {
+ it("does not render the Workspaces tab on OSS", async () => {
+ setup({ remoteSyncBranch: "main" });
+
+ expect(await screen.findByTestId("data-studio-nav")).toBeInTheDocument();
+ expect(screen.queryByLabelText("Workspaces")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx
index d65a416683b..23b2ac00b8e 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/enterprise.unit.spec.tsx
@@ -2,6 +2,7 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { screen, waitFor, within } from "__support__/ui";
+import * as Urls from "metabase/urls";
import { DEFAULT_EE_SETTINGS, setup } from "./setup";
@@ -204,4 +205,35 @@ describe("DataStudioLayout", () => {
).not.toBeInTheDocument();
});
});
+
+ describe("workspaces tab", () => {
+ it("admin sees the tab and it links to the workspaces index", async () => {
+ setup({ ...DEFAULT_EE_SETTINGS, isAdmin: true });
+
+ const tab = await screen.findByLabelText("Workspaces");
+ expect(tab).toHaveAttribute("href", Urls.workspaces());
+ });
+
+ it("non-admin with manage-workspaces permission sees the tab linking to the workspaces index", async () => {
+ setup({
+ ...DEFAULT_EE_SETTINGS,
+ isAdmin: false,
+ canManageWorkspaces: true,
+ });
+
+ const tab = await screen.findByLabelText("Workspaces");
+ expect(tab).toHaveAttribute("href", Urls.workspaces());
+ });
+
+ it("non-admin without manage-workspaces permission does not see the tab", async () => {
+ setup({
+ ...DEFAULT_EE_SETTINGS,
+ isAdmin: false,
+ canManageWorkspaces: false,
+ });
+
+ expect(await screen.findByTestId("data-studio-nav")).toBeInTheDocument();
+ expect(screen.queryByLabelText("Workspaces")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx
index 696dabf9629..064158ce0af 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx
@@ -3,6 +3,7 @@ import { Route } from "react-router";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
setupCollectionsEndpoints,
+ setupGetCurrentWorkspaceEndpoint,
setupLibraryEndpoints,
setupPropertiesEndpoints,
setupRemoteSyncEndpoints,
@@ -16,6 +17,7 @@ import type {
Collection,
RemoteSyncEntity,
TokenFeatures,
+ WorkspaceInstance,
} from "metabase-types/api";
import {
createMockDirtyCardEntity,
@@ -98,12 +100,14 @@ const setupNavbarEndpoints = (isOpened = true) => {
interface StoreStateOptions {
isAdmin?: boolean;
+ canManageWorkspaces?: boolean;
remoteSyncSettings?: Partial<RemoteSyncSettings>;
tokenFeatures?: Partial<TokenFeatures>;
}
const createStoreState = ({
isAdmin = true,
+ canManageWorkspaces = false,
remoteSyncSettings = {},
tokenFeatures,
}: StoreStateOptions = {}) => {
@@ -115,6 +119,7 @@ const createStoreState = ({
permissions: {
can_access_data_model: isAdmin,
can_access_db_details: false,
+ can_manage_workspaces: canManageWorkspaces,
},
}),
settings: mockSettings({
@@ -128,6 +133,8 @@ interface SetupOpts {
remoteSyncEnabled?: boolean;
remoteSyncBranch?: string | null;
isAdmin?: boolean;
+ canManageWorkspaces?: boolean;
+ currentWorkspace?: WorkspaceInstance | null;
hasDirtyChanges?: boolean;
hasTransformDirtyChanges?: boolean;
remoteSyncTransforms?: boolean;
@@ -140,6 +147,8 @@ export const setup = ({
remoteSyncEnabled = true,
remoteSyncBranch = null,
isAdmin = true,
+ canManageWorkspaces = false,
+ currentWorkspace = null,
hasDirtyChanges = false,
hasTransformDirtyChanges = false,
remoteSyncTransforms = false,
@@ -177,6 +186,7 @@ export const setup = ({
setupDirtyEndpoints({ dirty, collections });
setupNavbarEndpoints(isNavbarOpened);
setupLibraryEndpoints(false);
+ setupGetCurrentWorkspaceEndpoint(currentWorkspace);
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
key: "upsell-remote-sync-dev-instance",
@@ -185,6 +195,7 @@ export const setup = ({
const state = createStoreState({
isAdmin,
+ canManageWorkspaces,
remoteSyncSettings,
tokenFeatures,
});
@@ -193,34 +204,20 @@ export const setup = ({
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
}
- const hasUpsell = !remoteSyncEnabled;
-
- if (hasUpsell) {
- renderWithProviders(
- <Route
- path="/"
- component={() => (
- <DataStudioLayout>
- <div data-testid="content">{"Content"}</div>
- </DataStudioLayout>
- )}
- />,
- {
- storeInitialState: state,
- withRouter: true,
- },
- );
- } else {
- renderWithProviders(
- <DataStudioLayout>
- <div data-testid="content">{"Content"}</div>
- </DataStudioLayout>,
- {
- storeInitialState: state,
- withRouter: false,
- },
- );
- }
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => (
+ <DataStudioLayout>
+ <div data-testid="content">{"Content"}</div>
+ </DataStudioLayout>
+ )}
+ />,
+ {
+ storeInitialState: state,
+ withRouter: true,
+ },
+ );
};
export const DEFAULT_EE_SETTINGS: Partial<SetupOpts> = {
@@ -229,11 +226,13 @@ export const DEFAULT_EE_SETTINGS: Partial<SetupOpts> = {
"remote_sync",
"dependencies",
"feature_level_permissions",
+ "workspaces",
],
tokenFeatures: {
remote_sync: true,
advanced_permissions: true,
library: true,
dependencies: true,
+ workspaces: true,
},
};
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts
index 365725c955b..47fe45ef93c 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts
@@ -18,7 +18,7 @@ export const getCurrentTab = (pathname: string): TabName => {
return "glossary";
case pathname.startsWith(Urls.dataStudioGitSync()):
return "git-sync";
- case pathname.startsWith(Urls.workspaceList()):
+ case pathname.startsWith(Urls.workspaces()):
return "workspaces";
case pathname.startsWith(Urls.transformJobList()):
return "jobs";
diff --git a/frontend/src/metabase/forms/components/FormFileInput/FormFileInput.tsx b/frontend/src/metabase/forms/components/FormFileInput/FormFileInput.tsx
new file mode 100644
index 00000000000..0ba06ef1b2a
--- /dev/null
+++ b/frontend/src/metabase/forms/components/FormFileInput/FormFileInput.tsx
@@ -0,0 +1,50 @@
+import { useField, useFormikContext } from "formik";
+import type { FocusEvent, Ref } from "react";
+import { forwardRef, useCallback } from "react";
+
+import type { FileInputProps } from "metabase/ui";
+import { FileInput } from "metabase/ui";
+
+export interface FormFileInputProps extends Omit<
+ FileInputProps<false>,
+ "value" | "error" | "onChange"
+> {
+ name: string;
+}
+
+export const FormFileInput = forwardRef(function FormFileInput(
+ { name, onBlur, ...props }: FormFileInputProps,
+ ref: Ref<HTMLButtonElement>,
+) {
+ const [{ value }, { error, touched }, { setValue, setTouched }] =
+ useField<File | null>(name);
+ const { validateOnMount } = useFormikContext();
+
+ const handleChange = useCallback(
+ (file: File | null) => {
+ setValue(file);
+ },
+ [setValue],
+ );
+
+ const handleBlur = useCallback(
+ (event: FocusEvent<HTMLButtonElement>) => {
+ setTouched(true);
+ onBlur?.(event);
+ },
+ [setTouched, onBlur],
+ );
+
+ return (
+ <FileInput
+ {...props}
+ ref={ref}
+ name={name}
+ value={value ?? null}
+ error={(validateOnMount || touched) && error ? error : null}
+ onChange={handleChange}
+ onBlur={handleBlur}
+ errorProps={{ role: "alert" }}
+ />
+ );
+});
diff --git a/frontend/src/metabase/forms/components/FormFileInput/index.ts b/frontend/src/metabase/forms/components/FormFileInput/index.ts
new file mode 100644
index 00000000000..b321f8f326a
--- /dev/null
+++ b/frontend/src/metabase/forms/components/FormFileInput/index.ts
@@ -0,0 +1 @@
+export * from "./FormFileInput";
diff --git a/frontend/src/metabase/forms/components/index.ts b/frontend/src/metabase/forms/components/index.ts
index cc1a4e83498..cd0167f69f0 100644
--- a/frontend/src/metabase/forms/components/index.ts
+++ b/frontend/src/metabase/forms/components/index.ts
@@ -5,6 +5,7 @@ export * from "./FormChipGroup";
export * from "./FormDateInput";
export * from "./FormErrorMessage";
export * from "./FormField";
+export * from "./FormFileInput";
export * from "./FormGroupWidget";
export * from "./FormInlineUpdater";
export * from "./FormMessage";
diff --git a/frontend/src/metabase/plugins/oss/workspaces.ts b/frontend/src/metabase/plugins/oss/workspaces.ts
index 98e2b4457d4..c80d518ae0f 100644
--- a/frontend/src/metabase/plugins/oss/workspaces.ts
+++ b/frontend/src/metabase/plugins/oss/workspaces.ts
@@ -12,7 +12,7 @@ export type AdminConnectionInfoSectionProps = {
const getDefaultWorkspaces = () => ({
canManageWorkspaces: (_state: State): boolean => false,
- hasActiveWorkspace: (_state: State): boolean => false,
+ canManageWorkspaceInstance: (_state: State): boolean => false,
getDataStudioRoutes: (): ReactNode => null,
getAdminConnectionInfoRoutes: (_IsAdmin: RouteComponent): ReactNode => null,
AdminConnectionInfoSection:
diff --git a/frontend/src/metabase/urls/workspaces.ts b/frontend/src/metabase/urls/workspaces.ts
index 55cb252d26d..9f174352aaf 100644
--- a/frontend/src/metabase/urls/workspaces.ts
+++ b/frontend/src/metabase/urls/workspaces.ts
@@ -2,14 +2,10 @@ import type { WorkspaceId } from "metabase-types/api";
const WORKSPACES_ROOT_URL = `/data-studio/workspaces`;
-export function workspaceList() {
+export function workspaces() {
return WORKSPACES_ROOT_URL;
}
export function workspace(id: WorkspaceId) {
return `${WORKSPACES_ROOT_URL}/${id}`;
}
-
-export function workspaceInstance() {
- return `${WORKSPACES_ROOT_URL}/instance`;
-}
diff --git a/frontend/test/__support__/enterprise-typed.ts b/frontend/test/__support__/enterprise-typed.ts
index f72f6588fae..ea224ada53c 100644
--- a/frontend/test/__support__/enterprise-typed.ts
+++ b/frontend/test/__support__/enterprise-typed.ts
@@ -50,6 +50,7 @@ export const ENTERPRISE_PLUGIN_NAME_MAPPING = {
content_verification: "metabase-enterprise/content_verification",
moderation: "metabase-enterprise/moderation",
tenants: "metabase-enterprise/tenants",
+ workspaces: "metabase-enterprise/workspaces",
// Embedding SDK specific plugins
sdk_notifications: "embedding-sdk-ee/notifications",
diff --git a/frontend/test/__support__/server-mocks/advanced-config.ts b/frontend/test/__support__/server-mocks/advanced-config.ts
new file mode 100644
index 00000000000..8d7ebf7e788
--- /dev/null
+++ b/frontend/test/__support__/server-mocks/advanced-config.ts
@@ -0,0 +1,5 @@
+import fetchMock from "fetch-mock";
+
+export function setupApplyAdvancedConfigEndpoint() {
+ fetchMock.post("path:/api/ee/advanced-config", 204);
+}
diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.ts
index 974a538cd10..2bc0a90cb23 100644
--- a/frontend/test/__support__/server-mocks/index.ts
+++ b/frontend/test/__support__/server-mocks/index.ts
@@ -1,5 +1,6 @@
export * from "./action";
export * from "./activity";
+export * from "./advanced-config";
export * from "./ai-entity-analysis";
export * from "./alert";
export * from "./api-key";
diff --git a/frontend/test/__support__/server-mocks/workspace-instance.ts b/frontend/test/__support__/server-mocks/workspace-instance.ts
index a84a20722e0..3b80e065087 100644
--- a/frontend/test/__support__/server-mocks/workspace-instance.ts
+++ b/frontend/test/__support__/server-mocks/workspace-instance.ts
@@ -7,10 +7,11 @@ const BASE_URL = "path:/api/ee/workspace-instance";
export function setupGetCurrentWorkspaceEndpoint(
workspace: WorkspaceInstance | null,
) {
- fetchMock.get(
- `${BASE_URL}/current`,
- workspace ?? { status: 204, body: null },
- );
+ fetchMock.get(`${BASE_URL}/current`, { data: workspace });
+}
+
+export function setupDeleteWorkspaceInstanceEndpoint() {
+ fetchMock.delete(`${BASE_URL}/current`, 204);
}
export function setupListTableRemappingsEndpoint(remappings: TableRemapping[]) {
diff --git a/src/metabase/core/config_from_file.clj b/src/metabase/core/config_from_file.clj
index 4a818b417bb..2426d6f7bf0 100644
--- a/src/metabase/core/config_from_file.clj
+++ b/src/metabase/core/config_from_file.clj
@@ -6,7 +6,7 @@
(defn init-from-file-if-code-available!
"Shim for running the config-from-file code, used by [[metabase.core.core]]. The config-from-file code only ships in
the Enterprise Edition™ JAR, so this checks whether the namespace exists, and if it does,
- invokes [[metabase-enterprise.advanced-config.file/initialize!]]; otherwise, this no-ops."
+ invokes [[metabase-enterprise.advanced-config.file/boot-initialize!]]; otherwise, this no-ops."
[]
(when (try
(classloader/require 'metabase-enterprise.advanced-config.file)
@@ -14,4 +14,4 @@
(catch Throwable _
(log/debug "metabase-enterprise.advanced-config.file not available; cannot initialize from file.")
nil))
- ((resolve 'metabase-enterprise.advanced-config.file/initialize!))))
+ ((resolve 'metabase-enterprise.advanced-config.file/boot-initialize!))))
diff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.clj
index 7654dc88071..1dd533b6ccd 100644
--- a/src/metabase/testing_api/api.clj
+++ b/src/metabase/testing_api/api.clj
@@ -25,7 +25,6 @@
[metabase.util.json :as json]
[metabase.util.log :as log]
[metabase.util.malli.schema :as ms]
- [metabase.workspaces.core :as ws]
[toucan2.core :as t2])
(:import
(com.mchange.v2.c3p0 PoolBackedDataSource)
@@ -254,25 +253,6 @@
[]
(refresh-cache-configs!))
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/workspace-instance"
- "Install a workspace config atom on this instance for E2E testing. The body
- is passed straight through to `metabase.workspaces.core/set-instance-workspace!`
- — same shape the `:workspace` section of `config.yml` resolves to at boot.
- Validation happens inside that fn against the `::ws/workspace-instance-config`
- schema. No-op on OSS."
- [_route-params _query-params body :- ::ws/workspace-instance-config]
- (ws/set-instance-workspace! body)
- {:ok true})
-
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :delete "/workspace-instance"
- "Clear the in-process workspace config atom installed by POST `/workspace-instance`.
- No-op on OSS."
- []
- (ws/clear-instance-workspace!)
- {:ok true})
-
(api.macros/defendpoint :post "/query" :- ::lib.schema/query
"Creates a query from a test query spec."
[_route-params
diff --git a/src/metabase/workspaces/core.clj b/src/metabase/workspaces/core.clj
index 0c8febc2c3a..ba30d97aee6 100644
--- a/src/metabase/workspaces/core.clj
+++ b/src/metabase/workspaces/core.clj
@@ -36,9 +36,9 @@
The OSS jar has no workspace mode (`workspace-mode?` returns false), so
the gates are no-ops. The EE impl in `metabase-enterprise.workspaces.core`
- reads the in-process workspace atom."
+ reads the `instance-workspace` setting."
(:require
- [metabase.premium-features.core :refer [defenterprise defenterprise-schema]]
+ [metabase.premium-features.core :refer [defenterprise]]
[metabase.util.malli.registry :as mr]))
;;; ----------------------------- Workspace config schemas ----------------------------------
@@ -66,9 +66,9 @@
[:output ::table-namespace]])
(mr/def ::workspace-instance-config
- "The shape stored in the EE workspace atom after the `:workspace` config.yml
- loader has resolved database names to ids. Database keys are integer ids
- (post-resolution); the wire format with name keys lives in
+ "The shape stored in the EE `instance-workspace` setting after the `:workspace`
+ config.yml loader has resolved database names to ids. Database keys are integer
+ ids (post-resolution); the wire format with name keys lives in
`metabase-enterprise.advanced-config.file.workspace`."
[:map
[:name [:string {:min 1}]]
@@ -90,23 +90,6 @@
[]
false)
-(defenterprise-schema set-instance-workspace! :- :any
- "Install the in-process workspace config atom on this instance. The shape is
- validated against `::workspace-instance-config` at the OSS boundary so a
- malformed config never reaches the EE atom or the QP / transform hooks that
- read from it.
-
- No-op on OSS — workspace mode is EE-only."
- metabase-enterprise.workspaces.core
- [_config :- ::workspace-instance-config]
- nil)
-
-(defenterprise clear-instance-workspace!
- "Clear the in-process workspace config atom. No-op on OSS."
- metabase-enterprise.workspaces.core
- []
- nil)
-
(defn check-not-in-workspace-mode!
"Throws an HTTP 400 `ex-info` if this instance is running in workspace mode.