Files
waggle-os/packages/agent/tests/helpers/memory-secret-store.ts

73 lines
2.8 KiB
TypeScript

import { vi, type Mock } from 'vitest';
import type { SecretEntry, SecretStore } from '@waggle/core';
import {
setConnectorCredential,
type ConnectorCredentialInput,
} from '../../src/connectors/connector-credentials.js';
export type MockSecretStore = { [K in keyof SecretStore]: Mock<SecretStore[K]> };
/** An expiry in the past, for credentials that should read as expired. */
export const EXPIRED_AT = '2020-01-01T00:00:00.000Z';
/** A seed credential from the `{ value, isExpired }` shape the connector tests use. */
export function seedCredential(
cred: { value: string; isExpired: boolean },
type: ConnectorCredentialInput['type'] = 'bearer',
): ConnectorCredentialInput {
return { type, value: cred.value, expiresAt: cred.isExpired ? EXPIRED_AT : undefined };
}
export interface SecretStoreSeed {
/** Connector credentials by connector id, stored with setConnectorCredential. */
connectors?: Record<string, ConnectorCredentialInput>;
/** Plain secrets by name, such as `connector:jira:email`. */
secrets?: Record<string, string>;
}
/**
* A Map-backed SecretStore for connector tests. Every method is a vitest spy.
* The seed is written before the spies exist, so it does not show up in their calls.
*/
export function createMemorySecretStore(seed: SecretStoreSeed = {}): MockSecretStore {
const store = createPlainSecretStore(seed);
return {
get: vi.fn(store.get),
set: vi.fn(store.set),
setAsync: vi.fn(store.setAsync),
writeBatch: vi.fn(store.writeBatch),
delete: vi.fn(store.delete),
deleteAsync: vi.fn(store.deleteAsync),
list: vi.fn(store.list),
has: vi.fn(store.has),
};
}
/** The same Map-backed store without spies, for timing tests. */
export function createPlainSecretStore(seed: SecretStoreSeed = {}): SecretStore {
const entries = new Map<string, SecretEntry>();
const store: SecretStore = {
get: name => entries.get(name) ?? null,
set: (name, value, metadata) => {
entries.set(name, { name, value, metadata, updatedAt: new Date().toISOString() });
},
setAsync: async (name, value, metadata) => store.set(name, value, metadata),
writeBatch: (batch) => {
for (const name of batch.delete ?? []) entries.delete(name);
for (const { name, value, metadata } of batch.set ?? []) store.set(name, value, metadata);
},
delete: name => entries.delete(name),
deleteAsync: async name => store.delete(name),
list: () => [...entries.values()].map(({ name, metadata, updatedAt }) => ({ name, metadata, updatedAt })),
has: name => entries.has(name),
};
for (const [connectorId, credential] of Object.entries(seed.connectors ?? {})) {
setConnectorCredential(store, connectorId, credential);
}
for (const [name, value] of Object.entries(seed.secrets ?? {})) {
store.set(name, value);
}
return store;
}