# How to Secure PrimeAgent Instances: Credential Management and Best Practices

> Secure PrimeAgent instances effectively. Learn about credential management, AuthStorage subsystem, and best practices for protecting API keys and OAuth tokens in your PrimeAgent repository.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: best-practices
- Published: 2026-09-08

---

**PrimeAgent instances are secured through the `AuthStorage` subsystem in [`packages/coding-agent/src/core/auth-storage.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/auth-storage.ts), which enforces 0o600 file permissions, atomic writes, and concurrency-safe locking to protect API keys and OAuth tokens.**

Securing PrimeAgent instances requires understanding the credential management architecture implemented in the PrimeIntellect-ai/prime-agent repository. The system stores sensitive authentication data through a dedicated `AuthStorage` class that provides filesystem-level protection and race-condition prevention. By implementing the security patterns outlined in the source code, you can prevent credential leakage and ensure safe concurrent access to API keys across multiple agent processes.

## Core Security Architecture of AuthStorage

The `AuthStorage` class in [`packages/coding-agent/src/core/auth-storage.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/auth-storage.ts) provides the foundation for secure credential management through two primary mechanisms: strict filesystem permissions and robust concurrency control.

### Filesystem Isolation with Strict Permissions

The `FileAuthStorageBackend` implementation creates the [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json) credential store with mode **0o600** (owner-read/write only), as defined in lines 31-38 of the source. Parent directories are created with mode **0o700** (owner-only access), ensuring no other system users can traverse the credential path (lines 13-16).

### Concurrent Access Protection

To prevent race conditions during OAuth token refreshes, the library uses **`proper-lockfile`** with configurable retry logic (lines 44-78). The async implementation employs exponential back-off and stale-lock detection (lines 17-27), providing a fallback handler for compromised locks. This ensures that multiple PrimeAgent instances can safely share credential stores without collision.

## Credential Resolution and Storage Patterns

Understanding how PrimeAgent resolves authentication secrets is essential for deploying secure configurations.

### The Four-Tier Source Precedence

The `getApiKeyWithSourceToken` method (starting at line 68) implements a strict resolution hierarchy:

1. **Runtime overrides** via the `--api-key` CLI flag (memory-only)
2. **Prime Inference** sources: environment variable, Prime CLI config, then [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json)
3. **Other providers**: [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json) followed by environment variables
4. **Custom fallback resolver** (models-json) for extensible provider support

### Environment Variable Isolation

Short-lived secrets should use environment variables accessed via `findEnvKeys` and `getEnvApiKey` (lines 49-53). These values are never persisted to disk, limiting secret exposure to the current process lifetime.

### Prime CLI Integration

For Prime Inference keys, the system can store credentials in the user's Prime CLI configuration rather than [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json). The `usePrimeCliConfig` option (lines 71-74) triggers reads and writes via `loadPrimeCliConfig`, `savePrimeCliApiKey`, and `savePrimeCliTeamSelection` (lines 24-31, 38-45), keeping provider-specific credentials in their native management tools.

### Atomic Persistence Guarantees

All credential updates use `writeFileAtomicSync` (imported at line 22), ensuring that [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json) is never partially written. This atomic write operation maintains the 0o600 permission model even during active updates.

### Stale Credential Invalidation

The `markAuthStale` method (lines 84-86) records a token fingerprint when credentials expire or are superseded, preventing accidental reuse. The `clearAuthStale` method (lines 132-134) removes this marker upon successful re-authentication, maintaining a clean credential state.

## Best Practices for Securing PrimeAgent Instances

Implement these seven security measures to protect your PrimeAgent deployments:

1. **Restrict filesystem permissions** – Verify that `~/.pi/agent/auth.json` and its parent directory are owned by the executing user with permissions 0o600 and 0o700 respectively. The library enforces this by default, but explicit verification prevents configuration drift.

2. **Prefer environment variables for temporary secrets** – Use `PRIME_API_KEY`, `OPENAI_API_KEY`, or provider-specific variables for one-off runs. These never touch the persistent file, reducing disk exposure.

