Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion packages/accounts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,57 @@ and audited like every other vault entry.
| Item | Fields |
| --------- | ------------------------------------------------------------------ |
| `account` | `endpoint`, `email`, `user_id`, `access_token`\*, `access_token_expires_at` |
| `api_key` | `endpoint`, `account_id`, `key_id`, `api_key`\*, `expires_at` |
| `api_key` | `endpoint`, `account_id`, `key_id`, `api_key`\*, `expires_at`, `database_id`, `principal_id`, `org_id` |

\* concealed. `accessToken()` returns `null` rather than an expired token, so a caller cannot
present a dead credential by accident.

## Principals

A principal is a scoped sub-identity — what an API key or an agent actually acts as. It is owned by
a human account and can only ever *narrow* that human: read-only, restricted per scope by a
permission mask, and optionally allowed to skip MFA step-up so CI is not blocked on a phone.

```typescript
const principalId = await accounts.createPrincipal(account.itemId, {
name: 'ci-deploy',
orgId,
isReadOnly: true,
bypassStepUp: true,
});

// mint the key *as* the principal, so it carries the principal's scope
await accounts.createApiKey(account.itemId, { name: 'ci', principalId, orgId });

for (const principal of await accounts.listPrincipals(account.itemId)) {
principal.entityIds; // what it reaches
principal.scopes; // per-scope overrides: allowedMask, isActive, isReadOnly
}
```

A scope with no override row means the principal inherits its owner there; `allowedMask` is
AND-ed with the owner's permissions during the SPRT cascade, so an override can only take access
away. Principals are read from the server on demand rather than cached, because a stale local copy
of someone's permissions is worse than none.

## Serving a harness

`VaultCredentials` is a credential provider shaped like the harness contract, reading from the
unlocked vault instead of a plaintext `account.json`:

```typescript
const credentials = new VaultCredentials(accounts);

await credentials.accountBearer(); // the signed-in account's token, or null
await credentials.dataToken(databaseId); // { token, origin: 'vault' }
```

It refuses rather than guesses: `null` when no account is signed in, when several are and none was
named, when the token has expired, and when no key — or more than one — is tagged for that
database. Tag one with `accounts.assignKeyToDatabase(keyItemId, databaseId)` or
`createApiKey({ databaseId })`. Nothing is cached; every call re-reads the vault, so locking the
vault cuts every consumer off at once.

## Testing without a server

`AccountManager` takes an `AuthClientFactory`, so the whole vault side runs against a fake:
Expand Down
103 changes: 103 additions & 0 deletions packages/accounts/__tests__/accounts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import {
AuthClientFactory,
AuthError,
CreateApiKeyOptions,
CreatePrincipalOptions,
hasExpired,
PrincipalRecord,
StepUpKind,
stepUpKind,
StepUpRequiredError,
Expand All @@ -26,6 +28,7 @@ const ENDPOINT = 'http://auth.localhost:3000/graphql';
class FakeServer {
readonly calls: Array<{ operation: string; token?: string }> = [];
private nextKey = 0;
principals: PrincipalRecord[] = [];
expiresAt: string | null = null;
/** Refuse sensitive calls with this factor until it has been re-proved. */
demandStepUp: StepUpKind | null = null;
Expand Down Expand Up @@ -81,6 +84,32 @@ class FakeServer {
this.calls.push({ operation: `revokeApiKey:${keyId}`, token });
this.refuseWithoutStepUp('revokeApiKey');
},
listPrincipals: async () => {
this.calls.push({ operation: 'listPrincipals', token });
return this.principals;
},
createPrincipal: async (options: CreatePrincipalOptions) => {
this.calls.push({ operation: 'createPrincipal', token });
this.refuseWithoutStepUp('createPrincipal');
const principal: PrincipalRecord = {
principalId: `principal-${this.principals.length + 1}`,
name: options.name,
ownerId: 'user-dev@example.com',
isReadOnly: options.isReadOnly ?? false,
bypassStepUp: options.bypassStepUp ?? false,
useAdminOwner: options.useAdminOwner ?? true,
entityIds: [options.orgId],
scopes: [],
};
this.principals.push(principal);
return principal.principalId;
},
deletePrincipal: async (principalId: string) => {
this.calls.push({ operation: `deletePrincipal:${principalId}`, token });
this.principals = this.principals.filter(
(principal) => principal.principalId !== principalId
);
},
});

