@aigis-ai/cli 1.0.2 → 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.
- package/CONTRIBUTING.md +53 -0
- package/SKILL.md +20 -55
- package/bin/aigis.js +446 -59
- package/cli-python/LICENSE +21 -0
- package/cli-python/README.md +32 -0
- package/cli-python/aigis_cli/SKILL.md +70 -0
- package/cli-python/aigis_cli/__init__.py +3 -0
- package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/annotate.py +45 -0
- package/cli-python/aigis_cli/auto_verify.py +518 -0
- package/cli-python/aigis_cli/build.py +470 -0
- package/cli-python/aigis_cli/checksum.py +22 -0
- package/cli-python/aigis_cli/classify.py +192 -0
- package/cli-python/aigis_cli/cli.py +618 -0
- package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
- package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
- package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
- package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
- package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
- package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
- package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
- package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
- package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
- package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
- package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
- package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
- package/cli-python/aigis_cli/content/skills/core.md +62 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
- package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
- package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
- package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
- package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
- package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
- package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
- package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
- package/cli-python/aigis_cli/fetch.py +232 -0
- package/cli-python/aigis_cli/init_ide.py +159 -0
- package/cli-python/aigis_cli/keywords.py +73 -0
- package/cli-python/aigis_cli/search.py +69 -0
- package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
- package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
- package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
- package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
- package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
- package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
- package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
- package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
- package/cli-python/pyproject.toml +49 -0
- package/content/index/audit-scan.md +21 -207
- package/content/index/auto-verify-rules.json +439 -0
- package/content/index/context-rules.json +90 -0
- package/content/resolvers/triggers.json +229 -0
- package/content/skills/areas/audit-logging.md +176 -0
- package/content/skills/areas/bias-monitoring.md +172 -0
- package/content/skills/areas/confidence-scoring.md +180 -0
- package/content/skills/areas/data-integrity.md +257 -0
- package/content/skills/areas/explainability.md +174 -0
- package/content/skills/areas/fallback-patterns.md +200 -0
- package/content/skills/areas/human-oversight.md +220 -0
- package/content/skills/areas/input-validation.md +380 -0
- package/content/skills/areas/monitoring.md +207 -0
- package/content/skills/areas/output-sanitization.md +183 -0
- package/content/skills/areas/pii-handling.md +189 -0
- package/content/skills/areas/prompt-security.md +153 -0
- package/content/skills/areas/rag-security.md +230 -0
- package/content/skills/areas/rate-limiting.md +246 -0
- package/content/skills/areas/supply-chain.md +193 -0
- package/content/skills/core.md +62 -0
- package/content/skills/infrastructure/logging.md +202 -0
- package/content/skills/infrastructure/rate-limiting.md +169 -0
- package/content/skills/infrastructure/secrets.md +167 -0
- package/content/skills/workflows/fastapi-llm.md +86 -0
- package/docs/resolvers.md +114 -0
- package/lib/auto-verify.js +378 -0
- package/lib/build.js +629 -0
- package/lib/checksum.js +39 -0
- package/lib/fetch.js +164 -9
- package/lib/init.js +141 -93
- package/lib/keywords.js +92 -130
- package/lib/special-recognizers.js +370 -0
- package/package.json +6 -2
- package/scripts/baseline-cursorrules.snapshot.txt +30 -0
- package/scripts/bootstrap-step-6-bench.js +85 -0
- package/scripts/check-content-sync.js +91 -0
- package/scripts/triggers.schema.json +50 -0
- package/scripts/validate-triggers.js +176 -0
- package/content/implement/fallback-patterns.md +0 -190
- package/content/implement/input-validation.md +0 -212
- package/content/implement/pii-handling.md +0 -207
- package/content/implement/rate-limiting.md +0 -217
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: pii-handling
|
|
3
|
+
title: PII and sensitive data protection
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM02]
|
|
6
|
+
nist: [MAP-2.1, MEASURE-2.10]
|
|
7
|
+
iso42001: [Annex-A.7, Annex-A.4]
|
|
8
|
+
min_risk_tier: all
|
|
9
|
+
system_traits: [processes-pii, handles-financial, handles-health, handles-minors]
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Personally identifiable information that reaches the LLM (or the logs of LLM calls) leaks control of that data to the provider and to anyone with log access. This procedure redacts PII before it crosses those boundaries.
|
|
13
|
+
|
|
14
|
+
## Common incomplete implementations
|
|
15
|
+
|
|
16
|
+
1. **Partial pattern coverage.** Three classes out of five (typically: SSN + email + phone OR SSN + credit card + email). The one class most often missed is **physical addresses**, because addresses are harder to regex than structured fields. Missing any of the five below leaves a class of PII flowing to the LLM unredacted.
|
|
17
|
+
2. **Redaction on LLM input but not logs.** Redacting what goes to the model protects the model; logs of the raw request to the handler still contain raw PII.
|
|
18
|
+
3. **Hashable placeholder.** Using `hash(ssn)` or similar as the replacement. The hash is deterministic — anyone who observes a log entry with a given hash and has a candidate SSN can verify the match. Use non-reversible labels like `[SSN_REDACTED]`.
|
|
19
|
+
4. **Redaction applied only at one entry point.** If your handler ingests claim text in multiple places (main endpoint + retry endpoint + batch endpoint), every entry point must route through the redactor.
|
|
20
|
+
|
|
21
|
+
## The five required pattern classes
|
|
22
|
+
|
|
23
|
+
Every implementation of this pattern must cover these five classes at minimum:
|
|
24
|
+
|
|
25
|
+
| Class | What it matches | Example |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| `ssn` | US Social Security Numbers | `123-45-6789` |
|
|
28
|
+
| `email` | Email addresses | `alice@example.com` |
|
|
29
|
+
| `phone` | US phone numbers (with or without country code, with or without separators) | `(555) 123-4567`, `+1-555-123-4567` |
|
|
30
|
+
| `credit_card` | 13-19 digit card numbers with optional separators | `4242 4242 4242 4242` |
|
|
31
|
+
| `address` | US street addresses with directional / street-type tokens | `123 Main St`, `456 Elm Avenue, Apt 2B` |
|
|
32
|
+
|
|
33
|
+
Domain-specific classes (date of birth, account numbers, medical record numbers) should be added on top of these five, not in place of any of them.
|
|
34
|
+
|
|
35
|
+
## Implementation procedure
|
|
36
|
+
|
|
37
|
+
### Step 1 — Define PII_PATTERNS with all five required keys ⚠ CRITICAL
|
|
38
|
+
|
|
39
|
+
**What to do.** Create a dictionary (or equivalent structure) named `PII_PATTERNS` with exactly these keys: `ssn`, `email`, `phone`, `credit_card`, `address`. Each value is the regex that matches that class.
|
|
40
|
+
|
|
41
|
+
**Why this matters.** The regex dict is the single source of truth for what your redactor knows about. If a key is missing from the dict, it doesn't matter how careful the rest of your code is — that class of PII flows through.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import re
|
|
45
|
+
|
|
46
|
+
PII_PATTERNS = {
|
|
47
|
+
"ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
|
|
48
|
+
"email": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
|
|
49
|
+
"phone": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"),
|
|
50
|
+
"credit_card": re.compile(r"\b(?:\d{4}[-\s]?){3}\d{4}\b"),
|
|
51
|
+
"address": re.compile(
|
|
52
|
+
r"\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,3}"
|
|
53
|
+
r"(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Rd|Road|Ln|Lane|Dr|Drive|Way|Ct|Court|Pl|Place|Sq|Square|Pkwy|Parkway|Terr|Terrace)\b"
|
|
54
|
+
r"(?:,?\s*(?:Apt|Suite|Ste|Unit|#)\s*[\w-]+)?",
|
|
55
|
+
re.IGNORECASE,
|
|
56
|
+
),
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**Verification checkpoint.** Count the keys. The dictionary must have **exactly five** keys named `ssn`, `email`, `phone`, `credit_card`, `address`. If any is missing, add it before continuing. If you have additional keys for domain-specific classes, that is fine — do not remove them. But do not claim the redactor is complete without all five required keys.
|
|
61
|
+
|
|
62
|
+
### Step 2 — Write a redaction function with non-reversible placeholders
|
|
63
|
+
|
|
64
|
+
**What to do.** Implement `redact_pii(text) -> (redacted_text, seen: list[str])` that iterates `PII_PATTERNS` and replaces each match with a label like `[<CLASS>_REDACTED]`. Return the list of classes seen for metric / log context.
|
|
65
|
+
|
|
66
|
+
**Why this matters.** Reversible placeholders (hashes of PII) defeat the purpose — anyone with a candidate value can verify a match. Non-reversible labels keep the boundary intact.
|
|
67
|
+
|
|
68
|
+
**Verification checkpoint.** Run the redactor against a test string containing every required class. All five should be replaced; none of the originals should appear in the output. See the complete example at the end for the implementation + test.
|
|
69
|
+
|
|
70
|
+
### Step 3 — Call the redactor on every LLM input path
|
|
71
|
+
|
|
72
|
+
**What to do.** For every place in the code where user-provided text goes to the LLM, pass it through `redact_pii` first. Use the redacted text in the LLM request. Originals stay in the handler stack frame only — never in logs or persistent stores.
|
|
73
|
+
|
|
74
|
+
**Why this matters.** Redaction at the wrong layer leaks. If one endpoint redacts and another doesn't, the system leaks through the other.
|
|
75
|
+
|
|
76
|
+
**Verification checkpoint.** `grep -rn "messages.create\|chat.completions.create"` — every hit must be preceded by a call to `redact_pii` in the same function. Any callsite passing raw user text to the LLM is a leak.
|
|
77
|
+
|
|
78
|
+
### Step 4 — Redact PII from log output as well
|
|
79
|
+
|
|
80
|
+
**What to do.** Every log entry that contains user input or LLM output must use the redacted text, not raw. Hash the raw input with SHA-256 for correlation (`input_hash`) but never log the plaintext.
|
|
81
|
+
|
|
82
|
+
**Why this matters.** Redacting the model path protects the model; redacting logs protects everyone with log access from incidental exposure.
|
|
83
|
+
|
|
84
|
+
**Verification checkpoint.** `grep -rn "logger\.\(info\|warning\|error\)" --include="*.py"` — every hit that includes request or model text must route through `redact_pii` or use a hashed identifier. No raw user strings in logs.
|
|
85
|
+
|
|
86
|
+
### Step 5 — Add domain-specific classes on top
|
|
87
|
+
|
|
88
|
+
**What to do.** Consider whether your domain introduces additional classes of sensitive data. Add them to `PII_PATTERNS` — do not remove any of the five required ones.
|
|
89
|
+
|
|
90
|
+
Common additions:
|
|
91
|
+
|
|
92
|
+
| Class | When to add |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `dob` | Any system handling identity, insurance, medical, or minors |
|
|
95
|
+
| `account_number` | Financial or utility systems |
|
|
96
|
+
| `medical_record` | Health systems (ICD codes, MRN formats) |
|
|
97
|
+
| `drivers_license` | Insurance, age verification, identity |
|
|
98
|
+
| `passport` | Travel, immigration, identity |
|
|
99
|
+
|
|
100
|
+
**Verification checkpoint.** If your classify output included `handles-financial`, `handles-health`, or `handles-minors`, you have at least one domain-specific class to consider.
|
|
101
|
+
|
|
102
|
+
### Step 6 — Redact the model's output too
|
|
103
|
+
|
|
104
|
+
**What to do.** The LLM may reproduce PII from its input, or hallucinate PII-shaped output. Before returning the model's output to the user or to logs, run it through `redact_pii` as well.
|
|
105
|
+
|
|
106
|
+
**Why this matters.** Even with redaction on the input, the model can echo PII if you prompt it incorrectly or if the model confabulates something shaped like a phone number. Treat model output as untrusted PII-wise.
|
|
107
|
+
|
|
108
|
+
**Verification checkpoint.** The response payload that leaves your handler has been through `redact_pii` on the free-text fields. Structured fields (scores, enums) do not need redaction.
|
|
109
|
+
|
|
110
|
+
### Step 7 — Confirm no PII enters the LLM via database queries on the call path
|
|
111
|
+
|
|
112
|
+
**What to do.** Trace the database queries on the LLM call path — the code paths that run before a `messages.create` (or equivalent provider call). Confirm none of those queries return columns whose values are PII themselves (full name, email, full address, raw SSN, raw credit card, raw phone). If a row from such a query is interpolated into the prompt, the redactor never sees it as a literal — it sees an opaque variable that happens to contain PII.
|
|
113
|
+
|
|
114
|
+
**Why this matters.** Step 1's regex dictionary catches PII in the user-supplied text. It does not catch PII pulled from the database and concatenated into the prompt downstream. A SELECT that returns a customer's name and shipping address, then formatted into the system prompt as context, ships PII to the model regardless of how perfect the redactor is on the user input.
|
|
115
|
+
|
|
116
|
+
**Verification checkpoint.** For each LLM call site, walk back through every query that contributed to the prompt or message list. If any of them returned PII columns directly, either route that text through `redact_pii` before it reaches the prompt, or change the query to return only non-PII identifiers (a customer ID, not the customer's name) and resolve the PII fields at render-time outside the LLM path.
|
|
117
|
+
|
|
118
|
+
## Complete working example
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
"""PII redaction for LLM input, logs, and output."""
|
|
122
|
+
|
|
123
|
+
from __future__ import annotations
|
|
124
|
+
|
|
125
|
+
import hashlib
|
|
126
|
+
import json
|
|
127
|
+
import logging
|
|
128
|
+
import re
|
|
129
|
+
|
|
130
|
+
logger = logging.getLogger("pii")
|
|
131
|
+
audit = logging.getLogger("audit")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ─── Step 1 — five required classes (+ one domain-specific) ────────────
|
|
135
|
+
PII_PATTERNS: dict[str, re.Pattern[str]] = {
|
|
136
|
+
"ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
|
|
137
|
+
"email": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
|
|
138
|
+
"phone": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"),
|
|
139
|
+
"credit_card": re.compile(r"\b(?:\d{4}[-\s]?){3}\d{4}\b"),
|
|
140
|
+
"address": re.compile(
|
|
141
|
+
r"\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,3}"
|
|
142
|
+
r"(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Rd|Road|Ln|Lane|Dr|Drive|Way|Ct|Court|Pl|Place|Sq|Square|Pkwy|Parkway|Terr|Terrace)\b"
|
|
143
|
+
r"(?:,?\s*(?:Apt|Suite|Ste|Unit|#)\s*[\w-]+)?",
|
|
144
|
+
re.IGNORECASE,
|
|
145
|
+
),
|
|
146
|
+
# Step 5 — domain-specific add-on; not one of the required five
|
|
147
|
+
"dob": re.compile(r"\b(?:0[1-9]|1[0-2])/(?:0[1-9]|[12]\d|3[01])/(?:19|20)\d{2}\b"),
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ─── Step 2 — redaction with non-reversible placeholders ───────────────
|
|
152
|
+
def redact_pii(text: str) -> tuple[str, list[str]]:
|
|
153
|
+
seen: list[str] = []
|
|
154
|
+
out = text
|
|
155
|
+
for pii_type, pattern in PII_PATTERNS.items():
|
|
156
|
+
if pattern.search(out):
|
|
157
|
+
seen.append(pii_type)
|
|
158
|
+
out = pattern.sub(f"[{pii_type.upper()}_REDACTED]", out)
|
|
159
|
+
return out, seen
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ─── Step 3+6 — redact input before LLM and output before return ───────
|
|
163
|
+
def call_llm_with_redaction(user_text: str, trace_id: str, invoke) -> dict:
|
|
164
|
+
redacted_input, seen_in = redact_pii(user_text)
|
|
165
|
+
raw_output = invoke(redacted_input) # invoke returns model text
|
|
166
|
+
redacted_output, seen_out = redact_pii(raw_output)
|
|
167
|
+
|
|
168
|
+
# Step 4 — log with hashed input + redacted text only
|
|
169
|
+
audit.info(json.dumps({
|
|
170
|
+
"trace_id": trace_id,
|
|
171
|
+
"input_hash": hashlib.sha256(user_text.encode()).hexdigest(),
|
|
172
|
+
"input_redacted": redacted_input[:500],
|
|
173
|
+
"output_redacted": redacted_output[:2000],
|
|
174
|
+
"pii_types_in_input": seen_in,
|
|
175
|
+
"pii_types_in_output": seen_out,
|
|
176
|
+
}))
|
|
177
|
+
|
|
178
|
+
return {"text": redacted_output}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Related patterns
|
|
182
|
+
|
|
183
|
+
- `input-validation.md` — sanitization of user input prior to any LLM call (zero-width unicode, prompt-injection patterns).
|
|
184
|
+
- `audit-logging.md` — structure of log entries; works with this pattern's `input_hash` convention.
|
|
185
|
+
|
|
186
|
+
## Related infrastructure
|
|
187
|
+
|
|
188
|
+
- `aigis infra secrets` — keep API keys, database credentials, and connection strings out of source code (the procedure above assumes they live in env vars, not literals).
|
|
189
|
+
- `aigis infra logging` — redaction patterns for the structured logger that consumes `redact_pii` output.
|
|
@@ -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,62 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: aigis-core
|
|
3
|
+
description: AI governance for coding agents. Use before building any LLM feature or when auditing existing AI systems. Loads area skills and workflow skills on demand via the aigis CLI.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Aigis core skill
|
|
7
|
+
|
|
8
|
+
Aigis ships governance patterns mapped to NIST AI RMF, OWASP Top 10 for LLMs, and ISO/IEC 42001. This file orients you. Detailed procedures (per-area + per-workflow) load on demand.
|
|
9
|
+
|
|
10
|
+
## When to use
|
|
11
|
+
|
|
12
|
+
When building a new AI/LLM feature, or auditing one. Do this BEFORE writing the LLM call, not after.
|
|
13
|
+
|
|
14
|
+
## The workflow (build a new feature)
|
|
15
|
+
|
|
16
|
+
1. **Classify.** `aigis classify --traits <comma-separated> --json` (or `aigis classify "<natural language description>"`). Returns the risk tier + the list of pattern areas relevant to your system.
|
|
17
|
+
2. **Pick a workflow.** Read the suggested workflow at the bottom of classify output and run `aigis workflow <type>` (e.g. `aigis workflow fastapi-llm`). The workflow tells you which file each pattern lives in for your stack — so the wiring is consistent.
|
|
18
|
+
3. **For each recommended area, one at a time:**
|
|
19
|
+
- `aigis get <area-id>` — fetch the procedure
|
|
20
|
+
- Implement the procedure step by step. Honor each "verification checkpoint."
|
|
21
|
+
- `aigis verify <area-id> --auto .` — run the deterministic scanner against your project. Fix any FAIL or OVERCLAIM before moving on.
|
|
22
|
+
4. **Generate compliance docs** when all areas pass: `aigis template <id>` for each template the classify output named.
|
|
23
|
+
|
|
24
|
+
## The workflow (audit an existing project)
|
|
25
|
+
|
|
26
|
+
1. `aigis audit --scan` — discovery prompt. Walks you through inventory + trait detection + classify handoff.
|
|
27
|
+
2. `aigis audit --traits <detected> --json` — scoped checklist with the deterministic denominator.
|
|
28
|
+
3. For each area, run `aigis verify <id> --auto .` to surface PASS/FAIL/OVERCLAIM/JUDGMENT.
|
|
29
|
+
4. Implement fixes using `aigis get <id>` for the procedure.
|
|
30
|
+
|
|
31
|
+
## How to read `aigis verify <area> --auto` output
|
|
32
|
+
|
|
33
|
+
- **PASS**: code matches a deterministic pattern; cite the file:line.
|
|
34
|
+
- **FAIL**: pattern absent; either implement it or argue it's N/A in this context.
|
|
35
|
+
- **OVERCLAIM**: code passes the basic check but a structural anti-pattern is present (e.g. kill switch is restart-latched, injection detector logs without blocking).
|
|
36
|
+
- **JUDGMENT**: requires your evaluation; the scanner explains why.
|
|
37
|
+
|
|
38
|
+
When an OVERCLAIM is raised, the area is not complete — fix the anti-pattern before marking done.
|
|
39
|
+
|
|
40
|
+
## How to pick traits
|
|
41
|
+
|
|
42
|
+
Two ways to figure out which traits apply:
|
|
43
|
+
|
|
44
|
+
1. **CLI:** `aigis classify "<plain-English description of what you're building>"`. Reads the trigger map, returns high-confidence traits immediately, and asks one consolidated confirmation prompt for low-confidence triggers (if any).
|
|
45
|
+
|
|
46
|
+
2. **In-IDE:** scan the user's project description against the **AIGIS RESOLVER BLOCK** below in this rules file. Apply high-confidence triggers directly. For each low-confidence trigger that matches, ask the user the listed clarifying question (yes / no / unsure) before adding the trait.
|
|
47
|
+
|
|
48
|
+
Default to NO on low-confidence questions when the user is unsure — false-positive trait classification is worse than missing one trait the user can add manually with `aigis classify --traits ...`.
|
|
49
|
+
|
|
50
|
+
## Available commands
|
|
51
|
+
|
|
52
|
+
- `aigis classify` — risk tier + recommended areas
|
|
53
|
+
- `aigis workflow <type>` — canonical file layout + wiring contracts for a stack (run `aigis workflow --list` to see available)
|
|
54
|
+
- `aigis get <area-id> [--lang python|js|...] [--context web|agentic|rag|batch]` — area skill (the procedure)
|
|
55
|
+
- `aigis verify <area-id> [--auto <path>]` — checklist or deterministic scan
|
|
56
|
+
- `aigis template <id>` — compliance documentation template
|
|
57
|
+
- `aigis audit --scan | --traits <list>` — audit existing code
|
|
58
|
+
- `aigis infra <area>` — fetch infrastructure setup content (rate-limiting, secrets, logging). Use after the area procedure references it.
|
|
59
|
+
|
|
60
|
+
## What loads on demand vs always
|
|
61
|
+
|
|
62
|
+
This file (`core.md`) is always in your context after `aigis init`. **Area skills** load when you run `aigis get <id>`. **Workflow skills** load when you run `aigis workflow <type>`. Don't ask for them upfront — fetch them when classify points you at them.
|