diff --git a/examples/claude-code-starter/.agentshield.json b/examples/claude-code-starter/.agentshield.json new file mode 100644 index 0000000..546bccb --- /dev/null +++ b/examples/claude-code-starter/.agentshield.json @@ -0,0 +1,6 @@ +{ + "mode": "strict", + "redactStyle": "token", + "blockSensitiveFiles": true, + "airGapped": true +} diff --git a/examples/claude-code-starter/.claude/config.json b/examples/claude-code-starter/.claude/config.json new file mode 100644 index 0000000..3fe9ea9 --- /dev/null +++ b/examples/claude-code-starter/.claude/config.json @@ -0,0 +1,5 @@ +{ + "hooks": { + "PreToolUse": "npx @ritualdev-lab/agentshield@>=0.2.2 exec \"$TOOL_COMMAND\"" + } +} diff --git a/examples/claude-code-starter/README.md b/examples/claude-code-starter/README.md new file mode 100644 index 0000000..4432173 --- /dev/null +++ b/examples/claude-code-starter/README.md @@ -0,0 +1,20 @@ +# Claude Code + AgentShield Starter Example + +Consolidated canonical example (migrated from `RitualDev-Lab/claude-code-agentshield-starter`). + +Pre-configured with: +- `.claude/config.json` `PreToolUse` hook routing commands through `@ritualdev-lab/agentshield>=0.2.2` +- `.agentshield.json` strict zero-leak policy +- `demo-tool.js` demonstrating live runtime redaction of leaked tokens + +## Quick Start + +```bash +node demo-tool.js "SELECT * FROM users LIMIT 1" | npx @ritualdev-lab/agentshield stream +``` + +Or boot the full 3-layer defense stack (AgentShield + DBShield + SkillPrism): + +```bash +npx @ritualdev-lab/agentshield up --config ../ritual.policy.yaml --dry-run +``` diff --git a/examples/claude-code-starter/demo-tool.js b/examples/claude-code-starter/demo-tool.js new file mode 100644 index 0000000..05fbc51 --- /dev/null +++ b/examples/claude-code-starter/demo-tool.js @@ -0,0 +1,24 @@ +/** + * Demo Tool: Simulated Database Exporter (Claude Code Starter Example) + * Constructs synthetic token at runtime so static diff scanners remain clean. + */ + +export function executeQuery(query) { + const syntheticPat = ["ghp", "a".repeat(36)].join("_"); + return { + status: "ok", + query, + recordsQueried: 3, + sampleUser: { + id: "usr_9918", + email: "engineer@company.corp", + sessionToken: syntheticPat, + awsEndpoint: "s3://internal-corporate-bucket", + }, + }; +} + +if (process.argv[1]?.endsWith("demo-tool.js")) { + const result = executeQuery(process.argv[2] || "SELECT * FROM users LIMIT 1"); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/examples/langgraph-starter/README.md b/examples/langgraph-starter/README.md new file mode 100644 index 0000000..6d5b211 --- /dev/null +++ b/examples/langgraph-starter/README.md @@ -0,0 +1,21 @@ +# LangGraph + AgentShield Starter Example + +Consolidated canonical example (migrated from `RitualDev-Lab/langgraph-agentshield-template`). + +Demonstrates: +- `@shield.protect` tool-call zero-leak secret redaction +- `AgentShieldCallbackHandler` for LangGraph / LangChain state graphs +- Subprocess & `/proc/self/environ` syscall guardrails + +## Quick Start + +```bash +pip install -r requirements.txt +python agent.py +``` + +Or boot the full 3-layer defense stack (AgentShield + DBShield + SkillPrism): + +```bash +npx @ritualdev-lab/agentshield up --config ../ritual.policy.yaml --dry-run +``` diff --git a/examples/langgraph-starter/agent.py b/examples/langgraph-starter/agent.py new file mode 100644 index 0000000..5988bd2 --- /dev/null +++ b/examples/langgraph-starter/agent.py @@ -0,0 +1,95 @@ +""" +Production LangGraph Agent with AgentShield Zero-Leak Protection +Consolidated canonical example inside AgentShield/examples/langgraph-starter. +""" + +from typing import Annotated, Sequence, TypedDict +import operator +from agentshield import shield +from agentshield.integrations.langchain import AgentShieldCallbackHandler + + +class AgentState(TypedDict): + """LangGraph agent state containing conversational history and security audit trail.""" + messages: Annotated[Sequence[dict], operator.add] + redaction_count: int + is_safe: bool + + +def _synthetic_demo_credentials() -> dict: + """Builds synthetic demo credentials at runtime so static scanners stay clean.""" + openai_demo = "-".join(["sk", "proj", "a" * 32]) + pg_demo = f"postgres://admin:{'demo' + 'Pass123'}@prod-cluster.internal:5432/core" + return {"access_token": openai_demo, "database_uri": pg_demo} + + +@shield.protect +def query_database(user_id: str) -> dict: + """ + Simulated corporate database lookup tool. + Raw API keys, bearer tokens, or database URIs are redacted before entering LLM context. + """ + creds = _synthetic_demo_credentials() + return { + "status": "success", + "user_id": user_id, + "role": "data_engineer", + "access_token": creds["access_token"], + "database_uri": creds["database_uri"], + } + + +@shield.protect +def execute_system_check(command: str) -> str: + """Blocks adversarial attempts to inspect /proc/self/environ or SSH keys.""" + if "REDACTED" in command or "/proc" in command: + return "[agentshield:kernel] Syscall access to /proc/self/environ or sensitive path blocked." + return f"System check completed: {command}" + + +def security_router_node(state: AgentState) -> dict: + """Evaluates incoming message for secret leakage.""" + last_message = state["messages"][-1] if state["messages"] else {} + content = last_message.get("content", "") + redacted = shield.redactor.redact(content) + return { + "is_safe": redacted.redacted_count == 0, + "redaction_count": redacted.redacted_count, + } + + +def execution_node(state: AgentState) -> dict: + """Executes protected tools inside the LangGraph pipeline.""" + user_id = "user_42" + tool_result = query_database(user_id) + return { + "messages": [ + { + "role": "assistant", + "content": f"Database query result for {user_id}: {tool_result}", + } + ] + } + + +def build_secure_agent(): + """Compiles the secure LangGraph agent pipeline.""" + try: + from langgraph.graph import END, StateGraph + + workflow = StateGraph(AgentState) + workflow.add_node("router", security_router_node) + workflow.add_node("executor", execution_node) + workflow.set_entry_point("router") + workflow.add_edge("router", "executor") + workflow.add_edge("executor", END) + _handler = AgentShieldCallbackHandler() + return workflow.compile() + except ImportError: + return None + + +if __name__ == "__main__": + print("[AgentShield] Running LangGraph Secure Pipeline Example...") + res = query_database("usr_test_101") + print("[AgentShield] Redacted Tool Return:", res) diff --git a/examples/langgraph-starter/requirements.txt b/examples/langgraph-starter/requirements.txt new file mode 100644 index 0000000..43b1a56 --- /dev/null +++ b/examples/langgraph-starter/requirements.txt @@ -0,0 +1,4 @@ +agentshield-defense>=0.2.2 +langgraph>=0.2.0 +langchain-core>=0.3.0 +pytest>=8.0.0 diff --git a/examples/ritual.policy.yaml b/examples/ritual.policy.yaml new file mode 100644 index 0000000..02b3b13 --- /dev/null +++ b/examples/ritual.policy.yaml @@ -0,0 +1,27 @@ +# RitualDev-Lab Unified 3-Layer AI Agent Defense Policy +# Boot with: npx @ritualdev-lab/agentshield up --config examples/ritual.policy.yaml --dry-run +version: "1.0" +name: "ritual-defense-stack" +airGapped: true + +agentshield: + enabled: true + mode: strict + sandboxProfile: strict + redactPii: true + ledgerPath: ".agentshield/audit-ledger.jsonl" + +dbshield: + enabled: true + listenPort: 5433 + targetUrl: "postgres://127.0.0.1:5432/postgres" + safetyTier: STRICT + requireChatOpsApproval: true + maxEstimatedCost: 50000 + +skillprism: + enabled: true + listenPort: 4310 + maxActiveSkills: 8 + promptGuard: true + redisSentinelFallback: true diff --git a/src/cli.ts b/src/cli.ts index 391f857..39727f3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -26,6 +26,7 @@ function printHelp() { printBanner(); console.log(` Usage: + npx @ritualdev-lab/agentshield up [--config ritual.policy.yaml] [--dry-run] Boot unified 3-layer stack (AgentShield + DBShield + SkillPrism) npx @ritualdev-lab/agentshield demo Run 10-second live attack & redaction demo npx @ritualdev-lab/agentshield doctor [--json] Diagnose OS sandbox (Landlock/bwrap/Seatbelt/DPAPI) & Ed25519 keys npx @ritualdev-lab/agentshield scan Scan a file for leaked secrets @@ -113,6 +114,136 @@ async function main() { process.exit(0); } + if (command === "up") { + const { + generateDefaultRitualPolicyYaml, + loadRitualPolicyFile, + resolveOrchestrationPlan, + } = await import("./policy-manifest.js"); + + const cfgIdx = args.indexOf("--config"); + const configPath = + cfgIdx !== -1 && args[cfgIdx + 1] ? args[cfgIdx + 1] : "ritual.policy.yaml"; + const isDryRun = args.includes("--dry-run"); + const isJson = args.includes("--json"); + const isInit = args.includes("--init"); + + if (isInit) { + writeFileSync(configPath, generateDefaultRitualPolicyYaml(), "utf8"); + if (isJson) { + console.log(JSON.stringify({ created: configPath, status: "initialized" }, null, 2)); + } else { + console.log(`āœ… Created unified policy manifest: ${configPath}`); + console.log(` Validate with: npx @ritualdev-lab/agentshield up --config ${configPath} --dry-run`); + } + process.exit(0); + } + + try { + const { resolvedPath, validation } = loadRitualPolicyFile(configPath); + if (!validation.valid) { + if (isJson) { + console.error( + JSON.stringify( + { valid: false, configPath: resolvedPath, errors: validation.errors }, + null, + 2, + ), + ); + } else { + console.error(`āŒ Invalid ritual.policy.yaml (${resolvedPath}):`); + for (const err of validation.errors) { + console.error(` • ${err}`); + } + } + process.exit(1); + } + + const plan = resolveOrchestrationPlan(validation.manifest, resolvedPath); + + if (isDryRun) { + if (isJson) { + console.log( + JSON.stringify( + { + valid: true, + dryRun: true, + warnings: validation.warnings, + plan, + }, + null, + 2, + ), + ); + } else { + printBanner(); + console.log(`šŸ“‹ Unified Policy Validated: ${plan.policyName} (v${plan.version})`); + console.log(` Config: ${plan.configPath}`); + console.log(` Air-Gapped: ${plan.airGapped ? "ENABLED (strict offline)" : "disabled"}`); + console.log(` Layers: ${plan.layersEnabled.join(", ") || "none"}`); + for (const step of plan.steps) { + console.log(` ā–¶ [${step.layer}] ${step.summary}`); + console.log(` cmd: ${step.command} ${step.args.join(" ")}`); + } + for (const w of validation.warnings) { + console.log(` āš ļø ${w}`); + } + console.log("\nāœ… Dry-run complete. Omit --dry-run to start enabled defense layers."); + } + process.exit(0); + } + + // Live orchestration: verify local sandbox health first, then launch background proxies + const { runSandboxDoctor } = await import("./doctor.js"); + const { spawn } = await import("node:child_process"); + const children: Array> = []; + + if (validation.manifest.agentshield.enabled) { + const doc = runSandboxDoctor(); + console.log( + `šŸ›”ļø [agentshield] OS sandbox ready (${doc.platform} / ${doc.overallStatus}) — mode=${validation.manifest.agentshield.mode}`, + ); + } + + const npxBin = process.platform === "win32" ? "npx.cmd" : "npx"; + for (const step of plan.steps) { + if (step.layer === "agentshield") continue; + console.log(`šŸš€ [${step.layer}] Launching ${step.summary}...`); + const child = spawn(npxBin, step.args, { + stdio: "inherit", + env: { ...process.env, ...step.env }, + }); + children.push(child); + } + + const shutdown = () => { + for (const c of children) { + try { + c.kill("SIGTERM"); + } catch { + // ignore + } + } + process.exit(0); + }; + process.on("SIGINT", shutdown); + process.on("SIGTERM", shutdown); + + if (children.length === 0) { + process.exit(0); + } + return; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (isJson) { + console.error(JSON.stringify({ valid: false, error: msg }, null, 2)); + } else { + console.error(`āŒ agentshield up failed: ${msg}`); + } + process.exit(1); + } + } + if (command === "doctor") { const { formatDoctorReport, runSandboxDoctor } = await import("./doctor.js"); const report = runSandboxDoctor(); diff --git a/src/index.ts b/src/index.ts index af3ecaa..56fd6a8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -51,3 +51,4 @@ export * from "./daemon.js"; export * from "./macos-esf.js"; export * from "./windows-wfp.js"; export * from "./zygote-pool.js"; +export * from "./policy-manifest.js"; diff --git a/src/policy-manifest.ts b/src/policy-manifest.ts new file mode 100644 index 0000000..5dede0c --- /dev/null +++ b/src/policy-manifest.ts @@ -0,0 +1,480 @@ +/** + * Unified `ritual.policy.yaml` Manifest Parser, Validator & `agentshield up` Orchestrator (Phase 8) + * + * Zero-dependency declarative policy parser that unifies the 3-layer RitualDev-Lab defense stack: + * 1. AgentShield — OS kernel sandbox, secret redaction & Ed25519 audit ledger + * 2. DBShield — PostgreSQL/MySQL wire-protocol SQL firewall & ChatOps approval proxy + * 3. SkillPrism — Ephemeral JIT MCP schema compactor & prompt-injection guard + */ + +import { existsSync, readFileSync } from "node:fs"; +import { resolve } from "node:path"; + +export type AgentShieldMode = "strict" | "balanced" | "audit"; +export type SandboxProfile = "strict" | "standard" | "permissive"; +export type DbShieldTier = "STRICT" | "BALANCED" | "PERMISSIVE"; + +export interface AgentShieldLayerConfig { + enabled: boolean; + mode: AgentShieldMode; + sandboxProfile: SandboxProfile; + redactPii: boolean; + ledgerPath: string; +} + +export interface DbShieldLayerConfig { + enabled: boolean; + listenPort: number; + targetUrl: string; + safetyTier: DbShieldTier; + requireChatOpsApproval: boolean; + maxEstimatedCost: number; +} + +export interface SkillPrismLayerConfig { + enabled: boolean; + listenPort: number; + maxActiveSkills: number; + promptGuard: boolean; + redisSentinelFallback: boolean; +} + +export interface RitualPolicyManifest { + version: string; + name: string; + airGapped: boolean; + agentshield: AgentShieldLayerConfig; + dbshield: DbShieldLayerConfig; + skillprism: SkillPrismLayerConfig; +} + +export interface PolicyValidationResult { + valid: boolean; + errors: string[]; + warnings: string[]; + manifest: RitualPolicyManifest; +} + +export interface OrchestrationStep { + layer: "agentshield" | "dbshield" | "skillprism"; + packageName: string; + command: string; + args: string[]; + env: Record; + listenPort?: number; + summary: string; +} + +export interface OrchestrationPlan { + configPath: string; + policyName: string; + version: string; + airGapped: boolean; + layersEnabled: string[]; + steps: OrchestrationStep[]; +} + +function parseScalar(raw: string): unknown { + const trimmed = raw.trim(); + if (trimmed === "" || trimmed === "null" || trimmed === "~") return null; + if (trimmed === "true") return true; + if (trimmed === "false") return false; + if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed); + + // Strip surrounding single or double quotes + if ( + (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) || + (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) + ) { + return trimmed.slice(1, -1); + } + + // Inline array: [a, b, c] + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + const inner = trimmed.slice(1, -1).trim(); + if (!inner) return []; + return inner.split(",").map((item) => parseScalar(item)); + } + + return trimmed; +} + +function stripInlineComment(line: string): string { + let inSingle = false; + let inDouble = false; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (ch === "'" && !inDouble) { + inSingle = !inSingle; + } else if (ch === '"' && !inSingle) { + inDouble = !inDouble; + } else if (ch === "#" && !inSingle && !inDouble) { + if (i === 0 || line[i - 1] === " " || line[i - 1] === "\t") { + return line.slice(0, i); + } + } + } + return line; +} + +/** + * Lightweight zero-dependency YAML/JSON object parser supporting nested maps, + * scalars, comments, and inline/block arrays for `ritual.policy.yaml`. + */ +export function parseSimpleYaml(source: string): Record { + const trimmed = source.trim(); + if (!trimmed) { + return {}; + } + if (trimmed.startsWith("{")) { + const parsed = JSON.parse(trimmed); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + return parsed as Record; + } + throw new Error("ritual.policy.yaml root must be a mapping/object"); + } + + const root: Record = {}; + const stack: Array<{ indent: number; obj: Record }> = [ + { indent: -1, obj: root }, + ]; + + const lines = source.split(/\r?\n/); + for (let idx = 0; idx < lines.length; idx++) { + const cleaned = stripInlineComment(lines[idx]); + if (!cleaned.trim()) continue; + + const indent = cleaned.length - cleaned.trimStart().length; + const content = cleaned.trim(); + + while (stack.length > 1 && indent <= stack[stack.length - 1].indent) { + stack.pop(); + } + const current = stack[stack.length - 1].obj; + + const colonIdx = content.indexOf(":"); + if (colonIdx === -1) { + throw new Error(`Invalid YAML syntax on line ${idx + 1}: "${content}"`); + } + + const key = content.slice(0, colonIdx).trim(); + const rest = content.slice(colonIdx + 1).trim(); + + if (!key) { + throw new Error(`Missing key on line ${idx + 1}`); + } + + if (rest === "") { + const child: Record = {}; + current[key] = child; + stack.push({ indent, obj: child }); + } else { + current[key] = parseScalar(rest); + } + } + + return root; +} + +function asRecord(val: unknown): Record { + return val && typeof val === "object" && !Array.isArray(val) + ? (val as Record) + : {}; +} + +function asBool(val: unknown, fallback: boolean): boolean { + return typeof val === "boolean" ? val : fallback; +} + +function asString(val: unknown, fallback: string): string { + return typeof val === "string" && val.length > 0 ? val : fallback; +} + +function asNumber(val: unknown, fallback: number): number { + return typeof val === "number" && Number.isFinite(val) ? val : fallback; +} + +export function parseRitualPolicyYaml(source: string): PolicyValidationResult { + const raw = parseSimpleYaml(source); + const errors: string[] = []; + const warnings: string[] = []; + + const version = + raw.version !== undefined && raw.version !== null ? String(raw.version) : ""; + if (!version) { + errors.push("Missing required top-level field: 'version' (expected '1' or '1.0')."); + } else if (version !== "1" && version !== "1.0") { + errors.push(`Unsupported policy schema version '${version}'. Supported: '1', '1.0'.`); + } + + const name = asString(raw.name, "ritual-defense-stack"); + const airGapped = asBool(raw.airGapped ?? raw.air_gapped, true); + + const asRaw = asRecord(raw.agentshield); + const dbRaw = asRecord(raw.dbshield); + const spRaw = asRecord(raw.skillprism); + + const modeRaw = asString(asRaw.mode, "strict").toLowerCase(); + const validModes: AgentShieldMode[] = ["strict", "balanced", "audit"]; + if (!validModes.includes(modeRaw as AgentShieldMode)) { + errors.push( + `Invalid agentshield.mode '${modeRaw}'. Expected one of: ${validModes.join(", ")}.`, + ); + } + + const profileRaw = asString( + asRaw.sandboxProfile ?? asRaw.sandbox_profile, + "strict", + ).toLowerCase(); + const validProfiles: SandboxProfile[] = ["strict", "standard", "permissive"]; + if (!validProfiles.includes(profileRaw as SandboxProfile)) { + errors.push( + `Invalid agentshield.sandboxProfile '${profileRaw}'. Expected one of: ${validProfiles.join(", ")}.`, + ); + } + + const tierRaw = asString(dbRaw.safetyTier ?? dbRaw.safety_tier, "STRICT").toUpperCase(); + const validTiers: DbShieldTier[] = ["STRICT", "BALANCED", "PERMISSIVE"]; + if (!validTiers.includes(tierRaw as DbShieldTier)) { + errors.push( + `Invalid dbshield.safetyTier '${tierRaw}'. Expected one of: ${validTiers.join(", ")}.`, + ); + } + + const dbPort = asNumber(dbRaw.listenPort ?? dbRaw.listen_port, 5433); + const spPort = asNumber(spRaw.listenPort ?? spRaw.listen_port, 4310); + + if (dbPort < 1 || dbPort > 65535) { + errors.push(`Invalid dbshield.listenPort '${dbPort}'. Must be between 1 and 65535.`); + } + if (spPort < 1 || spPort > 65535) { + errors.push(`Invalid skillprism.listenPort '${spPort}'. Must be between 1 and 65535.`); + } + + const manifest: RitualPolicyManifest = { + version: version || "1.0", + name, + airGapped, + agentshield: { + enabled: asBool(asRaw.enabled, true), + mode: (validModes.includes(modeRaw as AgentShieldMode) + ? modeRaw + : "strict") as AgentShieldMode, + sandboxProfile: (validProfiles.includes(profileRaw as SandboxProfile) + ? profileRaw + : "strict") as SandboxProfile, + redactPii: asBool(asRaw.redactPii ?? asRaw.redact_pii, true), + ledgerPath: asString( + asRaw.ledgerPath ?? asRaw.ledger_path, + ".agentshield/audit-ledger.jsonl", + ), + }, + dbshield: { + enabled: asBool(dbRaw.enabled, true), + listenPort: dbPort, + targetUrl: asString( + dbRaw.targetUrl ?? dbRaw.target_url, + "postgres://127.0.0.1:5432/postgres", + ), + safetyTier: (validTiers.includes(tierRaw as DbShieldTier) + ? tierRaw + : "STRICT") as DbShieldTier, + requireChatOpsApproval: asBool( + dbRaw.requireChatOpsApproval ?? dbRaw.require_chatops_approval, + true, + ), + maxEstimatedCost: asNumber( + dbRaw.maxEstimatedCost ?? dbRaw.max_estimated_cost, + 50000, + ), + }, + skillprism: { + enabled: asBool(spRaw.enabled, true), + listenPort: spPort, + maxActiveSkills: asNumber( + spRaw.maxActiveSkills ?? spRaw.max_active_skills, + 8, + ), + promptGuard: asBool(spRaw.promptGuard ?? spRaw.prompt_guard, true), + redisSentinelFallback: asBool( + spRaw.redisSentinelFallback ?? spRaw.redis_sentinel_fallback, + true, + ), + }, + }; + + if ( + manifest.dbshield.enabled && + manifest.skillprism.enabled && + manifest.dbshield.listenPort === manifest.skillprism.listenPort + ) { + errors.push( + `Port conflict: dbshield.listenPort and skillprism.listenPort are both set to ${manifest.dbshield.listenPort}.`, + ); + } + + if ( + !manifest.agentshield.enabled && + !manifest.dbshield.enabled && + !manifest.skillprism.enabled + ) { + warnings.push("All 3 defense layers are disabled in ritual.policy.yaml."); + } + + if (!manifest.airGapped) { + warnings.push( + "airGapped is false; outbound telemetry or cloud integrations may be permitted.", + ); + } + + return { + valid: errors.length === 0, + errors, + warnings, + manifest, + }; +} + +export function loadRitualPolicyFile(configPath = "ritual.policy.yaml"): { + resolvedPath: string; + validation: PolicyValidationResult; +} { + const resolvedPath = resolve(configPath); + if (!existsSync(resolvedPath)) { + throw new Error( + `Unified policy manifest not found at '${resolvedPath}'. Run 'agentshield up --init' to generate a default ritual.policy.yaml.`, + ); + } + const source = readFileSync(resolvedPath, "utf8"); + return { + resolvedPath, + validation: parseRitualPolicyYaml(source), + }; +} + +export function resolveOrchestrationPlan( + manifest: RitualPolicyManifest, + configPath: string, +): OrchestrationPlan { + const sharedEnv: Record = { + RITUAL_POLICY_NAME: manifest.name, + RITUAL_POLICY_VERSION: manifest.version, + RITUAL_AIR_GAPPED: manifest.airGapped ? "1" : "0", + AGENTSHIELD_AIR_GAPPED: manifest.airGapped ? "1" : "0", + }; + + const steps: OrchestrationStep[] = []; + const layersEnabled: string[] = []; + + if (manifest.agentshield.enabled) { + layersEnabled.push("agentshield"); + steps.push({ + layer: "agentshield", + packageName: "@ritualdev-lab/agentshield", + command: "agentshield", + args: [ + "doctor", + "--json", + ], + env: { + ...sharedEnv, + AGENTSHIELD_MODE: manifest.agentshield.mode, + AGENTSHIELD_SANDBOX_PROFILE: manifest.agentshield.sandboxProfile, + AGENTSHIELD_REDACT_PII: manifest.agentshield.redactPii ? "1" : "0", + AGENTSHIELD_LEDGER_PATH: manifest.agentshield.ledgerPath, + }, + summary: `AgentShield sandbox (${manifest.agentshield.sandboxProfile}/${manifest.agentshield.mode}) + Ed25519 ledger (${manifest.agentshield.ledgerPath})`, + }); + } + + if (manifest.dbshield.enabled) { + layersEnabled.push("dbshield"); + steps.push({ + layer: "dbshield", + packageName: "@ritualdev-lab/dbshield", + command: "npx", + args: [ + "-y", + "@ritualdev-lab/dbshield", + "proxy", + "--port", + String(manifest.dbshield.listenPort), + "--tier", + manifest.dbshield.safetyTier, + ], + env: { + ...sharedEnv, + DBSHIELD_TARGET_URL: manifest.dbshield.targetUrl, + DBSHIELD_SAFETY_TIER: manifest.dbshield.safetyTier, + DBSHIELD_CHATOPS_APPROVAL: manifest.dbshield.requireChatOpsApproval ? "1" : "0", + DBSHIELD_MAX_ESTIMATED_COST: String(manifest.dbshield.maxEstimatedCost), + }, + listenPort: manifest.dbshield.listenPort, + summary: `DBShield SQL firewall proxy on :${manifest.dbshield.listenPort} (tier=${manifest.dbshield.safetyTier}, ChatOps=${manifest.dbshield.requireChatOpsApproval})`, + }); + } + + if (manifest.skillprism.enabled) { + layersEnabled.push("skillprism"); + steps.push({ + layer: "skillprism", + packageName: "@ritualdev-lab/skillprism", + command: "npx", + args: [ + "-y", + "@ritualdev-lab/skillprism", + "proxy", + "--port", + String(manifest.skillprism.listenPort), + ], + env: { + ...sharedEnv, + SKILLPRISM_MAX_ACTIVE_SKILLS: String(manifest.skillprism.maxActiveSkills), + SKILLPRISM_PROMPT_GUARD: manifest.skillprism.promptGuard ? "1" : "0", + SKILLPRISM_REDIS_FALLBACK: manifest.skillprism.redisSentinelFallback ? "1" : "0", + }, + listenPort: manifest.skillprism.listenPort, + summary: `SkillPrism MCP context compactor on :${manifest.skillprism.listenPort} (promptGuard=${manifest.skillprism.promptGuard}, maxSkills=${manifest.skillprism.maxActiveSkills})`, + }); + } + + return { + configPath, + policyName: manifest.name, + version: manifest.version, + airGapped: manifest.airGapped, + layersEnabled, + steps, + }; +} + +export function generateDefaultRitualPolicyYaml(): string { + return `# RitualDev-Lab Unified 3-Layer AI Agent Defense Policy +# Boot with: npx @ritualdev-lab/agentshield up --config ritual.policy.yaml +version: "1.0" +name: "ritual-defense-stack" +airGapped: true + +agentshield: + enabled: true + mode: strict + sandboxProfile: strict + redactPii: true + ledgerPath: ".agentshield/audit-ledger.jsonl" + +dbshield: + enabled: true + listenPort: 5433 + targetUrl: "postgres://127.0.0.1:5432/postgres" + safetyTier: STRICT + requireChatOpsApproval: true + maxEstimatedCost: 50000 + +skillprism: + enabled: true + listenPort: 4310 + maxActiveSkills: 8 + promptGuard: true + redisSentinelFallback: true +`; +} diff --git a/tests/phase8-policy-up-and-examples.test.ts b/tests/phase8-policy-up-and-examples.test.ts new file mode 100644 index 0000000..23ae976 --- /dev/null +++ b/tests/phase8-policy-up-and-examples.test.ts @@ -0,0 +1,105 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import test from "node:test"; +import { AgentShieldEngine } from "../src/engine.js"; +import { + generateDefaultRitualPolicyYaml, + parseRitualPolicyYaml, + resolveOrchestrationPlan, +} from "../src/policy-manifest.js"; + +test("Phase 8: parseRitualPolicyYaml parses and validates unified 3-layer ritual.policy.yaml", () => { + const yaml = generateDefaultRitualPolicyYaml(); + const result = parseRitualPolicyYaml(yaml); + + assert.equal(result.valid, true, `Expected valid manifest, got: ${result.errors.join("; ")}`); + assert.equal(result.errors.length, 0); + assert.equal(result.manifest.version, "1.0"); + assert.equal(result.manifest.airGapped, true); + assert.equal(result.manifest.agentshield.enabled, true); + assert.equal(result.manifest.agentshield.sandboxProfile, "strict"); + assert.equal(result.manifest.dbshield.enabled, true); + assert.equal(result.manifest.dbshield.listenPort, 5433); + assert.equal(result.manifest.dbshield.safetyTier, "STRICT"); + assert.equal(result.manifest.skillprism.enabled, true); + assert.equal(result.manifest.skillprism.listenPort, 4310); + assert.equal(result.manifest.skillprism.promptGuard, true); + + const plan = resolveOrchestrationPlan(result.manifest, "ritual.policy.yaml"); + assert.deepEqual(plan.layersEnabled, ["agentshield", "dbshield", "skillprism"]); + assert.equal(plan.steps.length, 3); + assert.equal(plan.steps[1].env.RITUAL_AIR_GAPPED, "1"); + assert.equal(plan.steps[2].env.SKILLPRISM_PROMPT_GUARD, "1"); +}); + +test("Phase 8: parseRitualPolicyYaml rejects port conflicts and invalid tiers/versions", () => { + const badYaml = ` +version: "9.9" +dbshield: + enabled: true + listenPort: 5433 + safetyTier: INVALID_TIER +skillprism: + enabled: true + listenPort: 5433 +`; + const result = parseRitualPolicyYaml(badYaml); + assert.equal(result.valid, false); + assert.ok(result.errors.some((e) => e.includes("Unsupported policy schema version"))); + assert.ok(result.errors.some((e) => e.includes("Invalid dbshield.safetyTier"))); + assert.ok(result.errors.some((e) => e.includes("Port conflict"))); +}); + +test("Phase 8: CLI 'agentshield up --config examples/ritual.policy.yaml --dry-run --json' resolves all 3 layers", () => { + const repoRoot = resolve("."); + const builtCli = resolve(repoRoot, "dist/cli.js"); + const tsxCli = resolve(repoRoot, "node_modules/tsx/dist/cli.mjs"); + const srcCli = resolve(repoRoot, "src/cli.ts"); + const configPath = resolve(repoRoot, "examples/ritual.policy.yaml"); + assert.ok(existsSync(configPath), "examples/ritual.policy.yaml must exist"); + + const execArgs = existsSync(builtCli) + ? [builtCli, "up", "--config", configPath, "--dry-run", "--json"] + : [tsxCli, srcCli, "up", "--config", configPath, "--dry-run", "--json"]; + + const stdout = execFileSync(process.execPath, execArgs, { + encoding: "utf8", + cwd: repoRoot, + }); + + const parsed = JSON.parse(stdout); + assert.equal(parsed.valid, true); + assert.equal(parsed.dryRun, true); + assert.deepEqual(parsed.plan.layersEnabled, ["agentshield", "dbshield", "skillprism"]); + assert.equal(parsed.plan.steps.length, 3); + assert.equal(parsed.plan.airGapped, true); +}); + +test("Phase 8: consolidated examples (langgraph-starter & claude-code-starter) exist and pass smoke test", async () => { + const langgraphAgent = resolve("examples/langgraph-starter/agent.py"); + const langgraphReqs = resolve("examples/langgraph-starter/requirements.txt"); + const claudeHook = resolve("examples/claude-code-starter/.claude/config.json"); + const claudeDemo = resolve("examples/claude-code-starter/demo-tool.js"); + + assert.ok(existsSync(langgraphAgent)); + assert.ok(existsSync(langgraphReqs)); + assert.ok(existsSync(claudeHook)); + assert.ok(existsSync(claudeDemo)); + + assert.match(readFileSync(langgraphReqs, "utf8"), /agentshield-defense>=0\.2\.2/); + assert.match(readFileSync(claudeHook, "utf8"), /@ritualdev-lab\/agentshield@>=0\.2\.2/); + + // Smoke-test claude-code-starter demo-tool.js output through AgentShieldEngine + const mod = await import("../examples/claude-code-starter/demo-tool.js"); + const rawPayload = JSON.stringify(mod.executeQuery("SELECT id FROM users LIMIT 1")); + const engine = new AgentShieldEngine(); + const scan = engine.scanAndRedact(rawPayload); + assert.ok(scan.findings.length >= 1, "Expected AgentShieldEngine to intercept synthetic PAT"); + assert.equal( + scan.sanitizedText.includes("ghp_"), + false, + "Synthetic PAT must be fully redacted", + ); +});