Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399import request from 'supertest';import type { TestContext } from './helpers';import { closeTestApp, createTestApp } from './helpers';
// The auth gate, end-to-end. Unlike the other suites, this one enables auth// ({ auth: true }) and drives bootstrap → login → protected access → logout.describe('Auth gate', () => { let ctx: TestContext; let http: ReturnType<typeof request>;
beforeAll(async () => { ctx = await createTestApp({ auth: true }); http = request(ctx.app.getHttpServer()); }); afterAll(() => closeTestApp(ctx));
it('reports unconfigured before any account exists', async () => { const res = await http.get('/api/auth/status').expect(200); expect(res.body.configured).toBe(false); expect(res.body.authDisabled).toBe(false); expect(res.body.providers).toEqual([{ name: 'local', label: 'Password', kind: 'credentials' }]); });
it('protects the API with 401 until authenticated', async () => { await http.get('/api/sync/manifest').expect(401); });
it('rejects a too-short bootstrap password with 400', async () => { await http .post('/api/auth/register') .send({ username: 'admin', password: 'short' }) .expect(400); });
it('bootstraps the first admin, sets a session cookie, and unlocks the API', async () => { const agent = request.agent(ctx.app.getHttpServer()); const reg = await agent .post('/api/auth/register') .send({ username: 'admin', password: 'correct horse battery' }) .expect(201); expect(reg.body.user).toMatchObject({ username: 'admin', role: 'admin', provider: 'local' }); expect(reg.body.user).not.toHaveProperty('password_hash'); // Session cookie is HttpOnly and signed. const setCookie = reg.headers['set-cookie'][0]; expect(setCookie).toMatch(/revision_session=/); expect(setCookie).toMatch(/HttpOnly/i);
// The same agent (carrying the cookie) can now read a protected route. await agent.get('/api/sync/manifest').expect(200);
// status now reports configured. const status = await agent.get('/api/auth/status').expect(200); expect(status.body.configured).toBe(true); });
it('refuses a second registration once an account exists', async () => { await http .post('/api/auth/register') .send({ username: 'intruder', password: 'another good one' }) .expect(409); });
it('rejects a wrong password with 401', async () => { await http .post('/api/auth/login') .send({ username: 'admin', password: 'wrong password here' }) .expect(401); });
it('logs in with correct credentials and returns the user', async () => { const agent = request.agent(ctx.app.getHttpServer()); const res = await agent .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); expect(res.body.user.username).toBe('admin'); await agent.get('/api/sync/manifest').expect(200); const me = await agent.get('/api/auth/me').expect(200); expect(me.body.user.username).toBe('admin'); });
it('returns an opaque token usable as a bearer header, without cookies', async () => { const res = await http .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); const token = res.body.token as string; expect(typeof token).toBe('string'); expect(token.length).toBeGreaterThan(20);
await http.get('/api/sync/manifest').set('Authorization', `Bearer ${token}`).expect(200); const me = await http.get('/api/auth/me').set('Authorization', `Bearer ${token}`).expect(200); expect(me.body.user.username).toBe('admin'); });
it('rejects a bogus bearer token with 401', async () => { await http.get('/api/sync/manifest').set('Authorization', 'Bearer not-a-session').expect(401); });
it('destroys the session behind a bearer token on logout', async () => { const res = await http .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); const token = res.body.token as string; await http.post('/api/auth/logout').set('Authorization', `Bearer ${token}`).expect(204); await http.get('/api/sync/manifest').set('Authorization', `Bearer ${token}`).expect(401); });
it('logout clears the session so protected routes 401 again', async () => { const agent = request.agent(ctx.app.getHttpServer()); await agent .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); await agent.get('/api/sync/manifest').expect(200); await agent.post('/api/auth/logout').expect(204); await agent.get('/api/sync/manifest').expect(401); const me = await agent.get('/api/auth/me').expect(200); expect(me.body.user).toBeNull(); });
it('does not enumerate users via login timing/response', async () => { // A missing user and a wrong password both give the same 401 shape. const missing = await http .post('/api/auth/login') .send({ username: 'ghost', password: 'whatever value' }) .expect(401); const wrong = await http .post('/api/auth/login') .send({ username: 'admin', password: 'definitely wrong' }) .expect(401); expect(missing.body).toEqual(wrong.body); });
// Self-signup from the login screen: an operator opt-in, closed by default. describe('self-signup (AUTH_ALLOW_SIGNUP)', () => { afterEach(() => { delete process.env.AUTH_ALLOW_SIGNUP; });
it('is closed when the flag is off and advertised as such', async () => { // Pin the flag: the dev .env may enable it, tests must not inherit that. process.env.AUTH_ALLOW_SIGNUP = 'false'; const status = await http.get('/api/auth/status').expect(200); expect(status.body.allowSignup).toBe(false); await http .post('/api/auth/signup') .send({ username: 'walkin', password: 'walkin passphrase' }) .expect(403); });
it('creates a user-role account and signs it in when enabled', async () => { process.env.AUTH_ALLOW_SIGNUP = 'true'; const status = await http.get('/api/auth/status').expect(200); expect(status.body.allowSignup).toBe(true);
const agent = request.agent(ctx.app.getHttpServer()); const res = await agent .post('/api/auth/signup') .send({ username: 'walkin', password: 'walkin passphrase' }) .expect(201); expect(res.body.user).toMatchObject({ username: 'walkin', role: 'user', provider: 'local' }); await agent.get('/api/sync/manifest').expect(200);
// Duplicates and short passwords are refused like everywhere else. await http .post('/api/auth/signup') .send({ username: 'walkin', password: 'another long pw' }) .expect(409); await http.post('/api/auth/signup').send({ username: 'w2', password: 'short' }).expect(400); }); });
// Admin-only user management + global settings. Runs before the password // block so the admin still signs in with the bootstrap credentials. describe('user management (admin)', () => { const asAdmin = () => { const agent = request.agent(ctx.app.getHttpServer()); return agent .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200) .then(() => agent); };
it('requires a session for the users endpoints', async () => { await http.get('/api/auth/users').expect(401); await http .post('/api/auth/users') .send({ username: 'x', password: 'long enough pw' }) .expect(401); });
it('lets the admin create an account (default role: user) and list it', async () => { const admin = await asAdmin(); const res = await admin .post('/api/auth/users') .send({ username: 'reader', password: 'reader passphrase' }) .expect(201); expect(res.body.user).toMatchObject({ username: 'reader', role: 'user', provider: 'local' }); expect(res.body.user).not.toHaveProperty('password_hash');
const list = await admin.get('/api/auth/users').expect(200); const names = list.body.users.map((u: { username: string }) => u.username); expect(names).toEqual(expect.arrayContaining(['admin', 'reader']));
// The new account can sign in. await http .post('/api/auth/login') .send({ username: 'reader', password: 'reader passphrase' }) .expect(200); });
it('rejects a duplicate username with 409 and a short password with 400', async () => { const admin = await asAdmin(); await admin .post('/api/auth/users') .send({ username: 'reader', password: 'another long one' }) .expect(409); await admin.post('/api/auth/users').send({ username: 'zed', password: 'short' }).expect(400); });
it('refuses user management and global AI settings to non-admins', async () => { const reader = request.agent(ctx.app.getHttpServer()); await reader .post('/api/auth/login') .send({ username: 'reader', password: 'reader passphrase' }) .expect(200);
await reader.get('/api/auth/users').expect(403); await reader .post('/api/auth/users') .send({ username: 'smuggled', password: 'long enough pw' }) .expect(403);
// Global AI settings: readable by anyone signed in, writable by admins. await reader.get('/api/settings/ai').expect(200); await reader.put('/api/settings/ai').send({ provider: 'claude', model: 'x' }).expect(403);
const admin = await asAdmin(); await admin.put('/api/settings/ai').send({ provider: 'claude', model: 'x' }).expect(200);
// Nor can a non-admin reset someone else's password. await reader .post('/api/auth/users/00000000-0000-4000-8000-000000000000/password') .send({ password: 'long enough pw' }) .expect(403); });
it('lets the admin change a role, but never their own', async () => { const admin = await asAdmin(); const list = await admin.get('/api/auth/users').expect(200); const byName = (n: string) => list.body.users.find((u: { username: string }) => u.username === n);
// Promote, verify the target can now use admin routes, then demote. await admin .put(`/api/auth/users/${byName('reader').id}/role`) .send({ role: 'admin' }) .expect(200); const readerAgent = request.agent(ctx.app.getHttpServer()); await readerAgent .post('/api/auth/login') .send({ username: 'reader', password: 'reader passphrase' }) .expect(200); await readerAgent.get('/api/auth/users').expect(200); await admin .put(`/api/auth/users/${byName('reader').id}/role`) .send({ role: 'user' }) .expect(200);
// Lockout guard: own role is untouchable; bad input and ghosts refused. await admin .put(`/api/auth/users/${byName('admin').id}/role`) .send({ role: 'user' }) .expect(400); await admin .put('/api/auth/users/00000000-0000-4000-8000-000000000000/role') .send({ role: 'admin' }) .expect(404); await admin .put(`/api/auth/users/${byName('reader').id}/role`) .send({ role: 'root' }) .expect(400); });
it('lets the admin reset another account’s password, revoking its sessions', async () => { const admin = await asAdmin(); const list = await admin.get('/api/auth/users').expect(200); const reader = list.body.users.find((u: { username: string }) => u.username === 'reader');
// The target is signed in; the reset must kick that session out. const readerAgent = request.agent(ctx.app.getHttpServer()); await readerAgent .post('/api/auth/login') .send({ username: 'reader', password: 'reader passphrase' }) .expect(200);
await admin .post(`/api/auth/users/${reader.id}/password`) .send({ password: 'short' }) .expect(400); await admin .post('/api/auth/users/00000000-0000-4000-8000-000000000000/password') .send({ password: 'long enough pw' }) .expect(404); await admin .post(`/api/auth/users/${reader.id}/password`) .send({ password: 'freshly reset pw' }) .expect(200);
await readerAgent.get('/api/sync/manifest').expect(401); await http .post('/api/auth/login') .send({ username: 'reader', password: 'reader passphrase' }) .expect(401); await http .post('/api/auth/login') .send({ username: 'reader', password: 'freshly reset pw' }) .expect(200); }); });
// Password change + recovery. These run last: they rotate the admin // password, so every earlier test still sees the bootstrap credentials. describe('passwords', () => { it('requires a session to change the password', async () => { await http .post('/api/auth/password') .send({ currentPassword: 'correct horse battery', newPassword: 'irrelevant here!' }) .expect(401); });
it('rejects a wrong current password with 401 and a short new one with 400', async () => { const agent = request.agent(ctx.app.getHttpServer()); await agent .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); await agent .post('/api/auth/password') .send({ currentPassword: 'not my password', newPassword: 'long enough though' }) .expect(401); await agent .post('/api/auth/password') .send({ currentPassword: 'correct horse battery', newPassword: 'short' }) .expect(400); });
it('changes the password, revokes other sessions, and keeps the caller signed in', async () => { const changer = request.agent(ctx.app.getHttpServer()); const other = request.agent(ctx.app.getHttpServer()); for (const agent of [changer, other]) { await agent .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(200); }
await changer .post('/api/auth/password') .send({ currentPassword: 'correct horse battery', newPassword: 'brand new passphrase' }) .expect(200);
// The caller got a fresh session cookie; the other session is dead. await changer.get('/api/sync/manifest').expect(200); await other.get('/api/sync/manifest').expect(401);
// Old credentials are gone, the new ones work. await http .post('/api/auth/login') .send({ username: 'admin', password: 'correct horse battery' }) .expect(401); await http .post('/api/auth/login') .send({ username: 'admin', password: 'brand new passphrase' }) .expect(200); });
it('AUTH_RESET_PASSWORD resets a local account (operator recovery)', async () => { // Exercise the same code path the boot hook runs, against this app's DB. const { AuthService } = await import('../src/auth/auth.service'); const auth = ctx.app.get(AuthService);
expect(await auth.resetPasswordFromEnv(undefined)).toBeNull(); expect(await auth.resetPasswordFromEnv('ghost:whatever value')).toBeNull(); expect(await auth.resetPasswordFromEnv('admin:short')).toBeNull();
const userId = await auth.resetPasswordFromEnv('admin:recovered passphrase'); expect(userId).not.toBeNull(); await http .post('/api/auth/login') .send({ username: 'admin', password: 'recovered passphrase' }) .expect(200); }); });});