# Security

> Learn about CodeBuddy Code's security protections and best practices for secure usage.

## Security Approach

### Security Foundation

Your code security is paramount. CodeBuddy Code is built with security as a core principle, developed following Tencent's comprehensive security program.

### Permission-Based Architecture

CodeBuddy Code uses strict read-only permissions by default. When additional operations are needed (editing files, running tests, executing commands), CodeBuddy Code requests explicit permission. Users control whether to approve operations once or allow automatically.

We designed CodeBuddy Code to be transparent and secure. For example, we require approval before executing bash commands, giving you direct control. This approach enables users and organizations to configure permissions directly.

For detailed permission configuration, see [Identity and Access Management](iam.md).

### Built-in Protections

To mitigate risks in agentic systems:

* **Sandboxed bash tool**: [Bash Sandbox](bash-sandboxing.md) isolates bash commands' file system and network access, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries within which CodeBuddy Code can work autonomously
* **Write Access Restrictions**: CodeBuddy Code can only write to the folder where it was launched and its subfolders—cannot modify files in parent directories without explicit permission. While CodeBuddy Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly limited to project scope, creating a clear security boundary
* **Prompt Fatigue Mitigation**: Support for whitelisting frequently used safe commands per user, per codebase, or per organization
* **Accept Edits Mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects

### User Responsibility

CodeBuddy Code only has the permissions you grant it. You are responsible for reviewing the security of suggested code and commands before approval.

## Prompt Injection Protection

Prompt injection is an attack technique where attackers attempt to override or manipulate an AI assistant's instructions by inserting malicious text. CodeBuddy Code includes multiple protections against these attacks:

### Core Protections

