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,297 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
require "thread"
|
|
6
|
+
|
|
7
|
+
require_relative "signer"
|
|
8
|
+
require_relative "transport"
|
|
9
|
+
require_relative "version"
|
|
10
|
+
|
|
11
|
+
module DevFortress
|
|
12
|
+
# License Manager — CV-M1, CV-M4, CV-M7.
|
|
13
|
+
#
|
|
14
|
+
# Implements:
|
|
15
|
+
# - CV-M1: Server-side license validation with a 24h check interval and
|
|
16
|
+
# a 72h grace period before degrading to monitor-only mode.
|
|
17
|
+
# - CV-M4: ML model staleness detection (30 days without a platform sync).
|
|
18
|
+
# - CV-M7: SDK anti-tampering HMAC integrity hash.
|
|
19
|
+
#
|
|
20
|
+
# This is the client-side half of the fix for the bug class TODO 321
|
|
21
|
+
# already fixed on the platform: license-check/heartbeat calls silently
|
|
22
|
+
# 404ing and causing silent monitor-only degradation. The platform's
|
|
23
|
+
# /api/sdk/license-check and /api/sdk/heartbeat endpoints already exist
|
|
24
|
+
# (TODO 321); this class only talks to them — no new platform route.
|
|
25
|
+
# Mirrors packages/devfortress-sdk/src/license-manager.ts.
|
|
26
|
+
#
|
|
27
|
+
# Every check is logged visibly (info/warn to $stderr, debug to $stdout
|
|
28
|
+
# when debug: true) — never silent — matching TODO 321's fix intent: a
|
|
29
|
+
# failing license check must be loud, not invisible.
|
|
30
|
+
#
|
|
31
|
+
# A background periodic-check thread is only started if
|
|
32
|
+
# check_interval_seconds is given and positive (mirrors Client's own
|
|
33
|
+
# opt-in flush_interval convention) — #check_license is always callable
|
|
34
|
+
# directly, which is what the test suite uses.
|
|
35
|
+
class LicenseManager
|
|
36
|
+
DEFAULT_CHECK_INTERVAL_SECONDS = 24 * 60 * 60 # 24 hours
|
|
37
|
+
DEFAULT_GRACE_PERIOD_SECONDS = 72 * 60 * 60 # 72 hours
|
|
38
|
+
DEFAULT_MODEL_EXPIRY_SECONDS = 30 * 24 * 60 * 60 # 30 days
|
|
39
|
+
DEFAULT_TIMEOUT_SECONDS = 10
|
|
40
|
+
|
|
41
|
+
CRITICAL_PATHS = %w[
|
|
42
|
+
DevFortress.observe
|
|
43
|
+
DevFortress.isBlocked
|
|
44
|
+
LicenseManager.checkLicense
|
|
45
|
+
InternalClosedLoopEngine.evaluate
|
|
46
|
+
TierGate.checkEventLimit
|
|
47
|
+
].join("|").freeze
|
|
48
|
+
|
|
49
|
+
LicenseState = Struct.new(
|
|
50
|
+
:valid, :tier, :last_checked_at, :consecutive_failures, :degraded, :degradation_reason,
|
|
51
|
+
keyword_init: true
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
ModelState = Struct.new(:last_synced_at, :model_version, :expired, keyword_init: true)
|
|
55
|
+
|
|
56
|
+
def initialize(
|
|
57
|
+
api_key:,
|
|
58
|
+
endpoint:,
|
|
59
|
+
check_interval_seconds: nil,
|
|
60
|
+
grace_period_seconds: DEFAULT_GRACE_PERIOD_SECONDS,
|
|
61
|
+
model_expiry_seconds: DEFAULT_MODEL_EXPIRY_SECONDS,
|
|
62
|
+
integrity_secret: nil,
|
|
63
|
+
debug: false,
|
|
64
|
+
timeout: DEFAULT_TIMEOUT_SECONDS,
|
|
65
|
+
transport: nil
|
|
66
|
+
)
|
|
67
|
+
@api_key = api_key
|
|
68
|
+
@endpoint = endpoint
|
|
69
|
+
@signer = Signer.new(api_key)
|
|
70
|
+
@check_interval_seconds = check_interval_seconds
|
|
71
|
+
@grace_period_seconds = grace_period_seconds || DEFAULT_GRACE_PERIOD_SECONDS
|
|
72
|
+
@model_expiry_seconds = model_expiry_seconds || DEFAULT_MODEL_EXPIRY_SECONDS
|
|
73
|
+
@integrity_secret = integrity_secret
|
|
74
|
+
@debug = debug
|
|
75
|
+
@timeout = timeout
|
|
76
|
+
@transport = transport || Transport.new
|
|
77
|
+
|
|
78
|
+
@mutex = Mutex.new
|
|
79
|
+
@license_state = LicenseState.new(
|
|
80
|
+
valid: false, tier: "starter", last_checked_at: 0, consecutive_failures: 0,
|
|
81
|
+
degraded: false, degradation_reason: nil
|
|
82
|
+
)
|
|
83
|
+
@model_state = ModelState.new(last_synced_at: now_ms, model_version: "embedded-v1", expired: false)
|
|
84
|
+
|
|
85
|
+
@check_thread = nil
|
|
86
|
+
@stop = false
|
|
87
|
+
@stop_cv = ConditionVariable.new
|
|
88
|
+
@initialized = false
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# ── CV-M1: License Validation ──────────────────────────────
|
|
92
|
+
|
|
93
|
+
# Performs an initial license check and, if check_interval_seconds was
|
|
94
|
+
# given and positive, starts a background thread for periodic checks.
|
|
95
|
+
# Safe to call more than once (a no-op after the first call).
|
|
96
|
+
def init
|
|
97
|
+
return license_state if @initialized
|
|
98
|
+
|
|
99
|
+
check_license
|
|
100
|
+
|
|
101
|
+
@check_thread = Thread.new { periodic_check } if @check_interval_seconds && @check_interval_seconds.positive?
|
|
102
|
+
|
|
103
|
+
@initialized = true
|
|
104
|
+
license_state
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Performs one license check against the platform. On failure, tracks
|
|
108
|
+
# consecutive failures and degrades to monitor-only once the grace
|
|
109
|
+
# period has elapsed since the last success.
|
|
110
|
+
def check_license
|
|
111
|
+
url = "#{@endpoint}/api/sdk/license-check"
|
|
112
|
+
body = JSON.generate({ "sdkVersion" => VERSION, "timestamp" => now_ms, "integrity" => compute_integrity_hash })
|
|
113
|
+
headers = sign_headers(url, body)
|
|
114
|
+
|
|
115
|
+
begin
|
|
116
|
+
response = @transport.send_request("POST", url, headers, body, @timeout)
|
|
117
|
+
|
|
118
|
+
if response.status_code >= 200 && response.status_code < 300
|
|
119
|
+
data = JSON.parse(response.body.to_s)
|
|
120
|
+
@mutex.synchronize do
|
|
121
|
+
@license_state = LicenseState.new(
|
|
122
|
+
valid: true,
|
|
123
|
+
tier: data["tier"] || @license_state.tier,
|
|
124
|
+
last_checked_at: now_ms,
|
|
125
|
+
consecutive_failures: 0,
|
|
126
|
+
degraded: false,
|
|
127
|
+
degradation_reason: nil
|
|
128
|
+
)
|
|
129
|
+
if data["modelVersion"]
|
|
130
|
+
@model_state = ModelState.new(last_synced_at: now_ms, model_version: data["modelVersion"],
|
|
131
|
+
expired: false)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
log(:info, "License validated: tier=#{@license_state.tier}")
|
|
135
|
+
elsif [402, 403].include?(response.status_code)
|
|
136
|
+
@mutex.synchronize do
|
|
137
|
+
@license_state = LicenseState.new(
|
|
138
|
+
valid: false, tier: "starter", last_checked_at: now_ms,
|
|
139
|
+
consecutive_failures: @license_state.consecutive_failures + 1,
|
|
140
|
+
degraded: true, degradation_reason: "License rejected: HTTP #{response.status_code}"
|
|
141
|
+
)
|
|
142
|
+
end
|
|
143
|
+
log(:warn, "License rejected: HTTP #{response.status_code}")
|
|
144
|
+
else
|
|
145
|
+
handle_check_failure("HTTP #{response.status_code}")
|
|
146
|
+
end
|
|
147
|
+
rescue StandardError => e
|
|
148
|
+
handle_check_failure(e.message)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
license_state
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def license_state
|
|
155
|
+
@mutex.synchronize { @license_state.dup }
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def degraded?
|
|
159
|
+
@mutex.synchronize { @license_state.degraded }
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# Checks whether a specific capability is available given current
|
|
163
|
+
# license state. action: "block", "rate_limit" or "observe".
|
|
164
|
+
def can_perform_action?(action)
|
|
165
|
+
return true if action.to_s == "observe"
|
|
166
|
+
|
|
167
|
+
state = @mutex.synchronize { @license_state }
|
|
168
|
+
return false if state.degraded
|
|
169
|
+
return true if !state.valid && state.last_checked_at.zero?
|
|
170
|
+
|
|
171
|
+
state.valid
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# ── CV-M4: ML Model Expiry ─────────────────────────────────
|
|
175
|
+
|
|
176
|
+
# Checks whether the embedded ML model has expired. If expired (>30
|
|
177
|
+
# days without platform sync), ICL falls back to Tier 1 only.
|
|
178
|
+
def model_expired?
|
|
179
|
+
@mutex.synchronize do
|
|
180
|
+
age_seconds = (now_ms - @model_state.last_synced_at) / 1000.0
|
|
181
|
+
@model_state.expired = age_seconds > @model_expiry_seconds
|
|
182
|
+
@model_state.expired
|
|
183
|
+
end
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def model_state
|
|
187
|
+
expired = model_expired?
|
|
188
|
+
@mutex.synchronize do
|
|
189
|
+
state = @model_state.dup
|
|
190
|
+
state.expired = expired
|
|
191
|
+
state
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Manually trigger a model sync (called from DevFortress.init or a
|
|
196
|
+
# license-check response that carries a modelVersion).
|
|
197
|
+
def sync_model(model_version)
|
|
198
|
+
@mutex.synchronize do
|
|
199
|
+
@model_state = ModelState.new(last_synced_at: now_ms, model_version: model_version, expired: false)
|
|
200
|
+
end
|
|
201
|
+
log(:info, "ML model synced: version=#{model_version}")
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# ── CV-M7: Anti-Tampering ──────────────────────────────────
|
|
205
|
+
|
|
206
|
+
# Computes an HMAC signature over critical SDK code paths. If the SDK
|
|
207
|
+
# distribution has been modified, this hash differs from the expected
|
|
208
|
+
# value on the platform side.
|
|
209
|
+
def compute_integrity_hash
|
|
210
|
+
return "no-integrity-secret" if @integrity_secret.nil? || @integrity_secret.empty?
|
|
211
|
+
|
|
212
|
+
OpenSSL::HMAC.hexdigest("SHA256", @integrity_secret, CRITICAL_PATHS + @api_key)[0, 16]
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# Verifies that the SDK has not been tampered with. Returns
|
|
216
|
+
# tampered: true if the integrity hash doesn't match expected_hash.
|
|
217
|
+
def verify_integrity(expected_hash = nil)
|
|
218
|
+
current_hash = compute_integrity_hash
|
|
219
|
+
return { tampered: false, hash: current_hash } unless expected_hash
|
|
220
|
+
|
|
221
|
+
{ tampered: current_hash != expected_hash, hash: current_hash }
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# ── Cleanup ────────────────────────────────────────────────
|
|
225
|
+
|
|
226
|
+
# Stops the periodic check thread (if any) and clean up. Safe to call
|
|
227
|
+
# more than once.
|
|
228
|
+
def destroy
|
|
229
|
+
@mutex.synchronize do
|
|
230
|
+
@stop = true
|
|
231
|
+
@stop_cv.broadcast
|
|
232
|
+
end
|
|
233
|
+
@check_thread&.join
|
|
234
|
+
@check_thread = nil
|
|
235
|
+
@initialized = false
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
private
|
|
239
|
+
|
|
240
|
+
def periodic_check
|
|
241
|
+
loop do
|
|
242
|
+
stop = @mutex.synchronize do
|
|
243
|
+
@stop_cv.wait(@mutex, @check_interval_seconds)
|
|
244
|
+
@stop
|
|
245
|
+
end
|
|
246
|
+
break if stop
|
|
247
|
+
|
|
248
|
+
check_license
|
|
249
|
+
end
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def handle_check_failure(reason)
|
|
253
|
+
@mutex.synchronize do
|
|
254
|
+
@license_state.consecutive_failures += 1
|
|
255
|
+
baseline_time = @license_state.last_checked_at.zero? ? now_ms : @license_state.last_checked_at
|
|
256
|
+
time_since_last_success_ms = now_ms - baseline_time
|
|
257
|
+
grace_period_ms = @grace_period_seconds * 1000
|
|
258
|
+
|
|
259
|
+
if time_since_last_success_ms >= grace_period_ms
|
|
260
|
+
@license_state.degraded = true
|
|
261
|
+
@license_state.degradation_reason =
|
|
262
|
+
"License check failed for #{(time_since_last_success_ms / 3_600_000.0).round}h " \
|
|
263
|
+
"(grace period: #{(grace_period_ms / 3_600_000.0).round}h). " \
|
|
264
|
+
"Reason: #{reason}. SDK degraded to monitor-only mode."
|
|
265
|
+
log(:warn, @license_state.degradation_reason)
|
|
266
|
+
else
|
|
267
|
+
remaining_h = ((grace_period_ms - time_since_last_success_ms) / 3_600_000.0).round
|
|
268
|
+
log(:debug, "License check failed (#{reason}), " \
|
|
269
|
+
"#{@license_state.consecutive_failures} consecutive failures, " \
|
|
270
|
+
"#{remaining_h}h grace remaining")
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
def sign_headers(url, body)
|
|
276
|
+
headers = @signer.sign("POST", Signer.request_target_from_url(url), body)
|
|
277
|
+
headers["Content-Type"] = "application/json"
|
|
278
|
+
headers
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
def now_ms
|
|
282
|
+
(Time.now.to_f * 1000).to_i
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def log(level, message)
|
|
286
|
+
return if level == :debug && !@debug
|
|
287
|
+
|
|
288
|
+
prefix = "[DevFortress:License]"
|
|
289
|
+
case level
|
|
290
|
+
when :warn, :error
|
|
291
|
+
warn("#{prefix} #{message}")
|
|
292
|
+
else
|
|
293
|
+
puts("#{prefix} #{message}")
|
|
294
|
+
end
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "classifier"
|
|
4
|
+
require_relative "client_ip"
|
|
5
|
+
|
|
6
|
+
module DevFortress
|
|
7
|
+
# Shared "classify this request/response, queue an event for it" logic for
|
|
8
|
+
# every Ruby framework adapter (the Rack middleware in
|
|
9
|
+
# devfortress-sdk-rails, and any future one), the same way the Go SDK's
|
|
10
|
+
# Observe/ObserveAndFlush is shared by its net/http and gin adapters.
|
|
11
|
+
#
|
|
12
|
+
# ObserveAndFlush is the one adapters should call, not Observe:
|
|
13
|
+
# Observe only queues the event; under sparse traffic (fewer requests than
|
|
14
|
+
# the client's batch size between flushes) a queued-only event can sit
|
|
15
|
+
# undelivered indefinitely. This is the exact gap the Go SDK's gin adapter
|
|
16
|
+
# and demos/go-non-agentic had (Brief 10.1), fixed in Brief 10.2 by having
|
|
17
|
+
# the adapter flush after observing — ported here from the start so the
|
|
18
|
+
# Ruby adapter never ships with the same gap.
|
|
19
|
+
module Observer
|
|
20
|
+
Input = Struct.new(
|
|
21
|
+
:method, :path, :raw_query, :status_code, :latency_ms,
|
|
22
|
+
:user_agent, :forwarded_for, :real_ip, :remote_addr, :user_id,
|
|
23
|
+
keyword_init: true
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# Classifies and queues an event in its own Thread, detached from the
|
|
27
|
+
# request so delivery never delays the response. Only queues — see the
|
|
28
|
+
# module doc for why adapters should prefer ObserveAndFlush.
|
|
29
|
+
def self.observe(client, input)
|
|
30
|
+
queue(client, input, flush: false)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Behaves like .observe, but also flushes the queue once the event has
|
|
34
|
+
# been classified and queued, in that same detached Thread — so a single
|
|
35
|
+
# event is delivered even under sparse traffic, with no separate thread
|
|
36
|
+
# racing the enqueue.
|
|
37
|
+
def self.observe_and_flush(client, input)
|
|
38
|
+
queue(client, input, flush: true)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def self.queue(client, input, flush:)
|
|
42
|
+
ip = ClientIp.resolve(input.forwarded_for, input.real_ip, input.remote_addr)
|
|
43
|
+
Thread.new do
|
|
44
|
+
event = Classifier.build_event(
|
|
45
|
+
ip: ip,
|
|
46
|
+
method: input.method,
|
|
47
|
+
path: input.path,
|
|
48
|
+
status_code: input.status_code,
|
|
49
|
+
latency_ms: input.latency_ms,
|
|
50
|
+
user_agent: input.user_agent,
|
|
51
|
+
query: input.raw_query.to_s,
|
|
52
|
+
user_id: input.user_id,
|
|
53
|
+
)
|
|
54
|
+
next if event.nil?
|
|
55
|
+
|
|
56
|
+
client.track_event(event)
|
|
57
|
+
client.flush if flush
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
private_class_method :queue
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DevFortress
|
|
4
|
+
# A16: Indirect Prompt Injection Filter.
|
|
5
|
+
#
|
|
6
|
+
# Mirrors packages/devfortress-sdk/src/security-extensions.ts's
|
|
7
|
+
# PromptInjectionFilter.
|
|
8
|
+
class PromptInjectionFilter
|
|
9
|
+
INJECTION_PATTERNS = [
|
|
10
|
+
{ pattern: 'ignore\s+(previous|above|all|prior)\s+(instructions?|context|rules?)', name: "instruction_override", weight: 40 },
|
|
11
|
+
{ pattern: 'you\s+are\s+now\s+(a|an|the)', name: "role_assignment", weight: 35 },
|
|
12
|
+
{ pattern: 'system\s*:\s*|\[SYSTEM\]|<\|system\|>', name: "system_prompt_injection", weight: 45 },
|
|
13
|
+
{ pattern: 'forget\s+(everything|all|what)', name: "memory_wipe", weight: 40 },
|
|
14
|
+
{ pattern: 'do\s+not\s+(follow|obey|listen)', name: "disobedience_injection", weight: 35 },
|
|
15
|
+
{ pattern: 'act\s+as\s+(if|though)|pretend\s+(to\s+be|you)', name: "persona_injection", weight: 30 },
|
|
16
|
+
{ pattern: "<script>|javascript:|onerror=|onload=", name: "xss_in_data", weight: 50 },
|
|
17
|
+
{ pattern: '\bexec\s*\(|eval\s*\(|__import__', name: "code_execution", weight: 50 },
|
|
18
|
+
{ pattern: "translate.*to.*base64|encode.*payload", name: "encoding_evasion", weight: 25 },
|
|
19
|
+
{ pattern: 'reveal\s+(your|the)\s+(system|secret|api|key|password)', name: "secret_extraction", weight: 45 },
|
|
20
|
+
].freeze
|
|
21
|
+
|
|
22
|
+
def initialize(sensitivity: "medium", custom_patterns: [], max_scan_length: 100_000)
|
|
23
|
+
@sensitivity = sensitivity
|
|
24
|
+
@max_scan_length = max_scan_length
|
|
25
|
+
|
|
26
|
+
@patterns = INJECTION_PATTERNS.map { |p| { regex: Regexp.new(p[:pattern], Regexp::IGNORECASE), name: p[:name], weight: p[:weight] } }
|
|
27
|
+
custom_patterns.each_with_index do |pattern, i|
|
|
28
|
+
@patterns << { regex: Regexp.new(pattern, Regexp::IGNORECASE), name: "custom_#{i}", weight: 30 }
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def scan(content)
|
|
33
|
+
text = content[0, @max_scan_length]
|
|
34
|
+
detected_patterns = []
|
|
35
|
+
total_weight = 0
|
|
36
|
+
|
|
37
|
+
@patterns.each do |pattern|
|
|
38
|
+
if pattern[:regex].match?(text)
|
|
39
|
+
detected_patterns << pattern[:name]
|
|
40
|
+
total_weight += pattern[:weight]
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
sensitivity_multiplier = case @sensitivity
|
|
45
|
+
when "high" then 1.5
|
|
46
|
+
when "low" then 0.7
|
|
47
|
+
else 1.0
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
score = [100, (total_weight * sensitivity_multiplier).round].min
|
|
51
|
+
confidence = detected_patterns.empty? ? 0.1 : [0.99, 0.5 + (detected_patterns.length * 0.15)].min
|
|
52
|
+
|
|
53
|
+
severity = if score >= 70
|
|
54
|
+
"CRITICAL"
|
|
55
|
+
elsif score >= 45
|
|
56
|
+
"HIGH"
|
|
57
|
+
elsif score >= 20
|
|
58
|
+
"MEDIUM"
|
|
59
|
+
else
|
|
60
|
+
"LOW"
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
{
|
|
64
|
+
safe: score < 30,
|
|
65
|
+
confidence: confidence,
|
|
66
|
+
severity: severity,
|
|
67
|
+
detected_patterns: detected_patterns,
|
|
68
|
+
reason: detected_patterns.empty? ? "Content appears safe" : "Prompt injection detected: #{detected_patterns.join(', ')} (score=#{score})",
|
|
69
|
+
}
|
|
70
|
+
end
|
|
71
|
+
alias scan_agent_input scan
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
require "time"
|
|
6
|
+
require_relative "transport"
|
|
7
|
+
require_relative "webhook_verifier"
|
|
8
|
+
require_relative "credential_isolation" # LRUCache
|
|
9
|
+
|
|
10
|
+
module DevFortress
|
|
11
|
+
# Delivers closed-loop response commands (session revocation, IP block)
|
|
12
|
+
# to a single customer-configured webhook endpoint — the outbound
|
|
13
|
+
# direction of the closed loop, complementing WebhookVerifier.verify
|
|
14
|
+
# (the inbound direction: verifying a command the platform sent to this
|
|
15
|
+
# application). Every delivery is HMAC-SHA256 signed the same way
|
|
16
|
+
# WebhookVerifier checks it (hex HMAC over "{timestamp}.{body}"), rate
|
|
17
|
+
# limited per endpoint (60/min, S28 webhook flooding protection), and
|
|
18
|
+
# awaited with a short SLA timeout. Mirrors the outbound-delivery half of
|
|
19
|
+
# packages/devfortress-sdk/src/devfortress.ts (deliverSessionRevocation /
|
|
20
|
+
# deliverIPBlock / checkWebhookRateLimit).
|
|
21
|
+
class ResponseWebhookClient
|
|
22
|
+
RATE_WINDOW_SECONDS = 60
|
|
23
|
+
RATE_LIMIT = 60
|
|
24
|
+
BLOCK_CACHE_MAX_ENTRIES = 10_000
|
|
25
|
+
DEFAULT_BLOCK_CACHE_TTL_SECONDS = 3600
|
|
26
|
+
|
|
27
|
+
def initialize(url, secret, transport: nil)
|
|
28
|
+
@url = url
|
|
29
|
+
@secret = secret
|
|
30
|
+
@transport = transport || Transport.new
|
|
31
|
+
@mutex = Mutex.new
|
|
32
|
+
@buckets = {}
|
|
33
|
+
@block_cache = LRUCache.new(BLOCK_CACHE_MAX_ENTRIES, DEFAULT_BLOCK_CACHE_TTL_SECONDS)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Reports whether ip was locally cached as blocked by a prior
|
|
37
|
+
# #record_inbound_command call — local-only, no network call. Mirrors
|
|
38
|
+
# Node's own external-mode isBlocked()/memGet pair and Python's
|
|
39
|
+
# ClosedLoopEngine#is_blocked_ip (TODO 358): this SDK previously
|
|
40
|
+
# delivered and verified block/revocation commands but never
|
|
41
|
+
# self-enforced them locally, leaving every embedding app to implement
|
|
42
|
+
# its own cache.
|
|
43
|
+
def ip_blocked?(ip)
|
|
44
|
+
@mutex.synchronize { @block_cache.has?("blocked:ip:#{ip}") }
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Reports whether user_id was locally cached as blocked by a prior
|
|
48
|
+
# #record_inbound_command call — local-only, no network call.
|
|
49
|
+
def user_blocked?(user_id)
|
|
50
|
+
@mutex.synchronize { @block_cache.has?("blocked:user:#{user_id}") }
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Locally caches the block/revocation decision carried by an
|
|
54
|
+
# already-verified inbound command (see WebhookVerifier.verify +
|
|
55
|
+
# WebhookCommand.parse), so a subsequent #ip_blocked?/#user_blocked?
|
|
56
|
+
# call enforces it without a remote round-trip.
|
|
57
|
+
#
|
|
58
|
+
# An "ip_block" command is cached only when its severity is "critical"
|
|
59
|
+
# or "high" (or unset — #deliver_ip_block defaults to "high" when the
|
|
60
|
+
# sender leaves it empty), matching Node/Python's own severity gate. A
|
|
61
|
+
# "session_revocation" command carries no severity field on this SDK's
|
|
62
|
+
# wire shape (see #deliver_session_revocation's body) — its delivery
|
|
63
|
+
# already represents a decided enforcement action, so it is always
|
|
64
|
+
# cached.
|
|
65
|
+
def record_inbound_command(command)
|
|
66
|
+
ttl_seconds = command["ttl_seconds"] || DEFAULT_BLOCK_CACHE_TTL_SECONDS
|
|
67
|
+
|
|
68
|
+
case command["type"]
|
|
69
|
+
when "ip_block"
|
|
70
|
+
severity = command["severity"]
|
|
71
|
+
return if severity && !%w[high critical].include?(severity)
|
|
72
|
+
|
|
73
|
+
ip = command["ip"]
|
|
74
|
+
cache_block("blocked:ip:#{ip}", ttl_seconds) if ip && !ip.empty?
|
|
75
|
+
when "session_revocation"
|
|
76
|
+
user_id = command["user_id"]
|
|
77
|
+
ip = command["ip"]
|
|
78
|
+
cache_block("blocked:user:#{user_id}", ttl_seconds) if user_id && !user_id.empty?
|
|
79
|
+
cache_block("blocked:ip:#{ip}", ttl_seconds) if ip && !ip.empty?
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Deliver a session-revocation command, awaiting acknowledgement with
|
|
84
|
+
# a 2-second SLA timeout.
|
|
85
|
+
def deliver_session_revocation(session_id:, user_id: nil, reason:, ip: nil)
|
|
86
|
+
return { delivered: false } if @url.nil? || @url.empty? || @secret.nil? || @secret.empty?
|
|
87
|
+
return { delivered: false } unless check_rate_limit(@url)
|
|
88
|
+
|
|
89
|
+
timestamp = now_iso
|
|
90
|
+
body = JSON.generate({
|
|
91
|
+
"type" => "session_revocation", "session_id" => session_id, "user_id" => user_id,
|
|
92
|
+
"reason" => reason, "ip" => ip, "issued_at" => timestamp,
|
|
93
|
+
})
|
|
94
|
+
deliver(timestamp, body, 2)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Deliver an IP-block command so the customer can enforce at the edge
|
|
98
|
+
# (CDN/WAF/load balancer), awaiting acknowledgement with a 5-second
|
|
99
|
+
# SLA timeout.
|
|
100
|
+
def deliver_ip_block(ip:, reason:, ttl_seconds: 3600, severity: "high")
|
|
101
|
+
return { delivered: false } if @url.nil? || @url.empty? || @secret.nil? || @secret.empty?
|
|
102
|
+
return { delivered: false } unless check_rate_limit(@url)
|
|
103
|
+
|
|
104
|
+
timestamp = now_iso
|
|
105
|
+
body = JSON.generate({
|
|
106
|
+
"type" => "ip_block", "ip" => ip, "reason" => reason, "ttl_seconds" => ttl_seconds,
|
|
107
|
+
"severity" => severity, "issued_at" => timestamp,
|
|
108
|
+
})
|
|
109
|
+
deliver(timestamp, body, 5)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
private
|
|
113
|
+
|
|
114
|
+
def cache_block(key, ttl_seconds)
|
|
115
|
+
@mutex.synchronize { @block_cache.set(key, "1", ttl_seconds) }
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def deliver(timestamp, body, timeout_seconds)
|
|
119
|
+
signature = OpenSSL::HMAC.hexdigest("SHA256", @secret, "#{timestamp}.#{body}")
|
|
120
|
+
headers = {
|
|
121
|
+
"Content-Type" => "application/json",
|
|
122
|
+
WebhookVerifier::SIGNATURE_HEADER => signature,
|
|
123
|
+
WebhookVerifier::TIMESTAMP_HEADER => timestamp,
|
|
124
|
+
}
|
|
125
|
+
start = Time.now
|
|
126
|
+
begin
|
|
127
|
+
@transport.send_request("POST", @url, headers, body, timeout_seconds)
|
|
128
|
+
{ delivered: true, ack_time_seconds: Time.now - start }
|
|
129
|
+
rescue TransportError
|
|
130
|
+
{ delivered: false, ack_time_seconds: Time.now - start }
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# S28 webhook flooding protection: at most RATE_LIMIT deliveries per
|
|
135
|
+
# endpoint per RATE_WINDOW_SECONDS.
|
|
136
|
+
def check_rate_limit(endpoint_url)
|
|
137
|
+
@mutex.synchronize do
|
|
138
|
+
now = Time.now
|
|
139
|
+
bucket = @buckets[endpoint_url]
|
|
140
|
+
if bucket.nil? || (now - bucket[:window_start]) >= RATE_WINDOW_SECONDS
|
|
141
|
+
@buckets[endpoint_url] = { count: 1, window_start: now }
|
|
142
|
+
return true
|
|
143
|
+
end
|
|
144
|
+
return false if bucket[:count] >= RATE_LIMIT
|
|
145
|
+
|
|
146
|
+
bucket[:count] += 1
|
|
147
|
+
true
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def now_iso
|
|
152
|
+
Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# A parsed, already-verified inbound command from the platform
|
|
157
|
+
# (session_revocation or ip_block) — the inbound direction of the closed
|
|
158
|
+
# loop. Call WebhookVerifier.verify first; this does not re-verify the
|
|
159
|
+
# signature.
|
|
160
|
+
module WebhookCommand
|
|
161
|
+
def self.parse(raw_body)
|
|
162
|
+
JSON.parse(raw_body)
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
end
|