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,431 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require_relative "agent_adapter"
|
|
5
|
+
require_relative "credential_isolation"
|
|
6
|
+
|
|
7
|
+
module DevFortress
|
|
8
|
+
# Agent Credential Aliasing & Security (IP-C2, IP-C3, IP-C4, IP-C5).
|
|
9
|
+
#
|
|
10
|
+
# Extends the core credential isolation system for AI agent credentials.
|
|
11
|
+
# Mirrors packages/devfortress-sdk/src/agent-security.ts.
|
|
12
|
+
|
|
13
|
+
AgentCredentialAliasData = Struct.new(
|
|
14
|
+
:alias_id, :agent_id, :credential_type, :created_at, :quarantined,
|
|
15
|
+
:quarantine_reason, :quarantined_at, :execution_context, keyword_init: true,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
AgentBaselineMetrics = Struct.new(
|
|
19
|
+
:avg_tools_per_session, :tool_diversity_entropy, :avg_data_volume_bytes,
|
|
20
|
+
:avg_session_duration_ms, :top_tools, :total_sessions, :created_at,
|
|
21
|
+
:last_updated_at, :task_definition, keyword_init: true,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
AgentSessionRecord = Struct.new(:session_id, :agent_id, :tool_calls, :started_at, :ended_at, :total_data_bytes, keyword_init: true)
|
|
25
|
+
|
|
26
|
+
AgentAnomalySignal = Struct.new(:type, :agent_id, :severity, :description, :detected_at, :details, keyword_init: true)
|
|
27
|
+
|
|
28
|
+
AgentScopeDefinition = Struct.new(:agent_id, :allowed_tools, :strict_mode, :created_at, :updated_at, keyword_init: true)
|
|
29
|
+
|
|
30
|
+
def self.shannon_entropy(items)
|
|
31
|
+
return 0.0 if items.empty?
|
|
32
|
+
|
|
33
|
+
freq = Hash.new(0)
|
|
34
|
+
items.each { |item| freq[item] += 1 }
|
|
35
|
+
total = items.length.to_f
|
|
36
|
+
freq.values.reduce(0.0) do |entropy, count|
|
|
37
|
+
p = count / total
|
|
38
|
+
p.positive? ? entropy - (p * Math.log2(p)) : entropy
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Agent Credential Manager (IP-C2).
|
|
43
|
+
class AgentCredentialManager
|
|
44
|
+
def initialize(token_manager, cache: nil)
|
|
45
|
+
@token_manager = token_manager
|
|
46
|
+
@cache = cache
|
|
47
|
+
@credentials = {}
|
|
48
|
+
@quarantines = {}
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def create_agent_alias(real_credential, agent_id, credential_type, ttl_seconds: 7200, execution_context: nil)
|
|
52
|
+
DevFortress.validate_agent_id(agent_id)
|
|
53
|
+
alias_id = @token_manager.create_alias(real_credential, agent_id, ttl_seconds: ttl_seconds)
|
|
54
|
+
|
|
55
|
+
data = AgentCredentialAliasData.new(
|
|
56
|
+
alias_id: alias_id, agent_id: agent_id, credential_type: credential_type,
|
|
57
|
+
created_at: now_ms, quarantined: false, execution_context: execution_context,
|
|
58
|
+
)
|
|
59
|
+
(@credentials[agent_id] ||= []) << data
|
|
60
|
+
|
|
61
|
+
if @cache
|
|
62
|
+
begin
|
|
63
|
+
existing = @cache.get("agent:creds:#{agent_id}")
|
|
64
|
+
list = existing ? JSON.parse(existing) : []
|
|
65
|
+
list << data.to_h
|
|
66
|
+
@cache.set("agent:creds:#{agent_id}", JSON.generate(list), ttl_seconds)
|
|
67
|
+
rescue StandardError
|
|
68
|
+
# In-memory is already set
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
alias_id
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Revoke ALL credentials for an agent (IP-C2).
|
|
76
|
+
def revoke_agent_access(agent_id, reason: "active_threat")
|
|
77
|
+
creds = @credentials[agent_id] || []
|
|
78
|
+
revoked_count = 0
|
|
79
|
+
creds.each do |cred|
|
|
80
|
+
@token_manager.revoke_by_alias(cred.alias_id, reason: reason, subject_id: agent_id)
|
|
81
|
+
revoked_count += 1
|
|
82
|
+
rescue StandardError
|
|
83
|
+
# Continue revoking remaining credentials
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
@credentials.delete(agent_id)
|
|
87
|
+
@quarantines.delete(agent_id)
|
|
88
|
+
|
|
89
|
+
if @cache
|
|
90
|
+
begin
|
|
91
|
+
@cache.del("agent:creds:#{agent_id}")
|
|
92
|
+
@cache.del("agent:quarantine:#{agent_id}")
|
|
93
|
+
rescue StandardError
|
|
94
|
+
# Best-effort
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
revoked_count
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Quarantine an agent (IP-C2) — suspend tool access but preserve
|
|
102
|
+
# session for forensics. Reversible, unlike revocation.
|
|
103
|
+
def quarantine_agent(agent_id, reason)
|
|
104
|
+
quarantine = { reason: reason, at: now_ms }
|
|
105
|
+
@quarantines[agent_id] = quarantine
|
|
106
|
+
|
|
107
|
+
(@credentials[agent_id] || []).each do |cred|
|
|
108
|
+
cred.quarantined = true
|
|
109
|
+
cred.quarantine_reason = reason
|
|
110
|
+
cred.quarantined_at = quarantine[:at]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
return unless @cache
|
|
114
|
+
|
|
115
|
+
begin
|
|
116
|
+
@cache.set("agent:quarantine:#{agent_id}", JSON.generate(quarantine), 86_400)
|
|
117
|
+
rescue StandardError
|
|
118
|
+
# In-memory is set
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Lift quarantine for an agent. Rejects if not currently quarantined.
|
|
123
|
+
def unquarantine_agent(agent_id)
|
|
124
|
+
unless @quarantines.key?(agent_id)
|
|
125
|
+
raise ArgumentError, "Agent \"#{agent_id}\" is not currently quarantined — nothing to reinstate."
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
@quarantines.delete(agent_id)
|
|
129
|
+
(@credentials[agent_id] || []).each do |cred|
|
|
130
|
+
cred.quarantined = false
|
|
131
|
+
cred.quarantine_reason = nil
|
|
132
|
+
cred.quarantined_at = nil
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
return unless @cache
|
|
136
|
+
|
|
137
|
+
begin
|
|
138
|
+
@cache.del("agent:quarantine:#{agent_id}")
|
|
139
|
+
rescue StandardError
|
|
140
|
+
# Best-effort
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def quarantined?(agent_id)
|
|
145
|
+
@quarantines.key?(agent_id)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def quarantine_details(agent_id)
|
|
149
|
+
@quarantines[agent_id]
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def agent_credentials(agent_id)
|
|
153
|
+
@credentials[agent_id] || []
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
private
|
|
157
|
+
|
|
158
|
+
def now_ms
|
|
159
|
+
(Time.now.to_f * 1000).to_i
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# Agent Behavioral Baseline (IP-C3).
|
|
164
|
+
class AgentBaselineEngine
|
|
165
|
+
BASELINE_WINDOW_DAYS = 30
|
|
166
|
+
MIN_SESSIONS_FOR_BASELINE = 5
|
|
167
|
+
|
|
168
|
+
def initialize
|
|
169
|
+
@sessions = {}
|
|
170
|
+
@baselines = {}
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def record_session(record)
|
|
174
|
+
sessions = (@sessions[record.agent_id] ||= [])
|
|
175
|
+
window_start = now_ms - (BASELINE_WINDOW_DAYS * 24 * 60 * 60 * 1000)
|
|
176
|
+
filtered = sessions.select { |s| s.started_at > window_start }
|
|
177
|
+
filtered << record
|
|
178
|
+
@sessions[record.agent_id] = filtered
|
|
179
|
+
|
|
180
|
+
recalculate_baseline(record.agent_id) if filtered.length >= MIN_SESSIONS_FOR_BASELINE
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# Establish a baseline from a task definition (IP-C3).
|
|
184
|
+
def agent_baseline(agent_id, task_definition)
|
|
185
|
+
existing = @baselines[agent_id]
|
|
186
|
+
if existing
|
|
187
|
+
existing.task_definition = task_definition
|
|
188
|
+
existing.last_updated_at = now_ms
|
|
189
|
+
return existing
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
sessions = @sessions[agent_id] || []
|
|
193
|
+
return nil if sessions.length < MIN_SESSIONS_FOR_BASELINE
|
|
194
|
+
|
|
195
|
+
recalculate_baseline(agent_id, task_definition)
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
def baseline(agent_id)
|
|
199
|
+
@baselines[agent_id]
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def sessions_for(agent_id)
|
|
203
|
+
@sessions[agent_id] || []
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def is_3_sigma_deviation?(values, new_value)
|
|
207
|
+
return false if values.length < 2
|
|
208
|
+
|
|
209
|
+
mean = values.sum.to_f / values.length
|
|
210
|
+
sd = std_dev(values)
|
|
211
|
+
return new_value != mean if sd.zero?
|
|
212
|
+
|
|
213
|
+
(new_value - mean).abs > 3 * sd
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
private
|
|
217
|
+
|
|
218
|
+
def recalculate_baseline(agent_id, task_definition = nil)
|
|
219
|
+
sessions = @sessions[agent_id] || []
|
|
220
|
+
|
|
221
|
+
tools_per_session = sessions.map { |s| s.tool_calls.length }
|
|
222
|
+
avg_tools_per_session = tools_per_session.sum.to_f / sessions.length
|
|
223
|
+
|
|
224
|
+
all_tools = sessions.flat_map { |s| s.tool_calls.map { |tc| tc[:tool] || tc["tool"] } }
|
|
225
|
+
tool_diversity_entropy = DevFortress.shannon_entropy(all_tools)
|
|
226
|
+
|
|
227
|
+
data_volumes = sessions.map(&:total_data_bytes)
|
|
228
|
+
avg_data_volume_bytes = data_volumes.sum.to_f / sessions.length
|
|
229
|
+
|
|
230
|
+
durations = sessions.select(&:ended_at).map { |s| s.ended_at - s.started_at }
|
|
231
|
+
avg_session_duration_ms = durations.empty? ? 0 : durations.sum.to_f / durations.length
|
|
232
|
+
|
|
233
|
+
tool_freq = Hash.new(0)
|
|
234
|
+
all_tools.each { |tool| tool_freq[tool] += 1 }
|
|
235
|
+
top_tools = tool_freq.sort_by { |_, count| -count }.first(10).map(&:first)
|
|
236
|
+
|
|
237
|
+
baseline = AgentBaselineMetrics.new(
|
|
238
|
+
avg_tools_per_session: avg_tools_per_session,
|
|
239
|
+
tool_diversity_entropy: tool_diversity_entropy,
|
|
240
|
+
avg_data_volume_bytes: avg_data_volume_bytes,
|
|
241
|
+
avg_session_duration_ms: avg_session_duration_ms,
|
|
242
|
+
top_tools: top_tools,
|
|
243
|
+
total_sessions: sessions.length,
|
|
244
|
+
created_at: @baselines[agent_id]&.created_at || now_ms,
|
|
245
|
+
last_updated_at: now_ms,
|
|
246
|
+
task_definition: task_definition || @baselines[agent_id]&.task_definition,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
@baselines[agent_id] = baseline
|
|
250
|
+
baseline
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
def std_dev(values)
|
|
254
|
+
return 0.0 if values.length < 2
|
|
255
|
+
|
|
256
|
+
mean = values.sum.to_f / values.length
|
|
257
|
+
sq_diffs = values.map { |v| (v - mean)**2 }
|
|
258
|
+
Math.sqrt(sq_diffs.sum / values.length)
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
def now_ms
|
|
262
|
+
(Time.now.to_f * 1000).to_i
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# Agent Anomaly Detector (IP-C4), with unsanctioned-tool scope
|
|
267
|
+
# enforcement (IP-C5) integrated here for convenience — mirrors the Go
|
|
268
|
+
# SDK's merged AgentAnomalyDetector, since scope enforcement is only
|
|
269
|
+
# ever consumed from inside #analyze_tool_call anyway.
|
|
270
|
+
class AgentAnomalyDetector
|
|
271
|
+
def initialize(baseline_engine)
|
|
272
|
+
@baseline_engine = baseline_engine
|
|
273
|
+
@anomaly_handlers = []
|
|
274
|
+
@credential_usage = {}
|
|
275
|
+
@scopes = {}
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
def on_anomaly(&handler)
|
|
279
|
+
@anomaly_handlers << handler
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
# Register the sanctioned tool scope for an agent (IP-C5). In strict
|
|
283
|
+
# mode, any tool outside allowed_tools fires a critical anomaly
|
|
284
|
+
# immediately.
|
|
285
|
+
def define_agent_scope(agent_id, allowed_tools, strict_mode: true)
|
|
286
|
+
scope = AgentScopeDefinition.new(
|
|
287
|
+
agent_id: agent_id, allowed_tools: allowed_tools, strict_mode: strict_mode,
|
|
288
|
+
created_at: @scopes[agent_id]&.created_at || now_ms, updated_at: now_ms,
|
|
289
|
+
)
|
|
290
|
+
@scopes[agent_id] = scope
|
|
291
|
+
scope
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# Whether tool_name is within agent_id's defined scope. Allows by
|
|
295
|
+
# default when no scope is defined, or when not in strict mode.
|
|
296
|
+
def tool_allowed?(agent_id, tool_name)
|
|
297
|
+
scope = @scopes[agent_id]
|
|
298
|
+
return true unless scope
|
|
299
|
+
return true unless scope.strict_mode
|
|
300
|
+
|
|
301
|
+
scope.allowed_tools.include?(tool_name)
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
def scope(agent_id)
|
|
305
|
+
@scopes[agent_id]
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def remove_scope(agent_id)
|
|
309
|
+
@scopes.delete(agent_id)
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
def add_allowed_tools(agent_id, tools)
|
|
313
|
+
scope = @scopes[agent_id]
|
|
314
|
+
unless scope
|
|
315
|
+
define_agent_scope(agent_id, tools, strict_mode: true)
|
|
316
|
+
return
|
|
317
|
+
end
|
|
318
|
+
scope.allowed_tools = (scope.allowed_tools + tools).uniq
|
|
319
|
+
scope.updated_at = now_ms
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
def remove_allowed_tools(agent_id, tools)
|
|
323
|
+
scope = @scopes[agent_id]
|
|
324
|
+
return unless scope
|
|
325
|
+
|
|
326
|
+
scope.allowed_tools -= tools
|
|
327
|
+
scope.updated_at = now_ms
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# Analyze a tool call for anomalies against the agent's baseline.
|
|
331
|
+
def analyze_tool_call(agent_id, tool_name, data_bytes: 0, credential_alias: nil)
|
|
332
|
+
signals = []
|
|
333
|
+
baseline = @baseline_engine.baseline(agent_id)
|
|
334
|
+
|
|
335
|
+
scope = @scopes[agent_id]
|
|
336
|
+
if scope && scope.strict_mode && !scope.allowed_tools.include?(tool_name)
|
|
337
|
+
signal = AgentAnomalySignal.new(
|
|
338
|
+
type: "unsanctioned_tool", agent_id: agent_id, severity: "critical",
|
|
339
|
+
description: "Agent #{agent_id} invoked unsanctioned tool \"#{tool_name}\". Allowed: [#{scope.allowed_tools.join(', ')}]",
|
|
340
|
+
detected_at: now_ms, details: { tool: tool_name, allowed_tools: scope.allowed_tools },
|
|
341
|
+
)
|
|
342
|
+
signals << signal
|
|
343
|
+
emit_signal(signal)
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
return signals unless baseline
|
|
347
|
+
|
|
348
|
+
# IP-C4.1: Tool invocation scope deviation
|
|
349
|
+
if !baseline.top_tools.empty? && !baseline.top_tools.include?(tool_name)
|
|
350
|
+
signal = AgentAnomalySignal.new(
|
|
351
|
+
type: "scope_deviation", agent_id: agent_id, severity: "medium",
|
|
352
|
+
description: "Agent #{agent_id} invoked tool \"#{tool_name}\" outside its baseline tool set",
|
|
353
|
+
detected_at: now_ms, details: { tool: tool_name, baseline_tools: baseline.top_tools },
|
|
354
|
+
)
|
|
355
|
+
signals << signal
|
|
356
|
+
emit_signal(signal)
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
# IP-C4.3: Data volume anomaly (3σ deviation)
|
|
360
|
+
if data_bytes.positive?
|
|
361
|
+
sessions = @baseline_engine.sessions_for(agent_id)
|
|
362
|
+
volumes = sessions.map(&:total_data_bytes)
|
|
363
|
+
if @baseline_engine.is_3_sigma_deviation?(volumes, data_bytes)
|
|
364
|
+
signal = AgentAnomalySignal.new(
|
|
365
|
+
type: "data_volume_anomaly", agent_id: agent_id, severity: "high",
|
|
366
|
+
description: "Agent #{agent_id} data volume #{data_bytes}B is 3σ deviation from baseline avg #{baseline.avg_data_volume_bytes.round}B",
|
|
367
|
+
detected_at: now_ms, details: { data_bytes: data_bytes, baseline_avg: baseline.avg_data_volume_bytes },
|
|
368
|
+
)
|
|
369
|
+
signals << signal
|
|
370
|
+
emit_signal(signal)
|
|
371
|
+
end
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
# IP-C4.4: Cross-agent credential sharing detection
|
|
375
|
+
if credential_alias
|
|
376
|
+
agents = (@credential_usage[credential_alias] ||= [])
|
|
377
|
+
agents << agent_id unless agents.include?(agent_id)
|
|
378
|
+
|
|
379
|
+
if agents.size > 1
|
|
380
|
+
signal = AgentAnomalySignal.new(
|
|
381
|
+
type: "cross_agent_credential_sharing", agent_id: agent_id, severity: "critical",
|
|
382
|
+
description: "Credential #{credential_alias[0, 16]}... shared across #{agents.size} agents: [#{agents.join(', ')}]",
|
|
383
|
+
detected_at: now_ms, details: { credential_alias: "#{credential_alias[0, 16]}...", sharing_agents: agents.dup },
|
|
384
|
+
)
|
|
385
|
+
signals << signal
|
|
386
|
+
emit_signal(signal)
|
|
387
|
+
end
|
|
388
|
+
end
|
|
389
|
+
|
|
390
|
+
signals
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# Analyze a completed session for sequence entropy anomaly (IP-C4.1).
|
|
394
|
+
def analyze_session(record)
|
|
395
|
+
signals = []
|
|
396
|
+
baseline = @baseline_engine.baseline(record.agent_id)
|
|
397
|
+
return signals if !baseline || baseline.total_sessions < 5
|
|
398
|
+
|
|
399
|
+
session_tools = record.tool_calls.map { |tc| tc[:tool] || tc["tool"] }
|
|
400
|
+
session_entropy = DevFortress.shannon_entropy(session_tools)
|
|
401
|
+
entropy_deviation = (session_entropy - baseline.tool_diversity_entropy).abs
|
|
402
|
+
|
|
403
|
+
if baseline.tool_diversity_entropy.positive? && (entropy_deviation / baseline.tool_diversity_entropy) > 0.5
|
|
404
|
+
deviation_percent = (entropy_deviation / baseline.tool_diversity_entropy) * 100
|
|
405
|
+
signal = AgentAnomalySignal.new(
|
|
406
|
+
type: "sequence_entropy_anomaly", agent_id: record.agent_id, severity: "high",
|
|
407
|
+
description: format("Agent %s session entropy %.2f deviates %d%% from baseline %.2f", record.agent_id, session_entropy, deviation_percent.round, baseline.tool_diversity_entropy),
|
|
408
|
+
detected_at: now_ms, details: { session_entropy: session_entropy, baseline_entropy: baseline.tool_diversity_entropy, deviation_percent: deviation_percent },
|
|
409
|
+
)
|
|
410
|
+
signals << signal
|
|
411
|
+
emit_signal(signal)
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
signals
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
private
|
|
418
|
+
|
|
419
|
+
def emit_signal(signal)
|
|
420
|
+
@anomaly_handlers.each do |handler|
|
|
421
|
+
handler.call(signal)
|
|
422
|
+
rescue StandardError
|
|
423
|
+
# Handler errors don't block detection
|
|
424
|
+
end
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
def now_ms
|
|
428
|
+
(Time.now.to_f * 1000).to_i
|
|
429
|
+
end
|
|
430
|
+
end
|
|
431
|
+
end
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "uri"
|
|
5
|
+
require_relative "transport"
|
|
6
|
+
require_relative "version"
|
|
7
|
+
|
|
8
|
+
module DevFortress
|
|
9
|
+
# Alias binding verification helper.
|
|
10
|
+
#
|
|
11
|
+
# Thin HTTP transport for POST /api/aliases/[id]/verify. All binding
|
|
12
|
+
# checks run server-side; nothing is evaluated locally. Retry behaviour
|
|
13
|
+
# matches Client: exponential backoff on 5xx and network errors only,
|
|
14
|
+
# never on 4xx. Mirrors
|
|
15
|
+
# packages/devfortress-sdk/src/alias-verify.ts.
|
|
16
|
+
class AliasVerifyError < StandardError
|
|
17
|
+
attr_reader :http_status, :body
|
|
18
|
+
|
|
19
|
+
def initialize(message, http_status: nil, body: nil)
|
|
20
|
+
super(message)
|
|
21
|
+
@http_status = http_status
|
|
22
|
+
@body = body
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
module AliasVerify
|
|
27
|
+
DEFAULT_BASE_URL = "https://www.devfortress.net"
|
|
28
|
+
DEFAULT_TIMEOUT = 15
|
|
29
|
+
DEFAULT_RETRIES = 3
|
|
30
|
+
MAX_BASE_URL_LENGTH = 2048
|
|
31
|
+
|
|
32
|
+
# Strip trailing slashes without a regex. `%r{/+\z}` is unanchored at
|
|
33
|
+
# the start, so on input that never matches (no trailing slash) the
|
|
34
|
+
# engine retries the same backtrack at every `/` run in the string —
|
|
35
|
+
# polynomial on a long run of slashes followed by a non-slash
|
|
36
|
+
# character. A plain loop is O(n) regardless. Mirrors
|
|
37
|
+
# packages/devfortress-sdk/src/alias-verify.ts.
|
|
38
|
+
def self.strip_trailing_slashes(value)
|
|
39
|
+
value = value.dup
|
|
40
|
+
value.chop! while value.end_with?("/")
|
|
41
|
+
value
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Verify an alias's observed context against its recorded binding.
|
|
45
|
+
# Resolves for 200 and 403 responses (the platform's normal verdicts).
|
|
46
|
+
# Raises AliasVerifyError for 400/401 and for 5xx/network failures
|
|
47
|
+
# once retries are exhausted.
|
|
48
|
+
def self.verify_alias_binding(alias_id, alias_key, context, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT,
|
|
49
|
+
retries: DEFAULT_RETRIES, transport: nil, sleeper: nil)
|
|
50
|
+
raise ArgumentError, "verify_alias_binding: alias_id is required" if alias_id.nil? || alias_id.empty?
|
|
51
|
+
raise ArgumentError, "verify_alias_binding: alias_key is required" if alias_key.nil? || alias_key.empty?
|
|
52
|
+
|
|
53
|
+
raw_base = base_url || DEFAULT_BASE_URL
|
|
54
|
+
raise ArgumentError, "verify_alias_binding: base_url exceeds maximum allowed length" if raw_base.length > MAX_BASE_URL_LENGTH
|
|
55
|
+
|
|
56
|
+
base = strip_trailing_slashes(raw_base)
|
|
57
|
+
transport ||= Transport.new
|
|
58
|
+
sleeper ||= ->(seconds) { sleep(seconds) if seconds.positive? }
|
|
59
|
+
url = "#{base}/api/aliases/#{URI.encode_www_form_component(alias_id)}/verify"
|
|
60
|
+
raw = JSON.generate({ "aliasKey" => alias_key, "context" => context })
|
|
61
|
+
headers = { "Content-Type" => "application/json", "X-DevFortress-SDK-Version" => VERSION }
|
|
62
|
+
|
|
63
|
+
attempt = 1
|
|
64
|
+
loop do
|
|
65
|
+
begin
|
|
66
|
+
response = transport.send_request("POST", url, headers, raw, timeout)
|
|
67
|
+
data = begin
|
|
68
|
+
response.body.to_s.empty? ? {} : JSON.parse(response.body)
|
|
69
|
+
rescue JSON::ParserError
|
|
70
|
+
{}
|
|
71
|
+
end
|
|
72
|
+
status = response.status_code
|
|
73
|
+
|
|
74
|
+
return { "httpStatus" => status, "violations" => [] }.merge(data) if [200, 403].include?(status)
|
|
75
|
+
|
|
76
|
+
message = data["error"] || "Alias verification failed with status #{status}"
|
|
77
|
+
raise AliasVerifyError.new(message, http_status: status, body: data) if status < 500 || attempt >= retries
|
|
78
|
+
rescue TransportError => e
|
|
79
|
+
raise AliasVerifyError.new("Alias verification request failed: #{e.message}") if attempt >= retries
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
sleeper.call(2**attempt)
|
|
83
|
+
attempt += 1
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|