@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.
- 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 +1 -1
- 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,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.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: infra-secrets
|
|
3
|
+
title: Secrets management infrastructure (env-var baseline + vault integration patterns)
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM02, LLM05]
|
|
6
|
+
nist: [MAP-2.3, MEASURE-2.7]
|
|
7
|
+
iso42001: [Clause-8.3]
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
Several area procedures (`pii-handling`, `supply-chain`, the `rate-limiting` infra file's Redis URL) require secrets — API keys, database credentials, connection strings — to live outside source code. This file shows the two infrastructure shapes that satisfy that requirement: an environment-variable baseline for new projects, and integration patterns for projects that already have a secrets manager. Pick one. Then return to the procedure that sent you here.
|
|
11
|
+
|
|
12
|
+
This is content, not a scaffold. Aigis does not write files for you. Copy the snippets you need; adapt them to your project.
|
|
13
|
+
|
|
14
|
+
## Starting from scratch (you have no secrets manager yet)
|
|
15
|
+
|
|
16
|
+
If you are building a new project and don't have a vault, the minimum acceptable baseline is environment variables loaded from a `.env` file in development and from your platform's secret store in production. Hard-coded secrets in source files are not acceptable at any stage — the supply-chain procedure will flag them.
|
|
17
|
+
|
|
18
|
+
### Required dependency
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
python-dotenv>=1.0 # loads .env into os.environ; pin per your supply-chain procedure
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### `.env.example` convention
|
|
25
|
+
|
|
26
|
+
Commit `.env.example` with placeholder values. Add `.env` to `.gitignore`. Every key in `.env.example` must be present in `.env` for the app to start.
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
# .env.example
|
|
30
|
+
ANTHROPIC_API_KEY=sk-ant-REPLACE_ME
|
|
31
|
+
OPENAI_API_KEY=sk-REPLACE_ME
|
|
32
|
+
DATABASE_URL=postgresql://user:REPLACE_ME@localhost:5432/dbname
|
|
33
|
+
REDIS_URL=redis://localhost:6379/0
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
# .gitignore
|
|
38
|
+
.env
|
|
39
|
+
.env.local
|
|
40
|
+
.env.*.local
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Do not deploy `.env` to production. Production secrets come from your platform's secret store (Vault, AWS Secrets Manager, GCP Secret Manager, or the wrappers below). The `.env` file exists only for local development; a `.env` in a container image or a production deploy is a leak.
|
|
44
|
+
|
|
45
|
+
### Loading code
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import os
|
|
49
|
+
from dotenv import load_dotenv
|
|
50
|
+
|
|
51
|
+
load_dotenv() # no-op in production if .env is absent
|
|
52
|
+
|
|
53
|
+
def require(name: str) -> str:
|
|
54
|
+
value = os.getenv(name)
|
|
55
|
+
if not value or value.endswith("REPLACE_ME"):
|
|
56
|
+
raise RuntimeError(f"Missing required secret: {name}")
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
ANTHROPIC_API_KEY = require("ANTHROPIC_API_KEY")
|
|
60
|
+
DATABASE_URL = require("DATABASE_URL")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The `require` helper fails fast at startup rather than at first use. A missing API key should crash the process on boot, not surface as a 500 the first time a user hits the LLM endpoint.
|
|
64
|
+
|
|
65
|
+
### Verifying the setup
|
|
66
|
+
|
|
67
|
+
Before wiring secrets into application code, confirm loading works and that no secret leaks into logs:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
print("ANTHROPIC_API_KEY loaded:", bool(os.getenv("ANTHROPIC_API_KEY")))
|
|
71
|
+
# Never print the value itself, even in development scripts.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
If this prints `False`, fix the `.env` location or `load_dotenv()` call before continuing.
|
|
75
|
+
|
|
76
|
+
## Integrate with existing infrastructure
|
|
77
|
+
|
|
78
|
+
If you already have a secrets manager, adapt rather than introduce a second source of truth. Common cases below; pick the closest match.
|
|
79
|
+
|
|
80
|
+
### HashiCorp Vault
|
|
81
|
+
|
|
82
|
+
Read secrets at process start, populate `os.environ`, and let the rest of the app use the env-var pattern above:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import hvac, os
|
|
86
|
+
|
|
87
|
+
client = hvac.Client(url=os.environ["VAULT_ADDR"], token=os.environ["VAULT_TOKEN"])
|
|
88
|
+
secrets = client.secrets.kv.v2.read_secret_version(path="myapp/prod")["data"]["data"]
|
|
89
|
+
for key, value in secrets.items():
|
|
90
|
+
os.environ.setdefault(key, value)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Use AppRole or Kubernetes auth in production; static `VAULT_TOKEN` is for local development only.
|
|
94
|
+
|
|
95
|
+
### AWS Secrets Manager
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import boto3, json, os
|
|
99
|
+
|
|
100
|
+
client = boto3.client("secretsmanager", region_name=os.environ["AWS_REGION"])
|
|
101
|
+
secret = json.loads(client.get_secret_value(SecretId="myapp/prod")["SecretString"])
|
|
102
|
+
for key, value in secret.items():
|
|
103
|
+
os.environ.setdefault(key, value)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Grant the application's IAM role `secretsmanager:GetSecretValue` on a single secret ARN, not `*`. Rotate via the built-in rotation Lambda, not by hand.
|
|
107
|
+
|
|
108
|
+
### GCP Secret Manager
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from google.cloud import secretmanager
|
|
112
|
+
import os
|
|
113
|
+
|
|
114
|
+
client = secretmanager.SecretManagerServiceClient()
|
|
115
|
+
def fetch(name: str) -> str:
|
|
116
|
+
path = f"projects/{os.environ['GCP_PROJECT']}/secrets/{name}/versions/latest"
|
|
117
|
+
return client.access_secret_version(name=path).payload.data.decode()
|
|
118
|
+
|
|
119
|
+
os.environ["ANTHROPIC_API_KEY"] = fetch("anthropic-api-key")
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Bind the service account to `roles/secretmanager.secretAccessor` on each secret, not at the project level.
|
|
123
|
+
|
|
124
|
+
### Doppler / 1Password / Infisical
|
|
125
|
+
|
|
126
|
+
These tools inject secrets as environment variables at process start via a CLI wrapper:
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
doppler run -- python app.py
|
|
130
|
+
op run --env-file=.env -- python app.py
|
|
131
|
+
infisical run -- python app.py
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Your application code does not change — it still reads `os.environ`. The wrapper handles fetch, decryption, and injection. Appropriate when you want centralized rotation without code changes.
|
|
135
|
+
|
|
136
|
+
These are developer-experience tools — good for smaller teams and centralized rotation. For regulated environments (SOC 2, HIPAA, FedRAMP), prefer the managed services above.
|
|
137
|
+
|
|
138
|
+
## Production considerations
|
|
139
|
+
|
|
140
|
+
Things to think about before deploying. None of these are blockers for the procedure that sent you here, but all of them affect whether your secret hygiene survives contact with a real environment.
|
|
141
|
+
|
|
142
|
+
### Rotation
|
|
143
|
+
|
|
144
|
+
Every secret should have a known rotation cadence. API keys: at least every 90 days, immediately on suspected compromise. Database credentials: managed by the secrets manager's rotation feature where available. Document the rotation procedure next to the secret definition; an undocumented secret is an unrotated secret.
|
|
145
|
+
|
|
146
|
+
For secrets that cannot rotate without downtime (primary database credentials on a live system), use dual-credential patterns — provision the new credential alongside the old, shift traffic, then revoke the old.
|
|
147
|
+
|
|
148
|
+
### Access control
|
|
149
|
+
|
|
150
|
+
Grant read access to specific secrets, not to the whole vault. Use separate credentials for development, staging, and production — a leaked dev key should not unlock prod. Audit access logs from your secrets manager; unexplained reads are an incident.
|
|
151
|
+
|
|
152
|
+
### Logging hygiene
|
|
153
|
+
|
|
154
|
+
Secrets must never appear in logs, error messages, stack traces, or telemetry. The `audit-logging` area procedure covers redaction patterns. At minimum, scrub `Authorization` headers, `*_KEY`, `*_SECRET`, `*_TOKEN`, `*_PASSWORD`, and connection strings before any log emit.
|
|
155
|
+
|
|
156
|
+
### Build-time vs runtime
|
|
157
|
+
|
|
158
|
+
Do not bake secrets into container images, build artifacts, or CI caches. Inject at runtime via the patterns above. A secret in a Docker layer is permanently exposed even after you "remove" it — image layers are append-only.
|
|
159
|
+
|
|
160
|
+
## After this file
|
|
161
|
+
|
|
162
|
+
Return to the area procedure that sent you here (`pii-handling`, `supply-chain`, or `rate-limiting`). The procedure's secret-handling checkpoint is satisfied once your application reads secrets from environment variables (or a managed source above) and your repository contains no hard-coded credentials.
|
|
163
|
+
|
|
164
|
+
## Related infrastructure
|
|
165
|
+
|
|
166
|
+
- `aigis infra logging` — redaction patterns to keep secrets out of log output.
|
|
167
|
+
- `aigis infra rate-limiting` — where the Redis connection string this file scopes for you actually gets used.
|