maquina-generators 0.9.0 → 0.11.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 (169) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +201 -12
  3. data/lib/generators/maquina/app/USAGE +4 -0
  4. data/lib/generators/maquina/app/app_generator.rb +38 -7
  5. data/lib/generators/maquina/app/templates/README.md.erb +21 -0
  6. data/lib/generators/maquina/app/templates/app/views/home/index.html.erb +1 -1
  7. data/lib/generators/maquina/auth_flavor.rb +59 -0
  8. data/lib/generators/maquina/backstage_signin/backstage_signin.rb +320 -0
  9. data/lib/generators/maquina/backstage_signin/templates/test/integration/backstage_access_test.rb.tt +104 -0
  10. data/lib/generators/maquina/csp_reports/csp_reports_generator.rb +13 -1
  11. data/lib/generators/maquina/csp_reports/templates/app/models/mcp/tools/csp_reports.rb +71 -0
  12. data/lib/generators/maquina/csp_reports/templates/test/models/mcp/tools/csp_reports_test.rb +35 -0
  13. data/lib/generators/maquina/error_context/USAGE +22 -0
  14. data/lib/generators/maquina/error_context/error_context_generator.rb +51 -0
  15. data/lib/generators/maquina/mcp/USAGE +38 -0
  16. data/lib/generators/maquina/mcp/mcp_generator.rb +194 -0
  17. data/lib/generators/maquina/mcp/mcp_sibling_tools.rb +122 -0
  18. data/lib/generators/maquina/mcp/templates/app/controllers/concerns/mcp_authenticatable.rb +63 -0
  19. data/lib/generators/maquina/mcp/templates/app/controllers/mcp_controller.rb +205 -0
  20. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_definitions.rb +38 -0
  21. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_error.rb +17 -0
  22. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools/app.rb +51 -0
  23. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools.rb +83 -0
  24. data/lib/generators/maquina/mcp/templates/app/models/mcp/user_scope.rb +50 -0
  25. data/lib/generators/maquina/mcp/templates/config/initializers/mcp_cors.rb +38 -0
  26. data/lib/generators/maquina/mcp/templates/test/integration/mcp_conformance_test.rb +223 -0
  27. data/lib/generators/maquina/mcp/templates/test/integration/mcp_flow_test.rb.tt +65 -0
  28. data/lib/generators/maquina/mcp/templates/test/models/mcp/tools_test.rb.tt +145 -0
  29. data/lib/generators/maquina/mcp/templates/test/test_helpers/mcp_test_helper.rb.tt +103 -0
  30. data/lib/generators/maquina/mcp_tool/USAGE +26 -0
  31. data/lib/generators/maquina/mcp_tool/mcp_tool_generator.rb +239 -0
  32. data/lib/generators/maquina/mcp_tool/templates/test/models/mcp/tools/tool_test.rb.tt +49 -0
  33. data/lib/generators/maquina/mission_control_jobs/USAGE +5 -0
  34. data/lib/generators/maquina/mission_control_jobs/mission_control_jobs_generator.rb +21 -5
  35. data/lib/generators/maquina/mission_control_jobs/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  36. data/lib/generators/maquina/mission_control_jobs/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  37. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_filters.html.erb +1 -1
  38. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_general_information.html.erb +1 -1
  39. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_job.html.erb +1 -1
  40. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/failed/_job.html.erb +1 -1
  41. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/queues/_job.html.erb +1 -1
  42. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/shared/_job.html.erb +1 -1
  43. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/workers/_worker.html.erb +1 -1
  44. data/lib/generators/maquina/oauth/USAGE +35 -0
  45. data/lib/generators/maquina/oauth/oauth_generator.rb +359 -0
  46. data/lib/generators/maquina/oauth/templates/app/controllers/connected_applications_controller.rb +26 -0
  47. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorization_servers_controller.rb +24 -0
  48. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorizations_controller.rb +92 -0
  49. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/protected_resources_controller.rb +14 -0
  50. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/revocations_controller.rb +20 -0
  51. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/tokens_controller.rb +67 -0
  52. data/lib/generators/maquina/oauth/templates/app/models/access_token.rb +83 -0
  53. data/lib/generators/maquina/oauth/templates/app/models/connected_application.rb +49 -0
  54. data/lib/generators/maquina/oauth/templates/app/models/mcp.rb.tt +33 -0
  55. data/lib/generators/maquina/oauth/templates/app/models/oauth_authorization_code.rb +52 -0
  56. data/lib/generators/maquina/oauth/templates/app/models/oauth_client/metadata_fetcher.rb +195 -0
  57. data/lib/generators/maquina/oauth/templates/app/models/oauth_client.rb +50 -0
  58. data/lib/generators/maquina/oauth/templates/app/views/connected_applications/index.html.erb +43 -0
  59. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/error.html.erb +8 -0
  60. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/new.html.erb +36 -0
  61. data/lib/generators/maquina/oauth/templates/config/locales/oauth.en.yml +34 -0
  62. data/lib/generators/maquina/oauth/templates/config/locales/oauth.es.yml +34 -0
  63. data/lib/generators/maquina/oauth/templates/migration_create_access_tokens.rb.tt +20 -0
  64. data/lib/generators/maquina/oauth/templates/migration_create_oauth_authorization_codes.rb.tt +19 -0
  65. data/lib/generators/maquina/oauth/templates/migration_create_oauth_clients.rb.tt +14 -0
  66. data/lib/generators/maquina/oauth/templates/test/fixtures/access_tokens.yml +48 -0
  67. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_authorization_codes.yml +11 -0
  68. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_clients.yml +7 -0
  69. data/lib/generators/maquina/oauth/templates/test/integration/connected_applications_test.rb.tt +70 -0
  70. data/lib/generators/maquina/oauth/templates/test/integration/oauth_authorization_test.rb.tt +150 -0
  71. data/lib/generators/maquina/oauth/templates/test/integration/oauth_discovery_test.rb +44 -0
  72. data/lib/generators/maquina/oauth/templates/test/integration/oauth_tokens_test.rb +147 -0
  73. data/lib/generators/maquina/oauth/templates/test/models/access_token_test.rb.tt +80 -0
  74. data/lib/generators/maquina/oauth/templates/test/models/connected_application_test.rb +41 -0
  75. data/lib/generators/maquina/oauth/templates/test/models/oauth_authorization_code_test.rb +58 -0
  76. data/lib/generators/maquina/oauth/templates/test/test_helpers/oauth_test_helper.rb.tt +82 -0
  77. data/lib/generators/maquina/passkeys/USAGE +4 -2
  78. data/lib/generators/maquina/passkeys/passkeys_generator.rb +16 -11
  79. data/lib/generators/maquina/passkeys/templates/app/controllers/session/{passkeys_controller.rb → passkeys_controller.rb.tt} +6 -2
  80. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.en.yml → passkeys.en.yml.tt} +15 -0
  81. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.es.yml → passkeys.es.yml.tt} +15 -0
  82. data/lib/generators/maquina/passkeys/templates/test/integration/{passkeys_test.rb → passkeys_test.rb.tt} +6 -0
  83. data/lib/generators/maquina/rack_attack/rack_attack_generator.rb +4 -1
  84. data/lib/generators/maquina/rack_attack/templates/config/initializers/rack_attack.rb.tt +317 -4
  85. data/lib/generators/maquina/registration/registration_generator.rb +32 -0
  86. data/lib/generators/maquina/registration/templates/app/views/registrations/new.html.erb.tt +4 -0
  87. data/lib/generators/maquina/registration/templates/app/views/sessions/new.html.erb.tt +5 -0
  88. data/lib/generators/maquina/security/USAGE +12 -0
  89. data/lib/generators/maquina/security/security_generator.rb +79 -7
  90. data/lib/generators/maquina/security/templates/app/models/mcp/tools/security.rb.tt +114 -0
  91. data/lib/generators/maquina/security/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  92. data/lib/generators/maquina/security/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  93. data/lib/generators/maquina/security/templates/test/models/mcp/tools/security_test.rb +99 -0
  94. data/lib/generators/maquina/solid_errors/USAGE +21 -10
  95. data/lib/generators/maquina/solid_errors/error_context_files.rb +82 -0
  96. data/lib/generators/maquina/solid_errors/solid_errors_generator.rb +52 -31
  97. data/lib/generators/maquina/solid_errors/templates/app/agents/errors_query.rb +86 -29
  98. data/lib/generators/maquina/solid_errors/templates/app/agents/failure_triage.rb +4 -2
  99. data/lib/generators/maquina/solid_errors/templates/app/agents/list_failures_tool.rb +9 -4
  100. data/lib/generators/maquina/solid_errors/templates/app/models/mcp/tools/solid_errors.rb.tt +132 -0
  101. data/lib/generators/maquina/solid_errors/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  102. data/lib/generators/maquina/solid_errors/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  103. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_actions.html.erb +0 -15
  104. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_error_details.html.erb +5 -5
  105. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/occurrences/_collection.html.erb +1 -1
  106. data/lib/generators/maquina/solid_errors/templates/config/initializers/error_context.rb +33 -0
  107. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_filters_test.rb +68 -0
  108. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_test.rb +109 -0
  109. data/lib/generators/maquina/solid_queue/USAGE +11 -0
  110. data/lib/generators/maquina/solid_queue/solid_queue_generator.rb +25 -1
  111. data/lib/generators/maquina/solid_queue/templates/app/models/mcp/tools/solid_queue.rb.tt +163 -0
  112. data/lib/generators/maquina/solid_queue/templates/test/models/mcp/tools/solid_queue_test.rb +99 -0
  113. data/lib/maquina_generators/version.rb +1 -1
  114. data/test/fixtures/error_context/0.10.0/app/agents/errors_query.rb +105 -0
  115. data/test/fixtures/error_context/0.10.0/app/agents/failure_triage.rb +21 -0
  116. data/test/fixtures/error_context/0.10.0/app/agents/list_failures_tool.rb +20 -0
  117. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors.rb +81 -0
  118. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors_write.rb +101 -0
  119. data/test/generators/maquina/app_generator_test.rb +67 -5
  120. data/test/generators/maquina/backstage_signin_test.rb +296 -0
  121. data/test/generators/maquina/csp_reports_generator_test.rb +125 -6
  122. data/test/generators/maquina/error_context_generator_test.rb +188 -0
  123. data/test/generators/maquina/mcp_generator_test.rb +429 -0
  124. data/test/generators/maquina/mcp_tool_generator_test.rb +235 -0
  125. data/test/generators/maquina/mission_control_jobs_generator_test.rb +23 -0
  126. data/test/generators/maquina/oauth_client_metadata_fetcher_test.rb +290 -0
  127. data/test/generators/maquina/oauth_generator_test.rb +568 -0
  128. data/test/generators/maquina/passkeys_generator_test.rb +62 -2
  129. data/test/generators/maquina/rack_attack_generator_test.rb +71 -0
  130. data/test/generators/maquina/rack_attack_rules_test.rb +304 -0
  131. data/test/generators/maquina/registration_generator_test.rb +62 -0
  132. data/test/generators/maquina/security_generator_test.rb +188 -13
  133. data/test/generators/maquina/solid_errors_generator_test.rb +299 -33
  134. data/test/generators/maquina/solid_queue_generator_test.rb +175 -25
  135. data/test/support/rails_auth_app.rb +48 -0
  136. data/test/test_helper.rb +1 -0
  137. metadata +90 -41
  138. data/lib/generators/maquina/solid_errors/templates/app/controllers/failures_mcp_controller.rb.tt +0 -65
  139. data/test/tmp/Gemfile +0 -2
  140. data/test/tmp/app/controllers/application_controller.rb +0 -3
  141. data/test/tmp/app/controllers/concerns/authentication.rb +0 -63
  142. data/test/tmp/app/controllers/registration/verification_resends_controller.rb +0 -38
  143. data/test/tmp/app/controllers/registration/verifications_controller.rb +0 -64
  144. data/test/tmp/app/controllers/registrations_controller.rb +0 -63
  145. data/test/tmp/app/controllers/session/verification_resends_controller.rb +0 -44
  146. data/test/tmp/app/controllers/session/verifications_controller.rb +0 -64
  147. data/test/tmp/app/controllers/sessions_controller.rb +0 -56
  148. data/test/tmp/app/helpers/authentication_helper.rb +0 -20
  149. data/test/tmp/app/jobs/authentication_cleanup_job.rb +0 -13
  150. data/test/tmp/app/mailers/verification_mailer.rb +0 -15
  151. data/test/tmp/app/models/account.rb +0 -5
  152. data/test/tmp/app/models/current.rb +0 -5
  153. data/test/tmp/app/models/email_verification.rb +0 -58
  154. data/test/tmp/app/models/session.rb +0 -18
  155. data/test/tmp/app/models/user.rb +0 -37
  156. data/test/tmp/app/views/registration/verifications/new.html.erb +0 -43
  157. data/test/tmp/app/views/registrations/new.html.erb +0 -39
  158. data/test/tmp/app/views/session/verifications/new.html.erb +0 -43
  159. data/test/tmp/app/views/sessions/new.html.erb +0 -40
  160. data/test/tmp/app/views/verification_mailer/verification_code.html.erb +0 -37
  161. data/test/tmp/app/views/verification_mailer/verification_code.text.erb +0 -11
  162. data/test/tmp/config/locales/clave.en.yml +0 -102
  163. data/test/tmp/config/locales/clave.es.yml +0 -102
  164. data/test/tmp/config/routes.rb +0 -12
  165. data/test/tmp/db/migrate/20261019191386_create_accounts.rb +0 -9
  166. data/test/tmp/db/migrate/20261019191387_create_users.rb +0 -17
  167. data/test/tmp/db/migrate/20261019191388_create_sessions.rb +0 -12
  168. data/test/tmp/db/migrate/20261019191389_create_email_verifications.rb +0 -17
  169. data/test/tmp/test/test_helpers/session_test_helper.rb +0 -19
