@aigis-ai/cli 1.0.3 → 2.0.2

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 (47) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/README.md +58 -188
  3. package/SKILL.md +20 -55
  4. package/aigis-ai-cli-2.0.1.tgz +0 -0
  5. package/bin/aigis.js +446 -59
  6. package/content/index/audit-scan.md +21 -207
  7. package/content/index/auto-verify-rules.json +439 -0
  8. package/content/index/context-rules.json +90 -0
  9. package/content/resolvers/triggers.json +229 -0
  10. package/content/{implement → skills/areas}/audit-logging.md +5 -0
  11. package/content/skills/areas/fallback-patterns.md +200 -0
  12. package/content/skills/areas/input-validation.md +380 -0
  13. package/content/skills/areas/pii-handling.md +189 -0
  14. package/content/skills/areas/rate-limiting.md +246 -0
  15. package/content/skills/core.md +62 -0
  16. package/content/skills/infrastructure/logging.md +202 -0
  17. package/content/skills/infrastructure/rate-limiting.md +169 -0
  18. package/content/skills/infrastructure/secrets.md +167 -0
  19. package/content/skills/workflows/fastapi-llm.md +86 -0
  20. package/docs/resolvers.md +114 -0
  21. package/lib/auto-verify.js +378 -0
  22. package/lib/build.js +629 -0
  23. package/lib/checksum.js +39 -0
  24. package/lib/fetch.js +164 -9
  25. package/lib/init.js +141 -93
  26. package/lib/keywords.js +92 -130
  27. package/lib/special-recognizers.js +370 -0
  28. package/package.json +1 -1
  29. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  30. package/scripts/bootstrap-step-6-bench.js +85 -0
  31. package/scripts/check-content-sync.js +91 -0
  32. package/scripts/triggers.schema.json +50 -0
  33. package/scripts/validate-triggers.js +176 -0
  34. package/content/implement/fallback-patterns.md +0 -190
  35. package/content/implement/input-validation.md +0 -212
  36. package/content/implement/pii-handling.md +0 -207
  37. package/content/implement/rate-limiting.md +0 -217
  38. /package/content/{implement → skills/areas}/bias-monitoring.md +0 -0
  39. /package/content/{implement → skills/areas}/confidence-scoring.md +0 -0
  40. /package/content/{implement → skills/areas}/data-integrity.md +0 -0
  41. /package/content/{implement → skills/areas}/explainability.md +0 -0
  42. /package/content/{implement → skills/areas}/human-oversight.md +0 -0
  43. /package/content/{implement → skills/areas}/monitoring.md +0 -0
  44. /package/content/{implement → skills/areas}/output-sanitization.md +0 -0
  45. /package/content/{implement → skills/areas}/prompt-security.md +0 -0
  46. /package/content/{implement → skills/areas}/rag-security.md +0 -0
  47. /package/content/{implement → skills/areas}/supply-chain.md +0 -0