/** Mimics the server's `STEP_UP_REQUIRED_*` exceptions. */
Expand Down Expand Up @@ -469,6 +498,80 @@ describe('linked one-time codes', () => {
});
});

describe('principals', () => {
const signIn = () =>
accounts.signIn({
endpoint: ENDPOINT,
email: 'dev@example.com',
password: 'hunter22',
});

it('creates a scoped sub-identity and mints a key as it', async () => {
const account = await signIn();
const principalId = await accounts.createPrincipal(account.itemId, {
name: 'ci-deploy',
orgId: 'org-1',
isReadOnly: true,
bypassStepUp: true,
});

const principals = await accounts.listPrincipals(account.itemId);
expect(principals).toHaveLength(1);
expect(principals[0]).toMatchObject({
principalId,
name: 'ci-deploy',
isReadOnly: true,
bypassStepUp: true,
entityIds: ['org-1'],
});

const key = await accounts.createApiKey(account.itemId, {
name: 'ci',
principalId,
orgId: 'org-1',
});
expect(key.principalId).toBe(principalId);
expect(key.orgId).toBe('org-1');
expect((await accounts.listApiKeys())[0].principalId).toBe(principalId);
});

it('answers a step-up when creating one, like every other sensitive call', async () => {
const account = await signIn();
server.demandStepUp = 'password';

await expect(
accounts.createPrincipal(account.itemId, { name: 'ci', orgId: 'org-1' })
).rejects.toBeInstanceOf(StepUpRequiredError);

const principalId = await accounts.createPrincipal(
account.itemId,
{ name: 'ci', orgId: 'org-1' },
{ password: 'hunter22' }
);
expect(principalId).toBe('principal-1');
});

it('deletes one server-side', async () => {
const account = await signIn();
const principalId = await accounts.createPrincipal(account.itemId, {
name: 'ci',
orgId: 'org-1',
});

await accounts.deletePrincipal(account.itemId, principalId);
expect(await accounts.listPrincipals(account.itemId)).toHaveLength(0);
});

it('refuses to reach the server when the account is signed out', async () => {
const account = await signIn();
await accounts.signOut(account.itemId);

await expect(accounts.listPrincipals(account.itemId)).rejects.toThrow(
'signed out'
);
});
});

