| type | Decision | ||||
|---|---|---|---|---|---|
| title | Bundle Isolation and Mutation Security Boundaries | ||||
| description | Defensive security architecture enforcing canonical bundle boundaries, symlink containment, path traversal prevention for local mutations and for untrusted remote hub, sync and registry input, and frontmatter injection defense. | ||||
| generated |
|
OKF Agent Memory is designed to be written, updated, and queried by autonomous AI agents operating across IDEs and CI/CD pipelines. Because AI agent tool calls may execute untrusted or adversarial prompts, the deterministic tooling layer must treat all mutation arguments and bundle directories as untrusted inputs.
The tooling layer enforces defensive confinement across nine critical choke-points:
All file reads in LoadBundle and writes in SaveConcept, UpdateParentIndex, and AppendLogEntry resolve symlinks and compare canonical paths against the bundle root via filepath.Rel.
- Traversal via relative parent references (
..) or absolute paths escaping the bundle directory is strictly denied. - Unified path resolution (
(*Bundle).ResolvePath, OKF v0.3) enforces CWE-22 read confinement across both Markdown body/index links and frontmatter path fields (resource,superseded_by,sources[].resource,computation,executor.resource,attester.resource), rejecting%2e%2e, backslashes, Windows drives, and UNC paths asPathKindEscapesso no target outside the bundle root is ever read locally. Per OKF v0.3 §6 (#70),okf validatetreats escaping concept body links as external outbound references (preservingis_conformant: true) and reports escapingindex.mdlinks and frontmatter path fields as non-blockingWarningswhileResolvePathand all mutation APIs keep strict CWE-22 confinement intact. - The bundle root is absolutised before its symlinks are resolved. A relative root under a symlinked working directory (macOS
/tmp→/private/tmp) otherwise stayed unresolved while the target resolved to the real path, and every legitimate write was refused as an escape. - Root-reserved files (
index.md,log.md,AGENTS.md) cannot be overwritten as arbitrary concept documents regardless of letter case (strings.EqualFold). Subdirectory concepts (e.g.architecture/agents.md) remain permissible.
To defend against Local File Inclusion (LFI) and Arbitrary File Overwrite:
LoadBundleinspects symlinks withensureWithinRoot. Any symlink whose resolved target escapes the canonical bundle root triggers an immediate traversal error.- Symlinks must point strictly to markdown (
.md) files within the bundle; symlinks to directories or non-markdown assets are rejected. - Writing through symlinks pointing outside the bundle is blocked.
The bundle root itself may be a symlink, because users legitimately link a bundle into place. The target is confined by scope:
- Project and vendor bundles (
LoadBundle): the root symlink must resolve inside the directory that contains the link. A repository that shipsknowledge -> /elsewhereis therefore rejected, with or without a trailing slash. - User and system scope roots (
~/.okf,/etc/okf,OKF_USER_DIR,OKF_SYSTEM_DIR; internalloadTrustedBundle): the root is configured by the user, not by the repository, so it may be a symlink to any location. Symlinks inside these bundles stay confined by rule 2. - A
knowledge/subdirectory symlink is always confined to its parent root, including in trusted scopes. - The walk always runs over the resolved root. Walking the unresolved path loaded an empty bundle silently, because
filepath.WalkDirdoes not follow a symlink at its root.
Metadata fields (type, title, description, stale_after, superseded_by, actor) are strictly validated prior to serialization:
- Newline characters (
\r,\n) are rejected in scalar metadata fields, preventing YAML attribute smuggling or forged verification states (verified.by: human). - The YAML document delimiter (
---) is forbidden within metadata values. - Body smuggling checks (
frontmatterSmuggleRegex) block nested---blocks containing reserved or protected keys (verified,governance,generated,type,status,superseded_by,code_refs,stale_after,x-okf-memory-protected). - Special scalar characters (
:,&,", etc.) are quoted safely in YAML serialization without escaping HTML entities.
The stdio Model Context Protocol (MCP) server confines dynamic bundle switching:
- The server initializes with a canonical
rootDir(governed by project workspace orOKF_MCP_ROOT). - When
OKF_MCP_ROOTis unset, the root is derived from the bundle's parent. If a multi-segment relative path is given (e.g.docs/knowledge), the bundle path is normalized to absolute first to prevent double-joining while maintaining strict boundary confinement. - Multi-bundle projects can dynamically select sub-bundles (e.g.
bundle="examples/software"), but any request escaping the server root is denied before loading. - Required MCP mutation arguments (
concept_id,type,title,description) are strictly non-empty.
OKF bundles are designed for shared Git repository version control:
- Files are created with
0o644(rw-r--r--) and directories with0o755(rwxr-xr-x). - Static analysis rules intended for secret credential files (such as
gosec G301/G306requiring0600/0750) are deliberately excluded, ensuring bundle readability across multi-user environments, CI/CD runners, and Git sub-processes.
SaveConcept refuses to let a non-human actor add a human verification:
- A human identity is
human,human:*, orhuman/*, compared case-insensitively (IsHumanIdentity).team:actors are valid but never qualify as human. - An agent may preserve
verifiedentries already recorded in the concept file. Adding one, or altering the timestamp of an existing one, is rejected. A new concept inherits nothing from an existing file at its path. - Scope of the guarantee: the actor is self-declared. The MCP server fixes it to
agent/mcp, so the guard is effective there. A CLI user can still pass--actor human/..., so for the CLI it guards against accidental or injected forgery, not against a deliberate caller.
Hub tree manifests, registry manifests, registry archives, and okf.lock entries are untrusted input: any holder of the vault key, a compromised registry, or a cloned repository controls them. Every path built from them must land inside the target bundle or workspace before anything is written or deleted.
- Hub tree paths (
pkg/sync,validateTreePath): a path that is empty, absolute or volume-qualified, contains.,..or empty segments, contains a hidden segment, a NUL byte, or a backslash separator is refused before any blob is fetched. Every write and delete target is then resolved through symlinks and must lie strictly inside the resolved bundle root (filepath.Rel, not a string prefix). One bad entry refuses the wholeokf hub pullorokf hub sync, and a stored sync state that holds such a path is ignored. - Sync state:
.okf/sync-state.jsonis read and written only when it resolves inside the bundle. - Registry bundle ids (
pkg/registry,ValidateBundleID): an id must be a canonical relative slash path. Registry manifests andokf.lockentries with an absolute,..,., empty, backslash, or NUL id are refused with an error naming the manifest or entry. Scoped and nested ids (@peter/django-5-rules,acme/tools/linter) remain valid..okf/vendormust resolve inside the workspace, and each bundle directory strictly inside.okf/vendor(ResolveVendorDir). - Archive extraction: every entry is checked lexically and through symlinks before anything is extracted, so an archive is applied in full or not at all.
- Staged installs and rollback:
okf pullandokf restoreextract and validate in a fresh staging directory under.okf, then move it into place. A failed install discards only that staging directory. Rollback never removes a directory this invocation did not create, and never follows a symlink.okf vendor removere-resolves its target and unlinks a symlink instead of following it.
To prevent silent Read-Modify-Write (RMW) lost updates when parallel subagents, multiple IDE MCP servers, or concurrent CLI invocations mutate the same local bundle (knowledge/ or ~/.okf/):
- Stage 1 (Cross-Process Bundle Write Lock):
InitBundle,SaveConcept,UpdateConcept,RelateConcepts,UpdateParentIndex, andAppendLogEntryacquire an exclusive lockfile (.okf-write.lock, confined viaensureWithinRootand created atomically withos.O_CREATE|os.O_EXCL) across the entire mutation transaction (concept write + parentindex.mdupdate +log.mdbookkeeping), with bounded backoff and automatic stale-lock eviction (acquired_atage check). - Stage 2a (Transactional RMW Scope):
UpdateConcept(used byokf updateand MCPokf_update) andRelateConcepts(okf relateand MCPokf_relate) acquire the bundle lock before callingLoadBundle, ensuring concurrent updates or link insertions on the same concept execute strictly in sequence against the latest committed disk state. - Stage 2b (Optimistic Concurrency Check / CAS):
LoadBundlerecords the SHA-256 digest (sourceHash) of each loaded concept file. WhenSaveConceptwrites an existing concept (IsNew: false) that was loaded viaLoadBundleoutsideUpdateConcept, it verifies inside the bundle lock that the on-disk file still matchessourceHash, returningErrConcurrentModificationif another writer modified the file in the interim.
To prevent autonomous agents from mutating or degrading critical human-authored policies, ADRs, or active code freezes:
- Protected Extension Lock (
x-okf-memory-protected: true): Orthogonal togovernance, any concept declaringx-okf-memory-protected: trueon disk rejects edits from non-human actors (!IsHumanIdentity(actor)), including attempts to strip or unset the flag (ErrProtectedConcept). governance: holdDowngrade Guard: Non-human actors cannot downgrade or clear an existinggovernance: holdon disk, even ifx-okf-memory-protected: trueis omitted.- CLI-Only Override: Human operators may override via CLI
okf update --allow-protected(SaveOptions.AllowProtected: true). No override parameter is ever exposed in MCP tools (pkg/okf/mcp.go,tools.json). - Provenance Validation:
okf validate --strictflags protected concepts lacking human provenance (generated.by: human:...or a current humanverifiedentry).
- Defined as part of Layer 4 in layers.
- Complements the deterministic single-binary tooling in tooling-decision.
- MCP Tool Security & Untrusted Agent Input: Behavioral MCP guidelines complement deterministic boundaries
- Automated Security Auditing & Defensive Verification Workflow: Proactive adversarial auditing and verification pipeline
- OKF v0.3 Conformance, Lifecycle Forwarding & Freshness Architecture: Unified path confinement and trust-tier rules