* **Permission System**: Sensitive operations require explicit approval
* **Context-Aware Analysis**: Detect potentially harmful instructions by analyzing complete requests
* **Input Sanitization**: Prevent command injection by processing user input
* **Command Blocklist**: Risky commands like `curl` and `wget` that fetch arbitrary content from the network are blocked by default. When explicitly allowed, note the [permission pattern limitations](iam.md#tool-specific-permission-rules)

### Privacy Protections

We implement multiple protections to safeguard your data, including:

* Limited retention periods for sensitive information
* Restricted access to user session data

For full details, please review our [Terms of Service](https://cloud.tencent.com/document/product/301/106125) and [Privacy Policy](https://privacy.qq.com/document/preview/284d799a07164d09bfc7cedd0ec3e089).

### Additional Protective Measures

* **Network Request Approval**: Tools that make network requests require user approval by default
* **Isolated Context Windows**: Web fetches use separate context windows to avoid injecting potentially malicious prompts
* **Trust Verification**: First-time codebase runs and new MCP servers require trust verification
  * Note: When running non-interactively with the `-p` flag, trust verification is disabled
* **Command Injection Detection**: Suspicious bash commands require manual approval even if previously whitelisted
* **Fail-Closed Matching**: Unmatched commands default to requiring manual approval
* **Natural Language Descriptions**: Complex bash commands include explanations for user understanding
* **Secure Credential Storage**: API keys and tokens are encrypted. See [Credential Management](iam.md#credential-management)

<Warning>
  **Windows WebDAV Security Risk**: When running CodeBuddy Code on Windows, we recommend not enabling WebDAV or allowing CodeBuddy Code to access paths that may contain WebDAV subdirectories, like `\\*`. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow CodeBuddy Code to trigger network requests to remote hosts, bypassing the permission system.
</Warning>

**Best Practices for Handling Untrusted Content**:

1. Review suggested commands before approval
2. Avoid piping untrusted content directly to CodeBuddy
3. Verify suggested changes to critical files
4. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services

<Warning>
  While these protections significantly reduce risk, no system is completely immune to all attacks. Always maintain good security practices when using any AI tool.
</Warning>

## MCP Security

CodeBuddy Code allows users to configure Model Context Protocol (MCP) servers. The list of allowed MCP servers is configured in source code as part of CodeBuddy Code settings checked into source control by engineers.

We encourage writing your own MCP servers or using MCP servers from providers you trust. You can configure CodeBuddy Code permissions for MCP servers. CodeBuddy does not manage or audit any MCP servers.

See [MCP Integration Documentation](mcp.md) for details.

## Gateway Network Security

When starting the HTTP service via `--serve` mode or Daemon, CodeBuddy Code employs multi-layered defenses to protect API endpoints:

### CORS Whitelist

Only cross-origin requests from legitimate origins are allowed. Requests with unauthorized Origins (whether OPTIONS preflight or actual requests) are rejected outright without executing any business logic. Three configuration modes are supported: exact origin (`https://example.com`), subdomain wildcard (`https://*.example.com`), and allow all (`*`). Configure via the environment variable `CODEBUDDY_CODE_CORS_ORIGINS` or the setting `gateway.corsOrigins`.

### Custom Request Header Validation

All API requests must include the `X-CodeBuddy-Request: 1` header. This mechanism leverages browser security policies: custom headers force a CORS preflight, and browsers do not allow sending custom headers in `no-cors` mode, thereby preventing cross-site request forgery.

Can be disabled via `CODEBUDDY_DISABLE_REQUEST_VALIDATION=1`. See [HTTP API Security](http-api.md#security) for details.

### Authentication Protection

Sensitive endpoints (including `/info`, `/health`) require a Bearer Token when password authentication is enabled. See [HTTP API Authentication](http-api.md#authentication) for details.

## Sandbox Security

CodeBuddy Code supports Bash sandbox functionality that isolates bash commands from your file system and network:

### Sandbox Isolation Levels

* **File System Isolation**: Control file access through Read/Edit permissions
* **Network Isolation**: Control network access through WebFetch permissions
* **Command Isolation**: Certain commands can be configured to run outside the sandbox

### Sandbox Configuration

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "excludedCommands": ["git", "docker"],
    "network": {
      "allowUnixSockets": ["/var/run/docker.sock"],
      "allowLocalBinding": true
    }
  }
}
```

### Sandbox Limitations

* **Platform Support**: Currently only supports macOS and Linux
* **Performance Impact**: Sandboxing may slightly affect command execution performance
* **Compatibility**: Some tools may not work properly in the sandbox

See [Bash Sandbox Documentation](bash-sandboxing.md) for complete configuration options.

## Security Best Practices

### Handling Sensitive Code

* Review all suggested changes before approval
* Use project-specific permission settings for sensitive repositories
* Regularly audit your permission settings using `/permissions`
* Use sandbox functionality for additional isolation

### Team Security

* Share approved permission configurations through version control
* Train team members on security best practices
* Regularly review and update permission policies
* Use project-level settings to enforce team standards

### Permission Configuration Best Practices

**1. Principle of Least Privilege**

Only grant minimum permissions needed to complete tasks:

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Edit(src/**/*.ts)",
      "Bash(npm:test,npm:build)"
    ],
    "deny": [
      "Edit(**/*.env)",
      "Bash(rm:*)",
      "Bash(sudo:*)"
    ]
  }
}
```

**2. Protect Sensitive Files**

Always deny access to files containing sensitive information:

```json
{
  "permissions": {
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(secrets/**)",
      "Read(~/.ssh/**)",
      "Read(~/.aws/**)",
      "Edit(**/*.key)",
      "Edit(**/*.pem)"
    ]
  }
}
```

**3. Use WebFetch Cautiously**

Deny or ask for network requests by default:

```json
{
  "permissions": {
    "ask": [
      "WebFetch"
    ],
    "allow": [
      "WebFetch(domain:github.com)",
      "WebFetch(domain:npmjs.com)"
    ]
  }
}
```

**4. Restrict Dangerous Commands**

Explicitly deny commands that could cause damage:

```json
{
  "permissions": {
    "deny": [
      "Bash(rm:*)",
      "Bash(sudo:*)",
      "Bash(chmod:*)",
      "Bash(chown:*)",
      "Bash(curl:*)",
      "Bash(wget:*)"
    ]
  }
}
```

### Environment Isolation

**1. Use Separate Development Environments**

Use different environments for different security levels:

```bash
# Production code - strict permissions
cd ~/production/app
codebuddy --permission-mode default

# Experimental projects - relaxed permissions
cd ~/experiments/test
codebuddy --permission-mode acceptEdits
```

**2. Containerized Development**

Use Docker containers for additional security boundaries:

```bash
# Run in container
docker run -it --rm -v $(pwd):/workspace codebuddy
```

### Code Review Process

**1. Pre-Commit Review**

Review CodeBuddy's changes before committing:

```bash
# View all changes
git diff

# Review specific files
git diff src/critical.ts
```

**2. Hook Validation**

Configure pre-commit hooks to validate changes:

```json
{
  "hooks": {
    "PreToolUse": {
      "Edit": "npm run lint-staged"
    }
  }
}
```

**3. Team Code Review**

Require team member review for important changes:

```bash
# Create PR instead of direct commit
git checkout -b feature/codebuddy-changes
git push origin feature/codebuddy-changes
```

### Sensitive Data Protection

**1. Use Environment Variables**

Don't hardcode sensitive information in code:

```bash
# Wrong example
export API_KEY="sk-1234567890"

# Correct example - use environment variable management tools
export $(cat .env.local | xargs)
```

**2. Configuration File Encryption**

Encrypt sensitive configuration files:

```bash
# Using git-crypt
git-crypt init
echo "secrets.json filter=git-crypt diff=git-crypt" >> .gitattributes
```

**3. Regular Credential Rotation**

Regularly change API keys and access tokens:

```bash
# Using apiKeyHelper for dynamic key retrieval
{
  "apiKeyHelper": "/usr/local/bin/get-rotating-key.sh"
}
```

### Auditing and Monitoring

**1. Log Permission Requests**

Track CodeBuddy's permission requests:

```json
{
  "hooks": {
    "PreToolUse": {
      "*": "echo \"[$(date)] Tool: $TOOL_NAME\" >> ~/.codebuddy/audit.log"
    }
  }
}
```

**2. Review Logs Regularly**

Check audit logs for anomalies:

```bash
# View recent tool usage
tail -f ~/.codebuddy/audit.log

# Search for sensitive operations
grep "Edit.*\.env" ~/.codebuddy/audit.log
```

**3. Permission Configuration Audit**

Regularly review permission configurations:

```bash
# View current permissions
codebuddy config get permissions

# List all settings files
find . -name "settings.json" -o -name "settings.local.json"
```

## Reporting Security Issues

If you discover a security vulnerability in CodeBuddy Code:

1. Do not disclose publicly
2. Report through [Contact Us](https://cloud.tencent.com/document/product/1749/104249)
3. Include detailed reproduction steps
4. Allow time for us to resolve the issue before public disclosure

## Security Checklist

Before using CodeBuddy Code, ensure:

- [ ] Reviewed and configured appropriate permission settings
- [ ] Added sensitive files to deny list
- [ ] Blocked or require confirmation for dangerous commands
- [ ] Enabled sandbox functionality as needed
- [ ] Stored API keys and tokens securely
- [ ] Team members received security training
- [ ] Established code review process
- [ ] Regularly audit permission usage
- [ ] Know how to report security issues

## Related Resources

* [Identity and Access Management](iam.md) - Configure permissions and access control
* [Bash Sandbox](bash-sandboxing.md) - File system and network isolation for bash commands
* [MCP Integration](mcp.md) - Configure MCP server permissions
* [Hooks Documentation](hooks.md) - Use hooks for custom security validation
* [Settings Configuration](settings.md) - Complete configuration options

---

*Ensure secure usage of CodeBuddy Code through proper security configuration and best practices*