@@ -0,0 +1,320 @@
1
+ require "erb"
2
+ require_relative "../auth_flavor"
3
+
4
+ module Maquina
5
+ module Generators
6
+ # Puts the backstage behind the app's own sign-in instead of the
7
+ # shared Basic Auth login. The dashboard generators (solid_errors,
8
+ # mission_control_jobs, security) call install_backstage_signin after they
9
+ # write their files, so whichever runs, and in whatever order, the backstage
10
+ # ends up on the sign-in when the app has one (AuthFlavor).
11
+ #
12
+ # Who gets in is User#backstage_access?. With Clave, an unblocked user whose
13
+ # email is listed under backstage.emails in credentials; with Rails'
14
+ # sign-in, an admin of an account whose allow_backstage is on (a column
15
+ # this adds, off by default). The same predicate gates
16
+ # the admin-only MCP tools, which is why maquina:mcp calls
17
+ # add_backstage_access_to_user too.
18
+ #
19
+ # Each step edits a snippet the generators wrote. One that is not found
20
+ # (the app changed it) is left alone and named in backstage_signin_pending
21
+ # for the post-install message.
22
+ #
23
+ # Every method is private: a public method on a generator is a Thor step.
24
+ module BackstageSignin
25
+ include AuthFlavor
26
+
27
+ TEMPLATES = File.expand_path("templates", __dir__)
28
+
29
+ USER_MODEL = "app/models/user.rb"
30
+ BACKSTAGE_CONTROLLER = "app/controllers/backstage_controller.rb"
31
+ DASHBOARD_CONTROLLER = "app/controllers/backstage_dashboard_controller.rb"
32
+ SECURITY_CONTROLLER = "app/controllers/backstage/security_controller.rb"
33
+ SOLID_ERRORS_INITIALIZER = "config/initializers/solid_errors.rb"
34
+ MISSION_CONTROL_INITIALIZER = "config/initializers/mission_control.rb"
35
+ ACCESS_TEST = "test/integration/backstage_access_test.rb"
36
+
37
+ BACKSTAGE_CLASS = /^class BackstageController < ActionController::Base\n/
38
+ CLASS_END = /^end\s*\z/
39
+ BASIC_AUTH_ACTIONS = /\n before_action :require_backstage_credentials\n before_action :authenticate(_backstage)?\n/
40
+ # The private section both controllers end with: nothing in it but the
41
+ # Basic Auth helpers.
42
+ DASHBOARD_BASIC_AUTH = /\n\n private\n\n # Closed \(503\) until credentials\.backstage is set\..*\n end\n(?=end\n?\z)/m
43
+ SECURITY_BASIC_AUTH = /\n\n private\n\n def authenticate\n.*\n end\n(?=end\n?\z)/m
44
+ SECURITY_HEADER = /# Rack::Attack's last week, read from the `security` database\. Behind the same\n.*\n.*so it is never left open\.\n/
45
+ SOLID_ERRORS_BASIC_AUTH = /\n backstage = Rails\.application\.credentials\.backstage \|\| \{\}\n\n config\.solid_errors\.username = .*\n config\.solid_errors\.password = .*\n/
46
+ MISSION_CONTROL_BASIC_AUTH = / backstage = Rails\.application\.credentials\.backstage \|\| \{\}\n\n MissionControl::Jobs\.http_basic_auth_user = .*\n MissionControl::Jobs\.http_basic_auth_password = .*\n/
47
+
48
+ # The people the generated access test signs in as, with their role on
49
+ # each sign-in: with Clave both are admins and only the operator is on the
50
+ # list; with Rails' sign-in the member is not an admin.
51
+ USER_FIXTURES = {
52
+ "backstage_operator" => [{"email_address" => "backstage-operator@example.com", "name" => "Backstage Operator"}, {clave: "admin", rails: "admin"}],
53
+ "backstage_member" => [{"email_address" => "backstage-member@example.com", "name" => "Backstage Member"}, {clave: "admin", rails: "member"}]
54
+ }.freeze
55
+ ALLOW_BACKSTAGE_MIGRATION = "add_allow_backstage_to_accounts"
56
+
57
+ private
58
+
59
+ # Clave's or Rails' sign-in, with a User to ask. Without one the
60
+ # backstage keeps its Basic Auth.
61
+ def backstage_signin_available?
62
+ backstage_file?(USER_MODEL) && !auth_flavor.nil?
63
+ end
64
+
65
+ # A file this module already moved to the sign-in: it no longer has the
66
+ # Basic Auth its generator writes. Rendering it again would only put the
67
+ # Basic Auth back (and make Thor ask to overwrite), so the generators keep it.
68
+ def backstage_signin_converted?(path, basic_auth_marker)
69
+ full_path = File.join(destination_root, path)
70
+ File.exist?(full_path) && !File.read(full_path).include?(basic_auth_marker)
71
+ end
72
+
73
+ def backstage_signin_pending
74
+ @backstage_signin_pending ||= []
75
+ end
76
+
77
+ # Returns true when the backstage is (now) behind the sign-in.
78
+ def install_backstage_signin
79
+ return false unless backstage_signin_available?
80
+
81
+ add_backstage_access_to_user
82
+ convert_backstage_controller
83
+ convert(DASHBOARD_CONTROLLER, done_unless: "require_backstage_credentials") do
84
+ gsub_file DASHBOARD_CONTROLLER, BASIC_AUTH_ACTIONS, ""
85
+ gsub_file DASHBOARD_CONTROLLER, DASHBOARD_BASIC_AUTH, "\n"
86
+ gsub_file DASHBOARD_CONTROLLER, "under the same backstage Basic auth.", "behind the same backstage sign-in."
87
+ end
88
+ convert(SECURITY_CONTROLLER, done_unless: "require_backstage_credentials") do
89
+ gsub_file SECURITY_CONTROLLER, BASIC_AUTH_ACTIONS, ""
90
+ gsub_file SECURITY_CONTROLLER, SECURITY_BASIC_AUTH, "\n"
91
+ gsub_file SECURITY_CONTROLLER, SECURITY_HEADER,
92
+ "# Rack::Attack's last week, read from the `security` database. Behind the\n" \
93
+ "# backstage sign-in, like every page BackstageController serves.\n"
94
+ end
95
+ convert(SOLID_ERRORS_INITIALIZER, done_unless: "config.solid_errors.password =") do
96
+ gsub_file SOLID_ERRORS_INITIALIZER, SOLID_ERRORS_BASIC_AUTH,
97
+ "\n # Signed-in backstage users only, through BackstageController. Leave\n" \
98
+ " # username and password unset: a password turns Basic Auth back on.\n"
99
+ end
100
+ convert(MISSION_CONTROL_INITIALIZER, done_unless: "http_basic_auth_user") do
101
+ gsub_file MISSION_CONTROL_INITIALIZER, MISSION_CONTROL_BASIC_AUTH,
102
+ " # Signed-in backstage users only, through BackstageController.\n" \
103
+ " MissionControl::Jobs.http_basic_auth_enabled = false\n"
104
+ end
105
+ create_backstage_access_test
106
+ true
107
+ end
108
+
109
+ # User#backstage_access? (and, with Clave, User.backstage_emails; with
110
+ # Rails' sign-in, the accounts.allow_backstage column). Also called by
111
+ # maquina:mcp, whose admin-only tools use the same gate.
112
+ def add_backstage_access_to_user
113
+ return unless backstage_file?(USER_MODEL)
114
+
115
+ add_allow_backstage_column if rails_auth?
116
+ content = File.read(File.join(destination_root, USER_MODEL))
117
+ return if content.include?("def backstage_access?")
118
+ return backstage_signin_pending << USER_MODEL if rails_auth? && !user_admin_predicate?(content)
119
+
120
+ if content.match?(/^ private$/)
121
+ inject_into_file USER_MODEL, backstage_access_methods, before: /^ private$/
122
+ elsif content.match?(CLASS_END)
123
+ inject_into_file USER_MODEL, "\n#{backstage_access_methods.chomp}", before: CLASS_END
124
+ else
125
+ backstage_signin_pending << USER_MODEL
126
+ end
127
+ end
128
+
129
+ def convert_backstage_controller
130
+ return unless backstage_file?(BACKSTAGE_CONTROLLER)
131
+
132
+ content = File.read(File.join(destination_root, BACKSTAGE_CONTROLLER))
133
+ return if content.include?("require_backstage_access")
134
+ return backstage_signin_pending << BACKSTAGE_CONTROLLER unless content.match?(BACKSTAGE_CLASS) && content.match?(CLASS_END)
135
+
136
+ inject_into_file BACKSTAGE_CONTROLLER, backstage_controller_header, after: BACKSTAGE_CLASS
137
+ inject_into_file BACKSTAGE_CONTROLLER, backstage_controller_private, before: CLASS_END
138
+ end
139
+
140
+ # Runs the edits when the file still has Basic Auth (`done_unless`), then
141
+ # checks they took. A file the app has reshaped keeps its Basic Auth and
142
+ # is named in the post-install message.
143
+ def convert(path, done_unless:)
144
+ full_path = File.join(destination_root, path)
145
+ return unless File.exist?(full_path)
146
+ return unless File.read(full_path).include?(done_unless)
147
+
148
+ yield
149
+ backstage_signin_pending << path if File.read(full_path).include?(done_unless)
150
+ end
151
+
152
+ def create_backstage_access_test
153
+ return unless backstage_file?("test/test_helpers/session_test_helper.rb")
154
+
155
+ unless backstage_file?(ACCESS_TEST)
156
+ create_file ACCESS_TEST, ERB.new(File.read(File.join(TEMPLATES, "#{ACCESS_TEST}.tt")), trim_mode: "-").result(binding)
157
+ end
158
+ account = {"name" => "Backstage"}
159
+ account["allow_backstage"] = true if rails_auth?
160
+ append_backstage_fixture "test/fixtures/accounts.yml", "backstage", account
161
+ USER_FIXTURES.each do |label, (attributes, roles)|
162
+ append_backstage_fixture "test/fixtures/users.yml", label,
163
+ attributes.merge(auth_fixture_attributes(role: roles.fetch(auth_flavor)), "account" => "backstage")
164
+ end
165
+ end
166
+
167
+ # Appends a fixture under its label unless the label is already there,
168
+ # creating the file when it is missing.
169
+ def append_backstage_fixture(path, label, attributes)
170
+ entry = "#{label}:\n" + attributes.map { |key, value| " #{key}: #{value}\n" }.join
171
+ return create_file(path, entry) unless backstage_file?(path)
172
+
173
+ content = File.read(File.join(destination_root, path))
174
+ return if content.match?(/^#{Regexp.escape(label)}:/)
175
+
176
+ separator = if content.empty?
177
+ ""
178
+ else
179
+ (content.end_with?("\n") ? "\n" : "\n\n")
180
+ end
181
+ append_to_file path, separator + entry
182
+ end
183
+
184
+ def backstage_file?(path)
185
+ File.exist?(File.join(destination_root, path))
186
+ end
187
+
188
+ def say_backstage_access
189
+ return say_rails_backstage_access if rails_auth?
190
+
191
+ say " - Backstage access: signed-in users listed in credentials (bin/rails credentials:edit)"
192
+ say " backstage:"
193
+ say " emails:"
194
+ say " - you@example.com"
195
+ say " Anyone else gets a 404. Do not set backstage.username or password: Solid Errors"
196
+ say " turns its Basic Auth back on when a password is set."
197
+ end
198
+
199
+ def say_rails_backstage_access
200
+ say " - Backstage access: admins of an account with the backstage on. Turn it on for"
201
+ say " your own account from the console (bin/rails console):"
202
+ say " Account.find_by!(name: \"...\").update!(allow_backstage: true)"
203
+ say " Anyone else gets a 404. Do not set backstage.username or password: Solid Errors"
204
+ say " turns its Basic Auth back on when a password is set."
205
+ end
206
+
207
+ def say_backstage_signin_pending
208
+ return if backstage_signin_pending.empty?
209
+
210
+ say ""
211
+ say "These files were changed by hand, so they keep their Basic Auth. Move them to", :yellow
212
+ say "the backstage sign-in yourself (BackstageController#require_backstage_access):"
213
+ backstage_signin_pending.uniq.each { |path| say " - #{path}" }
214
+ end
215
+
216
+ # accounts.allow_backstage, off by default, unless a migration or the
217
+ # schema already has it.
218
+ def add_allow_backstage_column
219
+ return unless backstage_file?("app/models/account.rb")
220
+ return if Dir.glob(File.join(destination_root, "db/migrate/*_#{ALLOW_BACKSTAGE_MIGRATION}.rb")).any?
221
+ return if backstage_file?("db/schema.rb") && File.read(File.join(destination_root, "db/schema.rb")).include?(%("allow_backstage"))
222
+
223
+ create_file "db/migrate/#{allow_backstage_migration_number}_#{ALLOW_BACKSTAGE_MIGRATION}.rb", <<~RUBY
224
+ class AddAllowBackstageToAccounts < ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]
225
+ def change
226
+ # Admins of an account with this on open the backstage and use the
227
+ # admin-only MCP tools (User#backstage_access?).
228
+ add_column :accounts, :allow_backstage, :boolean, default: false, null: false
229
+ end
230
+ end
231
+ RUBY
232
+ end
233
+
234
+ def allow_backstage_migration_number
235
+ current = Time.now.utc.strftime("%Y%m%d%H%M%S")
236
+ existing = Dir.glob(File.join(destination_root, "db/migrate/[0-9]*_*.rb")).map { |f| File.basename(f).split("_", 2).first }.max
237
+ (existing && existing >= current) ? existing.succ : current
238
+ end
239
+
240
+ # admin? from the registration role enum or the app's own method.
241
+ def user_admin_predicate?(content) = content.match?(/enum :role\b/) || content.include?("def admin?")
242
+
243
+ def backstage_access_methods
244
+ return rails_backstage_access_methods if rails_auth?
245
+
246
+ <<-RUBY
247
+ # Who may open the backstage and use the admin-only MCP tools: an unblocked
248
+ # user whose email is listed in credentials (backstage.emails). An empty list
249
+ # is nobody. A list in config.x.backstage_emails is used instead, even an
250
+ # empty one; that is how the tests grant access. (Unset, config.x answers an
251
+ # empty OrderedOptions, not nil.)
252
+ def self.backstage_emails
253
+ emails = Rails.configuration.x.backstage_emails
254
+ emails = Rails.application.credentials.dig(:backstage, :emails) unless emails.is_a?(Array)
255
+ Array(emails).map { |email| email.to_s.strip.downcase }
256
+ end
257
+
258
+ def backstage_access?
259
+ !blocked? && self.class.backstage_emails.include?(email_address)
260
+ end
261
+
262
+ RUBY
263
+ end
264
+
265
+ def rails_backstage_access_methods
266
+ <<-RUBY
267
+ # Who may open the backstage and use the admin-only MCP tools: an admin of an
268
+ # account whose allow_backstage is on (off by default; turn it on from the
269
+ # console). Anyone else gets a 404.
270
+ def backstage_access?
271
+ account.allow_backstage? && admin?
272
+ end
273
+
274
+ RUBY
275
+ end
276
+
277
+ def backstage_controller_header
278
+ <<-RUBY
279
+ # The app's sign-in rather than a shared Basic Auth password, for every
280
+ # backstage page: the overview, Security and, through base_controller_class,
281
+ # the Solid Errors and Mission Control Jobs engines. Who gets in is
282
+ # User#backstage_access?; anyone else gets a 404, so the pages never confirm
283
+ # they exist.
284
+ include Authentication
285
+
286
+ # After the include, so it runs behind require_authentication and can rely
287
+ # on Current.session being resolved.
288
+ before_action :require_backstage_access
289
+
290
+ RUBY
291
+ end
292
+
293
+ def backstage_controller_private
294
+ <<-RUBY
295
+
296
+ private
297
+
298
+ # ActiveRecord::RecordNotFound rather than a redirect with an alert: the
299
+ # alert would confirm there is a backstage.
300
+ def require_backstage_access
301
+ raise ActiveRecord::RecordNotFound unless Current.user&.backstage_access?
302
+ end
303
+
304
+ # Restated rather than inherited: this controller serves two mounted
305
+ # engines, and inside one a bare new_session_path generates against the
306
+ # engine's routes. main_app reaches the app's sign-in from anywhere.
307
+ #
308
+ # 303 for PATCH/PUT/DELETE: both engines submit those verbs (resolve, retry,
309
+ # discard), and Turbo keeps the verb through a 302, so an expired session on
310
+ # Discard would re-issue the DELETE against the sign-in page.
311
+ def request_authentication
312
+ session[:return_to_after_authenticating] = request.url
313
+ redirect_to main_app.new_session_path
314
+ response.status = :see_other if request.patch? || request.put? || request.delete?
315
+ end
316
+ RUBY
317
+ end
318
+ end
319
+ end
320
+ end
@@ -0,0 +1,104 @@
1
+ require "test_helper"
2
+ require_relative "../test_helpers/session_test_helper"
3
+
4
+ <% if clave? -%>
5
+ # The backstage is behind the app's sign-in (generated by the maquina dashboard
6
+ # generators). Only a signed-in, unblocked user whose email is on the backstage
7
+ # list gets in; anyone else signed in gets a 404, so the pages never confirm
8
+ # they exist. The list lives in credentials (backstage.emails); these tests set
9
+ # config.x.backstage_emails, which User.backstage_emails reads first.
10
+ <% else -%>
11
+ # The backstage is behind the app's sign-in (generated by the maquina dashboard
12
+ # generators). Only a signed-in admin of an account whose allow_backstage is on
13
+ # gets in; anyone else signed in gets a 404, so the pages never confirm they
14
+ # exist. The backstage fixture account has it on.
15
+ <% end -%>
16
+ class BackstageAccessTest < ActionDispatch::IntegrationTest
17
+ # The engine pages mounted under the backstage prefix, whichever are installed.
18
+ PAGES = %w[errors jobs security].freeze
19
+
20
+ <% if clave? -%>
21
+ setup do
22
+ @emails_before = Rails.configuration.x.backstage_emails
23
+ Rails.configuration.x.backstage_emails = [users(:backstage_operator).email_address]
24
+ end
25
+
26
+ teardown do
27
+ Rails.configuration.x.backstage_emails = @emails_before
28
+ end
29
+
30
+ <% end -%>
31
+ test "signed out, every backstage page asks to sign in" do
32
+ # Before any request: after one into a mounted engine, URL helpers in an
33
+ # integration test generate under that engine's mount point.
34
+ sign_in = new_session_url
35
+
36
+ backstage_paths.each do |path|
37
+ get path
38
+
39
+ assert_redirected_to sign_in, path
40
+ end
41
+ end
42
+
43
+ <% if clave? -%>
44
+ test "a user not on the list gets not found on every backstage page" do
45
+ <% else -%>
46
+ test "a user who is not an admin gets not found on every backstage page" do
47
+ <% end -%>
48
+ sign_in_as users(:backstage_member)
49
+
50
+ backstage_paths.each do |path|
51
+ get path
52
+
53
+ assert_response :not_found, path
54
+ end
55
+ end
56
+
57
+ <% if clave? -%>
58
+ test "a blocked user on the list gets not found" do
59
+ users(:backstage_operator).block!(reason: "test")
60
+ sign_in_as users(:backstage_operator)
61
+
62
+ get backstage_dashboard_path
63
+
64
+ assert_response :not_found
65
+ end
66
+
67
+ test "an empty list lets nobody in" do
68
+ Rails.configuration.x.backstage_emails = []
69
+ sign_in_as users(:backstage_operator)
70
+
71
+ get backstage_dashboard_path
72
+
73
+ assert_response :not_found
74
+ end
75
+
76
+ test "a user on the list gets in" do
77
+ <% else -%>
78
+ test "an admin of an account with the backstage off gets not found" do
79
+ accounts(:backstage).update!(allow_backstage: false)
80
+ sign_in_as users(:backstage_operator)
81
+
82
+ get backstage_dashboard_path
83
+
84
+ assert_response :not_found
85
+ end
86
+
87
+ test "an admin of an account with the backstage on gets in" do
88
+ <% end -%>
89
+ sign_in_as users(:backstage_operator)
90
+
91
+ get backstage_dashboard_path
92
+
93
+ assert_response :success
94
+ end
95
+
96
+ private
97
+
98
+ def backstage_paths
99
+ mounted = Rails.application.routes.routes.map { |route| route.path.spec.to_s }
100
+ pages = PAGES.map { |page| "#{backstage_dashboard_path}/#{page}" }.select { |path| mounted.any? { |spec| spec.start_with?(path) } }
101
+
102
+ [backstage_dashboard_path, *pages]
103
+ end
104
+ end
@@ -1,10 +1,12 @@
1
1
  require "rails/generators"
