All files / agent/src/security secretManager.ts

81.95% Statements 368/449
75.51% Branches 37/49
80.95% Functions 17/21
81.95% Lines 368/449

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 4501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 33x 33x 33x 1x 1x 33x 33x 33x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 8x 8x 8x 8x 7x 7x 7x 32x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 32x 1x 1x 1x 1x 1x 77x 77x 77x 77x 77x 1x 1x 1x 1x 1x 68x 68x 68x 1x 1x 1x 1x 1x 5x 5x 2x 2x 2x 2x 2x 2x 5x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 34x 34x 9x 34x 25x 25x 34x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 1x 1x 1x 1x 1x 1x 154x 4x 4x 154x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 1x 1x 9x 9x 9x 9x 9x 10x     9x 9x 9x 10x     9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x     2x     2x     2x 2x 2x 2x               2x                 2x                                                     1x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x                 1x 1x 1x 1x           1x 1x 1x 1x                  
/**
 * Secret Manager
 *
 * Provides encrypted secret storage at rest using AES-256-GCM.
 * Encryption key is derived from machine-specific data + optional passphrase
 * via PBKDF2. Secrets are stored in ~/.buildhive/secrets.enc as a single
 * encrypted blob containing a JSON envelope.
 *
 * Uses ONLY Node.js built-in modules (crypto, fs, path, os).
 */
 
import * as crypto from 'crypto';
import { promises as fs } from 'fs';
import * as path from 'path';
import * as os from 'os';
import type { AgentConfig } from '../config/types.js';
 
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
 
const ALGORITHM = 'aes-256-gcm';
const KEY_LENGTH = 32; // 256 bits
const IV_LENGTH = 16; // 128 bits for GCM
const AUTH_TAG_LENGTH = 16; // 128 bits
const SALT_LENGTH = 32;
const PBKDF2_ITERATIONS = 600_000; // OWASP recommendation
const PBKDF2_DIGEST = 'sha512';
const SECRETS_FILE_NAME = 'secrets.enc';
const SECRETS_FILE_MODE = 0o600; // Owner read/write only
const SECRET_REF_PREFIX = 'secret:';
const ENVELOPE_VERSION = 1;
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
interface SecretsEnvelope {
  secrets: Record<string, string>;
  version: number;
  updatedAt: string;
}
 
/**
 * Binary file layout (all lengths in bytes):
 *   [4]  magic bytes "BHSM"
 *   [1]  format version
 *   [32] PBKDF2 salt
 *   [16] AES-GCM IV
 *   [16] AES-GCM auth tag
 *   [*]  ciphertext (rest of file)
 */
const MAGIC = Buffer.from('BHSM');
const FORMAT_VERSION = 1;
const HEADER_SIZE = MAGIC.length + 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
 
// ---------------------------------------------------------------------------
// SecretManager
// ---------------------------------------------------------------------------
 
export class SecretManager {
  private readonly configDir: string;
  private readonly secretsPath: string;
  private derivedKey: Buffer | null = null;
  private envelope: SecretsEnvelope | null = null;
 
  constructor(configDir?: string) {
    this.configDir = configDir ?? path.join(os.homedir(), '.buildhive');
    this.secretsPath = path.join(this.configDir, SECRETS_FILE_NAME);
  }
 
  // -----------------------------------------------------------------------
  // Public API
  // -----------------------------------------------------------------------
 
  /**
   * Initialize the secret manager. If a secrets file already exists it is
   * unlocked (decrypted). Otherwise a new empty vault is created.
   *
   * @param passphrase Optional passphrase. When omitted a machine-derived
   *                   key is used (less secure but zero-friction for dev).
   */
  async initialize(passphrase?: string): Promise<void> {
    const exists = await this.isInitialized();
 
    if (exists) {
      // Unlock existing vault
      const raw = await fs.readFile(this.secretsPath);
      const { salt, iv, authTag, ciphertext } = this.parseFile(raw);
      this.derivedKey = await this.deriveKey(passphrase, salt);
 
      const plaintext = this.decrypt(ciphertext, iv, authTag);
      this.envelope = JSON.parse(plaintext) as SecretsEnvelope;
    } else {
      // Create new empty vault
      await fs.mkdir(this.configDir, { recursive: true });
      this.derivedKey = await this.deriveKey(passphrase);
      this.envelope = {
        secrets: {},
        version: ENVELOPE_VERSION,
        updatedAt: new Date().toISOString(),
      };
      await this.flush();
    }
  }
 
  /**
   * Store a secret value under the given key.
   */
  async setSecret(key: string, value: string): Promise<void> {
    this.ensureUnlocked();
    this.envelope!.secrets[key] = value;
    this.envelope!.updatedAt = new Date().toISOString();
    await this.flush();
  }
 
  /**
   * Retrieve a secret value. Returns null if the key does not exist.
   */
  async getSecret(key: string): Promise<string | null> {
    this.ensureUnlocked();
    return this.envelope!.secrets[key] ?? null;
  }
 
