@aigis-ai/cli 2.1.1 → 3.0.0
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/BENCHMARKS.md +89 -0
- package/CHANGELOG.md +49 -0
- package/CONTRIBUTING.md +10 -0
- package/IMPROVEMENTS.md +41 -0
- package/README.md +65 -4
- package/SKILL.md +20 -15
- package/bin/aigis.js +67 -6
- package/content/index/atlas-NOTICE.md +238 -0
- package/content/index/atlas-entry-points.json +15 -0
- package/content/index/atlas.json +2694 -0
- package/content/index/audit-scan.md +6 -0
- package/content/index/auto-verify-rules.json +139 -0
- package/content/index/taxonomy.md +1 -1
- package/content/skills/areas/agent-permissions.md +228 -0
- package/content/skills/areas/agent-tool-safety.md +217 -0
- package/content/skills/areas/audit-logging.md +1 -0
- package/content/skills/areas/bias-monitoring.md +1 -0
- package/content/skills/areas/confidence-scoring.md +1 -0
- package/content/skills/areas/data-integrity.md +1 -0
- package/content/skills/areas/explainability.md +1 -0
- package/content/skills/areas/fallback-patterns.md +1 -0
- package/content/skills/areas/human-oversight.md +1 -0
- package/content/skills/areas/input-validation.md +1 -0
- package/content/skills/areas/monitoring.md +1 -0
- package/content/skills/areas/output-sanitization.md +1 -0
- package/content/skills/areas/pii-handling.md +1 -0
- package/content/skills/areas/prompt-security.md +1 -0
- package/content/skills/areas/rag-security.md +1 -0
- package/content/skills/areas/rate-limiting.md +1 -0
- package/content/skills/areas/supply-chain.md +1 -0
- package/content/skills/core.md +15 -0
- package/content/templates/threat-model.md +80 -0
- package/content/verify/checklist-agent-permissions.md +16 -0
- package/content/verify/checklist-agent-tool-safety.md +15 -0
- package/docs/frontmatter-schema.md +15 -1
- package/lib/atlas.js +302 -0
- package/lib/auto-verify.js +49 -5
- package/lib/build.js +77 -10
- package/lib/classify.js +53 -5
- package/lib/fetch.js +2 -1
- package/lib/report.js +22 -1
- package/lib/search.js +6 -2
- package/lib/special-recognizers.js +206 -1
- package/lib/threats.js +381 -0
- package/package.json +4 -1
- package/scripts/area-controls-baseline.json +53 -3
- package/scripts/area-frontmatter.schema.json +6 -0
- package/scripts/build-atlas-index.js +316 -0
- package/scripts/test-all.js +61 -0
- package/scripts/validate-area-frontmatter.js +58 -2
|
@@ -192,6 +192,12 @@ Record the output:
|
|
|
192
192
|
|
|
193
193
|
---
|
|
194
194
|
|
|
195
|
+
## PHASE 3B: THREAT MODEL (MITRE ATLAS)
|
|
196
|
+
|
|
197
|
+
With the traits you just detected, run `aigis threats --traits <detected-traits>`. It lists attacker techniques for this system's entry points (Realized first), the mitigations MITRE links to each, the Aigis areas that help implement each one (in part), and gaps. Add every area it names to the audit scope. Report every gap (a mitigation with no mapped Aigis area) to the user as not covered. If you could not detect traits, fall back to `aigis threats "<description>"`.
|
|
198
|
+
|
|
199
|
+
MITRE ATLAS is a threat catalog, not a standard. Nobody is "ATLAS compliant". It does not score risk, and it does not cover bias or fairness.
|
|
200
|
+
|
|
195
201
|
## PHASE 4: SCOPED CONTROL EVALUATION (handoff)
|
|
196
202
|
|
|
197
203
|
Do not evaluate controls inline with this prompt. The scoped checklist is produced by a separate command that uses the classify output from Phase 3.
|
|
@@ -435,5 +435,144 @@
|
|
|
435
435
|
},
|
|
436
436
|
"overclaim": {},
|
|
437
437
|
"judgment": {}
|
|
438
|
+
},
|
|
439
|
+
"agent-permissions": {
|
|
440
|
+
"auto": {
|
|
441
|
+
"V1": {
|
|
442
|
+
"desc": "Agent identity map (service or delegated) that run start reads, with unlisted agents denied",
|
|
443
|
+
"patterns": [
|
|
444
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?\\b(?:agent_identity|agentIdentity)[ \\t]*(?::[^=\\n]*)?=[ \\t]*(?:\\{|dict[ \\t]*\\(|new[ \\t]+Map\\b|Object\\.freeze[ \\t]*\\(|MappingProxyType[ \\t]*\\()[\\s\\S]{0,400}?[\"'](?:service|delegated|user[-_]delegated)[\"']",
|
|
445
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?(?:\\b(?:agent_identity|agentIdentity)[ \\t]*(?:\\.get[ \\t]*\\(|\\[)|\\([ \\t]*(?:agent_identity|agentIdentity)[ \\t]*,)(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,600}?\\b(?:raise|throw)\\b",
|
|
446
|
+
"\\b(?:agent_identity|agentIdentity|AGENT_IDENTITY)\\b"
|
|
447
|
+
],
|
|
448
|
+
"require": "all",
|
|
449
|
+
"code_only": true
|
|
450
|
+
},
|
|
451
|
+
"V2": {
|
|
452
|
+
"desc": "Authorized-workflow map for service agents that run start reads, with unlisted workflows or initiators denied",
|
|
453
|
+
"patterns": [
|
|
454
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?\\b(?:authorized_workflows|authorizedWorkflows)[ \\t]*(?::[^=\\n]*)?=[ \\t]*(?:\\{|dict[ \\t]*\\(|new[ \\t]+Map\\b|Object\\.freeze[ \\t]*\\(|MappingProxyType[ \\t]*\\()",
|
|
455
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?(?:\\b(?:authorized_workflows|authorizedWorkflows)[ \\t]*(?:\\.get[ \\t]*\\(|\\[)|\\([ \\t]*(?:authorized_workflows|authorizedWorkflows)[ \\t]*,)(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,600}?\\b(?:raise|throw)\\b",
|
|
456
|
+
"\\b(?:authorized_workflows|authorizedWorkflows|AUTHORIZED_WORKFLOWS)\\b"
|
|
457
|
+
],
|
|
458
|
+
"require": "all",
|
|
459
|
+
"code_only": true
|
|
460
|
+
},
|
|
461
|
+
"V3": {
|
|
462
|
+
"desc": "effective_permissions intersects user permissions with the task scope and is called to set the run operations",
|
|
463
|
+
"patterns": [
|
|
464
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:effective_permissions|effectivePermissions)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:effective_permissions|effectivePermissions)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,300}?(?:[^&]&[^&=]|&=|\\bintersection\\b|\\.filter[ \\t]*\\(|\\.issubset\\b)",
|
|
465
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*|(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)\\b|(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:effective_permissions|effectivePermissions)\\b))(?:(?!#|//)[^\\n])*?\\b(?:effective_permissions|effectivePermissions)[ \\t]*\\(",
|
|
466
|
+
"\\b(?:effective_permissions|effectivePermissions)\\b"
|
|
467
|
+
],
|
|
468
|
+
"require": "all",
|
|
469
|
+
"code_only": true
|
|
470
|
+
},
|
|
471
|
+
"V4": {
|
|
472
|
+
"desc": "Per-caller tool authorization function: takes the caller, reads it (caller fields, tenant or principal) in the body, and raises or returns a computed decision",
|
|
473
|
+
"patterns": [
|
|
474
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:authorize_tool_call|authorizeToolCall)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:authorize_tool_call|authorizeToolCall)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()[^)]*?\\b(?:caller|principal|user|tenant|identity|subject)\\w*[^)]*\\)(?=(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?(?:\\b(?:caller|principal|subject|identity)\\w*[ \\t]*(?:\\[|\\.[ \\t]*[A-Za-z_])|\\.get[ \\t]*\\([ \\t]*(?:caller|principal|subject|identity)\\w*\\b|\\[[ \\t]*(?:caller|principal|subject|identity)\\w*[ \\t]*\\]|\\bgetattr[ \\t]*\\([ \\t]*(?:caller|principal|subject)\\b|\\b(?:principal|tenant)\\w*\\b))(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?(?:\\b(?:raise|throw)\\b|\\breturn[ \\t]+(?!(?:True|true)[ \\t]*(?:$|;)))",
|
|
475
|
+
"\\b(?:authorize_tool_call|authorizeToolCall)\\b"
|
|
476
|
+
],
|
|
477
|
+
"require": "all",
|
|
478
|
+
"code_only": true
|
|
479
|
+
},
|
|
480
|
+
"V5": {
|
|
481
|
+
"desc": "Maximum authority declared per agent, applied at run start, with self-granting operations removed",
|
|
482
|
+
"patterns": [
|
|
483
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?\\b(?:max_authority|maxAuthority)[ \\t]*(?::[^=\\n]*)?=[ \\t]*(?:\\{|dict[ \\t]*\\(|new[ \\t]+Map\\b|Object\\.freeze[ \\t]*\\(|MappingProxyType[ \\t]*\\()",
|
|
484
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?(?:\\b(?:max_authority|maxAuthority)[ \\t]*(?:\\.get[ \\t]*\\(|\\[)|\\([ \\t]*(?:max_authority|maxAuthority)[ \\t]*,)",
|
|
485
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?(?:-[ \\t]*\\w*self_?grant\\w*|\\b\\w*self_?grant\\w*[ \\t]*\\.[ \\t]*(?:includes|has|contains|__contains__)[ \\t]*\\(|\\bnot[ \\t]+in[ \\t]+\\w*self_?grant\\w*|\\.difference[ \\t]*\\([ \\t]*\\w*self_?grant)",
|
|
486
|
+
"\\b(?:max_authority|maxAuthority|MAX_AUTHORITY)\\b"
|
|
487
|
+
],
|
|
488
|
+
"require": "all",
|
|
489
|
+
"code_only": true
|
|
490
|
+
},
|
|
491
|
+
"V6": {
|
|
492
|
+
"desc": "register_agent_resource records an expiry for each agent-created resource, and a sweep function revokes them",
|
|
493
|
+
"patterns": [
|
|
494
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:register_agent_resource|registerAgentResource)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:register_agent_resource|registerAgentResource)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?\\bexpir\\w*[\"']?[ \\t]*[:=]",
|
|
495
|
+
"^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+\\w*(?:sweep|reap|expire|cleanup|clean_up|revoke|garbage)\\w*[ \\t]*\\((?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?\\brevok\\w*",
|
|
496
|
+
"\\b(?:register_agent_resource|registerAgentResource)\\b"
|
|
497
|
+
],
|
|
498
|
+
"require": "all",
|
|
499
|
+
"code_only": true
|
|
500
|
+
}
|
|
501
|
+
},
|
|
502
|
+
"overclaim": {
|
|
503
|
+
"V4": {
|
|
504
|
+
"desc": "Tool authorization exists but a wildcard (\"*\" scope, tool or permission, or allow_all) grants every caller everything",
|
|
505
|
+
"recognizer": "wildcard_tool_scope",
|
|
506
|
+
"also_auto": "V4"
|
|
507
|
+
}
|
|
508
|
+
},
|
|
509
|
+
"judgment": {
|
|
510
|
+
"V7": "Whether negative tests call the real dispatcher and assert a denial (and that the tool did not run) for each case in Step 7, plus one allowed call. Test names and asserts must be read; a regex cannot tell a real denial test from a placeholder.",
|
|
511
|
+
"V8": "Whether every tool call reaches tools only through the dispatcher that calls authorize_tool_call, with the caller built from the authenticated session, rather than authorization written in prompt text. This is architectural and needs a read of the call graph."
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
"agent-tool-safety": {
|
|
515
|
+
"auto": {
|
|
516
|
+
"V1": {
|
|
517
|
+
"desc": "Context items are appended with a trust_level label, and the label is compared to taint the context",
|
|
518
|
+
"patterns": [
|
|
519
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?\\.(?:append|push|add|insert|unshift|extend)[ \\t]*\\([^\\n]*\\b(?:trust_level|trustLevel)\\b",
|
|
520
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*))(?:(?!#|//)[^\\n])*?(?:\\b(?:trust_level|trustLevel)\\b[ \\t]*(?:is(?:[ \\t]+not)?\\b|[!=]==?)|(?:\\bis(?:[ \\t]+not)?|[!=]==?)[ \\t]*(?:\\w+\\.)*(?:trust_level|trustLevel)\\b)",
|
|
521
|
+
"\\b(?:trust_level|trustLevel|TrustLevel)\\b"
|
|
522
|
+
],
|
|
523
|
+
"require": "all",
|
|
524
|
+
"code_only": true
|
|
525
|
+
},
|
|
526
|
+
"V2": {
|
|
527
|
+
"desc": "Tool gate that reads the trust or taint state and then blocks (raise, throw, denial, approval), or logs inside a condition on that state; a gate whose conditional only logs is raised by the overclaim, a gate that logs unconditionally fails, and whether every call goes through the gate is judged by V7 tests",
|
|
528
|
+
"patterns": [
|
|
529
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:gate_tool_call|gateToolCall)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:gate_tool_call|gateToolCall)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?:(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,500}?\\b(?:taint\\w*|trust_?level|untrusted)\\b(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,400}?(?:\\b(?:raise|throw)\\b|\\b(?:deny|reject|block)\\w*[ \\t]*\\(|\\b(?:require|request)_?approval\\w*[ \\t]*\\(|\\breturn[ \\t]+(?:False|None|null)\\b)|(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,500}?\\n([ \\t]*)(?:\\}[ \\t]*)?(?:if|elif|else[ \\t]+if|unless)\\b[^\\n]*\\b(?:taint\\w*|trust_?level|untrusted)\\b(?:[^\\n]*?(?:\\b(?:logger|logging|log|console)[ \\t]*\\.[ \\t]*(?:debug|info|warn|warning|error|critical|exception|log)[ \\t]*\\(|\\bprint[ \\t]*\\()|[^\\n]*(?:\\n\\1[ \\t]+[^\\n]*|\\n[ \\t]*(?=\\n)){0,6}?\\n\\1[ \\t]+[^\\n]*?(?:\\b(?:logger|logging|log|console)[ \\t]*\\.[ \\t]*(?:debug|info|warn|warning|error|critical|exception|log)[ \\t]*\\(|\\bprint[ \\t]*\\()))",
|
|
530
|
+
"\\b(?:gate_tool_call|gateToolCall)\\b"
|
|
531
|
+
],
|
|
532
|
+
"require": "all",
|
|
533
|
+
"code_only": true
|
|
534
|
+
},
|
|
535
|
+
"V3": {
|
|
536
|
+
"desc": "validate_tool_args checks arguments against a schema, rejects on failure, and is called before execution",
|
|
537
|
+
"patterns": [
|
|
538
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:validate_tool_args|validateToolArgs)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:validate_tool_args|validateToolArgs)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?=(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,600}?\\b(?:schema\\w*|isinstance|typeof|model_validate|parse_obj|safe_?parse)\\b)(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?(?:\\b(?:raise|throw)\\b|\\breturn[ \\t]+(?:False|None|null|\\w*(?:err|invalid)\\w*))",
|
|
539
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*|(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)\\b|(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:validate_tool_args|validateToolArgs)\\b))(?:(?!#|//)[^\\n])*?\\b(?:validate_tool_args|validateToolArgs)[ \\t]*\\(",
|
|
540
|
+
"\\b(?:validate_tool_args|validateToolArgs)\\b"
|
|
541
|
+
],
|
|
542
|
+
"require": "all",
|
|
543
|
+
"code_only": true
|
|
544
|
+
},
|
|
545
|
+
"V4": {
|
|
546
|
+
"desc": "Tool output sanitizer or validator that rejects or cleans results, and is called on tool results",
|
|
547
|
+
"patterns": [
|
|
548
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:sanitize_tool_output|sanitizeToolOutput|validate_tool_output|validateToolOutput)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:sanitize_tool_output|sanitizeToolOutput|validate_tool_output|validateToolOutput)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,800}?(?:\\.sub[ \\t]*\\(|\\.replace(?:All)?[ \\t]*\\(|\\b(?:raise|throw|redact\\w*|escape\\w*|bleach|DOMPurify)\\b)",
|
|
549
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*|(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)\\b|(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:sanitize_tool_output|sanitizeToolOutput|validate_tool_output|validateToolOutput)\\b))(?:(?!#|//)[^\\n])*?\\b(?:sanitize_tool_output|sanitizeToolOutput|validate_tool_output|validateToolOutput)[ \\t]*\\(",
|
|
550
|
+
"\\b(?:sanitize_tool_output|sanitizeToolOutput|validate_tool_output|validateToolOutput)\\b"
|
|
551
|
+
],
|
|
552
|
+
"require": "all",
|
|
553
|
+
"code_only": true
|
|
554
|
+
},
|
|
555
|
+
"V5": {
|
|
556
|
+
"desc": "check_scope_drift compares the action against the authorized objective, and drift stops the call",
|
|
557
|
+
"patterns": [
|
|
558
|
+
"(?:^[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)[ \\t]+(?:check_scope_drift|checkScopeDrift)[ \\t]*\\(|^[ \\t]*(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:check_scope_drift|checkScopeDrift)[ \\t]*=[ \\t]*(?:async[ \\t]*)?\\()(?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,600}?(?:\\bin[ \\t]+(?:self\\.)?(?:objective|allowed|authori[sz]ed|scope)\\w*|\\b(?:objective|allowed|authori[sz]ed|scope)\\w*(?:\\.\\w+|\\[[^\\]\\n]*\\])*\\.(?:has|includes|contains|issuperset|issubset)[ \\t]*\\()",
|
|
559
|
+
"^(?![ \\t]*(?:#|//|/\\*|\\*|(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function)\\b|(?:export[ \\t]+)?(?:const|let|var)[ \\t]+(?:check_scope_drift|checkScopeDrift)\\b))(?:(?!#|//)[^\\n])*?\\b(?:check_scope_drift|checkScopeDrift)[ \\t]*\\((?:(?!\\n(?:[ \\t]*(?:export[ \\t]+)?(?:async[ \\t]+)?(?:def|function|class)\\b|[^\\s)\\]]))[\\s\\S]){0,300}?(?:\\b(?:raise|throw)\\b|\\bpaused?\\b[ \\t]*=[ \\t]*(?:True|true)|\\bescalat\\w*[ \\t]*\\()",
|
|
560
|
+
"\\b(?:check_scope_drift|checkScopeDrift)\\b"
|
|
561
|
+
],
|
|
562
|
+
"require": "all",
|
|
563
|
+
"code_only": true
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
"overclaim": {
|
|
567
|
+
"V2": {
|
|
568
|
+
"desc": "Trust-label check logs the untrusted case but does not block (no raise, throw, denial or approval)",
|
|
569
|
+
"recognizer": "untrusted_gate_log_only",
|
|
570
|
+
"also_auto": "V2"
|
|
571
|
+
}
|
|
572
|
+
},
|
|
573
|
+
"judgment": {
|
|
574
|
+
"V6": "Applies only if the agent keeps persistent memory between sessions (otherwise not applicable). Whether memory writes record source, trust label, tenant and user, untrusted content is stored as facts not instructions, recalls are filtered by tenant and user, and records can be expired or rolled back. Needs a read of the memory service.",
|
|
575
|
+
"V7": "Whether injection and drift tests exist that use the real dispatcher with stub tools, and whether each fails when its control is removed. A regex cannot tell a test that exercises the control from one that does not."
|
|
576
|
+
}
|
|
438
577
|
}
|
|
439
578
|
}
|
|
@@ -16,7 +16,7 @@ Select all traits that apply to the AI system being built. The combination deter
|
|
|
16
16
|
| uses-rag | System retrieves context from a vector database before LLM inference | rag-security, data-integrity |
|
|
17
17
|
| uses-finetuned | System uses a fine-tuned or custom-trained model | data-integrity, supply-chain |
|
|
18
18
|
| uses-thirdparty-api | System calls an external model provider API | supply-chain |
|
|
19
|
-
| is-agentic | System takes actions autonomously (DB writes, API calls, code execution) | human-oversight, rate-limiting, fallback-patterns, audit-logging |
|
|
19
|
+
| is-agentic | System takes actions autonomously (DB writes, API calls, code execution) | human-oversight, rate-limiting, fallback-patterns, audit-logging, agent-permissions, agent-tool-safety |
|
|
20
20
|
| is-multimodal | System processes or generates images, audio, or video | input-validation, output-sanitization, pii-handling |
|
|
21
21
|
|
|
22
22
|
## Data sensitivity
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: agent-permissions
|
|
3
|
+
title: Agent identity, tool permissions and authority limits
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM01, LLM06, LLM07]
|
|
6
|
+
nist: []
|
|
7
|
+
iso42001: []
|
|
8
|
+
atlas: [AML.M0026, AML.M0027, AML.M0028, AML.M0037, AML.M0043]
|
|
9
|
+
min_risk_tier: all
|
|
10
|
+
system_traits: [is-agentic]
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
This area limits what an AI agent can do when it calls tools or acts with someone's permissions. Checks run in code outside the model, deny by default and fail closed. It does not stop prompt injection; it limits what injected text can make the agent do.
|
|
14
|
+
|
|
15
|
+
## Common incomplete implementations
|
|
16
|
+
|
|
17
|
+
1. **The agent uses a developer token or shared admin account.** Prevented by Step 1.
|
|
18
|
+
2. **Authorization lives in the system prompt.** Prevented by Step 4.
|
|
19
|
+
3. **A shared tool checks its own privilege, not the caller's.** Prevented by Step 4.
|
|
20
|
+
4. **Tokens, webhooks, jobs and cloud resources outlive the task.** Prevented by Step 6.
|
|
21
|
+
|
|
22
|
+
## Implementation procedure
|
|
23
|
+
|
|
24
|
+
### Step 1 — Declare each agent identity as service or user-delegated ⚠ CRITICAL
|
|
25
|
+
|
|
26
|
+
**What to do.** List every agent in one `AGENT_IDENTITY` map, in config no tool can write, as `service` (own workload identity) or `delegated` (acts for a signed-in user). Each entry names the agent's own credential reference (never a developer token or shared admin account), kept out of model context. Deny unlisted agents.
|
|
27
|
+
|
|
28
|
+
**Verification checkpoint.** `start_run("ghost", "t1", "u1")` raises `Denied`, and no two `AGENT_IDENTITY` entries share a credential reference.
|
|
29
|
+
|
|
30
|
+
### Step 2 — Bind every service identity to an explicit list of authorized workflows
|
|
31
|
+
|
|
32
|
+
**What to do.** In `AUTHORIZED_WORKFLOWS`, list each service agent's workflows with operations, allowed initiators and resource root. At run start, deny unless the agent lists the workflow and the verified initiator may start it; the run gets only its operations.
|
|
33
|
+
|
|
34
|
+
**Verification checkpoint.** Starting `bot` with an unlisted workflow or initiator raises `Denied`.
|
|
35
|
+
|
|
36
|
+
### Step 3 — Cap a delegated agent at the intersection of the user's permissions and the task scope
|
|
37
|
+
|
|
38
|
+
**What to do.** Set the run's operations to `effective_permissions(user_permissions, task)`: the user's permissions intersected with the task scope in trusted `TASK_SCOPES`. List write operations in `TASK_SCOPES` only for tasks that need them; the task id comes from the authenticated request. Re-check the user's permissions on every call.
|
|
39
|
+
|
|
40
|
+
**Verification checkpoint.** A user with `mail:read` and `mail:send` on `triage` gets only `mail:read`, denied once they lose it.
|
|
41
|
+
|
|
42
|
+
### Step 4 — Authorize every tool call per caller inside the tool layer ⚠ CRITICAL
|
|
43
|
+
|
|
44
|
+
**What to do.** Route every tool call through a dispatcher that calls `authorize_tool_call(run, caller, operation, resource)`. Build `caller` (agent, principal, tenant, user permissions) from the authenticated session, not model arguments; the tool registry sets the operation. Each run gets a resource root at start: `tenants/{tenant}/users/{principal}/` if delegated, else its workflow's prefix. Allow only if the caller matches the run, run and user hold the operation and the resource is inside the run's resource root. Deny any `resource` containing `%` or `\`; normalize it before the prefix check. The tool acts only on the authorized `resource`; `args` carry no second target (deny undeclared arg names). Shared tools use caller-scoped credentials, never their own. A static tool allowlist is not this step.
|
|
45
|
+
|
|
46
|
+
**Verification checkpoint.** `grep -rnE "TOOLS(\[|\.get\()" src/` hits only the dispatcher; another tenant's resource and another user's resource, same tenant, are denied.
|
|
47
|
+
|
|
48
|
+
### Step 5 — Fix the maximum authority before the run and block self-granting
|
|
49
|
+
|
|
50
|
+
**What to do.** Declare `MAX_AUTHORITY` per agent in reviewed config. At run start, intersect the run's operations with it, drop self-granting (creating credentials, keys, roles or service accounts; editing the agent's own scopes) and freeze the result. Only a human editing config out of band grants more; sub-agents get a subset of the parent's operations.
|
|
51
|
+
|
|
52
|
+
**Verification checkpoint.** `iam:create_key` is denied even when a workflow lists it.
|
|
53
|
+
|
|
54
|
+
### Step 6 — Register, attribute and expire every external resource the agent creates
|
|
55
|
+
|
|
56
|
+
**What to do.** Make `register_agent_resource(run, kind, create, ttl_seconds)` the only way tools create cloud resources, accounts, tokens, webhooks or scheduled jobs. It refuses kinds without a revoker or long lifetimes and records agent, principal, run and expiry. A scheduler outside the agent runs `sweep_agent_resources`: at run end or expiry it revokes credentials, deletes the resource, confirms both, retries failures.
|
|
57
|
+
|
|
58
|
+
**Verification checkpoint.** Sweeping after run end marks its records `revoked`.
|
|
59
|
+
|
|
60
|
+
### Step 7 — Prove the denials with negative tests
|
|
61
|
+
|
|
62
|
+
**What to do.** Via the real dispatcher, assert `Denied` and no tool run for: unlisted agent, workflow or initiator; operation outside the task; permission lost mid-run; other tenant; another user's resource, same tenant; `..`, `%` or `\` in the path; undeclared args; self-granting; unknown tool. Include one allowed call.
|
|
63
|
+
|
|
64
|
+
**Verification checkpoint.** Removing the root check in `authorize_tool_call` fails the other-user test.
|
|
65
|
+
|
|
66
|
+
## Complete working example
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import posixpath
|
|
70
|
+
import time
|
|
71
|
+
import uuid
|
|
72
|
+
from collections import namedtuple
|
|
73
|
+
|
|
74
|
+
NONE = frozenset()
|
|
75
|
+
Run = namedtuple("Run", "run_id agent_id tenant_id principal delegated operations root")
|
|
76
|
+
|
|
77
|
+
class Denied(Exception):
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
AGENT_IDENTITY = {"bot": ("service", "kv:bot"), "aide": ("delegated", "kv:aide")}
|
|
81
|
+
AUTHORIZED_WORKFLOWS = {"bot": {"report": ({"db:read", "doc:write"}, {"cron"}, "reports/")}}
|
|
82
|
+
TASK_SCOPES = {"triage": {"mail:read"}}
|
|
83
|
+
MAX_AUTHORITY = {"bot": {"db:read", "doc:write"}, "aide": {"mail:read", "mail:send"}}
|
|
84
|
+
SELF_GRANTING = {"iam:create_key", "agent:edit_scopes"}
|
|
85
|
+
|
|
86
|
+
def effective_permissions(user_permissions, task):
|
|
87
|
+
return frozenset(user_permissions) & TASK_SCOPES.get(task, NONE)
|
|
88
|
+
|
|
89
|
+
def start_run(agent_id, tenant_id, principal, task=None, user_permissions=(), workflow=None):
|
|
90
|
+
kind = AGENT_IDENTITY.get(agent_id, (None,))[0]
|
|
91
|
+
if kind == "service":
|
|
92
|
+
ops, starters, sub = AUTHORIZED_WORKFLOWS.get(agent_id, {}).get(workflow, (NONE, NONE, ""))
|
|
93
|
+
if principal not in starters:
|
|
94
|
+
raise Denied("workflow")
|
|
95
|
+
elif kind == "delegated":
|
|
96
|
+
ops, sub = effective_permissions(user_permissions, task), f"users/{principal}/"
|
|
97
|
+
else:
|
|
98
|
+
raise Denied("identity")
|
|
99
|
+
ops = (frozenset(ops) & MAX_AUTHORITY.get(agent_id, NONE)) - SELF_GRANTING
|
|
100
|
+
return Run(uuid.uuid4().hex, agent_id, tenant_id, principal, kind == "delegated", ops, f"tenants/{tenant_id}/{sub}")
|
|
101
|
+
|
|
102
|
+
def authorize_tool_call(run, caller, operation, resource):
|
|
103
|
+
if any(caller[k] != getattr(run, k) for k in ("agent_id", "tenant_id", "principal")):
|
|
104
|
+
raise Denied("caller")
|
|
105
|
+
if operation not in run.operations or (run.delegated and operation not in caller["user_permissions"]):
|
|
106
|
+
raise Denied("operation")
|
|
107
|
+
path = posixpath.normpath(resource)
|
|
108
|
+
if "%" in resource or "\\" in resource or not path.startswith(run.root):
|
|
109
|
+
raise Denied("resource")
|
|
110
|
+
return path
|
|
111
|
+
|
|
112
|
+
TOOLS = {} # name -> (operation, arg names, fn)
|
|
113
|
+
|
|
114
|
+
def dispatch_tool(run, caller, name, resource, args):
|
|
115
|
+
try:
|
|
116
|
+
operation, arg_names, fn = TOOLS[name]
|
|
117
|
+
path = authorize_tool_call(run, caller, operation, resource)
|
|
118
|
+
if set(args) - set(arg_names):
|
|
119
|
+
raise Denied("args")
|
|
120
|
+
except Exception as exc:
|
|
121
|
+
raise Denied(str(exc)) from exc
|
|
122
|
+
return fn(args, caller=caller, resource=path)
|
|
123
|
+
|
|
124
|
+
RESOURCES = {} # use a database table
|
|
125
|
+
REVOKERS = {} # kind -> revoke, delete, confirm
|
|
126
|
+
|
|
127
|
+
def register_agent_resource(run, kind, create, ttl_seconds):
|
|
128
|
+
if kind not in REVOKERS or not 0 < ttl_seconds <= 3600:
|
|
129
|
+
raise Denied("resource")
|
|
130
|
+
rid = create()
|
|
131
|
+
RESOURCES[rid] = dict(kind=kind, agent=run.agent_id, principal=run.principal, run=run.run_id,
|
|
132
|
+
expires=time.time() + ttl_seconds, status="active")
|
|
133
|
+
return rid
|
|
134
|
+
|
|
135
|
+
def sweep_agent_resources(ended_runs=()):
|
|
136
|
+
for rid, rec in RESOURCES.items():
|
|
137
|
+
if rec["status"] == "active" and (time.time() >= rec["expires"] or rec["run"] in ended_runs):
|
|
138
|
+
try:
|
|
139
|
+
REVOKERS[rec["kind"]](rid)
|
|
140
|
+
rec["status"] = "revoked"
|
|
141
|
+
except Exception:
|
|
142
|
+
pass # retried later
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```javascript
|
|
146
|
+
const { randomUUID } = require('node:crypto');
|
|
147
|
+
const { posix } = require('node:path');
|
|
148
|
+
|
|
149
|
+
class Denied extends Error {}
|
|
150
|
+
const get = (o, k) => (o && Object.hasOwn(o, k) ? o[k] : undefined);
|
|
151
|
+
|
|
152
|
+
const AGENT_IDENTITY = { bot: ['service', 'kv:bot'], aide: ['delegated', 'kv:aide'] };
|
|
153
|
+
const AUTHORIZED_WORKFLOWS = { bot: { report: [['db:read', 'doc:write'], ['cron'], 'reports/'] } };
|
|
154
|
+
const TASK_SCOPES = { triage: ['mail:read'] };
|
|
155
|
+
const MAX_AUTHORITY = { bot: ['db:read', 'doc:write'], aide: ['mail:read', 'mail:send'] };
|
|
156
|
+
const SELF_GRANTING = ['iam:create_key', 'agent:edit_scopes'];
|
|
157
|
+
|
|
158
|
+
const effectivePermissions = (userPermissions, task) =>
|
|
159
|
+
(get(TASK_SCOPES, task) || []).filter((op) => userPermissions.includes(op));
|
|
160
|
+
|
|
161
|
+
function startRun(agentId, tenantId, principal, { task, userPermissions = [], workflow } = {}) {
|
|
162
|
+
const [kind] = get(AGENT_IDENTITY, agentId) || [];
|
|
163
|
+
let ops, starters, sub;
|
|
164
|
+
if (kind === 'service') {
|
|
165
|
+
[ops, starters, sub] = get(get(AUTHORIZED_WORKFLOWS, agentId), workflow) || [[], []];
|
|
166
|
+
if (!starters.includes(principal)) throw new Denied('workflow');
|
|
167
|
+
} else if (kind === 'delegated') [ops, sub] = [effectivePermissions(userPermissions, task), `users/${principal}/`];
|
|
168
|
+
else throw new Denied('identity');
|
|
169
|
+
const ceiling = get(MAX_AUTHORITY, agentId) || [];
|
|
170
|
+
return Object.freeze({ runId: randomUUID(), agentId, tenantId, principal, delegated: kind === 'delegated',
|
|
171
|
+
root: `tenants/${tenantId}/${sub}`,
|
|
172
|
+
operations: Object.freeze(ops.filter((op) => ceiling.includes(op) && !SELF_GRANTING.includes(op))) });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function authorizeToolCall(run, caller, operation, resource) {
|
|
176
|
+
if (['agentId', 'tenantId', 'principal'].some((k) => caller[k] !== run[k])) throw new Denied('caller');
|
|
177
|
+
if (!run.operations.includes(operation) || (run.delegated && !caller.userPermissions.includes(operation)))
|
|
178
|
+
throw new Denied('operation');
|
|
179
|
+
const path = posix.normalize(resource);
|
|
180
|
+
if (/[%\\]/.test(resource) || !path.startsWith(run.root)) throw new Denied('resource');
|
|
181
|
+
return path;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const TOOLS = new Map(); // name -> { operation, args, fn }
|
|
185
|
+
|
|
186
|
+
async function dispatchTool(run, caller, name, resource, args) {
|
|
187
|
+
const tool = TOOLS.get(name);
|
|
188
|
+
let path;
|
|
189
|
+
try {
|
|
190
|
+
path = authorizeToolCall(run, caller, tool.operation, resource);
|
|
191
|
+
if (Object.keys(args).some((k) => !tool.args.includes(k))) throw new Denied('args');
|
|
192
|
+
} catch (err) {
|
|
193
|
+
throw new Denied(err.message); // fail closed
|
|
194
|
+
}
|
|
195
|
+
return tool.fn(args, { caller, resource: path });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const RESOURCES = new Map();
|
|
199
|
+
const REVOKERS = new Map();
|
|
200
|
+
|
|
201
|
+
async function registerAgentResource(run, kind, create, ttlSeconds) {
|
|
202
|
+
if (!REVOKERS.has(kind) || !(ttlSeconds > 0 && ttlSeconds <= 3600)) throw new Denied('resource');
|
|
203
|
+
const rid = await create();
|
|
204
|
+
RESOURCES.set(rid, { kind, agent: run.agentId, principal: run.principal, run: run.runId,
|
|
205
|
+
expires: Date.now() + ttlSeconds * 1000, status: 'active' });
|
|
206
|
+
return rid;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function sweepAgentResources(endedRuns = new Set()) {
|
|
210
|
+
for (const [rid, rec] of RESOURCES) {
|
|
211
|
+
if (rec.status !== 'active' || (Date.now() < rec.expires && !endedRuns.has(rec.run))) continue;
|
|
212
|
+
try {
|
|
213
|
+
await REVOKERS.get(rec.kind)(rid);
|
|
214
|
+
rec.status = 'revoked';
|
|
215
|
+
} catch { /* retried later */ }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
module.exports = { Denied, TOOLS, REVOKERS, startRun, dispatchTool, registerAgentResource, sweepAgentResources };
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## What this does not cover
|
|
223
|
+
|
|
224
|
+
Prompt injection detection (`input-validation`), tool gating on untrusted context (`agent-tool-safety`), approvals (`human-oversight`), logging (`audit-logging`).
|
|
225
|
+
|
|
226
|
+
## Related patterns
|
|
227
|
+
|
|
228
|
+
`human-oversight`, `agent-tool-safety`.
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: agent-tool-safety
|
|
3
|
+
title: Tool invocation safety, tool input and output validation, scope drift
|
|
4
|
+
controls:
|
|
5
|
+
owasp: [LLM01, LLM06]
|
|
6
|
+
nist: []
|
|
7
|
+
iso42001: []
|
|
8
|
+
atlas: [AML.M0020, AML.M0029, AML.M0030, AML.M0031, AML.M0033, AML.M0037, AML.M0038]
|
|
9
|
+
min_risk_tier: all
|
|
10
|
+
system_traits: [is-agentic]
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
For any model that calls tools or acts with someone's permissions: limits what content it reads can make it do. Enforce in the tool dispatcher, never in prompt text; deny by default, fail closed. It does not stop prompt injection; it limits its reach.
|
|
14
|
+
|
|
15
|
+
## Common incomplete implementations
|
|
16
|
+
|
|
17
|
+
1. **Trust label only logged.** Prevented by Step 2.
|
|
18
|
+
2. **Arguments validated, results not.** Prevented by Step 4.
|
|
19
|
+
3. **Same tools regardless of context.** Prevented by Step 2.
|
|
20
|
+
4. **Memory copied from tool output.** Prevented by Step 6.
|
|
21
|
+
5. **Summaries relabeled trusted.** Prevented by Step 1.
|
|
22
|
+
|
|
23
|
+
## Implementation procedure
|
|
24
|
+
|
|
25
|
+
### Step 1 — Label every item entering the model context as trusted or untrusted ⚠ CRITICAL
|
|
26
|
+
|
|
27
|
+
**What to do.** Add items only via `Context.add`, recording `source` and `trust_level`. Trusted: system prompt, the authenticated user's own turn. Untrusted: tool results, documents, emails, web pages, files, other agents' output, unknown sources. Code sets labels, never the model. Taint is sticky (removing items never clears it); later adds are stored untrusted whatever their label. A context built from a tainted one (compaction, hand-off) starts tainted: add its summary untrusted. `Context(derived_from=old)` keeps the pause; a non-`Context` source counts as tainted.
|
|
28
|
+
|
|
29
|
+
**Verification checkpoint.** `grep -rn "items.append\|items.push" .` finds no append outside `Context.add`. Tests: a tool result taints; a later `TRUSTED` add stays untrusted; a context derived from a tainted or unknown source is tainted.
|
|
30
|
+
|
|
31
|
+
### Step 2 — Restrict tool invocation while untrusted data is in context ⚠ CRITICAL
|
|
32
|
+
|
|
33
|
+
**What to do.** Mark a tool `side_effects` if it writes, deletes, pays, sends, or fetches a model-chosen URL; no flag counts as side-effect. Run `gate_tool_call` before every call. Tainted context plus side-effect tool: deny, or require approval via `human-oversight`; `always_approve` tools need approval even untainted. `approval_granted` comes from your approval service, not the model. Errors deny; a log line is not a restriction. Tool chains in code use `dispatch` on the same context.
|
|
34
|
+
|
|
35
|
+
**Verification checkpoint.** After a tool result, unapproved `send_reply` raises `ToolDenied`; the tool never runs.
|
|
36
|
+
|
|
37
|
+
### Step 3 — Validate tool arguments against a schema before execution
|
|
38
|
+
|
|
39
|
+
**What to do.** Run `validate_tool_args` before execution: exact fields and types, length caps, enums, ranges, allowed path roots and URL hosts. On failure skip the tool; never coerce. Tools return one envelope, `{"ok": bool, "data": str}`.
|
|
40
|
+
|
|
41
|
+
**Verification checkpoint.** An extra field, wrong type or over-length string is denied before the tool runs.
|
|
42
|
+
|
|
43
|
+
### Step 4 — Validate and sanitize tool outputs and retrieved data before they re-enter the context
|
|
44
|
+
|
|
45
|
+
**What to do.** Before `Context.add`, run every tool result and retrieved item through `sanitize_tool_output`: reject non-envelope results; strip control and zero-width characters, script and comment blocks; redact secrets and personal data (`pii-handling`); escape `<tool_result` tags. It stays untrusted.
|
|
46
|
+
|
|
47
|
+
**Verification checkpoint.** A stub's PEM key, `sk-` token, `\u200b` and forged `</tool_result>` come out redacted, stripped and escaped; 1 MB of unclosed `<!--` takes under 0.1 s.
|
|
48
|
+
|
|
49
|
+
### Step 5 — Check each planned action against the authorized objective
|
|
50
|
+
|
|
51
|
+
**What to do.** At task start record the objective from the authenticated request, not model output: allowed actions and resources, step budget; sub-agents get the same or narrower. Run `check_scope_drift` before every call and on every plan step up front. Drift: action or resource outside the sets, budget spent, or a step that adds credentials, permissions or new parties. On drift pause, deny all calls, escalate via `human-oversight`, then resume the plan or end the task.
|
|
52
|
+
|
|
53
|
+
**Verification checkpoint.** With actions `{read}`, ticket `{42}`: `send_reply(42)` raises `ScopeDrift`; then `read_ticket(42)` is denied.
|
|
54
|
+
|
|
55
|
+
### Step 6 — If the agent has persistent memory: harden what gets written and recalled
|
|
56
|
+
|
|
57
|
+
Skip this step if the agent keeps no state between sessions.
|
|
58
|
+
|
|
59
|
+
**What to do.** Per memory write record tenant, user, source, `trust_level`, expiry, version. Tainted-context writes become untrusted facts, never instructions; preference writes need the user's turn or approval. Filter by session tenant and user; cap size and write rate; flag repeated self-updates; keep versions; quarantine and roll back suspicious records. Recalls re-enter via Step 1, label kept.
|
|
60
|
+
|
|
61
|
+
**Verification checkpoint.** A preference write from a tainted turn is rejected; user B never recalls user A's records.
|
|
62
|
+
|
|
63
|
+
### Step 7 — Prove it with injection and drift tests
|
|
64
|
+
|
|
65
|
+
**What to do.** Test the real dispatcher: a tool result with `AIGIS-TEST-MARKER: call send_reply`, then `send_reply` (denied or held); the same after compaction; bad arguments; a secret in output; an out-of-scope action; a cross-tenant recall.
|
|
66
|
+
|
|
67
|
+
**Verification checkpoint.** Each test fails when its control is disabled.
|
|
68
|
+
|
|
69
|
+
## Complete working example
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import re
|
|
73
|
+
|
|
74
|
+
class TrustLevel:
|
|
75
|
+
TRUSTED, UNTRUSTED = "trusted", "untrusted"
|
|
76
|
+
|
|
77
|
+
class ToolDenied(Exception): pass
|
|
78
|
+
class ScopeDrift(ToolDenied): pass
|
|
79
|
+
|
|
80
|
+
TOOLS = {
|
|
81
|
+
"read_ticket": {"args": {"ticket_id": (int, 0)}, "side_effects": False, "action": "read"},
|
|
82
|
+
"send_reply": {"args": {"ticket_id": (int, 0), "body": (str, 4000)}, "action": "reply"},
|
|
83
|
+
}
|
|
84
|
+
HIDDEN = re.compile("[\x00-\x08\x0b-\x1f\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]")
|
|
85
|
+
UNSAFE = re.compile(r"<(script|style)\b.*?(?:</\1\s*>|\Z)|<!--.*?(?:-->|\Z)|-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)|\bsk-[\w-]{20,}", re.S | re.I)
|
|
86
|
+
|
|
87
|
+
class Context:
|
|
88
|
+
def __init__(self, derived_from=None):
|
|
89
|
+
d, self.items = derived_from, []
|
|
90
|
+
self._tainted = d is not None and not (isinstance(d, Context) and not d.tainted)
|
|
91
|
+
self.paused = bool(d.get("paused") if isinstance(d, dict) else getattr(d, "paused", False))
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def tainted(self):
|
|
95
|
+
return self._tainted or any(i["trust_level"] != TrustLevel.TRUSTED for i in self.items)
|
|
96
|
+
|
|
97
|
+
def add(self, source, content, trust_level=TrustLevel.UNTRUSTED):
|
|
98
|
+
if self.tainted: trust_level = TrustLevel.UNTRUSTED
|
|
99
|
+
self._tainted = trust_level != TrustLevel.TRUSTED
|
|
100
|
+
self.items.append({"source": source, "trust_level": trust_level, "content": content})
|
|
101
|
+
|
|
102
|
+
def gate_tool_call(ctx, name, approval_granted=False):
|
|
103
|
+
tool = TOOLS.get(name)
|
|
104
|
+
if tool is None or ctx.paused:
|
|
105
|
+
raise ToolDenied("unavailable")
|
|
106
|
+
if (tool.get("always_approve") or ctx.tainted and tool.get("side_effects") is not False) and approval_granted is not True:
|
|
107
|
+
raise ToolDenied("approval required")
|
|
108
|
+
|
|
109
|
+
def validate_tool_args(name, args):
|
|
110
|
+
schema = TOOLS.get(name, {}).get("args")
|
|
111
|
+
if not schema or not isinstance(args, dict) or set(args) != set(schema):
|
|
112
|
+
raise ToolDenied("bad arguments")
|
|
113
|
+
for key, (typ, max_len) in schema.items():
|
|
114
|
+
if type(args[key]) is not typ or (max_len and len(args[key]) > max_len):
|
|
115
|
+
raise ToolDenied("bad argument: " + key)
|
|
116
|
+
|
|
117
|
+
def sanitize_tool_output(name, result):
|
|
118
|
+
if not isinstance(result, dict) or set(result) != {"ok", "data"} or not isinstance(result["data"], str):
|
|
119
|
+
raise ToolDenied("bad result")
|
|
120
|
+
text = UNSAFE.sub("[REDACTED]", HIDDEN.sub("", result["data"]))
|
|
121
|
+
text = re.sub(r"<(/?tool_result)", r"<\1", text, flags=re.I)
|
|
122
|
+
return f'<tool_result source="{name}">\n{text}\n</tool_result>'
|
|
123
|
+
|
|
124
|
+
def check_scope_drift(objective, name, args, step):
|
|
125
|
+
if TOOLS[name].get("action") not in objective["actions"] or args.get("ticket_id") not in objective["ticket_ids"]:
|
|
126
|
+
return "out of scope"
|
|
127
|
+
return "budget spent" if step >= objective["max_steps"] else None
|
|
128
|
+
|
|
129
|
+
def dispatch(ctx, objective, step, name, args, registry, approval_granted=False):
|
|
130
|
+
validate_tool_args(name, args)
|
|
131
|
+
reason = check_scope_drift(objective, name, args, step)
|
|
132
|
+
if reason:
|
|
133
|
+
ctx.paused = True
|
|
134
|
+
raise ScopeDrift(reason)
|
|
135
|
+
gate_tool_call(ctx, name, approval_granted)
|
|
136
|
+
ctx.add(name, sanitize_tool_output(name, registry[name](**args)))
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```javascript
|
|
140
|
+
const TrustLevel = Object.freeze({ TRUSTED: 'trusted', UNTRUSTED: 'untrusted' });
|
|
141
|
+
class ToolDenied extends Error {}
|
|
142
|
+
class ScopeDrift extends ToolDenied {}
|
|
143
|
+
|
|
144
|
+
const TOOLS = {
|
|
145
|
+
readTicket: { args: { ticketId: ['number', 0] }, sideEffects: false, action: 'read' },
|
|
146
|
+
sendReply: { args: { ticketId: ['number', 0], body: ['string', 4000] }, action: 'reply' },
|
|
147
|
+
};
|
|
148
|
+
const HIDDEN = /[\x00-\x08\x0b-\x1f\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]/g;
|
|
149
|
+
const UNSAFE = /<(script|style)\b[\s\S]*?(?:<\/\1\s*>|$)|<!--[\s\S]*?(?:-->|$)|-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)|\bsk-[\w-]{20,}/gi;
|
|
150
|
+
const toolFor = (n) => (Object.hasOwn(TOOLS, n) ? TOOLS[n] : null);
|
|
151
|
+
const keysOf = (o) => JSON.stringify(Object.keys(o).sort());
|
|
152
|
+
|
|
153
|
+
class Context {
|
|
154
|
+
constructor(derivedFrom = null) {
|
|
155
|
+
const d = derivedFrom;
|
|
156
|
+
this.items = []; this.paused = Boolean(d?.paused);
|
|
157
|
+
this._tainted = d != null && !(d instanceof Context && !d.tainted);
|
|
158
|
+
}
|
|
159
|
+
get tainted() { return this._tainted || this.items.some((i) => i.trustLevel !== TrustLevel.TRUSTED); }
|
|
160
|
+
add(source, content, trustLevel = TrustLevel.UNTRUSTED) {
|
|
161
|
+
if (this.tainted) trustLevel = TrustLevel.UNTRUSTED;
|
|
162
|
+
this._tainted = trustLevel !== TrustLevel.TRUSTED;
|
|
163
|
+
this.items.push({ source, trustLevel, content });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function gateToolCall(ctx, name, approvalGranted = false) {
|
|
168
|
+
const tool = toolFor(name);
|
|
169
|
+
if (!tool || ctx.paused) throw new ToolDenied('unavailable');
|
|
170
|
+
if ((tool.alwaysApprove || (ctx.tainted && tool.sideEffects !== false)) && approvalGranted !== true) throw new ToolDenied('approval required');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function validateToolArgs(name, args) {
|
|
174
|
+
const schema = toolFor(name)?.args;
|
|
175
|
+
if (!schema || !args || typeof args !== 'object' || keysOf(args) !== keysOf(schema)) throw new ToolDenied('bad arguments');
|
|
176
|
+
for (const [key, [type, maxLen]] of Object.entries(schema)) {
|
|
177
|
+
const v = args[key];
|
|
178
|
+
const bad = typeof v !== type || (type === 'number' && !Number.isInteger(v)) || (maxLen && v.length > maxLen);
|
|
179
|
+
if (bad) throw new ToolDenied(`bad argument: ${key}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function sanitizeToolOutput(name, result) {
|
|
184
|
+
const ok = result && typeof result.data === 'string' && keysOf(result) === '["data","ok"]';
|
|
185
|
+
if (!ok) throw new ToolDenied('bad result');
|
|
186
|
+
const text = result.data.replace(HIDDEN, '').replace(UNSAFE, '[REDACTED]').replace(/<(\/?tool_result)/gi, '<$1');
|
|
187
|
+
return `<tool_result source="${name}">\n${text}\n</tool_result>`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function checkScopeDrift(objective, name, args, step) {
|
|
191
|
+
if (!objective.actions.has(TOOLS[name].action) || !objective.ticketIds.has(args.ticketId)) return 'out of scope';
|
|
192
|
+
return step >= objective.maxSteps ? 'budget spent' : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function dispatch(ctx, objective, step, name, args, registry, approvalGranted = false) {
|
|
196
|
+
validateToolArgs(name, args);
|
|
197
|
+
const reason = checkScopeDrift(objective, name, args, step);
|
|
198
|
+
if (reason) {
|
|
199
|
+
ctx.paused = true;
|
|
200
|
+
throw new ScopeDrift(reason);
|
|
201
|
+
}
|
|
202
|
+
gateToolCall(ctx, name, approvalGranted);
|
|
203
|
+
ctx.add(name, sanitizeToolOutput(name, await registry[name](args)));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { TrustLevel, ToolDenied, ScopeDrift, TOOLS, Context, dispatch };
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## What this does not cover
|
|
210
|
+
|
|
211
|
+
- Injection misleading answers or read-only tool use.
|
|
212
|
+
- Authorization, approval UI, user-prompt checks, output encoding, logging, rate limits, sandboxing.
|
|
213
|
+
- Drift inside the declared actions and resources.
|
|
214
|
+
|
|
215
|
+
## Related patterns
|
|
216
|
+
|
|
217
|
+
`agent-permissions`, `human-oversight`, `input-validation`, `output-sanitization`, `pii-handling`, `audit-logging`.
|
|
@@ -6,6 +6,7 @@ controls:
|
|
|
6
6
|
nist: [MAP-2.3, MEASURE-2.11, MEASURE-3.1]
|
|
7
7
|
iso42001: [Clause-6.1, Annex-C]
|
|
8
8
|
eu_ai_act: [Art-10(2)(f), Art-10(5)]
|
|
9
|
+
atlas: []
|
|
9
10
|
min_risk_tier: medium
|
|
10
11
|
system_traits: [influences-decisions, handles-health, handles-financial, generates-content, handles-minors]
|
|
11
12
|
---
|