Implement tamper-evident audit logs for compliance (SOC 2, HIPAA, PCI DSS). Use when building compliance audit trails, tracking who did what and when, or implementing immutable event logs that satisfy regulatory retention requirements.
Compliance audit logs must answer: who did what to which resource, when, from where, and with what result. They must also be tamper-evident — an auditor must be able to verify logs haven't been modified.
Regulatory retention requirements:
Standard
Retention
HIPAA
6 years
PCI DSS
12 months online + 12 months archive
SOC 2 (typical)
1 year
GDPR
Defined by purpose (often 1-3 years)
Required Log Fields
interface AuditLogEntry {
// Core required fields
id: string; // UUID — unique event identifier
timestamp: string; // ISO 8601 UTC — when the event occurred
actor_id: string; // User/service that performed the action
actor_type: 'user' | 'service' | 'admin' | 'system';
action: string; // What happened: "read" | "write" | "delete" | "login" | "export"
resource_type: string; // "patient_record" | "invoice" | "user_account"
resource_id: string; // ID of the affected resource
result: 'success' | 'failure' | 'denied';
// Context fields
ip_address: string; // Source IP
user_agent?: string; // Browser/client identifier
session_id?: string; // Session identifier
// Optional fields
changed_fields?: string[]; // For write operations: which fields changed
old_values?: Record<string, unknown>; // Previous values (be careful with PII)
reason?: string; // Clinical justification (HIPAA), business reason
// Tamper-evidence
prev_hash?: string; // Hash of previous log entry (hash chaining)
hash: string; // SHA-256 of this entry
}
Hash Chain Implementation
Hash chaining makes log tampering detectable: each entry includes a hash of the previous entry. Modifying any entry breaks the chain.
import json
import hashlib
import uuid
from datetime import datetime, timezone
from typing import Optional
class AuditLogger:
def __init__(self, db_connection):
self.db = db_connection
self._last_hash: Optional[str] = None
def _compute_hash(self, entry: dict, prev_hash: Optional[str]) -> str:
"""Compute SHA-256 of the log entry for tamper-evidence."""
hashable = {
"id": entry["id"],
"timestamp": entry["timestamp"],
"actor_id": entry["actor_id"],
"action": entry["action"],
"resource_type": entry["resource_type"],
"resource_id": entry["resource_id"],
"result": entry["result"],
"prev_hash": prev_hash or "GENESIS"
}
content = json.dumps(hashable, sort_keys=True)
return hashlib.sha256(content.encode()).hexdigest()
async def log(
self,
actor_id: str,
actor_type: str,
action: str,
resource_type: str,
resource_id: str,
result: str,
ip_address: str,
**kwargs
) -> dict:
"""Create and persist a tamper-evident audit log entry."""
# Get last hash for chaining
prev_hash = self._last_hash or await self._get_last_hash()
entry = {
"id": str(uuid.uuid4()),
"timestamp": datetime.now(timezone.utc).isoformat(),
"actor_id": actor_id,
"actor_type": actor_type,
"action": action,
"resource_type": resource_type,
"resource_id": resource_id,
"result": result,
"ip_address": ip_address,
"prev_hash": prev_hash or "GENESIS",
**kwargs
}
entry["hash"] = self._compute_hash(entry, prev_hash)
self._last_hash = entry["hash"]
# Persist to append-only storage
await self.db.audit_logs.insert_one(entry)
return entry
async def verify_chain(self, limit: int = 1000) -> bool:
"""Verify the hash chain integrity."""
entries = await self.db.audit_logs.find(
sort=[("timestamp", 1)],
limit=limit
)
prev_hash = "GENESIS"
for i, entry in enumerate(entries):
expected_hash = self._compute_hash(entry, prev_hash)
if entry["hash"] != expected_hash:
print(f"❌ Chain broken at entry {i}: id={entry['id']}")
return False
if entry["prev_hash"] != prev_hash:
print(f"❌ prev_hash mismatch at entry {i}")
return False
prev_hash = entry["hash"]
print(f"✅ Chain verified: {len(entries)} entries intact")
return True
async def _get_last_hash(self) -> Optional[str]:
last = await self.db.audit_logs.find_one(sort=[("timestamp", -1)])
return last["hash"] if last else None
-- Append-only audit log table
-- The CHECK constraint and trigger prevent UPDATE/DELETE
CREATE TABLE audit_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
actor_id TEXT NOT NULL,
actor_type TEXT NOT NULL CHECK (actor_type IN ('user', 'service', 'admin', 'system')),
action TEXT NOT NULL,
resource_type TEXT NOT NULL,
resource_id TEXT NOT NULL,
result TEXT NOT NULL CHECK (result IN ('success', 'failure', 'denied')),
ip_address INET,
session_id TEXT,
reason TEXT,
changed_fields TEXT[],
prev_hash TEXT,
hash TEXT NOT NULL UNIQUE
);
-- Create append-only trigger — prevent modification
CREATE OR REPLACE FUNCTION prevent_audit_modification()
RETURNS TRIGGER AS $$
BEGIN
RAISE EXCEPTION 'Audit logs are immutable — modification not allowed';
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER audit_logs_immutable
BEFORE UPDATE OR DELETE ON audit_logs
FOR EACH ROW EXECUTE FUNCTION prevent_audit_modification();
-- Indexes for common queries
CREATE INDEX idx_audit_actor_id ON audit_logs(actor_id);
CREATE INDEX idx_audit_resource ON audit_logs(resource_type, resource_id);
CREATE INDEX idx_audit_timestamp ON audit_logs(timestamp DESC);
CREATE INDEX idx_audit_action ON audit_logs(action);
-- Query: All actions by a user in the last 30 days
SELECT timestamp, action, resource_type, resource_id, result, ip_address
FROM audit_logs
WHERE actor_id = 'user-123'
AND timestamp > NOW() - INTERVAL '30 days'
ORDER BY timestamp DESC;
-- Query: All access to a specific patient record
SELECT timestamp, actor_id, action, result, ip_address, reason
FROM audit_logs
WHERE resource_type = 'patient_record'
AND resource_id = 'patient-456'
ORDER BY timestamp DESC;
-- Query: Failed access attempts (security monitoring)
SELECT actor_id, COUNT(*) as failed_attempts, MAX(timestamp) as last_attempt
FROM audit_logs
WHERE result IN ('failure', 'denied')
AND timestamp > NOW() - INTERVAL '24 hours'
GROUP BY actor_id
HAVING COUNT(*) > 5
ORDER BY failed_attempts DESC;
Scripts and configures production rendering in Autodesk 3ds Max with the V-Ray and Corona renderers: output size and files, render elements, denoising, light mix, batch and command-line rendering, and network rendering. Use when a user asks to set up a production render, render several cameras in one batch, render from the command line or on a render farm, add render passes for compositing, or cut render time for archviz and product shots.
Covers scripting Autodesk 3ds Max, the 3D modeling and rendering application, with MAXScript and Python (pymxs): scene manipulation, object creation, material assignment, camera and light setup, batch operations, and file I/O. Use when tasks involve automating repetitive 3ds Max workflows, batch processing scenes, running scripts headless with 3dsmaxbatch, creating custom tools, or scripting scene setup for archviz, product visualization, or VFX.
3proxy is a small open-source proxy server that runs HTTP/HTTPS, SOCKS4/5, SNI and TCP/UDP port-mapping proxies from one config file. Use when a user asks to set up an HTTP or SOCKS5 proxy, add proxy users and passwords, write 3proxy access rules, chain or rotate upstream (parent) proxies, limit bandwidth, connections or monthly traffic per user, run 3proxy in Docker, or fix a 3proxy.cfg that will not start.
Builds Agent2Agent (A2A) servers and clients, the open protocol (originally from Google, now under the Linux Foundation) that lets AI agents from different frameworks call each other. Use when the user wants to create an A2A-compliant agent, build an Agent Card, implement task management, connect agents across frameworks, set up agent discovery, handle streaming responses, implement push notifications, or orchestrate multi-agent workflows. Trigger words: a2a, agent to agent, agent2agent, a2a protocol, a2a server, a2a client, agent card, agent interoperability, agent collaboration, multi-agent, agent discovery, a2a sdk, a2a task.
Plans a controlled experiment (A/B test) so its result can be trusted: writes the hypothesis, picks one primary metric and the guardrails, computes sample size and run time, specifies how visitors are assigned and when exposure is logged, and reads out the result with a confidence interval. Use when someone says "set up an A/B test", "split test this page", "how many visitors do I need", "how long should the experiment run", "is this result significant", "can I stop the test early", or wants to test a headline, price, layout or onboarding change against the current version.
Ably is a hosted realtime messaging service: clients publish and subscribe to named channels over WebSockets, see who is present, replay message history, and resume after a dropped connection. Use when a user asks to "add realtime updates", "push live notifications to the browser", "show who is online", "add a chat room with typing indicators", "publish from a serverless function", or "authenticate Ably clients without exposing the API key". Covers the ably 2.x JavaScript SDK (Realtime and REST), JWT token authentication, presence, history and rewind, batch publishing, and the @ably/chat 1.x SDK.