mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
feat(journey): protect a public journey link with a password and an expiry
A journey's share link can now ask readers for a password, stop working on a date its owner picks, and count how often it was opened (#2553, #1702, no password, no expiry and no views. - journey_share_tokens gains password_hash, password_version, expires_at, view_count and last_viewed_at (append-only migration, SQLite and Postgres, added only where missing). - The password is hashed with bcrypt at the account cost. POST /api/public/journey/:token/unlock checks it, rate limited per address and link (only refusals count), and sets an httpOnly cookie scoped to the link's API path holding an HMAC over the token and the password version. Secure follows the request, so plain-HTTP installs keep working. Changing or removing the password raises the version and locks every old cookie out. - Every public route, the photo proxies included, first checks the link: 404 unknown, 410 expired (JOURNEY_LINK_EXPIRED), 401 locked (JOURNEY_PASSWORD_REQUIRED). - Saving the share switches keeps the password and the expiry; the owner's read returns has_password, expires_at, view_count and last_viewed_at, never the hash, and none of it reaches the public payload. - A reader is counted once a day per address and browser, in an in-memory store behind an injectable port; a restart may count them again. - create_journey_share_link takes password and expires_at like the REST route; get_journey_share_link reports has_password.
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* A protected public journey link, end to end (#2553, #1702, #2959): the
|
||||
* whole app (buildApp, the real guards, share service and rate limit on a
|
||||
* migrated temp SQLite) between the owner who sets a password and an expiry
|
||||
* and the reader who opens the link. Every public route refuses a locked link,
|
||||
* the unlock sets a cookie scoped to the link's own path, a changed password
|
||||
* locks the old cookie out again, an expired link answers 410, saving a switch
|
||||
* keeps the protection, and readers are counted once a day for the owner only.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { JourneyShareTokens } from '../../src/db/entities/JourneyShareTokens.entity';
|
||||
import { makeJourney } from '../helpers/factories/journeys';
|
||||
import { findRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import type { Server } from 'node:http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let server: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
server = app.getHttpServer() as Server;
|
||||
await setAddonEnabled(orm, 'journey', true);
|
||||
}, 60_000);
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetRateLimits(app);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
/** A journey with a share link the owner saved with `body`; answers the owner and the token. */
|
||||
async function sharedJourney(body: Record<string, unknown> = {}) {
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, owner.id);
|
||||
const res = await request(server)
|
||||
.post(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send(body);
|
||||
expect(res.status).toBe(200);
|
||||
return { owner, journey, token: res.body.token as string };
|
||||
}
|
||||
|
||||
/** The share link as its owner reads it. */
|
||||
function ownerReads(journeyId: number, ownerId: number) {
|
||||
return request(server).get(`/api/journeys/${journeyId}/share-link`).set('Cookie', sessionCookie(ownerId));
|
||||
}
|
||||
|
||||
/** The `name=value` of the unlock cookie a response set, and the whole header line. */
|
||||
function unlockCookie(res: request.Response): { pair: string; line: string } {
|
||||
const lines = ([] as string[]).concat(res.headers['set-cookie'] ?? []);
|
||||
const line = lines.find((l) => l.startsWith('trek_journey_unlock=')) ?? '';
|
||||
return { pair: line.split(';')[0] ?? '', line };
|
||||
}
|
||||
|
||||
describe('a journey link with a password', () => {
|
||||
it('JPUBLINK-E2E-001: every public route refuses until the right password is typed', async () => {
|
||||
const { owner, journey, token } = await sharedJourney({ password: 'secret1' });
|
||||
|
||||
const read = await ownerReads(journey.id, owner.id);
|
||||
expect(read.body.link).toMatchObject({ has_password: true, expires_at: null, view_count: 0 });
|
||||
expect(JSON.stringify(read.body)).not.toContain('$2');
|
||||
|
||||
const locked = { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' };
|
||||
for (const path of ['', '/map-layers', '/photos/1/thumbnail', '/photo/local/a.jpg/1/original']) {
|
||||
const res = await request(server).get(`/api/public/journey/${token}${path}`);
|
||||
expect(res.status, path).toBe(401);
|
||||
expect(res.body, path).toEqual(locked);
|
||||
}
|
||||
|
||||
const wrong = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'nope' });
|
||||
expect(wrong.status).toBe(401);
|
||||
expect(wrong.body).toEqual({ error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' });
|
||||
expect(unlockCookie(wrong).line).toBe('');
|
||||
|
||||
const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
|
||||
expect(right.status).toBe(200);
|
||||
expect(right.body).toEqual({ success: true });
|
||||
const { pair, line } = unlockCookie(right);
|
||||
expect(line).toContain(`Path=/api/public/journey/${token}`);
|
||||
expect(line).toContain('HttpOnly');
|
||||
expect(line).toContain('SameSite=Lax');
|
||||
// Plain HTTP: a Secure cookie would be dropped and the reader locked out for good.
|
||||
expect(line).not.toContain('Secure');
|
||||
|
||||
const open = await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair);
|
||||
expect(open.status).toBe(200);
|
||||
expect(open.body.journey.title).toBe(journey.title);
|
||||
expect((await request(server).get(`/api/public/journey/${token}/map-layers`).set('Cookie', pair)).status).toBe(200);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-002: a new password locks out the browsers that unlocked the old one', async () => {
|
||||
const { owner, journey, token } = await sharedJourney({ password: 'secret1' });
|
||||
const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
|
||||
const { pair } = unlockCookie(right);
|
||||
|
||||
await request(server)
|
||||
.post(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ password: 'secret2' });
|
||||
|
||||
expect((await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-003: wrong passwords count per address and link, a right one does not', async () => {
|
||||
const { token } = await sharedJourney({ password: 'secret1' });
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const res = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: `nope${i}` });
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
const limited = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
|
||||
expect(limited.status).toBe(429);
|
||||
|
||||
// Another link is counted on its own.
|
||||
const other = await sharedJourney({ password: 'secret9' });
|
||||
const fine = await request(server).post(`/api/public/journey/${other.token}/unlock`).send({ password: 'secret9' });
|
||||
expect(fine.status).toBe(200);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-004: a bad unlock body is a 400, an unknown link a 404', async () => {
|
||||
const { token } = await sharedJourney({ password: 'secret1' });
|
||||
expect((await request(server).post(`/api/public/journey/${token}/unlock`).send({})).status).toBe(400);
|
||||
expect((await request(server).post('/api/public/journey/nope/unlock').send({ password: 'x' })).status).toBe(404);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-005: the owner refuses a password too short for the contract', async () => {
|
||||
const { owner, journey } = await sharedJourney();
|
||||
const res = await request(server)
|
||||
.post(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ password: 'abc' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a journey link with an expiry', () => {
|
||||
it('JPUBLINK-E2E-010: works until its date, then every route answers 410', async () => {
|
||||
const { owner, journey, token } = await sharedJourney({ expires_at: '2099-01-01T00:00:00Z' });
|
||||
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200);
|
||||
|
||||
await request(server)
|
||||
.post(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ expires_at: '2020-01-01T00:00:00Z' });
|
||||
|
||||
const gone = { error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' };
|
||||
for (const path of ['', '/map-layers', '/photos/1/thumbnail']) {
|
||||
const res = await request(server).get(`/api/public/journey/${token}${path}`);
|
||||
expect(res.status, path).toBe(410);
|
||||
expect(res.body, path).toEqual(gone);
|
||||
}
|
||||
const unlock = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'x' });
|
||||
expect(unlock.status).toBe(410);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-011: saving a switch keeps the password and the expiry', async () => {
|
||||
const { owner, journey, token } = await sharedJourney({ password: 'secret1', expires_at: '2099-01-01T00:00:00Z' });
|
||||
|
||||
await request(server)
|
||||
.post(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ share_timeline: true, share_gallery: false, share_map: true });
|
||||
|
||||
const read = await ownerReads(journey.id, owner.id);
|
||||
expect(read.body.link).toMatchObject({
|
||||
share_gallery: false,
|
||||
has_password: true,
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
});
|
||||
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-012: an existing link, saved before protection existed, stays open', async () => {
|
||||
const { token } = await sharedJourney();
|
||||
const row = await findRow(orm, JourneyShareTokens, { token });
|
||||
expect(row).toMatchObject({ password_hash: null, password_version: 0, expires_at: null });
|
||||
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the view count of a journey link', () => {
|
||||
it('JPUBLINK-E2E-020: counts each reader once a day, on the journey read only, for the owner only', async () => {
|
||||
const { owner, journey, token } = await sharedJourney();
|
||||
|
||||
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader A');
|
||||
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader A');
|
||||
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader B');
|
||||
await request(server).get(`/api/public/journey/${token}/map-layers`).set('User-Agent', 'Reader C');
|
||||
|
||||
const read = await ownerReads(journey.id, owner.id);
|
||||
expect(read.body.link.view_count).toBe(2);
|
||||
expect(read.body.link.last_viewed_at).toMatch(/Z$/);
|
||||
|
||||
const publicBody = await request(server).get(`/api/public/journey/${token}`);
|
||||
expect(JSON.stringify(publicBody.body)).not.toContain('view_count');
|
||||
});
|
||||
|
||||
it('JPUBLINK-E2E-021: a locked link counts nobody who has not unlocked it', async () => {
|
||||
const { token } = await sharedJourney({ password: 'secret1' });
|
||||
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Stranger');
|
||||
expect((await findRow(orm, JourneyShareTokens, { token }))?.view_count).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -128,7 +128,8 @@ const { gallerysvc } = vi.hoisted(() => ({
|
||||
const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn(), backfillSchedule: vi.fn() }));
|
||||
|
||||
const { sharesvc } = vi.hoisted(() => ({
|
||||
sharesvc: { getPublicJourney: vi.fn(), validateShareTokenForAsset: vi.fn() },
|
||||
// assertPublicAccess resolves: these cases are about the routes, the gate (#2553) has its own suite.
|
||||
sharesvc: { getPublicJourney: vi.fn(), validateShareTokenForAsset: vi.fn(), assertPublicAccess: vi.fn() },
|
||||
}));
|
||||
|
||||
// What the share service answers for a link with every section on: the route
|
||||
|
||||
Reference in New Issue
Block a user