devfortress-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +4 -0
  3. data/Gemfile +7 -0
  4. data/LICENSE +63 -0
  5. data/README.md +121 -0
  6. data/Rakefile +11 -0
  7. data/lib/devfortress/agent_adapter.rb +185 -0
  8. data/lib/devfortress/agent_loop_detector.rb +167 -0
  9. data/lib/devfortress/agent_output_exfiltration_detector.rb +115 -0
  10. data/lib/devfortress/agent_security.rb +431 -0
  11. data/lib/devfortress/alias_verify.rb +87 -0
  12. data/lib/devfortress/api_key_aliasing.rb +240 -0
  13. data/lib/devfortress/bounded_map.rb +80 -0
  14. data/lib/devfortress/circuit_breaker.rb +149 -0
  15. data/lib/devfortress/classifier.rb +133 -0
  16. data/lib/devfortress/client.rb +380 -0
  17. data/lib/devfortress/client_ip.rb +28 -0
  18. data/lib/devfortress/clock_drift_detector.rb +71 -0
  19. data/lib/devfortress/credential_isolation.rb +340 -0
  20. data/lib/devfortress/credential_vault.rb +93 -0
  21. data/lib/devfortress/delivery_result.rb +9 -0
  22. data/lib/devfortress/graduated_rate_limiter.rb +270 -0
  23. data/lib/devfortress/internal_closed_loop_engine.rb +658 -0
  24. data/lib/devfortress/license_manager.rb +297 -0
  25. data/lib/devfortress/observer.rb +62 -0
  26. data/lib/devfortress/prompt_injection_filter.rb +73 -0
  27. data/lib/devfortress/response_webhook_client.rb +165 -0
  28. data/lib/devfortress/shadow_agent_registry.rb +123 -0
  29. data/lib/devfortress/signer.rb +134 -0
  30. data/lib/devfortress/telemetry.rb +407 -0
  31. data/lib/devfortress/tier_gate.rb +294 -0
  32. data/lib/devfortress/tool_call_sequence_validator.rb +126 -0
  33. data/lib/devfortress/transport.rb +31 -0
  34. data/lib/devfortress/unified_audit_trail.rb +213 -0
  35. data/lib/devfortress/version.rb +5 -0
  36. data/lib/devfortress/webhook_verification.rb +9 -0
  37. data/lib/devfortress/webhook_verifier.rb +93 -0
  38. data/lib/devfortress.rb +96 -0
  39. metadata +110 -0