2
2
  require "rails/generators/migration"
3
+ require_relative "../mcp/mcp_sibling_tools"
3
4
 
4
5
  module Maquina
5
6
  module Generators
6
7
  class CspReportsGenerator < Rails::Generators::Base
7
8
  include Rails::Generators::Migration
9
+ include McpSiblingTools
8
10
 
9
11
  source_root File.expand_path("templates", __dir__)
10
12
 
@@ -130,7 +132,12 @@ module Maquina
130
132
  end
131
133
  end
132
134
 
133
- # 9. Post-install message
135
+ # 9. MCP tools (admin only, read-only), when maquina:mcp is installed
136
+ def create_mcp_tools
137
+ @mcp_tools_installed = install_mcp_tools(:csp_reports)
138
+ end
139
+
140
+ # 10. Post-install message
134
141
  def show_post_install
135
142
  return if options[:quiet]
136
143
 
@@ -141,6 +148,11 @@ module Maquina
141
148
  say " - Add the table: bin/rails db:migrate (db:prepare on deploy)"
142
149
  say " - Watch the Security page while the policy is report-only, then set"
143
150
  say " content_security_policy_report_only = false to enforce it."
151
+ if @mcp_tools_installed
152
+ say ""
153
+ say "MCP tools (admin only, read-only): app/models/mcp/tools/csp_reports.rb", :green
154
+ say " list_csp_reports, csp_report_summary"
155
+ end
144
156
  if @report_uri_pending