  /**
   * Delete a secret. Returns true if the key existed.
   */
  async deleteSecret(key: string): Promise<boolean> {
    this.ensureUnlocked();
    if (!(key in this.envelope!.secrets)) {
      return false;
    }
    delete this.envelope!.secrets[key];
    this.envelope!.updatedAt = new Date().toISOString();
    await this.flush();
    return true;
  }
 
  /**
   * List all stored secret keys (values are never exposed).
   */
  async listSecrets(): Promise<string[]> {
    this.ensureUnlocked();
    return Object.keys(this.envelope!.secrets);
  }
 
  /**
   * Check whether a secrets file already exists on disk.
   */
  async isInitialized(): Promise<boolean> {
    try {
      await fs.access(this.secretsPath);
      return true;
    } catch {
      return false;
    }
  }
 
  /**
   * Rotate the encryption key by re-encrypting all secrets with a new
   * passphrase. The old passphrase is required to unlock first.
   */
  async rotateKey(oldPassphrase: string, newPassphrase: string): Promise<void> {
    // Unlock with old key
    const raw = await fs.readFile(this.secretsPath);
    const { salt, iv, authTag, ciphertext } = this.parseFile(raw);
    const oldKey = await this.deriveKey(oldPassphrase, salt);
    const plaintext = this.decrypt(ciphertext, iv, authTag, oldKey);
    this.envelope = JSON.parse(plaintext) as SecretsEnvelope;
 
    // Re-encrypt with new key
    this.derivedKey = await this.deriveKey(newPassphrase);
    this.envelope.updatedAt = new Date().toISOString();
    await this.flush();
  }
 
  // -----------------------------------------------------------------------
  // Internals
  // -----------------------------------------------------------------------
 
  private ensureUnlocked(): void {
    if (!this.derivedKey || !this.envelope) {
      throw new Error('SecretManager is not initialized. Call initialize() first.');
    }
  }
 
  /**
   * Derive an encryption key from a passphrase (or machine-id fallback)
   * using PBKDF2. When `existingSalt` is provided, it is reused (unlock
   * path); otherwise a new random salt is generated (create / rotate path).
   */
  private deriveKey(passphrase?: string, existingSalt?: Buffer): Promise<Buffer> {
    const material = passphrase ?? this.getMachineMaterial();
    const salt = existingSalt ?? crypto.randomBytes(SALT_LENGTH);
 
    return new Promise<Buffer>((resolve, reject) => {
      crypto.pbkdf2(
        material,
        salt,
        PBKDF2_ITERATIONS,
        KEY_LENGTH,
        PBKDF2_DIGEST,
        (err, key) => {
          if (err) return reject(err);
          // Attach salt for later storage
          (key as any).__salt = salt;
          resolve(key);
        },
      );
    });
  }
 
  /**
   * Returns a machine-specific string used as fallback key material when
   * no passphrase is provided.
   */
  private getMachineMaterial(): string {
    const hostname = os.hostname();
    const homedir = os.homedir();
    const platform = os.platform();
    const arch = os.arch();
    return `buildhive:${hostname}:${homedir}:${platform}:${arch}`;
  }
 
  /**
   * Encrypt plaintext using AES-256-GCM.
   */
  private encrypt(plaintext: string): { iv: Buffer; authTag: Buffer; ciphertext: Buffer } {
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, this.derivedKey!, iv);
 
    const encrypted = Buffer.concat([
      cipher.update(plaintext, 'utf8'),
      cipher.final(),
    ]);
    const authTag = cipher.getAuthTag();
 
    return { iv, authTag, ciphertext: encrypted };
  }
 
  /**
   * Decrypt ciphertext using AES-256-GCM.
   */
  private decrypt(ciphertext: Buffer, iv: Buffer, authTag: Buffer, key?: Buffer): string {
    const useKey = key ?? this.derivedKey!;
    const decipher = crypto.createDecipheriv(ALGORITHM, useKey, iv);
    decipher.setAuthTag(authTag);
 
    const decrypted = Buffer.concat([
      decipher.update(ciphertext),
      decipher.final(),
    ]);
 
    return decrypted.toString('utf8');
  }
 
  /**
   * Serialize the current envelope to the encrypted file.
   */
  private async flush(): Promise<void> {
    const json = JSON.stringify(this.envelope);
    const { iv, authTag, ciphertext } = this.encrypt(json);
    const salt: Buffer = (this.derivedKey as any).__salt;
 
    // Build binary file: MAGIC | VERSION | SALT | IV | AUTH_TAG | CIPHERTEXT
    const header = Buffer.alloc(MAGIC.length + 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
    let offset = 0;
 
    MAGIC.copy(header, offset); offset += MAGIC.length;
    header.writeUInt8(FORMAT_VERSION, offset); offset += 1;
    salt.copy(header, offset); offset += SALT_LENGTH;
    iv.copy(header, offset); offset += IV_LENGTH;
    authTag.copy(header, offset);
 
    const file = Buffer.concat([header, ciphertext]);
 
    await fs.mkdir(this.configDir, { recursive: true });
    await fs.writeFile(this.secretsPath, file, { mode: SECRETS_FILE_MODE });
  }
 
  /**
   * Parse the binary secrets file into its component parts.
   */
  private parseFile(raw: Buffer): {
    salt: Buffer;
    iv: Buffer;
    authTag: Buffer;
    ciphertext: Buffer;
  } {
    if (raw.length < HEADER_SIZE) {
      throw new Error('Secrets file is corrupted: too small');
    }
 
    let offset = 0;
 
    const magic = raw.subarray(offset, offset + MAGIC.length);
    offset += MAGIC.length;
    if (!magic.equals(MAGIC)) {
      throw new Error('Secrets file is corrupted: invalid magic bytes');
    }
 
    const version = raw.readUInt8(offset);
    offset += 1;
    if (version !== FORMAT_VERSION) {
      throw new Error(`Unsupported secrets file version: ${version}`);
    }
 
    const salt = raw.subarray(offset, offset + SALT_LENGTH);
    offset += SALT_LENGTH;
 
    const iv = raw.subarray(offset, offset + IV_LENGTH);
    offset += IV_LENGTH;
 
    const authTag = raw.subarray(offset, offset + AUTH_TAG_LENGTH);
    offset += AUTH_TAG_LENGTH;
 
    const ciphertext = raw.subarray(offset);
 
    return { salt, iv, authTag, ciphertext };
  }
}
 