@@ -0,0 +1,240 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "securerandom"
5
+ require_relative "credential_vault"
6
+
7
+ module DevFortress
8
+ # API Key Aliasing Service (Invention A19).
9
+ # Patent Pending — KIPI KE/P/2026/005972
10
+ # Prior art: https://www.tdcommons.org/dpubs_series/9907/
11
+ #
12
+ # Mirrors packages/devfortress-sdk/src/api-key-aliasing.ts. Provides
13
+ # alias lifecycle management for API keys: create, rotate, revoke,
14
+ # inspect, and audit. Each alias is scoped to a workload (CI, agent,
15
+ # browser, server) with fingerprint and scope binding.
16
+ AliasRecord = Struct.new(
17
+ :alias_id, :alias_key, :primary_key_hash, :workload, :label, :state,
18
+ :fingerprint, :scope, :created_at, :expires_at, :last_used_at,
19
+ :rotated_from_id, :rotated_to_id, :usage_count, keyword_init: true,
20
+ )
21
+
22
+ AliasAuditEvent = Struct.new(:type, :alias_id, :primary_key_hash, :workload, :timestamp, :metadata, keyword_init: true)
23
+
24
+ WORKLOADS = %w[ci agent plugin browser server custom].freeze
25
+
26
+ class APIKeyAliasingService
27
+ def initialize(max_aliases_per_key: 50, rotation_overlap_ms: 300_000, max_primary_keys: 10_000,
28
+ anomaly_detection: true, creation_burst_threshold: 10, vault_secret: nil, debug: false)
29
+ @max_aliases_per_key = max_aliases_per_key
30
+ @rotation_overlap_ms = rotation_overlap_ms
31
+ @max_primary_keys = max_primary_keys
32
+ @anomaly_detection = anomaly_detection
33
+ @creation_burst_threshold = creation_burst_threshold
34
+ @debug = debug
35
+
36
+ @aliases = {}
37
+ @alias_key_index = {}
38
+ @primary_key_aliases = {}
39
+ @audit_log = []
40
+ @creation_timestamps = []
41
+
42
+ @vault_key = vault_secret ? CredentialVault.derive_vault_key(vault_secret, "api-key-aliasing") : SecureRandom.random_bytes(32)
43
+ end
44
+
45
+ # Create a new alias for a primary API key.
46
+ def create_alias(primary_key_hash, workload, label, fingerprint: nil, scope: nil, expires_in_ms: nil)
47
+ now = now_ms
48
+
49
+ existing = @primary_key_aliases[primary_key_hash]
50
+ if existing && existing.size >= @max_aliases_per_key
51
+ return { success: false, error: "Maximum aliases (#{@max_aliases_per_key}) reached for this key" }
52
+ end
53
+
54
+ if @anomaly_detection
55
+ @creation_timestamps << now
56
+ recent_creations = @creation_timestamps.select { |t| now - t <= 3_600_000 }
57
+ if recent_creations.length > @creation_burst_threshold
58
+ emit_audit(type: "alias_misuse_detected", alias_id: "N/A", primary_key_hash: primary_key_hash,
59
+ workload: workload, timestamp: now, metadata: { reason: "creation_burst", count: recent_creations.length })
60
+ return { success: false, error: "Alias creation burst detected: #{recent_creations.length} in 1 hour" }
61
+ end
62
+ end
63
+
64
+ alias_id = "alias_#{SecureRandom.hex(16)}"
65
+ alias_key = "vx_alias_#{SecureRandom.hex(24)}"
66
+ alias_key_hash = Digest::SHA256.hexdigest(alias_key)
67
+
68
+ record = AliasRecord.new(
69
+ alias_id: alias_id, alias_key: encrypt_alias_key(alias_key, primary_key_hash),
70
+ primary_key_hash: primary_key_hash, workload: workload, label: label, state: "active",
71
+ fingerprint: fingerprint, scope: scope, created_at: now,
72
+ expires_at: expires_in_ms ? now + expires_in_ms : nil, last_used_at: now, usage_count: 0,
73
+ )
74
+
75
+ @aliases[alias_id] = record
76
+ @alias_key_index[alias_key_hash] = alias_id
77
+ (@primary_key_aliases[primary_key_hash] ||= []) << alias_id
78
+
79
+ emit_audit(type: "alias_created", alias_id: alias_id, primary_key_hash: primary_key_hash, workload: workload,
80
+ timestamp: now, metadata: { label: label, has_fingerprint: !fingerprint.nil?, scope: scope })
81
+
82
+ redacted = record.dup
83
+ redacted.alias_key = "[REDACTED]"
84
+ { success: true, alias: redacted, alias_key: alias_key }
85
+ end
86
+
87
+ # Rotate an alias with zero-downtime overlap window.
88
+ def rotate_alias(alias_id)
89
+ now = now_ms
90
+ old_alias = @aliases[alias_id]
91
+ return { success: false, error: "Alias #{alias_id} not found or not active" } if !old_alias || old_alias.state != "active"
92
+
93
+ old_alias.state = "rotating"
94
+ old_alias.expires_at = now + @rotation_overlap_ms
95
+
96
+ result = create_alias(old_alias.primary_key_hash, old_alias.workload, "#{old_alias.label} (rotated)",
97
+ fingerprint: old_alias.fingerprint, scope: old_alias.scope)
98
+
99
+ unless result[:success] && result[:alias]
100
+ old_alias.state = "active" # Rollback
101
+ return { success: false, error: result[:error] }
102
+ end
103
+
104
+ old_alias.rotated_to_id = result[:alias].alias_id
105
+ result[:alias].rotated_from_id = alias_id
106
+
107
+ emit_audit(type: "alias_rotated", alias_id: alias_id, primary_key_hash: old_alias.primary_key_hash,
108
+ workload: old_alias.workload, timestamp: now,
109
+ metadata: { new_alias_id: result[:alias].alias_id, overlap_ms: @rotation_overlap_ms })
110
+
111
+ { success: true, old_alias_id: alias_id, new_alias: result[:alias], new_alias_key: result[:alias_key],
112
+ overlap_expires_at: old_alias.expires_at }
113
+ end
114
+
115
+ # Revoke a specific alias without affecting other aliases.
116
+ def revoke_alias(alias_id, reason: nil)
117
+ alias_record = @aliases[alias_id]
118
+ return false unless alias_record
119
+
120
+ alias_record.state = "revoked"
121
+ emit_audit(type: "alias_revoked", alias_id: alias_id, primary_key_hash: alias_record.primary_key_hash,
122
+ workload: alias_record.workload, timestamp: now_ms, metadata: { reason: reason || "manual_revocation" })
123
+ true
124
+ end
125
+
126
+ # Validate an alias key for incoming requests.
127
+ def validate_alias_key(alias_key, fingerprint: nil)
128
+ alias_key_hash = Digest::SHA256.hexdigest(alias_key)
129
+ alias_id = @alias_key_index[alias_key_hash]
130
+ return { valid: false, reason: "Unknown alias key" } unless alias_id
131
+
132
+ alias_record = @aliases[alias_id]
133
+ return { valid: false, reason: "Alias record not found" } unless alias_record
134
+
135
+ now = now_ms
136
+
137
+ if alias_record.state == "revoked"
138
+ return { valid: false, alias_id: alias_id, workload: alias_record.workload, reason: "Alias has been revoked" }
139
+ end
140
+
141
+ if alias_record.expires_at && now > alias_record.expires_at
142
+ alias_record.state = "expired"
143
+ emit_audit(type: "alias_expired", alias_id: alias_id, primary_key_hash: alias_record.primary_key_hash,
144
+ workload: alias_record.workload, timestamp: now)
145
+ return { valid: false, alias_id: alias_id, workload: alias_record.workload, reason: "Alias has expired" }
146
+ end
147
+
148
+ anomaly_detected = false
149
+ if alias_record.fingerprint && fingerprint && alias_record.fingerprint != fingerprint
150
+ anomaly_detected = true
151
+ emit_audit(type: "alias_misuse_detected", alias_id: alias_id, primary_key_hash: alias_record.primary_key_hash,
152
+ workload: alias_record.workload, timestamp: now,
153
+ metadata: { reason: "fingerprint_mismatch", expected_fingerprint: alias_record.fingerprint[0, 8] })
154
+ end
155
+
156
+ alias_record.last_used_at = now
157
+ alias_record.usage_count += 1
158
+
159
+ emit_audit(type: "alias_used", alias_id: alias_id, primary_key_hash: alias_record.primary_key_hash,
160
+ workload: alias_record.workload, timestamp: now)
161
+
162
+ {
163
+ valid: !anomaly_detected, alias_id: alias_id, workload: alias_record.workload,
164
+ primary_key_hash: alias_record.primary_key_hash,
165
+ reason: anomaly_detected ? "Fingerprint mismatch detected" : "Valid alias",
166
+ anomaly_detected: anomaly_detected,
167
+ }
168
+ end
169
+
170
+ # List all aliases for a primary key.
171
+ def list_aliases(primary_key_hash)
172
+ alias_ids = @primary_key_aliases[primary_key_hash]
173
+ return [] unless alias_ids
174
+
175
+ alias_ids.filter_map { |id| @aliases[id] }.map do |a|
176
+ redacted = a.dup
177
+ redacted.alias_key = "[REDACTED]"
178
+ redacted
179
+ end
180
+ end
181
+
182
+ def stats
183
+ result = {
184
+ total_aliases: @aliases.size, active_aliases: 0, rotating_aliases: 0, revoked_aliases: 0,
185
+ by_workload: WORKLOADS.to_h { |w| [w, 0] }, recent_anomalies: 0,
186
+ }
187
+
188
+ @aliases.each_value do |a|
189
+ case a.state
190
+ when "active" then result[:active_aliases] += 1
191
+ when "rotating" then result[:rotating_aliases] += 1
192
+ when "revoked" then result[:revoked_aliases] += 1
193
+ end
194
+ result[:by_workload][a.workload] += 1
195
+ end
196
+
197
+ one_hour_ago = now_ms - 3_600_000
198
+ result[:recent_anomalies] = @audit_log.count { |e| e.type == "alias_misuse_detected" && e.timestamp > one_hour_ago }
199
+ result
200
+ end
201
+
202
+ def audit_log(limit = 100)
203
+ @audit_log.last(limit)
204
+ end
205
+
206
+ # Resolve a stored alias back to its real alias key. Returns nil for
207
+ # an unknown/revoked/expired alias, or if the stored ciphertext fails
208
+ # auth-tag verification (tampered/corrupted).
209
+ def resolve(alias_id)
210
+ alias_record = @aliases[alias_id]
211
+ return nil unless alias_record
212
+ return nil if %w[revoked expired].include?(alias_record.state)
213
+
214
+ decrypted = CredentialVault.decrypt(alias_record.alias_key, @vault_key)
215
+ separator_index = decrypted.index(":")
216
+ separator_index.nil? ? decrypted : decrypted[(separator_index + 1)..]
217
+ rescue StandardError
218
+ nil
219
+ end
220
+
221
+ private
222
+
223
+ # AES-256-GCM encrypt the alias key for forward-map storage.
224
+ def encrypt_alias_key(alias_key, primary_key_hash)
225
+ CredentialVault.encrypt("#{primary_key_hash}:#{alias_key}", @vault_key)
226
+ end
227
+
228
+ def emit_audit(type:, alias_id:, primary_key_hash:, workload:, timestamp:, metadata: nil)
229
+ event = AliasAuditEvent.new(type: type, alias_id: alias_id, primary_key_hash: primary_key_hash,
230
+ workload: workload, timestamp: timestamp, metadata: metadata)
231
+ @audit_log << event
232
+ @audit_log.shift(@audit_log.length - 10_000) if @audit_log.length > 10_000
233
+ warn "[A19-Alias] #{type}: #{alias_id} (#{workload})" if @debug
234
+ end
235
+
236
+ def now_ms
237
+ (Time.now.to_f * 1000).to_i
238
+ end
239
+ end
240
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ # Bounded Map.
5
+ #
6
+ # Mirrors packages/devfortress-sdk/src/internal-closed-loop-engine.ts's
7
+ # generic, public BoundedMap. A bounded, LRU-ish map: once at
8
+ # capacity, Set evicts the oldest-inserted entry still present. Get
9
+ # does not change eviction order (eviction order is insertion order
10
+ # of still-present keys, mirroring Node's Map-backed original, which
11
+ # relies on Map#keys.first for the oldest key, not last-accessed).
12
+ # Safe for concurrent use.
13
+ class BoundedMap
14
+ def initialize(max_size)
15
+ @max_size = max_size
16
+ @store = {}
17
+ @order = []
18
+ @mutex = Mutex.new
19
+ end
20
+
21
+ def get(key)
22
+ @mutex.synchronize { @store[key] }
23
+ end
24
+
25
+ def set(key, value)
26
+ @mutex.synchronize do
27
+ existed = @store.key?(key)
28
+ evict_oldest if !existed && @store.size >= @max_size
29
+ @order << key unless existed
30
+ @store[key] = value
31
+ end
32
+ end
33
+
34
+ def has?(key)
35
+ @mutex.synchronize { @store.key?(key) }
36
+ end
37
+
38
+ def delete(key)
39
+ @mutex.synchronize do
40
+ existed = @store.key?(key)
41
+ @store.delete(key)
42
+ existed
43
+ end
44
+ end
45
+
46
+ def size
47
+ @mutex.synchronize { @store.size }
48
+ end
49
+
50
+ def clear
51
+ @mutex.synchronize do
52
+ @store = {}
53
+ @order = []
54
+ end
55
+ end
56
+
57
+ def values
58
+ @mutex.synchronize { @store.values }
59
+ end
60
+
61
+ def keys
62
+ @mutex.synchronize { @store.keys }
63
+ end
64
+
65
+ def each(&block)
66
+ @mutex.synchronize { @store.each(&block) }
67
+ end
68
+
69
+ private
70
+
71
+ def evict_oldest
72
+ while (oldest = @order.shift)
73
+ if @store.key?(oldest)
74
+ @store.delete(oldest)
75
+ return
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ # Platform Circuit Breaker.
5
+ #
6
+ # Mirrors packages/devfortress-sdk/src/circuit-breaker.ts. Monitors
7
+ # connectivity to the DevFortress platform and provides automatic
8
+ # failover from external to internal closed-loop mode.
9
+ #
10
+ # Three states:
11
+ # :closed - Platform is reachable, external CL is active
12
+ # :open - Platform is unreachable, internal CL takes over
13
+ # :half_open - Testing if the platform has recovered
14
+ #
15
+ # Transition rules:
16
+ # closed -> open: After failure_threshold consecutive failures
17
+ # open -> half_open: After recovery_time_seconds elapsed
18
+ # half_open -> closed: First successful call
19
+ # half_open -> open: First failed call
20
+ class PlatformCircuitBreaker
21
+ # Rules older than 5 minutes without a platform sync are
22
+ # considered stale.
23
+ STALE_THRESHOLD_SECONDS = 300
24
+
25
+ Diagnostics = Struct.new(
26
+ :state, :failure_count, :last_failure_time, :seconds_until_recovery_attempt,
27
+ :rules_stale, :stale_duration_seconds,
28
+ keyword_init: true
29
+ )
30
+
31
+ def initialize(failure_threshold: 3, recovery_time_seconds: 60, on_state_change: nil)
32
+ @failure_threshold = failure_threshold
33
+ @recovery_time_seconds = recovery_time_seconds
34
+ @on_state_change = on_state_change
35
+
36
+ @state = :closed
37
+ @failure_count = 0
38
+ @last_failure_time = Time.at(0)
39
+ # Tracks when internal rules became stale (circuit opened).
40
+ @stale_since = nil
41
+ @mutex = Mutex.new
42
+ end
43
+
44
+ # Returns whether external platform calls should be attempted
45
+ # (true if closed or half-open).
46
+ def should_call_external?
47
+ @mutex.synchronize do
48
+ case @state
49
+ when :closed
50
+ true
51
+ when :open
52
+ if Time.now - @last_failure_time >= @recovery_time_seconds
53
+ transition(:half_open, "recovery_timeout_elapsed")
54
+ true # allow one test call
55
+ else
56
+ false
57
+ end
58
+ else # :half_open
59
+ true
60
+ end
61
+ end
62
+ end
63
+
64
+ # Records a successful external call.
65
+ def record_success
66
+ @mutex.synchronize do
67
+ transition(:closed, "test_call_succeeded") if @state == :half_open
68
+ @failure_count = 0
69
+ @stale_since = nil
70
+ end
71
+ end
72
+
73
+ # Records a failed external call.
74
+ def record_failure
75
+ @mutex.synchronize do
76
+ @failure_count += 1
77
+ @last_failure_time = Time.now
78
+
79
+ if @state == :half_open
80
+ transition(:open, "test_call_failed")
81
+ elsif @state == :closed && @failure_count >= @failure_threshold
82
+ transition(:open, "consecutive_failures")
83
+ end
84
+ end
85
+ end
86
+
87
+ # Returns the current circuit state.
88
+ def state
89
+ @mutex.synchronize { @state }
90
+ end
91
+
92
+ # Returns diagnostics info.
93
+ def diagnostics
94
+ @mutex.synchronize do
95
+ seconds_until_recovery =
96
+ if @state == :open
97
+ elapsed = Time.now - @last_failure_time
98
+ elapsed < @recovery_time_seconds ? @recovery_time_seconds - elapsed : 0
99
+ else
100
+ 0
101
+ end
102
+
103
+ stale_duration = @stale_since ? Time.now - @stale_since : 0
104
+
105
+ Diagnostics.new(
106
+ state: @state, failure_count: @failure_count, last_failure_time: @last_failure_time,
107
+ seconds_until_recovery_attempt: seconds_until_recovery,
108
+ rules_stale: stale_duration > STALE_THRESHOLD_SECONDS,
109
+ stale_duration_seconds: stale_duration
110
+ )
111
+ end
112
+ end
113
+
114
+ # Forces the circuit breaker back to the closed state.
115
+ def reset
116
+ @mutex.synchronize do
117
+ transition(:closed, "manual_reset")
118
+ @failure_count = 0
119
+ @last_failure_time = Time.at(0)
120
+ @stale_since = nil
121
+ end
122
+ end
123
+
124
+ # Returns whether internal rules are stale (no platform sync for
125
+ # longer than STALE_THRESHOLD_SECONDS).
126
+ def rules_stale?
127
+ @mutex.synchronize { !@stale_since.nil? && (Time.now - @stale_since) > STALE_THRESHOLD_SECONDS }
128
+ end
129
+
130
+ private
131
+
132
+ def transition(to, reason)
133
+ from = @state
134
+ return if from == to
135
+
136
+ @state = to
137
+
138
+ @stale_since = Time.now if to == :open && @stale_since.nil?
139
+
140
+ return unless @on_state_change
141
+
142
+ begin
143
+ @on_state_change.call(from, to, reason)
144
+ rescue StandardError
145
+ # Callback errors should not break the circuit breaker.
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi"
4
+
5
+ module DevFortress
6
+ # Maps an HTTP response to a DevFortress event.
7
+ module Classifier
8
+ SQL = [
9
+ /\bor\b.*=.*/i,
10
+ /\bunion\b.*\bselect\b/i,
11
+ /\bdrop\b.*\btable\b/i,
12
+ /'\s*or\s*'1'\s*=\s*'1/i,
13
+ ].freeze
14
+
15
+ XSS = [
16
+ /javascript:/i,
17
+ /onerror\s*=\s*/i,
18
+ /onload\s*=\s*/i,
19
+ ].freeze
20
+
21
+ TRAVERSAL = [
22
+ %r{\.\.[/\\]},
23
+ %r{/etc/passwd}i,
24
+ ].freeze
25
+
26
+ # True if +text+ contains a <script> tag.
27
+ #
28
+ # Primary check is a plain linear scan for "<script" eventually
29
+ # followed by "</script>" — same reach as the
30
+ # `%r{<script[^>]*>[\s\S]*?</script>}` regex this replaces (including
31
+ # the classic `<scr<script>ipt>` nesting trick), but with no
32
+ # backtracking. When Loofah is loaded (Rails apps already have it via
33
+ # rails-html-sanitizer/actionview), malformed markup that survives the
34
+ # scan (a "<script" with no matching close) is confirmed by checking
35
+ # that Loofah's real HTML parser actually stripped something — not
36
+ # just the literal substring in plain prose. Falls back to the scan
37
+ # alone when Loofah isn't loaded: this gem is deliberately
38
+ # stdlib-only with no runtime gem dependency (see the gemspec),
39
+ # matching the Go/PHP SDKs.
40
+ def self.has_script_tag?(text)
41
+ lower = text.downcase
42
+ open_idx = lower.index("<script")
43
+ return true if open_idx && lower.index("</script>", open_idx)
44
+ return false unless lower.include?("<script")
45
+ return true unless defined?(Loofah)
46
+
47
+ Loofah.fragment(text).text != text
48
+ end
49
+
50
+ # Names of the suspicious patterns found in +text+.
51
+ #
52
+ # Matches the raw text and one percent-decoding pass. An invalid byte
53
+ # sequence (text is not valid UTF-8) is treated as not suspicious rather
54
+ # than raised, matching the PHP and Go classifiers' behaviour.
55
+ def self.detect_suspicious(text)
56
+ return [] unless text.valid_encoding?
57
+
58
+ candidates = [text]
59
+ decoded = CGI.unescape(text)
60
+ candidates << decoded if decoded != text && decoded.valid_encoding?
61
+
62
+ found = []
63
+ found << "sql_injection" if hit?(SQL, candidates)
64
+ found << "xss" if hit?(XSS, candidates) || candidates.any? { |c| has_script_tag?(c) }
65
+ found << "path_traversal" if hit?(TRAVERSAL, candidates)
66
+ found
67
+ end
68
+
69
+ # An event Hash, or nil when the request is not security-relevant.
70
+ def self.build_event(ip:, method:, path:, status_code:, latency_ms:, user_agent: nil, query: "", user_id: nil)
71
+ event_type = nil
72
+ severity = "LOW"
73
+ reason = nil
74
+ action = "monitored"
75
+
76
+ case status_code
77
+ when 401, 403
78
+ event_type = "auth_failure"
79
+ severity = "MEDIUM"
80
+ reason = "Authentication or authorization failed"
81
+ action = "blocked"
82
+ when 400, 422
83
+ event_type = "validation_error"
84
+ reason = "Request validation failed"
85
+ when 429
86
+ event_type = "rate_limit_exceeded"
87
+ severity = "MEDIUM"
88
+ reason = "Rate limit exceeded"
89
+ action = "rate_limited"
90
+ else
91
+ if status_code >= 500
92
+ event_type = "5xx_error"
93
+ severity = "HIGH"
94
+ reason = "Server error: #{status_code}"
95
+ elsif status_code >= 400
96
+ event_type = "4xx_error"
97
+ reason = "Client error: #{status_code}"
98
+ end
99
+ end
100
+
101
+ suspicious = detect_suspicious("#{path} #{query}")
102
+ unless suspicious.empty?
103
+ event_type = "suspicious_pattern"
104
+ severity = "HIGH"
105
+ reason = "Suspicious patterns detected: #{suspicious.join(', ')}"
106
+ action = "flagged"
107
+ end
108
+
109
+ return nil if event_type.nil?
110
+
111
+ {
112
+ "eventType" => event_type,
113
+ "ip" => ip.nil? || ip.empty? ? "0.0.0.0" : ip,
114
+ "method" => method,
115
+ "path" => path,
116
+ "userAgent" => user_agent,
117
+ "statusCode" => status_code,
118
+ "severity" => severity,
119
+ "clMode" => "external",
120
+ "authPhase" => user_id.nil? || user_id.to_s.empty? ? "pre_auth" : "post_auth",
121
+ "actionTaken" => action,
122
+ "responseLatencyMs" => latency_ms,
123
+ "userId" => user_id,
124
+ "metadata" => { "reason" => reason },
125
+ }
126
+ end
127
+
128
+ def self.hit?(patterns, candidates)
129
+ candidates.any? { |candidate| patterns.any? { |pattern| pattern.match?(candidate) } }
130
+ end
131
+ private_class_method :hit?
132
+ end
133
+ end