closeyourit-ruby 0.12.1 → 0.15.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e8e0fc4eed9289e8fbb3ac2b93e6bcf71c950200b24483be93ca9b03cbb5edf5
4
- data.tar.gz: bec0fc92de3a19b85caa500e41953726a1693ca8f757cd98022b8b5287e83f76
3
+ metadata.gz: 68859964e58c268009b7b74d1fde2008673a72bdb74b21dfd7e15359de4e20ce
4
+ data.tar.gz: 75870b53dc3311d3550edd626c024c0de2204a3a5c3855d3bb15e66eb5105267
5
5
  SHA512:
6
- metadata.gz: f39ecd3584260bf7257fb8efc7fcf12222a2adec2fa2d1ba7ff3a59e368ae6c6e52921d5c83dda516c588946d718c4407aa934d6f495cfd9269621226fd58555
7
- data.tar.gz: a634e8af76d32b12d1ffe210e73d3070c8059d15a55953caed9406d2c8db7fbeaac0f34bf800ee049bf9b4cdcb737d0239f3968978b970bb1175f42dfca3f0c5
6
+ metadata.gz: 4907e87c67aae231c5472fb9d4841729e0a2319db617f32b4a8844bfc810ca89d884143bbb37563e394d0cef9bc9f4189eede432f77ceff8eb1c3a5a5e6c3a7c
7
+ data.tar.gz: bb30d89bd74fb767742e777ab439e9e674eb1833c317635e505002c4cb6710ab77ac85eaa87c7058e218aa1328ab979fb15c84ae6705804f4b1630c5f6ff1ffd
data/README.md CHANGED
@@ -62,6 +62,10 @@ end
62
62
  **Senza `endpoint_url` / `token` / `project_id` la gemma è no-op** (nessun invio, nessun overhead). In
63
63
  `production` un `endpoint_url` `http://` viene rifiutato (no-op + warning): il token viaggerebbe in chiaro.
64
64
 