// ---------------------------------------------------------------------------
// Config integration helper
// ---------------------------------------------------------------------------
 
/**
 * Resolve any `secret:` prefixed values in an AgentConfig by looking them
 * up in the SecretManager. Plain values are returned as-is for backward
 * compatibility.
 *
 * Resolved fields:
 *   - config.apiKey
 *   - config.storageConfig.s3.accessKeyId
 *   - config.storageConfig.s3.secretAccessKey
 */
export async function resolveSecrets(
  config: AgentConfig,
  passphrase?: string,
): Promise<AgentConfig> {
  // Check whether any field actually needs resolution
  const fieldsToResolve: string[] = [];
 
  if (config.apiKey?.startsWith(SECRET_REF_PREFIX)) {
    fieldsToResolve.push('apiKey');
  }
  if (config.storageConfig?.s3?.accessKeyId?.startsWith(SECRET_REF_PREFIX)) {
    fieldsToResolve.push('s3.accessKeyId');
  }
  if (config.storageConfig?.s3?.secretAccessKey?.startsWith(SECRET_REF_PREFIX)) {
    fieldsToResolve.push('s3.secretAccessKey');
  }
 
  if (fieldsToResolve.length === 0) {
    return config;
  }

  const sm = new SecretManager();
  await sm.initialize(passphrase);

  // Build a shallow copy so we never mutate the original config
  const resolved: AgentConfig = { ...config };

  if (config.apiKey?.startsWith(SECRET_REF_PREFIX)) {
    const key = config.apiKey.slice(SECRET_REF_PREFIX.length);
    const value = await sm.getSecret(key);
    if (value === null) {
      throw new Error(`Secret reference "${key}" not found in SecretManager`);
    }
    resolved.apiKey = value;
  }

  if (config.storageConfig?.s3) {
    const s3 = { ...config.storageConfig.s3 };
    const storage = { ...config.storageConfig, s3 };

    if (s3.accessKeyId?.startsWith(SECRET_REF_PREFIX)) {
      const key = s3.accessKeyId.slice(SECRET_REF_PREFIX.length);
      const value = await sm.getSecret(key);
      if (value === null) {
        throw new Error(`Secret reference "${key}" not found in SecretManager`);
      }
      s3.accessKeyId = value;
    }

    if (s3.secretAccessKey?.startsWith(SECRET_REF_PREFIX)) {
      const key = s3.secretAccessKey.slice(SECRET_REF_PREFIX.length);
      const value = await sm.getSecret(key);
      if (value === null) {
        throw new Error(`Secret reference "${key}" not found in SecretManager`);
      }
      s3.secretAccessKey = value;
    }

    resolved.storageConfig = storage;
  }

  return resolved;
}
 
// ---------------------------------------------------------------------------
// CLI helper functions
// ---------------------------------------------------------------------------
 
/**
 * Store a secret (for CLI use).
 */
export async function secretSet(
  key: string,
  value: string,
  passphrase?: string,
): Promise<void> {
  const sm = new SecretManager();
  await sm.initialize(passphrase);
  await sm.setSecret(key, value);
}
 
/**
 * Retrieve a secret (for CLI use).
 */
export async function secretGet(
  key: string,
  passphrase?: string,
): Promise<string | null> {
  const sm = new SecretManager();
  await sm.initialize(passphrase);
  return sm.getSecret(key);
}
 
/**
 * List all secret keys (for CLI use).
 */
export async function secretList(passphrase?: string): Promise<string[]> {
  const sm = new SecretManager();
  await sm.initialize(passphrase);
  return sm.listSecrets();
}
 
/**
 * Delete a secret (for CLI use).
 */
export async function secretDelete(
  key: string,
  passphrase?: string,
): Promise<boolean> {
  const sm = new SecretManager();
  await sm.initialize(passphrase);
  return sm.deleteSecret(key);
}