Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
a689feb
Add security levels, the policy they resolve to, and owner-only secre…
zfoong Nov 24, 2026
578a11a
Add a security gate that asks for approval of high-risk actions by th…
zfoong Nov 24, 2026
53fb4ae
Add the Security settings backend messages, approval answers, audit v…
zfoong Nov 24, 2026
e35ce3a
Add the shared security store slice and resources for the Security pa…
zfoong Nov 24, 2026
023a55e
Declare the effects and result source of every built-in action so the…
zfoong Nov 24, 2026
e0f8835
Give MCP tools security effects from their standard readOnly and open…
zfoong Nov 24, 2026
102dfd4
Keep secret files owner-only, stop bundles reusing keys for a differe…
zfoong Nov 24, 2026
cb7a7cc
Keep the agent's file tools away from CraftBot's secret stores and, a…
zfoong Nov 24, 2026
95b1639
Add a network guard that checks every redirect hop and every resolved…
zfoong Nov 24, 2026
7e2ca42
Give MCP servers only basic system variables plus their own env when …
zfoong Nov 24, 2026
48225fb
Let the security level keep prompt text out of logs and mask CraftBot…
zfoong Nov 24, 2026
674bac4
Wrap third-party messages as untrusted content and match Discord owne…
zfoong Nov 24, 2026
4ba88a3
Delete log files and recorded AI calls older than the retention perio…
zfoong Nov 24, 2026
7c01880
Add the Settings > Security page and the in-chat approval card to the…
zfoong Nov 24, 2026
3dd27f4
Add the Security settings tab and the chat approval prompt to the ter…
zfoong Nov 24, 2026
f734632
Test that the default Standard level changes nothing and that the gat…
zfoong Nov 24, 2026
6417279
Add a security policy, a guide to security levels and approvals, and …
zfoong Nov 24, 2026
d046e2a
Test the Security settings messages the browser and terminal send ove…
zfoong Nov 24, 2026
78c99cd
Make sub-agents share their parent run's security state so taint and …
zfoong Nov 24, 2026
5cf892c
Resolve approval answers thread-safely on the waiting action's event …
zfoong Nov 24, 2026
e1d7bad
Translate the Security page, approval card and terminal security scre…
zfoong Nov 24, 2026
ba7b3d1
Add a read_settings action that shows settings with every key hidden …
zfoong Nov 24, 2026
3043985
Stop printing local variables in error tracebacks when the security l…
zfoong Nov 24, 2026
cf02f20
Pin the agent's web requests to the address the network guard checked…
zfoong Nov 24, 2026
3b3f4d5
Add an optional list of email senders whose Gmail and Outlook message…
zfoong Nov 24, 2026
fe96ca8
Start MCP servers only as they were saved through CraftBot's settings…
zfoong Nov 24, 2026
3ee1fdc
Extend the security check to runtime file permissions, prompt logging…
zfoong Nov 24, 2026
eb08ec4
Run the security tests, including the default-level and performance c…
zfoong Nov 24, 2026
293800d
Draft the security section of the v1.4.6 release notes.
zfoong Nov 24, 2026
034ca7f
Declare read_settings' section parameter as optional.
zfoong Nov 24, 2026
96346ef
Block commands that do damage no approval can undo, judged on the par…
zfoong Nov 24, 2026
4201690
Keep CraftBot's own keys out of the environment of commands the agent…
zfoong Nov 24, 2026
2d790e9
Match Discord owners by user ID and pin the owner's ID on first match…
zfoong Nov 24, 2026
8e7878d
Warn in the security check about MCP servers that download an unpinne…
zfoong Nov 24, 2026
c800222
Mention the new protections in the v1.4.6 security release notes draft.
zfoong Nov 24, 2026
2b802ce
Make the Security settings page short and layout-led, with no help pa…
zfoong Nov 25, 2026
52cb0da
Make the destructive-command floor, outside-content marking, log reda…
zfoong Nov 25, 2026
c244b2f
Add opt-in limits for runs started by a third party or a schedule, sy…
zfoong Nov 25, 2026
9c66cfe
Add opt-in malware lookups for MCP server packages and checksum verif…
zfoong Nov 25, 2026
8c4cae6
Add opt-in masking of secret-shaped text in tool results and removal …
zfoong Nov 25, 2026
3a2694b
Add an opt-in memory guard that keeps memory and profile files writte…
zfoong Nov 25, 2026
2dce4bd
Add opt-in review of risky commands that asks the user with Auto mode…
zfoong Nov 25, 2026
ad55a8e
Add opt-in scanning of skills before they are installed or enabled, o…
zfoong Nov 25, 2026
268a4d5
Make Block requests to local networks also stop the built-in browser …
zfoong Nov 25, 2026
88fba09
Show the new protections in Settings > Security in both interfaces an…
zfoong Nov 25, 2026
668c4a6
Test that the prompt cache prefix survives every security protection …
zfoong Nov 25, 2026
729036e
Give the prompt cache test's stand-in action an icon so the action di…
zfoong Nov 25, 2026
39550a7
Fix the Windows CI: let the Windows shell tests load the real securit…
zfoong Nov 25, 2026
1023816
Import the security modules afresh in each Windows shell test so a pa…
zfoong Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
name: Security

