@aigis-ai/cli 1.0.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/SKILL.md +20 -55
  3. package/bin/aigis.js +446 -59
  4. package/cli-python/LICENSE +21 -0
  5. package/cli-python/README.md +32 -0
  6. package/cli-python/aigis_cli/SKILL.md +70 -0
  7. package/cli-python/aigis_cli/__init__.py +3 -0
  8. package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
  9. package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
  10. package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
  11. package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
  12. package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
  13. package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
  14. package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
  15. package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
  16. package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
  17. package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
  18. package/cli-python/aigis_cli/annotate.py +45 -0
  19. package/cli-python/aigis_cli/auto_verify.py +518 -0
  20. package/cli-python/aigis_cli/build.py +470 -0
  21. package/cli-python/aigis_cli/checksum.py +22 -0
  22. package/cli-python/aigis_cli/classify.py +192 -0
  23. package/cli-python/aigis_cli/cli.py +618 -0
  24. package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
  25. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
  26. package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
  27. package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
  28. package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
  29. package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
  30. package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
  31. package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
  32. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
  33. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
  34. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
  35. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
  36. package/cli-python/aigis_cli/content/skills/core.md +62 -0
  37. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
  38. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
  39. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
  40. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
  41. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
  42. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
  43. package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
  44. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
  45. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
  46. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
  47. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
  48. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
  49. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
  50. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
  51. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
  52. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
  53. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
  54. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
  55. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
  56. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
  57. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
  58. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
  59. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
  60. package/cli-python/aigis_cli/fetch.py +232 -0
  61. package/cli-python/aigis_cli/init_ide.py +159 -0
  62. package/cli-python/aigis_cli/keywords.py +73 -0
  63. package/cli-python/aigis_cli/search.py +69 -0
  64. package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
  65. package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
  66. package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
  67. package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
  68. package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
  69. package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
  70. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  71. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  72. package/cli-python/pyproject.toml +49 -0
  73. package/content/index/audit-scan.md +21 -207
  74. package/content/index/auto-verify-rules.json +439 -0
  75. package/content/index/context-rules.json +90 -0
  76. package/content/resolvers/triggers.json +229 -0
  77. package/content/skills/areas/audit-logging.md +176 -0
  78. package/content/skills/areas/bias-monitoring.md +172 -0
  79. package/content/skills/areas/confidence-scoring.md +180 -0
  80. package/content/skills/areas/data-integrity.md +257 -0
  81. package/content/skills/areas/explainability.md +174 -0
  82. package/content/skills/areas/fallback-patterns.md +200 -0
  83. package/content/skills/areas/human-oversight.md +220 -0
  84. package/content/skills/areas/input-validation.md +380 -0
  85. package/content/skills/areas/monitoring.md +207 -0
  86. package/content/skills/areas/output-sanitization.md +183 -0
  87. package/content/skills/areas/pii-handling.md +189 -0
  88. package/content/skills/areas/prompt-security.md +153 -0
  89. package/content/skills/areas/rag-security.md +230 -0
  90. package/content/skills/areas/rate-limiting.md +246 -0
  91. package/content/skills/areas/supply-chain.md +193 -0
  92. package/content/skills/core.md +62 -0
  93. package/content/skills/infrastructure/logging.md +202 -0
  94. package/content/skills/infrastructure/rate-limiting.md +169 -0
  95. package/content/skills/infrastructure/secrets.md +167 -0
  96. package/content/skills/workflows/fastapi-llm.md +86 -0
  97. package/docs/resolvers.md +114 -0
  98. package/lib/auto-verify.js +378 -0
  99. package/lib/build.js +629 -0
  100. package/lib/checksum.js +39 -0
  101. package/lib/fetch.js +164 -9
  102. package/lib/init.js +141 -93
  103. package/lib/keywords.js +92 -130
  104. package/lib/special-recognizers.js +370 -0
  105. package/package.json +1 -1
  106. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  107. package/scripts/bootstrap-step-6-bench.js +85 -0
  108. package/scripts/check-content-sync.js +91 -0
  109. package/scripts/triggers.schema.json +50 -0
  110. package/scripts/validate-triggers.js +176 -0
  111. package/content/implement/fallback-patterns.md +0 -190
  112. package/content/implement/input-validation.md +0 -212
  113. package/content/implement/pii-handling.md +0 -207
  114. package/content/implement/rate-limiting.md +0 -217
  115. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
  116. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
  117. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
  118. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
  119. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
  120. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
  121. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
  122. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
  123. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
  124. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -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,246 @@
