decidim-apartment 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE-AGPLv3.txt +661 -0
  3. data/README.md +167 -0
  4. data/Rakefile +405 -0
  5. data/app/commands/decidim/apartment/create_tenant_command.rb +94 -0
  6. data/app/commands/decidim/apartment/noop_settings_tab_command.rb +13 -0
  7. data/app/commands/decidim/apartment/performance/create_seed_tentant.rb +194 -0
  8. data/app/controllers/decidim/apartment/tenants_controller.rb +29 -0
  9. data/app/forms/decidim/apartment/admin/organization_settings_form.rb +44 -0
  10. data/app/forms/decidim/apartment/tenant_form.rb +35 -0
  11. data/app/helpers/decidim/apartment/dashboard_helper.rb +17 -0
  12. data/app/models/decidim/apartment/distribution_host.rb +21 -0
  13. data/app/models/decidim/apartment/distribution_key.rb +91 -0
  14. data/app/overrides/apartment_edit_organization.rb +21 -0
  15. data/app/overrides/apartment_system_asset.rb +10 -0
  16. data/app/packs/entrypoints/apartment_system_styles.scss +1 -0
  17. data/app/packs/stylesheets/decidim/apartment/system/_apartment_system_styles.scss +95 -0
  18. data/app/services/active_storage/service/apartment_disk_storage_service.rb +14 -0
  19. data/app/services/active_storage/service/apartment_s3_storage_service.rb +24 -0
  20. data/app/views/decidim/apartment/dashboard/_apartment.html.erb +55 -0
  21. data/app/views/decidim/apartment/dashboard/show.html.erb +3 -0
  22. data/app/views/decidim/apartment/organizations/_organizations_list.html.erb +45 -0
  23. data/app/views/decidim/apartment/organizations/index.html.erb +9 -0
  24. data/app/views/decidim/apartment/organizations/new.html.erb +11 -0
  25. data/config/assets.rb +15 -0
  26. data/config/locales/decidim_apartment.en.yml +58 -0
  27. data/config/locales/decidim_apartment_toggle.en.yml +15 -0
  28. data/db/migrate/20250814075441_add_apartment_distribution_key.rb +15 -0
  29. data/db/migrate/20260907100000_add_apartment_distribution_hosts.rb +32 -0
  30. data/lib/decidim/apartment/active_storage_wrap.rb +51 -0
  31. data/lib/decidim/apartment/allowed_hosts.rb +78 -0
  32. data/lib/decidim/apartment/cache_namespace.rb +38 -0
  33. data/lib/decidim/apartment/config_registry.rb +102 -0
  34. data/lib/decidim/apartment/configuration.rb +11 -0
  35. data/lib/decidim/apartment/convert/attachment_integrity.rb +130 -0
  36. data/lib/decidim/apartment/convert/constraint_graph_pruner.rb +183 -0
  37. data/lib/decidim/apartment/convert/errors.rb +9 -0
  38. data/lib/decidim/apartment/convert/host_gate.rb +76 -0
  39. data/lib/decidim/apartment/convert/org_distribution_report.rb +106 -0
  40. data/lib/decidim/apartment/convert/org_metrics.rb +164 -0
  41. data/lib/decidim/apartment/convert/organization_converter.rb +154 -0
  42. data/lib/decidim/apartment/convert/organization_pruner.rb +210 -0
  43. data/lib/decidim/apartment/convert/organization_resolver.rb +386 -0
  44. data/lib/decidim/apartment/convert/paper_trail_report.rb +127 -0
  45. data/lib/decidim/apartment/convert/preflight.rb +140 -0
  46. data/lib/decidim/apartment/convert/schema_cloner.rb +157 -0
  47. data/lib/decidim/apartment/convert/storage_preconditions.rb +43 -0
  48. data/lib/decidim/apartment/convert/storage_relocator.rb +118 -0
  49. data/lib/decidim/apartment/convert/table_registry.rb +109 -0
  50. data/lib/decidim/apartment/convert.rb +20 -0
  51. data/lib/decidim/apartment/demo/blob.rb +31 -0
  52. data/lib/decidim/apartment/demo/city.rb +107 -0
  53. data/lib/decidim/apartment/demo/education.rb +83 -0
  54. data/lib/decidim/apartment/demo/foss.rb +153 -0
  55. data/lib/decidim/apartment/demo/homepage.rb +39 -0
  56. data/lib/decidim/apartment/demo/localized.rb +27 -0
  57. data/lib/decidim/apartment/demo/provision.rb +107 -0
  58. data/lib/decidim/apartment/demo/runner.rb +66 -0
  59. data/lib/decidim/apartment/demo/system_admin.rb +24 -0
  60. data/lib/decidim/apartment/demo.rb +19 -0
  61. data/lib/decidim/apartment/elevator.rb +20 -0
  62. data/lib/decidim/apartment/engine.rb +140 -0
  63. data/lib/decidim/apartment/excluded_model_pin.rb +40 -0
  64. data/lib/decidim/apartment/host_registry.rb +71 -0
  65. data/lib/decidim/apartment/import/confirm_prompt.rb +46 -0
  66. data/lib/decidim/apartment/import/database_restorer.rb +105 -0
  67. data/lib/decidim/apartment/import/dump_host_extractor.rb +67 -0
  68. data/lib/decidim/apartment/import/dump_preview.rb +96 -0
  69. data/lib/decidim/apartment/import/dump_transformer.rb +87 -0
  70. data/lib/decidim/apartment/import/errors.rb +9 -0
  71. data/lib/decidim/apartment/import/provision_tenant.rb +50 -0
  72. data/lib/decidim/apartment/import/schema_auditor.rb +118 -0
  73. data/lib/decidim/apartment/import/storage_migrator.rb +71 -0
  74. data/lib/decidim/apartment/import/tenant_context.rb +226 -0
  75. data/lib/decidim/apartment/import/tenant_importer.rb +73 -0
  76. data/lib/decidim/apartment/import/verifier.rb +58 -0
  77. data/lib/decidim/apartment/import.rb +15 -0
  78. data/lib/decidim/apartment/ops/attribute_cryptor.rb +68 -0
  79. data/lib/decidim/apartment/ops/ciphertext_rewriter.rb +230 -0
  80. data/lib/decidim/apartment/ops/encrypted_attribute_catalog.rb +106 -0
  81. data/lib/decidim/apartment/ops/encrypted_attribute_registry.rb +74 -0
  82. data/lib/decidim/apartment/ops/postgres_permissions.rb +179 -0
  83. data/lib/decidim/apartment/ops/secret_key_preflight.rb +94 -0
  84. data/lib/decidim/apartment/ops/secret_key_rotation.rb +226 -0
  85. data/lib/decidim/apartment/ops/storage_transfer.rb +188 -0
  86. data/lib/decidim/apartment/overrides/active_job_with_tenant.rb +38 -0
  87. data/lib/decidim/apartment/overrides/core_seeds.rb +31 -0
  88. data/lib/decidim/apartment/overrides/create_organization_command.rb +69 -0
  89. data/lib/decidim/apartment/overrides/dashboard_controller.rb +30 -0
  90. data/lib/decidim/apartment/overrides/decidim_seed.rb +16 -0
  91. data/lib/decidim/apartment/overrides/organizations_controller_overrides.rb +75 -0
  92. data/lib/decidim/apartment/overrides/postgresql_enable_extension.rb +15 -0
  93. data/lib/decidim/apartment/overrides/postgresql_schema_adapter.rb +34 -0
  94. data/lib/decidim/apartment/overrides/postgresql_schema_import.rb +35 -0
  95. data/lib/decidim/apartment/overrides/postgresql_schema_search_path.rb +15 -0
  96. data/lib/decidim/apartment/overrides/postgresql_schema_statements.rb +17 -0
  97. data/lib/decidim/apartment/overrides/seeds.rb +52 -0
  98. data/lib/decidim/apartment/overrides/tenant_init_without_database.rb +19 -0
  99. data/lib/decidim/apartment/overrides/update_organization_command.rb +38 -0
  100. data/lib/decidim/apartment/postgres_extensions.rb +198 -0
  101. data/lib/decidim/apartment/rake_replace.rb +21 -0
  102. data/lib/decidim/apartment/schema_search_path.rb +43 -0
  103. data/lib/decidim/apartment/system_organization.rb +67 -0
  104. data/lib/decidim/apartment/test/factories.rb +11 -0
  105. data/lib/decidim/apartment/test/seeds/association_1.jpg +0 -0
  106. data/lib/decidim/apartment/test/seeds/association_2.jpeg +0 -0
  107. data/lib/decidim/apartment/test/seeds/association_3.jpg +0 -0
  108. data/lib/decidim/apartment/test/seeds/association_4.jpg +0 -0
  109. data/lib/decidim/apartment/test/seeds/bg_Dusty Grass.png +0 -0
  110. data/lib/decidim/apartment/test/seeds/bg_Hyper Blue.png +0 -0
  111. data/lib/decidim/apartment/test/seeds/bg_Moonwalker.png +0 -0
  112. data/lib/decidim/apartment/test/seeds/bg_Neon Green.png +0 -0
  113. data/lib/decidim/apartment/test/seeds/bg_Visual Blue.png +0 -0
  114. data/lib/decidim/apartment/test/seeds/bg_hinehouse.png +0 -0
  115. data/lib/decidim/apartment/test/seeds/city_1.jpg +0 -0
  116. data/lib/decidim/apartment/test/seeds/city_2.jpg +0 -0
  117. data/lib/decidim/apartment/test/seeds/city_3.jpg +0 -0
  118. data/lib/decidim/apartment/test/seeds/city_4.webp +0 -0
  119. data/lib/decidim/apartment/test/seeds/city_5.jpg +0 -0
  120. data/lib/decidim/apartment/test/seeds/debian.jpeg +0 -0
  121. data/lib/decidim/apartment/test/seeds/democratic_school_1.jpg +0 -0
  122. data/lib/decidim/apartment/test/seeds/drupal.jpg +0 -0
  123. data/lib/decidim/apartment/test/seeds/foss.jpg +0 -0
  124. data/lib/decidim/apartment/test/seeds/immich.jpg +0 -0
  125. data/lib/decidim/apartment/test/seeds/kid_1.jpg +0 -0
  126. data/lib/decidim/apartment/test/seeds/kid_2.jpg +0 -0
  127. data/lib/decidim/apartment/test/seeds/montessori_1.jpg +0 -0
  128. data/lib/decidim/apartment/test/seeds/montessori_2.jpg +0 -0
  129. data/lib/decidim/apartment/test/seeds/neighboor_1.jpg +0 -0
  130. data/lib/decidim/apartment/test/seeds/neighbor_2.jpg +0 -0
  131. data/lib/decidim/apartment/test/seeds/neighbor_3.jpg +0 -0
  132. data/lib/decidim/apartment/test/seeds/pattern_cubes-3_4_2_0-0_0_1__hsla(240, 7_, 18_, 1.00)_hsla(47, 81_, 61_, 1.00).png +0 -0
  133. data/lib/decidim/apartment/test/seeds/pattern_cubes-3_4_2_0-0_55_1__hsla(240, 7_, 18_, 1.00)_hsla(47, 81_, 61_, 1.00)(1).png +0 -0
  134. data/lib/decidim/apartment/test/seeds/pattern_cubes-3_4_2_0-0_55_1__hsla(240, 7_, 18_, 1.00)_hsla(47, 81_, 61_, 1.00).png +0 -0
  135. data/lib/decidim/apartment/test/seeds/pattern_diamonds-1_1_10_0-0_0_1__hsla(240, 7_, 18_, 1.00)_hsla(174, 100_, 29_, 1.00).png +0 -0
  136. data/lib/decidim/apartment/test/seeds/pattern_diamonds-1_1_2_0-0_0_1__hsla(240, 7_, 18_, 1.00)_hsla(174, 100_, 29_, 1.00).png +0 -0
  137. data/lib/decidim/apartment/test/seeds/pattern_diamonds-1_5_10_0-0_0_1__hsla(240, 7_, 18_, 1.00)_hsla(174, 100_, 29_, 1.00).png +0 -0
  138. data/lib/decidim/apartment/test/seeds/pattern_diamonds-1_5_2_0-0_0_1__hsla(240, 7_, 18_, 1.00)_hsla(174, 100_, 29_, 1.00).png +0 -0
  139. data/lib/decidim/apartment/test/seeds/pattern_new_01.png +0 -0
  140. data/lib/decidim/apartment/test/seeds/pattern_new_02.png +0 -0
  141. data/lib/decidim/apartment/test/seeds/pattern_new_03.png +0 -0
  142. data/lib/decidim/apartment/test/seeds/pattern_squares_01.png +0 -0
  143. data/lib/decidim/apartment/test/seeds/pattern_squares_02.png +0 -0
  144. data/lib/decidim/apartment/test/seeds/pattern_squares_03.png +0 -0
  145. data/lib/decidim/apartment/test/seeds/pattern_squares_04.png +0 -0
  146. data/lib/decidim/apartment/test/seeds/pattern_squares_05.png +0 -0
  147. data/lib/decidim/apartment/test/seeds/pattern_squares_06.png +0 -0
  148. data/lib/decidim/apartment/test/seeds/pattern_squares_07.png +0 -0
  149. data/lib/decidim/apartment/test/seeds/pattern_squares_08.png +0 -0
  150. data/lib/decidim/apartment/test/seeds/pattern_squares_09.png +0 -0
  151. data/lib/decidim/apartment/test/seeds/pattern_squares_10.png +0 -0
  152. data/lib/decidim/apartment/test/seeds/pattern_squares_11.png +0 -0
  153. data/lib/decidim/apartment/test/seeds/pattern_squares_12.png +0 -0
  154. data/lib/decidim/apartment/test/seeds/pattern_squares_13.png +0 -0
  155. data/lib/decidim/apartment/test/seeds/pattern_squares_14.png +0 -0
  156. data/lib/decidim/apartment/test/seeds/pattern_squares_15.png +0 -0
  157. data/lib/decidim/apartment/test/seeds/pattern_squares_16.png +0 -0
  158. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_01.png +0 -0
  159. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_02.png +0 -0
  160. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_03.png +0 -0
  161. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_04.png +0 -0
  162. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_05.png +0 -0
  163. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_06.png +0 -0
  164. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_07.png +0 -0
  165. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_08.png +0 -0
  166. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_09.png +0 -0
  167. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_10.png +0 -0
  168. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_11.png +0 -0
  169. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_12.png +0 -0
  170. data/lib/decidim/apartment/test/seeds/pattern_squares_and_circles_13.png +0 -0
  171. data/lib/decidim/apartment/test/seeds/rails.jpg +0 -0
  172. data/lib/decidim/apartment/test/seeds/school_1.jpg +0 -0
  173. data/lib/decidim/apartment/test/seeds/school_3.jpg +0 -0
  174. data/lib/decidim/apartment/test/seeds/school_4.jpg +0 -0
  175. data/lib/decidim/apartment/test/seeds/school_5.jpg +0 -0
  176. data/lib/decidim/apartment/test/seeds/silverstripe.jpg +0 -0
  177. data/lib/decidim/apartment/test/seeds/street_1.jpg +0 -0
  178. data/lib/decidim/apartment/test/seeds/street_2.jpg +0 -0
  179. data/lib/decidim/apartment/test/seeds/street_3.jpg +0 -0
  180. data/lib/decidim/apartment/test/seeds/urban_agri_1.webp +0 -0
  181. data/lib/decidim/apartment/test/seeds/urban_agri_2.jpg +0 -0
  182. data/lib/decidim/apartment/test/seeds/urban_agri_3.jpg +0 -0
  183. data/lib/decidim/apartment/test/seeds/urban_agri_4.jpg +0 -0
  184. data/lib/decidim/apartment/test/seeds/world-map-colors.png +0 -0
  185. data/lib/decidim/apartment/version.rb +44 -0
  186. data/lib/decidim/apartment.rb +69 -0
  187. data/lib/tasks/decidim_apartment_check_install.rake +58 -0
  188. data/lib/tasks/decidim_apartment_convert.rake +60 -0
  189. data/lib/tasks/decidim_apartment_gem_manager.rake +62 -0
  190. data/lib/tasks/decidim_apartment_import.rake +39 -0
  191. data/lib/tasks/decidim_apartment_install_extension.rake +49 -0
  192. data/lib/tasks/decidim_apartment_performance_seed.rake +12 -0
  193. data/lib/tasks/decidim_apartment_rotate.rake +17 -0
  194. data/lib/tasks/decidim_apartment_storage.rake +27 -0
  195. data/lib/tasks/decidim_download_your_data_tasks.rake +121 -0
  196. data/lib/tasks/decidim_mailers.rake +38 -0
  197. data/lib/tasks/decidim_meetings.rake +30 -0
  198. data/lib/tasks/decidim_metrics_tasks.rake +29 -0
  199. data/lib/tasks/decidim_open_data_tasks.rake +24 -0
  200. data/lib/tasks/decidim_participatory_processes.rake +20 -0
  201. data/lib/tasks/decidim_reminders_tasks.rake +24 -0
  202. metadata +361 -0
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Decidim
6
+ module Apartment
7
+ module Ops
8
+ ##
9
+ # Rotates AttributeEncryptor ciphertext from SECRET_KEY_BASE_FROM to
10
+ # SECRET_KEY_BASE_TO across Apartment tenants.
11
+ class SecretKeyRotation
12
+ KEY_FILE = "tmp/decidim_apartment_secret_key_base"
13
+ Result = Struct.new(:status, :lines, :exit_code, keyword_init: true)
14
+
15
+ class << self
16
+ def call
17
+ new.call
18
+ end
19
+ end
20
+
21
+ def initialize
22
+ @from = ENV["SECRET_KEY_BASE_FROM"].to_s
23
+ @to = ENV["SECRET_KEY_BASE_TO"].presence || SecureRandom.hex(64)
24
+ @lines = []
25
+ @tenant_reports = []
26
+ @plaintext = 0
27
+ @rewritten = 0
28
+ @models = 0
29
+ @sessions_deleted = 0
30
+ @public_lines = []
31
+ end
32
+
33
+ def call
34
+ abort_result = validate_inputs
35
+ return abort_result if abort_result
36
+
37
+ keys = selected_keys
38
+ return abort_with("no distribution keys selected") if keys.empty?
39
+
40
+ header(keys)
41
+ preflight_all(keys) || run_transaction(keys)
42
+ end
43
+
44
+ private
45
+
46
+ def validate_inputs
47
+ return abort_with("YES=1 is required") unless Import::ConfirmPrompt.auto_yes?
48
+ return abort_with("SECRET_KEY_BASE_FROM is required") if @from.blank?
49
+ return abort_with("SECRET_KEY_BASE_FROM and SECRET_KEY_BASE_TO must differ") if @from == @to
50
+ return abort_with("new secret_key_base length must be 128") unless @to.length == 128
51
+
52
+ nil
53
+ end
54
+
55
+ def selected_keys
56
+ ::Apartment::Tenant.switch("public") { load_keys(ENV.fetch("DISTRIBUTION_KEY", "*")) }
57
+ end
58
+
59
+ def load_keys(filter)
60
+ scope = DistributionKey.all
61
+ return scope.to_a if filter.blank? || filter == "*"
62
+
63
+ key = scope.find_by(key: filter)
64
+ key ? [key] : []
65
+ end
66
+
67
+ def header(keys)
68
+ filter = ENV.fetch("DISTRIBUTION_KEY", "*")
69
+ @lines << "decidim_apartment:rotate"
70
+ @lines << "distribution_key: #{filter} (#{keys.size})"
71
+ @lines << "new_key_length: #{@to.length}"
72
+ print_not_loaded
73
+ end
74
+
75
+ def print_not_loaded
76
+ names = Decidim::Apartment.encrypted_attribute_registry.not_loaded
77
+ return if names.empty?
78
+
79
+ @lines << ""
80
+ @lines << "not_loaded:"
81
+ names.each { |name| @lines << " #{name}" }
82
+ end
83
+
84
+ def preflight_all(keys)
85
+ @lines << ""
86
+ @lines << "preflight:"
87
+ keys.each do |key|
88
+ failure = preflight_one(key)
89
+ return failure if failure
90
+ end
91
+ nil
92
+ end
93
+
94
+ def preflight_one(key)
95
+ result = nil
96
+ key.switch { result = SecretKeyPreflight.new(from: @from, to: @to).call }
97
+ if result.ok
98
+ @lines << " #{key.key} #{key.host} ok #{result.probe}"
99
+ return nil
100
+ end
101
+
102
+ @lines << " #{key.key} #{key.host} fail #{result.message}"
103
+ abort_with(result.message)
104
+ end
105
+
106
+ def run_transaction(keys)
107
+ ActiveRecord::Base.transaction do
108
+ rewrite_public
109
+ keys.each { |key| rewrite_tenant(key) }
110
+ wipe_sessions
111
+ end
112
+ finish_ok
113
+ rescue CiphertextRewriter::DecryptError => e
114
+ fail_result(e.message)
115
+ end
116
+
117
+ def rewrite_public
118
+ catalog = EncryptedAttributeCatalog.new
119
+ @public_lines.concat(rewrite_locations(catalog.public_locations))
120
+ end
121
+
122
+ def rewrite_tenant(key)
123
+ reports = []
124
+ key.switch do
125
+ reports = rewrite_locations(EncryptedAttributeCatalog.new.tenant_locations)
126
+ reports << bump_session_tokens
127
+ end
128
+ append_tenant(key, reports)
129
+ end
130
+
131
+ def append_tenant(key, reports)
132
+ @lines << ""
133
+ @lines << "#{key.key} #{key.host}"
134
+ reports.each { |line| @lines << " #{line}" }
135
+ @tenant_reports << key
136
+ end
137
+
138
+ def rewrite_locations(locations)
139
+ rewriter = CiphertextRewriter.new(from: @from, to: @to)
140
+ locations.map { |loc| format_stats(loc, rewriter.rewrite_location(loc)) }
141
+ end
142
+
143
+ def format_stats(location, stats)
144
+ @rewritten += stats.rewritten
145
+ @plaintext += stats.plaintext
146
+ @models += 1
147
+ "#{location.model.name} #{location.source} #{location.label} " \
148
+ "rows=#{stats.rows} rewritten=#{stats.rewritten} plaintext=#{stats.plaintext}"
149
+ end
150
+
151
+ def bump_session_tokens
152
+ count = 0
153
+ Decidim::User.find_each do |user|
154
+ user.update_columns(session_token: SecureRandom.hex)
155
+ count += 1
156
+ end
157
+ "Decidim::User session_token rows=#{count} bumped=#{count}"
158
+ end
159
+
160
+ def wipe_sessions
161
+ return unless Decidim::Toggle.gem_present?("activerecord-session_store")
162
+
163
+ ::Apartment::Tenant.switch("public") do
164
+ @sessions_deleted = ActiveRecord::SessionStore::Session.delete_all
165
+ end
166
+ @public_lines << "ActiveRecord::SessionStore::Session deleted=#{@sessions_deleted}"
167
+ end
168
+
169
+ def finish_ok
170
+ flush_public_lines
171
+ status = @plaintext.positive? ? "PARTIAL" : "SUCCESS"
172
+ write_key_file
173
+ append_result(status)
174
+ emit(status, 0)
175
+ end
176
+
177
+ def flush_public_lines
178
+ return if @public_lines.empty?
179
+
180
+ @lines << ""
181
+ @lines << "public:"
182
+ @public_lines.each { |line| @lines << " #{line}" }
183
+ end
184
+
185
+ def append_result(status)
186
+ @lines << ""
187
+ @lines << "Result: #{status}"
188
+ @lines << summary_line
189
+ @lines << "key_file: #{KEY_FILE}"
190
+ end
191
+
192
+ def summary_line
193
+ "tenants=#{@tenant_reports.size} models=#{@models} rows_rewritten=#{@rewritten} " \
194
+ "plaintext_left=#{@plaintext} sessions_deleted=#{@sessions_deleted}"
195
+ end
196
+
197
+ def write_key_file
198
+ path = Rails.root.join(KEY_FILE)
199
+ FileUtils.mkdir_p(path.dirname)
200
+ File.write(path, @to)
201
+ File.chmod(0o600, path)
202
+ end
203
+
204
+ def abort_with(message)
205
+ @lines << ""
206
+ @lines << "Result: ABORTED"
207
+ @lines << message
208
+ emit("ABORTED", 1)
209
+ end
210
+
211
+ def fail_result(message)
212
+ @lines << ""
213
+ @lines << "Result: FAILED"
214
+ @lines << message
215
+ @lines << "rolled back"
216
+ emit("FAILED", 1)
217
+ end
218
+
219
+ def emit(status, code)
220
+ puts @lines.join("\n")
221
+ Result.new(status: status, lines: @lines, exit_code: code)
222
+ end
223
+ end
224
+ end
225
+ end
226
+ end
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Decidim
6
+ module Apartment
7
+ module Ops
8
+ ##
9
+ # Moves Active Storage blobs between local disk folder and ApartmentS3Storage for a tenant.
10
+ #
11
+ # Both directions expect Active Storage configured as ApartmentS3Storage (cloud side).
12
+ # Local files live under DISK_ROOT/<tenant>/… (default: Rails.root/storage).
13
+ class StorageTransfer
14
+ Result = Struct.new(:copied, :skipped, :missing, keyword_init: true)
15
+
16
+ class << self
17
+ def to_s3(tenant:)
18
+ new(tenant: tenant, direction: :to_s3).call
19
+ end
20
+
21
+ def to_local(tenant:)
22
+ new(tenant: tenant, direction: :to_local).call
23
+ end
24
+ end
25
+
26
+ def initialize(tenant:, direction:)
27
+ @tenant = tenant.to_s
28
+ @direction = direction
29
+ @dry_run = Import::ConfirmPrompt.dry_run?
30
+ end
31
+
32
+ def call
33
+ assert_tenant!
34
+ assert_s3_service!
35
+
36
+ Import::ConfirmPrompt.ask(
37
+ "Transfer Active Storage blobs #{@direction} for tenant #{@tenant}? [y/N]"
38
+ )
39
+
40
+ result = Result.new(copied: 0, skipped: 0, missing: 0)
41
+ distribution_key.switch do
42
+ raise Import::ImportError, "active_storage_blobs missing in tenant #{@tenant}" unless ActiveRecord::Base.connection.table_exists?(:active_storage_blobs)
43
+
44
+ keys = ActiveRecord::Base.connection.select_values("SELECT key FROM active_storage_blobs")
45
+ keys.each { |key| transfer_key!(key, result) }
46
+ end
47
+
48
+ puts "StorageTransfer #{@direction}: copied=#{result.copied} skipped=#{result.skipped} missing=#{result.missing}"
49
+ raise Import::ImportError, "StorageTransfer: #{result.missing} blob(s) missing at source" if result.missing.positive?
50
+
51
+ puts "Note: switch Active Storage to ApartmentDiskStorage after download (DISK_ROOT=#{disk_root})." if @direction == :to_local
52
+
53
+ result
54
+ end
55
+
56
+ private
57
+
58
+ def distribution_key
59
+ @distribution_key ||= ::Apartment::Tenant.switch("public") do
60
+ DistributionKey.find_by!(key: @tenant)
61
+ end
62
+ end
63
+
64
+ def assert_tenant!
65
+ distribution_key
66
+ rescue ActiveRecord::RecordNotFound
67
+ raise Import::ImportError, "unknown TENANT=#{@tenant}"
68
+ end
69
+
70
+ def assert_s3_service!
71
+ service = ActiveStorage::Blob.service
72
+ return if service.is_a?(ActiveStorage::Service::ApartmentS3StorageService)
73
+
74
+ raise Import::ImportError,
75
+ "storage transfer requires ApartmentS3Storage (got #{service.class.name})"
76
+ end
77
+
78
+ def disk_root
79
+ ENV.fetch("DISK_ROOT") { Rails.root.join("storage").to_s }
80
+ end
81
+
82
+ def transfer_key!(key, result)
83
+ case @direction
84
+ when :to_s3 then upload_to_s3!(key, result)
85
+ when :to_local then download_to_local!(key, result)
86
+ end
87
+ end
88
+
89
+ def upload_to_s3!(key, result)
90
+ service = ActiveStorage::Blob.service
91
+ if object_exists?(service, key)
92
+ result.skipped += 1
93
+ return
94
+ end
95
+
96
+ source = find_disk_path(key)
97
+ unless source
98
+ result.missing += 1
99
+ puts " missing local file for key=#{key}"
100
+ return
101
+ end
102
+
103
+ if @dry_run
104
+ puts " [dry-run] would upload #{key}"
105
+ result.copied += 1
106
+ return
107
+ end
108
+
109
+ File.open(source, "rb") { |io| service.upload(key, io, **s3_upload_options(key)) }
110
+ result.copied += 1
111
+ end
112
+
113
+ def s3_upload_options(key)
114
+ blob = ActiveStorage::Blob.find_by!(key: key)
115
+
116
+ {
117
+ checksum: blob.checksum,
118
+ content_type: blob.content_type_for_serving,
119
+ filename: blob.filename,
120
+ disposition: disposition_for(blob.content_type)
121
+ }
122
+ end
123
+
124
+ def disposition_for(content_type)
125
+ return :inline if ActiveStorage.content_types_allowed_inline.include?(content_type)
126
+
127
+ :attachment
128
+ end
129
+
130
+ def download_to_local!(key, result)
131
+ dest = tenant_disk_path(key)
132
+ if File.exist?(dest)
133
+ result.skipped += 1
134
+ return
135
+ end
136
+
137
+ service = ActiveStorage::Blob.service
138
+ unless object_exists?(service, key)
139
+ result.missing += 1
140
+ puts " missing remote object for key=#{key}"
141
+ return
142
+ end
143
+
144
+ if @dry_run
145
+ puts " [dry-run] would download #{key}"
146
+ result.copied += 1
147
+ return
148
+ end
149
+
150
+ raise Import::ImportError, "Active Storage service cannot download key=#{key}" unless service.respond_to?(:download)
151
+
152
+ FileUtils.mkdir_p(File.dirname(dest))
153
+ File.open(dest, "wb") do |file|
154
+ file.binmode
155
+ file.write(service.download(key))
156
+ end
157
+ result.copied += 1
158
+ end
159
+
160
+ def find_disk_path(key)
161
+ [
162
+ tenant_disk_path(key),
163
+ File.join(disk_root, "public", folder_for(key), key),
164
+ File.join(disk_root, folder_for(key), key)
165
+ ].find { |path| File.exist?(path) }
166
+ end
167
+
168
+ def tenant_disk_path(key)
169
+ File.join(disk_root, @tenant, folder_for(key), key)
170
+ end
171
+
172
+ def folder_for(key)
173
+ [key[0..1], key[2..3]].join("/")
174
+ end
175
+
176
+ def object_exists?(service, key)
177
+ if service.respond_to?(:exist?)
178
+ service.exist?(key)
179
+ else
180
+ service.send(:object_for, key).exists?
181
+ end
182
+ rescue StandardError
183
+ false
184
+ end
185
+ end
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ ##
7
+ # Persist the current tenant on the ActiveJob payload and switch schema
8
+ # before adapters deserialize GlobalID arguments.
9
+ module ActiveJobWithTenant
10
+ def serialize
11
+ super.merge("tenant" => ::Apartment::Tenant.current.to_s)
12
+ end
13
+
14
+ # ponytail: prepend execute — around_perform is after GID lookup;
15
+ # around_execute cannot read job_data (Rails 7).
16
+ # ceiling: raw Sidekiq::Worker never hits execute; middleware only if we support those.
17
+ module Execute
18
+ def execute(job_data)
19
+ tenant = job_data["tenant"]
20
+ return super unless switchable_tenant?(tenant)
21
+
22
+ ::Apartment::Tenant.switch(tenant) { super }
23
+ end
24
+
25
+ private
26
+
27
+ def switchable_tenant?(tenant)
28
+ tenant.present? && known_tenants.include?(tenant)
29
+ end
30
+
31
+ def known_tenants
32
+ ::Apartment.tenant_names + [::Apartment.default_tenant]
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ module CoreSeeds
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ alias_method :apartment_original_call, :call
11
+ def call
12
+ host = ENV.fetch("DECIDIM_HOST", "localhost")
13
+ tenant_form = Decidim::Apartment::TenantForm.new({ host: host })
14
+ raise tenant_form.errors.full_messages.join(", ") unless tenant_form.valid?
15
+
16
+ Decidim::Apartment::CreateTenantCommand.call(tenant_form) do
17
+ on(:ok) do |distribution_key|
18
+ distribution_key.switch do
19
+ apartment_original_call
20
+ end
21
+ end
22
+ on(:invalid) do
23
+ raise "Failed to create tenant with host: #{host}"
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ ##
7
+ # Overrides CreateOrganizationCommand to handle tenant switch correctly
8
+ module CreateOrganizationCommand
9
+ extend ActiveSupport::Concern
10
+
11
+ included do
12
+ alias_method :apartment_original_call, :call
13
+
14
+ def call
15
+ return apartment_original_call if form.invalid?
16
+
17
+ if tenant_form.invalid?
18
+ tenant_form.errors.each do |err|
19
+ form.errors.add(err.attribute, err.type, **err.options)
20
+ end
21
+ return broadcast(:invalid)
22
+ end
23
+ # Create a distribution key and a tenant
24
+ tenant = create_tenant!
25
+
26
+ return broadcast(:invalid) unless tenant
27
+
28
+ begin
29
+ org_result = tenant.switch do
30
+ apartment_original_call
31
+ end
32
+ rescue ::Apartment::TenantNotFound
33
+ org_result = nil
34
+ end
35
+ unless org_result
36
+ # Rollback and drop the tenant
37
+ tenant.destroy
38
+ ::Apartment::Tenant.drop(tenant.key)
39
+ return self
40
+ end
41
+
42
+ sync_hosts_after_create!(tenant)
43
+ self
44
+ end
45
+
46
+ private
47
+
48
+ def create_tenant!
49
+ result = Decidim::Apartment::CreateTenantCommand.call(tenant_form)
50
+ return nil unless result[:ok]
51
+
52
+ result[:ok]
53
+ end
54
+
55
+ def tenant_form
56
+ @tenant_form ||= Decidim::Apartment::TenantForm.new({ host: form.host })
57
+ end
58
+
59
+ def sync_hosts_after_create!(tenant)
60
+ tenant.sync_hosts!(
61
+ primary_host: form.host,
62
+ secondary_hosts: form.secondary_hosts
63
+ )
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ ##
7
+ # Overrides DashboardController: public schema + apartment dashboard without Deface.
8
+ module DashboardController
9
+ extend ActiveSupport::Concern
10
+ included do
11
+ around_action :switch_public_schema
12
+ helper Decidim::Apartment::DashboardHelper
13
+ alias_method :apartment_origin_check_organizations_presence, :check_organizations_presence
14
+ end
15
+
16
+ def show
17
+ render template: "decidim/apartment/dashboard/show"
18
+ end
19
+
20
+ def switch_public_schema(&)
21
+ ::Apartment::Tenant.switch("public", &)
22
+ end
23
+
24
+ private
25
+
26
+ def check_organizations_presence; end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ # Replaces vanilla Decidim.seed! with curated multi-tenant demos.
7
+ module DecidimSeed
8
+ def seed!
9
+ return super if ENV["DECIDIM_APARTMENT_VANILLA_SEED"].present?
10
+
11
+ Decidim::Apartment::Demo::Runner.call
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ ##
7
+ # Overrides System Controller to manage organizations.
8
+ # As we now segregates organizations per tenant, we need to overload organization selection and update.
9
+ module OrganizationsControllerOverrides
10
+ extend ActiveSupport::Concern
11
+
12
+ included do
13
+ helper Decidim::Apartment::DashboardHelper
14
+ alias_method :apartment_index_organization, :index
15
+ alias_method :apartment_edit_organization, :edit
16
+ alias_method :apartment_resend_invitation, :resend_invitation
17
+ around_action :update_tenant_key, only: [:edit, :update]
18
+
19
+ def update_tenant_key(&block)
20
+ ensure_tenant!
21
+ match_tenant.switch(&block)
22
+ end
23
+
24
+ prepend(InstanceMethods)
25
+ end
26
+ ##
27
+ # Overrides of original methods
28
+ module InstanceMethods
29
+ def edit
30
+ if Decidim::Organization.count.zero?
31
+ return redirect_to decidim_system.new_organization_path(tenant: match_tenant.key),
32
+ alert: I18n.t("decidim.apartment.organizations.errors.no_organization")
33
+ end
34
+
35
+ @organization = Decidim::Organization.first
36
+ @organization.secondary_hosts ||= []
37
+ @form = form(::Decidim::System::UpdateOrganizationForm).from_model(@organization)
38
+ end
39
+
40
+ def index
41
+ @tenants = ::Decidim::Apartment::DistributionKey.all
42
+ render "decidim/apartment/organizations/index"
43
+ end
44
+
45
+ def resend_invitation
46
+ ensure_tenant!
47
+ match_tenant.switch do
48
+ apartment_resend_invitation
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def ensure_tenant!
55
+ return if match_tenant_key?
56
+
57
+ raise ActiveRecord::RecordNotFound,
58
+ I18n.t("decidim.apartment.organizations.errors.not_found")
59
+ end
60
+
61
+ def match_tenant_key?
62
+ match_tenant.present?
63
+ end
64
+
65
+ def match_tenant
66
+ @match_tenant ||= ::Decidim::Apartment::DistributionKey.for_system(
67
+ id: params[:id],
68
+ tenant: params[:tenant]
69
+ )
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Overrides
6
+ # Rails enable_extension without a schema follows search_path (tenant first).
7
+ # ponytail: qualify public; move leftovers out of shared_extensions after db:migrate
8
+ module PostgresqlEnableExtension
9
+ def enable_extension(name, **)
10
+ Decidim::Apartment::PostgresExtensions.new(self).enable!(name)
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end