# Identity and Access Management

> Learn how to configure user authentication, authorization, and access control for CodeBuddy Code in your organization.

## Authentication Methods

### Quick Start

Choose an authentication method based on your scenario:

| Scenario | Recommended Method | How to Get Credentials |
|:---------|:-------------------|:-----------------------|
| Individual Developer | `CODEBUDDY_API_KEY` | [Get API Key from platform](#individual-users-get-api-key) |
| Enterprise/Team (OAuth Integration) | `apiKeyHelper` | [Create app to get Client ID/Secret](#enterprise-users-oauth-authentication) |
| CI/CD with existing OAuth token | `CODEBUDDY_AUTH_TOKEN` | Use existing token directly |
| Third-party Model Service | `CODEBUDDY_API_KEY` + `BASE_URL` | Get from third-party provider |

> When multiple authentication methods are configured, they take effect in the following priority: **CODEBUDDY_AUTH_TOKEN > apiKeyHelper > CODEBUDDY_API_KEY**


### Enterprise Users: OAuth Authentication

Suitable for enterprise/team integration, obtaining tokens via OAuth 2.0.

> Currently only introducing the Client Credentials authorization method, suitable for server-side applications and CI/CD scenarios.

> **Prerequisite**: Enterprise users need to purchase CodeBuddy Premium before using OAuth authentication. See the [CodeBuddy Premium Purchase Guide](https://cloud.tencent.com/document/product/1749/110012) for details.

**Step 1: Create Application, Get Client ID and Secret**

Refer to the [Enterprise Developer Quick Start](https://copilot.tencent.com/apiDocs/open-platform.html) to complete:
1. Create an enterprise application
2. Get Client ID and Client Secret

**Step 2: Create a Script to Get Token**

```bash
#!/bin/bash
# get-oauth-token.sh - OAuth 2.0 Client Credentials flow

CLIENT_ID="${OAUTH_CLIENT_ID}"
CLIENT_SECRET="${OAUTH_CLIENT_SECRET}"
TOKEN_URL="https://copilot.tencent.com/oauth2/token"

response=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET")

echo "$response" | jq -r '.access_token'
```

**Step 3: Configure apiKeyHelper**

Configure in `~/.codebuddy/settings.json` or project `.codebuddy/settings.json`:

```json
{
  "apiKeyHelper": "/path/to/get-oauth-token.sh"
}
```

After configuration, you can use the `codebuddy` command.

> Tokens obtained by apiKeyHelper are cached for 5 minutes by default. You can adjust this via the `CODEBUDDY_CODE_API_KEY_HELPER_TTL_MS` environment variable (in milliseconds).

---

### Third-Party Model Services

Suitable for using third-party model services like OpenRouter.

> **Note:** When using third-party model services, there is no need to set the `CODEBUDDY_INTERNET_ENVIRONMENT` environment variable, as requests are sent directly to the third-party service endpoint.

```bash
export CODEBUDDY_API_KEY="sk-or-v1-xxx"
export CODEBUDDY_BASE_URL="https://openrouter.ai/api/v1"
codebuddy --model openai/gpt-4
```

---

### Authentication Methods Explained

#### CODEBUDDY_API_KEY

Static API Key, suitable for most scenarios.

| Feature | Description |
|:--------|:------------|
| Environment Variable | `CODEBUDDY_API_KEY` |
| Auth Type | API Key (X-Api-Key header) |
| Use Cases | Personal development, third-party model services |

> **Warning: When using API Key, you must also configure the `CODEBUDDY_INTERNET_ENVIRONMENT` environment variable!**
>
> | Version | Configuration Value |
> |:--------|:--------------------|
> | International | Not set (default) |
> | China | `internal` |
> | iOA | `ioa` |

```bash
# International version
export CODEBUDDY_API_KEY="your-api-key"

# China version
export CODEBUDDY_API_KEY="your-api-key"
export CODEBUDDY_INTERNET_ENVIRONMENT=internal

# iOA version
export CODEBUDDY_API_KEY="your-api-key"
export CODEBUDDY_INTERNET_ENVIRONMENT=ioa
```

#### CODEBUDDY_AUTH_TOKEN

Pre-obtained OAuth Bearer Token, suitable for CI/CD or scenarios with existing tokens.

| Feature | Description |
|:--------|:------------|
| Environment Variable | `CODEBUDDY_AUTH_TOKEN` |
| Auth Type | Bearer Token (Authorization header) |
| Use Cases | CI/CD automation, existing OAuth token |

```bash
export CODEBUDDY_AUTH_TOKEN="eyJhbGciOiJSUzI1NiIs..."
```

Can also be configured in settings.json:

```json
{
  "env": {
    "CODEBUDDY_AUTH_TOKEN": "your-oauth-token"
  }
}
```

#### apiKeyHelper

Dynamically obtain tokens via script, suitable for OAuth integration or scenarios requiring periodic token refresh.

| Feature | Description |
|:--------|:------------|
| Configuration | `apiKeyHelper` field in settings.json |
| Auth Type | Bearer Token (returned by script) |
| Caching | Default 5 minutes, configurable via `CODEBUDDY_CODE_API_KEY_HELPER_TTL_MS` |
| Use Cases | OAuth Client Credentials, Vault integration, automatic token refresh |

**Script Requirements:**
- Output the token to standard output (stdout)
- Exit with code 0 to indicate success
- Script execution timeout is 30 seconds

**Configuration Example:**

```json
{
  "apiKeyHelper": "/path/to/get-token.sh"
}
```

**Example of Getting Token from Vault:**

```bash
#!/bin/bash
vault read -field=api_key secret/codebuddy/api-key
```

For detailed authentication configuration, see [Settings Documentation - Environment Variables](settings.md#environment-variables).

## Access Control and Permissions

We support fine-grained permissions so you can precisely specify what the agent is allowed to do (e.g., run tests, run linters) and not allowed to do (e.g., update cloud infrastructure). These permission settings can be checked into version control and distributed to all developers in your organization, or customized by individual developers.

### Permission System

CodeBuddy Code uses a hierarchical permission system to balance functionality and security:

| Tool Type | Examples | Requires Approval | "Yes, don't ask again" Behavior |
|:----------|:---------|:------------------|:--------------------------------|
| Read-only | File reading, LS, Grep | No | N/A |
| Bash commands | Shell execution | Yes | Permanently remembered by project directory and command |
| File modifications | Edit/Write files | Yes | Effective until session ends |

### Configuring Permissions

You can use `/permissions` to view and manage CodeBuddy Code's tool permissions. This UI lists all permission rules and the settings.json files they come from.

* **Allow** rules will allow CodeBuddy Code to use specified tools without further manual approval.
* **Ask** rules will prompt for user confirmation when CodeBuddy Code attempts to use specified tools. Ask rules take precedence over allow rules.
* **Deny** rules will block CodeBuddy Code from using specified tools. Deny rules take precedence over allow and ask rules.
* **Additional directories** extend CodeBuddy's file access to directories beyond the initial working directory.
* **Default mode** controls CodeBuddy's permission behavior when encountering new requests.

Permission rules use the format: `Tool` or `Tool(optional-specifier)`

Rules with only the tool name match any use of that tool. For example, adding `Bash` to the allow rules list will allow CodeBuddy Code to use the Bash tool without user approval.

#### Permission Modes

CodeBuddy Code supports several permission modes, which can be set as `defaultMode` in the [settings file](settings.md#configuration-files):

| Mode | Description |
|:-----|:------------|
| `default` | Standard behavior - prompts for permission on first use of each tool |
| `acceptEdits` | Automatically accepts file edit permissions for the session |
| `plan` | Plan mode - CodeBuddy can analyze but not modify files or execute commands |
| `bypassPermissions` | Skips all permission prompts (requires secure environment - see warning below) |

<Warning>
  `bypassPermissions` mode should only be used in secure, isolated environments, such as Docker containers or VMs. Using this mode on production environments or systems with sensitive data may pose security risks.
</Warning>

<Note>
  **`trustAll` / `trustedDirectories` are not replacements for permission modes.** These two fields only affect the **directory trust authorization prompt at startup** (the one-time popup asking "trust this directory and allow CodeBuddy to run in it"), and have nothing to do with whether approval is prompted when a tool executes.

  - To exempt tool approval, set `permissions.defaultMode` or use `--permission-mode bypassPermissions` / `-y` / `--dangerously-skip-permissions`
  - To exempt the directory trust popup, use `trustAll: true` or add the directory to `trustedDirectories`
  - The two switches are independent; the directory trust popup still appears normally when `bypassPermissions` is enabled, and vice versa

  Therefore, the claim that "enabling `bypassPermissions` + `trustAll` means you don't need to configure anything else" is inaccurate — the former controls tool approval, the latter controls directory trust; they address different confirmation entry points.
</Note>

#### Working Directory

By default, CodeBuddy can access files in the directory where it's launched. You can extend this access:

* **At startup**: Use the `--add-dir <path>` CLI parameter
* **During session**: Use the `/add-dir` slash command
* **Persistent configuration**: Add to `additionalDirectories` in the [settings file](settings.md#configuration-files)

Files in additional directories follow the same permission rules as the original working directory - they can be read without prompts, and file edit permissions follow the current permission mode.

#### Tool-Specific Permission Rules

Some tools support more fine-grained permission control:

**Bash**

* `Bash(npm run build)` exactly matches the Bash command `npm run build`
* `Bash(npm run test:*)` matches Bash commands starting with `npm run test`
* `Bash(curl http://site.com/:*)` matches curl commands starting with `curl http://site.com/`

<Tip>
  CodeBuddy Code recognizes shell operators (like `&&`), so prefix matching rules like `Bash(safe-cmd:*)` won't grant it permission to run commands like `safe-cmd && other-cmd`
</Tip>

<Warning>
  Important limitations of Bash permission patterns:

  1. This tool uses **prefix matching**, not regular expressions or glob patterns
  2. The wildcard `:*` only works at the end of the pattern to match any subsequent content
  3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in multiple ways:
     * Options before URL: `curl -X GET http://github.com/...` doesn't match
     * Different protocol: `curl https://github.com/...` doesn't match
     * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)
     * Variables: `URL=http://github.com && curl $URL` doesn't match
     * Extra spaces: `curl  http://github.com` doesn't match

  For more reliable URL filtering, consider:

  * Using the WebFetch tool with `WebFetch(domain:github.com)` permission
  * Instructing CodeBuddy Code via CODEBUDDY.md about allowed curl patterns
  * Using hooks for custom permission validation
</Warning>

**Read & Edit**

`Edit` rules apply to all built-in tools that edit files. CodeBuddy will try its best to apply `Read` rules to all built-in tools that read files, like Grep, Glob, and LS.

Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification, with four different pattern types:

| Pattern | Meaning | Example | Matches |
|---------|---------|---------|---------|
| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |
| `~/path` | Path from **home directory** | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |
| `/path` | **Relative to settings file** path | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |
| `path` or `./path` | **Relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

<Warning>
  Patterns like `/Users/alice/file` are not absolute paths - they're relative to your settings file! Use `//Users/alice/file` for absolute paths.
</Warning>

**Examples:**

* `Edit(/docs/**)` - Edit in `<project>/docs/` (not `/docs/`!)
* `Read(~/.zshrc)` - Read home directory's `.zshrc`
* `Edit(//tmp/scratch.txt)` - Edit absolute path `/tmp/scratch.txt`
* `Read(src/**)` - Read from `<current directory>/src/`

**WebFetch**

* `WebFetch(domain:example.com)` matches fetch requests to example.com

**MCP**

* `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in CodeBuddy Code)
* `mcp__puppeteer__*` wildcard syntax, also matches all tools from the `puppeteer` server
* `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server

<Tip>
  To approve all tools from an MCP server, you can use either format:

  * Use: `mcp__github` (approves all GitHub tools)
  * Use: `mcp__github__*` (approves all GitHub tools, equivalent to the above)

  To approve only specific tools, list each one:

  * Use: `mcp__github__get_issue`
  * Use: `mcp__github__list_issues`
</Tip>

### Permission Configuration Examples

**Basic Permission Configuration:**

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Edit",
      "Bash(git:*)",
      "Bash(npm:*)"
    ],
    "ask": [
      "WebFetch",
      "Bash(docker:*)"
    ],
    "deny": [
      "Bash(rm:*)",
      "Bash(sudo:*)",
      "Edit(**/*.env)",
      "Read(~/.ssh/**)"
    ]
  }
}
```

**Security-Restricted Configuration:**

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Edit(src/**)",
      "Bash(git:status,git:diff)"
    ],
    "deny": [
      "Edit(**/*.env)",
      "Edit(**/*.key)",
      "Edit(**/*.pem)",
      "Bash(wget:*)",
      "Bash(curl:*)",
      "Read(/etc/**)",
      "Read(~/.ssh/**)",
      "Read(~/.aws/**)"
    ],
    "defaultMode": "default"
  }
}
```

### Using Hooks for Additional Permission Control

[CodeBuddy Code hooks](hooks.md) provide a way to register custom shell commands for runtime permission evaluation. When CodeBuddy Code makes a tool call, PreToolUse hooks run before the permission system, and hook output can decide to approve or deny the tool call instead of the permission system.

See [Hooks Documentation](hooks.md) for details.

## Settings Priority

When multiple settings sources exist, they are applied in the following order (from highest to lowest priority):

1. Command line arguments
2. Local project settings (`.codebuddy/settings.local.json`)
3. Shared project settings (`.codebuddy/settings.json`)
4. User settings (`~/.codebuddy/settings.json`)

This hierarchy ensures flexibility at project and user levels where appropriate.

## Credential Management

CodeBuddy Code securely manages your authentication credentials:

| Platform | Storage Location |
|:---------|:-----------------:|
| macOS | Encrypted macOS Keychain |
| Linux | System keyring (GNOME Keyring, KWallet) |
| Windows | Windows Credential Manager |

**Dynamic Credential Retrieval:** Use `apiKeyHelper` to configure custom scripts for dynamic token retrieval. See [apiKeyHelper Configuration](#apikeyhelper) for details.

## Security Best Practices

### 1. Principle of Least Privilege

Only grant CodeBuddy Code the 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 Bash Sandbox

Enable sandboxing on supported platforms to isolate bash commands:

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "excludedCommands": ["docker"]
  }
}
```

See [Bash Sandbox Documentation](bash-sandboxing.md) for details.

### 4. Review Permission Logs

Regularly check CodeBuddy Code's permission usage to ensure compliance with security policies.

### 5. Team Configuration Sharing

Check team-level permission configurations into version control:

```bash
# Create team shared configuration
.codebuddy/settings.json

# Add to .gitignore
.codebuddy/settings.local.json
```

## Common Questions

### What if API Key authentication fails?

This is the most common issue, usually caused by **not configuring or incorrectly configuring the `CODEBUDDY_INTERNET_ENVIRONMENT` environment variable**.

**Troubleshooting Steps:**

1. Confirm which version you're using (International/China/iOA)
2. Check if environment variables are correctly set:

```bash
# Check current configuration
echo $CODEBUDDY_API_KEY
echo $CODEBUDDY_INTERNET_ENVIRONMENT
```

3. Set the correct environment variables based on your version:

| Version | `CODEBUDDY_INTERNET_ENVIRONMENT` |
|:--------|:---------------------------------|
| International | Not set or `public` |
| China | `internal` |
| iOA | `ioa` |

**Common Errors:**

- China version users forget to set `CODEBUDDY_INTERNET_ENVIRONMENT=internal`
- iOA version users set it to `internal` instead of `ioa`
- Environment variables only take effect in the current terminal and are lost when opening a new terminal (recommend adding to shell configuration file)

### How do I temporarily bypass permissions?

Start CodeBuddy Code with `--permission-mode bypassPermissions`:

```bash
codebuddy --permission-mode bypassPermissions
```

<Warning>
  Only use this option in secure, isolated environments!
</Warning>

### How do I set different permissions for specific projects?

Create `.codebuddy/settings.json` in the project root directory:

```json
{
  "permissions": {
    "allow": ["project-specific permissions"]
  }
}
```

### How do I view current permission configuration?

Use the `/permissions` command to view all effective permission rules and their sources.

## See Also

* [Settings Configuration](settings.md) - Learn about complete configuration options
* [Hooks Documentation](hooks.md) - Use hooks for advanced permission control
* [Bash Sandbox](bash-sandboxing.md) - Learn about sandbox isolation features
* [MCP Integration](mcp.md) - Configure MCP server permissions

---

*Ensure CodeBuddy Code works within security boundaries through proper permission configuration*
