sitegoose 0.3.3 → 0.3.4

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.
@@ -21,10 +21,27 @@ module SiteGoose
21
21
  COUNTER_MAX = 100_000
22
22
  # The layers this server runs (X-Firewall-Layers): the address firewall and the browser check.
23
23
  LAYERS = "app check"
24
- # Files a page load asks for by the dozen: not counted against `rate`
25
- # (the agent's nginx limit leaves the same extensions out).
26
- STATIC = /\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|bmp|woff2?|ttf|otf|eot|mp4|webm|ogg|mp3|wav|pdf|wasm)\z/i.freeze
24
+ # Files a page load asks for by the dozen: not counted against `rate` or
25
+ # the page limits (the agent's nginx limit leaves the same extensions
26
+ # out). The extension follows a name in the last segment, not starts it:
27
+ # "/login/.css" is no file. Matched on the lower-cased path.
28
+ STATIC = %r{/[^/.][^/]*\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|bmp|woff2?|ttf|otf|eot|mp4|webm|ogg|mp3|wav|pdf|wasm)\z}.freeze
27
29
  STATIC_PREFIXES = %w[/assets/ /packs/ /vite/ /static/ /_next/static/].freeze
30
+ # In a path decoded once: a "%xx" still there (double encoding, which a
31
+ # router that decodes again reads differently), a ";" (a path parameter
32
+ # to some servers and proxies, part of the name to others), a "\\" (a
33
+ # "/" to some), a "?" or "#" that was encoded, or a control character.
34
+ STATIC_UNSURE = /%[0-9a-fA-F]{2}|[;\\?#\x00-\x1f\x7f]/.freeze
35
+ # Only GET and HEAD fetch a file: a form posts to a page. No method given reads as GET.
36
+ FETCHES = ["", "GET", "HEAD"].freeze
37
+ # Rails' own controllers for uploaded files: an image on a page is a
38
+ # request to them (and a redirect from them), 40 on a product list.
39
+ FILE_CONTROLLERS = %r{\A(?:active_storage|action_text)/}.freeze
40
+ # Page limits (firewall.md, "Page limits"): at most this many, ids as a request rule's.
41
+ MAX_LIMITS = 50
42
+ LIMIT_ID = /\A[a-z][a-z0-9_.-]{1,39}\z/.freeze
43
+ # What a visitor over a blocking page limit reads, with its 429.
44
+ LIMIT_BODY = "Too many requests to this page. Please wait a little and try again."
28
45
 
29
46
  attr_reader :pass_key, :queue, :bans
30
47
  attr_accessor :rules, :etag
@@ -43,9 +60,32 @@ module SiteGoose
43
60
  { exact: exact, prefix: prefix, ban: ban }
44
61
  end
45
62
 
46
- # Read from the path the router sees, so "/admin;x.css" isn't one.
47
- def self.static?(target)
48
- path = RequestRules.normalize_target(target)
63
+ # A file a page loads with itself, by its extension or its folder
64
+ # (firewall.md, `rate`), read from the target as sent decoded once, as
65
+ # the router reads PATH_INFO, lower case, "//" as "/". Only a path every
66
+ # router reads the same way can be a file: one with a "." or ".."
67
+ # segment, a ";", a "\\", an encoded "/" or a "%xx" left after decoding
68
+ # is a page, so "/static/../login", "/static%2F..%2Flogin",
69
+ # "/login;x.css" and "/login%3Bx.css" all count. A browser asks for its
70
+ # files with none of those. Nor is a path past the rules' 2,000
71
+ # characters: cut there, "/search/xxx...x.css/more" would end in .css and
72
+ # flood a catch-all route past the limits.
73
+ def self.static?(target, method = "")
74
+ return false unless FETCHES.include?(method.to_s)
75
+
76
+ raw = target.to_s.split(/[?#]/, 2).first.to_s
77
+ return false if raw.length > RequestRules::MAX_TEXT || !raw.start_with?("/") || raw.match?(/%2f/i)
78
+
79
+ decoded = RequestRules.decode_once(raw)
80
+ return false if decoded.match?(STATIC_UNSURE)
81
+
82
+ # A-Z only, as every package: "İ" is "i" lower-cased by some.
83
+ segments = decoded.tr("A-Z", "a-z").split("/", -1)
84
+ return false if segments.include?(".") || segments.include?("..")
85
+
86
+ parts = segments.reject(&:empty?)
87
+ path = "/#{parts.join('/')}"
88
+ path += "/" if !parts.empty? && segments.last.empty? # "/app.css/" isn't a file
49
89
  STATIC_PREFIXES.any? { |prefix| path.start_with?(prefix) } || path.match?(STATIC)
50
90
  end
51
91
 
@@ -78,6 +118,42 @@ module SiteGoose
78
118
  end
79
119
  end
80
120
 
121
+ # The rules' page limits -> {exempt:, rules:}, or nil when there are none.
122
+ # A limit that doesn't parse is left out, not the others: a bad id, a
123
+ # limit outside 1-100,000, a window outside 1-3,600 seconds, or nothing to
124
+ # match on. Sections are matched as a request rule's, without `regex`, so
125
+ # the agent's nginx can carry the same limit; a section with a regex only
126
+ # is no section.
127
+ def self.compile_limits(data)
128
+ return nil unless data.is_a?(Hash) && data["rules"].is_a?(Array)
129
+
130
+ rules = data["rules"].first(MAX_LIMITS).filter_map do |rule|
131
+ next unless rule.is_a?(Hash) && rule["id"].is_a?(String) && rule["id"].match?(LIMIT_ID)
132
+
133
+ limit = rule["limit"]
134
+ window = rule["window"]
135
+ next unless limit.is_a?(Integer) && limit.between?(1, 100_000) && window.is_a?(Integer) && window.between?(1, 3600)
136
+
137
+ methods = rule["methods"]
138
+ compiled = {
139
+ "id" => rule["id"],
140
+ "action" => rule["action"] == "block" ? "block" : "monitor",
141
+ "limit" => limit,
142
+ "window" => window,
143
+ "each" => rule["each"] == "path",
144
+ "methods" => methods.is_a?(Array) ? methods.select { |m| m.is_a?(String) }.map(&:upcase) : []
145
+ }
146
+ %w[path query].each do |name|
147
+ part = rule[name].is_a?(Hash) ? RequestRules.section(rule[name].except("regex")) : nil
148
+ compiled[name] = part if part
149
+ end
150
+ compiled if compiled["path"] || compiled["query"]
151
+ end
152
+ return nil if rules.empty?
153
+
154
+ { exempt: IpSet.new(Array(data["exempt"])), rules: rules }
155
+ end
156
+
81
157
  # The rules' browser check -> {skip:, exempt:}, or nil when the site isn't to be checked.
82
158
  def self.compile_challenge(data)
83
159
  return nil unless data.is_a?(Hash)
@@ -107,6 +183,16 @@ module SiteGoose
107
183
  @etag = ""
108
184
  @lock = Mutex.new
109
185
  @counts = {}
186
+ # Page limits: "id window who" -> [window start, hits]. Limits with
187
+ # each: "path" ("id window who path") count in a table of their own:
188
+ # one entry per address and page fills a table fast, and making room
189
+ # there mustn't start the login limit's counts again mid-window.
190
+ @limit_counts = {}
191
+ @path_counts = {}
192
+ # With a shared counter: the counts this process saw go over (their
193
+ # key, window and all), so a static file asked for after them can be
194
+ # turned away without adding to them (check, `peek`).
195
+ @over_noted = {}
110
196
  @queue = {}
111
197
  # Bot protection here: address -> when its ban ends; address -> [window start, failed logins].
112
198
  @bans = {}
@@ -162,6 +248,8 @@ module SiteGoose
162
248
  probes: Firewall.compile_probes(data["probes"]),
163
249
  # Virtual patching: rules that match the request, not the address.
164
250
  requests: RequestRules.compile(data["requests"]),
251
+ # Page limits: caps on one kind of request (absent in older rules).
252
+ limits: Firewall.compile_limits(data["limits"]),
165
253
  # The browser check: present only when the site is to be checked.
166
254
  challenge: Firewall.compile_challenge(data["challenge"])
167
255
  }
@@ -197,11 +285,19 @@ module SiteGoose
197
285
  @core.log("firewall", "rules not kept in the cache file:", e.message)
198
286
  end
199
287
 
200
- def over_rate?(ip, rate)
288
+ # peek: only compared with the count so far, nothing added (a static file).
289
+ def over_rate?(ip, rate, peek: false)
201
290
  who = Firewall.who(ip)
202
291
  window = (Time.now.to_f / rate[:window]).floor
203
292
  if @counter
204
- return @counter.call("afw:#{@core.site_id}:#{who}:#{window}", rate[:window] * 2).to_i > rate[:limit]
293
+ name = "afw:#{@core.site_id}:#{who}:#{window}"
294
+ return @over_noted.key?(name) if peek
295
+
296
+ return note_over(name, @counter.call(name, rate[:window] * 2).to_i > rate[:limit])
297
+ end
298
+ if peek
299
+ entry = @counts[who]
300
+ return !entry.nil? && entry[0] == window && entry[1] > rate[:limit]
205
301
  end
206
302
 
207
303
  @lock.synchronize do
@@ -219,6 +315,62 @@ module SiteGoose
219
315
  end
220
316
  end
221
317
 
318
+ # Counts the request toward every page limit it matches (firewall.md,
319
+ # step 6) and returns those now over their count, in the order sent.
320
+ # Every matching limit counts, not just the first, so one that is over
321
+ # can't hide the requests another one should see. A fixed window per
322
+ # limit, as `rate`; `each: "path"` keeps a count per page (the routed
323
+ # path), which stays here: one key per page in a shared counter would
324
+ # be as many keys as a crawler can make up.
325
+ # peek: as over_rate?'s.
326
+ def over_limits(ip, limits, req, peek: false)
327
+ who = Firewall.who(ip)
328
+ now = Time.now.to_f
329
+ limits.select do |limit|
330
+ next false unless RequestRules.matches?(limit, req)
331
+
332
+ window = (now / limit["window"]).floor
333
+ if @counter && !limit["each"]
334
+ name = "afw:#{@core.site_id}:l:#{limit['id']}:#{who}:#{window}"
335
+ next @over_noted.key?(name) if peek
336
+
337
+ next note_over(name, @counter.call(name, limit["window"] * 2).to_i > limit["limit"])
338
+ end
339
+
340
+ key = "#{limit['id']} #{limit['window']} #{who}#{limit['each'] ? " #{req[:routed_path]}" : ''}"
341
+ table = limit["each"] ? @path_counts : @limit_counts
342
+ if peek
343
+ entry = table[key]
344
+ next !entry.nil? && entry[0] == window && entry[1] > limit["limit"]
345
+ end
346
+
347
+ @lock.synchronize do
348
+ entry = table[key]
349
+ if entry.nil? || entry[0] != window
350
+ # Oldest first, as the rate counters: a full table loses the counts that went quiet longest ago.
351
+ table.delete(key)
352
+ Firewall.make_room(table)
353
+ entry = [window, 0]
354
+ table[key] = entry
355
+ end
356
+ entry[1] += 1
357
+ entry[1] > limit["limit"]
358
+ end
359
+ end
360
+ end
361
+
362
+ # A shared count seen over: noted under its key (window and all, so an
363
+ # old one never matches again), for a static file's peek. -> over.
364
+ def note_over(name, over)
365
+ if over
366
+ @lock.synchronize do
367
+ Firewall.make_room(@over_noted) unless @over_noted.key?(name)
368
+ @over_noted[name] = true
369
+ end
370
+ end
371
+ over
372
+ end
373
+
222
374
  # A table of addresses at COUNTER_MAX loses its oldest entries (insertion
223
375
  # order), not everyone's count at once.
224
376
  def self.make_room(table)
@@ -313,14 +465,20 @@ module SiteGoose
313
465
 
314
466
  ip = ip.to_s
315
467
  action = (@mode || rules[:mode]) == "block" ? "block" : "monitor"
468
+ event = lambda do |name, act|
469
+ { "ip" => ip, "rule" => name, "action" => act, "method" => SiteGoose.text(method, 10),
470
+ "path" => SiteGoose.text(path).split("?", 2)[0].to_s[0, 300], "user_agent" => SiteGoose.text(user_agent, 300) }
471
+ end
316
472
  rule = address_rule(rules, key, ip)
317
473
  if rule.empty? && Firewall.probe?(path, rules[:probes])
318
474
  rule = "probe"
319
475
  # Asking for a secret file: banned here in block mode; the report bans it on the other servers.
320
476
  ban_here(ip, rules[:probes][:ban]) if action == "block"
321
477
  end
478
+ limits = rules[:limits]
479
+ req = RequestRules.prepare(method, path, user_agent) if rule.empty? && (!rules[:requests].empty? || limits)
322
480
  if rule.empty?
323
- matched = RequestRules.match(rules[:requests], method, path, user_agent)
481
+ matched = RequestRules.match(rules[:requests], method, path, user_agent, req)
324
482
  if matched
325
483
  rule = "request:#{matched['id']}"
326
484
  # A rule the dashboard only watches passes even in block mode; one
@@ -329,27 +487,103 @@ module SiteGoose
329
487
  ban_here(ip, matched["ban"]) if action == "block" && matched["ban"].positive?
330
488
  end
331
489
  end
332
- if rule.empty? && rules[:rate] && !rules[:goodbots].has?(key) && !Firewall.static?(path) && over_rate?(ip, rules[:rate])
490
+ # A static file isn't counted toward the page limits or `rate`, only
491
+ # compared with the counts so far: an address already over them is
492
+ # turned away for its files too. It is counted after the response if
493
+ # the app routed it to a page after all (Rails reads /login.css as the
494
+ # login action, format css) or it answered an error (count_static).
495
+ static = Firewall.static?(path, method)
496
+ goodbot = rules[:goodbots].has?(key)
497
+ late_rate = false
498
+ late_limits = false
499
+ # Page limits (step 6). Never banned: a shopper who refreshes checkout
500
+ # too often is a customer, and the cap lifts when the window ends.
501
+ watched = nil
502
+ limit_window = nil
503
+ if rule.empty? && limits && !goodbot && !limits[:exempt].has?(key)
504
+ late_limits = static
505
+ over = over_limits(ip, limits[:rules], req, peek: static)
506
+ blocking = action == "block" ? over.find { |limit| limit["action"] == "block" } : nil
507
+ if blocking
508
+ rule = "limit:#{blocking['id']}"
509
+ limit_window = blocking["window"]
510
+ else
511
+ # Only watched: reported, and the check goes on to `rate`, so
512
+ # watching the login page doesn't let a flood through it untouched.
513
+ watched = over.first
514
+ end
515
+ end
516
+ late_rate = static if rule.empty? && rules[:rate] && !goodbot
517
+ if rule.empty? && rules[:rate] && !goodbot && over_rate?(ip, rules[:rate], peek: static)
333
518
  rule = "rate"
334
519
  # Banned here straight away in block mode, as a probe is; the report bans it on the other servers.
335
520
  ban_here(ip, rules[:ban]) if action == "block"
336
521
  end
337
- event = lambda do |name, act|
338
- { "ip" => ip, "rule" => name, "action" => act, "method" => SiteGoose.text(method, 10),
339
- "path" => SiteGoose.text(path).split("?", 2)[0].to_s[0, 300], "user_agent" => SiteGoose.text(user_agent, 300) }
522
+ if watched
523
+ if rule.empty?
524
+ rule = "limit:#{watched['id']}"
525
+ action = "monitor"
526
+ limit_window = watched["window"]
527
+ else
528
+ # `rate` decides; the watched limit is reported as well.
529
+ report(event.call("limit:#{watched['id']}", "monitor"))
530
+ end
340
531
  end
341
532
  # Not a mode matter: the collector only sends `challenge` when the site
342
533
  # is to be checked, and a match only watched (monitor) gets it too
343
- # (firewall.md, step 7).
534
+ # (firewall.md, step 8).
344
535
  if (rule.empty? || action != "block") && needs_check?(rules, key, ip, method, path, accept, cookie, now)
345
536
  report(event.call(rule, action)) unless rule.empty?
346
537
  rule = "challenge"
347
538
  action = "block"
539
+ limit_window = nil
348
540
  end
349
- return allow if rule.empty?
541
+ decision = if rule.empty?
542
+ allow
543
+ else
544
+ report(event.call(rule, action))
545
+ if limit_window
546
+ # retry_after: the limit's own window, which the 429 carries.
547
+ { action: action, rule: rule, status: 429, retry_after: limit_window }
548
+ else
549
+ { action: action, rule: rule, status: rule == "rate" ? 429 : (rule == "challenge" ? 503 : 403) }
550
+ end
551
+ end
552
+ # What count_static needs after the response of a static file that went on to the app.
553
+ if (late_rate || late_limits) && decision[:action] != "block"
554
+ decision[:static] = { ip: ip, rate: late_rate, req: late_limits ? req : nil }
555
+ end
556
+ decision
557
+ end
558
+
559
+ # After the response to a static file check() let through (its
560
+ # decision's :static): counted toward `rate` and the page limits it
561
+ # skipped when the app routed it to a page after all, or it answered an
562
+ # error (>= 400), so neither "/login.css" on Rails nor a flood of
563
+ # made-up file names that each boot the app gets past them. env: the
564
+ # Rack env, where Rails leaves the route it took.
565
+ def count_static(hit, status, env = nil)
566
+ return unless hit && (status.to_i >= 400 || Firewall.routed?(env))
567
+
568
+ rules = @rules
569
+ return unless rules
570
+
571
+ over_rate?(hit[:ip], rules[:rate]) if hit[:rate] && rules[:rate]
572
+ over_limits(hit[:ip], rules[:limits][:rules], hit[:req]) if hit[:req] && rules[:limits]
573
+ nil
574
+ end
350
575
 
351
- report(event.call(rule, action))
352
- { action: action, rule: rule, status: rule == "rate" ? 429 : (rule == "challenge" ? 503 : 403) }
576
+ # Whether Rails' router sent the request to a controller action: it
577
+ # leaves the action's path parameters in the env. A file
578
+ # ActionDispatch::Static, Propshaft or a mounted app served has none,
579
+ # and Active Storage's own controllers serve files (each image on a page
580
+ # is a request to one, and with the disk service a second).
581
+ def self.routed?(env)
582
+ params = env.is_a?(Hash) ? env["action_dispatch.request.path_parameters"] : nil
583
+ return false unless params.is_a?(Hash)
584
+
585
+ controller = params[:controller] || params["controller"]
586
+ !controller.nil? && !controller.to_s.match?(FILE_CONTROLLERS)
353
587
  end
354
588
 
355
589
  # The rules about the address alone (deny, bans, lists, shared): "" when none.
@@ -383,7 +617,7 @@ module SiteGoose
383
617
  { action: action, rule: rule, status: 403 }
384
618
  end
385
619
 
386
- # Step 7: the browser check is on, the request asks for a page outside
620
+ # Step 8: the browser check is on, the request asks for a page outside
387
621
  # skip, the address is in none of allow (already passed), goodbots and
388
622
  # exempt, and it has no valid pass.
389
623
  def needs_check?(rules, key, ip, method, path, accept, cookie, now)
@@ -53,6 +53,7 @@ module SiteGoose
53
53
  @rows = {}
54
54
  @lock = Mutex.new
55
55
  @job = core.valid? ? Periodic.new(FLUSH_EVERY) { flush(everything: false); FLUSH_EVERY } : nil
56
+ reset_inflight
56
57
  Forking.register(self)
57
58
  end
58
59
 
@@ -60,6 +61,43 @@ module SiteGoose
60
61
  def after_fork_in_child
61
62
  @lock = Mutex.new
62
63
  @rows = {}
64
+ reset_inflight
65
+ end
66
+
67
+ # Requests in progress now, and the most at once since the resources
68
+ # module last asked (resources.md, "Limits": inflight_peak). Nothing is
69
+ # known until the middleware first runs, so an app without it reports no
70
+ # peak rather than 0.
71
+ def reset_inflight
72
+ @inflight_lock = Mutex.new
73
+ @inflight = 0
74
+ @peak = 0
75
+ @timed = false
76
+ end
77
+ private :reset_inflight
78
+
79
+ def enter
80
+ @inflight_lock.synchronize do
81
+ @timed = true
82
+ @inflight += 1
83
+ @peak = @inflight if @inflight > @peak
84
+ end
85
+ end
86
+
87
+ def leave
88
+ @inflight_lock.synchronize { @inflight -= 1 if @inflight.positive? }
89
+ end
90
+
91
+ # The peak since the last call (nil before any request); it starts again
92
+ # from what is still in progress.
93
+ def take_inflight_peak
94
+ @inflight_lock.synchronize do
95
+ next nil unless @timed
96
+
97
+ most = @peak
98
+ @peak = @inflight
99
+ most
100
+ end
63
101
  end
64
102
 
65
103
  # One finished request. route: the framework's pattern, or "" to work it
@@ -15,10 +15,11 @@ module SiteGoose
15
15
  # collector's URL); trust_proxy (how to find the visitor's address: nil
16
16
  # uses the connection's, a number of proxies in X-Forwarded-For,
17
17
  # "cloudflare"); debug (print send problems); server_name (this
18
- # service's name); queries (false: Server speed without the database
19
- # queries); per module true / false / {options}.
18
+ # service's name); queries, calls, queues (false: Server speed without
19
+ # the database queries, the outgoing calls, the job queues); per module
20
+ # true / false / {options}.
20
21
  def initialize(site_id: nil, secret: nil, endpoint: nil, trust_proxy: nil, debug: false, server_name: nil,
21
- logger: nil, queries: true, **modules)
22
+ logger: nil, queries: true, calls: true, queues: true, **modules)
22
23
  unknown = modules.keys.map(&:to_s) - MODULES
23
24
  warn "[analytics-platform] unknown options ignored: #{unknown.join(', ')}" unless unknown.empty?
24
25
  @core = Core.new(site_id, secret, endpoint, debug: debug, server_name: server_name, logger: logger)
@@ -46,20 +47,31 @@ module SiteGoose
46
47
  warn "[analytics-platform] the #{name} module could not start and is off: #{e.message}"
47
48
  end
48
49
  end
49
- @queries = nil
50
+ @queries = @calls = @queues = nil
50
51
  performance = @modules["performance"]
51
- if performance && queries != false
52
- begin
53
- @queries = Queries.new(@core, server_name: performance.server_name)
54
- rescue StandardError, ScriptError => e
55
- warn "[analytics-platform] database queries could not start and are off: #{e.message}"
56
- end
52
+ if performance
53
+ @queries = part("database queries", queries) { Queries.new(@core, server_name: performance.server_name) }
54
+ @calls = part("outgoing calls", calls) { Calls.new(@core, server_name: performance.server_name) }
55
+ @queues = part("job queues", queues) { Queues.new(@core, server_name: performance.server_name) }
57
56
  end
57
+ # The most requests in progress at once, beside the machine's figures.
58
+ @modules["resources"]&.use_inflight(performance && -> { performance.take_inflight_peak })
58
59
  @core.start(@modules.keys)
59
60
  @closed = false
60
61
  SiteGoose.created(self)
61
62
  end
62
63
 
64
+ # One of Server speed's parts, unless switched off with false.
65
+ def part(what, setting)
66
+ return nil if setting == false
67
+
68
+ yield
69
+ rescue StandardError, ScriptError => e
70
+ warn "[analytics-platform] #{what} could not start and are off: #{e.message}"
71
+ nil
72
+ end
73
+ private :part
74
+
63
75
  def load(name, opts)
64
76
  case name
65
77
  when "firewall" then Firewall.new(@core, **opts)
@@ -100,9 +112,9 @@ module SiteGoose
100
112
  @modules["errors"]
101
113
  end
102
114
 
103
- # The database queries Server speed records (nil with queries: false or
104
- # performance off).
105
- attr_reader :queries
115
+ # The database queries, outgoing calls and job queues Server speed
116
+ # records (each nil when switched off with false, or performance off).
117
+ attr_reader :queries, :calls, :queues
106
118
 
107
119
  # The first-party proxy: proxy.script_url and proxy.collect_url are the
108
120
  # two addresses the page's script tag needs, on this site's own domain.
@@ -276,7 +288,10 @@ module SiteGoose
276
288
  def time_request(method, route, status, started, path = "")
277
289
  performance = @modules["performance"]
278
290
  recorded = performance&.record(method, route, status, (SiteGoose.clock - started) * 1000, path)
279
- @queries&.finish(*recorded) if recorded
291
+ if recorded
292
+ @queries&.finish(*recorded)
293
+ @calls&.finish(*recorded)
294
+ end
280
295
  rescue StandardError => e
281
296
  @core.log("performance", "could not time a request:", e.message)
282
297
  end
@@ -321,7 +336,7 @@ module SiteGoose
321
336
 
322
337
  # Sends everything waiting (serverless, a job runner: before returning).
323
338
  def flush
324
- [*@modules.values, @queries].compact.each do |mod|
339
+ [*@modules.values, @queries, @calls, @queues].compact.each do |mod|
325
340
  mod.flush
326
341
  rescue StandardError
327
342
  nil
@@ -335,7 +350,7 @@ module SiteGoose
335
350
 
336
351
  @closed = true
337
352
  @core.stop
338
- [*@modules.values, @queries].compact.each do |mod|
353
+ [*@modules.values, @queries, @calls, @queues].compact.each do |mod|
339
354
  mod.close
340
355
  rescue StandardError
341
356
  nil
@@ -351,8 +366,10 @@ module SiteGoose
351
366
 
352
367
  # [status, headers, body] when the firewall turns the request away, else
353
368
  # nil. headers: a hash with lowercase names. target: the request target
354
- # as sent, query string and all (SiteGoose.request_target).
355
- def blocked(remote, headers, method, target)
369
+ # as sent, query string and all (SiteGoose.request_target). late: a hash
370
+ # given :static when the request is a static file let through, for
371
+ # Firewall#count_static after the response.
372
+ def blocked(remote, headers, method, target, late = nil)
356
373
  fw = firewall
357
374
  return nil unless fw
358
375
 
@@ -361,6 +378,8 @@ module SiteGoose
361
378
  decision = fw.check(ip, method, target, SiteGoose.header(headers, "user-agent"),
362
379
  SiteGoose.header(headers, "accept"), SiteGoose.header(headers, "cookie"))
363
380
  return fw.challenge_page(ip, method) if decision[:action] == "block" && decision[:rule] == "challenge"
381
+
382
+ late[:static] = decision[:static] if late && decision[:static]
364
383
  rescue StandardError => e
365
384
  @core.log("firewall", "check failed, request passed:", e.message)
366
385
  return nil
@@ -369,8 +388,9 @@ module SiteGoose
369
388
 
370
389
  extra = { "content-type" => "text/plain; charset=utf-8", "cache-control" => "no-store" }
371
390
  if decision[:status] == 429
372
- extra["retry-after"] = fw.retry_after
373
- return [429, extra, "Too Many Requests"]
391
+ # A page limit waits out its own window, not the site-wide one.
392
+ extra["retry-after"] = (decision[:retry_after] || fw.retry_after).to_s
393
+ return [429, extra, decision[:rule].start_with?("limit:") ? Firewall::LIMIT_BODY : "Too Many Requests"]
374
394
  end
375
395
  [403, extra, "Forbidden"]
376
396
  end
@@ -392,7 +412,8 @@ module SiteGoose
392
412
  return SiteGoose.rack_response(answered, method) if answered
393
413
 
394
414
  ip = nil
395
- refused = blocked(remote, headers, method, SiteGoose.request_target(env))
415
+ late = {}
416
+ refused = blocked(remote, headers, method, SiteGoose.request_target(env), late)
396
417
  if refused
397
418
  ip = firewall ? firewall.client_ip(remote, headers) : remote
398
419
  # A crawler the firewall turned away is still a crawler, and counted
@@ -407,6 +428,10 @@ module SiteGoose
407
428
  fields = -> { SiteGoose.request_fields(env, method, path) }
408
429
  status = 500
409
430
  response = nil
431
+ performance = @modules["performance"]
432
+ resources = @modules["resources"]
433
+ resources.see_server unless resources.nil? || resources.server_seen?
434
+ performance&.enter
410
435
  Context.with(fields) do
411
436
  response = yield
412
437
  status = response[0].to_i
@@ -421,6 +446,12 @@ module SiteGoose
421
446
  end
422
447
  raise
423
448
  ensure
449
+ begin
450
+ # A static file the app routed to a page, or that answered an error, counts after all.
451
+ firewall&.count_static(late[:static], status, env) if late[:static]
452
+ rescue StandardError
453
+ nil
454
+ end
424
455
  begin
425
456
  route = SiteGoose.route_of(env, path)
426
457
  time_request(method, route, status, started, path)
@@ -429,6 +460,7 @@ module SiteGoose
429
460
  rescue StandardError
430
461
  nil
431
462
  end
463
+ performance&.leave
432
464
  end
433
465
  SiteGoose.add_headers(response, security_headers(SiteGoose.header_names(response[1])), remember)
434
466
  end