import { describe, expect, test } from 'bun:test';
import { PERMITTED_ENV, assertEnvSafe } from './spawn-as-member';

// Pins the two guards standing between a member's agent turn and the owner's credential.
//
// Both of them shipped dead before this test existed, and in both cases the reason was the same: they were
// written inside the spawn closure, where the only way to reach them is to spawn, and the passing path spawns
// `sudo`. So nothing ever demonstrated them firing, and "it looks right" carried the weight. That is what
// these tests are for — not the happy path, which is obvious, but the two edits a future reader will actually
// make.

const OWNER_CRED = 'ANTHROPIC_API_KEY';

describe('assertEnvSafe', () => {
  test('the shipping lists are clean', () => {
    // The regression this exists to catch: somebody adds a credential to ALLOWED_ENV.
    expect(() => assertEnvSafe(PERMITTED_ENV, { HOME: '/home/x' }, 'x')).not.toThrow();
  });

  test('throws when a credential is in the allowlist — guards the constant', () => {
    // The realistic dangerous edit. Note the credential is NOT in childEnv: the point is that the *list*
    // permits it, so the next call that inherits one would pass it through silently.
    const poisoned = new Set([...PERMITTED_ENV, OWNER_CRED]);
    expect(() => assertEnvSafe(poisoned, { HOME: '/home/x' }, 'green')).toThrow(/is in the allowlist/);
  });

  test('throws when the built env carries an unvetted key — guards the construction', () => {
    expect(() => assertEnvSafe(PERMITTED_ENV, { HOME: '/home/x', POSTGRES_URL: 'postgres://…' }, 'green')).toThrow(
      /unvetted env/,
    );
  });

  test('names the offending variable, so the error is actionable', () => {
    expect(() => assertEnvSafe(PERMITTED_ENV, { JWT_SECRET: 'x' }, 'green')).toThrow(/JWT_SECRET/);
  });

  test('every NEVER_ENV name would be caught if it were permitted', () => {
    // Guards against the list being quietly narrowed as well as the allowlist being widened.
    for (const name of ['ANTHROPIC_BASE_URL', 'CLAUDE_CODE_OAUTH_TOKEN', 'POSTGRES_URL', 'JWT_SECRET']) {
      expect(() => assertEnvSafe(new Set([...PERMITTED_ENV, name]), {}, 'green')).toThrow(name);
    }
  });
});