# Settings > Security: the gate, guards and their tests, including the
# check that the default Standard level changes nothing and the gate's
# per-action time budget (tests/test_security_standard_unchanged.py).

on:
push:
paths:
- 'app/security/**'
- 'app/data/action/**'
- 'app/agent_base.py'
- 'agent_core/core/impl/action/manager.py'
- 'agent_core/core/action_framework/registry.py'
- 'agent_core/core/action/action.py'
- 'agent_core/core/impl/mcp/**'
- 'agent_core/utils/logger.py'
- 'app/ui_layer/settings/security_settings.py'
- 'app/ui_layer/settings/profile_bundle.py'
- 'app/ui_layer/adapters/ws_auth.py'
- 'craftos_integrations/providers/discord/client.py'
- 'craftos_integrations/providers/gmail/client.py'
- 'craftos_integrations/providers/outlook/client.py'
- 'tests/test_security_*.py'
- 'tests/test_ws_auth.py'
- '.github/workflows/security.yml'
pull_request:
paths:
- 'app/security/**'
- 'app/data/action/**'
- 'app/agent_base.py'
- 'agent_core/core/impl/action/manager.py'
- 'agent_core/core/action_framework/registry.py'
- 'agent_core/core/action/action.py'
- 'agent_core/core/impl/mcp/**'
- 'agent_core/utils/logger.py'
- 'app/ui_layer/settings/security_settings.py'
- 'app/ui_layer/settings/profile_bundle.py'
- 'app/ui_layer/adapters/ws_auth.py'
- 'craftos_integrations/providers/discord/client.py'
- 'craftos_integrations/providers/gmail/client.py'
- 'craftos_integrations/providers/outlook/client.py'
- 'tests/test_security_*.py'
- 'tests/test_ws_auth.py'
- '.github/workflows/security.yml'

permissions:
contents: read

