Skip to content

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

Warn when startup encrypts legacy plaintext, and make migrations leave none behind (#81898)

Alexander Polyankin6be1b2761e73
diff --git a/resources/migrations/058_update_migrations.yaml b/resources/migrations/058_update_migrations.yaml
index dda4867225e..fe2c297fdd9 100644
--- a/resources/migrations/058_update_migrations.yaml
+++ b/resources/migrations/058_update_migrations.yaml
@@ -1321,29 +1321,6 @@ databaseChangeLog:
tableName: data_permissions
constraintName: idx_unique_data_permissions
- - changeSet:
- id: v58.2026-08-25T00:00:00
- author: ranquild
- comment: >-
- Encrypt any plaintext auth_identity.credentials rows written by the v58 password/SSO backfill (raw SQL that
- bypassed encryption), so the credentials column can be read strictly once MB_ENCRYPTION_SECRET_KEY is set.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptAuthIdentityCredentials
-
- - changeSet:
- id: v58.2026-08-25T00:00:01
- author: ranquild
- comment: >-
- Encrypt any plaintext api_key.key bcrypt hashes at rest, so the column can be read strictly once
- MB_ENCRYPTION_SECRET_KEY is set: authentication must only accept hashes written through the application, and
- the strict read enforces that by rejecting a plaintext value written directly to the app DB.
- Already-encrypted values are left untouched. On rollback the values are decrypted back to the plaintext hash,
- so a downgrade to code that reads the column directly can still verify keys.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptApiKeys
-
- changeSet:
id: v58.2026-08-25T00:00:02
author: ranquild
@@ -1596,70 +1573,6 @@ databaseChangeLog:
- sql: >-
UPDATE document SET public_uuid_prefix = NULL
- - changeSet:
- id: v58.2026-08-25T00:00:18
- author: ranquild
- comment: >-
- Encrypt any plaintext public_uuid values at rest for cards, dashboards, actions, and documents, so the column
- can be read strictly once MB_ENCRYPTION_SECRET_KEY is set: public links must only resolve to values issued by
- the application, and the strict read enforces that by rejecting a plaintext value written directly to the app
- DB. Already-encrypted values are left untouched.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptPublicUuids
-
- - changeSet:
- id: v58.2026-08-25T00:00:19
- author: ranquild
- comment: >-
- Encrypt at rest the details column of notification_recipient and pulse_channel, which stores raw external email
- recipients for alerts and dashboard subscriptions, so a plaintext value written directly to the app DB is
- rejected on the strict read once MB_ENCRYPTION_SECRET_KEY is set. Already-encrypted values are left untouched.
- On rollback the values are decrypted back to plaintext.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptNotificationAndPulseChannelDetails
-
- - changeSet:
- id: v58.2026-08-28T00:00:00
- author: ranquild
- comment: >-
- Encrypt at rest any plaintext value of the settings this release newly marks
- :encryption :when-encryption-key-set (they were previously stored plaintext), so the strict decrypting read
- added for encrypted settings accepts them once MB_ENCRYPTION_SECRET_KEY is set. Already-encrypted values are
- left untouched. Rollback decrypts them again, so a downgraded version that reads them as :encryption :no
- still sees the values.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptSettingsV58
-
- - changeSet:
- id: v58.2026-08-28T14:00:00
- author: ranquild
- comment: >-
- Encrypt at rest any plaintext values left in the columns that were encrypted long before any backfill existed:
- metabase_database details/settings, core_user.settings, channel.details, and secret.value.
- Encryption used to be write-time only, and the old startup auto-encrypt and key rotation covered only some of
- these columns, so an upgraded database can hold a mix of plaintext and encrypted rows that the strict reads
- would reject. Already-encrypted values are left untouched; without MB_ENCRYPTION_SECRET_KEY this is a no-op.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptRemainingColumns
-
- - changeSet:
- id: v58.2026-08-30T00:00:00
- author: ranquild
- comment: >-
- Encrypt at rest any plaintext value of the :setter :none settings. They default to
- :encryption :when-encryption-key-set whatever their type, so the strict decrypting read applies to them, but
- some were settable in older versions and stored plaintext back then (e.g. enable-query-caching, once an admin
- toggle saved as a plaintext boolean); such a row made restoring the settings cache fail at startup.
- Already-encrypted values are left untouched. No rollback: these settings were always meant to be encrypted,
- and a downgraded version reads them either way. Without MB_ENCRYPTION_SECRET_KEY this is a no-op.
- changes:
- - customChange:
- class: metabase.app_db.custom_migrations.EncryptSetterNoneSettingsV58
-
- changeSet:
id: v58.2026-09-01T00:00:00
author: ranquild
@@ -1682,6 +1595,46 @@ databaseChangeLog:
constraints:
nullable: true
+ - changeSet:
+ id: v58.2026-09-03T00:00:00
+ author: ranquild
+ comment: >-
+ Forget the changelog records of the Encrypt* backfill changesets this release removes: encrypting a value that a
+ previous version stored unencrypted is the startup sweep's job, and a one-shot migration cannot be relied on to
+ have done it. Keeps the changelog table in step with the changelog; a database that has not run them is
+ unaffected either way.
+ changes:
+ - sql:
+ sql: DELETE FROM ${databasechangelog.name} WHERE id IN ('v58.2026-08-25T00:00:00', 'v58.2026-08-25T00:00:01', 'v58.2026-08-25T00:00:18', 'v58.2026-08-25T00:00:19', 'v58.2026-08-28T00:00:00', 'v58.2026-08-28T14:00:00', 'v58.2026-08-30T00:00:00');
+ rollback: []
+
+ - changeSet:
+ id: v58.2026-09-03T00:00:03
+ author: ranquild
+ comment: >-
+ Delete the plaintext "unencrypted" encryption-check marker that v53.2024-12-27T17:33:54 inserted on every new
+ database, encrypted ones included, so it said nothing about the actual state. With no row the state is unknown
+ and is judged from the content; the encryption tooling writes the sentinel itself when the state changes.
+ changes:
+ - sql:
+ dbms: postgresql
+ sql: DELETE FROM setting WHERE "key" = 'encryption-check' AND value = 'unencrypted';
+ - sql:
+ dbms: mysql,mariadb
+ sql: DELETE FROM setting WHERE `key` = 'encryption-check' AND value = 'unencrypted';
+ - sql:
+ dbms: h2
+ sql: DELETE FROM setting WHERE "KEY" = 'encryption-check' AND "VALUE" = 'unencrypted';
+ rollback: []
+
+ - changeSet:
+ id: v58.2026-09-03T00:00:04
+ author: ranquild
+ comment: Fill setting.value_with_aad for the example-dashboard-id row CreateSampleContentV2 wrote before the column existed
+ changes:
+ - customChange:
+ class: "metabase.app_db.custom_migrations.BackfillExampleDashboardIdValueWithAad"
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.clj
index d7b2302b9eb..3c1b64a78da 100644
--- a/src/metabase/app_db/custom_migrations.clj
+++ b/src/metabase/app_db/custom_migrations.clj
@@ -28,6 +28,7 @@
[metabase.app-db.custom-migrations.pulse-to-notification :as pulse-to-notification]
[metabase.app-db.custom-migrations.reserve-at-symbol-user-attributes :as reserve-at-symbol-user-attributes]
[metabase.app-db.custom-migrations.util :as custom-migrations.util]
+ [metabase.app-db.setting :as mdb.setting]
[metabase.config.core :as config]
[metabase.task.bootstrap]
[metabase.util.date-2 :as u.date]
@@ -45,8 +46,7 @@
(liquibase.change Change)
(liquibase.change.custom CustomTaskChange CustomTaskRollback)
(liquibase.exception ValidationErrors)
- (liquibase.util BooleanUtil)
- (org.mindrot.jbcrypt BCrypt)))
+ (liquibase.util BooleanUtil)))
(set! *warn-on-reflection* true)
@@ -130,9 +130,13 @@
s))
s))
-(def ^:private encrypted-json-in
- "Should mirror [[metabase.models.interface/encrypted-json-in]]"
- (comp encryption/maybe-encrypt json-in))
+(defn- encrypted-json-in
+ "Serialize `v` to replace `stored`, the encrypted-json column value it was derived from, keeping the column as it
+ was: encrypted when `stored` decrypts with the current key, plaintext otherwise. A migration that rewrites a row
+ never changes whether it is encrypted at rest; the startup sweep does that, with a warning."
+ [stored v]
+ (cond-> (json-in v)
+ (encryption/decryptable-string? stored) encryption/encrypt))
(defn- encrypted-json-out
"Lenient deserialize of an encrypted-json column that tolerates plaintext at rest, for reading legacy rows during
@@ -724,9 +728,10 @@
(define-reversible-migration MigrateDatabaseOptionsToSettings
(let [update-one! (fn [{:keys [id settings options]}]
- (let [settings (encrypted-json-out settings)
+ (let [stored settings
+ settings (encrypted-json-out settings)
options (json-out options true)
- new-settings (encrypted-json-in (merge settings options))]
+ new-settings (encrypted-json-in stored (merge settings options))]
(t2/query {:update :metabase_database
:set {:settings new-settings}
:where [:= :id id]})))]
@@ -737,12 +742,13 @@
[:not= :options "{}"]
[:not= :options nil]]})))
(let [rollback-one! (fn [{:keys [id settings options]}]
- (let [settings (encrypted-json-out settings)
+ (let [stored settings
+ settings (encrypted-json-out settings)
options (json-out options true)]
(when (some? (:persist-models-enabled settings))
(t2/query {:update :metabase_database
:set {:options (json/encode (select-keys settings [:persist-models-enabled]))
- :settings (encrypted-json-in (dissoc settings :persist-models-enabled))}
+ :settings (encrypted-json-in stored (dissoc settings :persist-models-enabled))}
:where [:= :id id]}))))]
(run! rollback-one! (t2/reducible-query {:select [:id :settings :options]
:from [:metabase_database]}))))
@@ -1115,44 +1121,36 @@
;; use the table, not model/Database because we don't want to trigger the hooks
(t2/update! :metabase_database :id [:in (map :id dbs)] {:cache_field_values_schedule nil}))))
-(defn- hash-bcrypt
- "Hashes a given plaintext password using bcrypt. Should be used to hash
- passwords included in stored user credentials that are to be later verified
- using `bcrypt-credential-fn`."
- [password]
- (BCrypt/hashpw password (BCrypt/gensalt)))
-
(defn- internal-user-exists? []
(pos? (first (vals (t2/query-one {:select [:%count.*] :from :core_user :where [:= :id config/internal-mb-user-id]})))))
(define-migration CreateInternalUser
;; the internal user may have been created in a previous version for Metabase Analytics, so don't add it again if it
- ;; exists already.
+ ;; exists already. It has no password: it is inactive and can never log in, and a password would be copied into
+ ;; `auth_identity` bare by the v58 SQL changesets.
(when (not (internal-user-exists?))
- (let [salt (str (random-uuid))
- password (hash-bcrypt (str salt (random-uuid)))
- user {;; we insert the internal user ID directly because it's
- ;; deliberately high enough to not conflict with any other
- :id config/internal-mb-user-id
- :password_salt salt
- :password password
- :first_name "Metabase"
- :locale nil
- :last_login nil
- :is_active false
- :settings nil
- :type "internal"
- :is_qbnewb true
- :updated_at nil
- :reset_triggered nil
- :is_superuser false
- :login_attributes nil
- :reset_token nil
- :last_name "Internal"
- :date_joined :%now
- :sso_source nil
- :is_datasetnewb true}]
+ (let [user {;; we insert the internal user ID directly because it's
+ ;; deliberately high enough to not conflict with any other
+ :id config/internal-mb-user-id
+ :password_salt nil
+ :password nil
+ :first_name "Metabase"
+ :locale nil
+ :last_login nil
+ :is_active false
+ :settings nil
+ :type "internal"
+ :is_qbnewb true
+ :updated_at nil
+ :reset_triggered nil
+ :is_superuser false
+ :login_attributes nil
+ :reset_token nil
+ :last_name "Internal"
+ :date_joined :%now
+ :sso_source nil
+ :is_datasetnewb true}]
(t2/query {:insert-into :core_user :values [user]}))
(let [all-users-id (first (vals (t2/query-one {:select [:id] :from :permissions_group :where [:= :name "All Users"]})))
perms-group {:user_id config/internal-mb-user-id :group_id all-users-id}]
@@ -1768,7 +1766,8 @@
(define-reversible-migration MigrateClickHouseDetailsToMultiDB
(let [update-one! (fn [{:keys [id details]}]
- (let [decrypted-details (encrypted-json-out details)
+ (let [stored details
+ decrypted-details (encrypted-json-out details)
scan-all-databases? (boolean (:scan-all-databases decrypted-details))
db-filters-type (if scan-all-databases? "all" "inclusion")
dbname (:dbname decrypted-details)
@@ -1780,7 +1779,7 @@
{:db-filters-type db-filters-type}
(when-not scan-all-databases?
{:db-filters-patterns db-filters-patterns}))
- encrypted-details (encrypted-json-in new-details)]
+ encrypted-details (encrypted-json-in stored new-details)]
(t2/query {:update :metabase_database
:set {:details encrypted-details}
:where [:= :id id]})))]
@@ -1788,12 +1787,13 @@
:from [:metabase_database]
:where [:= :engine "clickhouse"]})))
(let [rollback-one! (fn [{:keys [id details]}]
- (let [decrypted-details (encrypted-json-out details)
+ (let [stored details
+ decrypted-details (encrypted-json-out details)
new-details (dissoc decrypted-details
:enable-multiple-db
:db-filters-type
:db-filters-patterns)
- encrypted-details (encrypted-json-in new-details)]
+ encrypted-details (encrypted-json-in stored new-details)]
(t2/query {:update :metabase_database
:set {:details encrypted-details}
:where [:= :id id]})))]
@@ -2246,224 +2246,12 @@
(llm-providers/migrate-up!)
(llm-providers/migrate-down!))
-(define-migration EncryptAuthIdentityCredentials
- (when (encryption/default-encryption-enabled?)
- (run! (fn [{:keys [id credentials]}]
- (when (not (encryption/decryptable-string? credentials))
- (t2/query {:update :auth_identity
- :set {:credentials (encryption/encrypt credentials)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :credentials]
- :from [:auth_identity]
- :where [:!= :credentials nil]}))))
-
-(define-reversible-migration EncryptApiKeys
- (when (encryption/default-encryption-enabled?)
- (run! (fn [{:keys [id] k :key}]
- (when (not (encryption/decryptable-string? k))
- (t2/query {:update :api_key
- :set {:key (encryption/encrypt k)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :key]
- :from [:api_key]
- :where [:!= :key nil]})))
- (when (encryption/default-encryption-enabled?)
- (run! (fn [{:keys [id] k :key}]
- (when (encryption/decryptable-string? k)
- (t2/query {:update :api_key
- :set {:key (encryption/decrypt k)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :key]
- :from [:api_key]
- :where [:!= :key nil]}))))
-
-(defn encrypt-settings
- "Encrypt at rest the plaintext value of every setting in `setting-keys`, so the strict decrypting read of an
- `:encryption :when-encryption-key-set` setting accepts it. A value already encrypted with the current key (e.g. by a
- key rotation, which re-encrypts every setting) is left untouched -- decided by decrypting it, never by its shape,
- since plaintext can look like ciphertext (see [[metabase.util.encryption/possibly-encrypted-string?]]). A blank value
- is encrypted too, since a strict read would reject it as plaintext. No-op without an encryption key. Use it as the
- forward body of a migration that marks existing settings as encrypted, paired with [[decrypt-settings]].
-
- `setting-keys` must be exactly the settings whose stored value could be plaintext as of the release the migration
- ships in: the ones whose `:encryption` went from `:no` to `:when-encryption-key-set` in it, or whose rows predate
- their encryption (see [[encrypted-setter-none-settings-v58]])."
- [setting-keys]
- (when (encryption/default-encryption-enabled?)
- (run! (fn [{:keys [key value]}]
- (when (not (encryption/decryptable-string? value))
- (t2/query {:update :setting
- :set {:value (encryption/encrypt value)}
- :where [:= :key key]})))
- (t2/reducible-query {:select [:key :value]
- :from [:setting]
- :where [:and [:in :key setting-keys] [:!= :value nil]]}))))
-
-(defn decrypt-settings
- "Reverse of [[encrypt-settings]]: store the plaintext value of every setting in `setting-keys` that is encrypted with
- the current key, so a downgraded version that reads them as `:encryption :no` still sees them. Plaintext values,
- including ones that merely look like ciphertext, are left untouched."
- [setting-keys]
- (when (encryption/default-encryption-enabled?)
- (run! (fn [{:keys [key value]}]
- (when (encryption/decryptable-string? value)
- (t2/query {:update :setting
- :set {:value (encryption/decrypt value)}
- :where [:= :key key]})))
- (t2/reducible-query {:select [:key :value]
- :from [:setting]
- :where [:and [:in :key setting-keys] [:!= :value nil]]}))))
-
-(def ^:private encrypted-settings-v58
- "Every registered setting stored in the setting table that is encrypted at rest as of v58: the ones whose
- `:encryption` went from `:no` to `:when-encryption-key-set` in v58, and the previously-encrypted ones, whose rows
- can still be plaintext from the era when encryption was write-time only. Settings with `:setter :none` are listed
- separately in [[encrypted-setter-none-settings-v58]]; rows for settings that no longer exist are left alone.
- Settings that are neither secret nor integrity-critical are deliberately absent -- they are `:encryption :no`, and
- the startup reconcile decrypts any row of theirs this migration encrypted before they were reclassified.
- `encrypt-settings-test` checks this list against the registry."
- ["admin-email" "ai-service-base-url" "allowed-iframe-hosts"
- "api-key" "csp-img-allowed-hosts" "custom-geojson"
- "database-replication-connections" "ee-embedding-provider" "ee-embedding-service-api-key"
- "ee-embedding-service-base-url" "email-from-address" "email-from-address-override"
- "email-from-name" "email-reply-to" "email-smtp-host"
- "email-smtp-host-override" "email-smtp-password" "email-smtp-password-override"
- "email-smtp-port" "email-smtp-port-override" "email-smtp-security"
- "email-smtp-security-override" "email-smtp-username" "email-smtp-username-override"
- "embedding-app-origins-interactive" "embedding-app-origins-sdk" "embedding-secret-key"
- "google-auth-auto-create-accounts-domain" "google-auth-client-id" "gsheets"
- "jwt-attribute-email" "jwt-attribute-firstname" "jwt-attribute-groups"
- "jwt-attribute-lastname" "jwt-attribute-tenant" "jwt-attribute-tenant-attributes"
- "jwt-group-mappings" "jwt-identity-provider-uri" "jwt-shared-secret"
- "ldap-attribute-email" "ldap-attribute-firstname" "ldap-attribute-lastname"
- "ldap-bind-dn" "ldap-group-base" "ldap-group-mappings"
- "ldap-group-membership-filter" "ldap-host" "ldap-password"
- "ldap-port" "ldap-sync-user-attributes-blacklist" "ldap-user-base"
- "ldap-user-filter" "llm-anthropic-api-base-url" "llm-anthropic-api-key"
- "llm-azure-api-base-url" "llm-azure-api-key" "llm-bedrock-access-key-id"
- "llm-bedrock-secret-access-key" "llm-bedrock-session-token" "llm-deepseek-api-base-url"
- "llm-deepseek-api-key" "llm-google-api-base-url" "llm-google-oauth-access-token"
- "llm-google-service-account-key" "llm-mistral-api-base-url" "llm-mistral-api-key"
- "llm-moonshot-api-base-url" "llm-moonshot-api-key" "llm-openai-api-base-url"
- "llm-openai-api-key" "llm-openrouter-api-base-url" "llm-openrouter-api-key"
- "llm-providers" "llm-proxy-base-url" "llm-vllm-api-base-url"
- "llm-vllm-api-key" "llm-zai-api-base-url" "llm-zai-api-key"
- "map-tile-server-url" "mcp-apps-cors-custom-origins" "mcp-apps-cors-enabled-clients"
- "metabot-chat-system-prompt" "metabot-nlq-system-prompt" "metabot-slack-signing-secret"
- "metabot-sql-system-prompt" "metaplow-url" "mfa-challenge-signing-key"
- "migration-dump-file" "notification-link-base-url" "oidc-providers"
- "premium-embedding-token" "python-runner-api-token" "python-runner-url"
- "python-storage-s-3-access-key" "python-storage-s-3-container-endpoint" "python-storage-s-3-endpoint"
- "python-storage-s-3-secret-key" "remote-sync-branch" "remote-sync-token"
- "remote-sync-url" "report-timezone" "saml-application-name"
- "saml-attribute-email" "saml-attribute-firstname" "saml-attribute-group"
- "saml-attribute-lastname" "saml-attribute-tenant" "saml-group-mappings"
- "saml-identity-provider-certificate" "saml-identity-provider-issuer" "saml-identity-provider-slo-uri"
- "saml-identity-provider-uri" "saml-keystore-alias" "saml-keystore-password"
- "saml-keystore-path" "sdk-encryption-validation-key" "search-language"
- "security-center-email-recipients" "security-center-slack-channel" "session-timeout"
- "site-url" "slack-app-token" "slack-bug-report-channel"
- "slack-connect-attribute-team-id" "slack-connect-authentication-mode" "slack-connect-client-id"
- "slack-connect-client-secret" "slack-files-channel" "snowplow-url"
- "source-address-header" "store-api-url" "store-url"
- "subscription-allowed-domains"])
-
-(define-reversible-migration EncryptSettingsV58
- (encrypt-settings encrypted-settings-v58)
- (decrypt-settings encrypted-settings-v58))
-
-(def ^:private encrypted-setter-none-settings-v58
- "The `:setter :none` settings that are encrypted at rest: each is either a secret or a value whose integrity
- decides who gets access (`setup-token` creates the first admin, `support-access-grant-email` drives creation of a
- support superuser, `site-uuid-for-unsubscribing-url` salts unsubscribe URLs, `mcp-embedding-signing-secret` signs
- embedding tokens, `tracing-endpoint` decides where telemetry is sent). Their rows can be plaintext from before they
- were encrypted, which the strict read rejects -- and since the settings cache restores the whole table at once, one
- such row took every setting down with it. `encrypt-setter-none-settings-test` checks these names are listed."
- ["mcp-embedding-signing-secret" "setup-token" "site-uuid-for-unsubscribing-url"
- "support-access-grant-email" "tracing-endpoint"])
-
-(define-migration EncryptSetterNoneSettingsV58
- (encrypt-settings encrypted-setter-none-settings-v58))
-
-(define-reversible-migration EncryptPublicUuids
- (when (encryption/default-encryption-enabled?)
- (doseq [table [:report_card :report_dashboard :action :document]]
- (run! (fn [{:keys [id public_uuid]}]
- (when (not (encryption/decryptable-string? public_uuid))
- (t2/query {:update table
- :set {:public_uuid (encryption/encrypt public_uuid)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :public_uuid]
- :from [table]
- :where [:!= :public_uuid nil]}))))
- (when (encryption/default-encryption-enabled?)
- (doseq [table [:report_card :report_dashboard :action :document]]
- (run! (fn [{:keys [id public_uuid]}]
- (when (encryption/decryptable-string? public_uuid)
- (t2/query {:update table
- :set {:public_uuid (encryption/decrypt public_uuid)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :public_uuid]
- :from [table]
- :where [:!= :public_uuid nil]})))))
-
-(define-reversible-migration EncryptNotificationAndPulseChannelDetails
- (when (encryption/default-encryption-enabled?)
- (doseq [table [:notification_recipient :pulse_channel]]
- (run! (fn [{:keys [id details]}]
- (when (not (encryption/decryptable-string? details))
- (t2/query {:update table
- :set {:details (encryption/encrypt details)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :details]
- :from [table]
- :where [:!= :details nil]}))))
- (when (encryption/default-encryption-enabled?)
- (doseq [table [:notification_recipient :pulse_channel]]
- (run! (fn [{:keys [id details]}]
- (when (encryption/decryptable-string? details)
- (t2/query {:update table
- :set {:details (encryption/decrypt details)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id :details]
- :from [table]
- :where [:!= :details nil]})))))
-
-(def ^:private encrypt-remaining-columns-v58
- "Encrypted-at-rest string columns that predate any backfill: pre-v53 encryption was write-time only, and the
- v53-v62 startup auto-encrypt and pre-v63 key rotation covered only `metabase_database.details`, `setting`, and
- `secret`, so an upgraded database can hold a mix of plaintext and encrypted rows within one of these columns.
- Columns newer than v58 (`metabase_database.write_data_details` and later) are not listed: they do not exist yet
- when this changeset runs on an older database."
- [[:metabase_database :details]
- [:metabase_database :settings]
- [:core_user :settings]
- [:channel :details]])
-
-(defn- secret-value->bytes ^bytes [v]
- (cond
- (bytes? v) v
- (instance? java.sql.Blob v) (.getBytes ^java.sql.Blob v 0 (.length ^java.sql.Blob v))
- :else nil))
-
-(define-migration EncryptRemainingColumns
- (when (encryption/default-encryption-enabled?)
- (doseq [[table column] encrypt-remaining-columns-v58]
- (run! (fn [{:keys [id value]}]
- (when (and (string? value)
- (not (encryption/possibly-encrypted-string? value)))
- (t2/query {:update table
- :set {column (encryption/maybe-encrypt value)}
- :where [:= :id id]})))
- (t2/reducible-query {:select [:id [column :value]]
- :from [table]
- :where [:!= column nil]})))
- (run! (fn [{:keys [id value]}]
- (let [value (secret-value->bytes value)]
- (when (and value (not (encryption/possibly-encrypted-bytes? value)))
- (t2/query {:update :secret
- :set {:value (encryption/maybe-encrypt-bytes value)}
- :where [:= :id id]}))))
- (t2/reducible-query {:select [:id :value]
- :from [:secret]
- :where [:!= :value nil]}))))
+(define-migration BackfillExampleDashboardIdValueWithAad
+ ;; `CreateSampleContentV2` runs before `setting.value_with_aad` exists, so it writes the setting's legacy `value` only.
+ (when-let [value (:value (t2/query-one {:select [:value]
+ :from [:setting]
+ :where [:and [:= :key "example-dashboard-id"] [:= :value_with_aad nil]]}))]
+ (t2/query {:update :setting
+ :set {:value_with_aad (encryption/maybe-encrypt (encryption/maybe-decrypt value)
+ {:aad (mdb.setting/setting-aad "example-dashboard-id")})}
+ :where [:= :key "example-dashboard-id"]})))
diff --git a/src/metabase/app_db/custom_migrations/llm_providers.clj b/src/metabase/app_db/custom_migrations/llm_providers.clj
index 4ea6b3457b1..2794c9ddbf8 100644
--- a/src/metabase/app_db/custom_migrations/llm_providers.clj
+++ b/src/metabase/app_db/custom_migrations/llm_providers.clj
@@ -11,6 +11,7 @@
Migrations must not call application code — see the `metabase.app-db.custom-migrations` namespace docstring."
(:require
[clojure.string :as str]
+ [metabase.app-db.setting :as mdb.setting]
[metabase.util.encryption :as encryption]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -102,11 +103,16 @@
(not-empty (str/trim value))))
(defn- write-setting!
- "Writes `value` for `setting-key`, encrypted only when `encrypt?` — a setting declared `:encryption :no` should
- not come out of a downgrade holding ciphertext, even though reads would decrypt it opportunistically."
+ "Writes `value` for `setting-key`, in both `value` and `value_with_aad`, encrypted only when `encrypt?` — a setting
+ declared `:encryption :no` should not come out of a downgrade holding ciphertext, even though reads would decrypt it
+ opportunistically."
[setting-key value encrypt?]
(t2/query {:delete-from :setting :where [:= :key setting-key]})
- (t2/insert! :setting {:key setting-key :value (cond-> value encrypt? encryption/maybe-encrypt)}))
+ (t2/query {:insert-into :setting
+ :values [{:key setting-key
+ :value (cond-> value encrypt? encryption/maybe-encrypt)
+ :value_with_aad (cond-> value
+ encrypt? (encryption/maybe-encrypt {:aad (mdb.setting/setting-aad setting-key)}))}]}))
;;; ------------------------------------------------------ Up ------------------------------------------------------
diff --git a/src/metabase/app_db/db.clj b/src/metabase/app_db/db.clj
new file mode 100644
index 00000000000..a30a97dc329
--- /dev/null
+++ b/src/metabase/app_db/db.clj
@@ -0,0 +1,71 @@
+(ns metabase.app-db.db
+ "Application database queries for the app-db module's encryption and setting storage. Every function here is a direct
+ Toucan 2 call with no additional logic, so no other namespace in the module runs a query itself -- except the custom
+ migrations, which keep their own, frozen at the version they shipped in. Every write is a plain `t2/query` rather
+ than a Toucan DML statement: the cloud-migration guard on Toucan DML reads `read-only-mode` through the Setting model
+ first, and while rows are being re-encrypted a setting row can be plaintext under a key, or ciphertext under a key
+ not yet in effect, which that model's strict read rejects."
+ (:require
+ [toucan2.core :as t2]))
+
+(def ^:private unmigrated-settings-where
+ [:and [:= :value_with_aad nil] [:not= :value nil] [:not= :value ""]])
+
+(defn setting-value
+ "The legacy `value` of the setting row with `setting-key`, or nil."
+ [setting-key]
+ (t2/select-one-fn :value :setting :key setting-key))
+
+(defn settings
+ "Every setting row, raw."
+ []
+ (t2/select :setting))
+
+(defn reducible-setting-values-with-aad
+ "A reducible of the key and `value_with_aad` of every setting row that has one."
+ []
+ (t2/reducible-select [:setting :key :value_with_aad] {:where [:!= :value_with_aad nil]}))
+
+(defn unmigrated-settings?
+ "Whether any setting row has a non-blank `value` but no `value_with_aad`."
+ []
+ (t2/exists? :setting {:where unmigrated-settings-where}))
+
+(defn unmigrated-settings
+ "Every setting row with a non-blank `value` but no `value_with_aad`, locked for update."
+ []
+ (t2/select :setting {:where unmigrated-settings-where, :for :update}))
+
+(defn insert-setting!
+ "Insert a setting row for `setting-key` holding `value` and `value-with-aad`."
+ [setting-key value value-with-aad]
+ (t2/query {:insert-into :setting
+ :values [{:key setting-key, :value value, :value_with_aad value-with-aad}]}))
+
+(defn update-setting-values!
+ "Set the columns in `changes` -- `:value` and/or `:value_with_aad`, nil writing NULL -- of the setting row with
+ `setting-key`."
+ [setting-key changes]
+ (t2/query {:update :setting
+ :set (select-keys changes [:value :value_with_aad])
+ :where [:= :key setting-key]}))
+
+(defn delete-setting!
+ "Delete the setting row with `setting-key`."
+ [setting-key]
+ (t2/query {:delete-from :setting, :where [:= :key setting-key]}))
+
+(defn reducible-column-values
+ "A reducible of the id and `column` value of every row of `table`."
+ [table column]
+ (t2/reducible-select [table :id [column :value]]))
+
+(defn update-column-value!
+ "Set `column` of the row of `table` with `id` to `value`."
+ [table column id value]
+ (t2/query {:update table, :set {column value}, :where [:= :id id]}))
+
+(defn delete-query-cache!
+ "Delete every cached query result."
+ []
+ (t2/query {:delete-from :query_cache}))
diff --git a/src/metabase/app_db/encryption.clj b/src/metabase/app_db/encryption.clj
index 2fb04adfef6..ca4d9f749df 100644
--- a/src/metabase/app_db/encryption.clj
+++ b/src/metabase/app_db/encryption.clj
@@ -1,9 +1,10 @@
(ns metabase.app-db.encryption
- "Encrypting, decrypting, and re-keying the application database at rest. Every write here is a plain `t2/query`
- rather than a Toucan DML statement: the cloud-migration guard on Toucan DML reads `read-only-mode` through the
- Setting model first, and while rows are being re-encrypted a setting row can be plaintext under a key, or ciphertext
- under a key not yet in effect, which that model's strict read rejects."
+ "Encrypting, decrypting, and re-keying the application database at rest. Every write goes through
+ [[metabase.app-db.db]] as a plain `t2/query` rather than a Toucan DML statement: the cloud-migration guard on Toucan
+ DML reads `read-only-mode` through the Setting model first, and while rows are being re-encrypted a setting row can
+ be plaintext under a key, or ciphertext under a key not yet in effect, which that model's strict read rejects."
(:require
+ [metabase.app-db.db :as mdb.db]
[metabase.app-db.query :as mdb.query]
[metabase.app-db.setting :as mdb.setting]
[metabase.util :as u]
@@ -76,13 +77,14 @@
:valid - a key is set and the sentinel decrypts to a UUID with it, so the key is correct
:invalid - the sentinel exists but does not decrypt (wrong or unset key, corruption)
:absent - no sentinel: a `setting` table that does not exist yet (before migrations on a fresh database), no
- row, or the plaintext \"unencrypted\" marker (inserted by the v53 migration, and written back when
- the database is decrypted) -- an explicit statement of the same thing a missing row means
+ row, or the plaintext \"unencrypted\" marker (written when the database is decrypted; a v53 changeset
+ also inserts it on a new database and a v58 one deletes it again) -- an explicit statement of the same
+ thing a missing row means
Read raw, from the legacy `value` column: this runs before migrations, and `value` is the one column every version
writes the sentinel to."
[]
- (let [raw (u/ignore-exceptions (t2/select-one-fn :value :setting :key encryption-check-key))]
+ (let [raw (u/ignore-exceptions (mdb.db/setting-value encryption-check-key))]
(cond
(or (nil? raw) (= raw "unencrypted"))
:absent
@@ -124,7 +126,7 @@
(decryptable? value) :decryptable
:else (reduced :not-decryptable)))
:none
- (t2/reducible-select [table [column :value]]))
+ (mdb.db/reducible-column-values table column))
(catch Exception e
(if (column-exists? table column)
(throw e)
@@ -161,11 +163,10 @@
from the same database."
[encrypt-fn encrypt-setting-fn]
(let [sentinel (if encrypt-fn (str (random-uuid)) "unencrypted")]
- (t2/query {:delete-from :setting, :where [:= :key encryption-check-key]})
- (t2/query {:insert-into :setting
- :values [{:key encryption-check-key
- :value (cond-> sentinel encrypt-fn encrypt-fn)
- :value_with_aad (cond-> sentinel encrypt-setting-fn (encrypt-setting-fn encryption-check-key))}]})))
+ (mdb.db/delete-setting! encryption-check-key)
+ (mdb.db/insert-setting! encryption-check-key
+ (cond-> sentinel encrypt-fn encrypt-fn)
+ (cond-> sentinel encrypt-setting-fn (encrypt-setting-fn encryption-check-key)))))
(defn- encrypt-setting
"A function of a string and a setting key that encrypts the string the way `setting.value_with_aad` holds it: under
@@ -284,8 +285,8 @@
"{}")
(throw (ex-info (trs "Can''t decrypt app db with MB_ENCRYPTION_SECRET_KEY")
{:table table, :id id, :column column} e)))))]
- (t2/query {:update table, :set {column (encrypt-str-fn decrypted)}, :where [:= :id id]}))))
- (t2/reducible-select [table :id [column :value]])))
+ (mdb.db/update-column-value! table column id (encrypt-str-fn decrypted)))))
+ (mdb.db/reducible-column-values table column)))
(defn- reencrypt-encrypted-bytes-column!
"Re-encrypt a `^bytes` `column` for every row in `table` using `encrypt-bytes-fn`. See `encrypted-bytes-columns`.
@@ -300,37 +301,64 @@
(catch Throwable e
(throw (ex-info (trs "Can''t decrypt app db with MB_ENCRYPTION_SECRET_KEY")
{:table table, :id id, :column column} e))))]
- (t2/query {:update table, :set {column (encrypt-bytes-fn decrypted)}, :where [:= :id id]}))))
- (t2/reducible-select [table :id [column :value]])))
+ (mdb.db/update-column-value! table column id (encrypt-bytes-fn decrypted)))))
+ (mdb.db/reducible-column-values table column)))
+
+(defn- legacy-unencrypted-string?
+ "Whether `value`, read from an encrypted-at-rest string column, is legacy plaintext: MB_ENCRYPTION_SECRET_KEY is set
+ and `value` is a string that does not decrypt with it (under `opts`, e.g. `:aad`), so a previous version of Metabase
+ must have stored it unencrypted."
+ ([value]
+ (legacy-unencrypted-string? value nil))
+ ([value opts]
+ (and (encryption/default-encryption-enabled?)
+ (string? value)
+ (not (encryption/decryptable-string? value opts)))))
+
+(defn- handle-legacy-unencrypted-values!
+ "What happens when legacy values that a previous version of Metabase stored unencrypted are found in `location` (a
+ `table.column`), before they are encrypted: for now a warning."
+ [location]
+ (log/warnf "Encrypting legacy values in %s that a previous version of Metabase stored unencrypted." location))
(defn encrypt-plaintext-columns!
- "Encrypt at rest any plaintext value in the encrypted-at-rest string columns. Runs on every startup: the one-shot
- encryption backfill migrations cannot be relied on to have done this -- run without MB_ENCRYPTION_SECRET_KEY (the
- `migrate` command does not check the key) they are recorded as executed while doing nothing, a boot of an older
- version re-writes these columns through its own plaintext-era transforms (e.g. notification seeding re-creates
- `notification_recipient.details` rows every boot), and `load-from-h2` copies a decrypted dump's values verbatim.
- A value that decrypts with the current key is left byte-identical; whether a value is encrypted is
- decided by [[encryption/decryptable-string?]] (actually decrypting), never by shape. The `^bytes` columns are not
- scanned: every shipped version writes those encrypted, so they cannot regress this way. No-op when
+ "Encrypt at rest any plaintext value in the encrypted-at-rest string columns. Runs on every startup, and is the only
+ backfill of these columns -- the one-shot `Encrypt*` migrations are no-ops, since a migration cannot be relied on to
+ do this: run without MB_ENCRYPTION_SECRET_KEY (the `migrate` command does not check the key) it is recorded as
+ executed while doing nothing, a boot of an older version re-writes these columns through its own plaintext-era
+ transforms (e.g. notification seeding re-creates `notification_recipient.details` rows every boot), and
+ `load-from-h2` copies a decrypted dump's values verbatim. A value that decrypts with the current key is left
+ byte-identical; whether a value is encrypted is decided by [[encryption/decryptable-string?]] (actually decrypting),
+ never by shape. Streams each column, warning once per column before its first row is encrypted. The `^bytes`
+ columns are not scanned: every shipped version writes those encrypted, so they cannot regress this way. No-op when
MB_ENCRYPTION_SECRET_KEY is not set."
[]
(when (encryption/default-encryption-enabled?)
(t2/with-transaction [_conn]
- (doseq [[table column] encrypted-string-columns]
- (run! (fn [{:keys [id value]}]
- (when (and (string? value)
- (not (encryption/decryptable-string? value)))
- (t2/query {:update table, :set {column (encryption/encrypt value)}, :where [:= :id id]})))
- (t2/reducible-select [table :id [column :value]] {:where [:!= column nil]})))
- ;; `setting.value_with_aad` is bound to its row, so it is checked and encrypted under each row's own AAD
- (let [encrypt-setting-fn (encrypt-setting nil)]
- (run! (fn [{:keys [key value_with_aad]}]
- (when (and (string? value_with_aad)
- (not (encryption/decryptable-string? value_with_aad {:aad (mdb.setting/setting-aad key)})))
- (t2/query {:update :setting
- :set {:value_with_aad (encrypt-setting-fn value_with_aad key)}
- :where [:= :key key]})))
- (t2/reducible-select [:setting :key :value_with_aad] {:where [:!= :value_with_aad nil]}))))))
+ (letfn [(encrypt-legacy-values! [location legacy? encrypt-row! rows]
+ (reduce (fn [handled? row]
+ (if (legacy? row)
+ (do (when-not handled?
+ (handle-legacy-unencrypted-values! location))
+ (encrypt-row! row)
+ true)
+ handled?))
+ false
+ rows))]
+ (doseq [[table column] encrypted-string-columns]
+ (encrypt-legacy-values! (str (name table) "." (name column))
+ (comp legacy-unencrypted-string? :value)
+ (fn [{:keys [id value]}]
+ (mdb.db/update-column-value! table column id (encryption/encrypt value)))
+ (mdb.db/reducible-column-values table column)))
+ ;; `setting.value_with_aad` is bound to its row, so it is checked and encrypted under each row's own AAD
+ (let [encrypt-setting-fn (encrypt-setting nil)]
+ (encrypt-legacy-values! "setting.value_with_aad"
+ (fn [{:keys [key value_with_aad]}]
+ (legacy-unencrypted-string? value_with_aad {:aad (mdb.setting/setting-aad key)}))
+ (fn [{:keys [key value_with_aad]}]
+ (mdb.db/update-setting-values! key {:value_with_aad (encrypt-setting-fn value_with_aad key)}))
+ (mdb.db/reducible-setting-values-with-aad)))))))
(defn- do-encryption
"Encrypt or decrypt the db using the current `MB_ENCRYPTION_SECRET_KEY` to read data.
@@ -357,24 +385,21 @@
;;
;; Both columns are re-encrypted: `value_with_aad` under each row's own AAD, and `value` because a version
;; predating that column reads it, so a rollback must not land on ciphertext under the old key.
- (doseq [{:keys [key value value_with_aad]} (t2/select :setting)]
+ (doseq [{:keys [key value value_with_aad]} (mdb.db/settings)]
(case key
"settings-last-updated" (let [now (mdb.query/current-timestamp-string db-type)]
- (t2/query {:update :setting
- :set {:value now
- :value_with_aad (encrypt-setting-fn now key)}
- :where [:= :key key]}))
+ (mdb.db/update-setting-values! key {:value now, :value_with_aad (encrypt-setting-fn now key)}))
"encryption-check" nil
(let [aad-opts {:aad (mdb.setting/setting-aad key)}
changes (cond-> {}
(seq value) (assoc :value (encrypt-str-fn (encryption/maybe-decrypt-accepting-plaintext value)))
(seq value_with_aad) (assoc :value_with_aad (encrypt-setting-fn (encryption/maybe-decrypt-accepting-plaintext value_with_aad aad-opts) key)))]
(when (seq changes)
- (t2/query {:update :setting, :set changes, :where [:= :key key]})))))
+ (mdb.db/update-setting-values! key changes)))))
(replace-encryption-check! (when encrypting? encrypt-str-fn) (when encrypting? encrypt-setting-fn))
(doseq [[table column] encrypted-bytes-columns]
(reencrypt-encrypted-bytes-column! table column encrypt-bytes-fn))
- (t2/query {:delete-from :query_cache}))))
+ (mdb.db/delete-query-cache!))))
(defn encrypt-db
"Encrypt the db using the current `MB_ENCRYPTION_SECRET_KEY` to read existing data, and the passed `to-key` to re-encrypt.
diff --git a/src/metabase/app_db/setting.clj b/src/metabase/app_db/setting.clj
index 13016abdf2c..2e8dd0bce71 100644
--- a/src/metabase/app_db/setting.clj
+++ b/src/metabase/app_db/setting.clj
@@ -6,7 +6,7 @@
the model never does: the `settings-last-updated` marker and the `encryption-check` sentinel."
(:require
[buddy.core.codecs :as codecs]
- [metabase.util :as u]
+ [metabase.app-db.db :as mdb.db]
[metabase.util.encryption :as encryption]
[metabase.util.log :as log]
[toucan2.core :as t2]))
@@ -28,23 +28,16 @@
`value` says beside it -- nothing in this version reads `value`, and a version that does reconciles it at its own
startup.
- Reads and writes the table directly, never through the model: the model's read is the strict one this fills in
- for, and the cloud-migration guard on Toucan DML reads `read-only-mode` through it before every update -- a row that
- may itself be among those being filled in."
+ Whether a `value` is encrypted is decided by decrypting it, never by its shape: a plaintext value that merely looks
+ like ciphertext is a value too. Reads and writes the table directly, never through the model: the model's read is
+ the strict one this fills in for, and the cloud-migration guard on Toucan DML reads `read-only-mode` through it
+ before every update -- a row that may itself be among those being filled in."
[]
(let [filled (atom 0)]
(t2/with-transaction [_conn]
- (doseq [{:keys [key value]} (t2/select :setting
- {:where [:and
- [:= :value_with_aad nil]
- [:not= :value nil]
- [:not= :value ""]]
- :for :update})
- :let [plain (u/ignore-exceptions (encryption/maybe-decrypt-accepting-plaintext value))]
- :when (some? plain)]
+ (doseq [{:keys [key value]} (mdb.db/unmigrated-settings)
+ :let [plain (if (encryption/decryptable-string? value) (encryption/decrypt value) value)]]
(swap! filled inc)
- (t2/query {:update :setting
- :set {:value_with_aad (encryption/maybe-encrypt plain {:aad (setting-aad key)})}
- :where [:= :key key]})))
+ (mdb.db/update-setting-values! key {:value_with_aad (encryption/maybe-encrypt plain {:aad (setting-aad key)})})))
(when (pos? @filled)
(log/infof "Filled in the authenticated value of %d setting(s) from their value." @filled))))
diff --git a/src/metabase/app_db/setup.clj b/src/metabase/app_db/setup.clj
index 219a17d3abb..f16c20b4de6 100644
--- a/src/metabase/app_db/setup.clj
+++ b/src/metabase/app_db/setup.clj
@@ -14,12 +14,14 @@
[honey.sql :as sql]
[metabase.app-db.connection :as mdb.connection]
[metabase.app-db.custom-migrations :as custom-migrations]
+ [metabase.app-db.db :as mdb.db]
[metabase.app-db.encryption :as mdb.encryption]
[metabase.app-db.jdbc-protocols :as mdb.jdbc-protocols]
[metabase.app-db.liquibase :as liquibase]
[metabase.app-db.setting :as mdb.setting]
[metabase.config.core :as config]
[metabase.util :as u]
+ [metabase.util.encryption :as encryption]
[metabase.util.honey-sql-2]
[metabase.util.i18n :refer [trs]]
[metabase.util.log :as log]
@@ -251,6 +253,10 @@
encryption commands -- and a JVM that skipped the repair would read every setting as nil."
[db-state]
(when (#{:encrypted :unencrypted :fresh :pre-sentinel} db-state)
+ (when (mdb.db/unmigrated-settings?)
+ (log/warn (str "Some settings were saved by an older version of Metabase and are being converted to the current "
+ "storage format" (when (encryption/default-encryption-enabled?) ", encrypted with MB_ENCRYPTION_SECRET_KEY")
+ ". This is expected once after an upgrade.")))
(mdb.setting/migrate-settings!)))
;; TODO -- consider renaming to something like `verify-connection-and-migrate!`
diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.clj
index 75c58e690b6..38e043016f3 100644
--- a/test/metabase/app_db/custom_migrations_test.clj
+++ b/test/metabase/app_db/custom_migrations_test.clj
@@ -25,6 +25,7 @@
[metabase.app-db.custom-migrations :as custom-migrations]
[metabase.app-db.custom-migrations.util :as custom-migrations.util]
[metabase.app-db.schema-migrations-test.impl :as impl]
+ [metabase.app-db.setting :as mdb.setting]
[metabase.driver :as driver]
[metabase.models.interface :as mi]
[metabase.permissions.models.permissions-group :as perms-group]
@@ -2676,6 +2677,23 @@
(testing "everything back to normal after downgrade"
(assert-pre-conditions)))))))
+(deftest migrate-clickhouse-details-keeps-encryption-state-test
+ (testing "v57.2025-08-23T16:00:00 : rewriting details keeps each row as plaintext or ciphertext, whichever it was"
+ (encryption-test/with-secret-key "clickhouse-details-state-key-1234"
+ (impl/test-migrations "v57.2025-08-23T16:00:00" [migrate!]
+ (let [plain-id (:id (new-instance-with-default :metabase_database {:engine "clickhouse"
+ :details (json/encode {:dbname "plain_db"})}))
+ enc-id (:id (new-instance-with-default :metabase_database {:engine "clickhouse"
+ :details (encryption/encrypt (json/encode {:dbname "enc_db"}))}))
+ raw (fn [id] (t2/select-one-fn :details :metabase_database :id id))]
+ (migrate!)
+ (testing "a plaintext row stays plaintext"
+ (is (not (encryption/decryptable-string? (raw plain-id))))
+ (is (= "plain_db" (:db-filters-patterns (json/decode+kw (raw plain-id))))))
+ (testing "an encrypted row stays encrypted"
+ (is (encryption/decryptable-string? (raw enc-id)))
+ (is (= "enc_db" (:db-filters-patterns (json/decode+kw (encryption/maybe-decrypt (raw enc-id))))))))))))
+
(deftest escape-existing-at-symbol-user-attributes-test
(testing "v58.2025-11-18T12:31:49 : rename any existing `@.+` user attrs to add a preceding underscore"
(impl/test-migrations ["v58.2025-11-18T12:31:49"] [migrate!]
@@ -2701,198 +2719,24 @@
(is (= {"_@foo" "bang"}
(json/decode (t2/select-one-fn :login_attributes :core_user :id other-user-id))))))))
-(deftest encrypt-auth-identity-credentials-test
- (testing "v58.2026-08-25T00:00:00 : plaintext auth_identity.credentials rows are encrypted, encrypted rows untouched"
- (encryption-test/with-secret-key "encrypt-creds-test-key-1234"
- (impl/test-migrations ["v58.2026-08-25T00:00:00"] [migrate!]
- (let [user-id (:id (new-instance-with-default :core_user))
- ins-cred (fn [provider creds-str]
- (t2/insert-returning-pk! :auth_identity {:user_id user-id
- :provider provider
- :credentials creds-str
- :created_at :%now
- :updated_at :%now}))
- plain-id (ins-cred "password" (json/encode {:password_hash "h" :password_salt "s"}))
- enc-str (encryption/maybe-encrypt (json/encode {:password_hash "h2" :password_salt "s2"}))
- enc-id (ins-cred "google" enc-str)
- raw-cred (fn [id] (t2/select-one-fn :credentials :auth_identity :id id))]
- (is (not (encryption/possibly-encrypted-string? (raw-cred plain-id))))
- (migrate!)
- (testing "plaintext credentials are encrypted and decrypt to the original value"
- (is (encryption/decryptable-string? (raw-cred plain-id)))
- (is (= {:password_hash "h" :password_salt "s"}
- (json/decode+kw (encryption/maybe-decrypt-accepting-plaintext (raw-cred plain-id))))))
- (testing "already-encrypted credentials row is left unchanged"
- (is (= enc-str (raw-cred enc-id)))))))))
-
-(deftest encrypt-api-keys-test
- (testing "v58.2026-08-25T00:00:01 : plaintext api_key.key hashes are encrypted, encrypted rows untouched"
- (encryption-test/with-secret-key "encrypt-api-keys-test-key-1234"
- (impl/test-migrations ["v58.2026-08-25T00:00:01"] [migrate!]
- (let [user-id (:id (new-instance-with-default :core_user {:entity_id (u/generate-nano-id)}))
- ins-key (fn [prefix key-str]
- (:id (new-instance-with-default :api_key {:name (str "k-" prefix)
- :user_id user-id
- :creator_id user-id
- :updated_by_id user-id
- :key key-str
- :key_prefix prefix})))
- plain-id (ins-key "mb_plai" "plaintext-bcrypt-hash")
- enc-str (encryption/maybe-encrypt "another-bcrypt-hash")
- enc-id (ins-key "mb_encr" enc-str)
- raw-key (fn [id] (t2/select-one-fn :key :api_key :id id))]
- (is (not (encryption/possibly-encrypted-string? (raw-key plain-id))))
- (migrate!)
- (testing "plaintext key is encrypted and decrypts to the original hash"
- (is (encryption/decryptable-string? (raw-key plain-id)))
- (is (= "plaintext-bcrypt-hash"
- (encryption/maybe-decrypt-accepting-plaintext (raw-key plain-id)))))
- (testing "already-encrypted key row is left unchanged"
- (is (= enc-str (raw-key enc-id))))
- (testing "rollback decrypts keys back to the plaintext hash so downgraded code can still verify them"
- (migrate! :down 57)
- (is (not (encryption/possibly-encrypted-string? (raw-key plain-id))))
- (is (= "plaintext-bcrypt-hash" (raw-key plain-id)))
- (is (= "another-bcrypt-hash" (raw-key enc-id)))))))))
-
-(deftest encrypt-notification-and-pulse-channel-details-test
- (testing "v58.2026-08-25T00:00:19 encrypts pulse_channel details at rest"
- (impl/test-migrations ["v58.2026-08-25T00:00:19"] [migrate!]
- (let [user-id (:id (new-instance-with-default :core_user))
- pulse-id (:id (new-instance-with-default :pulse {:creator_id user-id}))
- pc-details (json/encode {:emails ["[email protected]"]})
- pc-id (:id (new-instance-with-default :pulse_channel
- {:pulse_id pulse-id
- :channel_type "email"
- :schedule_type "daily"
- :details pc-details}))
- raw-pc #(:details (t2/query-one {:select [:details] :from [:pulse_channel] :where [:= :id pc-id]}))]
- (testing "plaintext before migration (written with no encryption key)"
- (is (not (encryption/possibly-encrypted-string? (raw-pc)))))
- (encryption-test/with-secret-key "dont-tell-anyone-about-this"
- (migrate!)
- (testing "encrypted after migration, and still decrypts to the original value"
- (is (encryption/decryptable-string? (raw-pc)))
- (is (= pc-details (encryption/maybe-decrypt (raw-pc))))))))))
-
-(deftest encrypt-remaining-columns-test
- (testing "v58.2026-08-28T14:00:00 : plaintext rows in the historically mixable columns are encrypted, encrypted rows untouched"
- (encryption-test/with-secret-key "encrypt-remaining-test-key-1234"
- (impl/test-migrations ["v58.2026-08-28T14:00:00"] [migrate!]
- (let [plain-details (json/encode {:db "/plain.db"})
- enc-details (encryption/maybe-encrypt (json/encode {:db "/enc.db"}))
- plain-db-id (:id (new-instance-with-default :metabase_database {:details plain-details}))
- enc-db-id (:id (new-instance-with-default :metabase_database {:details enc-details}))
- user-settings (json/encode {:locale "en"})
- user-id (:id (new-instance-with-default :core_user {:settings user-settings}))
- secret-bytes (.getBytes "sooper-secret" "UTF-8")
- secret-id (t2/insert-returning-pk! :secret {:name "s"
- :kind "password"
- :value secret-bytes
- :version 1
- :creator_id user-id
- :created_at :%now
- :updated_at :%now})
- raw (fn [table column id]
- (:value (t2/query-one {:select [[column :value]] :from [table] :where [:= :id id]})))
- ;; convert the blob inside the reduction, while its connection is still open
- raw-secret (fn [id]
- (first (into []
- (map (fn [{:keys [value]}] (#'custom-migrations/secret-value->bytes value)))
- (t2/reducible-query {:select [:value] :from [:secret] :where [:= :id id]}))))]
- (is (not (encryption/possibly-encrypted-string? (raw :metabase_database :details plain-db-id))))
- (migrate!)
- (testing "plaintext string values are encrypted and decrypt to the original"
- (is (encryption/possibly-encrypted-string? (raw :metabase_database :details plain-db-id)))
- (is (= plain-details (encryption/maybe-decrypt (raw :metabase_database :details plain-db-id))))
- (is (encryption/possibly-encrypted-string? (raw :core_user :settings user-id)))
- (is (= user-settings (encryption/maybe-decrypt (raw :core_user :settings user-id)))))
- (testing "already-encrypted values are untouched"
- (is (= enc-details (raw :metabase_database :details enc-db-id))))
- (testing "plaintext secret bytes are encrypted and decrypt to the original"
- (let [v (raw-secret secret-id)]
- (is (encryption/possibly-encrypted-bytes? v))
- (is (= "sooper-secret" (String. (encryption/maybe-decrypt-bytes v) "UTF-8"))))))))))
-
-(deftest encrypt-settings-test
- ;; some of the settings are enterprise-only, so they are registered only when the EE namespaces are loaded
- (testing "a few known encrypted settings are in the migration list"
- (doseq [k ["email-smtp-password" "ldap-password" "saml-keystore-password" "site-url" "snowplow-url"]]
- (testing k
- (is (some #{k} @#'custom-migrations/encrypted-settings-v58)))))
- (testing "v58.2026-08-28T00:00:00 : plaintext values of newly-encrypted settings are encrypted at rest, others untouched"
- (encryption-test/with-secret-key "encrypt-settings-test-key-1234"
- (impl/test-migrations "v58.2026-08-28T00:00:00" [migrate!]
- (let [ins! (fn [k v] (t2/query {:insert-into :setting :values [{:key k :value v}]}))
- raw (fn [k] (t2/select-one-fn :value :setting :key k))
- enc-str (encryption/maybe-encrypt "https://already.example")
- ;; base64 of 64 bytes: plaintext with exactly the shape of ciphertext
- shaped-str (str (apply str (repeat 86 "a")) "==")]
- (ins! "snowplow-url" "https://plain.example")
- (ins! "ldap-user-filter" " ")
- (ins! "email-reply-to" "")
- (ins! "map-tile-server-url" enc-str)
- (ins! "store-url" shaped-str)
- (ins! "site-name" "Metabase")
- (is (not (encryption/possibly-encrypted-string? (raw "snowplow-url"))))
- (is (encryption/possibly-encrypted-string? shaped-str))
- (migrate!)
- (testing "a plaintext value of a listed setting is encrypted and decrypts back"
- (is (encryption/decryptable-string? (raw "snowplow-url")))
- (is (= "https://plain.example" (encryption/maybe-decrypt (raw "snowplow-url")))))
- (testing "a blank value of a listed setting is encrypted too, since a strict read would reject plaintext"
- (is (encryption/decryptable-string? (raw "ldap-user-filter")))
- (is (= " " (encryption/maybe-decrypt (raw "ldap-user-filter"))))
- (is (encryption/decryptable-string? (raw "email-reply-to")))
- (is (= "" (encryption/maybe-decrypt (raw "email-reply-to")))))
- (testing "a plaintext value that merely looks like ciphertext is encrypted, not skipped"
- (is (encryption/decryptable-string? (raw "store-url")))
- (is (= shaped-str (encryption/maybe-decrypt (raw "store-url")))))
- (testing "an already-encrypted value is left unchanged"
- (is (= enc-str (raw "map-tile-server-url"))))
- (testing "a setting not in the list is left plaintext"
- (is (= "Metabase" (raw "site-name"))))
- (testing "rollback decrypts the listed settings back to plaintext, others untouched"
- (migrate! :down 57)
- (is (= "https://plain.example" (raw "snowplow-url")))
- (is (= " " (raw "ldap-user-filter")))
- (is (= "" (raw "email-reply-to")))
- (is (= shaped-str (raw "store-url")))
- (is (= "https://already.example" (raw "map-tile-server-url")))
- (is (= "Metabase" (raw "site-name")))))))))
-
-(deftest encrypt-setter-none-settings-test
- ;; some of the settings are enterprise-only, so they are registered only when the EE namespaces are loaded
- (testing "the :setter :none settings that are encrypted at rest are in the migration list"
- (doseq [k ["setup-token" "support-access-grant-email" "site-uuid-for-unsubscribing-url"]]
- (testing k
- (is (some #{k} @#'custom-migrations/encrypted-setter-none-settings-v58)))))
- (testing "settings that are neither secret nor integrity-critical are not"
- (doseq [k ["enable-query-caching" "instance-creation" "token-features" "version"]]
- (testing k
- (is (not (some #{k} @#'custom-migrations/encrypted-setter-none-settings-v58))))))
- (testing "v58.2026-08-30T00:00:00 : plaintext rows of listed settings are encrypted at rest, others untouched"
- (encryption-test/with-secret-key "encrypt-setter-none-settings-key-1234"
- (impl/test-migrations "v58.2026-08-30T00:00:00" [migrate!]
- (let [insert-setting! (fn [k v] (t2/query {:insert-into :setting :values [{:key k :value v}]}))
- raw-setting (fn [k] (t2/select-one-fn :value :setting :key k))
- encrypted-value (encryption/maybe-encrypt "https://otel.example")]
- ;; a plaintext row from before the setting was encrypted
- (insert-setting! "setup-token" "b7f4a1e2-0000-4000-8000-000000000000")
- (insert-setting! "support-access-grant-email" "[email protected]")
- ;; an already-encrypted row
- (insert-setting! "tracing-endpoint" encrypted-value)
- ;; a setting that is deliberately plaintext at rest is not this migration's business
- (insert-setting! "instance-creation" "2026-08-30T00:00:00Z")
- (migrate!)
- (testing "a plaintext row of a listed setting is encrypted and decrypts back"
- (is (encryption/decryptable-string? (raw-setting "setup-token")))
- (is (= "b7f4a1e2-0000-4000-8000-000000000000" (encryption/maybe-decrypt (raw-setting "setup-token"))))
- (is (= "[email protected]" (encryption/maybe-decrypt (raw-setting "support-access-grant-email")))))
- (testing "an already-encrypted row is left unchanged"
- (is (= encrypted-value (raw-setting "tracing-endpoint"))))
- (testing "a setting not in the list is left plaintext"
- (is (= "2026-08-30T00:00:00Z" (raw-setting "instance-creation")))))))))
+(deftest backfill-example-dashboard-id-value-with-aad-test
+ (testing "v58.2026-09-03T00:00:04 : the example-dashboard-id row gets its value_with_aad from its encrypted value"
+ (encryption-test/with-secret-key "example-dashboard-id-key-1234"
+ (impl/test-migrations "v58.2026-09-03T00:00:04" [migrate!]
+ (t2/query {:delete-from :setting :where [:= :key "example-dashboard-id"]})
+ (t2/query {:insert-into :setting :values [{:key "example-dashboard-id" :value (encryption/encrypt "7")}]})
+ (migrate!)
+ (let [{:keys [value value_with_aad]} (t2/select-one :setting :key "example-dashboard-id")]
+ (is (= "7" (encryption/maybe-decrypt value)))
+ (is (= "7" (encryption/maybe-decrypt value_with_aad {:aad (mdb.setting/setting-aad "example-dashboard-id")})))))))
+ (testing "without a key both columns stay plaintext"
+ (encryption-test/with-secret-key nil
+ (impl/test-migrations "v58.2026-09-03T00:00:04" [migrate!]
+ (t2/query {:delete-from :setting :where [:= :key "example-dashboard-id"]})
+ (t2/query {:insert-into :setting :values [{:key "example-dashboard-id" :value "7"}]})
+ (migrate!)
+ (is (= {:value "7", :value_with_aad "7"}
+ (select-keys (t2/select-one :setting :key "example-dashboard-id") [:value :value_with_aad])))))))
(deftest backfill-transform-target-db-id-test
(testing "v59.2026-01-31T12:01:23 : backfill target_db_id from target and source JSON"
diff --git a/test/metabase/app_db/encryption_test.clj b/test/metabase/app_db/encryption_test.clj
index ee2c64f8cd7..ea63a118330 100644
--- a/test/metabase/app_db/encryption_test.clj
+++ b/test/metabase/app_db/encryption_test.clj
@@ -30,7 +30,11 @@
:set {:details "{\"pattern\":\"plain\"}"}
:where [:!= :details nil]})
(is (not-any? encryption/decryptable-string? (recipient-details)) "now plaintext, as an old build leaves them")
- (mdb/encrypt-plaintext-columns!)
+ (mt/with-log-messages-for-level [messages :warn]
+ (mdb/encrypt-plaintext-columns!)
+ (is (=? [{:level :warn, :message #"Encrypting legacy values in notification_recipient\.details that a previous version of Metabase stored unencrypted\."}]
+ (filter #(re-find #"notification_recipient" (:message %)) (messages)))
+ "the heal warns about the column it had to encrypt"))
(let [healed (recipient-details)]
(is (every? encryption/decryptable-string? healed))
(is (= "{\"pattern\":\"plain\"}" (encryption/decrypt (first healed))))))
diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.clj
index 613d973db5d..73ca3cee3fb 100644
--- a/test/metabase/app_db/schema_migrations_test.clj
+++ b/test/metabase/app_db/schema_migrations_test.clj
@@ -1598,8 +1598,8 @@
:first_name "Metabase"
:last_name "Internal"
- :password some?
- :password_salt some?
+ :password nil
+ :password_salt nil
:is_active false
:is_superuser false
:login_attributes nil
@@ -2845,6 +2845,22 @@
(is (thrown? Exception
(perm! {:perm_type "perms/view-data" :perm_value "blocked"}))))))))
+(deftest delete-plaintext-encryption-check-marker-test
+ (testing "v58.2026-09-03T00:00:03: the plaintext \"unencrypted\" encryption-check marker is deleted"
+ (impl/test-migrations "v58.2026-09-03T00:00:03" [migrate!]
+ (t2/query {:delete-from :setting :where [:= :key "encryption-check"]})
+ (t2/query {:insert-into :setting :values [{:key "encryption-check" :value "unencrypted"}]})
+ (migrate!)
+ (is (nil? (t2/select-one :setting :key "encryption-check")))))
+ (testing "an encrypted sentinel is left alone"
+ (encryption-test/with-secret-key "encryption-check-marker-key-1234"
+ (impl/test-migrations "v58.2026-09-03T00:00:03" [migrate!]
+ (let [sentinel (encryption/encrypt (str (random-uuid)))]
+ (t2/query {:delete-from :setting :where [:= :key "encryption-check"]})
+ (t2/query {:insert-into :setting :values [{:key "encryption-check" :value sentinel}]})
+ (migrate!)
+ (is (= sentinel (t2/select-one-fn :value :setting :key "encryption-check"))))))))
+
(deftest dependency-status-segment-handles-missing-column-migration-test
(testing "The whole 20260402_dependency_status changeset run survives a missing
segment.dependency_analysis_version column (issue #74443). Every changeset that
diff --git a/test/metabase/app_db/setup_test.clj b/test/metabase/app_db/setup_test.clj
index 48999f9bff1..50726f9289a 100644
--- a/test/metabase/app_db/setup_test.clj
+++ b/test/metabase/app_db/setup_test.clj
@@ -6,6 +6,7 @@
[metabase.app-db.connection-pool-setup :as mdb.connection-pool-setup]
[metabase.app-db.core :as mdb]
[metabase.app-db.data-source :as mdb.data-source]
+ [metabase.app-db.db :as mdb.db]
[metabase.app-db.liquibase :as liquibase]
[metabase.app-db.setting :as mdb.setting]
[metabase.app-db.setup :as mdb.setup]
@@ -245,6 +246,39 @@
(mdb/setup-db! :create-sample-content? false :manage-encryption-state? false)
(is (= ciphertext (t2/select-one-fn :value_with_aad :setting :key "site-name"))))))))
+(deftest setup-db-warns-about-settings-from-an-older-version-test
+ (testing "a setting row written by a version without value_with_aad is reported once and then filled in"
+ (mt/with-temp-empty-app-db [_conn :h2]
+ (mdb/setup-db! :create-sample-content? false)
+ (is (not (mdb.db/unmigrated-settings?)))
+ (t2/query {:insert-into :setting, :values [{:key "site-name", :value "Sad Can"}]})
+ (is (mdb.db/unmigrated-settings?))
+ (reset! (:status mdb.connection/*application-db*) ::not-set-up)
+ (mt/with-log-messages-for-level [messages :warn]
+ (mdb/setup-db! :create-sample-content? false)
+ (is (=? [{:level :warn, :message #"(?s)Some settings were saved by an older version of Metabase.*"}]
+ (filter #(re-find #"older version" (:message %)) (messages)))))
+ (is (not (mdb.db/unmigrated-settings?)))
+ (is (= "Sad Can" (t2/select-one-fn :value_with_aad :setting :key "site-name"))))))
+
+(deftest migrate-settings-decides-by-decrypting-test
+ (testing "the value_with_aad backfill treats a value as encrypted only if it decrypts, and copes with one that encrypts to nothing"
+ (mt/with-temp-empty-app-db [_conn :h2]
+ (mdb/setup-db! :create-sample-content? false)
+ (encryption-test/with-secret-key "ABCDEFGH12345678"
+ (mdb/encrypt-db (mdb/db-type) (mdb/data-source) nil)
+ (let [shaped (str (apply str (repeat 86 "a")) "==")]
+ (is (encryption/possibly-encrypted-string? shaped))
+ (t2/query {:insert-into :setting, :values [{:key "shaped", :value shaped}
+ {:key "blank", :value (encryption/encrypt "")}]})
+ (reset! (:status mdb.connection/*application-db*) ::not-set-up)
+ (is (= :done (mdb/setup-db! :create-sample-content? false)))
+ (testing "a plaintext value that merely looks like ciphertext is a value, not skipped"
+ (is (= shaped (encryption/maybe-decrypt (t2/select-one-fn :value_with_aad :setting :key "shaped")
+ {:aad (mdb.setting/setting-aad "shaped")}))))
+ (testing "an encrypted blank value has nothing to store, and is written as NULL rather than failing"
+ (is (nil? (t2/select-one-fn :value_with_aad :setting :key "blank")))))))))
+
(deftest encryption-check-status-falls-back-to-value-test
(testing "the sentinel is read from `value`, whatever `value_with_aad` holds -- an older version rewrites only `value`"
(mt/with-temp-empty-app-db [_conn :h2]
diff --git a/test/metabase/cmd/enable_encryption_test.clj b/test/metabase/cmd/enable_encryption_test.clj
index dbb05813079..223b197080c 100644
--- a/test/metabase/cmd/enable_encryption_test.clj
+++ b/test/metabase/cmd/enable_encryption_test.clj
@@ -52,12 +52,11 @@
(mt/with-temp-empty-app-db [_conn :h2]
(mdb/setup-db! :create-sample-content? true)
(t2/insert! :model/Setting {:key "enable-encryption-test-setting", :value "plain value"})
- ;; the v53 migration's legacy plaintext marker; new code never writes it and reads it as "no sentinel"
- (is (= "unencrypted" (raw-value "encryption-check")))
+ (is (nil? (raw-value "encryption-check")))
(encryption-test/with-secret-key "key1"
(testing "startup refuses until the command has been run"
(is (thrown-with-msg? Exception #"already contains data.*run `enable-encryption`" (restart!)))
- (is (= "unencrypted" (raw-value "encryption-check"))))
+ (is (nil? (raw-value "encryption-check"))))
(testing "the command encrypts everything and writes the sentinel"
(enable-encryption!)
(is (encryption/decryptable-string? (raw-value "encryption-check")))
diff --git a/test/metabase/setup/core_test.clj b/test/metabase/setup/core_test.clj
index 25f2c77e1e8..e1767fdf574 100644
--- a/test/metabase/setup/core_test.clj
+++ b/test/metabase/setup/core_test.clj
@@ -138,8 +138,7 @@
(mdb/setup-db! :create-sample-content? true)
(let [cache-backend (i/cache-backend :db)]
(i/save-results! cache-backend (codecs/to-bytes "cache-key") (codecs/to-bytes "cache-value"))
- ;; the v53 migration's legacy plaintext marker; new code never writes it and reads it as "no sentinel"
- (is (= "unencrypted" (t2/select-one-fn :value "setting" :key "encryption-check")))
+ (is (nil? (t2/select-one-fn :value "setting" :key "encryption-check")))
(is (not (encryption/possibly-encrypted-string? (t2/select-one-fn :details "metabase_database"))))
(is (= 1 (t2/count :model/QueryCache)))
(testing "Adding a key to an existing instance refuses to start rather than encrypting on its own"
@@ -147,7 +146,7 @@
(reset! (:status mdb.connection/*application-db*) ::setup-finished)
(is (thrown-with-msg? Exception #"already contains data.*run `enable-encryption`"
(mdb/setup-db! :create-sample-content? false)))
- (is (= "unencrypted" (t2/select-one-fn :value "setting" :key "encryption-check")))
+ (is (nil? (t2/select-one-fn :value "setting" :key "encryption-check")))
(is (not (encryption/possibly-encrypted-string? (t2/select-one-fn :details "metabase_database"))))
(is (= 1 (t2/count :model/QueryCache)))
(testing "after `enable-encryption` the database is encrypted and starts"
@@ -162,6 +161,7 @@
(mt/with-temp-empty-app-db [_conn driver/*driver*]
(encryption-test/with-secret-key "key2"
(mdb/setup-db! :create-sample-content? true)
+ (mdb/encrypt-plaintext-columns!)
(is (encryption/decryptable-string? (t2/select-one-fn :value "setting" :key "encryption-check")))
(is (encryption/decryptable-string? (t2/select-one-fn :details "metabase_database")))
(testing "Re-running server works"
@@ -232,7 +232,14 @@
(testing "a database created with MB_ENCRYPTION_SECRET_KEY set stores every encrypted-at-rest value encrypted"
(mt/with-temp-empty-app-db [_conn :h2]
(encryption-test/with-secret-key "fresh-install-test-key-1234"
- (mdb/setup-db! :create-sample-content? true)
+ (testing "and sets up without a warning: nothing on a fresh install is legacy data"
+ (is (= [] (mt/with-log-messages-for-level [messages [metabase.app-db :warn]]
+ (mdb/setup-db! :create-sample-content? true)
+ (messages)))))
+ (testing "the sample content's example-dashboard-id setting is stored whole and encrypted"
+ (let [{:keys [value value_with_aad]} (t2/select-one :setting :key "example-dashboard-id")]
+ (is (= "1" (encryption/maybe-decrypt value)))
+ (is (= "1" (encryption/maybe-decrypt value_with_aad {:aad (mdb.setting/setting-aad "example-dashboard-id")})))))
(testing "encrypted-at-rest columns (read raw, so no model transform can hide a plaintext value)"
(doseq [[table column] @#'mdb.encryption/encrypted-string-columns
{:keys [id value]} (t2/select [table :id [column :value]] {:where [:!= column nil]})]
@@ -252,4 +259,8 @@
(testing "every setting's value_with_aad, under its own setting's AAD"
(doseq [{k :key v :value_with_aad} (t2/select :setting {:where [:!= :value_with_aad nil]})]
(testing k
- (is (encryption/decryptable-string? v {:aad (mdb.setting/setting-aad k)})))))))))
+ (is (encryption/decryptable-string? v {:aad (mdb.setting/setting-aad k)})))))
+ (testing "and the startup sweep then has nothing left to encrypt"
+ (is (= [] (mt/with-log-messages-for-level [messages [metabase.app-db :warn]]
+ (mdb/encrypt-plaintext-columns!)
+ (messages)))))))))