3. **Leverage runtime CLI flags** – Use the `--api-key` flag for ad-hoc sessions. This stores credentials only in memory and clears them on process exit.

4. **Prevent version control exposure** – Never commit [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json) or `.env` files containing real keys. Add these paths to `.gitignore` and audit repositories for accidental secret inclusion.

5. **Rely on built-in locking** – Do not implement custom file-based synchronization. The `proper-lockfile` integration handles concurrent token refreshes safely.

6. **Explicitly mark credentials stale** – Call `authStorage.logout(provider)` or `authStorage.markAuthStale(provider)` after logout or rotation to prevent accidental reuse of revoked tokens.

7. **Audit custom fallback resolvers** – Only enable custom providers when you control the resolver code. The resolver receives the provider name and must return a secret string or `undefined`, making it a critical trust boundary.

## Implementation Example

The following TypeScript demonstrates secure credential management using the PrimeAgent SDK:

```typescript
import { AuthStorage } from "@earendil-works/pi-ai";

// 1️⃣ Create an AuthStorage backed by the default auth.json path.
const auth = AuthStorage.create();   // reads ~/.pi/agent/auth.json

// 2️⃣ Store a new API key for OpenAI (writes atomically with 0o600 mode).
await auth.set("openai", { type: "api_key", key: "sk-••••••••••••••" });

// 3️⃣ Retrieve the key, respecting the source precedence.
const key = await auth.getApiKey("openai");          // → "sk-••••••••••••••"
const { source } = await auth.getApiKeyWithSourceToken("openai");
console.log(`Key came from ${source.source}`);       // e.g. "stored"

// 4️⃣ Use a runtime override (CLI flag) – not persisted to disk.
auth.setRuntimeApiKey("openai", "sk‑temp‑override");

// 5️⃣ Mark a credential stale after manual rotation.
auth.markAuthStale("openai");

// 6️⃣ Log out of an OAuth provider (clears Prime‑CLI credentials if needed).
await auth.logout("google-vertex");

```

## Summary

Securing PrimeAgent instances centers on the `AuthStorage` subsystem and its implementation in [`packages/coding-agent/src/core/auth-storage.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/auth-storage.ts). Key takeaways include:

- **Filesystem permissions** are enforced at 0o600 for files and 0o700 for directories by default
- **Concurrency safety** is handled through `proper-lockfile` with exponential back-off
- **Credential resolution** follows a strict precedence: runtime flags, environment variables, Prime CLI config, then [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json)
- **Atomic writes** prevent partial credential corruption during updates
- **Stale credential tracking** prevents accidental use of expired tokens

## Frequently Asked Questions

### What file permissions does PrimeAgent use for credential storage?

PrimeAgent creates the [`auth.json`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth.json) file with mode 0o600 (owner read/write only) and parent directories with mode 0o700 (owner-only access). These permissions are hardcoded in [`packages/coding-agent/src/core/auth-storage.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/auth-storage.ts) at lines 31-38 and 13-16, ensuring no other system users can access stored API keys.

### How does PrimeAgent handle concurrent access to authentication tokens?

The system uses the `proper-lockfile` library with retry logic and exponential back-off to prevent race conditions during token refreshes. This implementation in lines 44-78 of [`auth-storage.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/auth-storage.ts) ensures that multiple agent instances can safely update OAuth tokens without corruption or collision.

### Can I use environment variables instead of the auth.json file?

Yes. PrimeAgent checks environment variables such as `PRIME_API_KEY` and `OPENAI_API_KEY` through the `findEnvKeys` and `getEnvApiKey` methods (lines 49-53). These values take precedence over stored credentials and are never written to disk, making them ideal for containerized or temporary deployments.

### How do I revoke or rotate credentials in PrimeAgent?

Use the `markAuthStale` method (lines 84-86) to invalidate credentials after rotation, or call `logout` to remove them entirely. For Prime Inference credentials stored via the CLI integration, the system updates the Prime CLI configuration files directly, ensuring synchronization across tools.