# Security Measures for Loading Token Files via CLI Arguments in CLI‑Anything

> Discover robust security measures for loading token files via CLI arguments in HKUDS/CLI-Anything. Learn about private directories, strict file modes, and Windows ACL isolation for enhanced protection.

- Repository: [✨Data Intelligence Lab@HKU✨/CLI-Anything](https://github.com/HKUDS/CLI-Anything)
- Tags: security-measures
- Published: 2026-08-16

---

**CLI‑Anything enforces defense‑in‑depth for OAuth token files through private directory creation, strict Unix file modes (0o600/0o700), and Windows ACL isolation via `icacls`.**

When handling credentials passed through CLI arguments, HKUDS/CLI‑Anything implements comprehensive file‑system protections to prevent unauthorized access. The Zoom integration demonstrates this approach through a hardened token storage layer that operates across Linux, macOS, and Windows environments.

## Dedicated Private Configuration Directory

The CLI creates a separate config directory for each integration. For Zoom, this is `~/.cli‑anything‑zoom`.

In `zoom/agent‑harness/cli_anything/zoom/utils/zoom_backend.py` at lines 56‑60, the backend ensures the directory exists with owner‑only access:

```python
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
_restrict_path(CONFIG_DIR, 0o700)

```

The **mode `0o700`** grants read, write, and execute permissions exclusively to the directory owner. No group or other users can access the directory contents.

## Token File Permissions with Strict Mode Enforcement

When OAuth tokens are written to disk, the file receives **mode `0o600`** (lines 87‑94):

```python
def save_tokens(tokens: Dict[str, Any]) -> None:
    tokens["saved_at"] = time.time()
    with open(TOKEN_FILE, "w") as f:
        json.dump(tokens, f)
    _restrict_path(TOKEN_FILE, 0o600)  # Owner read/write only

```

This guarantees that even if an attacker gains limited system access, the token file remains inaccessible without owner privileges.

## Cross‑Platform Access Control Implementation

The `_restrict_path()` helper enforces equivalent protections on Windows through native ACL commands (lines 43‑52):

```python
def _restrict_path(path: Path, mode: int) -> None:
    if platform.system() == "Windows":
        # Strip inherited permissions and grant current user full control

        subprocess.run(
            ["icacls", str(path), "/inheritance:r", "/grant:r", f"{getpass.getuser()}:F"],
            check=True
        )
    else:
        path.chmod(mode)

```

This ensures **consistent security semantics** across operating systems rather than relying on platform‑default behavior.

## Safe Token Loading and Validation

The `load_tokens()` function (lines 79‑85) implements defensive read patterns:

```python
def load_tokens() -> Dict[str, Any]:
    if not TOKEN_FILE.exists():
        return {}  # Explicit empty state, no exception handling needed

    with open(TOKEN_FILE) as f:
        return json.load(f)

```

By returning an empty dictionary for missing files, the CLI avoids exception‑based control flow and prevents accidental use of partially initialized data.

## Automatic Token Refresh with Protected Persistence

The `_get_valid_token()` method (lines 51‑68) combines expiration checking with secure rewrite:

1. Validates the stored `saved_at` timestamp against `expires_in`
2. Refreshes via OAuth if expiry is within **5 minutes**
3. Persists new credentials through the same `save_tokens()` pipeline

This ensures tokens never linger on disk beyond their validity period and refreshed credentials inherit the same file protections.

## Practical Integration Examples

Below are runnable patterns demonstrating secure token handling.

### Storing Tokens After OAuth Completion

```python
from cli_anything.zoom.utils.zoom_backend import save_tokens

def complete_oauth_flow(oauth_response: dict):
    """Store credentials with automatic permission enforcement."""
    token_payload = {
        "access_token": oauth_response["access_token"],
        "refresh_token": oauth_response["refresh_token"],
        "expires_in": oauth_response["expires_in"],
    }
    save_tokens(token_payload)  # Applies 0o600 permissions automatically

```

### Making Authenticated API Requests

```python
from cli_anything.zoom.utils.zoom_backend import api_get

def fetch_meetings():
    """Token refresh and validation handled internally."""
    return api_get("/users/me/meetings")

```

### CLI Usage Flow

```bash

# Initialize secure storage and complete OAuth

$ cli-anything-zoom auth login

# Subsequent commands transparently use protected tokens

$ cli-anything-zoom meetings list

```

## Key Source Files

| File Path | Security Responsibility |
|-----------|------------------------|
| `zoom/agent‑harness/cli_anything/zoom/utils/zoom_backend.py` | Core `_restrict_path()`, `save_tokens()`, `load_tokens()`, refresh logic |
| `zoom/agent‑harness/cli_anything/zoom/core/auth.py` | CLI command handlers invoking secure backend methods |
| `zoom/agent‑harness/cli_anything/zoom/zoom_cli.py` | Entry point routing for Zoom subcommands |

## Summary

- **Private directories** are created with `0o700` permissions before any token storage occurs
- **Token files** are written with `0o600` mode via `_restrict_path()` on Unix systems
- **Windows compatibility** is achieved through `icacls` commands that remove inheritance and grant exclusive user control
- **Defensive loading** returns explicit empty states rather than raising exceptions on missing files
- **Automatic refresh** validates timestamps and rewrites credentials through the same protected pipeline

## Frequently Asked Questions

### What file permissions does CLI‑Anything use for OAuth tokens?

CLI‑Anything applies **mode `0o600`** to token files, permitting read and write access only to the file owner. The containing directory uses **mode `0o700`**. On Windows, equivalent restrictions are enforced via `icacls` inheritance removal and user‑specific grants.

### How does the CLI prevent token leakage to other processes?

Tokens are **never passed as command‑line arguments** to subprocesses. The CLI reads the protected JSON file into memory and injects the bearer token directly into HTTP headers. The helper functions `save_tokens()` and `load_tokens()` abstract all disk access through the permission‑enforcing `_restrict_path()` wrapper.

### What happens if the token file is deleted or corrupted?

The `load_tokens()` function in [`zoom_backend.py`](https://github.com/HKUDS/CLI-Anything/blob/main/zoom_backend.py) returns an empty dictionary when `TOKEN_FILE.exists()` is false, triggering a new OAuth flow rather than failing with an exception. This design prevents crash loops and ensures users re‑authenticate cleanly.

### Does CLI‑Anything support automatic token refresh?

Yes. The `_get_valid_token()` method checks the `saved_at` timestamp against the token lifetime and proactively refreshes credentials when expiry is within 5 minutes. Refreshed tokens are persisted using the same `save_tokens()` routine that enforces `0o600` permissions.