1
+ ---
2
+ id: rate-limiting
3
+ title: Rate limiting, token budgets, 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, uses-llm]
10
+ ---
11
+
12
+ LLM endpoints are expensive and easy to abuse. Rate limiting caps per-user request volume, token budgets cap per-user dollar cost, and timeouts cap the damage a hung LLM call can do.
13
+
14
+ <!--
15
+ Procedure-design note (for maintainers, not for agents):
16
+ Step 1 requires a durable backing store unconditionally. Earlier drafts
17
+ allowed in-memory for single-process dev — an agent following that
18
+ variant produced code that cleared the Retry-After overclaim recognizer
19
+ but stayed at rubric Score 5 because the rubric requires durable + cross-
20
+ replica state without carve-outs. The rubric is locked for baseline
21
+ comparison; we tighten the procedure to match it rather than accept a
22
+ ceiling at Score 5. If you loosen this step in the future, re-benchmark
23
+ against the rubric before shipping.
24
+ -->
25
+
26
+ ## Common incomplete implementations
27
+
28
+ 1. **In-memory store.** A per-user bucket held in a Python dict (`defaultdict(deque)`) or JS `Map`. Loses state on restart. Gives every user a fresh quota every deploy. Does not share state across replicas — the same user hits two pods and doubles their quota. Not acceptable, including for dev builds — use Redis locally via docker-compose.
29
+ 2. **No `Retry-After` header.** HTTP 429 responses without `Retry-After` leave clients guessing. Well-behaved clients (including every major LLM SDK retry wrapper) read `Retry-After` to decide when to try again. Without it, clients either thundering-herd retry immediately or give up entirely.
30
+ 3. **Request-count only, no token budget.** An abuser can stay under the request-count limit but still burn through your LLM budget by sending large inputs with large outputs. Token budget is separate from request count and must be enforced separately.
31
+ 4. **No LLM call timeout.** A hung call to the provider can hold a request for minutes, blocking a worker and consuming tokens on the eventual response. Every LLM call must have an explicit, tight timeout.
32
+ 5. **Rate limit keyed on IP only.** NAT'd enterprise users share an IP. Rate-limiting by IP either throttles everyone behind the NAT or you have to set the limit so high that actual abuse gets through. Key on authenticated user or API key first, IP only as a last-resort fallback.
33
+
34
+ ## Implementation procedure
35
+
36
+ ### Step 1 — Use a durable backing store (Redis or DB) ⚠ CRITICAL
37
+
38
+ **What to do.** The rate-limit counter must live in a store that (a) survives process restart, and (b) is shared across replicas. Use Redis (`INCR` + `EXPIRE`, and `TTL` to compute Retry-After) or a DB table with an expiry column. **Do not** use an in-memory `dict`, `defaultdict`, or `deque`, even for a dev build.
39
+
40
+ **Why this matters.** In-memory rate limiting fails in two ways that matter in production: the counter resets on every deploy (attacker gets a fresh quota on every redeploy), and two replicas of the same service can't share state (the attacker doubles their quota by hitting a second pod). Every baseline run silently chose in-memory; the production deployment inherits the limitation. Making the durable choice at build time is cheaper than debugging a rate-limit bypass later.
41
+
42
+ **Verification checkpoint.** `grep -rn "defaultdict\|deque" <rate-limit-module>` — if either match is storing the counter, that's the in-memory anti-pattern. Replace with a Redis client call (the dependency is small, Docker-compose-able for local dev). The benchmark's single-process nature is not a justification for skipping this — the rubric measures production readiness, not development convenience.
43
+
44
+ ### Step 2 — Key on authenticated user first
45
+
46
+ **What to do.** Extract the rate-limit key from the authenticated user ID (`X-User-Id`) or API key (`X-API-Key`) if available. Fall back to IP only if neither is present, and log a warning when you do.
47
+
48
+ **Why this matters.** Shared-IP environments (corporate NAT, mobile carriers) make IP-based rate limiting either too loose or too strict for real users.
49
+
50
+ **Verification checkpoint.** Find the handler using the rate limiter. Confirm the key comes from a header before falling back to IP. See the complete example at the end.
51
+
52
+ ### Step 3 — Return 429 with Retry-After on block ⚠ CRITICAL
53
+
54
+ **What to do.** When the limiter blocks a request, raise a 429 with a `Retry-After` response header whose value is the **actual** number of seconds until the bucket refills. Read it from the store — Redis `TTL` or the DB expiry column. Do not hard-code `Retry-After: 60`.
55
+
56
+ **Why this matters.** Every baseline run returned 429 without `Retry-After`. LLM SDKs and well-behaved HTTP clients use that header to drive retry backoff. Without it, clients either retry immediately (worsening the problem) or give up entirely.
57
+
58
+ ```python
59
+ raise HTTPException(
60
+ status_code=429,
61
+ detail="Rate limit exceeded",
62
+ headers={"Retry-After": str(retry_after)},
63
+ )
64
+ ```
65
+
66
+ **Verification checkpoint.** `grep -rn "status_code=429\|HTTPException(429" --include="*.py"` — every hit must set a `Retry-After` header or route through a helper that does. A 429 without this header is incomplete.
67
+
68
+ ### Step 4 — Separate token budget from request count
69
+
70
+ **What to do.** Track approximate tokens consumed per user per day. Enforce a daily ceiling on tokens independently of the per-window request count. Consume the estimate **before** the LLM call; reconcile with provider-reported actual usage afterward (Anthropic and OpenAI both return token counts).
71
+
72
+ **Why this matters.** Request-count limits cap call frequency but not cost. An abuser sending one huge request per minute stays under a 60-rpm limit while burning your monthly budget.
73
+
74
+ **Verification checkpoint.** `grep -rn "token_budget\|TokenBudget\|daily_token" --include="*.py"` — if no hits, Step 4 is not done. Request-count-only is incomplete.
75
+
76
+ ### Step 5 — Timeout every LLM call
77
+
78
+ **What to do.** Configure a timeout on the LLM client. Do not rely on the SDK default (which is often minutes or unbounded).
79
+
80
+ **Why this matters.** A hung provider call holds a worker and continues to count against rate-limit and token budgets. Tight timeouts keep failures fast and cheap.
81
+
82
+ ```python
83
+ from anthropic import Anthropic
84
+
85
+ client = Anthropic(api_key=..., timeout=30.0) # 30-second ceiling
86
+ ```
87
+
88
+ **Verification checkpoint.** `grep -rn "Anthropic\s*(\|OpenAI\s*(" --include="*.py"` — every client instantiation includes an explicit `timeout=`.
89
+
90
+ ### Step 6 — Verify the 429 response end-to-end
91
+
92
+ **What to do.** Write a test (or execute manually) that exceeds the rate limit and confirms:
93
+
94
+ - Response status is 429
95
+ - Response includes a `Retry-After` header
96
+ - The value of `Retry-After` is a positive integer (seconds), not 0 and not absurdly large
97
+
98
+ **Why this matters.** This is the only test that proves the pieces fit together. An in-code grep can miss that the header is set to `"0"` (a no-op value from a buggy TTL read).
99
+
100
+ ```python
101
+ def test_rate_limit_returns_retry_after():
102
+ # hammer the endpoint past max_requests
103
+ for _ in range(max_requests + 1):
104
+ r = client.post("/api/assess-claim", ...)
105
+ assert r.status_code == 429
106
+ assert "Retry-After" in r.headers
107
+ assert int(r.headers["Retry-After"]) > 0
108
+ ```
109
+
110
+ **Verification checkpoint.** The test passes.
111
+
112
+ ## Complete working example
113
+
114
+ ```python
115
+ """Rate limiting with durable store, per-user key, Retry-After, token budget."""
116
+
117
+ from __future__ import annotations
118
+
119
+ import logging
120
+ import time
121
+ from typing import Annotated
122
+
123
+ import redis
124
+ from anthropic import Anthropic
125
+ from fastapi import Depends, FastAPI, Header, HTTPException, Request
126
+ from pydantic import BaseModel
127
+
128
+ logger = logging.getLogger("rate_limit")
129
+ app = FastAPI()
130
+
131
+ _redis = redis.Redis(host="localhost", port=6379, decode_responses=True)
132
+
133
+
134
+ # ─── Step 1 — durable store via Redis ──────────────────────────────────
135
+ class RateLimiter:
136
+ def __init__(self, max_requests: int, window_seconds: int):
137
+ self.max_requests = max_requests
138
+ self.window_seconds = window_seconds
139
+
140
+ def check_and_increment(self, key: str) -> tuple[bool, int]:
141
+ bucket = f"ratelimit:{key}"
142
+ pipe = _redis.pipeline()
143
+ pipe.incr(bucket, 1)
144
+ pipe.expire(bucket, self.window_seconds, nx=True)
145
+ count, _ = pipe.execute()
146
+ if int(count) > self.max_requests:
147
+ ttl = _redis.ttl(bucket) or 1
148
+ return False, max(int(ttl), 1)
149
+ return True, 0
150
+
151
+
152
+ api_limiter = RateLimiter(max_requests=60, window_seconds=60)
153
+
154
+
155
+ # ─── Step 4 — token budget (daily) ─────────────────────────────────────
156
+ class TokenBudget:
157
+ def __init__(self, max_tokens_per_day: int):
158
+ self.max = max_tokens_per_day
159
+
160
+ def consume(self, key: str, tokens: int) -> tuple[bool, int]:
161
+ day = time.strftime("%Y-%m-%d")
162
+ bucket = f"tokens:{key}:{day}"
163
+ pipe = _redis.pipeline()
164
+ pipe.incrby(bucket, tokens)
165
+ pipe.expire(bucket, 60 * 60 * 26, nx=True)
166
+ used, _ = pipe.execute()
167
+ if int(used) > self.max:
168
+ return False, 0
169
+ return True, self.max - int(used)
170
+
171
+
172
+ token_budget = TokenBudget(max_tokens_per_day=200_000)
173
+
174
+
175
+ # ─── Step 2 — rate-limit key from auth, IP as last resort ──────────────
176
+ def get_rate_limit_key(
177
+ request: Request,
178
+ x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
179
+ x_user_id: Annotated[str | None, Header(alias="X-User-Id")] = None,
180
+ ) -> str:
181
+ if x_api_key:
182
+ return f"api_key:{x_api_key}"
183
+ if x_user_id:
184
+ return f"user:{x_user_id}"
185
+ ip = request.client.host if request.client else "unknown"
186
+ logger.warning("rate_limit_fallback_to_ip", extra={"ip": ip})
187
+ return f"ip:{ip}"
188
+
189
+
190
+ # ─── Step 5 — LLM client with explicit timeout ─────────────────────────
191
+ llm = Anthropic(timeout=30.0)
192
+
193
+
194
+ class ClaimBody(BaseModel):
195
+ claim_description: str
196
+
197
+
198
+ @app.post("/api/assess-claim")
199
+ async def assess_claim(
200
+ body: ClaimBody,
201
+ key: Annotated[str, Depends(get_rate_limit_key)],
202
+ ) -> dict:
203
+ # Step 3 — 429 with Retry-After
204
+ allowed, retry_after = api_limiter.check_and_increment(key)
205
+ if not allowed:
206
+ raise HTTPException(
207
+ status_code=429,
208
+ detail="Rate limit exceeded",
209
+ headers={"Retry-After": str(retry_after)},
210
+ )
211
+
212
+ # Step 4 — estimate tokens and check budget before the call
213
+ est_tokens = max(1, len(body.claim_description) // 4) + 500
214
+ allowed, remaining = token_budget.consume(key, est_tokens)
215
+ if not allowed:
216
+ raise HTTPException(
217
+ status_code=429,
218
+ detail="Daily token budget exhausted",
219
+ headers={"Retry-After": "86400"},
220
+ )
221
+
222
+ # Step 5 — timeout is on the client instance; call proceeds
223
+ result = llm.messages.create(
224
+ model="claude-sonnet-4-20250514",
225
+ max_tokens=512,
226
+ messages=[{"role": "user", "content": body.claim_description}],
227
+ )
228
+
229
+ # Reconcile actual tokens with budget (Anthropic returns usage info)
230
+ actual = getattr(result, "usage", None)
231
+ if actual:
232
+ total = (actual.input_tokens or 0) + (actual.output_tokens or 0)
233
+ token_budget.consume(key, max(0, total - est_tokens))
234
+
235
+ return {"text": result.content[0].text if result.content else ""}
236
+ ```
237
+
238
+ ## Related patterns
239
+
240
+ - `fallback-patterns.md` — what to return when the LLM call fails or the breaker is open.
241
+ - `monitoring.md` — tracking rate-limit hit rates and token-budget usage as operational metrics.
242
+
243
+ ## Related infrastructure
244
+
245
+ - `aigis infra rate-limiting` — Redis-backed setup (docker-compose for dev, managed Redis for prod) plus integration patterns for Upstash, ElastiCache, and Memcached/DynamoDB alternatives.
246
+ - `aigis infra secrets` — where the `REDIS_URL` connection string belongs.
@@ -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.