@aigis-ai/cli 1.0.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.
- package/LICENSE +21 -0
- package/README.md +204 -0
- package/SKILL.md +74 -0
- package/bin/aigis.js +337 -0
- package/content/implement/audit-logging.md +171 -0
- package/content/implement/bias-monitoring.md +172 -0
- package/content/implement/confidence-scoring.md +180 -0
- package/content/implement/data-integrity.md +257 -0
- package/content/implement/explainability.md +174 -0
- package/content/implement/fallback-patterns.md +190 -0
- package/content/implement/human-oversight.md +220 -0
- package/content/implement/input-validation.md +212 -0
- package/content/implement/monitoring.md +207 -0
- package/content/implement/output-sanitization.md +183 -0
- package/content/implement/pii-handling.md +207 -0
- package/content/implement/prompt-security.md +153 -0
- package/content/implement/rag-security.md +230 -0
- package/content/implement/rate-limiting.md +217 -0
- package/content/implement/supply-chain.md +193 -0
- package/content/index/audit-scan.md +403 -0
- package/content/index/frameworks.md +82 -0
- package/content/index/guardrails.json +23 -0
- package/content/index/taxonomy.md +81 -0
- package/content/templates/ai-impact-assessment.md +54 -0
- package/content/templates/intended-purpose-doc.md +39 -0
- package/content/templates/risk-characterization.md +34 -0
- package/content/templates/third-party-assessment.md +41 -0
- package/content/verify/checklist-audit-logging.md +13 -0
- package/content/verify/checklist-bias-monitoring.md +13 -0
- package/content/verify/checklist-confidence-scoring.md +13 -0
- package/content/verify/checklist-data-integrity.md +12 -0
- package/content/verify/checklist-explainability.md +13 -0
- package/content/verify/checklist-fallback-patterns.md +13 -0
- package/content/verify/checklist-human-oversight.md +14 -0
- package/content/verify/checklist-input-validation.md +16 -0
- package/content/verify/checklist-monitoring.md +13 -0
- package/content/verify/checklist-output-sanitization.md +14 -0
- package/content/verify/checklist-pii-handling.md +14 -0
- package/content/verify/checklist-prompt-security.md +13 -0
- package/content/verify/checklist-rag-security.md +12 -0
- package/content/verify/checklist-rate-limiting.md +13 -0
- package/content/verify/checklist-supply-chain.md +13 -0
- package/lib/annotate.js +53 -0
- package/lib/classify.js +185 -0
- package/lib/fetch.js +112 -0
- package/lib/init.js +122 -0
- package/lib/keywords.js +139 -0
- package/lib/search.js +76 -0
- package/package.json +35 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: rag-security
|
|
3
|
+
title: RAG and embedding security
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM08]
|
|
6
|
+
nist: [MEASURE-2.7]
|
|
7
|
+
iso42001: [Clause-8.2, Annex-A.7]
|
|
8
|
+
min_risk_tier: all
|
|
9
|
+
system_traits: [uses-rag]
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## What this addresses
|
|
13
|
+
|
|
14
|
+
OWASP LLM08 (new in 2025) covers vulnerabilities in retrieval-augmented generation systems: poisoned embeddings, unauthorized access to vector databases, manipulation of similarity search, and data leakage through embedding inversion.
|
|
15
|
+
|
|
16
|
+
## Implementation patterns
|
|
17
|
+
|
|
18
|
+
### Pattern 1: Access control on vector databases
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
class SecureVectorStore:
|
|
22
|
+
def query(self, embedding: list, user_context: dict, top_k: int = 5) -> list:
|
|
23
|
+
# Apply access control filters BEFORE similarity search
|
|
24
|
+
access_filter = self.build_access_filter(user_context)
|
|
25
|
+
results = self.vector_db.search(
|
|
26
|
+
vector=embedding,
|
|
27
|
+
filter=access_filter,
|
|
28
|
+
limit=top_k
|
|
29
|
+
)
|
|
30
|
+
# Audit log every retrieval
|
|
31
|
+
log_event("vector_query", user=user_context["user_id"],
|
|
32
|
+
results_count=len(results), filter_applied=access_filter)
|
|
33
|
+
return results
|
|
34
|
+
|
|
35
|
+
def build_access_filter(self, user_context: dict) -> dict:
|
|
36
|
+
return {
|
|
37
|
+
"department": {"$in": user_context["allowed_departments"]},
|
|
38
|
+
"classification": {"$lte": user_context["clearance_level"]}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
class SecureVectorStore {
|
|
44
|
+
async query(embedding, userContext, topK = 5) {
|
|
45
|
+
const accessFilter = this.buildAccessFilter(userContext);
|
|
46
|
+
const results = await this.vectorDb.search({
|
|
47
|
+
vector: embedding,
|
|
48
|
+
filter: accessFilter,
|
|
49
|
+
limit: topK,
|
|
50
|
+
});
|
|
51
|
+
logEvent('vector_query', {
|
|
52
|
+
user: userContext.userId,
|
|
53
|
+
resultsCount: results.length,
|
|
54
|
+
filterApplied: accessFilter,
|
|
55
|
+
});
|
|
56
|
+
return results;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
buildAccessFilter(userContext) {
|
|
60
|
+
return {
|
|
61
|
+
department: { $in: userContext.allowedDepartments },
|
|
62
|
+
classification: { $lte: userContext.clearanceLevel },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
### Pattern 2: Multi-tenant isolation
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
class MultiTenantVectorStore:
|
|
73
|
+
def upsert(self, tenant_id: str, documents: list):
|
|
74
|
+
for doc in documents:
|
|
75
|
+
doc["metadata"]["tenant_id"] = tenant_id
|
|
76
|
+
self.vector_db.upsert(documents)
|
|
77
|
+
|
|
78
|
+
def query(self, tenant_id: str, embedding: list, top_k: int = 5) -> list:
|
|
79
|
+
# ALWAYS filter by tenant — never allow cross-tenant retrieval
|
|
80
|
+
return self.vector_db.search(
|
|
81
|
+
vector=embedding,
|
|
82
|
+
filter={"tenant_id": tenant_id},
|
|
83
|
+
limit=top_k
|
|
84
|
+
)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
```javascript
|
|
88
|
+
class MultiTenantVectorStore {
|
|
89
|
+
async upsert(tenantId, documents) {
|
|
90
|
+
for (const doc of documents) {
|
|
91
|
+
doc.metadata.tenantId = tenantId;
|
|
92
|
+
}
|
|
93
|
+
await this.vectorDb.upsert(documents);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async query(tenantId, embedding, topK = 5) {
|
|
97
|
+
// ALWAYS filter by tenant
|
|
98
|
+
return this.vectorDb.search({
|
|
99
|
+
vector: embedding,
|
|
100
|
+
filter: { tenantId },
|
|
101
|
+
limit: topK,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
### Pattern 3: Retrieved context validation
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
def validate_retrieved_context(results: list, query: str) -> list:
|
|
112
|
+
"""Filter out suspicious or irrelevant retrieval results."""
|
|
113
|
+
validated = []
|
|
114
|
+
for result in results:
|
|
115
|
+
# Check relevance score threshold
|
|
116
|
+
if result["score"] < MIN_RELEVANCE_SCORE:
|
|
117
|
+
continue
|
|
118
|
+
# Check for injection patterns in retrieved content
|
|
119
|
+
if check_injection_patterns(result["content"])["flagged"]:
|
|
120
|
+
log_security_event("suspicious_retrieval", doc_id=result["id"])
|
|
121
|
+
continue
|
|
122
|
+
# Verify document is still current
|
|
123
|
+
if result["metadata"].get("expires_at") and result["metadata"]["expires_at"] < now():
|
|
124
|
+
continue
|
|
125
|
+
validated.append(result)
|
|
126
|
+
return validated
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
```javascript
|
|
130
|
+
function validateRetrievedContext(results, query) {
|
|
131
|
+
return results.filter(result => {
|
|
132
|
+
if (result.score < MIN_RELEVANCE_SCORE) return false;
|
|
133
|
+
if (checkInjectionPatterns(result.content).flagged) {
|
|
134
|
+
logSecurityEvent('suspicious_retrieval', { docId: result.id });
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
if (result.metadata.expiresAt && new Date(result.metadata.expiresAt) < new Date())
|
|
138
|
+
return false;
|
|
139
|
+
return true;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
### Pattern 4: Embedding endpoint access control
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
class SecureEmbeddingService:
|
|
150
|
+
def embed(self, text: str, user_context: dict) -> list:
|
|
151
|
+
"""Only authorized users can generate embeddings."""
|
|
152
|
+
if not self.authorize(user_context, "embed"):
|
|
153
|
+
log_security_event("unauthorized_embed_attempt", user=user_context["user_id"])
|
|
154
|
+
raise PermissionError("Not authorized to generate embeddings")
|
|
155
|
+
embedding = self.model.encode(text)
|
|
156
|
+
log_event("embedding_generated", user=user_context["user_id"],
|
|
157
|
+
text_hash=hashlib.sha256(text.encode()).hexdigest())
|
|
158
|
+
return embedding
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
```javascript
|
|
162
|
+
class SecureEmbeddingService {
|
|
163
|
+
async embed(text, userContext) {
|
|
164
|
+
if (!this.authorize(userContext, 'embed')) {
|
|
165
|
+
logSecurityEvent('unauthorized_embed_attempt', { user: userContext.userId });
|
|
166
|
+
throw new Error('Not authorized to generate embeddings');
|
|
167
|
+
}
|
|
168
|
+
const embedding = await this.model.encode(text);
|
|
169
|
+
logEvent('embedding_generated', {
|
|
170
|
+
user: userContext.userId,
|
|
171
|
+
textHash: crypto.createHash('sha256').update(text).digest('hex'),
|
|
172
|
+
});
|
|
173
|
+
return embedding;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Pattern 5: Document permission inheritance
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
def embed_with_permissions(document: dict, source_permissions: dict) -> dict:
|
|
182
|
+
"""Embeddings inherit the access permissions of their source documents."""
|
|
183
|
+
embedding = embed_model.encode(document["content"])
|
|
184
|
+
return {
|
|
185
|
+
"embedding": embedding,
|
|
186
|
+
"metadata": {
|
|
187
|
+
"source_doc_id": document["id"],
|
|
188
|
+
"source_chunk": document.get("chunk_index"),
|
|
189
|
+
"permissions": source_permissions, # Inherited from source
|
|
190
|
+
"department": source_permissions.get("department"),
|
|
191
|
+
"classification": source_permissions.get("classification"),
|
|
192
|
+
"embedded_at": datetime.utcnow().isoformat(),
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
```javascript
|
|
198
|
+
async function embedWithPermissions(document, sourcePermissions) {
|
|
199
|
+
const embedding = await embedModel.encode(document.content);
|
|
200
|
+
return {
|
|
201
|
+
embedding,
|
|
202
|
+
metadata: {
|
|
203
|
+
sourceDocId: document.id,
|
|
204
|
+
sourceChunk: document.chunkIndex,
|
|
205
|
+
permissions: sourcePermissions,
|
|
206
|
+
department: sourcePermissions.department,
|
|
207
|
+
classification: sourcePermissions.classification,
|
|
208
|
+
embeddedAt: new Date().toISOString(),
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## Anti-patterns
|
|
215
|
+
|
|
216
|
+
- **No tenant isolation in multi-tenant RAG.** Always filter by tenant ID.
|
|
217
|
+
- **Returning all results regardless of relevance score.** Set minimum thresholds.
|
|
218
|
+
- **No access control on the vector database.** Apply the same access controls as the source data.
|
|
219
|
+
|
|
220
|
+
## Related files
|
|
221
|
+
|
|
222
|
+
- **data-integrity.md:** All data entering the RAG pipeline must be validated using data-integrity.md Pattern 2 (RAG data validation pipeline) before embedding. RAG security controls access to the vector store; data integrity controls what goes into it.
|
|
223
|
+
- **input-validation.md:** Retrieved context can contain injection payloads. Apply input-validation.md Pattern 5 (injection pattern detection) to retrieved documents, not just direct user input. Pattern 3 of this file handles this but the injection patterns come from input-validation.
|
|
224
|
+
- **pii-handling.md:** Documents in the vector store may contain PII. Apply pii-handling.md Pattern 1 (PII redaction) before embedding documents, or ensure access controls (Pattern 1 of this file) prevent unauthorized PII retrieval.
|
|
225
|
+
|
|
226
|
+
## Edge cases
|
|
227
|
+
|
|
228
|
+
- **Embedding inversion attacks.** Attackers reconstructing source text from embeddings. Use access controls on embedding endpoints.
|
|
229
|
+
- **Cross-collection leakage.** Ensure collections with different sensitivity levels are isolated.
|
|
230
|
+
- **Stale embeddings.** When source documents are updated or deleted, embeddings must be updated too.
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: rate-limiting
|
|
3
|
+
title: Rate limiting and resource control
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM10]
|
|
6
|
+
nist: [MEASURE-2.6, MANAGE-2.4]
|
|
7
|
+
iso42001: [Clause-8.2]
|
|
8
|
+
min_risk_tier: all
|
|
9
|
+
system_traits: [is-external, is-high-volume, is-agentic]
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## What this addresses
|
|
13
|
+
|
|
14
|
+
OWASP LLM10 covers unbounded consumption — excessive resource usage leading to denial of service, financial exploitation ("denial of wallet"), or model theft through extraction attacks.
|
|
15
|
+
|
|
16
|
+
## Implementation patterns
|
|
17
|
+
|
|
18
|
+
### Pattern 1: Per-user rate limiting
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from functools import wraps
|
|
22
|
+
import time
|
|
23
|
+
|
|
24
|
+
class RateLimiter:
|
|
25
|
+
def __init__(self, max_requests: int, window_seconds: int):
|
|
26
|
+
self.max_requests = max_requests
|
|
27
|
+
self.window_seconds = window_seconds
|
|
28
|
+
self.requests = {} # user_id -> [timestamps]
|
|
29
|
+
|
|
30
|
+
def check(self, user_id: str) -> bool:
|
|
31
|
+
now = time.time()
|
|
32
|
+
user_requests = self.requests.get(user_id, [])
|
|
33
|
+
# Remove expired entries
|
|
34
|
+
user_requests = [t for t in user_requests if now - t < self.window_seconds]
|
|
35
|
+
if len(user_requests) >= self.max_requests:
|
|
36
|
+
return False
|
|
37
|
+
user_requests.append(now)
|
|
38
|
+
self.requests[user_id] = user_requests
|
|
39
|
+
return True
|
|
40
|
+
|
|
41
|
+
# Configure per endpoint
|
|
42
|
+
api_limiter = RateLimiter(max_requests=60, window_seconds=60)
|
|
43
|
+
llm_limiter = RateLimiter(max_requests=20, window_seconds=60)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```javascript
|
|
47
|
+
class RateLimiter {
|
|
48
|
+
constructor(maxRequests, windowSeconds) {
|
|
49
|
+
this.maxRequests = maxRequests;
|
|
50
|
+
this.windowSeconds = windowSeconds;
|
|
51
|
+
this.requests = new Map();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
check(userId) {
|
|
55
|
+
const now = Date.now() / 1000;
|
|
56
|
+
const userRequests = (this.requests.get(userId) || [])
|
|
57
|
+
.filter(t => now - t < this.windowSeconds);
|
|
58
|
+
if (userRequests.length >= this.maxRequests) return false;
|
|
59
|
+
userRequests.push(now);
|
|
60
|
+
this.requests.set(userId, userRequests);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const apiLimiter = new RateLimiter(60, 60);
|
|
66
|
+
const llmLimiter = new RateLimiter(20, 60);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
### Pattern 2: Token budget enforcement
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
class TokenBudget:
|
|
74
|
+
def __init__(self, daily_limit: int, per_request_limit: int):
|
|
75
|
+
self.daily_limit = daily_limit
|
|
76
|
+
self.per_request_limit = per_request_limit
|
|
77
|
+
|
|
78
|
+
def check_and_deduct(self, user_id: str, estimated_tokens: int) -> bool:
|
|
79
|
+
if estimated_tokens > self.per_request_limit:
|
|
80
|
+
return False
|
|
81
|
+
daily_usage = self.get_daily_usage(user_id)
|
|
82
|
+
if daily_usage + estimated_tokens > self.daily_limit:
|
|
83
|
+
log_event("daily_token_limit_reached", user=user_id)
|
|
84
|
+
return False
|
|
85
|
+
self.record_usage(user_id, estimated_tokens)
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
budget = TokenBudget(daily_limit=100_000, per_request_limit=4_000)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```javascript
|
|
92
|
+
class TokenBudget {
|
|
93
|
+
constructor(dailyLimit, perRequestLimit) {
|
|
94
|
+
this.dailyLimit = dailyLimit;
|
|
95
|
+
this.perRequestLimit = perRequestLimit;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async checkAndDeduct(userId, estimatedTokens) {
|
|
99
|
+
if (estimatedTokens > this.perRequestLimit) return false;
|
|
100
|
+
const dailyUsage = await this.getDailyUsage(userId);
|
|
101
|
+
if (dailyUsage + estimatedTokens > this.dailyLimit) {
|
|
102
|
+
logEvent('daily_token_limit_reached', { user: userId });
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
await this.recordUsage(userId, estimatedTokens);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
### Pattern 3: Cost monitoring and alerting
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
class CostMonitor:
|
|
116
|
+
def __init__(self, hourly_budget: float, daily_budget: float):
|
|
117
|
+
self.hourly_budget = hourly_budget
|
|
118
|
+
self.daily_budget = daily_budget
|
|
119
|
+
|
|
120
|
+
def record_and_check(self, cost: float) -> dict:
|
|
121
|
+
self.record(cost)
|
|
122
|
+
hourly_total = self.get_hourly_total()
|
|
123
|
+
daily_total = self.get_daily_total()
|
|
124
|
+
|
|
125
|
+
alerts = []
|
|
126
|
+
if hourly_total > self.hourly_budget * 0.8:
|
|
127
|
+
alerts.append({"level": "warning", "message": f"80% of hourly budget used: {hourly_total:.2f}"})
|
|
128
|
+
if hourly_total > self.hourly_budget:
|
|
129
|
+
alerts.append({"level": "critical", "message": "Hourly budget exceeded — throttling"})
|
|
130
|
+
self.enable_throttle()
|
|
131
|
+
if daily_total > self.daily_budget:
|
|
132
|
+
alerts.append({"level": "emergency", "message": "Daily budget exceeded — circuit breaker"})
|
|
133
|
+
self.trip_circuit_breaker()
|
|
134
|
+
|
|
135
|
+
return {"cost": cost, "hourly_total": hourly_total, "daily_total": daily_total, "alerts": alerts}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
```javascript
|
|
139
|
+
class CostMonitor {
|
|
140
|
+
constructor(hourlyBudget, dailyBudget) {
|
|
141
|
+
this.hourlyBudget = hourlyBudget;
|
|
142
|
+
this.dailyBudget = dailyBudget;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async recordAndCheck(cost) {
|
|
146
|
+
await this.record(cost);
|
|
147
|
+
const hourlyTotal = await this.getHourlyTotal();
|
|
148
|
+
const dailyTotal = await this.getDailyTotal();
|
|
149
|
+
const alerts = [];
|
|
150
|
+
if (hourlyTotal > this.hourlyBudget * 0.8)
|
|
151
|
+
alerts.push({ level: 'warning', message: '80% of hourly budget used' });
|
|
152
|
+
if (hourlyTotal > this.hourlyBudget) {
|
|
153
|
+
alerts.push({ level: 'critical', message: 'Hourly budget exceeded' });
|
|
154
|
+
await this.enableThrottle();
|
|
155
|
+
}
|
|
156
|
+
if (dailyTotal > this.dailyBudget) {
|
|
157
|
+
alerts.push({ level: 'emergency', message: 'Daily budget exceeded' });
|
|
158
|
+
await this.tripCircuitBreaker();
|
|
159
|
+
}
|
|
160
|
+
return { cost, hourlyTotal, dailyTotal, alerts };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
### Pattern 4: Request timeout
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
import asyncio
|
|
170
|
+
|
|
171
|
+
async def call_llm_with_timeout(messages: list, timeout: int = 30) -> dict:
|
|
172
|
+
try:
|
|
173
|
+
result = await asyncio.wait_for(
|
|
174
|
+
client.chat.completions.create(model=MODEL, messages=messages),
|
|
175
|
+
timeout=timeout
|
|
176
|
+
)
|
|
177
|
+
return {"success": True, "result": result}
|
|
178
|
+
except asyncio.TimeoutError:
|
|
179
|
+
log_event("llm_timeout", timeout=timeout)
|
|
180
|
+
return {"success": False, "error": "timeout", "fallback": default_safe_response()}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
```javascript
|
|
184
|
+
async function callLlmWithTimeout(messages, timeout = 30000) {
|
|
185
|
+
const controller = new AbortController();
|
|
186
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
187
|
+
try {
|
|
188
|
+
const result = await client.chat.completions.create(
|
|
189
|
+
{ model: MODEL, messages },
|
|
190
|
+
{ signal: controller.signal }
|
|
191
|
+
);
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
return { success: true, result };
|
|
194
|
+
} catch (e) {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
if (e.name === 'AbortError') {
|
|
197
|
+
logEvent('llm_timeout', { timeout });
|
|
198
|
+
return { success: false, error: 'timeout', fallback: defaultSafeResponse() };
|
|
199
|
+
}
|
|
200
|
+
throw e;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
## Anti-patterns
|
|
207
|
+
|
|
208
|
+
- **No rate limits on LLM endpoints.** Every endpoint must have limits.
|
|
209
|
+
- **Same limits for all users.** Tier your limits by user role and subscription.
|
|
210
|
+
- **No cost monitoring.** LLM costs can spike unexpectedly. Monitor and alert.
|
|
211
|
+
- **Unlimited context windows.** Cap the conversation history sent to the LLM.
|
|
212
|
+
|
|
213
|
+
## Edge cases
|
|
214
|
+
|
|
215
|
+
- **Distributed attacks.** Rate limit by API key, not just IP address.
|
|
216
|
+
- **Legitimate burst traffic.** Allow temporary bursts with backpressure, don't hard-block.
|
|
217
|
+
- **Cost estimation accuracy.** Token counts for prompts and completions differ. Estimate both.
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: supply-chain
|
|
3
|
+
title: Supply chain and third-party AI management
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM03]
|
|
6
|
+
nist: [GOVERN-6.1, GOVERN-6.2, MANAGE-3.1, MANAGE-3.2]
|
|
7
|
+
iso42001: [Annex-A.10]
|
|
8
|
+
min_risk_tier: all
|
|
9
|
+
system_traits: [uses-thirdparty-api, uses-finetuned]
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## What this addresses
|
|
13
|
+
|
|
14
|
+
OWASP LLM03 covers supply chain risks: the LLM provider, fine-tuning data, plugins, and pre-built components. When you depend on a third-party model API, you inherit their risks. Model updates can change behavior. Service outages affect your availability. Terms of service changes affect your compliance.
|
|
15
|
+
|
|
16
|
+
## Implementation patterns
|
|
17
|
+
|
|
18
|
+
### Pattern 1: Pin model versions
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
# CORRECT: pin to specific version
|
|
22
|
+
response = client.chat.completions.create(
|
|
23
|
+
model="gpt-4o-2024-11-20", # Specific version, not "gpt-4o"
|
|
24
|
+
messages=messages
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# WRONG: floating version
|
|
28
|
+
response = client.chat.completions.create(
|
|
29
|
+
model="gpt-4o", # Could change behavior without warning
|
|
30
|
+
messages=messages
|
|
31
|
+
)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```javascript
|
|
35
|
+
// CORRECT: pin to specific version
|
|
36
|
+
const response = await client.chat.completions.create({
|
|
37
|
+
model: 'gpt-4o-2024-11-20', // Specific version
|
|
38
|
+
messages,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// WRONG: floating version
|
|
42
|
+
// model: 'gpt-4o', // Could change behavior without warning
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
### Pattern 2: Model version tracking in responses
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
def call_llm(messages: list, metadata: dict) -> dict:
|
|
50
|
+
response = client.chat.completions.create(
|
|
51
|
+
model=PINNED_MODEL_VERSION,
|
|
52
|
+
messages=messages
|
|
53
|
+
)
|
|
54
|
+
return {
|
|
55
|
+
"content": response.choices[0].message.content,
|
|
56
|
+
"model_version": PINNED_MODEL_VERSION,
|
|
57
|
+
"provider": "openai",
|
|
58
|
+
"response_id": response.id,
|
|
59
|
+
"timestamp": datetime.utcnow().isoformat(),
|
|
60
|
+
"trace_id": metadata["trace_id"]
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```javascript
|
|
65
|
+
async function callLlm(messages, metadata) {
|
|
66
|
+
const response = await client.chat.completions.create({
|
|
67
|
+
model: PINNED_MODEL_VERSION,
|
|
68
|
+
messages,
|
|
69
|
+
});
|
|
70
|
+
return {
|
|
71
|
+
content: response.choices[0].message.content,
|
|
72
|
+
modelVersion: PINNED_MODEL_VERSION,
|
|
73
|
+
provider: 'openai',
|
|
74
|
+
responseId: response.id,
|
|
75
|
+
timestamp: new Date().toISOString(),
|
|
76
|
+
traceId: metadata.traceId,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
### Pattern 3: Regression testing before model upgrades
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
class ModelUpgradeValidator:
|
|
86
|
+
def __init__(self, test_suite_path: str, threshold: float = 0.95):
|
|
87
|
+
self.test_cases = load_test_suite(test_suite_path)
|
|
88
|
+
self.threshold = threshold
|
|
89
|
+
|
|
90
|
+
def validate_new_version(self, new_model: str, current_model: str) -> dict:
|
|
91
|
+
current_results = self.run_suite(current_model)
|
|
92
|
+
new_results = self.run_suite(new_model)
|
|
93
|
+
|
|
94
|
+
agreement_rate = self.compare_results(current_results, new_results)
|
|
95
|
+
regression_cases = self.find_regressions(current_results, new_results)
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
"approved": agreement_rate >= self.threshold and len(regression_cases) == 0,
|
|
99
|
+
"agreement_rate": agreement_rate,
|
|
100
|
+
"regressions": regression_cases,
|
|
101
|
+
"recommendation": "approve" if agreement_rate >= self.threshold else "review_required"
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
```javascript
|
|
106
|
+
class ModelUpgradeValidator {
|
|
107
|
+
constructor(testSuitePath, threshold = 0.95) {
|
|
108
|
+
this.testCases = loadTestSuite(testSuitePath);
|
|
109
|
+
this.threshold = threshold;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async validateNewVersion(newModel, currentModel) {
|
|
113
|
+
const currentResults = await this.runSuite(currentModel);
|
|
114
|
+
const newResults = await this.runSuite(newModel);
|
|
115
|
+
const agreementRate = this.compareResults(currentResults, newResults);
|
|
116
|
+
const regressions = this.findRegressions(currentResults, newResults);
|
|
117
|
+
return {
|
|
118
|
+
approved: agreementRate >= this.threshold && regressions.length === 0,
|
|
119
|
+
agreementRate,
|
|
120
|
+
regressions,
|
|
121
|
+
recommendation: agreementRate >= this.threshold ? 'approve' : 'review_required',
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
### Pattern 4: Fallback provider configuration
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
PROVIDER_CONFIG = {
|
|
132
|
+
"primary": {"provider": "anthropic", "model": "claude-sonnet-4-20250514", "timeout": 30},
|
|
133
|
+
"fallback": {"provider": "openai", "model": "gpt-4o-2024-11-20", "timeout": 30},
|
|
134
|
+
"emergency": {"provider": "local", "model": "rules-based-fallback", "timeout": 5}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async def call_with_fallback(messages: list) -> dict:
|
|
138
|
+
for tier in ["primary", "fallback", "emergency"]:
|
|
139
|
+
try:
|
|
140
|
+
config = PROVIDER_CONFIG[tier]
|
|
141
|
+
result = await call_provider(config, messages, timeout=config["timeout"])
|
|
142
|
+
result["provider_tier"] = tier
|
|
143
|
+
if tier != "primary":
|
|
144
|
+
log_event("fallback_activated", tier=tier)
|
|
145
|
+
return result
|
|
146
|
+
except (TimeoutError, ProviderError) as e:
|
|
147
|
+
log_event("provider_failure", tier=tier, error=str(e))
|
|
148
|
+
continue
|
|
149
|
+
raise ServiceUnavailable("All providers failed")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```javascript
|
|
153
|
+
const PROVIDER_CONFIG = {
|
|
154
|
+
primary: { provider: 'anthropic', model: 'claude-sonnet-4-20250514', timeout: 30000 },
|
|
155
|
+
fallback: { provider: 'openai', model: 'gpt-4o-2024-11-20', timeout: 30000 },
|
|
156
|
+
emergency: { provider: 'local', model: 'rules-based-fallback', timeout: 5000 },
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
async function callWithFallback(messages) {
|
|
160
|
+
for (const tier of ['primary', 'fallback', 'emergency']) {
|
|
161
|
+
try {
|
|
162
|
+
const config = PROVIDER_CONFIG[tier];
|
|
163
|
+
const result = await callProvider(config, messages, config.timeout);
|
|
164
|
+
result.providerTier = tier;
|
|
165
|
+
if (tier !== 'primary') logEvent('fallback_activated', { tier });
|
|
166
|
+
return result;
|
|
167
|
+
} catch (e) {
|
|
168
|
+
logEvent('provider_failure', { tier, error: e.message });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
throw new Error('All providers failed');
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
## Anti-patterns
|
|
177
|
+
|
|
178
|
+
- **Using "latest" or unversioned model identifiers.** Always pin versions.
|
|
179
|
+
- **No fallback for provider outages.** Define degradation behavior.
|
|
180
|
+
- **Trusting provider claims without testing.** Run your own evaluation suite.
|
|
181
|
+
- **No SBOM for AI components.** Track all AI dependencies just like software dependencies.
|
|
182
|
+
|
|
183
|
+
## Related files
|
|
184
|
+
|
|
185
|
+
- **fallback-patterns.md:** When the primary model provider fails, fallback-patterns.md Pattern 2 (circuit breaker) and Pattern 1 (default safe response) define what happens. Supply chain Pattern 4 (fallback provider) should use the circuit breaker to manage the switch.
|
|
186
|
+
- **monitoring.md:** Provider health should be tracked. Use monitoring.md Pattern 1 (key metrics dashboard) to monitor provider latency, error rates, and cost. Set alerts for provider degradation.
|
|
187
|
+
- **audit-logging.md:** Every model call should log the provider and model version. Use audit-logging.md Pattern 1 (structured log entry) with the model_version and provider fields.
|
|
188
|
+
|
|
189
|
+
## Edge cases
|
|
190
|
+
|
|
191
|
+
- **Provider API changes.** API parameters or response formats can change. Pin client library versions too.
|
|
192
|
+
- **Data residency.** Third-party providers may process data in different jurisdictions. Verify data routing.
|
|
193
|
+
- **Model deprecation.** Providers retire models. Monitor deprecation notices and have migration plans.
|