From ffa10323814b3ea0f15ac9cd2238164e42a873ad Mon Sep 17 00:00:00 2001
From: Claire <claire.github-309c@sitedethib.com>
Date: Mon, 14 Oct 2024 15:00:20 +0200
Subject: [PATCH] Add further warnings about encryption secrets (#32476)

---
 config/initializers/active_record_encryption.rb |  1 +
 lib/tasks/db.rake                               | 11 +++++++++++
 2 files changed, 12 insertions(+)

diff --git a/config/initializers/active_record_encryption.rb b/config/initializers/active_record_encryption.rb
index b7a874e40..c53f16d4d 100644
--- a/config/initializers/active_record_encryption.rb
+++ b/config/initializers/active_record_encryption.rb
@@ -20,6 +20,7 @@
         - ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY
 
       Run `bin/rails db:encryption:init` to generate new secrets and then assign the environment variables.
+      Do not change the secrets once they are set, as doing so may cause data loss and other issues that will be difficult or impossible to recover from.
     MESSAGE
   end
 
diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake
index 79599bd91..73de0c120 100644
--- a/lib/tasks/db.rake
+++ b/lib/tasks/db.rake
@@ -7,6 +7,17 @@ namespace :db do
   namespace :encryption do
     desc 'Generate a set of keys for configuring Active Record encryption in a given environment'
     task :init do # rubocop:disable Rails/RakeEnvironment
+      if %w(
+        ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY
+        ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT
+        ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY
+      ).any? { |key| ENV.key?(key) }
+        pastel = Pastel.new
+        puts pastel.red(<<~MSG)
+          WARNING: It looks like encryption secrets have already been set. Please ensure you are not changing secrets for a Mastodon installation that already uses them, as this will cause data loss and other issues that are difficult to recover from.
+        MSG
+      end
+
       puts <<~MSG
         Add the following secret environment variables to your Mastodon environment (e.g. .env.production), ensure they are shared across all your nodes and do not change them after they are set:#{' '}