From 23fceb0cfbcf49373ebf12658ed5adb8b0bef069 Mon Sep 17 00:00:00 2001 From: Wanjohi Date: Fri, 16 Oct 2026 00:57:14 +0300 Subject: [PATCH] feat(api): an installer sign-in can only ask for an install token A session the issuer minted for the installer exists to make one call: POST /machine/install-token. The installer runs on a machine that may not belong to the person who approved it, so anything else that session could do with the account is exposure with no use. The auth middleware now refuses a token whose audience is `installer` on every other route with 403 `forbidden`, "This sign-in can only add a host". It is checked once, in the middleware, so a route added later cannot forget it. Tokens for every other audience behave as before. --- apps/api/app/middleware/auth.ts | 21 +++++ apps/api/test/install-token.test.ts | 120 ++++++++++++++++++++++++++++ apps/auth/WIP-installer.md | 1 + 3 files changed, 142 insertions(+) create mode 100644 apps/api/test/install-token.test.ts diff --git a/apps/api/app/middleware/auth.ts b/apps/api/app/middleware/auth.ts index 21e0244a..98246f75 100644 --- a/apps/api/app/middleware/auth.ts +++ b/apps/api/app/middleware/auth.ts @@ -84,6 +84,16 @@ function getClient(env: Record) { }); } +/** + * A token minted for the host installer is good for one call: trading it for + * a single-use install token. The installer signs a person in on a machine + * that may not be theirs, so the session it holds must not be able to do + * anything else with the account — and checking it here, once, means a route + * added later cannot forget to. + */ +const INSTALLER_AUDIENCE = 'installer'; +const INSTALLER_ROUTE = { method: 'POST', path: '/machine/install-token' }; + export const auth: MiddlewareHandler = async (c, next) => { // A registered nessh host proves it is itself, rather than asserting an id // nobody checks. Wrong credentials fall through to public rather than @@ -188,6 +198,17 @@ export const auth: MiddlewareHandler = async (c, next) => { return Actor.with({ type: 'public', properties: {} }, next); } + if ( + verified.aud === INSTALLER_AUDIENCE && + !(c.req.method === INSTALLER_ROUTE.method && c.req.path === INSTALLER_ROUTE.path) + ) { + throw new VisibleError( + 'forbidden', + ErrorCodes.Permission.INSUFFICIENT_PERMISSIONS, + 'This sign-in can only add a host' + ); + } + const { subject } = verified; if (subject.type === 'user') { const teamID = c.req.header('x-nestri-team'); diff --git a/apps/api/test/install-token.test.ts b/apps/api/test/install-token.test.ts new file mode 100644 index 00000000..97366317 --- /dev/null +++ b/apps/api/test/install-token.test.ts @@ -0,0 +1,120 @@ +import { afterAll, beforeEach, describe, expect, test } from 'bun:test'; + +import { Fixtures } from '@nestri/core/db/fixtures'; +import { testDb } from '@nestri/core/db/test'; +import { Env } from '@nestri/core/env'; +import { exportJWK, generateKeyPair, SignJWT } from 'jose'; + +import { app } from '../app/index'; +import { TEST_FRONTEND_URL } from './setup'; + +const sql = testDb(); +const createdUserIds: string[] = []; + +afterAll(async () => { + if (createdUserIds.length > 0) { + await sql`delete from machine where owner_user_id in ${sql(createdUserIds)}`; + await sql`delete from "user" where id in ${sql(createdUserIds)}`; + } +}); + +/** + * An issuer, reached the way the API reaches one in production: through a + * binding that serves its discovery document and its keys. Tokens are signed + * here with the claims the real issuer writes, `aud` being the client id. + */ +const ISSUER = 'https://auth.test'; +const keys = await generateKeyPair('ES256'); +const jwk = { ...(await exportJWK(keys.publicKey)), kid: 'test', alg: 'ES256', use: 'sig' }; +const env = { + AUTH: { + fetch: async (request: Request) => { + const { pathname } = new URL(request.url); + if (pathname === '/.well-known/oauth-authorization-server') { + return Response.json({ issuer: ISSUER, jwks_uri: `${ISSUER}/.well-known/jwks.json` }); + } + if (pathname === '/.well-known/jwks.json') return Response.json({ keys: [jwk] }); + return new Response('not found', { status: 404 }); + } + } +}; + +beforeEach(() => { + Env.init({ NODE_ENV: 'test', FRONTEND_URL: TEST_FRONTEND_URL, AUTH_ISSUER_URL: ISSUER }); +}); + +/** An access token for `userId`, minted for `clientID` and so carrying it as `aud`. */ +async function tokenFor(userId: string, clientID: string): Promise { + return new SignJWT({ + mode: 'access', + type: 'user', + properties: { userID: userId, linkedAccountID: '' } + }) + .setProtectedHeader({ alg: 'ES256', kid: 'test', typ: 'JWT' }) + .setIssuer(ISSUER) + .setAudience(clientID) + .setSubject(`user:${userId}`) + .setExpirationTime('15m') + .sign(keys.privateKey); +} + +async function person(label: string) { + const owner = await Fixtures.owner(label); + createdUserIds.push(owner.userId); + return owner; +} + +function call(method: string, path: string, token: string, body?: unknown) { + return app.request( + path, + { + method, + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body) + }, + env + ); +} + +describe('a sign-in made by the installer', () => { + test('can ask for an install token', async () => { + const owner = await person('aud-ok'); + const response = await call( + 'POST', + '/machine/install-token', + await tokenFor(owner.userId, 'installer'), + {} + ); + expect(response.status).toBe(200); + const body = (await response.json()) as any; + expect(body.data.token).toStartWith('nit_'); + }); + + test('can do nothing else', async () => { + const owner = await person('aud-refused'); + const token = await tokenFor(owner.userId, 'installer'); + + const elsewhere: [string, string][] = [ + ['GET', '/user'], + ['GET', '/machine'], + ['POST', '/machine/register'], + ['POST', '/access-token'] + ]; + for (const [method, path] of elsewhere) { + const response = await call(method, path, token, method === 'POST' ? {} : undefined); + expect(response.status).toBe(403); + expect((await response.json()) as any).toEqual({ + type: 'forbidden', + code: 'insufficient_permissions', + message: 'This sign-in can only add a host' + }); + } + }); + + test('every other client is unaffected', async () => { + const owner = await person('aud-desktop'); + const token = await tokenFor(owner.userId, 'desktop'); + expect((await call('GET', '/user', token)).status).toBe(200); + expect((await call('POST', '/machine/install-token', token, {})).status).toBe(200); + }); +}); diff --git a/apps/auth/WIP-installer.md b/apps/auth/WIP-installer.md index 1893bb03..4b29f4d0 100644 --- a/apps/auth/WIP-installer.md +++ b/apps/auth/WIP-installer.md @@ -6,6 +6,7 @@ Branch: feat/installer-sign-in - 1. installer device client, 15 min, no refresh (engine `clientTTL`, apps/auth `clientTTL`) - 2. per-address limit on POST /device/authorize (engine `deviceVerification.requestLimit`), 429 slow_down + Retry-After - 3. confirm wording per client (engine `deviceConfirm`, apps/auth `deviceConfirm`), preview entry +- 4. api middleware: aud `installer` only on POST /machine/install-token, else 403 (test: apps/api/test/install-token.test.ts) ## Left 1. issuer: `installer` device client, 15 min access, no refresh token