devkitx 1.0.0__py3-none-any.whl → 2.0.0__py3-none-any.whl
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.
- devkitx/__init__.py +56 -0
- devkitx/_version.py +3 -0
- devkitx/cli/__init__.py +5 -0
- devkitx/cli/main.py +328 -0
- devkitx/compliance/__init__.py +14 -0
- devkitx/compliance/audit_logger.py +173 -0
- devkitx/compliance/nist_controls.py +113 -0
- devkitx/compliance/pii_detector.py +137 -0
- devkitx/security/__init__.py +15 -0
- devkitx/security/crypto.py +135 -0
- devkitx/security/input_sanitizer.py +108 -0
- devkitx/security/secrets_scanner.py +121 -0
- devkitx/utils/__init__.py +18 -0
- devkitx/utils/json_utils.py +70 -0
- devkitx/utils/string_utils.py +124 -0
- devkitx/utils/time_utils.py +97 -0
- devkitx/utils/validation.py +81 -0
- devkitx-2.0.0.dist-info/METADATA +352 -0
- devkitx-2.0.0.dist-info/RECORD +21 -0
- {devkitx-1.0.0.dist-info → devkitx-2.0.0.dist-info}/WHEEL +1 -1
- devkitx-2.0.0.dist-info/entry_points.txt +2 -0
- devkitx-1.0.0.dist-info/METADATA +0 -560
- devkitx-1.0.0.dist-info/RECORD +0 -22
- devkitx-1.0.0.dist-info/entry_points.txt +0 -2
- devkitx-1.0.0.dist-info/licenses/LICENSE +0 -0
- devtools_py/__init__.py +0 -62
- devtools_py/__main__.py +0 -457
- devtools_py/async_utils.py +0 -436
- devtools_py/cli_utils.py +0 -320
- devtools_py/config_utils.py +0 -557
- devtools_py/data_utils.py +0 -288
- devtools_py/dev_utils.py +0 -393
- devtools_py/file_utils.py +0 -211
- devtools_py/http_utils.py +0 -346
- devtools_py/json_utils.py +0 -244
- devtools_py/log_utils.py +0 -158
- devtools_py/py.typed +0 -0
- devtools_py/security_utils.py +0 -326
- devtools_py/string_utils.py +0 -489
- devtools_py/system_utils.py +0 -262
- devtools_py/time_utils.py +0 -433
- devtools_py/validation_utils.py +0 -388
devkitx/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""DevKitX - Security-first Python utilities for regulated environments.
|
|
2
|
+
|
|
3
|
+
This package provides security and compliance-focused utilities for government,
|
|
4
|
+
healthcare, and financial applications. Features include audit logging, PII detection,
|
|
5
|
+
secrets scanning, and secure defaults.
|
|
6
|
+
|
|
7
|
+
Core features:
|
|
8
|
+
- NIST 800-53 compliant audit logging
|
|
9
|
+
- PII detection and scanning
|
|
10
|
+
- Secrets scanning for hardcoded credentials
|
|
11
|
+
- Secure HTTP clients with production defaults
|
|
12
|
+
- Configuration management with secret detection
|
|
13
|
+
- Async/sync conversion utilities
|
|
14
|
+
|
|
15
|
+
Example:
|
|
16
|
+
>>> from devkitx.compliance import AuditLogger
|
|
17
|
+
>>> from devkitx.security import SecretsScanner
|
|
18
|
+
>>>
|
|
19
|
+
>>> # Audit logging
|
|
20
|
+
>>> logger = AuditLogger(service="my-api")
|
|
21
|
+
>>> logger.log_auth("user_login", user_id="123", outcome="success")
|
|
22
|
+
>>>
|
|
23
|
+
>>> # Security scanning
|
|
24
|
+
>>> scanner = SecretsScanner()
|
|
25
|
+
>>> matches = scanner.scan_directory("./src")
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from ._version import __version__
|
|
29
|
+
|
|
30
|
+
# Re-export micro-package functionality
|
|
31
|
+
from asyncbridge import async_to_sync, sync_to_async
|
|
32
|
+
from httpx_defaults import Client as SecureClient, AsyncClient as SecureAsyncClient
|
|
33
|
+
from confmerge import load as load_config, merge as merge_config
|
|
34
|
+
|
|
35
|
+
# Core utilities
|
|
36
|
+
from .utils.json_utils import flatten_json
|
|
37
|
+
from .utils.string_utils import to_snake_case, to_camel_case, to_pascal_case, to_kebab_case
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"__version__",
|
|
41
|
+
# Async utilities
|
|
42
|
+
"async_to_sync",
|
|
43
|
+
"sync_to_async",
|
|
44
|
+
# HTTP utilities
|
|
45
|
+
"SecureClient",
|
|
46
|
+
"SecureAsyncClient",
|
|
47
|
+
# Config utilities
|
|
48
|
+
"load_config",
|
|
49
|
+
"merge_config",
|
|
50
|
+
# Core utilities
|
|
51
|
+
"flatten_json",
|
|
52
|
+
"to_snake_case",
|
|
53
|
+
"to_camel_case",
|
|
54
|
+
"to_pascal_case",
|
|
55
|
+
"to_kebab_case",
|
|
56
|
+
]
|
devkitx/_version.py
ADDED
devkitx/cli/__init__.py
ADDED
devkitx/cli/main.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""DevKitX CLI - Security-first developer utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
import typer
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
_CLI_AVAILABLE = True
|
|
13
|
+
except ImportError:
|
|
14
|
+
_CLI_AVAILABLE = False
|
|
15
|
+
|
|
16
|
+
if _CLI_AVAILABLE:
|
|
17
|
+
app = typer.Typer(
|
|
18
|
+
name="devkitx",
|
|
19
|
+
help="Security-first developer utilities for regulated environments.",
|
|
20
|
+
no_args_is_help=True,
|
|
21
|
+
)
|
|
22
|
+
console = Console()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def check_cli_deps() -> None:
|
|
26
|
+
"""Check CLI dependencies are installed."""
|
|
27
|
+
if not _CLI_AVAILABLE:
|
|
28
|
+
print(
|
|
29
|
+
"CLI requires additional dependencies.\n"
|
|
30
|
+
"Install with: pip install 'devkitx[cli]'"
|
|
31
|
+
)
|
|
32
|
+
sys.exit(1)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ============================================================================
|
|
36
|
+
# AUDIT COMMANDS
|
|
37
|
+
# ============================================================================
|
|
38
|
+
|
|
39
|
+
if _CLI_AVAILABLE:
|
|
40
|
+
audit_app = typer.Typer(help="Security auditing commands")
|
|
41
|
+
app.add_typer(audit_app, name="audit")
|
|
42
|
+
|
|
43
|
+
@audit_app.command("secrets")
|
|
44
|
+
def audit_secrets(
|
|
45
|
+
path: Path = typer.Argument(Path("."), help="Path to scan"),
|
|
46
|
+
output: str = typer.Option("table", help="Output format: table, json, sarif"),
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Scan for hardcoded secrets in source code."""
|
|
49
|
+
from ..security import SecretsScanner
|
|
50
|
+
|
|
51
|
+
scanner = SecretsScanner()
|
|
52
|
+
matches = list(scanner.scan_directory(path))
|
|
53
|
+
|
|
54
|
+
if not matches:
|
|
55
|
+
console.print("[green]✓ No secrets found[/green]")
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
if output == "json":
|
|
59
|
+
import json
|
|
60
|
+
print(json.dumps([{
|
|
61
|
+
"type": m.secret_type,
|
|
62
|
+
"file": m.file_path,
|
|
63
|
+
"line": m.line_number,
|
|
64
|
+
"severity": m.severity,
|
|
65
|
+
} for m in matches], indent=2))
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
# Table output
|
|
69
|
+
table = Table(title=f"Secrets Found: {len(matches)}")
|
|
70
|
+
table.add_column("Severity", style="bold")
|
|
71
|
+
table.add_column("Type")
|
|
72
|
+
table.add_column("File")
|
|
73
|
+
table.add_column("Line")
|
|
74
|
+
|
|
75
|
+
severity_colors = {
|
|
76
|
+
"critical": "red",
|
|
77
|
+
"high": "yellow",
|
|
78
|
+
"medium": "blue",
|
|
79
|
+
"low": "dim",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
for match in sorted(matches, key=lambda m: (
|
|
83
|
+
{"critical": 0, "high": 1, "medium": 2, "low": 3}[m.severity],
|
|
84
|
+
m.file_path,
|
|
85
|
+
)):
|
|
86
|
+
color = severity_colors.get(match.severity, "white")
|
|
87
|
+
table.add_row(
|
|
88
|
+
f"[{color}]{match.severity.upper()}[/{color}]",
|
|
89
|
+
match.secret_type,
|
|
90
|
+
match.file_path,
|
|
91
|
+
str(match.line_number),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
console.print(table)
|
|
95
|
+
sys.exit(1) # Exit with error if secrets found
|
|
96
|
+
|
|
97
|
+
@audit_app.command("pii")
|
|
98
|
+
def audit_pii(
|
|
99
|
+
path: Path = typer.Argument(Path("."), help="Path to scan"),
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Scan for PII (personally identifiable information)."""
|
|
102
|
+
from ..compliance import PIIDetector
|
|
103
|
+
|
|
104
|
+
detector = PIIDetector()
|
|
105
|
+
matches = list(detector.scan_directory(path))
|
|
106
|
+
|
|
107
|
+
if not matches:
|
|
108
|
+
console.print("[green]✓ No PII found[/green]")
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
table = Table(title=f"PII Found: {len(matches)}")
|
|
112
|
+
table.add_column("Type")
|
|
113
|
+
table.add_column("Value (Redacted)")
|
|
114
|
+
table.add_column("File")
|
|
115
|
+
table.add_column("Line")
|
|
116
|
+
|
|
117
|
+
for match in matches[:100]: # Limit output
|
|
118
|
+
table.add_row(
|
|
119
|
+
match.pii_type,
|
|
120
|
+
match.redacted,
|
|
121
|
+
match.file_path,
|
|
122
|
+
str(match.line_number),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
if len(matches) > 100:
|
|
126
|
+
console.print(f"[dim]... and {len(matches) - 100} more[/dim]")
|
|
127
|
+
|
|
128
|
+
console.print(table)
|
|
129
|
+
|
|
130
|
+
@audit_app.command("deps")
|
|
131
|
+
def audit_deps(
|
|
132
|
+
path: Path = typer.Argument(Path("."), help="Project path"),
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Check dependencies for known vulnerabilities."""
|
|
135
|
+
import subprocess
|
|
136
|
+
|
|
137
|
+
console.print("[bold]Checking dependencies for vulnerabilities...[/bold]\n")
|
|
138
|
+
|
|
139
|
+
# Try pip-audit first
|
|
140
|
+
try:
|
|
141
|
+
result = subprocess.run(
|
|
142
|
+
["pip-audit", "--strict"],
|
|
143
|
+
cwd=path,
|
|
144
|
+
capture_output=True,
|
|
145
|
+
text=True,
|
|
146
|
+
)
|
|
147
|
+
print(result.stdout)
|
|
148
|
+
if result.returncode != 0:
|
|
149
|
+
print(result.stderr)
|
|
150
|
+
sys.exit(1)
|
|
151
|
+
except FileNotFoundError:
|
|
152
|
+
console.print(
|
|
153
|
+
"[yellow]pip-audit not found. Install with: pip install pip-audit[/yellow]"
|
|
154
|
+
)
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# ============================================================================
|
|
159
|
+
# JSON COMMANDS
|
|
160
|
+
# ============================================================================
|
|
161
|
+
|
|
162
|
+
if _CLI_AVAILABLE:
|
|
163
|
+
json_app = typer.Typer(help="JSON utilities")
|
|
164
|
+
app.add_typer(json_app, name="json")
|
|
165
|
+
|
|
166
|
+
@json_app.command("flatten")
|
|
167
|
+
def json_flatten(
|
|
168
|
+
path: Path = typer.Argument(..., help="JSON file to flatten"),
|
|
169
|
+
) -> None:
|
|
170
|
+
"""Flatten nested JSON to dot notation."""
|
|
171
|
+
import json
|
|
172
|
+
from ..utils.json_utils import flatten_json
|
|
173
|
+
|
|
174
|
+
data = json.loads(path.read_text())
|
|
175
|
+
flat = flatten_json(data)
|
|
176
|
+
print(json.dumps(flat, indent=2))
|
|
177
|
+
|
|
178
|
+
@json_app.command("diff")
|
|
179
|
+
def json_diff(
|
|
180
|
+
file1: Path = typer.Argument(..., help="First JSON file"),
|
|
181
|
+
file2: Path = typer.Argument(..., help="Second JSON file"),
|
|
182
|
+
) -> None:
|
|
183
|
+
"""Show differences between two JSON files."""
|
|
184
|
+
import json
|
|
185
|
+
|
|
186
|
+
data1 = json.loads(file1.read_text())
|
|
187
|
+
data2 = json.loads(file2.read_text())
|
|
188
|
+
|
|
189
|
+
def diff_dict(d1: dict, d2: dict, path: str = "") -> None:
|
|
190
|
+
all_keys = set(d1.keys()) | set(d2.keys())
|
|
191
|
+
|
|
192
|
+
for key in sorted(all_keys):
|
|
193
|
+
current_path = f"{path}.{key}" if path else key
|
|
194
|
+
|
|
195
|
+
if key not in d1:
|
|
196
|
+
console.print(f"[green]+ {current_path}: {d2[key]}[/green]")
|
|
197
|
+
elif key not in d2:
|
|
198
|
+
console.print(f"[red]- {current_path}: {d1[key]}[/red]")
|
|
199
|
+
elif isinstance(d1[key], dict) and isinstance(d2[key], dict):
|
|
200
|
+
diff_dict(d1[key], d2[key], current_path)
|
|
201
|
+
elif d1[key] != d2[key]:
|
|
202
|
+
console.print(f"[red]- {current_path}: {d1[key]}[/red]")
|
|
203
|
+
console.print(f"[green]+ {current_path}: {d2[key]}[/green]")
|
|
204
|
+
|
|
205
|
+
diff_dict(data1, data2)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ============================================================================
|
|
209
|
+
# STRING COMMANDS
|
|
210
|
+
# ============================================================================
|
|
211
|
+
|
|
212
|
+
if _CLI_AVAILABLE:
|
|
213
|
+
string_app = typer.Typer(help="String utilities")
|
|
214
|
+
app.add_typer(string_app, name="string")
|
|
215
|
+
|
|
216
|
+
@string_app.command("convert")
|
|
217
|
+
def string_convert(
|
|
218
|
+
text: str = typer.Argument(..., help="Text to convert"),
|
|
219
|
+
to: str = typer.Option(..., "--to", help="Target case: snake, camel, pascal, kebab"),
|
|
220
|
+
) -> None:
|
|
221
|
+
"""Convert string between case formats."""
|
|
222
|
+
from ..utils import string_utils
|
|
223
|
+
|
|
224
|
+
converters = {
|
|
225
|
+
"snake": string_utils.to_snake_case,
|
|
226
|
+
"camel": string_utils.to_camel_case,
|
|
227
|
+
"pascal": string_utils.to_pascal_case,
|
|
228
|
+
"kebab": string_utils.to_kebab_case,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if to not in converters:
|
|
232
|
+
console.print(f"[red]Unknown case: {to}[/red]")
|
|
233
|
+
sys.exit(1)
|
|
234
|
+
|
|
235
|
+
print(converters[to](text))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# ============================================================================
|
|
239
|
+
# INIT COMMAND
|
|
240
|
+
# ============================================================================
|
|
241
|
+
|
|
242
|
+
if _CLI_AVAILABLE:
|
|
243
|
+
@app.command()
|
|
244
|
+
def init(
|
|
245
|
+
name: str = typer.Argument(..., help="Project name"),
|
|
246
|
+
template: str = typer.Option("basic", help="Template: basic, fastapi, django"),
|
|
247
|
+
) -> None:
|
|
248
|
+
"""Initialize a new project with secure defaults."""
|
|
249
|
+
path = Path(name)
|
|
250
|
+
if path.exists():
|
|
251
|
+
console.print(f"[red]Directory {name} already exists[/red]")
|
|
252
|
+
sys.exit(1)
|
|
253
|
+
|
|
254
|
+
# Create basic project structure
|
|
255
|
+
path.mkdir()
|
|
256
|
+
|
|
257
|
+
# Create basic files
|
|
258
|
+
(path / "README.md").write_text(f"# {name}\n\nA secure Python project created with DevKitX.\n")
|
|
259
|
+
(path / ".gitignore").write_text("""
|
|
260
|
+
# Python
|
|
261
|
+
__pycache__/
|
|
262
|
+
*.py[cod]
|
|
263
|
+
*$py.class
|
|
264
|
+
*.so
|
|
265
|
+
.Python
|
|
266
|
+
build/
|
|
267
|
+
develop-eggs/
|
|
268
|
+
dist/
|
|
269
|
+
downloads/
|
|
270
|
+
eggs/
|
|
271
|
+
.eggs/
|
|
272
|
+
lib/
|
|
273
|
+
lib64/
|
|
274
|
+
parts/
|
|
275
|
+
sdist/
|
|
276
|
+
var/
|
|
277
|
+
wheels/
|
|
278
|
+
*.egg-info/
|
|
279
|
+
.installed.cfg
|
|
280
|
+
*.egg
|
|
281
|
+
|
|
282
|
+
# Virtual environments
|
|
283
|
+
.env
|
|
284
|
+
.venv
|
|
285
|
+
env/
|
|
286
|
+
venv/
|
|
287
|
+
ENV/
|
|
288
|
+
env.bak/
|
|
289
|
+
venv.bak/
|
|
290
|
+
|
|
291
|
+
# IDE
|
|
292
|
+
.vscode/
|
|
293
|
+
.idea/
|
|
294
|
+
*.swp
|
|
295
|
+
*.swo
|
|
296
|
+
*~
|
|
297
|
+
|
|
298
|
+
# OS
|
|
299
|
+
.DS_Store
|
|
300
|
+
Thumbs.db
|
|
301
|
+
|
|
302
|
+
# Secrets
|
|
303
|
+
*.key
|
|
304
|
+
*.pem
|
|
305
|
+
secrets.json
|
|
306
|
+
.secrets
|
|
307
|
+
""".strip())
|
|
308
|
+
|
|
309
|
+
console.print(f"[green]✓ Created project: {name}[/green]")
|
|
310
|
+
console.print(f"\nNext steps:")
|
|
311
|
+
console.print(f" cd {name}")
|
|
312
|
+
console.print(f" python -m venv .venv")
|
|
313
|
+
console.print(f" source .venv/bin/activate # On Windows: .venv\\Scripts\\activate")
|
|
314
|
+
console.print(f" pip install devkitx[all]")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# ============================================================================
|
|
318
|
+
# MAIN ENTRY POINT
|
|
319
|
+
# ============================================================================
|
|
320
|
+
|
|
321
|
+
def main() -> None:
|
|
322
|
+
"""CLI entry point."""
|
|
323
|
+
check_cli_deps()
|
|
324
|
+
app()
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
if __name__ == "__main__":
|
|
328
|
+
main()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Compliance utilities for regulated environments."""
|
|
2
|
+
|
|
3
|
+
from .audit_logger import AuditLogger, AuditEvent
|
|
4
|
+
from .pii_detector import PIIDetector, PIIMatch
|
|
5
|
+
from .nist_controls import NISTControl, get_controls_for
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AuditLogger",
|
|
9
|
+
"AuditEvent",
|
|
10
|
+
"PIIDetector",
|
|
11
|
+
"PIIMatch",
|
|
12
|
+
"NISTControl",
|
|
13
|
+
"get_controls_for",
|
|
14
|
+
]
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""NIST 800-53 AU-compliant audit logging."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import datetime
|
|
7
|
+
import hashlib
|
|
8
|
+
import socket
|
|
9
|
+
from dataclasses import dataclass, field, asdict
|
|
10
|
+
from typing import Any, TextIO
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class AuditEvent:
|
|
16
|
+
"""Structured audit event meeting NIST AU-3 requirements.
|
|
17
|
+
|
|
18
|
+
NIST AU-3 requires: what, when, where, source, outcome, identity.
|
|
19
|
+
"""
|
|
20
|
+
# What happened
|
|
21
|
+
event_type: str
|
|
22
|
+
action: str
|
|
23
|
+
|
|
24
|
+
# When
|
|
25
|
+
timestamp: str = field(default_factory=lambda: datetime.datetime.utcnow().isoformat() + "Z")
|
|
26
|
+
|
|
27
|
+
# Where
|
|
28
|
+
hostname: str = field(default_factory=socket.gethostname)
|
|
29
|
+
service: str = ""
|
|
30
|
+
|
|
31
|
+
# Source
|
|
32
|
+
source_ip: str = ""
|
|
33
|
+
user_agent: str = ""
|
|
34
|
+
|
|
35
|
+
# Identity
|
|
36
|
+
user_id: str = ""
|
|
37
|
+
session_id: str = ""
|
|
38
|
+
|
|
39
|
+
# Outcome
|
|
40
|
+
outcome: str = "success" # success, failure, error
|
|
41
|
+
outcome_reason: str = ""
|
|
42
|
+
|
|
43
|
+
# Additional context
|
|
44
|
+
resource_type: str = ""
|
|
45
|
+
resource_id: str = ""
|
|
46
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
47
|
+
|
|
48
|
+
# Integrity
|
|
49
|
+
event_id: str = field(default="")
|
|
50
|
+
|
|
51
|
+
def __post_init__(self) -> None:
|
|
52
|
+
if not self.event_id:
|
|
53
|
+
# Generate deterministic event ID for integrity checking
|
|
54
|
+
content = f"{self.timestamp}{self.event_type}{self.action}{self.user_id}"
|
|
55
|
+
self.event_id = hashlib.sha256(content.encode()).hexdigest()[:16]
|
|
56
|
+
|
|
57
|
+
def to_json(self) -> str:
|
|
58
|
+
"""Serialize to JSON for logging."""
|
|
59
|
+
return json.dumps(asdict(self), separators=(",", ":"))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AuditLogger:
|
|
63
|
+
"""NIST-compliant audit logger.
|
|
64
|
+
|
|
65
|
+
Features:
|
|
66
|
+
- Structured JSON output (AU-3)
|
|
67
|
+
- Tamper-evident hashing (AU-9)
|
|
68
|
+
- Required fields enforcement (AU-3)
|
|
69
|
+
- Multiple output targets
|
|
70
|
+
|
|
71
|
+
Example:
|
|
72
|
+
>>> logger = AuditLogger(service="my-api")
|
|
73
|
+
>>> logger.log_auth("user_login", user_id="123", outcome="success")
|
|
74
|
+
>>> logger.log_access("read", resource_type="document", resource_id="doc-456")
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
service: str,
|
|
80
|
+
output: TextIO | Path | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.service = service
|
|
83
|
+
self._output = output
|
|
84
|
+
self._previous_hash: str = "0" * 64 # Chain for tamper evidence
|
|
85
|
+
|
|
86
|
+
def log(self, event: AuditEvent) -> None:
|
|
87
|
+
"""Log an audit event."""
|
|
88
|
+
# Add chain hash for tamper evidence (AU-9)
|
|
89
|
+
event.metadata["_chain_hash"] = self._compute_chain_hash(event)
|
|
90
|
+
|
|
91
|
+
line = event.to_json()
|
|
92
|
+
|
|
93
|
+
if self._output is None:
|
|
94
|
+
print(line)
|
|
95
|
+
elif isinstance(self._output, Path):
|
|
96
|
+
with open(self._output, "a") as f:
|
|
97
|
+
f.write(line + "\n")
|
|
98
|
+
else:
|
|
99
|
+
self._output.write(line + "\n")
|
|
100
|
+
self._output.flush()
|
|
101
|
+
|
|
102
|
+
self._previous_hash = event.metadata["_chain_hash"]
|
|
103
|
+
|
|
104
|
+
def log_auth(
|
|
105
|
+
self,
|
|
106
|
+
action: str,
|
|
107
|
+
user_id: str,
|
|
108
|
+
outcome: str = "success",
|
|
109
|
+
**kwargs: Any,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Log authentication event."""
|
|
112
|
+
event = AuditEvent(
|
|
113
|
+
event_type="authentication",
|
|
114
|
+
action=action,
|
|
115
|
+
service=self.service,
|
|
116
|
+
user_id=user_id,
|
|
117
|
+
outcome=outcome,
|
|
118
|
+
**kwargs,
|
|
119
|
+
)
|
|
120
|
+
self.log(event)
|
|
121
|
+
|
|
122
|
+
def log_access(
|
|
123
|
+
self,
|
|
124
|
+
action: str,
|
|
125
|
+
resource_type: str,
|
|
126
|
+
resource_id: str,
|
|
127
|
+
user_id: str = "",
|
|
128
|
+
outcome: str = "success",
|
|
129
|
+
**kwargs: Any,
|
|
130
|
+
) -> None:
|
|
131
|
+
"""Log resource access event."""
|
|
132
|
+
event = AuditEvent(
|
|
133
|
+
event_type="access",
|
|
134
|
+
action=action,
|
|
135
|
+
service=self.service,
|
|
136
|
+
resource_type=resource_type,
|
|
137
|
+
resource_id=resource_id,
|
|
138
|
+
user_id=user_id,
|
|
139
|
+
outcome=outcome,
|
|
140
|
+
**kwargs,
|
|
141
|
+
)
|
|
142
|
+
self.log(event)
|
|
143
|
+
|
|
144
|
+
def log_change(
|
|
145
|
+
self,
|
|
146
|
+
action: str,
|
|
147
|
+
resource_type: str,
|
|
148
|
+
resource_id: str,
|
|
149
|
+
user_id: str = "",
|
|
150
|
+
changes: dict[str, Any] | None = None,
|
|
151
|
+
**kwargs: Any,
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Log data change event."""
|
|
154
|
+
metadata = kwargs.pop("metadata", {})
|
|
155
|
+
if changes:
|
|
156
|
+
metadata["changes"] = changes
|
|
157
|
+
|
|
158
|
+
event = AuditEvent(
|
|
159
|
+
event_type="change",
|
|
160
|
+
action=action,
|
|
161
|
+
service=self.service,
|
|
162
|
+
resource_type=resource_type,
|
|
163
|
+
resource_id=resource_id,
|
|
164
|
+
user_id=user_id,
|
|
165
|
+
metadata=metadata,
|
|
166
|
+
**kwargs,
|
|
167
|
+
)
|
|
168
|
+
self.log(event)
|
|
169
|
+
|
|
170
|
+
def _compute_chain_hash(self, event: AuditEvent) -> str:
|
|
171
|
+
"""Compute chain hash for tamper evidence."""
|
|
172
|
+
content = f"{self._previous_hash}{event.event_id}{event.timestamp}"
|
|
173
|
+
return hashlib.sha256(content.encode()).hexdigest()
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""NIST 800-53 control mapping utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Dict, List
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class NISTControl:
|
|
11
|
+
"""NIST 800-53 security control."""
|
|
12
|
+
control_id: str
|
|
13
|
+
title: str
|
|
14
|
+
description: str
|
|
15
|
+
family: str
|
|
16
|
+
priority: str # low, moderate, high
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# NIST 800-53 controls relevant to DevKitX features
|
|
20
|
+
NIST_CONTROLS = {
|
|
21
|
+
"AU-2": NISTControl(
|
|
22
|
+
control_id="AU-2",
|
|
23
|
+
title="Audit Events",
|
|
24
|
+
description="Identify the types of events that the system is capable of auditing",
|
|
25
|
+
family="Audit and Accountability",
|
|
26
|
+
priority="moderate"
|
|
27
|
+
),
|
|
28
|
+
"AU-3": NISTControl(
|
|
29
|
+
control_id="AU-3",
|
|
30
|
+
title="Content of Audit Records",
|
|
31
|
+
description="Ensure audit records contain information that establishes what, when, where, source, outcome, and identity",
|
|
32
|
+
family="Audit and Accountability",
|
|
33
|
+
priority="moderate"
|
|
34
|
+
),
|
|
35
|
+
"AU-9": NISTControl(
|
|
36
|
+
control_id="AU-9",
|
|
37
|
+
title="Protection of Audit Information",
|
|
38
|
+
description="Protect audit information and audit logging tools from unauthorized access, modification, and deletion",
|
|
39
|
+
family="Audit and Accountability",
|
|
40
|
+
priority="moderate"
|
|
41
|
+
),
|
|
42
|
+
"SA-3": NISTControl(
|
|
43
|
+
control_id="SA-3",
|
|
44
|
+
title="System Development Life Cycle",
|
|
45
|
+
description="Manage the system using a system development life cycle methodology that includes information security considerations",
|
|
46
|
+
family="System and Services Acquisition",
|
|
47
|
+
priority="moderate"
|
|
48
|
+
),
|
|
49
|
+
"SC-8": NISTControl(
|
|
50
|
+
control_id="SC-8",
|
|
51
|
+
title="Transmission Confidentiality and Integrity",
|
|
52
|
+
description="Protect the confidentiality and integrity of transmitted information",
|
|
53
|
+
family="System and Communications Protection",
|
|
54
|
+
priority="moderate"
|
|
55
|
+
),
|
|
56
|
+
"SC-13": NISTControl(
|
|
57
|
+
control_id="SC-13",
|
|
58
|
+
title="Cryptographic Protection",
|
|
59
|
+
description="Implement cryptographic mechanisms to prevent unauthorized disclosure of information",
|
|
60
|
+
family="System and Communications Protection",
|
|
61
|
+
priority="moderate"
|
|
62
|
+
),
|
|
63
|
+
"SC-28": NISTControl(
|
|
64
|
+
control_id="SC-28",
|
|
65
|
+
title="Protection of Information at Rest",
|
|
66
|
+
description="Protect the confidentiality and integrity of information at rest",
|
|
67
|
+
family="System and Communications Protection",
|
|
68
|
+
priority="moderate"
|
|
69
|
+
),
|
|
70
|
+
"SI-12": NISTControl(
|
|
71
|
+
control_id="SI-12",
|
|
72
|
+
title="Information Handling and Retention",
|
|
73
|
+
description="Handle and retain information within the system and information output from the system",
|
|
74
|
+
family="System and Information Integrity",
|
|
75
|
+
priority="moderate"
|
|
76
|
+
),
|
|
77
|
+
"PM-25": NISTControl(
|
|
78
|
+
control_id="PM-25",
|
|
79
|
+
title="Minimization of Personally Identifiable Information",
|
|
80
|
+
description="Implement policies and procedures to minimize the use of personally identifiable information",
|
|
81
|
+
family="Program Management",
|
|
82
|
+
priority="moderate"
|
|
83
|
+
),
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def get_controls_for(feature: str) -> List[NISTControl]:
|
|
88
|
+
"""Get NIST controls relevant to a DevKitX feature.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
feature: DevKitX feature name
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
List of relevant NIST controls
|
|
95
|
+
|
|
96
|
+
Example:
|
|
97
|
+
>>> controls = get_controls_for("audit_logger")
|
|
98
|
+
>>> for control in controls:
|
|
99
|
+
... print(f"{control.control_id}: {control.title}")
|
|
100
|
+
AU-2: Audit Events
|
|
101
|
+
AU-3: Content of Audit Records
|
|
102
|
+
AU-9: Protection of Audit Information
|
|
103
|
+
"""
|
|
104
|
+
feature_mapping = {
|
|
105
|
+
"audit_logger": ["AU-2", "AU-3", "AU-9"],
|
|
106
|
+
"secrets_scanner": ["SA-3", "SC-28"],
|
|
107
|
+
"pii_detector": ["SI-12", "PM-25"],
|
|
108
|
+
"secure_client": ["SC-8", "SC-13"],
|
|
109
|
+
"http_defaults": ["SC-8", "SC-13"],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
control_ids = feature_mapping.get(feature, [])
|
|
113
|
+
return [NIST_CONTROLS[control_id] for control_id in control_ids if control_id in NIST_CONTROLS]
|