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.
- checksums.yaml +7 -0
- data/.gitignore +4 -0
- data/Gemfile +7 -0
- data/LICENSE +63 -0
- data/README.md +121 -0
- data/Rakefile +11 -0
- data/lib/devfortress/agent_adapter.rb +185 -0
- data/lib/devfortress/agent_loop_detector.rb +167 -0
- data/lib/devfortress/agent_output_exfiltration_detector.rb +115 -0
- data/lib/devfortress/agent_security.rb +431 -0
- data/lib/devfortress/alias_verify.rb +87 -0
- data/lib/devfortress/api_key_aliasing.rb +240 -0
- data/lib/devfortress/bounded_map.rb +80 -0
- data/lib/devfortress/circuit_breaker.rb +149 -0
- data/lib/devfortress/classifier.rb +133 -0
- data/lib/devfortress/client.rb +380 -0
- data/lib/devfortress/client_ip.rb +28 -0
- data/lib/devfortress/clock_drift_detector.rb +71 -0
- data/lib/devfortress/credential_isolation.rb +340 -0
- data/lib/devfortress/credential_vault.rb +93 -0
- data/lib/devfortress/delivery_result.rb +9 -0
- data/lib/devfortress/graduated_rate_limiter.rb +270 -0
- data/lib/devfortress/internal_closed_loop_engine.rb +658 -0
- data/lib/devfortress/license_manager.rb +297 -0
- data/lib/devfortress/observer.rb +62 -0
- data/lib/devfortress/prompt_injection_filter.rb +73 -0
- data/lib/devfortress/response_webhook_client.rb +165 -0
- data/lib/devfortress/shadow_agent_registry.rb +123 -0
- data/lib/devfortress/signer.rb +134 -0
- data/lib/devfortress/telemetry.rb +407 -0
- data/lib/devfortress/tier_gate.rb +294 -0
- data/lib/devfortress/tool_call_sequence_validator.rb +126 -0
- data/lib/devfortress/transport.rb +31 -0
- data/lib/devfortress/unified_audit_trail.rb +213 -0
- data/lib/devfortress/version.rb +5 -0
- data/lib/devfortress/webhook_verification.rb +9 -0
- data/lib/devfortress/webhook_verifier.rb +93 -0
- data/lib/devfortress.rb +96 -0
- metadata +110 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
require "thread"
|
|
6
|
+
|
|
7
|
+
require_relative "signer"
|
|
8
|
+
require_relative "transport"
|
|
9
|
+
require_relative "delivery_result"
|
|
10
|
+
require_relative "version"
|
|
11
|
+
require_relative "internal_closed_loop_engine"
|
|
12
|
+
require_relative "circuit_breaker"
|
|
13
|
+
|
|
14
|
+
module DevFortress
|
|
15
|
+
# DevFortress event client (external mode, plus internal/hybrid
|
|
16
|
+
# closed-loop mode — see #observe).
|
|
17
|
+
#
|
|
18
|
+
# Events are queued in memory (track_event, track_events) and delivered in
|
|
19
|
+
# batches ({"events": [...]}, server maximum MAX_SERVER_BATCH) by #flush.
|
|
20
|
+
# Every request is signed with the request signature contract (see Signer):
|
|
21
|
+
# the API key never goes on the wire, only a key ID does.
|
|
22
|
+
#
|
|
23
|
+
# Retry: up to +retries+ attempts, exponential backoff, only on 5xx
|
|
24
|
+
# responses and network errors. 3xx and 4xx responses are never retried.
|
|
25
|
+
# Every attempt is signed again with a fresh nonce and timestamp.
|
|
26
|
+
#
|
|
27
|
+
# Delivery never raises into the host application: a failed delivery comes
|
|
28
|
+
# back as a DeliveryResult and is logged. Only a missing API key raises, at
|
|
29
|
+
# construction. The queue is safe for concurrent use.
|
|
30
|
+
class Client
|
|
31
|
+
DEFAULT_ENDPOINT = "https://www.devfortress.net/api/events/ingest"
|
|
32
|
+
DEFAULT_TIMEOUT = 15
|
|
33
|
+
DEFAULT_RETRIES = 3
|
|
34
|
+
DEFAULT_BATCH_SIZE = 25
|
|
35
|
+
# MAX_SERVER_BATCH is the largest number of events the platform accepts
|
|
36
|
+
# in one ingest request; #flush splits the queue into chunks this size.
|
|
37
|
+
MAX_SERVER_BATCH = 100
|
|
38
|
+
|
|
39
|
+
# Current closed-loop mode ("external", "internal" or "hybrid").
|
|
40
|
+
attr_reader :mode
|
|
41
|
+
# The InternalClosedLoopEngine instance, or nil in external mode.
|
|
42
|
+
attr_reader :internal_engine
|
|
43
|
+
# The PlatformCircuitBreaker instance, or nil outside hybrid mode.
|
|
44
|
+
attr_reader :circuit_breaker
|
|
45
|
+
|
|
46
|
+
def initialize(
|
|
47
|
+
api_key,
|
|
48
|
+
endpoint = DEFAULT_ENDPOINT,
|
|
49
|
+
timeout: DEFAULT_TIMEOUT,
|
|
50
|
+
retries: DEFAULT_RETRIES,
|
|
51
|
+
batch_size: DEFAULT_BATCH_SIZE,
|
|
52
|
+
backoff_base: 1.0,
|
|
53
|
+
defaults: {},
|
|
54
|
+
privacy: "standard",
|
|
55
|
+
logger: nil,
|
|
56
|
+
transport: nil,
|
|
57
|
+
sleeper: nil,
|
|
58
|
+
flush_interval: nil,
|
|
59
|
+
mode: "external",
|
|
60
|
+
circuit_breaker_failure_threshold: 3,
|
|
61
|
+
circuit_breaker_recovery_time_seconds: 60
|
|
62
|
+
)
|
|
63
|
+
@signer = Signer.new(api_key)
|
|
64
|
+
@endpoint = endpoint.nil? || endpoint.empty? ? DEFAULT_ENDPOINT : endpoint
|
|
65
|
+
@request_target = Signer.request_target_from_url(@endpoint)
|
|
66
|
+
@timeout = timeout
|
|
67
|
+
@retries = [retries, 1].max
|
|
68
|
+
@batch_size = [batch_size, 1].max
|
|
69
|
+
@backoff_base = backoff_base
|
|
70
|
+
@defaults = defaults || {}
|
|
71
|
+
@privacy = privacy
|
|
72
|
+
@logger = logger
|
|
73
|
+
@transport = transport || Transport.new
|
|
74
|
+
@sleeper = sleeper || ->(seconds) { sleep(seconds) if seconds.positive? }
|
|
75
|
+
|
|
76
|
+
@mutex = Mutex.new
|
|
77
|
+
@queue = []
|
|
78
|
+
@stop_cv = ConditionVariable.new
|
|
79
|
+
|
|
80
|
+
@flush_thread = nil
|
|
81
|
+
@stop = false
|
|
82
|
+
|
|
83
|
+
# Mirrors Node's DevFortressCore and this session's Python port:
|
|
84
|
+
# internal/hybrid mode gets its own InternalClosedLoopEngine
|
|
85
|
+
# instance; hybrid additionally gets a PlatformCircuitBreaker.
|
|
86
|
+
# Default "external" is a no-op here — existing callers that never
|
|
87
|
+
# pass `mode:` see no behaviour change.
|
|
88
|
+
@mode = mode
|
|
89
|
+
@internal_engine = nil
|
|
90
|
+
@circuit_breaker = nil
|
|
91
|
+
if %w[internal hybrid].include?(@mode)
|
|
92
|
+
@internal_engine = InternalClosedLoopEngine.new(
|
|
93
|
+
enable_external_relay: @mode == "hybrid",
|
|
94
|
+
on_relay: @mode == "hybrid" ? method(:relay_internal_decision_to_platform) : nil,
|
|
95
|
+
)
|
|
96
|
+
end
|
|
97
|
+
if @mode == "hybrid"
|
|
98
|
+
@circuit_breaker = PlatformCircuitBreaker.new(
|
|
99
|
+
failure_threshold: circuit_breaker_failure_threshold,
|
|
100
|
+
recovery_time_seconds: circuit_breaker_recovery_time_seconds,
|
|
101
|
+
)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
@flush_thread = Thread.new { background_flush(flush_interval) } if flush_interval && flush_interval.positive?
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# ── Internal / hybrid closed-loop mode ────────────────────────────
|
|
108
|
+
# Mirrors Node's DevFortressCore#observeInternal/#observeHybrid and
|
|
109
|
+
# this session's Python port's #observe(): a pre-response gate the
|
|
110
|
+
# caller (typically middleware) invokes before the request reaches
|
|
111
|
+
# the application. Mode is fixed at construction time; external mode
|
|
112
|
+
# has no #observe behaviour — external-mode reporting stays on the
|
|
113
|
+
# existing after-response track_event path, unchanged.
|
|
114
|
+
#
|
|
115
|
+
# Returns a Hash (flagged: true, event_id:, confidence:, decision:,
|
|
116
|
+
# matched_rules:) if the request should be blocked/rate-limited/
|
|
117
|
+
# challenged/quarantined, else nil (allowed). Always nil in external
|
|
118
|
+
# mode (no internal engine exists to ask).
|
|
119
|
+
def observe(req)
|
|
120
|
+
case @mode
|
|
121
|
+
when "internal" then observe_internal(req)
|
|
122
|
+
when "hybrid" then observe_hybrid(req)
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Ruby-idiomatic equivalent of Node's isIPBlocked()/Python's
|
|
127
|
+
# is_blocked(), named to match this SDK's own public API exactly as
|
|
128
|
+
# specified (TODO 407). Whether +ip+ is currently blocked by the
|
|
129
|
+
# internal engine's in-memory cache. Always false in external mode.
|
|
130
|
+
def is_blocked?(ip) # rubocop:disable Naming/PredicateName
|
|
131
|
+
return false unless @internal_engine
|
|
132
|
+
|
|
133
|
+
@internal_engine.ip_blocked?(ip)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# Queues one event. The queue is sent (synchronously, like #flush) once
|
|
137
|
+
# it reaches the batch size; it is also sent when #flush is called, or
|
|
138
|
+
# at #close. A caller that must not block on delivery runs track_event
|
|
139
|
+
# from its own thread (see Rack::Middleware).
|
|
140
|
+
def track_event(event)
|
|
141
|
+
enqueue([event])
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Queues several events.
|
|
145
|
+
def track_events(events)
|
|
146
|
+
enqueue(events)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Sends everything queued, in chunks of at most MAX_SERVER_BATCH events,
|
|
150
|
+
# and returns one DeliveryResult per chunk. #flush never raises; failures
|
|
151
|
+
# are reported through the returned results.
|
|
152
|
+
def flush
|
|
153
|
+
events = @mutex.synchronize do
|
|
154
|
+
q = @queue
|
|
155
|
+
@queue = []
|
|
156
|
+
q
|
|
157
|
+
end
|
|
158
|
+
return [] if events.empty?
|
|
159
|
+
|
|
160
|
+
events.each_slice(MAX_SERVER_BATCH).map { |chunk| post({ "events" => chunk }) }
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# Number of events waiting to be flushed.
|
|
164
|
+
def pending_events
|
|
165
|
+
@mutex.synchronize { @queue.length }
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# Reports whether the platform accepts a signed test event with this key.
|
|
169
|
+
# Never raises; an unreachable platform or a rejected key both report false.
|
|
170
|
+
def test_connection
|
|
171
|
+
event = prepare(
|
|
172
|
+
"eventType" => "custom",
|
|
173
|
+
"ip" => "127.0.0.1",
|
|
174
|
+
"method" => "GET",
|
|
175
|
+
"path" => "/__devfortress/test",
|
|
176
|
+
"severity" => "LOW",
|
|
177
|
+
"authPhase" => "pre_auth",
|
|
178
|
+
"actionTaken" => "monitored",
|
|
179
|
+
"responseLatencyMs" => 0,
|
|
180
|
+
"clMode" => "external",
|
|
181
|
+
"metadata" => { "test" => true, "sdk" => "ruby" },
|
|
182
|
+
)
|
|
183
|
+
post(event).ok
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# Stops the background flush thread (if any) and flushes whatever is
|
|
187
|
+
# still queued. Safe to call more than once.
|
|
188
|
+
def close
|
|
189
|
+
@mutex.synchronize do
|
|
190
|
+
@stop = true
|
|
191
|
+
@stop_cv.broadcast # wakes background_flush immediately, instead of after its current sleep
|
|
192
|
+
end
|
|
193
|
+
@flush_thread&.join
|
|
194
|
+
flush
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
private
|
|
198
|
+
|
|
199
|
+
def observe_internal(req)
|
|
200
|
+
result = @internal_engine.evaluate(req)
|
|
201
|
+
return nil if result.decision == :allow
|
|
202
|
+
|
|
203
|
+
{
|
|
204
|
+
flagged: true,
|
|
205
|
+
event_id: result.event_id,
|
|
206
|
+
confidence: result.score / 100.0,
|
|
207
|
+
decision: result.decision,
|
|
208
|
+
matched_rules: result.matched_rules,
|
|
209
|
+
}
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def observe_hybrid(req)
|
|
213
|
+
# Step 1: internal evaluation (immediate, sub-ms, no round-trip).
|
|
214
|
+
internal_result = observe_internal(req)
|
|
215
|
+
if internal_result
|
|
216
|
+
# The internal engine's own on_relay callback (wired in
|
|
217
|
+
# #initialize) already handles the Tier-3 relay for this
|
|
218
|
+
# decision — no second relay call here, matching Node's TODO-210
|
|
219
|
+
# double-billing fix and the Python port's own observe_hybrid.
|
|
220
|
+
return internal_result
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# Step 2: external enrichment, circuit-breaker gated.
|
|
224
|
+
#
|
|
225
|
+
# KNOWN LIMITATION (documented, not silently overclaimed): Node's
|
|
226
|
+
# observeHybrid() calls observeExternal() here for a real
|
|
227
|
+
# platform-side enrichment verdict. This port does not yet make
|
|
228
|
+
# that platform call — it only exercises the circuit breaker's
|
|
229
|
+
# success/failure bookkeeping around a no-op enrichment step, so
|
|
230
|
+
# clean traffic is allowed and the circuit stays closed, but a
|
|
231
|
+
# request that internal mode missed and only the platform's own
|
|
232
|
+
# cross-customer intelligence would have caught is not enriched
|
|
233
|
+
# here. Matches the Python port's identically-documented gap.
|
|
234
|
+
@circuit_breaker.record_success if @circuit_breaker&.should_call_external?
|
|
235
|
+
nil
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
# Tier-3 relay target for hybrid mode — wired as the internal
|
|
239
|
+
# engine's on_relay callable (see #initialize). Reuses the existing
|
|
240
|
+
# #track_event path, same as every other outbound event from this
|
|
241
|
+
# client, rather than opening a second HTTP path. #track_event only
|
|
242
|
+
# enqueues (fast, in-memory, safe to call synchronously here, matching
|
|
243
|
+
# the engine's own documented expectation that on_relay stay
|
|
244
|
+
# zero-network in its own critical path); flushing happens in its own
|
|
245
|
+
# Thread.new below, mirroring Observer.observe_and_flush's exact
|
|
246
|
+
# pattern, so a single hybrid-mode relay (sparse traffic — the common
|
|
247
|
+
# case) is actually delivered promptly instead of sitting queued until
|
|
248
|
+
# this client's batch size or flush interval is reached. Found live,
|
|
249
|
+
# via this port's own end-to-end demo proof against a real platform.
|
|
250
|
+
def relay_internal_decision_to_platform(result, req)
|
|
251
|
+
event_type = result.matched_rules.first || "icl_#{result.decision}"
|
|
252
|
+
severity = if result.score >= 85
|
|
253
|
+
"CRITICAL"
|
|
254
|
+
elsif result.score >= 60
|
|
255
|
+
"HIGH"
|
|
256
|
+
elsif result.score >= 35
|
|
257
|
+
"MEDIUM"
|
|
258
|
+
else
|
|
259
|
+
"LOW"
|
|
260
|
+
end
|
|
261
|
+
action_map = {
|
|
262
|
+
allow: "allowed", block: "blocked", rate_limit: "rate_limited",
|
|
263
|
+
challenge: "challenge_required", quarantine: "flagged",
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
track_event(
|
|
267
|
+
"eventType" => event_type,
|
|
268
|
+
"ip" => req.ip,
|
|
269
|
+
"severity" => severity,
|
|
270
|
+
"method" => req.method,
|
|
271
|
+
"path" => req.path,
|
|
272
|
+
"userAgent" => req.user_agent,
|
|
273
|
+
"authPhase" => req.user_id ? "post_auth" : "pre_auth",
|
|
274
|
+
"actionTaken" => action_map[result.decision] || "flagged",
|
|
275
|
+
"responseLatencyMs" => (result.evaluation_time_us / 1000.0).round,
|
|
276
|
+
"clMode" => "hybrid",
|
|
277
|
+
"metadata" => {
|
|
278
|
+
"source" => "internal-closed-loop-engine",
|
|
279
|
+
"tier" => result.tier,
|
|
280
|
+
"matchedRules" => result.matched_rules,
|
|
281
|
+
"internalEventId" => result.event_id,
|
|
282
|
+
"sessionId" => req.session_id,
|
|
283
|
+
"agentId" => req.agent_id,
|
|
284
|
+
},
|
|
285
|
+
)
|
|
286
|
+
Thread.new { flush }
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
# Waits on a ConditionVariable rather than plain `sleep`, so #close can
|
|
290
|
+
# wake this loop immediately via @stop_cv.broadcast instead of leaving it
|
|
291
|
+
# to sleep out its current interval first — a real bug found via live
|
|
292
|
+
# testing (devfortress-sdk-rails's demo hung at shutdown for a full
|
|
293
|
+
# flush_interval, because Thread#join had nothing to wake it early).
|
|
294
|
+
def background_flush(interval)
|
|
295
|
+
loop do
|
|
296
|
+
stop = @mutex.synchronize do
|
|
297
|
+
@stop_cv.wait(@mutex, interval)
|
|
298
|
+
@stop
|
|
299
|
+
end
|
|
300
|
+
break if stop
|
|
301
|
+
|
|
302
|
+
flush
|
|
303
|
+
end
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
def enqueue(events)
|
|
307
|
+
should_flush = @mutex.synchronize do
|
|
308
|
+
events.each { |event| @queue << prepare(event) }
|
|
309
|
+
@queue.length >= @batch_size
|
|
310
|
+
end
|
|
311
|
+
flush if should_flush
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
def prepare(event)
|
|
315
|
+
item = @defaults.merge(event)
|
|
316
|
+
item["timestamp"] ||= Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
|
|
317
|
+
if @privacy == "strict"
|
|
318
|
+
item.delete("userAgent")
|
|
319
|
+
if item["ip"].is_a?(String)
|
|
320
|
+
item["ip"] = Digest::SHA256.hexdigest(item["ip"])[0, 16]
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
item["metadata"] = {} if item.key?("metadata") && item["metadata"].nil?
|
|
324
|
+
item
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
def post(payload)
|
|
328
|
+
raw = JSON.generate(payload)
|
|
329
|
+
last = DeliveryResult.new(ok: false, error: "no delivery attempt was made", attempts: 0)
|
|
330
|
+
|
|
331
|
+
1.upto(@retries) do |attempt|
|
|
332
|
+
# A fresh nonce and timestamp on every attempt, so a retry is not a replay.
|
|
333
|
+
headers = @signer.sign("POST", @request_target, raw)
|
|
334
|
+
headers["Content-Type"] = "application/json"
|
|
335
|
+
headers["Accept"] = "application/json"
|
|
336
|
+
headers["User-Agent"] = "devfortress-sdk-ruby/#{VERSION}"
|
|
337
|
+
|
|
338
|
+
begin
|
|
339
|
+
response = @transport.send_request("POST", @endpoint, headers, raw, @timeout)
|
|
340
|
+
body = decode(response.body)
|
|
341
|
+
if response.status_code >= 200 && response.status_code < 300
|
|
342
|
+
return DeliveryResult.new(ok: true, status_code: response.status_code, body: body, attempts: attempt)
|
|
343
|
+
end
|
|
344
|
+
|
|
345
|
+
last = DeliveryResult.new(ok: false, status_code: response.status_code, body: body,
|
|
346
|
+
error: "HTTP #{response.status_code}", attempts: attempt)
|
|
347
|
+
return fail(last) if response.status_code < 500 # 3xx and 4xx: never retried
|
|
348
|
+
rescue TransportError => e
|
|
349
|
+
last = DeliveryResult.new(ok: false, error: "request failed: #{e.message}", attempts: attempt)
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
@sleeper.call(@backoff_base * (2**(attempt - 1))) if attempt < @retries
|
|
353
|
+
end
|
|
354
|
+
|
|
355
|
+
fail(last)
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
def fail(result)
|
|
359
|
+
log("warning", "devfortress: delivery failed: #{result.error || 'unknown error'}",
|
|
360
|
+
status: result.status_code, attempts: result.attempts)
|
|
361
|
+
result
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
def decode(raw)
|
|
365
|
+
return {} if raw.nil? || raw.empty?
|
|
366
|
+
|
|
367
|
+
JSON.parse(raw)
|
|
368
|
+
rescue JSON::ParserError
|
|
369
|
+
raw
|
|
370
|
+
end
|
|
371
|
+
|
|
372
|
+
def log(level, message, fields = {})
|
|
373
|
+
return unless @logger
|
|
374
|
+
|
|
375
|
+
@logger.log(level, message, fields)
|
|
376
|
+
rescue StandardError
|
|
377
|
+
# A failing logger must not reach the host application either.
|
|
378
|
+
end
|
|
379
|
+
end
|
|
380
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ipaddr"
|
|
4
|
+
|
|
5
|
+
module DevFortress
|
|
6
|
+
# Picks the end-user IP for an event from what the request shows.
|
|
7
|
+
#
|
|
8
|
+
# Precedence: first X-Forwarded-For entry, then X-Real-IP, then the socket
|
|
9
|
+
# address, then 0.0.0.0. A candidate that is not an IP address is skipped, so a
|
|
10
|
+
# malformed forwarded header cannot poison a batch.
|
|
11
|
+
module ClientIp
|
|
12
|
+
def self.resolve(forwarded_for, real_ip, remote_addr)
|
|
13
|
+
first = forwarded_for.nil? ? "" : forwarded_for.split(",").first.to_s.strip
|
|
14
|
+
[first, real_ip.to_s.strip, remote_addr.to_s.strip].each do |candidate|
|
|
15
|
+
return candidate if !candidate.empty? && ip?(candidate)
|
|
16
|
+
end
|
|
17
|
+
"0.0.0.0"
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def self.ip?(candidate)
|
|
21
|
+
IPAddr.new(candidate)
|
|
22
|
+
true
|
|
23
|
+
rescue IPAddr::Error
|
|
24
|
+
false
|
|
25
|
+
end
|
|
26
|
+
private_class_method :ip?
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DevFortress
|
|
4
|
+
# Clock Drift Anomaly Detector (Invention A18).
|
|
5
|
+
#
|
|
6
|
+
# Mirrors packages/devfortress-sdk/src/security-extensions.ts's
|
|
7
|
+
# ClockDriftDetector. TODO 419/422 — one of the 20 Node-only claims
|
|
8
|
+
# identified by the 2026-11-02 patent audit; ported to Python and Go in
|
|
9
|
+
# that session, here extended to Ruby.
|
|
10
|
+
#
|
|
11
|
+
# Compares a client-supplied timestamp against server time and
|
|
12
|
+
# classifies the drift into an escalating action: allow, warn (audit
|
|
13
|
+
# with server time), use_server_time (enforce server-authoritative
|
|
14
|
+
# timestamps), or reject (possible timestamp manipulation).
|
|
15
|
+
class ClockDriftDetector
|
|
16
|
+
Result = Struct.new(:valid, :drift_ms, :severity, :action, :reason, keyword_init: true)
|
|
17
|
+
Trend = Struct.new(:avg_drift, :increasing, keyword_init: true)
|
|
18
|
+
|
|
19
|
+
MAX_HISTORY_PER_CLIENT = 100
|
|
20
|
+
|
|
21
|
+
def initialize(acceptable_threshold_ms: 30_000, suspicious_threshold_ms: 120_000,
|
|
22
|
+
critical_threshold_ms: 300_000)
|
|
23
|
+
@acceptable_threshold_ms = acceptable_threshold_ms
|
|
24
|
+
@suspicious_threshold_ms = suspicious_threshold_ms
|
|
25
|
+
@critical_threshold_ms = critical_threshold_ms
|
|
26
|
+
@drift_history = {}
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Check a client timestamp (epoch milliseconds) against server time.
|
|
30
|
+
def check(client_timestamp_ms, client_id: nil)
|
|
31
|
+
server_time_ms = Time.now.to_f * 1000
|
|
32
|
+
drift_ms = (client_timestamp_ms - server_time_ms).abs
|
|
33
|
+
direction = client_timestamp_ms > server_time_ms ? "ahead" : "behind"
|
|
34
|
+
|
|
35
|
+
if client_id
|
|
36
|
+
history = (@drift_history[client_id] ||= [])
|
|
37
|
+
history.push(drift_ms)
|
|
38
|
+
history.shift while history.length > MAX_HISTORY_PER_CLIENT
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
if drift_ms <= @acceptable_threshold_ms
|
|
42
|
+
Result.new(valid: true, drift_ms: drift_ms, severity: "LOW", action: "allow",
|
|
43
|
+
reason: "Clock drift #{drift_ms.round}ms (#{direction}) within acceptable range")
|
|
44
|
+
elsif drift_ms <= @suspicious_threshold_ms
|
|
45
|
+
Result.new(valid: true, drift_ms: drift_ms, severity: "MEDIUM", action: "warn",
|
|
46
|
+
reason: "Clock drift #{drift_ms.round}ms (#{direction}) — suspicious, using server time for audit")
|
|
47
|
+
elsif drift_ms <= @critical_threshold_ms
|
|
48
|
+
Result.new(valid: true, drift_ms: drift_ms, severity: "HIGH", action: "use_server_time",
|
|
49
|
+
reason: "Clock drift #{drift_ms.round}ms (#{direction}) — enforcing server-authoritative timestamps")
|
|
50
|
+
else
|
|
51
|
+
Result.new(valid: false, drift_ms: drift_ms, severity: "CRITICAL", action: "reject",
|
|
52
|
+
reason: "Clock drift #{drift_ms.round}ms (#{direction}) exceeds critical threshold — possible timestamp manipulation")
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Returns the drift trend for a client, or nil if fewer than 3 samples.
|
|
57
|
+
def get_drift_trend(client_id)
|
|
58
|
+
history = @drift_history[client_id]
|
|
59
|
+
return nil if history.nil? || history.length < 3
|
|
60
|
+
|
|
61
|
+
avg_drift = history.sum / history.length.to_f
|
|
62
|
+
recent = history.last(3)
|
|
63
|
+
recent_avg = recent.sum / 3.0
|
|
64
|
+
Trend.new(avg_drift: avg_drift, increasing: recent_avg > avg_drift * 1.2)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def get_stats
|
|
68
|
+
{ tracked_clients: @drift_history.size }
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|