145
157
  say ""
146
158
  say "Point the policy at the endpoint in config/initializers/content_security_policy.rb:", :yellow
@@ -0,0 +1,71 @@
1
+ # MCP tools over the Content Security Policy violations browsers report
2
+ # (generated by maquina:csp_reports).
3
+ #
4
+ # Admin only: a member's token neither sees nor reaches these tools. Read-only.
5
+ # Reported URLs are stored without query or fragment; the reporter's IP address
6
+ # is not returned.
7
+ module Mcp
8
+ module Tools
9
+ module CspReports
10
+ ADMIN_ONLY = true
11
+ WRITE_TOOLS = %w[].freeze
12
+
13
+ MAX_LIMIT = 50
14
+ MAX_DAYS = 30
15
+ SCHEMA = "https://json-schema.org/draft/2020-12/schema"
16
+
17
+ DEFINITIONS = [
18
+ {
19
+ name: "list_csp_reports",
20
+ description: "Content Security Policy violations browsers reported, newest first. Each entry has " \
21
+ "the directive that was violated, the blocked URI, the page (document URI), the source file " \
22
+ "with line and column, the disposition (enforce or report), a code sample when the browser " \
23
+ "sent one, the user agent and at (ISO 8601 UTC). Reports are kept for 30 days. Returns at " \
24
+ "most 50 entries.",
25
+ inputSchema: {
26
+ "$schema": SCHEMA, type: "object",
27
+ properties: {limit: {type: "integer", description: "Number of reports to return, 1-50. Default 20."}},
28
+ required: [], additionalProperties: false
29
+ },
30
+ annotations: {readOnlyHint: true}
31
+ },
32
+ {
33
+ name: "csp_report_summary",
34
+ description: "Content Security Policy violations over the last days, grouped by directive, " \
35
+ "blocked URI and page, most frequent first: one group per thing to fix, with its count and " \
36
+ "last_seen (ISO 8601 UTC). Also returns the total number of reports in the window. Returns at " \
37
+ "most 50 groups.",
38
+ inputSchema: {
39
+ "$schema": SCHEMA, type: "object",
40
+ properties: {days: {type: "integer", description: "Window length in days, 1-30. Default 7."}},
41
+ required: [], additionalProperties: false
42
+ },
43
+ annotations: {readOnlyHint: true}
44
+ }
45
+ ].freeze
46
+
47
+ def self.list_csp_reports(scope:, limit: 20)
48
+ reports = ::Security::CspViolation.recent.limit(limit.to_i.clamp(1, MAX_LIMIT)).map do |violation|
49
+ {effective_directive: violation.effective_directive, blocked_uri: violation.blocked_uri,
50
+ document_uri: violation.document_uri, source_file: violation.source_file,
51
+ line_number: violation.line_number, column_number: violation.column_number,
52
+ disposition: violation.disposition, sample: violation.sample, user_agent: violation.user_agent,
53
+ at: violation.created_at.utc.iso8601}
54
+ end
55
+
56
+ {reports: reports}
57
+ end
58
+
59
+ def self.csp_report_summary(scope:, days: 7)
60
+ days = days.to_i.clamp(1, MAX_DAYS)
61
+ report = ::Security::CspViolationReport.new(window: days.days, limit: MAX_LIMIT)
62
+
63
+ groups = report.top.map do |group|
64
+ group.to_h.merge(last_seen: group.last_seen&.utc&.iso8601)
65
+ end
66
+
67
+ {days: days, total: report.total, groups: groups}
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,35 @@
1
+ require "test_helper"
2
+
3
+ # The CSP report MCP tools are admin only (generated by maquina:csp_reports).
4
+ # A member's token must not learn they exist: they are absent from tools/list
5
+ # and a call gets the same -32602 as an unknown tool. McpTestHelper turns
6
+ # any MCP feature flag on, so the role is the only gate tested.
7
+ class Mcp::Tools::CspReportsTest < ActionDispatch::IntegrationTest
8
+ TOOLS = Mcp::Tools::CspReports::DEFINITIONS.map { |definition| definition[:name] }
9
+ ARGUMENTS = {}.freeze
10
+
11
+ test "an admin sees the tools" do
12
+ assert_equal TOOLS, TOOLS & listed_tools(users(:mcp_admin))
13
+ end
14
+
15
+ test "a member does not see the tools" do
16
+ assert_empty TOOLS & listed_tools(users(:mcp_member))
17
+ end
18
+
19
+ test "a member calling any of the tools gets unknown tool" do
20
+ token = oauth_token_for(users(:mcp_member), scope: "read write")
21
+
22
+ TOOLS.each do |name|
23
+ mcp_post({jsonrpc: "2.0", id: 1, method: "tools/call", params: {name: name, arguments: ARGUMENTS.fetch(name, {})}}, token: token)
24
+
25
+ assert_equal(-32602, response.parsed_body.dig("error", "code"), name)
26
+ end
27
+ end
28
+
29
+ private
30
+
31
+ def listed_tools(user)
32
+ mcp_post({jsonrpc: "2.0", id: 1, method: "tools/list", params: {}}, token: oauth_token_for(user, scope: "read write"))
33
+ response.parsed_body.dig("result", "tools").map { |tool| tool["name"] }
34
+ end
35
+ end
@@ -0,0 +1,22 @@
1
+ Description:
2
+ Tags every error Solid Errors records with who and where it happened: the
3
+ request's id, method and path, and the signed-in user's and account's ids
4
+ (ids only, no email). Needs maquina:solid_errors; a new install of
5
+ maquina:solid_errors already includes it, so run this in an app installed
6
+ before 0.11.
7
+
8
+ Adds config/initializers/error_context.rb, a Rails error reporter
9
+ middleware that reads Current when the error is reported, so it sees a
10
+ Current.account set late by a tenant scope and covers jobs and controllers
11
+ that do not inherit ApplicationController. It gives the MCP tool
12
+ list_failures (and bin/failures) user_id, account_id and since filters.
13
+
14
+ Nothing maquina:solid_errors would overwrite is touched. The query and tool
15
+ files (app/agents/errors_query.rb, failure_triage.rb, list_failures_tool.rb,
16
+ app/models/mcp/tools/solid_errors.rb) are replaced only when they are
17
+ exactly what an earlier release wrote; an edited one is kept and listed
18
+ after the install. The filters' test goes in its own file,
19
+ test/models/mcp/tools/solid_errors_filters_test.rb.
20
+
21
+ Examples:
22
+ rails g maquina:error_context
@@ -0,0 +1,51 @@
1
+ require "rails/generators"
2
+ require_relative "../mcp/mcp_sibling_tools"
3
+ require_relative "../solid_errors/error_context_files"
4
+
5
+ module Maquina
6
+ module Generators
7
+ # Request error context for an app that ran maquina:solid_errors before it
8
+ # existed. Touches nothing maquina:solid_errors would overwrite (views,
9
+ # layout, initializer): it adds config/initializers/error_context.rb,
10
+ # upgrades the query and MCP tool files only where they are unedited, and
11
+ # adds their test.
12
+ class ErrorContextGenerator < Rails::Generators::Base
13
+ include McpSiblingTools
14
+ include ErrorContextFiles
15
+
16
+ source_root File.expand_path("../solid_errors/templates", __dir__)
17
+
18
+ class_option :quiet, type: :boolean, default: false,
19
+ desc: "Suppress post-install instructions"
20
+
21
+ # 1. Solid Errors is where the context goes.
22
+ def require_solid_errors
23
+ return if File.exist?(File.join(destination_root, "config/initializers/solid_errors.rb"))
24
+
25
+ raise Thor::Error, "maquina:error_context tags the errors Solid Errors records. Run `rails g maquina:solid_errors --prefix /admin` first."
26
+ end
27
+
28
+ # 2. The error reporter middleware
29
+ def create_initializer
30
+ install_error_context_initializer
31
+ end
32
+
33
+ # 3. The user/account filters, where the files are as a release wrote them
34
+ def upgrade_query_and_tools
35
+ @error_context_files = upgrade_error_context_files
36
+ end
37
+
38
+ # 4. Their host-app test, once the tool file has the filters
39
+ def create_filters_test
40
+ install_mcp_feature_tests(:solid_errors)
41
+ end
42
+
43
+ def show_post_install
44
+ return if options[:quiet]
45
+
46
+ say ""
47
+ say_error_context_installed(customized: @error_context_files[:customized])
48
+ end
49
+ end
50
+ end
51
+ end