mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
refactor(plugins): outbound OAuth tokens and per-user plugin settings through repositories
This commit is contained in:
@@ -16,9 +16,11 @@ vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
});
|
||||
|
||||
const { getDb } = vi.hoisted(() => ({ getDb: { current: null as unknown } }));
|
||||
// The mock stays even though nothing in this file imports `db` directly any more
|
||||
// (the service dropped its last raw-connection use) — a transitive importer of
|
||||
// `src/db/database` elsewhere in the module graph would otherwise try to open a
|
||||
// real connection at import time.
|
||||
vi.mock('../../../src/db/database', () => ({ get db() { return getDb.current; } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
// The token POST now runs through the SSRF guard (ssrfGuard.safeFetchLlm), which
|
||||
// resolves the host before fetching. Stub DNS so the fake provider.example host
|
||||
@@ -31,6 +33,11 @@ vi.mock('node:dns/promises', () => {
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
|
||||
const CFG = {
|
||||
oauth_authorize_url: 'https://provider.example/authorize',
|
||||
@@ -44,7 +51,7 @@ function freshDb(cfg: Record<string, unknown> = CFG) {
|
||||
const d = new Database(':memory:');
|
||||
d.exec(`
|
||||
CREATE TABLE plugins (id TEXT PRIMARY KEY, config TEXT, status TEXT);
|
||||
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT);
|
||||
CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT);
|
||||
CREATE TABLE plugin_oauth_tokens (plugin_id TEXT, user_id INTEGER, access_token TEXT, refresh_token TEXT, expires_at INTEGER, scope TEXT, updated_at TEXT, PRIMARY KEY (plugin_id, user_id));
|
||||
CREATE TABLE plugin_oauth_state (state TEXT PRIMARY KEY, plugin_id TEXT, user_id INTEGER, verifier TEXT, created_at INTEGER);
|
||||
`);
|
||||
@@ -54,14 +61,25 @@ function freshDb(cfg: Record<string, unknown> = CFG) {
|
||||
|
||||
const NOW = 1_700_000_000_000;
|
||||
|
||||
/**
|
||||
* `PluginOAuthService`, built with real repositories over whichever fresh
|
||||
* `getDb.current` the caller just set — `sharedTestOrm` is memoized per db HANDLE,
|
||||
* and every test below assigns a brand-new `:memory:` db, so each call here gets
|
||||
* its own ORM, matching the pattern `plugin-user-settings.test.ts` established.
|
||||
*/
|
||||
async function makeOauthService(): Promise<PluginOAuthService> {
|
||||
const orm = await sharedTestOrm(getDb.current as Database.Database);
|
||||
return new PluginOAuthService(orm.repo(Plugins), orm.repo(PluginOauthTokens), orm.repo(PluginOauthState), orm.repo(PluginSettingsFields));
|
||||
}
|
||||
|
||||
describe('PluginOAuthService', () => {
|
||||
let svc: PluginOAuthService;
|
||||
beforeEach(() => { getDb.current = freshDb(); svc = new PluginOAuthService(new DatabaseService(dbConn)); vi.restoreAllMocks(); dnsState.address = '93.184.216.34'; dnsState.family = 4; });
|
||||
beforeEach(async () => { getDb.current = freshDb(); svc = await makeOauthService(); vi.restoreAllMocks(); dnsState.address = '93.184.216.34'; dnsState.family = 4; });
|
||||
|
||||
it('providerConfig returns null unless every piece is present, decrypting the secrets', async () => {
|
||||
expect(await svc.providerConfig('p')).toMatchObject({ clientId: 'client-123', clientSecret: 'secret-abc', scopes: 'read write' });
|
||||
getDb.current = freshDb({ ...CFG, oauth_client_secret: '' });
|
||||
expect(await new PluginOAuthService(new DatabaseService(dbConn)).providerConfig('p')).toBeNull();
|
||||
expect(await (await makeOauthService()).providerConfig('p')).toBeNull();
|
||||
});
|
||||
|
||||
it('providerConfig falls back to the manifest defaults for the endpoints the admin left unset', async () => {
|
||||
@@ -74,7 +92,7 @@ describe('PluginOAuthService', () => {
|
||||
ins.run('oauth_authorize_url', JSON.stringify('https://provider.example/authorize'));
|
||||
ins.run('oauth_token_url', JSON.stringify('https://provider.example/token'));
|
||||
ins.run('oauth_scopes', JSON.stringify('read'));
|
||||
svc = new PluginOAuthService(new DatabaseService(dbConn));
|
||||
svc = (await makeOauthService());
|
||||
expect(await svc.providerConfig('p')).toEqual({
|
||||
authorizeUrl: 'https://provider.example/authorize',
|
||||
tokenUrl: 'https://provider.example/token',
|
||||
@@ -102,18 +120,18 @@ describe('PluginOAuthService', () => {
|
||||
|
||||
it('rejects a non-https / loopback / metadata / internal authorize endpoint', async () => {
|
||||
getDb.current = freshDb({ ...CFG, oauth_authorize_url: 'http://provider.example/authorize' });
|
||||
await expect(new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).rejects.toThrow(/https/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/https/);
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://127.0.0.1/token' });
|
||||
await expect(new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|private/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|private/);
|
||||
// IPv6-literal loopback must not slip past the fast-fail
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://[::1]/token' });
|
||||
await expect(new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).rejects.toThrow(/loopback/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback/);
|
||||
// cloud-metadata by literal is refused too
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://169.254.169.254/token' });
|
||||
await expect(new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|metadata/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|metadata/);
|
||||
// an internal name suffix is refused
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://idp.internal/token' });
|
||||
await expect(new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).rejects.toThrow(/local/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/local/);
|
||||
});
|
||||
|
||||
it('completeCallback verifies state (single-use, user-bound, TTL), exchanges the code, encrypts tokens', async () => {
|
||||
@@ -180,4 +198,55 @@ describe('PluginOAuthService', () => {
|
||||
await svc.disconnect('p', 42);
|
||||
expect((await svc.status('p', 42)).connected).toBe(false);
|
||||
});
|
||||
|
||||
/**
|
||||
* PO5+PO6+PO7 — single-use is enforced by `consumeByState`'s ONE atomic
|
||||
* delete, on EVERY path out of `completeCallback`: the expired/foreign-state
|
||||
* refusal and the success path both leave the row gone, not just the
|
||||
* success one.
|
||||
*/
|
||||
it('single-use: the state row is gone after EITHER the refused path or the success path', async () => {
|
||||
const rows = getDb.current as unknown as InstanceType<typeof Database>;
|
||||
|
||||
// Refused path: wrong user — the row is still consumed.
|
||||
const stateA = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateA)).toBeTruthy();
|
||||
await expect(svc.completeCallback('p', 99, 'code', stateA, NOW + 1000)).rejects.toThrow(/state/);
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateA)).toBeUndefined();
|
||||
|
||||
// Success path.
|
||||
const stateB = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ access_token: 'AT' }) } as Response);
|
||||
await svc.completeCallback('p', 42, 'code', stateB, NOW + 1000);
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateB)).toBeUndefined();
|
||||
});
|
||||
|
||||
/**
|
||||
* R-oauth-upsert's TRAP: the state consume is a check-then-act primitive.
|
||||
* `consumeByState`'s atomic `DELETE ... RETURNING` (PluginOauthState.repository.ts)
|
||||
* exists specifically so two concurrent `completeCallback` calls for the SAME
|
||||
* state cannot both see a live row — racing them here is the proof, matching
|
||||
* the legacy synchronous-JS outcome (exactly one consumer wins, the token
|
||||
* exchange fires exactly once).
|
||||
*/
|
||||
it('the state consume race: two concurrent completeCallback calls for the SAME state — exactly one wins', async () => {
|
||||
const state = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600 }),
|
||||
} as Response);
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
svc.completeCallback('p', 42, 'code', state, NOW + 1000),
|
||||
svc.completeCallback('p', 42, 'code', state, NOW + 1000),
|
||||
]);
|
||||
const fulfilled = results.filter((r) => r.status === 'fulfilled');
|
||||
const rejected = results.filter((r) => r.status === 'rejected');
|
||||
expect(fulfilled).toHaveLength(1); // exactly one consumer wins the state
|
||||
expect(rejected).toHaveLength(1);
|
||||
expect((rejected[0] as PromiseRejectedResult).reason as Error).toMatchObject({ message: expect.stringMatching(/state/) });
|
||||
// The token exchange fired exactly once — the loser never reached it.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const rows = getDb.current as unknown as InstanceType<typeof Database>;
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(state)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,7 +64,7 @@ async function buildRuntime(withOrm: boolean): Promise<PluginRuntimeService> {
|
||||
const dbs = new DatabaseService(testDb);
|
||||
const audit = new AuditService(t.repo(AuditLog), t.repo(Users));
|
||||
const addons = await createTestAddonsService(testDb, dbs);
|
||||
const userSettings = new PluginUserSettingsService(dbs);
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
return new PluginRuntimeService(
|
||||
dbs,
|
||||
audit,
|
||||
|
||||
@@ -46,8 +46,15 @@ async function makePluginsService(dbs: DatabaseService): Promise<PluginsService>
|
||||
orm.repo(PluginCapabilityAudit),
|
||||
);
|
||||
}
|
||||
/** The host-side settings reads, over the same connection the test seeded. */
|
||||
const userSettings = () => new PluginUserSettingsService(new DatabaseService(dbConn));
|
||||
/**
|
||||
* The host-side settings reads, over the same connection the test seeded — a fresh
|
||||
* `orm` per test (`sharedTestOrm` is memoized per db HANDLE, and `beforeEach` swaps
|
||||
* `getDb.current` to a brand-new `:memory:` db every time, same as `makePluginsService`).
|
||||
*/
|
||||
async function userSettings(): Promise<PluginUserSettingsService> {
|
||||
const orm = await sharedTestOrm(getDb.current as Database.Database);
|
||||
return new PluginUserSettingsService(orm.repo(PluginSettingsFields), orm.repo(PluginUserConfig));
|
||||
}
|
||||
|
||||
function freshDb() {
|
||||
const d = new Database(':memory:');
|
||||
@@ -84,14 +91,14 @@ describe('per-user plugin settings', () => {
|
||||
expect(masked.apiKey).toBe('••••••••'); // never echoed
|
||||
expect(masked.units).toBe('metric');
|
||||
// decrypted runtime read returns the real value; the stored form is ciphertext
|
||||
expect(await userSettings().readOne('p', 42, 'apiKey')).toBe('sk-123');
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBe('sk-123');
|
||||
expect((await svc.getUserConfig('p', 42)).apiKey).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('an unchanged secret (the mask) keeps the stored ciphertext', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
await svc.updateUserConfig('p', 42, { apiKey: '••••••••', units: 'imperial' }); // mask = untouched
|
||||
expect(await userSettings().readOne('p', 42, 'apiKey')).toBe('sk-123'); // still the original
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBe('sk-123'); // still the original
|
||||
expect((await svc.getUserConfig('p', 42)).units).toBe('imperial');
|
||||
});
|
||||
|
||||
@@ -110,7 +117,7 @@ describe('per-user plugin settings', () => {
|
||||
// test is that user 99 sees none of user 42's values.
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', units: 'metric' });
|
||||
expect((await svc.getUserConfig('p', 99)).units).toBeUndefined();
|
||||
expect(await userSettings().readOne('p', 99, 'apiKey')).toBeUndefined();
|
||||
expect(await (await userSettings()).readOne('p', 99, 'apiKey')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -132,28 +139,28 @@ describe('manifest defaults reach the runtime reads', () => {
|
||||
});
|
||||
|
||||
it('readOne falls back to the declared default when nothing is stored', async () => {
|
||||
expect(await userSettings().readOne('p', 42, 'region')).toBe('eu');
|
||||
expect(await userSettings().readOne('p', 42, 'retries')).toBe(3); // JSON round-trip keeps the type
|
||||
expect(await userSettings().readOne('p', 42, 'apiKey')).toBeUndefined(); // no default declared
|
||||
expect(await (await userSettings()).readOne('p', 42, 'region')).toBe('eu');
|
||||
expect(await (await userSettings()).readOne('p', 42, 'retries')).toBe(3); // JSON round-trip keeps the type
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBeUndefined(); // no default declared
|
||||
});
|
||||
|
||||
it('a stored value wins over the default', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(await userSettings().readOne('p', 42, 'region')).toBe('us');
|
||||
expect(await userSettings().readOne('p', 99, 'region')).toBe('eu'); // another user still gets the default
|
||||
expect(await (await userSettings()).readOne('p', 42, 'region')).toBe('us');
|
||||
expect(await (await userSettings()).readOne('p', 99, 'region')).toBe('eu'); // another user still gets the default
|
||||
});
|
||||
|
||||
it('readAll folds defaults in for the fields the user left unset', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(await userSettings().readAll('p', 42)).toMatchObject({ apiKey: 'sk-123', region: 'us', retries: 3, endpoint: 'https://api.example' });
|
||||
expect(await (await userSettings()).readAll('p', 42)).toMatchObject({ apiKey: 'sk-123', region: 'us', retries: 3, endpoint: 'https://api.example' });
|
||||
});
|
||||
|
||||
it('hasRequired treats a required field with a default as filled', async () => {
|
||||
// apiKey is required with no default → not configured until stored.
|
||||
expect(await userSettings().hasRequired('p', 42)).toBe(false);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(false);
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
// endpoint is required too, but its default satisfies it.
|
||||
expect(await userSettings().hasRequired('p', 42)).toBe(true);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -173,13 +180,13 @@ describe('hasRequired applies the same "filled" rule as the save gate', () => {
|
||||
|
||||
it('exempts a required checkbox (consent, not a settings field)', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' }); // consent never set
|
||||
expect(await userSettings().hasRequired('p', 42)).toBe(true);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(true);
|
||||
});
|
||||
|
||||
it('treats a whitespace-only value as empty', async () => {
|
||||
(getDb.current as import('better-sqlite3').Database)
|
||||
.prepare("INSERT INTO plugin_user_config (plugin_id, user_id, config, updated_at) VALUES ('p', 42, ?, '')")
|
||||
.run(JSON.stringify({ apiKey: ' ', consent: true }));
|
||||
expect(await userSettings().hasRequired('p', 42)).toBe(false);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -46,8 +46,15 @@ import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrati
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
/** The host-side settings reads, over the same connection the test seeded. */
|
||||
const userSettings = () => new PluginUserSettingsService(new DatabaseService(dbConn));
|
||||
/**
|
||||
* The host-side settings reads, over the same connection the test seeded. `t` is
|
||||
* initialized in `beforeAll` (below) before any test runs — this reaches for
|
||||
* `PluginSettingsFieldsRepository`/`PluginUserConfigRepository` through it, matching
|
||||
* PSET-007's own `PluginRuntimeService` construction further down, which reuses the
|
||||
* SAME `t` rather than a second ORM over the same connection.
|
||||
*/
|
||||
const userSettings = () =>
|
||||
new PluginUserSettingsService((t as TestOrm).repo(PluginSettingsFields), (t as TestOrm).repo(PluginUserConfig));
|
||||
|
||||
let uid: number;
|
||||
let t: TestOrm | undefined;
|
||||
@@ -66,7 +73,14 @@ function setUserConfig(pluginId: string, config: Record<string, unknown>) {
|
||||
testDb.prepare('INSERT OR REPLACE INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(pluginId, uid, JSON.stringify(config));
|
||||
}
|
||||
|
||||
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
|
||||
beforeAll(async () => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
// Plan 3j Task 4 — `userSettings()` above now needs repositories, so the ORM this
|
||||
// file eventually built only inside PSET-007 is built here instead, before any
|
||||
// test runs (PSET-001..006 call `userSettings()` with no ORM of their own).
|
||||
t = await createTestOrm(dbConn);
|
||||
});
|
||||
beforeEach(() => {
|
||||
testDb.prepare('DELETE FROM plugin_settings_fields').run();
|
||||
testDb.prepare('DELETE FROM plugin_user_config').run();
|
||||
@@ -149,7 +163,6 @@ describe('a plugin channel label is bounded by the host', () => {
|
||||
VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
|
||||
).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
|
||||
|
||||
t = await createTestOrm(dbConn);
|
||||
const rt = new PluginRuntimeService(
|
||||
new DatabaseService(dbConn),
|
||||
new AuditService(t.repo(AuditLog), t.repo(Users)),
|
||||
|
||||
Reference in New Issue
Block a user