Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Keep rich text images through a secret_key_base rotation and re-sign them

Guido Boykef731fd20f83f
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 572a752..8958fea 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -202,6 +202,7 @@ jobs:
spec/migrations/remove_ticket_id_from_chats_spec.rb
spec/jobs/rich_text_embed_variant_job_spec.rb
spec/models/action_text/rich_text_embed_guard_inclusion_spec.rb
+ spec/models/action_text/rich_text_embed_key_rotation_spec.rb
spec/models/action_text/rich_text_embed_lifecycle_spec.rb
spec/models/action_text/rich_text_embed_missing_spec.rb
spec/models/action_text/rich_text_embed_plain_text_spec.rb
@@ -568,6 +569,7 @@ jobs:
spec/services/time_sessions/viewing_scope_spec.rb
spec/services/time_session_navigation_service_spec.rb
spec/services/rich_text_embed_url_sweep_spec.rb
+ spec/services/rich_text_sgid_resign_spec.rb
spec/services/power_search_service_spec.rb
spec/services/docs/plain_text_spec.rb
spec/services/product_knowledge/ensure_fresh_spec.rb
diff --git a/app/models/concerns/rich_text_embed_retention.rb b/app/models/concerns/rich_text_embed_retention.rb
new file mode 100644
index 0000000..1ecf279
--- /dev/null
+++ b/app/models/concerns/rich_text_embed_retention.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+# Safety net on ActionText::RichText (included by config/initializers/rich_text_embed_retention.rb):
+# a stored embed stays attached while the body still holds an attachment node whose sgid
+# does not resolve.
+#
+# Rails rebuilds `embeds` in its own before_validation from the sgids that resolve
+# (rich_text.rb: `self.embeds = body.attachables.grep(ActiveStorage::Blob).uniq`). A sgid
+# stops resolving for everything stored before a secret_key_base rotation, and then
+# editing only the words of a text detached every image and enqueued the purge of its
+# file. Which embed a dead node meant cannot be told without
+# the old key, so every stored embed that would be dropped is kept. The price is that an
+# image removed in the same edit stays attached until the text is saved again with
+# readable nodes; RichTextSgidResign makes them readable.
+#
+# Runs after Rails' callback because this module is included after the class body.
+module RichTextEmbedRetention
+ extend ActiveSupport::Concern
+
+ included do
+ before_validation :retain_embeds_behind_unresolved_nodes, if: -> { persisted? && body.present? }
+ end
+
+ private
+
+ def retain_embeds_behind_unresolved_nodes
+ attachables = body.attachables
+ return unless attachables.any?(ActionText::Attachables::MissingAttachable)
+
+ resolved = attachables.grep(ActiveStorage::Blob)
+ stored = ActiveStorage::Blob.joins(:attachments)
+ .where(active_storage_attachments: { record_type: self.class.name, record_id: id, name: 'embeds' })
+ .to_a
+ retained = stored.reject { |blob| resolved.include?(blob) }
+ return if retained.empty?
+
+ self.embeds = (resolved + retained).uniq
+ end
+end
diff --git a/app/services/rich_text_sgid_resign.rb b/app/services/rich_text_sgid_resign.rb
new file mode 100644
index 0000000..448aa3f
--- /dev/null
+++ b/app/services/rich_text_sgid_resign.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+# One-off repair after a secret_key_base rotation: every
+# <action-text-attachment sgid> stored before it was signed with the old key, so Rails
+# renders each image and wiki mention as "☒". This re-signs those nodes with the current key.
+#
+# The old key is an argument of this one run, never configuration: a key is rotated because
+# others may hold it, and a sgid forged with it must not gain a target. So a node is re-signed only when
+# 1. the old key verifies it (an unverified sgid is never decoded: older ones are Marshal),
+# 2. its record still exists, and
+# 3. the record belongs to this text: a blob only when it is attached to THIS rich text
+# (its embeds), anything else (a mention) only within the carrier's organisation.
+# Everything else is counted (unreadable) or listed with its ids (gone, refused); a gone
+# blob was purged after the rotation and can only come back from the attachment backup.
+#
+# Writes with update_column like RichTextEmbedUrlSweep: no validation, no NoteVersion, no
+# embeds sync; a note's derived markdown_body is re-derived so the next edit shows no
+# spurious diff. Idempotent: a node that resolves is left alone.
+#
+# Entry point: RichTextSgidResign.call(old_secret_key_base:, dry_run: true)
+class RichTextSgidResign
+ Result = Struct.new(:scanned, :changed, :resigned, :unreadable, :gone, :refused, :dry_run, keyword_init: true)
+
+ def self.call(old_secret_key_base:, dry_run: true) = new(old_secret_key_base: old_secret_key_base, dry_run: dry_run).call
+
+ def initialize(old_secret_key_base:, dry_run: true)
+ raise ArgumentError, 'old_secret_key_base is required' if old_secret_key_base.blank?
+
+ # The same derivation GlobalID's railtie uses for SignedGlobalID.verifier.
+ @old_verifier = GlobalID::Verifier.new(Rails.application.key_generator(old_secret_key_base).generate_key('signed_global_ids'))
+ @dry_run = dry_run
+ end
+
+ def call
+ @result = Result.new(scanned: 0, changed: 0, resigned: 0, unreadable: 0, gone: [], refused: [], dry_run: @dry_run)
+
+ ActsAsTenant.without_tenant do
+ candidates.find_each do |rich_text|
+ @result.scanned += 1
+ html = resign(rich_text)
+ next if html.nil?
+
+ @result.changed += 1
+ persist(rich_text, html) unless @dry_run
+ end
+ end
+
+ @result
+ end
+
+ private
+
+ def candidates
+ ActionText::RichText.where('body LIKE ?', "%<#{ActionText::Attachment.tag_name}%").includes(:record)
+ end
+
+ # @return [String, nil] the html with re-signed nodes, or nil when nothing changed
+ def resign(rich_text)
+ fragment = ActionText::Fragment.wrap(rich_text.body.to_html)
+ touched = false
+ fragment.find_all(ActionText::Attachment.tag_name).each do |node|
+ sgid = resign_stale_node(rich_text, node['sgid'])
+ next if sgid.nil?
+
+ node['sgid'] = sgid
+ touched = true
+ @result.resigned += 1
+ end
+ touched ? fragment.to_html : nil
+ end
+
+ # @return [String, nil] the new sgid, or nil when the node stays as it is
+ def resign_stale_node(rich_text, sgid)
+ return if sgid.blank? || signed_with_current_key?(sgid)
+
+ gid = SignedGlobalID.parse(sgid, for: ActionText::Attachable::LOCATOR_NAME, verifier: @old_verifier)
+ if gid.nil?
+ @result.unreadable += 1
+ return
+ end
+
+ record = locate(gid)
+ return list(:gone, rich_text, gid) if record.nil?
+ return list(:refused, rich_text, gid) unless belongs_to_text?(rich_text, record)
+
+ record.attachable_sgid
+ end
+
+ # A sgid of the current key whose record is gone raises instead of answering nil; it is
+ # still current, and no re-signing would bring its record back.
+ def signed_with_current_key?(sgid)
+ GlobalID::Locator.locate_signed(sgid, for: ActionText::Attachable::LOCATOR_NAME).present?
+ rescue ActiveRecord::RecordNotFound
+ true
+ end
+
+ def locate(gid)
+ GlobalID::Locator.locate(gid)
+ rescue ActiveRecord::RecordNotFound
+ nil
+ end
+
+ def belongs_to_text?(rich_text, record)
+ if record.is_a?(ActiveStorage::Blob)
+ ActiveStorage::Attachment.exists?(record: rich_text, name: 'embeds', blob: record)
+ else
+ carrier_organisation_id = rich_text.record.try(:organisation_id)
+ carrier_organisation_id.present? && record.try(:organisation_id) == carrier_organisation_id
+ end
+ end
+
+ # Model and id, never gid.to_s: on a SignedGlobalID that signs the id again.
+ def list(kind, rich_text, gid)
+ @result[kind] << { rich_text_id: rich_text.id, record_type: rich_text.record_type, record_id: rich_text.record_id,
+ target_type: gid.model_name, target_id: gid.model_id }
+ nil
+ end
+
+ def persist(rich_text, html)
+ rich_text.update_column(:body, html)
+ carrier = rich_text.record
+ return unless carrier.is_a?(Note) && carrier.has_attribute?(:markdown_body)
+
+ carrier.update_column(:markdown_body, Wiki::MarkdownSerializer.new.to_markdown(html))
+ end
+end
diff --git a/config/initializers/rich_text_embed_retention.rb b/config/initializers/rich_text_embed_retention.rb
new file mode 100644
index 0000000..b633552
--- /dev/null
+++ b/config/initializers/rich_text_embed_retention.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+# Keeps the images of a rich text whose attachment nodes no longer resolve (a sgid signed
+# with a previous secret_key_base). Why and how: app/models/concerns/rich_text_embed_retention.rb.
+ActiveSupport.on_load(:action_text_rich_text) do
+ include RichTextEmbedRetention
+end
diff --git a/lib/tasks/rich_text_embeds.rake b/lib/tasks/rich_text_embeds.rake
index 7f60f13..ac3d000 100644
--- a/lib/tasks/rich_text_embeds.rake
+++ b/lib/tasks/rich_text_embeds.rake
@@ -11,4 +11,27 @@ namespace :rich_text_embeds do
puts " Rich-Texte mit Attachment-Knoten: #{result.scanned}"
puts " #{result.dry_run ? 'Würden geändert' : 'Geändert'}: #{result.changed}"
end
+
+ # After a secret_key_base rotation (RichTextSgidResign). The old key comes from the
+ # environment of this one run only; read it with `read -rs OLD_SECRET_KEY_BASE` and
+ # export it, so it lands neither in the shell history nor in a file.
+ desc 'Attachment-Knoten mit dem aktuellen Schlüssel neu signieren. OLD_SECRET_KEY_BASE setzen, zuerst DRY_RUN=1.'
+ task resign_sgids: :environment do
+ old_secret_key_base = ENV.fetch('OLD_SECRET_KEY_BASE', '')
+ abort 'OLD_SECRET_KEY_BASE fehlt (der Schlüssel VOR dem Tausch).' if old_secret_key_base.blank?
+ abort 'OLD_SECRET_KEY_BASE ist der aktuelle Schlüssel.' if old_secret_key_base == Rails.application.secret_key_base
+
+ result = RichTextSgidResign.call(old_secret_key_base: old_secret_key_base, dry_run: ENV['DRY_RUN'] == '1')
+ puts format('rich_text_embeds:resign_sgids%<mode>s', mode: result.dry_run ? ' (DRY_RUN, nichts geschrieben)' : '')
+ puts " Rich-Texte mit Attachment-Knoten: #{result.scanned}"
+ puts " #{result.dry_run ? 'Würden geändert' : 'Geändert'}: #{result.changed} Texte, #{result.resigned} Knoten"
+ puts " Mit keinem der beiden Schlüssel lesbar: #{result.unreadable}"
+ { gone: 'Ziel fehlt (Blob gelöscht, aus der Sicherung holen)', refused: 'Abgelehnt (gehört nicht zu diesem Text)' }.each do |kind, label|
+ rows = result[kind]
+ puts " #{label}: #{rows.size}"
+ rows.each do |row|
+ puts " #{row[:record_type]} #{row[:record_id]} (Rich-Text #{row[:rich_text_id]}) -> #{row[:target_type]} #{row[:target_id]}"
+ end
+ end
+ end
end
diff --git a/spec/models/action_text/rich_text_embed_key_rotation_spec.rb b/spec/models/action_text/rich_text_embed_key_rotation_spec.rb
new file mode 100644
index 0000000..274fd76
--- /dev/null
+++ b/spec/models/action_text/rich_text_embed_key_rotation_spec.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: Saving a rich text whose image nodes carry sgids signed with a previous
+# secret_key_base keeps those images attached.
+# Type: Model spec (2026-10-20).
+# Why: After a secret_key_base rotation no stored sgid resolves. Rails'
+# own before_validation rebuilds `embeds` from the sgids that resolve, so editing
+# only the words of such a text detached every image and enqueued the purge of its
+# file. RichTextEmbedRetention keeps a stored embed while the body still holds a
+# node it cannot resolve; the re-sign task (RichTextSgidResign) repairs the nodes.
+RSpec.describe 'Rich text embeds across a secret_key_base rotation', :ci_guard do
+ include ActiveJob::TestHelper
+
+ let(:organisation) { create(:organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+
+ after { ActsAsTenant.current_tenant = nil }
+
+ around do |example|
+ verifier = SignedGlobalID.verifier
+ adapter_was = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ example.run
+ ensure
+ ActiveJob::Base.queue_adapter = adapter_was
+ SignedGlobalID.verifier = verifier
+ end
+
+ def png_blob(name = 'shot.png')
+ ActiveStorage::Blob.create_and_upload!(
+ io: StringIO.new("\x89PNG\r\n\x1a\n#{'x' * 64}"), filename: name, content_type: 'image/png'
+ )
+ end
+
+ def node(blob) = %(<action-text-attachment sgid="#{blob.attachable_sgid}"></action-text-attachment>)
+
+ def rotate_secret_key_base!
+ key = ActiveSupport::KeyGenerator.new('a-rotated-secret-key-base' * 4, iterations: 1000)
+ .generate_key('signed_global_ids')
+ SignedGlobalID.verifier = GlobalID::Verifier.new(key)
+ end
+
+ def embed_blob_ids(rich_text)
+ ActiveStorage::Attachment.where(record: rich_text, name: 'embeds').pluck(:blob_id)
+ end
+
+ def purge_jobs
+ enqueued_jobs.count { |job| job['job_class'] == 'ActiveStorage::PurgeJob' }
+ end
+
+ it 'keeps the images of a text whose words are edited after the rotation' do
+ blob = png_blob
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>Schritt 1</div>#{node(blob)}")
+ rotate_secret_key_base!
+ ticket = Ticket.find(ticket.id)
+ clear_enqueued_jobs
+
+ ticket.update!(content: ticket.content.body.to_html.sub('Schritt 1', 'Schritt 1, ergänzt'))
+
+ expect(embed_blob_ids(ticket.reload.content)).to eq([blob.id])
+ expect(purge_jobs).to eq(0)
+ end
+
+ it 'still adds a new image next to the stale ones' do
+ old_blob = png_blob('alt.png')
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>x</div>#{node(old_blob)}")
+ rotate_secret_key_base!
+ ticket = Ticket.find(ticket.id)
+ new_blob = png_blob('neu.png')
+
+ ticket.update!(content: ticket.content.body.to_html + node(new_blob))
+
+ expect(embed_blob_ids(ticket.reload.content)).to contain_exactly(old_blob.id, new_blob.id)
+ end
+
+ # The retention is a safety net for nodes that cannot be read, not a second rule for
+ # removing images: with every node resolving, Rails' own sync stays in charge.
+ it 'still detaches an image that was removed from a text whose nodes all resolve' do
+ kept = png_blob('bleibt.png')
+ removed = png_blob('weg.png')
+ ticket = create(:ticket, project: project, organisation: organisation,
+ content: "<div>x</div>#{node(kept)}#{node(removed)}")
+
+ ticket.update!(content: "<div>x</div>#{node(kept)}")
+
+ expect(embed_blob_ids(ticket.reload.content)).to eq([kept.id])
+ end
+end
diff --git a/spec/services/rich_text_sgid_resign_spec.rb b/spec/services/rich_text_sgid_resign_spec.rb
new file mode 100644
index 0000000..849246d
--- /dev/null
+++ b/spec/services/rich_text_sgid_resign_spec.rb
@@ -0,0 +1,159 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: RichTextSgidResign re-signs the attachment nodes of stored rich texts whose sgid
+# was signed with the previous secret_key_base.
+# Type: Service spec (2026-10-20).
+# Why: A secret_key_base rotation turns every stored image and wiki mention into a
+# "☒". The old key comes only from the one run of the task, so a node is accepted
+# only when the old key signed it AND its target belongs to this text: an image
+# only when it is attached to THIS text, a mention only within the text's own
+# organisation. Others may hold a rotated key; a sgid forged with it must gain nothing.
+RSpec.describe RichTextSgidResign, :ci_guard do
+ let(:organisation) { create(:organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:old_secret_key_base) { Rails.application.secret_key_base }
+
+ before { ActsAsTenant.current_tenant = organisation }
+
+ after { ActsAsTenant.current_tenant = nil }
+
+ around do |example|
+ verifier = SignedGlobalID.verifier
+ example.run
+ ensure
+ SignedGlobalID.verifier = verifier
+ end
+
+ def png_blob(name = 'shot.png')
+ ActiveStorage::Blob.create_and_upload!(
+ io: StringIO.new("\x89PNG\r\n\x1a\n#{'x' * 64}"), filename: name, content_type: 'image/png'
+ )
+ end
+
+ def node(record, extra = '')
+ %(<action-text-attachment sgid="#{record.attachable_sgid}"#{extra}></action-text-attachment>)
+ end
+
+ def mention(note) = node(note, ' content-type="application/vnd.actiontext.mention"')
+
+ # What a rotation does: the sgids written so far were signed with the key
+ # the application booted with, every one minted from now on uses the new key.
+ def rotate_secret_key_base!
+ key = ActiveSupport::KeyGenerator.new('a-rotated-secret-key-base' * 4, iterations: 1000)
+ .generate_key('signed_global_ids')
+ SignedGlobalID.verifier = GlobalID::Verifier.new(key)
+ end
+
+ def sgids_of(record)
+ Nokogiri::HTML.fragment(record.reload.content.body.to_html).css('action-text-attachment').map { |n| n['sgid'] }
+ end
+
+ def resolves?(sgid)
+ ActionText::Attachable.from_attachable_sgid(sgid).present?
+ rescue ActiveRecord::RecordNotFound
+ false
+ end
+
+ def run(dry_run: false) = described_class.call(old_secret_key_base: old_secret_key_base, dry_run: dry_run)
+
+ it 'brings back an image of the text and renders it instead of the glyph' do
+ blob = png_blob
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>Schritt 1</div>#{node(blob)}")
+ rotate_secret_key_base!
+ expect(Ticket.find(ticket.id).content.to_s).to include('☒')
+
+ result = run
+
+ expect(result.resigned).to eq(1)
+ expect(sgids_of(ticket)).to all(satisfy { |sgid| resolves?(sgid) })
+ expect(Ticket.find(ticket.id).content.to_s).not_to include('☒')
+ end
+
+ it 'reports without writing in dry run' do
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>x</div>#{node(png_blob)}")
+ stale = sgids_of(ticket)
+ rotate_secret_key_base!
+
+ result = run(dry_run: true)
+
+ expect(result.to_h).to include(changed: 1, resigned: 1, dry_run: true)
+ expect(sgids_of(ticket)).to eq(stale)
+ end
+
+ it 'leaves nodes that already resolve alone and is idempotent' do
+ create(:ticket, project: project, organisation: organisation, content: "<div>x</div>#{node(png_blob)}")
+ rotate_secret_key_base!
+ run
+
+ expect(run.to_h).to include(changed: 0, resigned: 0)
+ end
+
+ it 'brings back a wiki mention within the organisation and re-derives the markdown body' do
+ target = create(:note, project: project, organisation: organisation, title: 'Zielnotiz')
+ note = create(:note, project: project, organisation: organisation, content: "<div>Siehe</div>#{mention(target)}")
+ rotate_secret_key_base!
+ note.update_column(:markdown_body, 'stale')
+
+ expect(run.resigned).to eq(1)
+ expect(resolves?(sgids_of(note).first)).to be(true)
+ expect(note.reload.markdown_body).to eq(Wiki::MarkdownSerializer.new.to_markdown(note.content.body.to_html))
+ end
+
+ it 'refuses an image that is not attached to this text' do
+ foreign = png_blob('fremd.png')
+ ticket = create(:ticket, project: project, organisation: organisation, content: '<div>x</div>')
+ ticket.content.update_column(:body, "<div>x</div>#{node(foreign)}")
+ rotate_secret_key_base!
+
+ result = run
+
+ expect(result.resigned).to eq(0)
+ expect(result.refused).to contain_exactly(hash_including(rich_text_id: ticket.content.id, target_type: 'ActiveStorage::Blob', target_id: foreign.id))
+ expect(resolves?(sgids_of(ticket).first)).to be(false)
+ end
+
+ it 'refuses a mention of a record in another organisation' do
+ other = create(:organisation)
+ target = ActsAsTenant.with_tenant(other) do
+ create(:note, project: create(:project, organisation: other), organisation: other, title: 'Fremd')
+ end
+ note = create(:note, project: project, organisation: organisation, content: '<div>x</div>')
+ note.content.update_column(:body, "<div>x</div>#{mention(target)}")
+ rotate_secret_key_base!
+
+ result = run
+
+ expect(result.resigned).to eq(0)
+ expect(result.refused).to contain_exactly(hash_including(target_type: 'Note', target_id: target.id))
+ end
+
+ it 'refuses a sgid the old key did not sign, without decoding it' do
+ blob = png_blob
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>x</div>#{node(blob)}")
+ rotate_secret_key_base!
+
+ result = described_class.call(old_secret_key_base: 'not-the-old-key' * 8, dry_run: false)
+
+ expect(result.to_h).to include(resigned: 0, unreadable: 1)
+ expect(resolves?(sgids_of(ticket).first)).to be(false)
+ end
+
+ it 'lists an image whose blob is gone so it can be restored from the backup' do
+ blob = png_blob
+ ticket = create(:ticket, project: project, organisation: organisation, content: "<div>x</div>#{node(blob)}")
+ ticket.content.embeds.each(&:destroy!)
+ blob.purge
+ rotate_secret_key_base!
+
+ result = run
+
+ expect(result.resigned).to eq(0)
+ expect(result.gone).to contain_exactly(hash_including(rich_text_id: ticket.content.id, target_type: 'ActiveStorage::Blob', target_id: blob.id))
+ end
+
+ it 'refuses to run without the old key' do
+ expect { described_class.call(old_secret_key_base: '', dry_run: true) }.to raise_error(ArgumentError)
+ end
+end