65
+ In **`development` e `test` la gemma non invia niente** (`disabled_environments`), e gli errori dei
66
+ comandi lanciati a mano non partono mai: vedi [Comandi lanciati a mano e ambienti
67
+ locali](#comandi-lanciati-a-mano-e-ambienti-locali).
68
+
65
69
  > **Endpoint:** usa l'host canonico **`https://app.closeyour.it`**. Le installazioni già configurate su
66
70
  > `https://www.closeyour.it` continuano a funzionare: l'ingest su `www` resta inoltrato all'app.
67
71
 
@@ -74,7 +78,8 @@ end
74
78
  | `project_id` | `ENV["CLOSEYOURIT_PROJECT_ID"]` | UUID progetto (nel path di ingest) |
75
79
  | `release` | `ENV["CLOSEYOURIT_RELEASE"]` | Versione riportata negli errori (opzionale) |
76
80
  | `environment` | `Rails.env` / `RACK_ENV` / `"development"` | Ambiente riportato negli eventi |
77
- | `excluded_exceptions` | `RoutingError`, `RecordNotFound` | Eccezioni da NON inviare — **String** (nome classe) o **Regexp** (match su nome/messaggio) |
81
+ | `disabled_environments` | `development`, `test` | Ambienti che **non inviano niente**: in locale le credenziali sono quelle dell'app in produzione (vedi [Comandi lanciati a mano e ambienti locali](#comandi-lanciati-a-mano-e-ambienti-locali)) |
82
+ | `excluded_exceptions` | `RoutingError`, `RecordNotFound` + i rifiuti delle richieste malformate (vedi [Rifiuti delle richieste malformate](#rifiuti-delle-richieste-malformate)) | Eccezioni da NON inviare — **String** (nome classe) o **Regexp** (match su nome/messaggio) |
78
83
  | `before_send` | `nil` | `->(payload) { ... }` — scrub finale; ritorna payload o `nil` per scartare |
79
84
  | `sample_rate` | `1.0` | Frazione di errori/messaggi inviata (`1.0` tutto, `0.0` niente) |
80
85
  | `async_threads` | `cpu/2` | Thread di invio; `0` = sincrono (test) |
@@ -91,6 +96,7 @@ end
91
96
  | `max_breadcrumbs` | `100` | Dimensione max del ring buffer breadcrumbs |
92
97
  | `capture_handled_errors` | `true` | Cattura gli errori riportati via `Rails.error.report` |
93
98
  | `report_active_job_errors` | `true` | Cattura gli errori dei job ActiveJob/Solid Queue/Sidekiq |
99
+ | `capture_console_errors` | `false` | Cattura anche gli errori dei comandi lanciati a mano (`rails console`, `rails runner`); i lavori programmati sono monitorati comunque (vedi [Comandi lanciati a mano e ambienti locali](#comandi-lanciati-a-mano-e-ambienti-locali)) |
94
100
  | `send_pii` | `false` | Master switch PII |
95
101
  | `obfuscate_sql` | `true` | Maschera i literal nello SQL |
96
102
  | `filter_parameters` | `[]` | Chiavi extra da redarre, in aggiunta a `Rails.application.config.filter_parameters` (unite automaticamente dalla Railtie) |
@@ -152,6 +158,45 @@ rescue => e
152
158
  end
153
159
  ```
154
160
 
161
+ #### Rifiuti delle richieste malformate
162
+
163
+ Alcune eccezioni sono la **risposta corretta** a una richiesta sbagliata o truccata: l'app che le
164
+ solleva sta funzionando, non si sta rompendo. Sono escluse **di default** — erano migliaia di eventi
165
+ su quasi ogni app:
166
+
167
+ | Eccezione | Richiesta che la provoca |
168
+ |---|---|
169
+ | `ActionController::RoutingError` | path inesistente (favicon, scansioni dei bot) |
170
+ | `ActiveRecord::RecordNotFound` | id inesistente nell'URL |
171
+ | `ActionDispatch::RemoteIp::IpSpoofAttackError` | `X-Forwarded-For` e `Client-IP` in contrasto |
172
+ | `ActionController::InvalidAuthenticityToken` | token CSRF mancante o scaduto |
173
+ | `ActionController::UnknownFormat` | formato che l'app non rende (sonde `.php`, `.env`) |
174
+ | `ActionController::BadRequest` | query string o parametri del body malformati |
175
+ | `ActionDispatch::Http::MimeNegotiation::InvalidType` | header `Accept`/`Content-Type` non valido |
176
+
177
+ Restano nei **log dell'app**: è lì che si guarda quando uno di questi rifiuti è un difetto vero del
178
+ frontend (un `Accept` sbagliato, un form che perde il token). Per rivederli tra gli errori si toglie
179
+ la classe dalla lista:
180
+
181
+ ```ruby
182
+ config.excluded_exceptions -= [ "ActionController::UnknownFormat" ]
183
+ ```
184
+
185
+ Il match percorre gli **antenati**: una sottoclasse sollevata dall'app è coperta anch'essa.
186
+
187
+ #### Comandi lanciati a mano e ambienti locali
188
+
189
+ Altre due sorgenti non sono difetti dell'app, e di default **non vengono inviate**:
190
+
191
+ | Cosa non parte | Perché | Come riaccenderla |
192
+ |---|---|---|
193
+ | gli errori di `rails console` e `rails runner` (script, codice inline o letto da `-`) | lo sbaglio è di chi ha scritto il comando: erano 36 gruppi chiusi a mano in un giorno (culprit `p28.rb`, `np.rb`, `stdin`) | `c.capture_console_errors = true` |
194
+ | tutto, negli ambienti `development` e `test` | in locale le credenziali sono quelle dell'app in produzione: un lavoro a metà o una migration pendente finivano tra i suoi errori | `c.disabled_environments = []` |
195
+
196
+ **I lavori programmati restano monitorati**: rake task, job (ActiveJob/Solid Queue/Sidekiq) e server
197
+ web non fanno parte della famiglia "comando lanciato a mano". Se però un `rails runner` è davvero
198
+ schedulato (cron), i suoi errori arrivano solo con `capture_console_errors = true`.
199
+
155
200
  ### Request context (automatico, con Rails)
156
201
 
157
202
  Un Rack middleware allega a ogni evento il contesto HTTP della richiesta: **method**, **url** (senza
@@ -213,7 +258,8 @@ Il broadcast rispetta anche **`excluded_exceptions`**: se la riga nomina una cla
213
258
  inoltrata. Serve perché un'eccezione tolta dal canale errori rientrava da quello dei log — Rails la
214
259
  registra comunque con `logger.error`. Con le esclusioni di default questo copre già
215
260
  `ActionController::RoutingError`, cioè le favicon mancanti e le scansioni dei bot, che in produzione
216
- sono la voce di gran lunga più numerosa dello stream. Per il rumore ripetuto che **non** è
261
+ sono la voce di gran lunga più numerosa dello stream, e gli altri
262
+ [rifiuti delle richieste malformate](#rifiuti-delle-richieste-malformate). Per il rumore ripetuto che **non** è
217
263
  un'eccezione c'è `excluded_log_patterns`:
218
264
 
219
265
  ```ruby
@@ -401,6 +447,40 @@ ActiveJob dentro Sidekiq è osservato una sola volta quando il subscriber Active
401
447
  Sampling, disabilitazione o perdita del transport impediscono di considerare questi log un censimento.
402
448
  Il raggruppamento backend v1 separa framework, nome, coda e misura; i gruppi legacy restano intatti.
403
449
 
450
+ ## Open Dashboard (opt-in)
451
+
452
+ Il servizio mostra i suoi numeri (utenti, abbonamenti, incassi…) a chi ha la chiave, su
453
+ `GET /open-dashboard`. Lo standard completo: contratto `contracts/open-dashboard/v1`.
454
+
455
+ ```ruby
456
+ # config/initializers/open_dashboard.rb
457
+ CloseYourIt::OpenDashboard.configure do |od|
458
+ od.token = ENV["OPEN_DASHBOARD_TOKEN"] # without it the route does not exist
459
+ od.name = "scontino"
460
+ od.app = "scontino-rails"
461
+ od.url = "https://scontino.it"
462
+ od.locale = "it"
463
+
464
+ od.metric "users.registered", label: "Utenti registrati", group: "Utenti", type: :count do |since|
465
+ { value: User.count, previous: User.where(created_at: ...since).count }
466
+ end
467
+
468
+ od.metric "revenue.mrr", label: "Incasso mensile ricorrente", group: "Incassi",
469
+ type: :money, currency: "EUR" do
470
+ Subscription.active.sum(:amount_cents)
471
+ end
472
+ end
473
+ ```
474
+
475
+ - `since` è l'inizio del periodo di confronto (`period:`, default `"30d"`; anche `1d`, `7d`, `90d`, `365d`).
476
+ - Il blocco restituisce un numero, oppure `{ value:, previous: }`.
477
+ - Tipi: `count` e `money` (interi; `money` in centesimi con `currency`), `percent` (0–100), `duration` (secondi).
478
+ - `better: :down` per i numeri che vanno bene quando scendono.
479
+ - Una metrica che solleva arriva come «non disponibile» e l'errore finisce in CloseYourIt; le altre restano.
480
+ - I blocchi girano a ogni richiesta e chi legge aspetta al massimo 10 secondi: i numeri lenti vanno precalcolati.
481
+ - Una dichiarazione sbagliata (chiave doppia, tipo sconosciuto, `money` senza valuta) blocca l'avvio.
482
+ - Solo totali: mai dati di singole persone.
483
+
404
484
  ## Privacy & PII
405
485
 
406
486
  Privacy-by-default (`send_pii = false`). In sintesi:
@@ -7,14 +7,43 @@ module CloseYourIt
7
7
  # Holds all client options. Built by `CloseYourIt.init { |c| ... }`.
8
8
  # Without `endpoint_url`/`token`/`project_id` (or with `http://` in production) the client is a no-op.
9
9
  class Configuration
10
+ # 4xx answers to requests that are malformed or forged at the source: bot scans, spoofed
11
+ # X-Forwarded-For, stale CSRF tokens, `.php`/`.env` probes asking for a format the app does not
12
+ # render, bodies that are not the declared content type. The app rejecting them is the app working,
13
+ # not failing, so they are noise in the error channel: on 2026-11-10 they were thousands of events
14
+ # spread over nearly every app (IpSpoof 1,495, UnknownFormat 390+, CSRF 263). Excluded by DEFAULT
15
+ # so the list is not repeated in every initializer (CYRB-46).
16
+ #
17
+ # They stay in the app's own Rails log, which is where to look when one of them is a real
18
+ # frontend defect (a wrong `Accept`, a form that lost its token): whoever wants them back among
19
+ # the errors takes the class off this list (`config.excluded_exceptions -= [...]`).
20
+ #
21
+ # Matching walks the ancestors (see CloseYourIt.ignored_exception?), so a subclass raised by the
22
+ # host app is covered too.
10
23
  DEFAULT_EXCLUDED_EXCEPTIONS = %w[
11
24
  ActionController::RoutingError
12
25
  ActiveRecord::RecordNotFound
26
+ ActionDispatch::RemoteIp::IpSpoofAttackError
27
+ ActionController::InvalidAuthenticityToken
28
+ ActionController::UnknownFormat
29
+ ActionController::BadRequest
30
+ ActionDispatch::Http::MimeNegotiation::InvalidType
13
31
  ].freeze
14
32
 
15
33
  # HTTP headers captured in the request context (never Authorization/Cookie → no PII/secrets).
16
34
  DEFAULT_REQUEST_HEADER_ALLOWLIST = %w[Accept Content-Type User-Agent Referer].freeze
17
35
 
36
+ # Environments that send NOTHING. A local run normally shares the credentials of the deployed app
37
+ # (same `.env`, same project_id), so a half-written feature or a pending migration on the
38
+ # developer's machine was filed as an error of the live app: on 2026-11-10, 11 groups closed by
39
+ # hand on a single app came from a laptop (`ActiveRecord::PendingMigrationError`, 74 events).
40
+ # Silent by DEFAULT because the opposite default costs a manual cleanup every day (CYRB-47).
41
+ #
42
+ # The list is a denylist, not an allowlist: an app with its own environment name (`staging`,
43
+ # `preproduction`) keeps sending without touching the configuration. Whoever wants the laptop's
44
+ # events back empties it (`config.disabled_environments = []`).
45
+ DEFAULT_DISABLED_ENVIRONMENTS = %w[development test].freeze
46
+
18
47
  # Solid stack service tables: they are framework infrastructure, not application code. A slow
19
48
  # query on them cannot be fixed by reading your own repo — it only says the database is under
20
49
  # contention, which the app's queries already show. Excluded by DEFAULT from slowdown measurement
@@ -34,7 +63,7 @@ module CloseYourIt
34
63
  :capture_request, :request_header_allowlist, :context_lines,
35
64
  :capture_request_body,
36
65
  :breadcrumbs_enabled, :max_breadcrumbs, :sample_rate,
37
- :capture_handled_errors, :report_active_job_errors,
66
+ :capture_handled_errors, :report_active_job_errors, :capture_console_errors,
38
67
  :logs_enabled, :logs_sample_rate, :logs_batch_size, :logs_flush_interval,
39
68
  :capture_rails_logs, :logs_min_level, :capture_rails_logs_min_level,
40
69
  :detect_performance_issues, :n_plus_one_threshold, :query_count_threshold,
@@ -45,7 +74,8 @@ module CloseYourIt
45
74
  :usage_enabled, :usage_flush_interval, :usage_max_symbols
46
75
  attr_writer :release, :project_root
47
76
  attr_reader :excluded_exceptions, :excluded_log_patterns, :excluded_query_patterns,
48
- :filter_parameters, :scrub_message_patterns, :trace_propagation_allowlist
77
+ :filter_parameters, :scrub_message_patterns, :trace_propagation_allowlist,
78
+ :disabled_environments
49
79
 
50
80
  def initialize
51
81
  @endpoint_url = ENV.fetch("CLOSEYOURIT_ENDPOINT_URL", nil)
@@ -54,8 +84,9 @@ module CloseYourIt
54
84
  @release = ENV.fetch("CLOSEYOURIT_RELEASE", nil)
55
85
  @environment = ENV.fetch("CLOSEYOURIT_ENVIRONMENT") { detect_environment }
56
86
 
57
- @excluded_exceptions = DEFAULT_EXCLUDED_EXCEPTIONS.dup
58
- @before_send = nil
87
+ @excluded_exceptions = DEFAULT_EXCLUDED_EXCEPTIONS.dup
88
+ @disabled_environments = DEFAULT_DISABLED_ENVIRONMENTS.dup
89
+ @before_send = nil
59
90
 
60
91
  # Opt-in diagnostic hook: `->(event, details) { ... }` called at every stage of an event's
61
92
  # lifecycle (:enqueue, :send, :drop, :timeout, :shutdown) with details free of sensitive data
@@ -109,6 +140,11 @@ module CloseYourIt
109
140
  @capture_handled_errors = true
110
141
  @report_active_job_errors = true
111
142
 
143
+ # Errors of the commands a person types by hand (`rails console`, `rails runner`): default OFF,
144
+ # they are the typist's mistake, not the app's (see ConsoleSession, CYRB-47). Scheduled work
145
+ # (rake, jobs) is unaffected. Turn it on to also watch what a hand-run script does.
146
+ @capture_console_errors = false
147
+
112
148
  # Captures parameter values — opt-in, default OFF (privacy). Binds/arguments may contain PII.
113
149
  @capture_query_bindings = false
114
150
  @capture_method_arguments = false
@@ -185,6 +221,12 @@ module CloseYourIt
185
221
  @excluded_exceptions = Array(list).map { |item| item.is_a?(Regexp) ? item : item.to_s }
186
222
  end
187
223
 
224
+ # Environment names → String, so `[:development]` and `["development"]` behave the same (the
225
+ # environment is compared as text).
226
+ def disabled_environments=(list)
227
+ @disabled_environments = Array(list).map(&:to_s)
228
+ end
229
+
188
230
  # Rails.logger broadcast patterns to drop. Strings become Regexps (literal match on the text):
189
231
  # whoever writes `config.excluded_log_patterns = ["Rendered layout"]` means exactly that.
190
232
  def excluded_log_patterns=(list)
@@ -222,11 +264,13 @@ module CloseYourIt
222
264
  environment.to_s == "production"
223
265
  end
224
266
 
225
- # The client sends only with complete credentials (endpoint + token + project_id) and a secure
226
- # transport (http:// allowed outside production).
267
+ # The client sends only with complete credentials (endpoint + token + project_id), a secure
268
+ # transport (http:// allowed outside production) and from an environment that is not local
269
+ # (`disabled_environments`, default development + test — CYRB-47).
227
270
  def enabled?
228
271
  return false if blank?(endpoint_url) || blank?(token) || blank?(project_id)
229
272
  return false if insecure_endpoint? && production?
273
+ return false if disabled_environment?
230
274
 
231
275
  true
232
276
  end
@@ -312,6 +356,10 @@ module CloseYourIt
312
356
  !uri.nil? && uri.scheme != "https"
313
357
  end
314
358
 
359
+ def disabled_environment?
360
+ disabled_environments.include?(environment.to_s)
361
+ end
362
+
315
363
  # Warns when project_id is set but does not look like a UUID (the typical mistake is pasting a
316
364
  # slug/name instead of the id). It does not block: the server is the authority on validity.
317
365
  def malformed_project_id?
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloseYourIt
4
+ # Tells whether this process is a one-off command typed by a person: `rails console` and
5
+ # `rails runner` (a script, inline code or code piped to `-`). Their mistakes belong to whoever
6
+ # typed them, not to the application, and they were the single biggest source of errors closed by
7
+ # hand: 36 groups in one day with culprits `p28.rb`, `np.rb`, `stdin`, `rails in <main>` — e.g.
8
+ # `NameError: uninitialized constant Project` (CYRB-47).
9
+ #
10
+ # Detection reads the command class Rails loaded to run the process. `Rails::Command.invoke`
11
+ # requires ONLY the file of the command being run (`lookup`, one glob per namespace), so the
12
+ # constant exists exactly when that command is driving the process. The whole-catalogue require
13
+ # (`lookup!`) happens only to print the help, where there is no app to report errors for.
14
+ #
15
+ # Deliberately NOT in this family: `rake`, `bin/jobs`/Solid Queue, Sidekiq, the web server. That
16
+ # work is scheduled, nobody is watching the terminal, and its errors must keep arriving.
17
+ module ConsoleSession
18
+ # Rails command classes that mean "a person is driving this process".
19
+ COMMAND_CLASSES = %w[
20
+ Rails::Command::ConsoleCommand
21
+ Rails::Command::RunnerCommand
22
+ ].freeze
23
+
24
+ class << self
25
+ def active?
26
+ COMMAND_CLASSES.any? { |name| Object.const_defined?(name) }
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloseYourIt
4
+ module OpenDashboard
5
+ # Raised at boot when the service declares a metric the standard does not allow.
6
+ class ConfigurationError < StandardError; end
7
+
8
+ # One metric of the Open Dashboard standard. Rules are checked when the service boots, so a bad
9
+ # declaration fails the deploy instead of producing an invalid response in production.
10
+ class Metric
11
+ TYPES = %w[count money percent duration].freeze
12
+ INTEGER_TYPES = %w[count money].freeze
13
+ PERIODS = { "1d" => 1, "7d" => 7, "30d" => 30, "90d" => 90, "365d" => 365 }.freeze
14
+ BETTER = %w[up down].freeze
15
+ KEY_FORMAT = /\A[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+\z/
16
+ CURRENCY_FORMAT = /\A[A-Z]{3}\z/
17
+ UNAVAILABLE = "unavailable"
18
+ SECONDS_PER_DAY = 86_400
19
+
20
+ attr_reader :key
21
+
22
+ def initialize(key, label:, group:, type:, currency: nil, period: "30d", better: nil, &block)
23
+ @key = key.to_s
24
+ @label = label.to_s
25
+ @group = group.to_s
26
+ @type = type.to_s
27
+ @currency = currency
28
+ @period = period.to_s
29
+ @better = better&.to_s
30
+ @block = block
31
+ validate!
32
+ end
33
+
34
+ # The block gets the start of the comparison period. A failure never breaks the other metrics:
35
+ # it is reported to CloseYourIt and the metric goes out as unavailable.
36
+ def to_h(now)
37
+ since = now - (PERIODS.fetch(@period) * SECONDS_PER_DAY)
38
+ identity.merge(values(@block.call(since)))
39
+ rescue StandardError => e
40
+ CloseYourIt.capture_exception(e, handled: true)
41
+ identity.merge(value: nil, error: UNAVAILABLE)
42
+ end
43
+
44
+ private
45
+
46
+ def identity
47
+ { key: @key, label: @label, group: @group, type: @type, currency: @currency, better: @better }.compact
48
+ end
49
+
50
+ def values(result)
51
+ return { value: number(result) } unless result.is_a?(Hash)
52
+
53
+ out = { value: number(result.fetch(:value)) }
54
+ out.merge!(previous: number(result[:previous]), period: @period) unless result[:previous].nil?
55
+ out
56
+ end
57
+
58
+ # Returns the value to emit: an Integer for count/money, a Float for percent/duration.
59
+ def number(value)
60
+ reject("value must be numeric") unless value.is_a?(Numeric)
61
+ reject("value must be finite") unless !value.respond_to?(:finite?) || value.finite?
62
+
63
+ normalised = INTEGER_TYPES.include?(@type) ? whole(value) : Float(value)
64
+ check_range(normalised)
65
+ normalised
66
+ end
67
+
68
+ def whole(value)
69
+ reject("#{@type} must be an integer") unless value == value.to_i
70
+
71
+ value.to_i
72
+ end
73
+
74
+ def check_range(value)
75
+ reject("count must not be negative") if @type == "count" && value.negative?
76
+ reject("percent must be between 0 and 100") if @type == "percent" && !value.between?(0, 100)
77
+ reject("duration must not be negative") if @type == "duration" && value.negative?
78
+ end
79
+
80
+ def reject(message)
81
+ raise TypeError, "open_dashboard metric #{@key}: #{message}"
82
+ end
83
+
84
+ def validate!
85
+ fail_with("key must be lowercase and dotted, e.g. users.registered") unless KEY_FORMAT.match?(@key)
86
+ fail_with("label is blank") if @label.strip.empty?
87
+ fail_with("group is blank") if @group.strip.empty?
88
+ fail_with("type must be one of #{TYPES.join(', ')}") unless TYPES.include?(@type)
89
+ validate_currency!
90
+ fail_with("period must be one of #{PERIODS.keys.join(', ')}") unless PERIODS.key?(@period)
91
+ fail_with("better must be up or down") if @better && !BETTER.include?(@better)
92
+ fail_with("a block computing the value is required") unless @block
93
+ end
94
+
95
+ def validate_currency!
96
+ if @type == "money"
97
+ fail_with("money needs an ISO 4217 currency, e.g. EUR") unless CURRENCY_FORMAT.match?(@currency.to_s)
98
+ elsif @currency
99
+ fail_with("currency is allowed only on money")
100
+ end
101
+ end
102
+
103
+ def fail_with(message)
104
+ raise ConfigurationError, "open_dashboard metric #{@key}: #{message}"
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require "openssl"
6
+
7
+ module CloseYourIt
8
+ module OpenDashboard
9
+ # Pure Rack: answers GET /open-dashboard and passes everything else to the app. Without a token
10
+ # the request also goes to the app, so the route simply does not exist (404 from the app).
11
+ class Middleware
12
+ JSON_HEADERS = { "content-type" => "application/json", "cache-control" => "no-store" }.freeze
13
+ BEARER = "Bearer "
14
+
15
+ def initialize(app)
16
+ @app = app
17
+ end
18
+
19
+ def call(env)
20
+ settings = OpenDashboard.settings
21
+ return @app.call(env) unless dashboard_request?(env) && settings&.enabled?
22
+ return [ 401, { "cache-control" => "no-store" }, [] ] unless authorized?(env["HTTP_AUTHORIZATION"], settings.token)
23
+
24
+ [ 200, JSON_HEADERS.dup, [ JSON.generate(Report.new(settings).to_h) ] ]
25
+ end
26
+
27
+ private
28
+
29
+ def dashboard_request?(env)
30
+ env["REQUEST_METHOD"] == "GET" && env["PATH_INFO"] == PATH
31
+ end
32
+
33
+ # Hashing both sides gives equal lengths, so the comparison time does not leak the token length.
34
+ def authorized?(header, token)
35
+ header = header.to_s
36
+ return false unless header.start_with?(BEARER)
37
+
38
+ OpenSSL.fixed_length_secure_compare(
39
+ Digest::SHA256.digest(header.delete_prefix(BEARER)),
40
+ Digest::SHA256.digest(token.to_s)
41
+ )
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module CloseYourIt
6
+ module OpenDashboard
7
+ # Builds the response body. Service identity comes from the same ENV as GET /version, so the
8
+ # dashboard and the deploy smoke test always agree on which build is live.
9
+ class Report
10
+ UNKNOWN = "unknown"
11
+
12
+ def initialize(settings, now: Time.now.utc)
13
+ @settings = settings
14
+ @now = now
15
+ end
16
+
17
+ def to_h
18
+ {
19
+ open_dashboard: SPEC_VERSION,
20
+ service: service,
21
+ locale: @settings.locale,
22
+ generated_at: @now.getutc.iso8601,
23
+ metrics: @settings.metrics.map { |metric| metric.to_h(@now) }
24
+ }
25
+ end
26
+
27
+ private
28
+
29
+ def service
30
+ {
31
+ name: @settings.name,
32
+ app: @settings.app,
33
+ version: present(ENV["APP_GIT_TAG"]) || UNKNOWN,
34
+ sha: present(ENV["APP_GIT_SHA"])&.slice(0, 7) || UNKNOWN,
35
+ environment: CloseYourIt.configuration.environment.to_s,
36
+ url: present(@settings.url)
37
+ }.compact
38
+ end
39
+
40
+ def present(value)
41
+ value.to_s.strip.empty? ? nil : value.to_s
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloseYourIt
4
+ module OpenDashboard
5
+ # What the service declares in config/initializers/open_dashboard.rb.
6
+ class Settings
7
+ LOCALE_FORMAT = /\A[a-z]{2}(-[A-Z]{2})?\z/
8
+
9
+ attr_accessor :token, :name, :app, :url, :locale
10
+ attr_reader :metrics
11
+
12
+ def initialize
13
+ @metrics = []
14
+ end
15
+
16
+ def metric(key, **options, &block)
17
+ if @metrics.any? { |existing| existing.key == key.to_s }
18
+ raise ConfigurationError, "open_dashboard metric #{key}: duplicated key"
19
+ end
20
+
21
+ @metrics << Metric.new(key, **options, &block)
22
+ end
23
+
24
+ # No token means the feature is off: the route does not exist.
25
+ def enabled? = !token.to_s.strip.empty?
26
+
27
+ def validate!
28
+ %i[name app].each do |field|
29
+ raise ConfigurationError, "open_dashboard: #{field} is required" if public_send(field).to_s.strip.empty?
30
+ end
31
+ raise ConfigurationError, "open_dashboard: locale must look like it or en-US" unless LOCALE_FORMAT.match?(locale.to_s)
32
+ raise ConfigurationError, "open_dashboard: at most #{MAX_METRICS} metrics" if @metrics.size > MAX_METRICS
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloseYourIt
4
+ # Open Dashboard standard: GET /open-dashboard returns who the service is and its business
5
+ # numbers, behind a per-service token. Contract: contracts/open-dashboard/v1.
6
+ module OpenDashboard
7
+ SPEC_VERSION = "1.0"
8
+ PATH = "/open-dashboard"
9
+ MAX_METRICS = 50
10
+
11
+ class << self
12
+ # Kept separate from CloseYourIt.init: init rebuilds its configuration on every call, and the
13
+ # dashboard declaration must not disappear when telemetry is reconfigured.
14
+ def configure
15
+ candidate = Settings.new
16
+ yield candidate
17
+ candidate.validate!
18
+ @settings = candidate
19
+ end
20
+
21
+ attr_reader :settings
22
+
23
+ def reset!
24
+ @settings = nil
25
+ end
26
+ end
27
+ end
28
+ end
29
+
30
+ require_relative "open_dashboard/metric"
31
+ require_relative "open_dashboard/settings"
32
+ require_relative "open_dashboard/report"
33
+ require_relative "open_dashboard/middleware"
@@ -28,6 +28,16 @@ module CloseYourIt
28
28
  )
29
29
  end
30
30
 
31
+ # Open Dashboard (GET /open-dashboard). Inside CaptureExceptions, so a crash while building the
32
+ # report is reported like any other request error. Inert until the app calls
33
+ # CloseYourIt::OpenDashboard.configure with a token.
34
+ initializer "closeyourit.open_dashboard" do |app|
35
+ app.config.middleware.insert_after(
36
+ CloseYourIt::Rails::CaptureExceptions,
37
+ CloseYourIt::OpenDashboard::Middleware
38
+ )
39
+ end
40
+
31
41
  initializer "closeyourit.subscribe_slow_queries" do
32
42
  subscriber = CloseYourIt::Subscribers::SlowQuery.new
33
43
 
@@ -12,7 +12,8 @@ module CloseYourIt
12
12
  OPEN_TIMEOUT = 2
13
13
  READ_TIMEOUT = 3
14
14
  # Net::HTTP does not follow redirects: the canonical host may answer 301 (e.g. apex → www).
15
- # We re-POST to Location keeping method + body, so the event is not silently lost.
15
+ # We re-POST to Location keeping method + body, so the event is not silently lost — but only while
16
+ # Location stays on the configured endpoint's authority (see #same_authority?).
16
17
  MAX_REDIRECTS = 2
17
18
 
18
19
  # Maximum duration of ONE send_event: open + read, repeated for every followed redirect. It is the
@@ -64,25 +65,39 @@ module CloseYourIt
64
65
  redirects = 0
65
66
 
66
67
  loop do
67
- response = post_once(uri, body, authorize: same_authority?(origin, uri))
68
+ response = post_once(uri, body)
68
69
  location = response["location"] if response.is_a?(Net::HTTPRedirection)
69
70
  return response unless location && redirects < MAX_REDIRECTS
70
71
 
72
+ target = redirect_uri(uri, location)
73
+ # The payload is as sensitive as the Bearer (stack traces, tags, request data): a redirect off
74
+ # the configured endpoint's authority is not followed at all (CYRB-31). The redirect response
75
+ # is returned, so send_event counts it as failed like any other non-2xx.
76
+ return refuse_redirect(response, target, path) unless same_authority?(origin, target)
77
+
71
78
  redirects += 1
72
- uri = redirect_uri(uri, location)
79
+ uri = target
73
80
  end
74
81
  end
75
82
 
76
- def post_once(uri, body, authorize:)
83
+ def refuse_redirect(response, target, path)
84
+ CloseYourIt.internal_logger.warn(
85
+ "CloseYourIt transport: redirect to #{target.scheme}://#{target.host}:#{target.port} on #{path} " \
86
+ "refused: it leaves the configured endpoint (other host, other port or https→http). " \
87
+ "Set endpoint_url to the final address."
88
+ )
89
+ response
90
+ end
91
+
92
+ def post_once(uri, body)
77
93
  http = Net::HTTP.new(uri.host, uri.port)
78
94
  http.use_ssl = uri.scheme == "https"
79
95
  http.open_timeout = OPEN_TIMEOUT
80
96
  http.read_timeout = READ_TIMEOUT
81
97
 
82
98
  request = Net::HTTP::Post.new(uri.request_uri)
83
- # The Bearer is an ingest secret: do not resend it after a redirect to a different host
84
- # (or an https→http downgrade), so it is never handed to an untrusted endpoint.
85
- request["Authorization"] = "Bearer #{@configuration.token}" if authorize
99
+ # Only reached on the configured endpoint's authority (see #post): the Bearer always goes.
100
+ request["Authorization"] = "Bearer #{@configuration.token}"
86
101
  request["Content-Type"] = "application/json"
87
102
  request["User-Agent"] = "closeyourit-ruby/#{VERSION}"
88
103
  request.body = body
@@ -96,10 +111,10 @@ module CloseYourIt
96
111
  target.relative? ? current + target : target
97
112
  end
98
113
 
99
- # The Bearer is resent only if the redirect stays on the configured endpoint's authority:
114
+ # A redirect is followed (body + Bearer) only if it stays on the configured endpoint's authority:
100
115
  # same host (or its www variant), same effective port and no https→http downgrade.
101
116
  # The port is part of the trust boundary (CYRB-22): on the same server a different port is a
102
- # separate service, which must not receive the ingest secret.
117
+ # separate service, which must receive neither the ingest secret nor the payload (CYRB-31).
103
118
  def same_authority?(origin, target)
104
119
  return false if origin.scheme == "https" && target.scheme != "https"
105
120
  return false unless canonical_host(origin) == canonical_host(target)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CloseYourIt
4
- VERSION = "0.12.1"
4
+ VERSION = "0.15.0"
5
5
  end
@@ -4,6 +4,7 @@ require "logger"
4
4
 
5
5
  require_relative "closeyourit/version"
6
6
  require_relative "closeyourit/configuration"
7
+ require_relative "closeyourit/console_session"
7
8
  require_relative "closeyourit/breadcrumb"
8
9
  require_relative "closeyourit/trace_context"
9
10
  require_relative "closeyourit/scope"
@@ -39,6 +40,7 @@ require_relative "closeyourit/rails/active_job_extension"
39
40
  require_relative "closeyourit/rails/error_subscriber"
40
41
  require_relative "closeyourit/sidekiq/error_handler"
41
42
  require_relative "closeyourit/sidekiq/job_metrics_middleware"
43
+ require_relative "closeyourit/open_dashboard"
42
44
 
43
45
  # CloseYourIt — telemetry client (errors + slow query/method statistics)
44
46
  # that sends events to the CloseYourIt ingest endpoint.
@@ -91,11 +93,12 @@ module CloseYourIt
91
93
  configuration.enabled?
92
94
  end
93
95
 
94
- # Captures an exception and sends it (fire-and-forget). No-op when disabled,
95
- # or when the exception is excluded or already captured.
96
+ # Captures an exception and sends it (fire-and-forget). No-op when disabled, in a hand-typed
97
+ # command, or when the exception is excluded or already captured.
96
98
  def capture_exception(exception, handled: false, level: "error", contexts: nil)
97
99
  return nil if in_diagnostic?
98
100
  return nil unless enabled?
101
+ return nil if console_error?
99
102
  return nil if ignored_exception?(exception)
100
103
  return nil if exception_captured?(exception)
101
104
 
@@ -446,6 +449,14 @@ module CloseYourIt
446
449
  internal_logger.warn("CloseYourIt: SIGTERM trap not installed (#{e.class}: #{e.message})")
447
450
  end
448
451
 
452
+ # True when the exception comes from a command typed by hand (`rails console`, `rails runner`)
453
+ # and the app has not asked to watch those: a typo at the keyboard is not an app failure, and it
454
+ # was the top source of errors closed by hand (CYRB-47). Scheduled work (rake, jobs) is never in
455
+ # this family, so its errors keep arriving. Checked on the error path only → cost irrelevant.
456
+ def console_error?
457
+ !configuration.capture_console_errors && ConsoleSession.active?
458
+ end
459
+
449
460
  def ignored_exception?(exception)
450
461
  return true if exception.is_a?(CloseYourIt::Error)
451
462
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: closeyourit-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.12.1
4
+ version: 0.15.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alessio Bussolari
@@ -53,6 +53,7 @@ files:
53
53
  - lib/closeyourit/breadcrumb_buffer.rb
54
54
  - lib/closeyourit/client.rb
55
55
  - lib/closeyourit/configuration.rb
56
+ - lib/closeyourit/console_session.rb
56
57
  - lib/closeyourit/event.rb
57
58
  - lib/closeyourit/events/error_event.rb
58
59
  - lib/closeyourit/events/job_metric_event.rb
@@ -67,6 +68,11 @@ files:
67
68
  - lib/closeyourit/log_buffer.rb
68
69
  - lib/closeyourit/log_device.rb
69
70
  - lib/closeyourit/monitor.rb
71
+ - lib/closeyourit/open_dashboard.rb
72
+ - lib/closeyourit/open_dashboard/metric.rb
73
+ - lib/closeyourit/open_dashboard/middleware.rb
74
+ - lib/closeyourit/open_dashboard/report.rb
75
+ - lib/closeyourit/open_dashboard/settings.rb
70
76
  - lib/closeyourit/performance/request_profile.rb
71
77
  - lib/closeyourit/performance/rollup.rb
72
78
  - lib/closeyourit/rails/active_job_extension.rb