jobs:
security-tests:
name: Security tests (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.10"

- name: Install dependencies from the lock
shell: bash
run: |
python -m venv .venv-sec
if [ -f .venv-sec/bin/python ]; then PY=.venv-sec/bin/python;
else PY=.venv-sec/Scripts/python.exe; fi
echo "PY=$PY" >> "$GITHUB_ENV"
"$PY" -m pip install --upgrade pip
LOCK=$("$PY" -c "from app.provision.deps import find_lock; print(find_lock('.') or '')")
if [ -z "$LOCK" ]; then
echo "::error::no lock for this platform — run scripts/generate_lock.py"
exit 1
fi
"$PY" -m pip install --require-hashes -r "$LOCK"
"$PY" -m pip install pytest==9.0.2

- name: Run security tests
shell: bash
run: '"$PY" -m pytest tests/test_security_*.py tests/test_ws_auth.py -q'
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ config.json
node_modules
.env
.credentials/
# Security state: audit log, MCP trust ledger, session token files
.security/
/run/
**/agent_logs.txt
**/memory.txt
**/gui/config
Expand Down Expand Up @@ -148,6 +151,7 @@ agent_file_system/*.local-backup
/app/config/mcp_config.json
/app/config/scheduler_config.json
/app/config/skills_config.json
/app/config/security.json
/agent_file_system/MEMORY.md
/agent_file_system/ENTITIES.md
/agent_file_system/PROACTIVE.md
Expand Down
42 changes: 42 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Security Policy

## Reporting a vulnerability

Please report vulnerabilities privately through GitHub: open the repository's **Security** tab and choose **Report a vulnerability**. Do not open a public issue, pull request or discussion for a vulnerability before it is fixed.

Include what you found, the affected version, and steps to reproduce. A harmless proof (for example, one that only creates a marker file) is the most useful.

We will acknowledge your report, keep you updated while we work on it, and publish a GitHub Security Advisory once it is fixed, crediting you unless you ask us not to.

## Supported versions

Security fixes go into the latest release. Please upgrade to it before reporting.

| Version | Supported |
| --- | --- |
| Latest release (1.4.x) | Yes |
| Older releases | No |

## Trust model

CraftBot is a personal agent that runs on your computer with your user account's permissions. It is built for one trusted owner per installation.

- **The agent can do what you can do.** It runs commands, reads and writes files, and uses the accounts you connect. The operating system user account is the boundary; CraftBot does not sandbox the commands the agent runs.
- **Outside content is untrusted.** Web pages, emails, chat messages from other people, files and MCP tool results can contain instructions aimed at the agent (prompt injection). Settings > Security lets you reduce what such instructions can achieve; see [the security levels guide](docs/security-levels.md).
- **The local interface is for this computer.** It listens on localhost and has no login of its own. Do not expose its ports to a network without putting an authenticating proxy in front of it.
- **Extensions run with full permissions.** MCP servers, skills, Agent Apps and profile bundles you install run code as you. Install only what you trust.

## In scope

- Ways for a website, an email, a third party's message, an MCP server, a skill or a profile bundle to run code, read secrets or act as the owner without the owner's approval when a security setting says it should not.
- Bypasses of a Settings > Security protection that its description says it provides.
- Exposure of credentials or of the local interface to other users or other machines.
- Vulnerabilities in the installer, updater or release artifacts.

## Out of scope

- Prompt injection that only makes the agent use permissions the owner gave it, at a security level that does not restrict them (for example Standard with Auto mode on).
- Anything that needs the attacker to already run code as the owner's user account.
- Commands the agent runs reaching files or the network: the file and network guards cover the agent's file and web tools, not the shell. Turn Auto mode off to approve commands before they run.
- Malicious MCP servers, skills or Agent Apps that the owner chose to install.
- Exposing the interface to the internet against the guidance above.
14 changes: 14 additions & 0 deletions agent_core/core/action/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ def __init__(
timeout: Optional[int] = None,
parallelizable: bool = True,
irreversible: bool = False,
integration: Optional[str] = None,
effects: Optional[List[str]] = None,
result_source: Optional[str] = None,
):
"""
Initialize a new Action definition.
Expand Down Expand Up @@ -125,6 +128,11 @@ def __init__(
self.timeout = timeout if timeout is not None else self.DEFAULT_TIMEOUT
self.parallelizable = parallelizable
self.irreversible = irreversible
# Security declarations (see ActionMetadata): the integration the
# action belongs to, what it can do, and where its result comes from.
self.integration = integration
self.effects = list(effects) if effects is not None else None
self.result_source = result_source

@property
def display_name(self) -> str:
Expand Down Expand Up @@ -168,6 +176,9 @@ def to_dict(self) -> Dict[str, Any]:
"timeout": self.timeout,
"parallelizable": self.parallelizable,
"irreversible": self.irreversible,
"integration": self.integration,
"effects": self.effects,
"result_source": self.result_source,
}

@classmethod
Expand Down Expand Up @@ -209,6 +220,9 @@ def from_dict(cls, data: Dict[str, Any]) -> "Action":
timeout=data.get("timeout"),
parallelizable=data.get("parallelizable", True),
irreversible=data.get("irreversible", False),
integration=data.get("integration"),
effects=data.get("effects"),
result_source=data.get("result_source"),
)

return data_to_return
20 changes: 20 additions & 0 deletions agent_core/core/action_framework/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ class ActionMetadata:
display_param: Optional[str] = None
icon: Optional[str] = None
integration: Optional[str] = None
# What the action can do to the world (app/security/policy.py Effect
# values: "execute", "write_files", "send_external", "change_agent",
# "use_credentials"). Security decisions read these declarations; an
# empty list declares a read-only action. None means undeclared.
effects: Optional[List[str]] = None
# Where the action's result comes from: "local" or "network". A network
# result is untrusted content for the rest of the turn.
result_source: Optional[str] = None

@property
def display_name(self) -> str:
Expand Down Expand Up @@ -332,6 +340,9 @@ def _get_action_as_json(self, platform_impls) -> Dict[str, Any]:
"platform_overrides": {},
"parallelizable": meta.parallelizable,
"irreversible": meta.irreversible,
"integration": meta.integration,
"effects": meta.effects,
"result_source": meta.result_source,
}

# 3. Handle Platform Overrides
Expand Down Expand Up @@ -492,6 +503,8 @@ def action(
display_param: Optional[str] = None,
icon: Optional[str] = None,
integration: Optional[str] = None,
effects: Optional[List[str]] = None,
result_source: Optional[str] = None,
):
"""
Decorator used by developers to register functions as actions.
Expand Down Expand Up @@ -525,6 +538,11 @@ def action(
of no integration.
integration: Integration id whose logo is shown before the action's
name, for an integration's action.
effects: What the action can do: any of "execute", "write_files",
"send_external", "change_agent", "use_credentials". [] for
a read-only action. Approvals and security checks use this.
result_source: "network" when the result is content from outside
(web pages, email, chat, APIs), else "local".
"""
# Normalize platforms input to a list of lowercase strings
if platforms is None:
Expand Down Expand Up @@ -553,6 +571,8 @@ def decorator_factory(func: Callable):
display_param=display_param,
icon=icon,
integration=integration,
effects=list(effects) if effects is not None else None,
result_source=result_source,
)

# 2. Create the full registration object
Expand Down
56 changes: 56 additions & 0 deletions agent_core/core/impl/action/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,20 @@ def __init__(
self._on_action_end = on_action_end
self._get_parent_id = get_parent_id
self._idempotency_guard = idempotency_guard
# Optional security gate (app/security/gate.py). It reviews every
# action before it runs and sees every result; None costs nothing.
self._action_gate = None

def set_action_gate(self, gate) -> None:
"""Install the gate every action passes through before it runs.

``gate.review(action, input_data, session_id=...)`` returns None to
let the action run, or the output to return instead of running it.
``gate.after(action, rendered_output, session_id=...)`` returns the
output text the agent reads. Both cover sub-agents, parallel batches
and sub-actions, since all of them run through execute_action.
"""
self._action_gate = gate

# ------------------------------------------------------------------
# Public helpers
Expand Down Expand Up @@ -279,6 +293,41 @@ async def execute_action(
# same wall-clock second.
run_id = run_id or str(uuid.uuid4())

# ── Security gate ──
# Before anything with a side effect, including the idempotency
# ledger's intent record. A gate that fails blocks the action.
if self._action_gate is not None:
try:
blocked = await self._action_gate.review(
action, input_data, session_id=session_id
)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.exception(f"Security gate failed for {action.name}")
blocked = {
"status": "error",
"error": f"Blocked: the security check failed ({type(exc).__name__}).",
"error_code": "security_gate_error",
}
if blocked is not None:
self._log_event_stream(
is_gui_task=is_gui_task,
event_kind="action_end",
event_type=EventType.ACTION_END,
event=(
f"Action {action.name} was not run: "
f"{_to_json(blocked, compact=True)}."
),
display_message=f"{action.display_name} → not allowed",
action_name=action.name,
action_display_name=action.display_name,
action_id=run_id,
action_output=blocked,
session_id=session_id,
)
return blocked

# ── Idempotency guard for irreversible actions ──
# BEFORE the side effect: record intent durably, and refuse to
# re-execute work the ledger shows as already completed (or as
Expand Down Expand Up @@ -487,6 +536,13 @@ async def execute_action(
"failed" if (status == "error" or output_has_error) else "completed"
)
rendered_output = _to_json(outputs, compact=True)
if self._action_gate is not None and not was_cancelled:
try:
rendered_output = self._action_gate.after(
action, rendered_output, session_id=session_id
)
except Exception as exc:
logger.warning(f"Security gate after() failed: {exc}")
self._log_event_stream(
is_gui_task=is_gui_task,
event_kind="action_end",
Expand Down
14 changes: 14 additions & 0 deletions agent_core/core/impl/context/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@
from agent_core.utils.logger import logger


def _memory_file_excluded(name: str) -> bool:
"""Whether the host's memory guard keeps this file out of the prompt
(app/security/memory_guard.py; off unless the user turned it on)."""
try:
from app.security.memory_guard import is_excluded
except ImportError:
return False
return is_excluded(name)


class EventStreamContext:
"""The event-stream half of a context engine: renders a session's stream
for a prompt and tracks how far its LLM session history has been sent.
Expand Down Expand Up @@ -442,6 +452,8 @@ def create_system_user_profile(self) -> str:

user_md_path = AGENT_FILE_SYSTEM_PATH / "USER.md"

if _memory_file_excluded("USER.md"):
return ""
if user_md_path.exists():
content = user_md_path.read_text(encoding="utf-8").strip()
if content:
Expand All @@ -458,6 +470,8 @@ def create_system_soul(self) -> str:

soul_md_path = AGENT_FILE_SYSTEM_PATH / "SOUL.md"

if _memory_file_excluded("SOUL.md"):
return ""
if soul_md_path.exists():
content = soul_md_path.read_text(encoding="utf-8").strip()
if content:
Expand Down
15 changes: 12 additions & 3 deletions agent_core/core/impl/llm/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ def _call_type_from_name(name: str):
return name


def _prompts_logged() -> bool:
"""Settings > Security > "Write full prompts to logs" (on at Standard)."""
try:
from app.security.policy import get_policy
except ImportError: # agent_core used without the app
return True
return get_policy().log_prompts


@dataclass(frozen=True)
class RequestUsage:
"""What the provider reported for a session's last request."""
Expand Down Expand Up @@ -1142,7 +1151,7 @@ def _generate_response_sync(
# Check if we've hit the consecutive failure threshold
self._check_failure_latch()

if log_response:
if log_response and _prompts_logged():
logger.info(f"[LLM SEND] system={system_prompt} | user={user_prompt}")

try:
Expand Down Expand Up @@ -1240,7 +1249,7 @@ def _generate_response_sync(
current_count = self._get_token_count()
self._set_token_count(current_count + billable_tokens(response))

if log_response:
if log_response and _prompts_logged():
logger.info(f"[LLM RECV] {cleaned}")
return LLMReply(cleaned, bool(response.get("cut_off")))

Expand Down Expand Up @@ -1789,7 +1798,7 @@ def _session_attempt(fb, _t=task_id, _c=call_type):
cleaned = re.sub(self._CODE_BLOCK_RE, "", content)
current_count = self._get_token_count()
self._set_token_count(current_count + billable_tokens(response))
if log_response:
if log_response and _prompts_logged():
logger.info(f"[LLM RECV] {cleaned}")
return LLMReply(cleaned, bool(response.get("cut_off")))

Expand Down
Loading
Loading