describe('hasExpired', () => {
const now = new Date('2026-01-01T00:00:00.000Z');

Expand Down
160 changes: 160 additions & 0 deletions packages/accounts/__tests__/credentials.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { Vault } from '@decryption/vault';
import { promises as fs } from 'fs';
import * as os from 'os';
import * as path from 'path';

import {
AccountManager,
AuthClient,
AuthClientFactory,
VaultCredentials,
} from '../src';

jest.setTimeout(120000);

const MODULE_PATH = path.resolve(__dirname, '../../../pgpm-modules/dcrypt-vault');
const FAST = { t: 1, m: 8192, p: 1 };
const PASSPHRASE = 'a rather long master passphrase';
const ENDPOINT = 'http://auth.localhost:3000/graphql';

let nextKey = 0;

const factory: AuthClientFactory = (): AuthClient => ({
signIn: async ({ email }) => ({
userId: `user-${email}`,
accessToken: `token-${email}`,
accessTokenExpiresAt: null,
}),
signUp: async ({ email }) => ({
userId: `user-${email}`,
accessToken: `token-${email}`,
accessTokenExpiresAt: null,
}),
signOut: async () => {},
verifyPassword: async () => {},
verifyTotp: async () => {},
createApiKey: async (options) => {
nextKey += 1;
return {
apiKey: `cnc_live_sk_${options.name}`,
keyId: `key-${nextKey}`,
expiresAt: null,
};
},
revokeApiKey: async () => {},
listPrincipals: async () => [],
createPrincipal: async () => 'principal-1',
deletePrincipal: async () => {},
});

let dir: string;
let vault: Vault;
let accounts: AccountManager;

const signIn = (email: string) =>
accounts.signIn({ endpoint: ENDPOINT, email, password: 'hunter22' });

beforeAll(async () => {
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dcrypt-credentials-'));
vault = await Vault.open({
file: path.join(dir, 'vault.dcrypt'),
passphrase: PASSPHRASE,
modulePath: MODULE_PATH,
kdf: FAST,
});
});

afterAll(async () => {
await vault.discard();
await fs.rm(dir, { recursive: true, force: true });
});

beforeEach(async () => {
for (const kind of ['account', 'api_key'] as const) {
for (const item of await vault.listItems({ kind })) {
await vault.deleteItemForever(item.id);
}
}
accounts = new AccountManager(vault, { createClient: factory });
});

describe('VaultCredentials', () => {
it('serves the bearer of the one signed-in account', async () => {
await signIn('dev@example.com');
const credentials = new VaultCredentials(accounts);
expect(await credentials.accountBearer()).toBe('token-dev@example.com');
});

it('serves nothing rather than guess when several accounts are signed in', async () => {
await signIn('dev@example.com');
await signIn('ops@example.com');

expect(await new VaultCredentials(accounts).accountBearer()).toBeNull();
});

it('serves the named account even when several are signed in', async () => {
const dev = await signIn('dev@example.com');
await signIn('ops@example.com');

const credentials = new VaultCredentials(accounts, { accountItemId: dev.itemId });
expect(await credentials.accountBearer()).toBe('token-dev@example.com');
});

it('serves nothing once the account is signed out', async () => {
const account = await signIn('dev@example.com');
const credentials = new VaultCredentials(accounts, {
accountItemId: account.itemId,
});

await accounts.signOut(account.itemId);
expect(await credentials.accountBearer()).toBeNull();
});

it('hands over the key tagged for a database, and nothing else', async () => {
const account = await signIn('dev@example.com');
await accounts.createApiKey(account.itemId, {
name: 'app-data',
databaseId: 'db-1',
});
await accounts.createApiKey(account.itemId, { name: 'unrelated' });

const credentials = new VaultCredentials(accounts);
expect(await credentials.dataToken('db-1')).toEqual({
token: 'cnc_live_sk_app-data',
origin: 'vault',
});
expect(await credentials.dataToken('db-2')).toEqual({ token: null });
});

it('tags a key that already exists', async () => {
const account = await signIn('dev@example.com');
const key = await accounts.createApiKey(account.itemId, { name: 'ci' });
expect(key.databaseId).toBeNull();

await accounts.assignKeyToDatabase(key.itemId, 'db-9');

const credentials = new VaultCredentials(accounts);
expect((await credentials.dataToken('db-9')).token).toBe('cnc_live_sk_ci');
expect((await accounts.listApiKeys())[0].databaseId).toBe('db-9');
});

it('serves a data token from a signed-out account, because a key is its own credential', async () => {
const account = await signIn('dev@example.com');
await accounts.createApiKey(account.itemId, { name: 'ci', databaseId: 'db-1' });
await accounts.signOut(account.itemId);

const credentials = new VaultCredentials(accounts);
expect((await credentials.dataToken('db-1')).token).toBe('cnc_live_sk_ci');
expect(await credentials.accountBearer()).toBeNull();
});

it('refuses when two keys claim the same database', async () => {
const account = await signIn('dev@example.com');
await accounts.createApiKey(account.itemId, { name: 'one', databaseId: 'db-1' });
await accounts.createApiKey(account.itemId, { name: 'two', databaseId: 'db-1' });

expect(await new VaultCredentials(accounts).dataToken('db-1')).toEqual({
token: null,
});
});
});
Loading
Loading