@@ -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.
@@ -0,0 +1,202 @@
1
+ ---
2
+ id: infra-logging
3
+ title: Structured logging infrastructure (JSON logs + redaction patterns)
4
+ companion_to_area: audit-logging
5
+ controls:
6
+ owasp: [LLM02, LLM08]
7
+ nist: [MEASURE-2.7, MANAGE-4.1]
8
+ iso42001: [Clause-9.1]
9
+ ---
10
+
11
+ The `audit-logging` area procedure (`aigis get audit-logging`) requires structured, queryable logs with PII and secret redaction. This file shows the two infrastructure shapes that satisfy that requirement: a from-scratch JSON-logging setup for new projects, and integration patterns for projects that already ship logs to a platform. Pick one. Then return to the procedure.
12
+
13
+ This is content, not a scaffold. Aigis does not write files for you. Copy the snippets you need; adapt them to your project.
14
+
15
+ ## Starting from scratch (you have no structured logger yet)
16
+
17
+ If you are building a new project and currently use `print()` or default Python logging with text formatting, the simplest acceptable upgrade is `structlog` emitting JSON to stdout, captured by your platform's log driver.
18
+
19
+ ### Required dependency
20
+
21
+ ```
22
+ structlog>=24.0 # pin per your supply-chain procedure
23
+ ```
24
+
25
+ ### Configuration
26
+
27
+ ```python
28
+ import logging
29
+ import structlog
30
+
31
+ REDACT_KEYS = {
32
+ # Credentials
33
+ "password", "passwd", "secret", "token", "api_key", "apikey",
34
+ "authorization", "cookie", "set-cookie",
35
+ # Personally identifiable
36
+ "email", "phone", "phone_number", "address", "street_address",
37
+ "ssn", "tax_id", "credit_card", "card_number",
38
+ "dob", "date_of_birth", "ip_address",
39
+ "first_name", "last_name", "full_name",
40
+ "zip", "postal_code",
41
+ }
42
+ # This set errs on the side of over-redaction. A log line with
43
+ # email="support@company.com" will be redacted even though it's a
44
+ # service address, not user PII. The tradeoff is acceptable: missed
45
+ # PII is worse than redacted non-PII.
46
+
47
+ def redact(_, __, event_dict):
48
+ for key in list(event_dict):
49
+ if key.lower() in REDACT_KEYS:
50
+ event_dict[key] = "[REDACTED]"
51
+ return event_dict
52
+
53
+ logging.basicConfig(format="%(message)s", level=logging.INFO)
54
+
55
+ structlog.configure(
56
+ processors=[
57
+ structlog.contextvars.merge_contextvars,
58
+ structlog.processors.add_log_level,
59
+ structlog.processors.TimeStamper(fmt="iso", utc=True),
60
+ redact,
61
+ structlog.processors.JSONRenderer(),
62
+ ],
63
+ )
64
+
65
+ log = structlog.get_logger()
66
+ ```
67
+
68
+ ### Usage
69
+
70
+ ```python
71
+ log.info("llm_call_started", model="claude-opus-4", user_id=user.id, prompt_tokens=1234)
72
+ log.warning("rate_limit_exceeded", user_id=user.id, key="user:42", retry_after=37)
73
+ log.error("auth_failed", user_id=user.id, reason="invalid_token")
74
+ ```
75
+
76
+ Always pass structured fields, never f-string the values into the message. The message is the event name (`llm_call_started`); the data is fields. This is what makes the logs queryable.
77
+
78
+ ```python
79
+ # Wrong — f-string embeds PII into the unredacted 'event' field:
80
+ log.info(f"user {user.email} logged in")
81
+
82
+ # Right — structured fields pass through the redactor:
83
+ log.info("user_login", email=user.email)
84
+ ```
85
+
86
+ ### Verifying the setup
87
+
88
+ ```python
89
+ # Works — top-level key is redacted:
90
+ log.info("test_event", api_key="sk-should-be-redacted", user_id=42)
91
+ # Expect stdout: {"event": "test_event", "api_key": "[REDACTED]", ...}
92
+
93
+ # Known limitation — nested dict values are NOT redacted:
94
+ log.info("test_request", headers={"authorization": "Bearer xyz"})
95
+ # Expect stdout: headers.authorization visible (not redacted)
96
+ # Mitigation: do not log full headers/request/response dicts.
97
+ # Log only the fields you need, at the top level.
98
+ ```
99
+
100
+ If `api_key` appears unredacted, fix the redactor before continuing the audit-logging procedure.
101
+
102
+ ## Integrate with existing infrastructure
103
+
104
+ If you already ship logs somewhere, route through the existing pipeline rather than adding a second one.
105
+
106
+ ### Datadog / New Relic / Honeycomb (agent-based)
107
+
108
+ These platforms scrape stdout from your container or host. The `structlog` JSON output above is consumed as-is — you do not need a vendor SDK. Set the platform's source/service tags via the agent config, not in application code.
109
+
110
+ ### CloudWatch Logs
111
+
112
+ ECS/EKS/Lambda send stdout to CloudWatch automatically. Use JSON output as above; CloudWatch Insights queries the structured fields directly:
113
+
114
+ ```
115
+ fields @timestamp, event, user_id
116
+ | filter event = "rate_limit_exceeded"
117
+ | stats count() by user_id
118
+ ```
119
+
120
+ ### Sentry (error events only)
121
+
122
+ Sentry is for errors and exceptions, not general logs. Wire it alongside `structlog`:
123
+
124
+ ```python
125
+ import sentry_sdk
126
+ sentry_sdk.init(
127
+ dsn=os.environ["SENTRY_DSN"],
128
+ send_default_pii=False,
129
+ max_request_body_size='never',
130
+ )
131
+ ```
132
+
133
+ `send_default_pii=False` prevents cookies, IPs, and form data from being attached to events. `max_request_body_size='never'` is the line vibe coders miss: without it, Sentry's Flask/Django/FastAPI integrations capture full request bodies on error — which ships PII to Sentry even when `send_default_pii` is False. Confirm in the Sentry UI that captured events do not contain PII before deploying to production.
134
+
135
+ ### OpenTelemetry / OTLP
136
+
137
+ For projects on the OpenTelemetry stack, route logs through the OTLP exporter so they flow alongside traces and metrics to your collector. The OTLP path replaces the stdout/JSONRenderer path from the Configuration section — it is not additive. Use this config in place of the earlier one:
138
+
139
+ ```python
140
+ import logging
141
+ import structlog
142
+ from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
143
+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
144
+ from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
145
+
146
+ provider = LoggerProvider()
147
+ provider.add_log_record_processor(
148
+ BatchLogRecordProcessor(OTLPLogExporter(endpoint='http://collector:4317'))
149
+ )
150
+ handler = LoggingHandler(logger_provider=provider)
151
+ logging.basicConfig(format='%(message)s', level=logging.INFO, handlers=[handler])
152
+
153
+ structlog.configure(
154
+ processors=[
155
+ structlog.contextvars.merge_contextvars,
156
+ structlog.processors.add_log_level,
157
+ structlog.processors.TimeStamper(fmt='iso', utc=True),
158
+ redact,
159
+ structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
160
+ ],
161
+ logger_factory=structlog.stdlib.LoggerFactory(),
162
+ )
163
+
164
+ log = structlog.get_logger()
165
+ ```
166
+
167
+ The `redact` processor stays in the chain — OTel does not redact for you. Point the OTLP endpoint at your collector (OpenTelemetry Collector, Grafana Agent, Datadog Agent with OTLP ingest, etc.). The collector handles batching, retries, and forwarding to your backend.
168
+
169
+ ## Production considerations
170
+
171
+ Things to think about before deploying. None of these are blockers for the procedure to verify PASS, but all of them affect whether the logs are useful in production.
172
+
173
+ ### Redaction is allow-list-adjacent, not perfect
174
+
175
+ The `REDACT_KEYS` set above catches obvious cases. It does not catch:
176
+
177
+ - PII embedded in a free-form `message` field (an email inside an error string).
178
+ - Secrets in a URL query string logged as `request_url`.
179
+ - PII in a nested dict not at the top level.
180
+
181
+ For high-risk surfaces, log only IDs and event names — never log the full request or response body. The `pii-handling` area procedure has the canonical guidance.
182
+
183
+ ### Log levels and volume
184
+
185
+ `INFO` for business events (request received, LLM call started). `WARNING` for recoverable issues (rate limit hit, retry). `ERROR` for unrecoverable issues. Do not log every database query at `INFO` — volume hides signal and inflates cost.
186
+
187
+ ### Retention and access
188
+
189
+ Logs containing user IDs are subject to your privacy policy's retention limits. Configure platform-side retention (30/90/365 days) per data class. Restrict log query access to the people who need it; production logs are a regulated surface.
190
+
191
+ ### Correlation IDs
192
+
193
+ Attach a request-scoped correlation ID via `structlog.contextvars.bind_contextvars(request_id=...)` at request entry. Every log line in that request inherits the ID, making cross-service tracing possible without a full distributed-tracing system.
194
+
195
+ ## After this file
196
+
197
+ Return to the area procedure: `aigis get audit-logging`. The procedure's structured-logging checkpoint is satisfied once your application emits JSON logs with the redactor active. Continue from the next step.
198
+
199
+ ## Related infrastructure
200
+
201
+ - `aigis infra secrets` — keep API keys, tokens, and connection strings out of the log fields shown above.
202
+ - `aigis infra rate-limiting` — `rate_limit_exceeded` events should land in the structured logger, not a separate sink.
@@ -0,0 +1,169 @@
1
+ ---
2
+ id: infra-rate-limiting
3
+ title: Rate limiting infrastructure (Redis-backed setup + integration patterns)
4
+ companion_to_area: rate-limiting
5
+ controls:
6
+ owasp: [LLM10]
7
+ nist: [MEASURE-2.6, MANAGE-2.4]
8
+ iso42001: [Clause-8.2]
9
+ ---
10
+
11
+ The `rate-limiting` area procedure (`aigis get rate-limiting`) requires a durable backing store unconditionally. This file shows the two infrastructure shapes that satisfy that requirement: a from-scratch Redis setup for new projects, and integration patterns for projects that already have a key-value store. Pick one. Then return to the procedure.
12
+
13
+ This is content, not a scaffold. Aigis does not write files for you. Copy the snippets you need; adapt them to your project.
14
+
15
+ ## Starting from scratch (you have no Redis yet)
16
+
17
+ If you are building a new project and don't have a Redis instance, the simplest production-ready setup is Redis 7+ running in Docker for development, with a managed Redis (Upstash, Redis Cloud, ElastiCache) for production.
18
+
19
+ ### Required dependency
20
+
21
+ ```
22
+ redis>=5.0 # Python client; pin per your supply-chain procedure
23
+ ```
24
+
25
+ ### Local development (docker-compose)
26
+
27
+ ```yaml
28
+ # docker-compose.yml
29
+ services:
30
+ redis:
31
+ image: redis:7-alpine
32
+ container_name: aigis-rate-limit
33
+ ports:
34
+ - "6379:6379"
35
+ healthcheck:
36
+ test: ["CMD", "redis-cli", "ping"]
37
+ interval: 10s
38
+ timeout: 3s
39
+ retries: 5
40
+ restart: unless-stopped
41
+ ```
42
+
43
+ Run: `docker compose up -d redis`. Verify: `redis-cli ping` returns `PONG`.
44
+
45
+ ### Environment variable convention
46
+
47
+ ```
48
+ # .env.example
49
+ REDIS_URL=redis://localhost:6379/0
50
+ RATE_LIMIT_MAX_REQUESTS=60
51
+ RATE_LIMIT_WINDOW_SECONDS=60
52
+ TOKEN_BUDGET_PER_DAY=200000
53
+ ```
54
+
55
+ Do not hard-code the connection string; read from `REDIS_URL` so your local, staging, and production environments swap cleanly.
56
+
57
+ ### Connection code
58
+
59
+ ```python
60
+ import os
61
+ import redis
62
+
63
+ _client: redis.Redis | None = None
64
+
65
+ def get_redis() -> redis.Redis:
66
+ global _client
67
+ if _client is None:
68
+ _client = redis.Redis.from_url(
69
+ os.getenv("REDIS_URL", "redis://localhost:6379/0"),
70
+ decode_responses=True,
71
+ )
72
+ return _client
73
+ ```
74
+
75
+ ### Verifying the connection
76
+
77
+ Before wiring this into the rate-limiter, confirm the application can talk to Redis:
78
+
79
+ ```python
80
+ from your_module import get_redis
81
+ get_redis().ping() # returns True or raises ConnectionError
82
+ ```
83
+
84
+ If this raises, fix it before continuing the rate-limiting procedure. The procedure assumes the connection works.
85
+
86
+ ## Integrate with existing infrastructure
87
+
88
+ If you already have a key-value store, adapt rather than add a second one. Common cases below; pick the closest match.
89
+
90
+ ### You already have Redis (self-hosted or managed)
91
+
92
+ Set `REDIS_URL` to your existing connection string. That's it. The connection code above reads the env var; nothing else changes.
93
+
94
+ ```
95
+ REDIS_URL=redis://user:password@redis.internal.company.com:6379/0
96
+ ```
97
+
98
+ ### Upstash (serverless Redis)
99
+
100
+ Upstash provides a Redis-compatible HTTP and TCP interface. Use the TCP URL with the standard `redis` client:
101
+
102
+ ```
103
+ REDIS_URL=rediss://default:<token>@<region>.upstash.io:6379
104
+ ```
105
+
106
+ Note the `rediss://` scheme (TLS) and that Upstash serverless is rate-limited per request — appropriate for low-volume rate limiting, less appropriate for high-frequency token-budget tracking. If your rate-limit traffic exceeds Upstash's free tier, switch to managed Redis.
107
+
108
+ ### AWS ElastiCache
109
+
110
+ ElastiCache is Redis-protocol-compatible. Connect from inside the same VPC:
111
+
112
+ ```
113
+ REDIS_URL=redis://my-elasticache.abc123.0001.use1.cache.amazonaws.com:6379
114
+ ```
115
+
116
+ Use IAM auth if your cluster is configured for it; otherwise rely on VPC security groups. Do not expose ElastiCache to the public internet.
117
+
118
+ ### Memcached, DynamoDB, or another KV store
119
+
120
+ The rate-limiting procedure's reference implementation uses Redis primitives (`INCR`, `EXPIRE`, `TTL`). If you cannot use Redis, the conceptual operations are:
121
+
122
+ - **Counter increment with TTL** — atomic increment of a per-key counter that expires after the window. Memcached's `incr` + `set` combo. DynamoDB's `UpdateItem` with a TTL attribute.
123
+ - **Read remaining TTL for Retry-After** — Redis returns this directly with `TTL`. Memcached doesn't expose it; you must compute it from the time you set the key. DynamoDB exposes it via the TTL attribute.
124
+
125
+ If you adopt one of these alternatives, document the choice in a comment at the top of your rate-limit module (the procedure's Step 1 verification checkpoint expects this). The rest of the area procedure (Retry-After header, token budget separation, LLM client timeout) is store-agnostic and applies as written.
126
+
127
+ ## Production considerations
128
+
129
+ Things to think about before deploying. None of these are blockers for the procedure to verify PASS, but all of them affect whether the rate limiter actually works in production.
130
+
131
+ ### Key namespace conventions
132
+
133
+ Prefix every rate-limit key with a namespace so multiple services can share one Redis without colliding:
134
+
135
+ ```
136
+ ratelimit:<service>:<key> # request count
137
+ tokens:<service>:<key>:<YYYY-MM-DD> # token budget per day
138
+ ```
139
+
140
+ The procedure's reference implementation uses `ratelimit:<key>` and `tokens:<key>:<day>`. Add the `<service>` segment if your Redis is shared.
141
+
142
+ ### TTL strategy
143
+
144
+ The window-based limiter sets the key's TTL on first increment. If the key is hit only once in the window and not renewed, it expires when the window ends — correct behavior. If the key is hit continuously, do not refresh the TTL (the limiter would never reset). The procedure's Redis snippet uses `EXPIRE bucket <window> NX` (set only if no TTL exists) for this reason.
145
+
146
+ ### Failure modes
147
+
148
+ What happens when Redis is unreachable? Three reasonable choices:
149
+
150
+ 1. **Fail open** — log the error, allow the request through. Highest availability, lowest safety. Appropriate for non-critical paths.
151
+ 2. **Fail closed** — return 503. Highest safety, blocks all traffic on a Redis outage. Appropriate for high-risk endpoints.
152
+ 3. **Fall back to in-memory** — track in a process-local counter for the duration of the outage. Acceptable trade for medium-risk endpoints if the outage is rare and you alert on it.
153
+
154
+ Pick one and document it. The procedure's reference handler catches `redis.exceptions.ConnectionError` and returns 503 (fail closed); change it if your risk tolerance is different.
155
+
156
+ ### Multi-region
157
+
158
+ For most projects, **per-region rate limits** are the right starting point — each region runs its own Redis; users routed to a region get per-region quota. Acceptable when traffic is sticky to a region.
159
+
160
+ If per-region quotas don't fit (you genuinely need a global cap on a per-user basis), the escape hatch is an **external rate-limit service** (Cloudflare, Kong, AWS API Gateway). Removes the per-app rate-limit logic entirely; trades implementation complexity for vendor lock-in.
161
+
162
+ ## After this file
163
+
164
+ Return to the area procedure: `aigis get rate-limiting`. The procedure's Step 1 (durable backing store) is satisfied once the connection works. Continue from Step 2 onward.
165
+
166
+ ## Related infrastructure
167
+
168
+ - `aigis infra logging` — where rate-limit blocks should be logged.
169
+ - `aigis infra secrets` — where to store the Redis connection string and credentials.