studio-engine 0.145.0 → 0.146.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +11 -0
- data/app/jobs/studio/email_delivery_job.rb +12 -0
- data/app/models/error_log.rb +9 -0
- data/lib/studio/engine.rb +8 -0
- data/lib/studio/error_alerts.rb +439 -0
- data/lib/studio/health_report.rb +25 -3
- data/lib/studio/mail_transport.rb +43 -3
- data/lib/studio/version.rb +1 -1
- data/lib/studio.rb +1 -0
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: e20e5de5e8bb5ad4584ff7c1bf4f26055486c26f03c4f401675ccd8beac93e5f
|
|
4
|
+
data.tar.gz: 57d6a19c2e82d7b9d781ee90d2d32bd4eddd3fe02966335f03c2308eff2a0d77
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: cd18dd860bb685ef9b85da9f164f61cf2d5d6a43087bfb53710e3111bed194e9589e2f1fef552c7e714af0b9ce32528b1a8c84c8d2861acb94d9afd64cb57371
|
|
7
|
+
data.tar.gz: 62a7517bec8db1ab436f70bea1527163f914654c8967be11f31cc66bc7036c5d5024886809a1b3f43d75da3cfcdaa803f8c0d24582381cf50e92c9cc682ffcb5
|
data/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,17 @@ The format is [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). This pro
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.146.0 — 2026-11-28
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **Error alerts to the hub (`Studio::ErrorAlerts`).** Every `ErrorLog.capture!` in production now sends one HMAC-signed alert to the McRitchie Studio hub (`POST /api/v1/error_alerts`), signed with the `STUDIO_HEALTH_TOKEN` the app already holds, throttled once per fingerprint per hour per process with a held-back count, on its own thread, never raising. Alerts are classified: magic-link mail failures, sign-in/SSO/session errors and a production boot with no mail transport are `front_door` (the hub pings the owner). `STUDIO_ERROR_ALERTS=off` stops it. See `docs/ERROR_ALERTS.md`.
|
|
12
|
+
- **`front_door` on `GET /_studio/health_report`.** An additive key: `mail_transport` (`Studio::MailTransport.status`: configured, transport, delivery_method) and `login_path`, read by the hub's hourly front-door probe. `Studio::MailTransport.configure!` now records `last_result`.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **A failed `Studio::EmailDeliveryJob` send is an `ErrorLog` row.** On an app with no worker (the `:async` adapter) a dead mail transport used to kill every magic link with no trace; the job now logs the failure before it re-raises.
|
|
17
|
+
|
|
7
18
|
## 0.145.0 — 2026-11-28
|
|
8
19
|
|
|
9
20
|
### Added
|
|
@@ -2,8 +2,20 @@ module Studio
|
|
|
2
2
|
class EmailDeliveryJob < (defined?(::ApplicationJob) ? ::ApplicationJob : ActiveJob::Base)
|
|
3
3
|
queue_as :mailers
|
|
4
4
|
|
|
5
|
+
# A failed send is an ErrorLog row before it re-raises. An app with no
|
|
6
|
+
# worker runs this on the :async adapter, which only logs the raise; without
|
|
7
|
+
# the row a dead mail transport (every magic link failing) left no trace
|
|
8
|
+
# anyone reads. The row also raises the hub's front-door alert
|
|
9
|
+
# (Studio::ErrorAlerts, category magic_link_delivery).
|
|
5
10
|
def perform(id)
|
|
6
11
|
Studio::EmailDelivery.find_by(id: id)&.deliver_now!
|
|
12
|
+
rescue StandardError => e
|
|
13
|
+
begin
|
|
14
|
+
ErrorLog.capture!(e) if defined?(::ErrorLog) && ::ErrorLog.respond_to?(:capture!)
|
|
15
|
+
rescue StandardError => log_error
|
|
16
|
+
Rails.logger.warn("[Studio::EmailDeliveryJob] could not log the failed send: #{log_error.class}")
|
|
17
|
+
end
|
|
18
|
+
raise
|
|
7
19
|
end
|
|
8
20
|
end
|
|
9
21
|
end
|
data/app/models/error_log.rb
CHANGED
|
@@ -42,6 +42,15 @@ class ErrorLog < ApplicationRecord
|
|
|
42
42
|
end
|
|
43
43
|
end
|
|
44
44
|
|
|
45
|
+
# One signed alert to the hub, which posts it to Discord (docs/ERROR_ALERTS.md).
|
|
46
|
+
# Inert outside production or with no hub token; never raises, never blocks,
|
|
47
|
+
# and writes no row of its own.
|
|
48
|
+
begin
|
|
49
|
+
Studio::ErrorAlerts.report_exception(exception, error_log: log) if defined?(Studio::ErrorAlerts)
|
|
50
|
+
rescue StandardError => e
|
|
51
|
+
Rails.logger.warn "[ErrorLog.capture!] error alert failed: #{e.class}"
|
|
52
|
+
end
|
|
53
|
+
|
|
45
54
|
log
|
|
46
55
|
end
|
|
47
56
|
|
data/lib/studio/engine.rb
CHANGED
|
@@ -445,6 +445,14 @@ module Studio
|
|
|
445
445
|
Studio::HostSchema.check!
|
|
446
446
|
Studio::HostSchema.device_session_check!
|
|
447
447
|
end
|
|
448
|
+
|
|
449
|
+
# A production boot whose mail goes nowhere real (no RESEND_API_KEY, so
|
|
450
|
+
# ActionMailer is still the Rails default SMTP on localhost:25): every
|
|
451
|
+
# magic link dies while the login page looks fine. Raise the front-door
|
|
452
|
+
# alert once at boot. Inert outside production, in QA, with no hub token,
|
|
453
|
+
# and in a rake task (assets:precompile boots production too).
|
|
454
|
+
# Studio::ErrorAlerts, docs/ERROR_ALERTS.md.
|
|
455
|
+
Studio::ErrorAlerts.boot_check! unless Studio::HostSchema.inside_rake_task?
|
|
448
456
|
end
|
|
449
457
|
|
|
450
458
|
end
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "active_support"
|
|
4
|
+
require "active_support/core_ext/module/attribute_accessors"
|
|
5
|
+
require "active_support/core_ext/object/blank"
|
|
6
|
+
require "active_support/core_ext/string/inflections"
|
|
7
|
+
require "active_support/security_utils"
|
|
8
|
+
require "digest"
|
|
9
|
+
require "json"
|
|
10
|
+
require "net/http"
|
|
11
|
+
require "openssl"
|
|
12
|
+
require "uri"
|
|
13
|
+
require_relative "version"
|
|
14
|
+
|
|
15
|
+
# Error alerts: every ErrorLog row an app writes becomes one signed alert to the
|
|
16
|
+
# McRitchie Studio hub, which posts it to Discord with a link to a page that
|
|
17
|
+
# explains it in words. The guide is docs/ERROR_ALERTS.md.
|
|
18
|
+
#
|
|
19
|
+
# THE FRONT DOOR. An alert is classified. A "front_door" alert is a failure at
|
|
20
|
+
# the way in: a magic-link email that could not be sent, a sign-in / SSO /
|
|
21
|
+
# session / token error, or a production boot with no mail transport. The hub
|
|
22
|
+
# pings the owner for those. Every other alert ("error") posts without a ping.
|
|
23
|
+
#
|
|
24
|
+
# INERT BY DEFAULT. Nothing is sent unless the app runs in production (not QA),
|
|
25
|
+
# names the hub token it already holds for the daily health report
|
|
26
|
+
# (Studio.health_report_token / STUDIO_HEALTH_TOKEN), and has not set
|
|
27
|
+
# STUDIO_ERROR_ALERTS=off. The same token signs the alert (HMAC-SHA256), so an
|
|
28
|
+
# app wired for the health report needs no new secret; the hub verifies with
|
|
29
|
+
# its HEALTH_TOKEN_<SLUG> twin.
|
|
30
|
+
#
|
|
31
|
+
# NEVER IN THE WAY. Reporting never raises and never blocks: the POST runs on
|
|
32
|
+
# its own thread with short timeouts, and any failure is a log line, never an
|
|
33
|
+
# ErrorLog row (a row would alert again). Each process sends a fingerprint at
|
|
34
|
+
# most once an hour and carries the count it held back on the next send; the
|
|
35
|
+
# hub dedupes across processes the same way.
|
|
36
|
+
#
|
|
37
|
+
# The config lives HERE (like Studio::HealthReport's) so the unit suite loads it
|
|
38
|
+
# with the rules it governs; `Studio.configure` sets it like any other setting.
|
|
39
|
+
module Studio
|
|
40
|
+
# nil (auto) = on in production outside QA when a token is set; true / false force it.
|
|
41
|
+
mattr_accessor :error_alerts_enabled, default: nil
|
|
42
|
+
# Where alerts go: the hub's POST /api/v1/error_alerts.
|
|
43
|
+
mattr_accessor :error_alerts_hub_url, default: "https://mcritchie.studio"
|
|
44
|
+
# The app's registry slug at the hub (config/apps.yml). nil falls through to
|
|
45
|
+
# ENV["STUDIO_APP_SLUG"], then to Studio.app_name parameterized
|
|
46
|
+
# ("Commercial Welding" -> "commercial-welding").
|
|
47
|
+
mattr_accessor :error_alerts_app_slug, default: nil
|
|
48
|
+
# A callable taking the payload Hash, used INSTEAD of the HTTP POST. The hub
|
|
49
|
+
# sets it to record its own alerts in-process (no HTTP to itself); tests set it
|
|
50
|
+
# to capture. nil = POST to the hub.
|
|
51
|
+
mattr_accessor :error_alerts_sink, default: nil
|
|
52
|
+
|
|
53
|
+
module ErrorAlerts
|
|
54
|
+
SCHEMA = 1
|
|
55
|
+
PATH = "/api/v1/error_alerts"
|
|
56
|
+
OFF_ENV = "STUDIO_ERROR_ALERTS"
|
|
57
|
+
SLUG_ENV = "STUDIO_APP_SLUG"
|
|
58
|
+
# Armed by the test helpers: a real POST raises before it opens a socket.
|
|
59
|
+
NO_LIVE_CALLS_ENV = "STUDIO_ERROR_ALERTS_NO_LIVE_CALLS"
|
|
60
|
+
SIGNATURE_HEADER = "X-Studio-Signature"
|
|
61
|
+
TIMESTAMP_HEADER = "X-Studio-Timestamp"
|
|
62
|
+
APP_HEADER = "X-Studio-App"
|
|
63
|
+
# A signature older or newer than this is refused (replay and clock skew).
|
|
64
|
+
MAX_SKEW = 300
|
|
65
|
+
THROTTLE_WINDOW = 3600
|
|
66
|
+
THROTTLE_MAX_KEYS = 500
|
|
67
|
+
BACKTRACE_LINES = 15
|
|
68
|
+
MESSAGE_LIMIT = 1000
|
|
69
|
+
OPEN_TIMEOUT = 3
|
|
70
|
+
READ_TIMEOUT = 5
|
|
71
|
+
|
|
72
|
+
KINDS = %w[front_door error].freeze
|
|
73
|
+
# category => kind. The hub owns the words for each (ErrorAlerts::Explainer).
|
|
74
|
+
CATEGORIES = {
|
|
75
|
+
"magic_link_delivery" => "front_door",
|
|
76
|
+
"mail_transport_missing" => "front_door",
|
|
77
|
+
"sign_in" => "front_door",
|
|
78
|
+
"login_page_down" => "front_door",
|
|
79
|
+
"error" => "error"
|
|
80
|
+
}.freeze
|
|
81
|
+
|
|
82
|
+
# Controllers that ARE the front door (the engine's own, and the names
|
|
83
|
+
# every host uses for them).
|
|
84
|
+
AUTH_CONTROLLERS = %w[
|
|
85
|
+
SessionsController MagicLinksController RegistrationsController OmniauthCallbacksController
|
|
86
|
+
SolanaSessionsController Studio::LinksController Studio::LocalReviewsController Studio::SessionStatesController
|
|
87
|
+
].freeze
|
|
88
|
+
AUTH_PATH = %r{\A/(?:login|logout|signup|magic_link|sso_continue|sso_login|auth/|l/|links/|_studio/session)}
|
|
89
|
+
# Error classes that mean "could not sign in" wherever they are raised.
|
|
90
|
+
AUTH_ERROR = /\A(?:ActionController::InvalidAuthenticityToken|OmniAuth::|JWT::|Studio::LinkToken|Studio::OauthIdentity|Studio::GoogleSignIn)/
|
|
91
|
+
# Backtrace frames from the engine's sign-in code.
|
|
92
|
+
AUTH_FRAME = %r{(?:magic_link|link_consumption|link_token|session_drift|user_session|omniauth|google_sign_in|oauth_identity|sessions_controller|solana_sessions|registrations_controller)}
|
|
93
|
+
# Mail transport failures: the socket, SMTP, or the Resend API.
|
|
94
|
+
MAIL_ERROR = /\A(?:Net::SMTP|Net::OpenTimeout|Net::ReadTimeout|Errno::ECONNREFUSED|Errno::ECONNRESET|Errno::EHOSTUNREACH|SocketError|OpenSSL::SSL|Resend::)/
|
|
95
|
+
MAIL_FRAME = %r{(?:/mail-[\d.]+/|net/smtp|/resend|action_mailer|email_delivery|mail_delivery_job)}
|
|
96
|
+
MAIL_JOBS = %w[Studio::EmailDeliveryJob ActionMailer::MailDeliveryJob EmailDeliveryJob].freeze
|
|
97
|
+
AUTH_MAILER_ACTION = /magic_link|login|sign_in|signin|verify|confirm|password/i
|
|
98
|
+
|
|
99
|
+
EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/
|
|
100
|
+
# Long opaque runs (tokens, keys, signed ids) in a message.
|
|
101
|
+
OPAQUE = /\b[A-Za-z0-9_\-]{32,}\b/
|
|
102
|
+
|
|
103
|
+
LiveCallAttempted = Class.new(StandardError)
|
|
104
|
+
LOOPBACK_HOSTS = %w[127.0.0.1 localhost ::1 [::1]].freeze
|
|
105
|
+
|
|
106
|
+
module_function
|
|
107
|
+
|
|
108
|
+
# ---- switches -----------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def token = Studio.respond_to?(:health_report_token) ? Studio.health_report_token : ENV["STUDIO_HEALTH_TOKEN"].presence
|
|
111
|
+
|
|
112
|
+
def enabled?(rails_env: current_rails_env, env: ENV)
|
|
113
|
+
return false if %w[off false 0 no].include?(env[OFF_ENV].to_s.strip.downcase)
|
|
114
|
+
return false if token.blank? && Studio.error_alerts_sink.nil?
|
|
115
|
+
|
|
116
|
+
forced = Studio.error_alerts_enabled
|
|
117
|
+
return forced unless forced.nil?
|
|
118
|
+
|
|
119
|
+
rails_env.to_s == "production" && !qa?
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def app_slug
|
|
123
|
+
Studio.error_alerts_app_slug.presence || ENV[SLUG_ENV].presence || Studio.app_name.to_s.parameterize.presence || "app"
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# ---- classification -----------------------------------------------------
|
|
127
|
+
|
|
128
|
+
# [kind, category] for one failure. `context` is the Hash #context_for
|
|
129
|
+
# builds: controller / path / job / mailer.
|
|
130
|
+
def classify(error_class:, message: nil, backtrace: [], context: {})
|
|
131
|
+
context = (context || {}).transform_keys(&:to_s)
|
|
132
|
+
error_class = error_class.to_s
|
|
133
|
+
frames = Array(backtrace).map(&:to_s)
|
|
134
|
+
|
|
135
|
+
category =
|
|
136
|
+
if mail_failure?(error_class, frames, context) then "magic_link_delivery"
|
|
137
|
+
elsif sign_in_failure?(error_class, frames, context) then "sign_in"
|
|
138
|
+
else "error"
|
|
139
|
+
end
|
|
140
|
+
[CATEGORIES.fetch(category), category]
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def mail_failure?(error_class, frames, context)
|
|
144
|
+
in_mail_job = MAIL_JOBS.include?(context["job"].to_s)
|
|
145
|
+
mail_stack = frames.any? { |f| f.match?(MAIL_FRAME) }
|
|
146
|
+
return false unless in_mail_job || mail_stack
|
|
147
|
+
|
|
148
|
+
# A transport failure kills every email, the magic link included. Any
|
|
149
|
+
# other failure in a mail job counts when the mail is a sign-in mail.
|
|
150
|
+
error_class.match?(MAIL_ERROR) || context["mailer_action"].to_s.match?(AUTH_MAILER_ACTION) ||
|
|
151
|
+
(in_mail_job && context["mailer_action"].blank?)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def sign_in_failure?(error_class, frames, context)
|
|
155
|
+
AUTH_CONTROLLERS.include?(context["controller"].to_s) ||
|
|
156
|
+
context["path"].to_s.match?(AUTH_PATH) ||
|
|
157
|
+
error_class.match?(AUTH_ERROR) ||
|
|
158
|
+
frames.first(5).any? { |f| f.match?(AUTH_FRAME) }
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Stable across occurrences: the app, the category, the class, and the
|
|
162
|
+
# message with its variable parts (numbers, ids, emails, tokens) blanked.
|
|
163
|
+
# Named alert_fingerprint because Studio::SessionFingerprint owns the bare word.
|
|
164
|
+
def alert_fingerprint(app:, category:, error_class:, message:)
|
|
165
|
+
normalized = scrub(message).gsub(/0x\h+/, "0x").gsub(/\d+/, "N").squeeze(" ").strip[0, 200]
|
|
166
|
+
Digest::SHA256.hexdigest([app, category, error_class, normalized].join("|"))[0, 32]
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# No addresses and no opaque tokens leave the app.
|
|
170
|
+
def scrub(text) = text.to_s.gsub(EMAIL, "[email]").gsub(OPAQUE, "[redacted]")
|
|
171
|
+
|
|
172
|
+
# ---- reporting ----------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
# Called by ErrorLog.capture! after it writes the row. Never raises.
|
|
175
|
+
def report_exception(exception, error_log: nil, context: nil, now: Time.now)
|
|
176
|
+
return nil unless enabled?
|
|
177
|
+
|
|
178
|
+
context ||= context_for(execution_context)
|
|
179
|
+
backtrace = Array(exception.backtrace).first(BACKTRACE_LINES)
|
|
180
|
+
kind, category = classify(error_class: exception.class.name, message: exception.message, backtrace: backtrace,
|
|
181
|
+
context: context)
|
|
182
|
+
report(category: category, kind: kind, error_class: exception.class.name, message: exception.message,
|
|
183
|
+
backtrace: backtrace, context: context, error_log_slug: error_log.respond_to?(:slug) ? error_log.slug : nil,
|
|
184
|
+
now: now)
|
|
185
|
+
rescue StandardError => e
|
|
186
|
+
warn_log("report_exception failed: #{e.class}")
|
|
187
|
+
nil
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# A condition rather than an exception: the production boot with no mail
|
|
191
|
+
# transport, or the hub's own probe. Never raises.
|
|
192
|
+
def report_condition(category:, message:, error_class: "Studio::ErrorAlerts::Condition", context: {}, now: Time.now)
|
|
193
|
+
return nil unless enabled?
|
|
194
|
+
|
|
195
|
+
report(category: category, kind: CATEGORIES.fetch(category, "error"), error_class: error_class,
|
|
196
|
+
message: message, backtrace: [], context: context, now: now)
|
|
197
|
+
rescue StandardError => e
|
|
198
|
+
warn_log("report_condition failed: #{e.class}")
|
|
199
|
+
nil
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# The boot half of the front door (lib/studio/engine.rb after_initialize):
|
|
203
|
+
# production mail that would go nowhere real raises mail_transport_missing.
|
|
204
|
+
# Returns the payload sent, or nil. Never raises.
|
|
205
|
+
def boot_check!(status: mail_transport_status, now: Time.now)
|
|
206
|
+
return nil unless enabled?
|
|
207
|
+
return nil if status.nil? || status[:configured]
|
|
208
|
+
|
|
209
|
+
report_condition(
|
|
210
|
+
category: "mail_transport_missing",
|
|
211
|
+
error_class: "Studio::MailTransport",
|
|
212
|
+
message: "#{Studio::MailTransport::NOT_CONFIGURED} (transport #{status[:transport]}, " \
|
|
213
|
+
"delivery_method #{status[:delivery_method].presence || 'none'})",
|
|
214
|
+
context: { "phase" => "boot" }, now: now
|
|
215
|
+
)
|
|
216
|
+
rescue StandardError => e
|
|
217
|
+
warn_log("boot_check! failed: #{e.class}")
|
|
218
|
+
nil
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Throttle, build, dispatch. Returns the payload sent, or nil when held back.
|
|
222
|
+
def report(category:, kind:, error_class:, message:, backtrace:, context:, now:, error_log_slug: nil)
|
|
223
|
+
slug = app_slug
|
|
224
|
+
fingerprint = alert_fingerprint(app: slug, category: category, error_class: error_class, message: message)
|
|
225
|
+
count = throttle.admit(fingerprint, now)
|
|
226
|
+
return nil if count.nil?
|
|
227
|
+
|
|
228
|
+
payload = build_payload(slug: slug, category: category, kind: kind, error_class: error_class, message: message,
|
|
229
|
+
backtrace: backtrace, context: context, fingerprint: fingerprint, count: count,
|
|
230
|
+
now: now, error_log_slug: error_log_slug)
|
|
231
|
+
dispatch(payload)
|
|
232
|
+
payload
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def build_payload(slug:, category:, kind:, error_class:, message:, backtrace:, context:, fingerprint:, count:, now:,
|
|
236
|
+
error_log_slug: nil)
|
|
237
|
+
{
|
|
238
|
+
schema: SCHEMA,
|
|
239
|
+
app: slug,
|
|
240
|
+
app_name: Studio.app_name.to_s,
|
|
241
|
+
engine_version: Studio::VERSION,
|
|
242
|
+
environment: current_rails_env.to_s,
|
|
243
|
+
kind: kind,
|
|
244
|
+
category: category,
|
|
245
|
+
alert_fingerprint: fingerprint,
|
|
246
|
+
count: count,
|
|
247
|
+
occurred_at: now.utc.iso8601,
|
|
248
|
+
error_class: error_class.to_s,
|
|
249
|
+
message: scrub(message)[0, MESSAGE_LIMIT],
|
|
250
|
+
backtrace: Array(backtrace).first(BACKTRACE_LINES).map { |line| scrub(line)[0, 300] },
|
|
251
|
+
context: (context || {}).transform_keys(&:to_s).transform_values { |v| scrub(v)[0, 300] },
|
|
252
|
+
error_log_slug: error_log_slug,
|
|
253
|
+
mail_transport: mail_transport_status
|
|
254
|
+
}
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# Where it happened, from Rails' own execution context: the request
|
|
258
|
+
# (path WITHOUT its query string, method, controller#action, request id) or
|
|
259
|
+
# the job (class, id, and an email job's mailer#action).
|
|
260
|
+
def context_for(exec)
|
|
261
|
+
exec ||= {}
|
|
262
|
+
out = {}
|
|
263
|
+
if (controller = exec[:controller])
|
|
264
|
+
out["controller"] = controller.class.name
|
|
265
|
+
out["action"] = controller.action_name.to_s if controller.respond_to?(:action_name)
|
|
266
|
+
if controller.respond_to?(:request) && (request = controller.request)
|
|
267
|
+
# The ROUTE, never the live path: /l/:token carries a live magic link.
|
|
268
|
+
pattern = request.route_uri_pattern if request.respond_to?(:route_uri_pattern)
|
|
269
|
+
out["path"] = (pattern.presence || request.path).to_s.delete_suffix("(.:format)")
|
|
270
|
+
out["method"] = request.request_method.to_s
|
|
271
|
+
out["request_id"] = request.request_id.to_s if request.respond_to?(:request_id)
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
if (job = exec[:job])
|
|
275
|
+
out["job"] = job.class.name
|
|
276
|
+
out["job_id"] = job.job_id.to_s if job.respond_to?(:job_id)
|
|
277
|
+
mailer_action = mailer_action_for(job)
|
|
278
|
+
out["mailer_action"] = mailer_action if mailer_action
|
|
279
|
+
end
|
|
280
|
+
out.compact.reject { |_, v| v.to_s.empty? }
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
def mailer_action_for(job)
|
|
284
|
+
if job.class.name == "Studio::EmailDeliveryJob" && defined?(Studio::EmailDelivery)
|
|
285
|
+
id = Array(job.arguments).first
|
|
286
|
+
row = Studio::EmailDelivery.find_by(id: id) if id
|
|
287
|
+
return "#{row.mailer}##{row.action}" if row
|
|
288
|
+
elsif job.class.name == "ActionMailer::MailDeliveryJob"
|
|
289
|
+
mailer, action = Array(job.arguments).first(2)
|
|
290
|
+
return "#{mailer}##{action}" if mailer
|
|
291
|
+
end
|
|
292
|
+
nil
|
|
293
|
+
rescue StandardError
|
|
294
|
+
nil
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
def execution_context
|
|
298
|
+
return {} unless defined?(ActiveSupport::ExecutionContext)
|
|
299
|
+
|
|
300
|
+
ActiveSupport::ExecutionContext.to_h
|
|
301
|
+
rescue StandardError
|
|
302
|
+
{}
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def mail_transport_status
|
|
306
|
+
return nil unless defined?(Studio::MailTransport)
|
|
307
|
+
|
|
308
|
+
Studio::MailTransport.status
|
|
309
|
+
rescue StandardError
|
|
310
|
+
nil
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
# ---- delivery -----------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
def dispatch(payload)
|
|
316
|
+
sink = Studio.error_alerts_sink
|
|
317
|
+
return run_safely { sink.call(payload) } if sink && synchronous?
|
|
318
|
+
|
|
319
|
+
Thread.new do
|
|
320
|
+
Thread.current.name = "studio-error-alert" if Thread.current.respond_to?(:name=)
|
|
321
|
+
run_safely { sink ? sink.call(payload) : deliver(payload) }
|
|
322
|
+
end
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
# The hub's sink runs inline in tests; a thread everywhere else.
|
|
326
|
+
def synchronous? = current_rails_env.to_s == "test"
|
|
327
|
+
|
|
328
|
+
def run_safely
|
|
329
|
+
yield
|
|
330
|
+
rescue Exception => e # rubocop:disable Lint/RescueException -- a reporter thread must never take the process down
|
|
331
|
+
raise if e.is_a?(LiveCallAttempted)
|
|
332
|
+
|
|
333
|
+
warn_log("delivery failed: #{e.class}")
|
|
334
|
+
nil
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
# POST the payload, signed. Returns the HTTP status code.
|
|
338
|
+
def deliver(payload, hub_url: Studio.error_alerts_hub_url, token: self.token, now: Time.now)
|
|
339
|
+
body = JSON.generate(payload)
|
|
340
|
+
timestamp = now.to_i.to_s
|
|
341
|
+
uri = URI.join(hub_url.to_s.end_with?("/") ? hub_url.to_s : "#{hub_url}/", PATH.delete_prefix("/"))
|
|
342
|
+
if live_calls_refused? && !LOOPBACK_HOSTS.include?(uri.host.to_s)
|
|
343
|
+
raise LiveCallAttempted, "error alert POST to #{uri.host} while #{NO_LIVE_CALLS_ENV} is armed"
|
|
344
|
+
end
|
|
345
|
+
request = Net::HTTP::Post.new(uri)
|
|
346
|
+
request["Content-Type"] = "application/json"
|
|
347
|
+
request["Accept"] = "application/json"
|
|
348
|
+
request["User-Agent"] = "studio-engine/#{Studio::VERSION} error-alerts"
|
|
349
|
+
request[APP_HEADER] = payload[:app].to_s
|
|
350
|
+
request[TIMESTAMP_HEADER] = timestamp
|
|
351
|
+
request[SIGNATURE_HEADER] = signature(body, timestamp: timestamp, token: token)
|
|
352
|
+
request.body = body
|
|
353
|
+
|
|
354
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
355
|
+
http.use_ssl = uri.scheme == "https"
|
|
356
|
+
http.open_timeout = OPEN_TIMEOUT
|
|
357
|
+
http.read_timeout = READ_TIMEOUT
|
|
358
|
+
http.write_timeout = OPEN_TIMEOUT if http.respond_to?(:write_timeout=)
|
|
359
|
+
http.max_retries = 0
|
|
360
|
+
code = http.request(request).code.to_i
|
|
361
|
+
warn_log("hub answered HTTP #{code}") unless code.between?(200, 299)
|
|
362
|
+
code
|
|
363
|
+
end
|
|
364
|
+
|
|
365
|
+
# Armed by the test helpers, and always in a Rails test environment.
|
|
366
|
+
def live_calls_refused? = ENV[NO_LIVE_CALLS_ENV].present? || current_rails_env.to_s == "test"
|
|
367
|
+
|
|
368
|
+
# ---- signing (the hub verifies with the same code) ----------------------
|
|
369
|
+
|
|
370
|
+
# "v1=<hex>": HMAC-SHA256 over "<timestamp>.<body>" keyed by the token.
|
|
371
|
+
def signature(body, timestamp:, token:)
|
|
372
|
+
"v1=#{OpenSSL::HMAC.hexdigest('SHA256', token.to_s, "#{timestamp}.#{body}")}"
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
# True when `presented` signs `body` at `timestamp` with `token`, and the
|
|
376
|
+
# timestamp is within MAX_SKEW of `now`. Constant-time; false on any blank.
|
|
377
|
+
def verify(body:, timestamp:, presented:, token:, now: Time.now)
|
|
378
|
+
return false if token.to_s.strip.empty? || presented.to_s.empty? || timestamp.to_s !~ /\A\d{1,12}\z/
|
|
379
|
+
return false if (now.to_i - timestamp.to_i).abs > MAX_SKEW
|
|
380
|
+
|
|
381
|
+
expected = signature(body, timestamp: timestamp, token: token.to_s.strip)
|
|
382
|
+
ActiveSupport::SecurityUtils.secure_compare(Digest::SHA256.hexdigest(expected), Digest::SHA256.hexdigest(presented.to_s))
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# ---- the per-process throttle -------------------------------------------
|
|
386
|
+
|
|
387
|
+
# Once per fingerprint per THROTTLE_WINDOW. #admit answers the count to send
|
|
388
|
+
# (1, or 1 plus what was held back since the last send), or nil to hold back.
|
|
389
|
+
class Throttle
|
|
390
|
+
def initialize(window: THROTTLE_WINDOW, max_keys: THROTTLE_MAX_KEYS)
|
|
391
|
+
@window = window
|
|
392
|
+
@max_keys = max_keys
|
|
393
|
+
@seen = {}
|
|
394
|
+
@lock = Mutex.new
|
|
395
|
+
end
|
|
396
|
+
|
|
397
|
+
def admit(key, now = Time.now)
|
|
398
|
+
@lock.synchronize do
|
|
399
|
+
entry = @seen[key]
|
|
400
|
+
if entry && now.to_f - entry[:sent_at] < @window
|
|
401
|
+
entry[:held] += 1
|
|
402
|
+
return nil
|
|
403
|
+
end
|
|
404
|
+
|
|
405
|
+
held = entry ? entry[:held] : 0
|
|
406
|
+
prune(now) if @seen.size >= @max_keys
|
|
407
|
+
@seen[key] = { sent_at: now.to_f, held: 0 }
|
|
408
|
+
held + 1
|
|
409
|
+
end
|
|
410
|
+
end
|
|
411
|
+
|
|
412
|
+
def reset! = @lock.synchronize { @seen.clear }
|
|
413
|
+
|
|
414
|
+
private
|
|
415
|
+
|
|
416
|
+
def prune(now)
|
|
417
|
+
@seen.delete_if { |_, entry| now.to_f - entry[:sent_at] >= @window }
|
|
418
|
+
@seen.shift while @seen.size >= @max_keys
|
|
419
|
+
end
|
|
420
|
+
end
|
|
421
|
+
|
|
422
|
+
def throttle = (@throttle ||= Throttle.new)
|
|
423
|
+
|
|
424
|
+
# ---- helpers ------------------------------------------------------------
|
|
425
|
+
|
|
426
|
+
def qa?
|
|
427
|
+
Studio.respond_to?(:qa_environment?) ? Studio.qa_environment? : %w[1 true].include?(ENV["QA_ENV"].to_s.downcase)
|
|
428
|
+
end
|
|
429
|
+
|
|
430
|
+
def current_rails_env
|
|
431
|
+
defined?(Rails) && Rails.respond_to?(:env) ? Rails.env : ENV.fetch("RAILS_ENV", "development")
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
def warn_log(message)
|
|
435
|
+
logger = defined?(Rails) && Rails.respond_to?(:logger) ? Rails.logger : nil
|
|
436
|
+
logger&.warn("[studio-error-alerts] #{message}")
|
|
437
|
+
end
|
|
438
|
+
end
|
|
439
|
+
end
|
data/lib/studio/health_report.rb
CHANGED
|
@@ -176,8 +176,11 @@ module Studio
|
|
|
176
176
|
# The report as the hub reads it. COUNTS ONLY, by construction: a Section's
|
|
177
177
|
# `items` (names and emails) never reach this hash, so no signup or contact
|
|
178
178
|
# detail leaves the app. Error groups carry the class and the truncated
|
|
179
|
-
# message the email already shows.
|
|
180
|
-
|
|
179
|
+
# message the email already shows. `front_door` (additive,
|
|
180
|
+
# under the same SCHEMA) is what the hub's hourly front-door probe reads:
|
|
181
|
+
# whether mail would reach anyone, and the sign-in page's path. The hub
|
|
182
|
+
# treats a missing key as unknown, so an app on an older engine is never red.
|
|
183
|
+
def payload(report, front_door: self.front_door)
|
|
181
184
|
{
|
|
182
185
|
schema: SCHEMA,
|
|
183
186
|
app: report.app_name.to_s,
|
|
@@ -194,10 +197,29 @@ module Studio
|
|
|
194
197
|
error_groups: Array(report.error_groups).map do |group|
|
|
195
198
|
{ error_class: group.error_class, message: scrub(group.message), count: group.count.to_i,
|
|
196
199
|
first_seen: iso(group.first_seen), last_seen: iso(group.last_seen) }
|
|
197
|
-
end
|
|
200
|
+
end,
|
|
201
|
+
front_door: front_door
|
|
198
202
|
}
|
|
199
203
|
end
|
|
200
204
|
|
|
205
|
+
# { mail_transport: { configured:, transport:, delivery_method: }, login_path: } —
|
|
206
|
+
# either half nil when it cannot be read. Never raises.
|
|
207
|
+
def front_door
|
|
208
|
+
mail = Studio::MailTransport.status if defined?(Studio::MailTransport)
|
|
209
|
+
{ mail_transport: mail, login_path: login_path }
|
|
210
|
+
rescue StandardError
|
|
211
|
+
{ mail_transport: nil, login_path: nil }
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def login_path
|
|
215
|
+
return nil unless defined?(Rails) && Rails.respond_to?(:application) && Rails.application
|
|
216
|
+
|
|
217
|
+
helpers = Rails.application.routes.url_helpers
|
|
218
|
+
helpers.respond_to?(:login_path) ? helpers.login_path : nil
|
|
219
|
+
rescue StandardError
|
|
220
|
+
nil
|
|
221
|
+
end
|
|
222
|
+
|
|
201
223
|
def iso(time) = time&.iso8601
|
|
202
224
|
|
|
203
225
|
EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/
|
|
@@ -4,7 +4,33 @@ module Studio
|
|
|
4
4
|
class MailTransport
|
|
5
5
|
Result = Struct.new(:transport, :delivery_method, :message, keyword_init: true)
|
|
6
6
|
|
|
7
|
+
# What the app's last configure! chose (its initializer runs it at boot), or
|
|
8
|
+
# nil when the app never called it. Read by #status, which the hub's
|
|
9
|
+
# front-door probe sees through GET /_studio/health_report and the boot
|
|
10
|
+
# alert reads in production (Studio::ErrorAlerts).
|
|
11
|
+
NOT_CONFIGURED = "no transactional transport configured"
|
|
12
|
+
LOOPBACK_SMTP_HOSTS = ["", "localhost", "127.0.0.1", "::1"].freeze
|
|
13
|
+
|
|
7
14
|
class << self
|
|
15
|
+
attr_accessor :last_result
|
|
16
|
+
|
|
17
|
+
# { configured:, transport:, delivery_method: } for the running app.
|
|
18
|
+
# `configured` is false when the mail would go nowhere real: configure!
|
|
19
|
+
# chose no transport AND ActionMailer still points at the Rails default
|
|
20
|
+
# SMTP on localhost (every magic link then dies on ECONNREFUSED :25), or
|
|
21
|
+
# the method cannot deliver at all (:test, :file). An app that set its own
|
|
22
|
+
# deliverable method (Postmark, a real SMTP host) counts as configured.
|
|
23
|
+
def status(action_mailer: defined?(ActionMailer) ? ActionMailer::Base : nil, result: last_result)
|
|
24
|
+
method = action_mailer&.delivery_method
|
|
25
|
+
transport = result&.transport
|
|
26
|
+
configured =
|
|
27
|
+
if transport == :resend then true
|
|
28
|
+
elsif method.nil? then false
|
|
29
|
+
else deliverable_method?(method, action_mailer)
|
|
30
|
+
end
|
|
31
|
+
{ configured: configured, transport: (transport || :unknown).to_s, delivery_method: method.to_s }
|
|
32
|
+
end
|
|
33
|
+
|
|
8
34
|
def configure!(env: ENV,
|
|
9
35
|
rails_env: defined?(Rails) && Rails.respond_to?(:env) ? Rails.env : "development",
|
|
10
36
|
action_mailer: defined?(ActionMailer) ? ActionMailer::Base : nil,
|
|
@@ -15,7 +41,8 @@ module Studio
|
|
|
15
41
|
raise ArgumentError, "action_mailer is required" unless action_mailer
|
|
16
42
|
|
|
17
43
|
if rails_env.to_s == "test"
|
|
18
|
-
return Result.new(transport: :test, delivery_method: action_mailer.delivery_method,
|
|
44
|
+
return self.last_result = Result.new(transport: :test, delivery_method: action_mailer.delivery_method,
|
|
45
|
+
message: "test environment skipped")
|
|
19
46
|
end
|
|
20
47
|
|
|
21
48
|
selected = env["MAIL_TRANSPORT"].to_s.downcase
|
|
@@ -35,10 +62,12 @@ module Studio
|
|
|
35
62
|
resend_configurer.call(env["RESEND_API_KEY"])
|
|
36
63
|
action_mailer.delivery_method = :resend
|
|
37
64
|
log(logger, :info, "[mail] transport=Resend from=#{mailer_from}")
|
|
38
|
-
return Result.new(transport: :resend, delivery_method: action_mailer.delivery_method,
|
|
65
|
+
return self.last_result = Result.new(transport: :resend, delivery_method: action_mailer.delivery_method,
|
|
66
|
+
message: "Resend active")
|
|
39
67
|
end
|
|
40
68
|
|
|
41
|
-
Result.new(transport: :default, delivery_method: action_mailer.delivery_method,
|
|
69
|
+
self.last_result = Result.new(transport: :default, delivery_method: action_mailer.delivery_method,
|
|
70
|
+
message: NOT_CONFIGURED)
|
|
42
71
|
end
|
|
43
72
|
|
|
44
73
|
def load_resend!
|
|
@@ -51,6 +80,17 @@ module Studio
|
|
|
51
80
|
|
|
52
81
|
private
|
|
53
82
|
|
|
83
|
+
def deliverable_method?(method, action_mailer)
|
|
84
|
+
case method.to_sym
|
|
85
|
+
when :test, :file then false
|
|
86
|
+
when :smtp
|
|
87
|
+
settings = action_mailer.respond_to?(:smtp_settings) ? action_mailer.smtp_settings.to_h : {}
|
|
88
|
+
address = (settings[:address] || settings["address"] || "localhost").to_s.strip.downcase
|
|
89
|
+
!LOOPBACK_SMTP_HOSTS.include?(address)
|
|
90
|
+
else true
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
54
94
|
def present?(value)
|
|
55
95
|
!value.to_s.strip.empty?
|
|
56
96
|
end
|
data/lib/studio/version.rb
CHANGED
data/lib/studio.rb
CHANGED
|
@@ -58,6 +58,7 @@ require "studio/oauth_identity"
|
|
|
58
58
|
require "studio/google_sign_in"
|
|
59
59
|
require "studio/newsletter"
|
|
60
60
|
require "studio/health_report"
|
|
61
|
+
require "studio/error_alerts"
|
|
61
62
|
require "studio/agent_chat"
|
|
62
63
|
require "studio/username_generator"
|
|
63
64
|
require "studio/public_user"
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: studio-engine
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.146.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Alex McRitchie
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-11-
|
|
11
|
+
date: 2026-11-29 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: rails
|
|
@@ -934,6 +934,7 @@ files:
|
|
|
934
934
|
- lib/studio/email_smoke.rb
|
|
935
935
|
- lib/studio/engine.rb
|
|
936
936
|
- lib/studio/environment_banner.rb
|
|
937
|
+
- lib/studio/error_alerts.rb
|
|
937
938
|
- lib/studio/exceptions_app.rb
|
|
938
939
|
- lib/studio/geo.rb
|
|
939
940
|
- lib/studio/geo/countries.rb
|