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,230 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Re-encrypts one AttributeEncryptor string from one secret_key_base to another.
8
+ class CiphertextRewriter
9
+ class DecryptError < StandardError; end
10
+
11
+ Stats = Struct.new(:rows, :rewritten, :plaintext, keyword_init: true)
12
+
13
+ def initialize(from:, to:)
14
+ @from = from
15
+ @to = to
16
+ end
17
+
18
+ def rewrite_location(location)
19
+ stats = Stats.new(rows: 0, rewritten: 0, plaintext: 0)
20
+ location.model.find_each { |row| rewrite_row(row, location, stats) }
21
+ stats
22
+ end
23
+
24
+ def self.decrypt_string(value, secret_key_base:, generator_secret: "attribute")
25
+ new(from: secret_key_base, to: secret_key_base)
26
+ .decrypt_value(value, generator_secret)
27
+ end
28
+
29
+ def self.sample_ciphertext(from:)
30
+ new(from: from, to: from).sample_ciphertext
31
+ end
32
+
33
+ def self.raw_attribute(row, attr)
34
+ new(from: "", to: "").raw_attribute(row, attr)
35
+ end
36
+
37
+ def decrypt_value(value, generator_secret)
38
+ encryptor(@from, generator_secret).decrypt(value)
39
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage,
40
+ ActiveSupport::MessageVerifier::InvalidSignature
41
+ raise DecryptError, "cannot decrypt with provided secret_key_base" if framed?(value)
42
+
43
+ value
44
+ end
45
+
46
+ def sample_ciphertext
47
+ found = false
48
+ EncryptedAttributeCatalog.new.tenant_locations.each do |loc|
49
+ status = sample_location(loc)
50
+ return status if status.is_a?(String)
51
+
52
+ found ||= status
53
+ end
54
+ found ? :ok : :empty
55
+ end
56
+
57
+ private
58
+
59
+ def rewrite_row(row, location, stats)
60
+ stats.rows += 1
61
+ rewrite_row_body(row, location, stats)
62
+ rescue DecryptError => e
63
+ raise DecryptError, "#{location.model.name}##{row.id} #{location.label}: #{e.message}"
64
+ end
65
+
66
+ def rewrite_row_body(row, location, stats)
67
+ if location.source == :record_encryptor
68
+ rewrite_encryptor_row(row, location, stats)
69
+ else
70
+ rewrite_registry_row(row, location, stats)
71
+ end
72
+ end
73
+
74
+ def rewrite_encryptor_row(row, location, stats)
75
+ updates = {}
76
+ location.attributes.each do |attr|
77
+ result = rewrite_raw(raw_attribute(row, attr), location)
78
+ updates[attr] = result[:value]
79
+ bump_stats(stats, result[:status])
80
+ end
81
+ row.update_columns(updates) if updates.any?
82
+ end
83
+
84
+ def rewrite_registry_row(row, location, stats)
85
+ raw = raw_attribute(row, location.column)
86
+ result = rewrite_container(raw, location)
87
+ bump_stats(stats, result[:status])
88
+ row.update_columns(location.column => result[:value])
89
+ end
90
+
91
+ def raw_attribute(row, attr)
92
+ coerce_value(row.attributes_before_type_cast[attr.to_s])
93
+ end
94
+ public :raw_attribute
95
+
96
+ def coerce_value(raw)
97
+ return raw unless raw.is_a?(String)
98
+ return JSON.parse(raw) if raw.start_with?("{", "[")
99
+
100
+ raw
101
+ rescue JSON::ParserError
102
+ raw
103
+ end
104
+
105
+ def rewrite_container(raw, location)
106
+ return rewrite_json_key(raw, location) if location.json_key
107
+ return rewrite_json_strings(raw, location) if location.json_strings
108
+
109
+ rewrite_raw(raw, location)
110
+ end
111
+
112
+ def rewrite_json_key(raw, location)
113
+ hash = hash_dup(raw)
114
+ key = location.json_key.to_s
115
+ result = rewrite_raw(hash[key], location)
116
+ hash[key] = result[:value]
117
+ { value: hash, status: result[:status] }
118
+ end
119
+
120
+ def rewrite_json_strings(raw, location)
121
+ hash = hash_dup(raw)
122
+ status = :blank
123
+ hash.each_key do |key|
124
+ value = hash[key]
125
+ next unless value.is_a?(String) && value.present?
126
+
127
+ result = rewrite_raw(value, location)
128
+ hash[key] = result[:value]
129
+ status = prefer_status(status, result[:status])
130
+ end
131
+ { value: hash, status: status }
132
+ end
133
+
134
+ def hash_dup(raw)
135
+ return {} unless raw.is_a?(Hash)
136
+
137
+ raw.transform_keys(&:to_s)
138
+ end
139
+
140
+ def rewrite_raw(value, location)
141
+ return { value: value, status: :blank } if value.blank?
142
+ return rewrite_hash_values(value, location) if value.is_a?(Hash)
143
+
144
+ rewrite_one_string(value, location)
145
+ end
146
+
147
+ def rewrite_hash_values(hash, location)
148
+ status = :blank
149
+ rewritten = hash_dup(hash).transform_values do |value|
150
+ next value unless value.is_a?(String)
151
+
152
+ result = rewrite_one_string(value, location)
153
+ status = prefer_status(status, result[:status])
154
+ result[:value]
155
+ end
156
+ { value: rewritten, status: status }
157
+ end
158
+
159
+ def rewrite_one_string(value, location)
160
+ secret = location.generator_secret.call
161
+ plain = decrypt_value(value, secret)
162
+ return { value: value, status: :plaintext } if plain == value && !framed?(value)
163
+
164
+ { value: encryptor(@to, secret).encrypt(plain), status: :rewritten }
165
+ end
166
+
167
+ def encryptor(secret_key_base, generator_secret)
168
+ AttributeCryptor.new(
169
+ secret: generator_secret,
170
+ secret_key_base: secret_key_base
171
+ )
172
+ end
173
+
174
+ def framed?(value)
175
+ value.is_a?(String) && value.include?("--")
176
+ end
177
+
178
+ def bump_stats(stats, status)
179
+ stats.rewritten += 1 if status == :rewritten
180
+ stats.plaintext += 1 if status == :plaintext
181
+ end
182
+
183
+ def prefer_status(current, next_status)
184
+ return :rewritten if [current, next_status].include?(:rewritten)
185
+ return :plaintext if [current, next_status].include?(:plaintext)
186
+
187
+ current
188
+ end
189
+
190
+ def sample_location(location)
191
+ location.model.find_each do |row|
192
+ status = sample_row(row, location)
193
+ return status if status.is_a?(String)
194
+ return true if status
195
+ end
196
+ false
197
+ end
198
+
199
+ def sample_row(row, location)
200
+ location.attributes.each do |attr|
201
+ status = sample_value(raw_attribute(row, attr))
202
+ return status if status.is_a?(String)
203
+ return true if status
204
+ end
205
+ false
206
+ end
207
+
208
+ def sample_value(value)
209
+ ciphertext_strings(value).each do |string|
210
+ status = sample_string(string)
211
+ return status unless status == :continue
212
+ end
213
+ false
214
+ end
215
+
216
+ def ciphertext_strings(value)
217
+ list = value.is_a?(Hash) ? value.values.select { |v| v.is_a?(String) } : [value]
218
+ list.compact_blank
219
+ end
220
+
221
+ def sample_string(string)
222
+ decrypt_value(string, "attribute")
223
+ framed?(string) || :continue
224
+ rescue DecryptError => e
225
+ e.message
226
+ end
227
+ end
228
+ end
229
+ end
230
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Unions RecordEncryptor descendants with EncryptedAttributeRegistry entries.
8
+ class EncryptedAttributeCatalog
9
+ Location = Struct.new(
10
+ :model, :column, :attributes, :json_key, :json_strings,
11
+ :generator_secret, :source, :scope, :label,
12
+ keyword_init: true
13
+ )
14
+
15
+ def initialize(registry: Decidim::Apartment.encrypted_attribute_registry)
16
+ @registry = registry
17
+ end
18
+
19
+ def locations
20
+ Rails.application.eager_load!
21
+ record_encryptor_locations + registry_locations
22
+ end
23
+
24
+ def tenant_locations
25
+ locations.reject { |loc| loc.scope == :public }
26
+ end
27
+
28
+ def public_locations
29
+ locations.select { |loc| loc.scope == :public }
30
+ end
31
+
32
+ private
33
+
34
+ def record_encryptor_locations
35
+ # Engine models often inherit from their own ApplicationRecord
36
+ # (e.g. Decidim-decidim_awesome), not the host ApplicationRecord.
37
+ ActiveRecord::Base.descendants.filter_map { |model| encryptor_location(model) }
38
+ end
39
+
40
+ def encryptor_location(model)
41
+ return unless encryptor_model?(model)
42
+
43
+ build_encryptor_location(model)
44
+ end
45
+
46
+ def encryptor_model?(model)
47
+ return false if model.abstract_class?
48
+ return false unless live_model?(model)
49
+
50
+ model.included_modules.include?(Decidim::RecordEncryptor) &&
51
+ model.encrypted_attributes.present?
52
+ end
53
+
54
+ # Test subclasses stay in ActiveRecord::Base.descendants after their
55
+ # constant is removed. Rewriting them again decrypts with the wrong key.
56
+ def live_model?(model)
57
+ name = model.name
58
+ return false if name.blank?
59
+
60
+ name.safe_constantize.equal?(model)
61
+ end
62
+
63
+ def build_encryptor_location(model)
64
+ attrs = model.encrypted_attributes.dup
65
+ Location.new(
66
+ model: model, column: nil, attributes: attrs, json_key: nil,
67
+ json_strings: false, generator_secret: -> { "attribute" },
68
+ source: :record_encryptor, scope: scope_for(model),
69
+ label: attrs.join(",")
70
+ )
71
+ end
72
+
73
+ def registry_locations
74
+ @registry.entries.filter_map { |entry| registry_location(entry) }
75
+ end
76
+
77
+ def registry_location(entry)
78
+ model = entry.class_name.safe_constantize
79
+ return unless model
80
+
81
+ build_registry_location(model, entry)
82
+ end
83
+
84
+ def build_registry_location(model, entry)
85
+ Location.new(
86
+ model: model, column: entry.column, attributes: [entry.column],
87
+ json_key: entry.json_key, json_strings: entry.json_strings,
88
+ generator_secret: entry.generator_secret, source: :registry,
89
+ scope: scope_for(model), label: registry_label(entry)
90
+ )
91
+ end
92
+
93
+ def registry_label(entry)
94
+ return "#{entry.column}.#{entry.json_key}" if entry.json_key
95
+
96
+ entry.column.to_s
97
+ end
98
+
99
+ def scope_for(model)
100
+ excluded = ::Apartment.excluded_models.map(&:to_s)
101
+ excluded.include?(model.name) ? :public : :tenant
102
+ end
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Explicit list of AttributeEncryptor columns that do not use RecordEncryptor.
8
+ # Host apps extend this via Decidim::Apartment.register_encrypted_attribute.
9
+ class EncryptedAttributeRegistry
10
+ Entry = Struct.new(
11
+ :class_name, :column, :json_key, :json_strings, :generator_secret,
12
+ keyword_init: true
13
+ )
14
+
15
+ def initialize
16
+ @entries = {}
17
+ @not_loaded = Set.new
18
+ end
19
+
20
+ def add(class_name, column, json_key: nil, json_strings: false, generator_secret: nil)
21
+ name = class_name.to_s
22
+ model = name.safe_constantize
23
+ return remember_missing(name) unless model
24
+
25
+ store_entry(name, column, json_key, json_strings, generator_secret)
26
+ end
27
+
28
+ def entries
29
+ @entries.values
30
+ end
31
+
32
+ def not_loaded
33
+ @not_loaded.to_a.sort
34
+ end
35
+
36
+ def register_defaults!
37
+ add "Decidim::Organization", :smtp_settings, json_key: "encrypted_password"
38
+ add "Decidim::Organization", :omniauth_settings, json_strings: true
39
+ add_initiatives_default
40
+ end
41
+
42
+ private
43
+
44
+ def remember_missing(name)
45
+ @not_loaded << name
46
+ end
47
+
48
+ def store_entry(name, column, json_key, json_strings, generator_secret)
49
+ key = [name, column.to_s, json_key.to_s]
50
+ @entries[key] = build_entry(name, column, json_key, json_strings, generator_secret)
51
+ @not_loaded.delete(name)
52
+ end
53
+
54
+ def build_entry(name, column, json_key, json_strings, generator_secret)
55
+ Entry.new(
56
+ class_name: name,
57
+ column: column.to_sym,
58
+ json_key: json_key,
59
+ json_strings: json_strings,
60
+ generator_secret: generator_secret || -> { "attribute" }
61
+ )
62
+ end
63
+
64
+ def add_initiatives_default
65
+ add(
66
+ "Decidim::InitiativesVote",
67
+ :encrypted_metadata,
68
+ generator_secret: -> { Decidim::Initiatives.signature_handler_encryption_secret }
69
+ )
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,179 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Probes PostgreSQL privileges needed by import/convert bulk load paths.
8
+ class PostgresPermissions
9
+ Check = Struct.new(:name, :ok, :detail, keyword_init: true)
10
+
11
+ class << self
12
+ def audit!(connection: ActiveRecord::Base.connection, schema: "public", error_class: Import::ImportError,
13
+ require_psql: false)
14
+ checks = call(connection: connection, schema: schema, require_psql: require_psql)
15
+ raise_if_failed!(checks, error_class: error_class, connection: connection)
16
+ checks
17
+ end
18
+
19
+ def raise_if_failed!(checks, error_class: Import::ImportError, connection: ActiveRecord::Base.connection)
20
+ failures = checks.reject(&:ok)
21
+ return if failures.empty?
22
+
23
+ lines = failures.map { |check| " - #{check.name}: #{check.detail}" }
24
+ raise error_class,
25
+ "PostgreSQL permissions check failed (#{connection_db_user(connection)}):\n#{lines.join("\n")}"
26
+ end
27
+
28
+ def call(connection: ActiveRecord::Base.connection, schema: "public", require_psql: false)
29
+ checks = []
30
+ checks << check_current_user(connection)
31
+ checks << check_session_replication_role(connection)
32
+ checks << check_sequence_reset(connection, schema)
33
+ checks << check_create_schema(connection)
34
+ checks << check_pg_dump_cli(connection) if ::Apartment.use_sql
35
+ checks << check_psql_cli if require_psql
36
+ checks
37
+ end
38
+
39
+ def print_report!(checks)
40
+ puts "postgres permissions:"
41
+ checks.each do |check|
42
+ status = check.ok ? "ok" : "FAIL"
43
+ suffix = check.detail && !check.ok ? " — #{check.detail}" : ""
44
+ suffix = " (#{check.detail})" if check.ok && check.detail.present?
45
+ puts " #{check.name}: #{status}#{suffix}"
46
+ end
47
+ puts ""
48
+ end
49
+
50
+ private
51
+
52
+ def connection_db_user(connection)
53
+ connection.select_value("SELECT current_user")
54
+ end
55
+
56
+ def check_current_user(connection)
57
+ row = connection.select_one(<<~SQL.squish)
58
+ SELECT current_user AS user, usesuper AS superuser
59
+ FROM pg_user
60
+ WHERE usename = current_user
61
+ SQL
62
+ detail = "user=#{row["user"]}, superuser=#{row["superuser"]}"
63
+ Check.new(name: "current_user", ok: true, detail: detail)
64
+ rescue StandardError => e
65
+ Check.new(name: "current_user", ok: false, detail: e.message)
66
+ end
67
+
68
+ def check_session_replication_role(connection)
69
+ probe_in_rollback(connection) do
70
+ connection.execute("SET LOCAL session_replication_role = replica")
71
+ connection.execute("SET LOCAL session_replication_role = DEFAULT")
72
+ end
73
+ Check.new(name: "session_replication_role", ok: true, detail: "SET LOCAL replica")
74
+ rescue ActiveRecord::StatementInvalid => e
75
+ Check.new(
76
+ name: "session_replication_role",
77
+ ok: false,
78
+ detail: "#{e.message.strip} — requires superuser or REPLICATION attribute on managed Postgres"
79
+ )
80
+ end
81
+
82
+ def check_sequence_reset(connection, schema)
83
+ table = sample_table_with_id(connection, schema)
84
+ return Check.new(name: "setval_sequences", ok: true, detail: "skipped (no sample table in #{schema})") unless table
85
+
86
+ qualified = %("#{schema}"."#{table}")
87
+ probe_in_rollback(connection) do
88
+ connection.execute(<<~SQL.squish)
89
+ SELECT setval(
90
+ pg_get_serial_sequence('#{schema}.#{table}', 'id'),
91
+ COALESCE((SELECT MAX(id) FROM #{qualified}), 1),
92
+ true
93
+ )
94
+ SQL
95
+ end
96
+ Check.new(name: "setval_sequences", ok: true, detail: "tested on #{schema}.#{table}")
97
+ rescue ActiveRecord::StatementInvalid => e
98
+ Check.new(
99
+ name: "setval_sequences",
100
+ ok: false,
101
+ detail: "#{e.message.strip} — needs USAGE/UPDATE on sequences in #{schema}"
102
+ )
103
+ end
104
+
105
+ def check_create_schema(connection)
106
+ test_schema = "_decidim_apartment_perm_#{SecureRandom.hex(4)}"
107
+ probe_in_rollback(connection) do
108
+ connection.execute(%(CREATE SCHEMA "#{test_schema}"))
109
+ connection.execute(%(DROP SCHEMA "#{test_schema}"))
110
+ end
111
+ Check.new(name: "create_schema", ok: true, detail: "CREATE/DROP SCHEMA")
112
+ rescue ActiveRecord::StatementInvalid => e
113
+ Check.new(
114
+ name: "create_schema",
115
+ ok: false,
116
+ detail: "#{e.message.strip} — required for Apartment::Tenant.create"
117
+ )
118
+ end
119
+
120
+ def check_psql_cli
121
+ if system("which psql > /dev/null 2>&1")
122
+ Check.new(name: "psql_cli", ok: true, detail: "psql in PATH")
123
+ else
124
+ Check.new(name: "psql_cli", ok: false, detail: "psql not found — import database restore requires it")
125
+ end
126
+ end
127
+
128
+ def check_pg_dump_cli(connection)
129
+ return Check.new(name: "pg_dump_cli", ok: false, detail: "pg_dump not found — required when Apartment.use_sql") unless system("which pg_dump > /dev/null 2>&1")
130
+
131
+ client_major = `pg_dump --version`.match(/ (\d+)\./)&.[](1).to_i
132
+ server_major = connection.select_value("SHOW server_version").to_s.match(/^(\d+)/)&.[](1).to_i
133
+ version_line = `pg_dump --version`.strip
134
+
135
+ return Check.new(name: "pg_dump_cli", ok: false, detail: "could not parse pg_dump/server version") if client_major.zero? || server_major.zero?
136
+
137
+ if client_major == server_major
138
+ Check.new(name: "pg_dump_cli", ok: true, detail: version_line)
139
+ else
140
+ Check.new(
141
+ name: "pg_dump_cli",
142
+ ok: false,
143
+ detail: "#{version_line} — server is PostgreSQL #{server_major}; install postgresql-client-#{server_major}"
144
+ )
145
+ end
146
+ end
147
+
148
+ def sample_table_with_id(connection, schema)
149
+ return "decidim_organizations" if table_exists?(connection, schema, "decidim_organizations")
150
+
151
+ connection.select_value(<<~SQL.squish)
152
+ SELECT tablename
153
+ FROM pg_tables
154
+ WHERE schemaname = #{connection.quote(schema)}
155
+ ORDER BY tablename
156
+ LIMIT 1
157
+ SQL
158
+ end
159
+
160
+ def table_exists?(connection, schema, table)
161
+ connection.select_value(<<~SQL.squish).to_i.positive?
162
+ SELECT COUNT(*)
163
+ FROM pg_tables
164
+ WHERE schemaname = #{connection.quote(schema)}
165
+ AND tablename = #{connection.quote(table)}
166
+ SQL
167
+ end
168
+
169
+ def probe_in_rollback(connection)
170
+ connection.transaction do
171
+ yield
172
+ raise ActiveRecord::Rollback
173
+ end
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end
179
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Validates new key length and that the old key decrypts tenant probes.
8
+ class SecretKeyPreflight
9
+ Result = Struct.new(:ok, :probe, :message, keyword_init: true)
10
+
11
+ def initialize(from:, to:)
12
+ @from = from
13
+ @to = to
14
+ end
15
+
16
+ def call
17
+ return length_failure unless @to.to_s.length == 128
18
+
19
+ probe_tenant
20
+ end
21
+
22
+ private
23
+
24
+ def length_failure
25
+ Result.new(ok: false, probe: nil, message: "new secret_key_base length must be 128")
26
+ end
27
+
28
+ def probe_tenant
29
+ smtp = smtp_probe
30
+ auth = authorization_probe
31
+ return both_probes(smtp, auth) if smtp || auth
32
+
33
+ other_or_empty
34
+ end
35
+
36
+ def both_probes(smtp, auth)
37
+ return fail_probe(smtp[1]) if smtp&.first == :fail
38
+ return fail_probe(auth[1]) if auth&.first == :fail
39
+
40
+ Result.new(ok: true, probe: (smtp || auth)[1], message: nil)
41
+ end
42
+
43
+ def other_or_empty
44
+ sample = CiphertextRewriter.sample_ciphertext(from: @from)
45
+ return Result.new(ok: true, probe: "empty", message: nil) if sample == :empty
46
+ return Result.new(ok: true, probe: "other", message: nil) if sample == :ok
47
+
48
+ fail_probe(sample)
49
+ end
50
+
51
+ def fail_probe(message)
52
+ Result.new(ok: false, probe: nil, message: message)
53
+ end
54
+
55
+ def smtp_probe
56
+ settings = Decidim::Organization.first&.smtp_settings
57
+ value = settings&.with_indifferent_access&.[]("encrypted_password")
58
+ return nil if value.blank?
59
+
60
+ decrypt_probe(value, "smtp_settings")
61
+ end
62
+
63
+ def authorization_probe
64
+ value = first_authorization_ciphertext
65
+ return nil if value.blank?
66
+
67
+ decrypt_probe(value, "authorization")
68
+ end
69
+
70
+ def first_authorization_ciphertext
71
+ Decidim::Authorization.find_each do |row|
72
+ found = hash_ciphertext(row, :metadata) || hash_ciphertext(row, :verification_metadata)
73
+ return found if found
74
+ end
75
+ nil
76
+ end
77
+
78
+ def hash_ciphertext(row, attr)
79
+ raw = CiphertextRewriter.raw_attribute(row, attr)
80
+ return unless raw.is_a?(Hash)
81
+
82
+ raw.values.find { |v| v.is_a?(String) && v.include?("--") }
83
+ end
84
+
85
+ def decrypt_probe(value, name)
86
+ CiphertextRewriter.decrypt_string(value, secret_key_base: @from)
87
+ [:ok, name]
88
+ rescue CiphertextRewriter::DecryptError => e
89
+ [:fail, e.message]
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end