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,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Creates a tenant registry row and PostgreSQL schema with an explicit UUID key.
8
+ class ProvisionTenant
9
+ class << self
10
+ def call(target_tenant:, host:)
11
+ new(target_tenant: target_tenant, host: host).call
12
+ end
13
+ end
14
+
15
+ def initialize(target_tenant:, host:)
16
+ @target_tenant = target_tenant
17
+ @host = host
18
+ end
19
+
20
+ def call
21
+ existing = find_distribution_key
22
+ if existing
23
+ existing.sync_hosts!(primary_host: @host)
24
+ return existing
25
+ end
26
+
27
+ ::Apartment::Tenant.switch("public") do
28
+ now = Time.current
29
+ Decidim::Apartment::DistributionKey.insert_all(
30
+ [{ host: @host, key: @target_tenant, created_at: now, updated_at: now }]
31
+ )
32
+ end
33
+
34
+ ::Apartment::Tenant.create(@target_tenant)
35
+ key = find_distribution_key
36
+ key.sync_hosts!(primary_host: @host)
37
+ key
38
+ end
39
+
40
+ private
41
+
42
+ def find_distribution_key
43
+ ::Apartment::Tenant.switch("public") do
44
+ Decidim::Apartment::DistributionKey.find_by(key: @target_tenant)
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Validates SQL dumps reference only allowed schemas and contain no cross-tenant DDL.
8
+ class SchemaAuditor
9
+ UUID_PATTERN = /
10
+ \b
11
+ [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
12
+ \b
13
+ /ix
14
+
15
+ FIXED_SCHEMAS = %w(public).freeze
16
+
17
+ DANGEROUS_PATTERNS = [
18
+ /\bDROP\s+DATABASE\b/i,
19
+ /\bALTER\s+DATABASE\b/i,
20
+ /\bTRUNCATE\s+public\./i,
21
+ /\bDELETE\s+FROM\s+public\./i,
22
+ /\bDROP\s+SCHEMA\s+public\b/i,
23
+ /\bDROP\s+SCHEMA\s+shared_extensions\b/i
24
+ ].freeze
25
+
26
+ class << self
27
+ def audit_raw_dump!(path, source_schema:)
28
+ new(path, source_schema: source_schema).audit_raw!
29
+ end
30
+
31
+ def audit_transformed!(path, target_schema:)
32
+ new(path, target_schema: target_schema).audit_transformed!
33
+ end
34
+ end
35
+
36
+ def initialize(path, source_schema: nil, target_schema: nil)
37
+ @path = path
38
+ @source_schema = source_schema&.downcase
39
+ @target_schema = target_schema&.downcase
40
+ end
41
+
42
+ def audit_raw!
43
+ tenant_schemas = Set.new
44
+ each_line do |line|
45
+ check_dangerous!(line, allowed_drop_schema: @source_schema)
46
+ collect_tenant_schemas(line, tenant_schemas)
47
+ end
48
+
49
+ tenant_schemas.delete(@source_schema) if @source_schema
50
+ if tenant_schemas.any?
51
+ raise ImportError,
52
+ "dump references multiple tenant schemas: #{(tenant_schemas.to_a + [@source_schema]).compact.uniq.join(", ")}"
53
+ end
54
+
55
+ true
56
+ end
57
+
58
+ def audit_transformed!
59
+ disallowed = Set.new
60
+ each_line do |line|
61
+ check_dangerous!(line, allowed_drop_schema: @target_schema)
62
+ schemas_in_line(line).each do |schema|
63
+ next if schema == @target_schema
64
+
65
+ disallowed << schema
66
+ end
67
+ end
68
+
69
+ return true if disallowed.empty?
70
+
71
+ raise ImportError, "transformed dump references disallowed schemas: #{disallowed.to_a.sort.join(", ")}"
72
+ end
73
+
74
+ private
75
+
76
+ def each_line(&)
77
+ File.foreach(@path, &)
78
+ end
79
+
80
+ def check_dangerous!(line, allowed_drop_schema:)
81
+ DANGEROUS_PATTERNS.each do |pattern|
82
+ raise ImportError, "unsafe SQL detected: #{line.strip}" if line.match?(pattern)
83
+ end
84
+
85
+ if line.match?(/\bDROP\s+SCHEMA\b/i)
86
+ drop_target = line[/DROP\s+SCHEMA\s+(?:IF\s+EXISTS\s+)?["']?([^"'\s;]+)/i, 1]&.downcase
87
+ raise ImportError, "unsafe DROP SCHEMA: #{line.strip}" if drop_target && drop_target != allowed_drop_schema && FIXED_SCHEMAS.exclude?(drop_target)
88
+ end
89
+ end
90
+
91
+ def collect_tenant_schemas(line, tenant_schemas)
92
+ schemas_in_line(line).each do |schema|
93
+ next if FIXED_SCHEMAS.include?(schema)
94
+
95
+ tenant_schemas << schema if schema.match?(UUID_PATTERN)
96
+ end
97
+ end
98
+
99
+ def schemas_in_line(line)
100
+ schemas = Set.new
101
+ line.scan(/COPY\s+([^.\s(]+)\./i) { |match| schemas << normalize_schema_name(match[0]) }
102
+ line.scan(/CREATE\s+SCHEMA\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?([^"'\s;]+)/i) do |match|
103
+ schemas << normalize_schema_name(match[0])
104
+ end
105
+ line.scan(/SET\s+search_path\s*=\s*([^;]+)/i) do |match|
106
+ match[0].split(",").each { |part| schemas << normalize_schema_name(part) }
107
+ end
108
+ line.scan(/["']([0-9a-f-]{36})["']\./i) { |match| schemas << match[0].downcase }
109
+ schemas
110
+ end
111
+
112
+ def normalize_schema_name(name)
113
+ name.to_s.delete('"').strip.downcase
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Copies blob files from a source folder into S3 under the target tenant prefix.
8
+ class StorageMigrator
9
+ Result = Struct.new(:copied, :skipped, :missing, keyword_init: true)
10
+
11
+ class << self
12
+ def call(context:)
13
+ new(context: context).call
14
+ end
15
+ end
16
+
17
+ def initialize(context:)
18
+ @context = context
19
+ end
20
+
21
+ def call
22
+ result = Result.new(copied: 0, skipped: 0, missing: 0)
23
+
24
+ distribution_key.switch do
25
+ keys = ActiveRecord::Base.connection.select_values("SELECT key FROM active_storage_blobs")
26
+ keys.each do |key|
27
+ source_path = File.join(@context.storage_source_path, key)
28
+ unless File.exist?(source_path)
29
+ result.missing += 1
30
+ puts " missing source: #{source_path}" if ConfirmPrompt.dry_run?
31
+ next
32
+ end
33
+
34
+ if destination_exists?(key)
35
+ result.skipped += 1
36
+ next
37
+ end
38
+
39
+ upload!(key, source_path)
40
+ result.copied += 1
41
+ end
42
+ end
43
+
44
+ puts "Storage import complete: copied=#{result.copied} skipped=#{result.skipped} missing=#{result.missing}"
45
+ result
46
+ end
47
+
48
+ private
49
+
50
+ def distribution_key
51
+ @distribution_key ||= ::Apartment::Tenant.switch("public") do
52
+ Decidim::Apartment::DistributionKey.find_by!(key: @context.target_tenant)
53
+ end
54
+ end
55
+
56
+ def destination_exists?(key)
57
+ service = ActiveStorage::Blob.service
58
+ object = service.send(:object_for, key)
59
+ object.exists?
60
+ end
61
+
62
+ def upload!(key, source_path)
63
+ service = ActiveStorage::Blob.service
64
+ File.open(source_path, "rb") do |io|
65
+ service.upload(key, io)
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Read-only preflight resolution and validation for tenant import.
8
+ class TenantContext
9
+ Context = Struct.new(
10
+ :target_tenant,
11
+ :source_schema,
12
+ :host,
13
+ :dump_host,
14
+ :org_name,
15
+ :distribution_key,
16
+ :needs_provision,
17
+ :stats,
18
+ :dump_file,
19
+ :storage_source,
20
+ :s3_bucket,
21
+ :postgres_permissions,
22
+ keyword_init: true
23
+ ) do
24
+ def storage_source_path
25
+ raise ImportError, "SOURCE_SCHEMA is required for storage import" if source_schema.blank?
26
+
27
+ File.join(storage_source, source_schema)
28
+ end
29
+
30
+ def s3_destination_prefix
31
+ "#{s3_bucket}/#{target_tenant}/"
32
+ end
33
+ end
34
+
35
+ class << self
36
+ def build!(mode:)
37
+ new(mode: mode).build!
38
+ end
39
+ end
40
+
41
+ def initialize(mode:)
42
+ @mode = mode
43
+ end
44
+
45
+ def build!
46
+ target_tenant = fetch_env!("TARGET_TENANT")
47
+ dump_file = fetch_env_if!("DUMP_FILE", database_mode?)
48
+ storage_source = fetch_env_if!("STORAGE_SOURCE", storage_mode?)
49
+ source_schema = detect_source_schema(dump_file)
50
+ org_info = extract_org_info(dump_file, source_schema)
51
+ dump_host = org_info&.dig(:host)
52
+ org_name = org_info&.dig(:org_name)
53
+ stats = dump_file ? DumpPreview.call(dump_file, source_schema) : nil
54
+
55
+ distribution_key = find_distribution_key(target_tenant)
56
+ needs_provision = distribution_key.nil? && database_mode?
57
+
58
+ host = resolve_host!(needs_provision:, dump_host:, distribution_key:)
59
+ assert_s3_destination! if storage_mode? || verify_mode?
60
+
61
+ if distribution_key
62
+ assert_schema_exists!(target_tenant)
63
+ assert_empty_tenant!(distribution_key) if database_mode?
64
+ elsif database_mode?
65
+ raise ImportError, "TARGET_TENANT is not registered; set HOST to provision on import"
66
+ elsif verify_mode? || storage_mode?
67
+ raise ImportError, "TARGET_TENANT is not registered"
68
+ end
69
+
70
+ permission_checks = postgres_permission_checks!(target_tenant) if database_mode?
71
+
72
+ Context.new(
73
+ target_tenant: target_tenant,
74
+ source_schema: source_schema,
75
+ host: host,
76
+ dump_host: dump_host,
77
+ org_name: org_name,
78
+ distribution_key: distribution_key,
79
+ needs_provision: needs_provision,
80
+ stats: stats,
81
+ dump_file: dump_file,
82
+ storage_source: storage_source,
83
+ s3_bucket: storage_mode? ? s3_bucket_name : nil,
84
+ postgres_permissions: permission_checks
85
+ )
86
+ end
87
+
88
+ def print_summary!(context)
89
+ puts "Preflight OK"
90
+ Ops::PostgresPermissions.print_report!(context.postgres_permissions) if context.respond_to?(:postgres_permissions) && context.postgres_permissions
91
+ puts " source_schema: #{context.source_schema}"
92
+ puts " target_tenant: #{context.target_tenant}"
93
+ puts " host: #{context.host}"
94
+ if context.stats
95
+ puts " dump: #{context.stats.organizations} org, #{context.stats.users} users, " \
96
+ "#{context.stats.spaces} spaces, #{context.stats.components} components, #{context.stats.blobs} blobs"
97
+ end
98
+ if context.storage_source
99
+ puts " storage: #{context.stats&.blobs || 0} files expected under #{context.storage_source_path}/"
100
+ puts " destination: s3://#{context.s3_destination_prefix}"
101
+ end
102
+ end
103
+
104
+ private
105
+
106
+ def database_mode?
107
+ [:full, :database].include?(@mode)
108
+ end
109
+
110
+ def storage_mode?
111
+ [:full, :storage].include?(@mode)
112
+ end
113
+
114
+ def verify_mode?
115
+ @mode == :verify
116
+ end
117
+
118
+ def fetch_env!(key)
119
+ ENV.fetch(key) { raise ImportError, "#{key} is required" }
120
+ end
121
+
122
+ def fetch_env_if!(key, required)
123
+ return ENV.fetch(key, nil) unless required
124
+
125
+ fetch_env!(key)
126
+ end
127
+
128
+ def find_distribution_key(target_tenant)
129
+ ::Apartment::Tenant.switch("public") do
130
+ Decidim::Apartment::DistributionKey.find_by(key: target_tenant)
131
+ end
132
+ end
133
+
134
+ def normalize_host(host)
135
+ host.to_s.strip.downcase.delete_suffix(".")
136
+ end
137
+
138
+ def resolve_host!(needs_provision:, dump_host:, distribution_key:)
139
+ if needs_provision
140
+ host = ENV["HOST"].presence || raise(ImportError, "HOST is required when TARGET_TENANT is not registered")
141
+ raise ImportError, "HOST (#{host}) does not match dump organization host (#{dump_host})" if dump_host && normalize_host(host) != dump_host
142
+
143
+ host
144
+ elsif distribution_key
145
+ registry_host = normalize_host(distribution_key.host)
146
+ if dump_host && registry_host != dump_host
147
+ raise ImportError,
148
+ "DistributionKey host (#{distribution_key.host}) does not match dump organization host (#{dump_host})"
149
+ end
150
+
151
+ distribution_key.host
152
+ else
153
+ raise ImportError, "TARGET_TENANT is not registered"
154
+ end
155
+ end
156
+
157
+ def detect_source_schema(dump_file)
158
+ return ENV["SOURCE_SCHEMA"].downcase if ENV["SOURCE_SCHEMA"].present?
159
+ return nil unless dump_file
160
+
161
+ DumpPreview.detect_source_schema(dump_file)
162
+ end
163
+
164
+ def extract_org_info(dump_file, source_schema)
165
+ return nil unless dump_file && source_schema
166
+
167
+ SchemaAuditor.audit_raw_dump!(dump_file, source_schema: source_schema)
168
+ DumpHostExtractor.call(dump_file, source_schema)
169
+ end
170
+
171
+ def assert_schema_exists!(target_tenant)
172
+ return if ::Apartment.tenant_names.include?(target_tenant)
173
+
174
+ raise ImportError, "PostgreSQL schema #{target_tenant} does not exist"
175
+ end
176
+
177
+ def assert_empty_tenant!(distribution_key)
178
+ distribution_key.switch do
179
+ conn = ActiveRecord::Base.connection
180
+ users_present = conn.table_exists?(:decidim_users) &&
181
+ conn.select_value("SELECT COUNT(*) FROM decidim_users").to_i.positive?
182
+ blobs_present = conn.table_exists?(:active_storage_blobs) &&
183
+ conn.select_value("SELECT COUNT(*) FROM active_storage_blobs").to_i.positive?
184
+
185
+ raise ImportError, "target tenant #{distribution_key.key} is not empty" if Decidim::Organization.exists? || users_present || blobs_present
186
+ end
187
+ end
188
+
189
+ def assert_s3_destination!
190
+ service = ActiveStorage::Blob.service
191
+ return if service.is_a?(ActiveStorage::Service::ApartmentS3StorageService)
192
+
193
+ raise ImportError,
194
+ "Active Storage must use ApartmentS3Storage (see website/docs/active_storage.md); " \
195
+ "got #{service.class.name}"
196
+ end
197
+
198
+ def s3_bucket_name
199
+ service = ActiveStorage::Blob.service
200
+ service.send(:bucket).name
201
+ end
202
+
203
+ def postgres_permission_checks!(tenant_schema)
204
+ schema = permission_probe_schema(tenant_schema)
205
+ checks = Ops::PostgresPermissions.call(
206
+ connection: ActiveRecord::Base.connection,
207
+ schema: schema,
208
+ require_psql: true
209
+ )
210
+ Ops::PostgresPermissions.raise_if_failed!(
211
+ checks,
212
+ error_class: ImportError,
213
+ connection: ActiveRecord::Base.connection
214
+ )
215
+ checks
216
+ end
217
+
218
+ def permission_probe_schema(tenant_schema)
219
+ return tenant_schema if ::Apartment.tenant_names.include?(tenant_schema)
220
+
221
+ "public"
222
+ end
223
+ end
224
+ end
225
+ end
226
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Orchestrates tenant import: preflight, confirmation gates, and write phases.
8
+ class TenantImporter
9
+ class << self
10
+ def run(mode: :full)
11
+ new(mode: mode).run
12
+ end
13
+ end
14
+
15
+ def initialize(mode: :full)
16
+ @mode = mode
17
+ end
18
+
19
+ def run
20
+ context = TenantContext.build!(mode: @mode)
21
+ TenantContext.new(mode: @mode).print_summary!(context)
22
+
23
+ run_database_flow!(context) if database_mode?
24
+ run_storage_flow!(context) if storage_mode?
25
+ Verifier.call(context: context) if @mode == :full && ConfirmPrompt.write_mode?
26
+
27
+ true
28
+ end
29
+
30
+ private
31
+
32
+ def database_mode?
33
+ [:full, :database].include?(@mode)
34
+ end
35
+
36
+ def storage_mode?
37
+ [:full, :storage].include?(@mode)
38
+ end
39
+
40
+ def run_database_flow!(context)
41
+ if context.needs_provision
42
+ ConfirmPrompt.ask("Create a new #{context.target_tenant} schema? [y/N]")
43
+ ProvisionTenant.call(target_tenant: context.target_tenant, host: context.host) if ConfirmPrompt.write_mode?
44
+ end
45
+
46
+ stats = context.stats
47
+ ConfirmPrompt.ask(
48
+ "Import #{stats.organizations} org, #{stats.users} users, #{stats.spaces} spaces, " \
49
+ "#{stats.components} components? [y/N]"
50
+ )
51
+ DatabaseRestorer.call(context: context) if ConfirmPrompt.write_mode?
52
+ end
53
+
54
+ def run_storage_flow!(context)
55
+ blob_count = context.stats&.blobs || blob_count_from_db(context)
56
+ ConfirmPrompt.ask(
57
+ "Upload #{blob_count} blobs to S3 (#{context.s3_destination_prefix})? [y/N]"
58
+ )
59
+ StorageMigrator.call(context: context) if ConfirmPrompt.write_mode?
60
+ end
61
+
62
+ def blob_count_from_db(context)
63
+ distribution_key = ::Apartment::Tenant.switch("public") do
64
+ Decidim::Apartment::DistributionKey.find_by!(key: context.target_tenant)
65
+ end
66
+ distribution_key.switch do
67
+ ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM active_storage_blobs").to_i
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Import
6
+ ##
7
+ # Post-import verification inside the target tenant.
8
+ class Verifier
9
+ class << self
10
+ def call(context:)
11
+ new(context: context).call
12
+ end
13
+ end
14
+
15
+ def initialize(context:)
16
+ @context = context
17
+ end
18
+
19
+ def call
20
+ distribution_key.switch do
21
+ org_count = Decidim::Organization.count
22
+ raise ImportError, "expected 1 organization, got #{org_count}" unless org_count == 1
23
+
24
+ org = Decidim::Organization.first
25
+ user_count = ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM decidim_users").to_i
26
+ component_count = ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM decidim_components").to_i
27
+ blob_keys = ActiveRecord::Base.connection.select_values("SELECT key FROM active_storage_blobs")
28
+
29
+ missing = blob_keys.count { |key| !destination_exists?(key) }
30
+ raise ImportError, "#{missing} blob(s) missing on S3" if missing.positive?
31
+
32
+ puts "Verify OK"
33
+ puts " host: #{distribution_key.host}"
34
+ puts " organization: #{org.name}"
35
+ puts " users: #{user_count}"
36
+ puts " components: #{component_count}"
37
+ puts " blobs: #{blob_keys.size - missing}/#{blob_keys.size} present on S3"
38
+ end
39
+
40
+ true
41
+ end
42
+
43
+ private
44
+
45
+ def distribution_key
46
+ @distribution_key ||= ::Apartment::Tenant.switch("public") do
47
+ Decidim::Apartment::DistributionKey.find_by!(key: @context.target_tenant)
48
+ end
49
+ end
50
+
51
+ def destination_exists?(key)
52
+ service = ActiveStorage::Blob.service
53
+ service.send(:object_for, key).exists?
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "import/errors"
4
+ require_relative "import/confirm_prompt"
5
+ require_relative "ops/postgres_permissions"
6
+ require_relative "import/schema_auditor"
7
+ require_relative "import/dump_host_extractor"
8
+ require_relative "import/dump_preview"
9
+ require_relative "import/dump_transformer"
10
+ require_relative "import/provision_tenant"
11
+ require_relative "import/tenant_context"
12
+ require_relative "import/database_restorer"
13
+ require_relative "import/storage_migrator"
14
+ require_relative "import/verifier"
15
+ require_relative "import/tenant_importer"
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Decidim
4
+ module Apartment
5
+ module Ops
6
+ ##
7
+ # Local MessageEncryptor matching Decidim::AttributeEncryptor key derivation,
8
+ # with an explicit secret_key_base. Decidim 0.31 exposes only class methods
9
+ # bound to Rails.application.secret_key_base; 0.32+ has instances. This class
10
+ # covers both without mutating the process encryptor.
11
+ class AttributeCryptor
12
+ def initialize(secret_key_base:, secret: "attribute", hash_digest_class: nil, is_retry: false)
13
+ @secret = secret
14
+ @secret_key_base = secret_key_base
15
+ @hash_digest_class = hash_digest_class || default_digest
16
+ @is_retry = is_retry
17
+ end
18
+
19
+ def encrypt(string)
20
+ return if string.blank?
21
+
22
+ encryptor.encrypt_and_sign(string)
23
+ end
24
+
25
+ def decrypt(string)
26
+ return if string.blank?
27
+ return string unless string.is_a?(String)
28
+
29
+ encryptor.decrypt_and_verify(string)
30
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage => e
31
+ raise e if @is_retry
32
+
33
+ legacy.decrypt(string)
34
+ end
35
+
36
+ private
37
+
38
+ def default_digest
39
+ return OpenSSL::Digest::SHA1 unless instance_api?
40
+
41
+ Rails.application.config.active_support.hash_digest_class
42
+ end
43
+
44
+ def instance_api?
45
+ Decidim::AttributeEncryptor.instance_method(:initialize).parameters.any?
46
+ end
47
+
48
+ def legacy
49
+ self.class.new(
50
+ secret: @secret,
51
+ secret_key_base: @secret_key_base,
52
+ hash_digest_class: OpenSSL::Digest::SHA1,
53
+ is_retry: true
54
+ )
55
+ end
56
+
57
+ def encryptor
58
+ @encryptor ||= ActiveSupport::MessageEncryptor.new(key)
59
+ end
60
+
61
+ def key
62
+ ActiveSupport::KeyGenerator.new(@secret, hash_digest_class: @hash_digest_class)
63
+ .generate_key(@secret_key_base, ActiveSupport::MessageEncryptor.key_len)
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end