From 228df15528550b7f61f2417d758146b4ade1bd0e Mon Sep 17 00:00:00 2001 From: Wanjohi Date: Fri, 16 Oct 2026 01:01:55 +0300 Subject: [PATCH] feat(machine): a team may own at most ten machines Adding a host is a command anyone signed in can run, so one account could register as many hosts as it could script. A team now owns at most ten machines that are not deleted; hardware an organisation owns outright is not counted. The limit is held in Machine.register, under a lock on the team's row, so it covers registering directly and spending an install token alike, including one minted while there was still room; a refused spend leaves the token unspent. Minting an install token for a full team is refused too, so nobody is handed a command that cannot work. Both answer 429 `rate_limit` / `quota_exceeded`, "Your team already has 10 machines. Remove one to add another." --- apps/api/app/routes/machine.ts | 8 +- apps/api/test/install-token.test.ts | 59 ++++++++ apps/auth/WIP-installer.md | 1 + packages/core/src/machine/index.ts | 126 ++++++++++++------ .../core/src/machine/install-token.test.ts | 29 ++++ packages/core/src/machine/install-token.ts | 6 +- packages/core/src/machine/machine.test.ts | 52 ++++++++ 7 files changed, 238 insertions(+), 43 deletions(-) diff --git a/apps/api/app/routes/machine.ts b/apps/api/app/routes/machine.ts index d3a475a0..07c047a6 100644 --- a/apps/api/app/routes/machine.ts +++ b/apps/api/app/routes/machine.ts @@ -55,7 +55,8 @@ export namespace MachineApi { description: 'The box is registered' }, 401: ErrorResponses[401], - 403: ErrorResponses[403] + 403: ErrorResponses[403], + 429: ErrorResponses[429] } }), validator( @@ -176,7 +177,7 @@ export namespace MachineApi { tags: ['Machine'], summary: 'Issue an install token', description: - 'Mint a one-time token that registers one host to a team — or, with `organisationId`, to your organisation’s fleet — when the installer presents it. It expires after an hour and is spent by its first use, because it travels in a command a person pastes and so ends up in shell history. One person may make five an hour and hold three unspent at once.', + 'Mint a one-time token that registers one host to a team — or, with `organisationId`, to your organisation’s fleet — when the installer presents it. It expires after an hour and is spent by its first use, because it travels in a command a person pastes and so ends up in shell history. One person may make five an hour and hold three unspent at once, and a team may own at most ten hosts; fleet hosts are not counted.', responses: { 200: { content: { @@ -292,7 +293,8 @@ export namespace MachineApi { }, description: 'The host is registered' }, - 401: ErrorResponses[401] + 401: ErrorResponses[401], + 429: ErrorResponses[429] } }), validator( diff --git a/apps/api/test/install-token.test.ts b/apps/api/test/install-token.test.ts index 929d25f4..a252b31e 100644 --- a/apps/api/test/install-token.test.ts +++ b/apps/api/test/install-token.test.ts @@ -159,3 +159,62 @@ describe('how many install tokens one person may have', () => { }); }); }); + +describe('how many machines a team may own', () => { + const full = { + type: 'rate_limit', + code: 'quota_exceeded', + message: 'Your team already has 10 machines. Remove one to add another.' + }; + + function install(token: string, label: string) { + return app.request('/machine/install', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ token, label }) + }); + } + + test('a full team is not handed an install token', async () => { + const owner = await person('cap-mint'); + for (let i = 0; i < 10; i++) await Fixtures.machine(owner, `box-${i}`); + const refused = await call( + 'POST', + '/machine/install-token', + await tokenFor(owner.userId, 'installer'), + {} + ); + expect(refused.status).toBe(429); + expect((await refused.json()) as any).toEqual(full); + }); + + test('a token minted with room left cannot add an eleventh', async () => { + const owner = await person('cap-redeem'); + for (let i = 0; i < 9; i++) await Fixtures.machine(owner, `box-${i}`); + const issued = await call( + 'POST', + '/machine/install-token', + await tokenFor(owner.userId, 'installer'), + {} + ); + const { data } = (await issued.json()) as any; + await Fixtures.machine(owner, 'the-last-place'); + + const refused = await install(data.token, 'eleventh'); + expect(refused.status).toBe(429); + expect((await refused.json()) as any).toEqual(full); + }); + + test('registering directly is held to the same limit', async () => { + const owner = await person('cap-register'); + for (let i = 0; i < 10; i++) await Fixtures.machine(owner, `box-${i}`); + const refused = await call( + 'POST', + '/machine/register', + await tokenFor(owner.userId, 'desktop'), + { label: 'eleventh' } + ); + expect(refused.status).toBe(429); + expect((await refused.json()) as any).toEqual(full); + }); +}); diff --git a/apps/auth/WIP-installer.md b/apps/auth/WIP-installer.md index 67e5fc04..88a594c9 100644 --- a/apps/auth/WIP-installer.md +++ b/apps/auth/WIP-installer.md @@ -8,6 +8,7 @@ Branch: feat/installer-sign-in - 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) - 5. core InstallToken.create: 5/h + 3 outstanding per user (HOURLY_LIMIT, OUTSTANDING_LIMIT), 429 too_many_requests +- 6. Machine.TEAM_MACHINE_LIMIT = 10 in Machine.register (team row lock) + InstallToken.create, 429 quota_exceeded ## Left 1. issuer: `installer` device client, 15 min access, no refresh token diff --git a/packages/core/src/machine/index.ts b/packages/core/src/machine/index.ts index 64daf345..5917189d 100644 --- a/packages/core/src/machine/index.ts +++ b/packages/core/src/machine/index.ts @@ -10,6 +10,7 @@ import { Examples } from '../examples.js'; import { fn } from '../fn.js'; import { SessionTable } from '../session/session.sql.js'; import { Member } from '../team/member.js'; +import { TeamTable } from '../team/team.sql.js'; import { MachineTable } from './machine.sql.js'; import { Slug } from './slug.js'; @@ -149,10 +150,45 @@ export namespace Machine { return diff === 0; } + /** + * Most machines one team may own. + * + * A host somebody brings is added by a command anyone signed in can run, + * so without a ceiling one account is as many hosts as it can script. + * Hardware an organisation owns outright is not counted: its own people + * add it, deliberately, and it is never reached through a team. + */ + export const TEAM_MACHINE_LIMIT = 10; + + /** + * Refuses when `teamId` already owns {@link TEAM_MACHINE_LIMIT} machines, + * with a message the person can act on. + */ + export async function assertTeamHasRoom(teamId: string) { + const owned = await Database.use((tx) => + tx + .select({ count: sql`count(*)::int` }) + .from(MachineTable) + .where(and(eq(MachineTable.teamId, teamId), isNull(MachineTable.timeDeleted))) + .then((rows) => rows[0]?.count ?? 0) + ); + if (owned >= TEAM_MACHINE_LIMIT) { + throw new VisibleError( + 'rate_limit', + ErrorCodes.RateLimit.QUOTA_EXCEEDED, + `Your team already has ${TEAM_MACHINE_LIMIT} machines. Remove one to add another.` + ); + } + } + /** * Register a box. The secret is returned here and nowhere else — it is * stored only as a digest, so a lost secret means re-registering rather * than looking it up. + * + * A team at {@link TEAM_MACHINE_LIMIT} is refused here, which is what holds + * the limit for every way of registering, an install token minted while + * there was still room included. */ export const register = fn( Info.pick({ id: true, ownerUserId: true, teamId: true, label: true }) @@ -160,50 +196,62 @@ export namespace Machine { .refine((v) => (v.teamId === null) !== ((v.organisationId ?? null) === null), { message: 'A machine belongs to a team or to an organisation, and not to both' }), - async (input) => { - const secret = generateSecret(); - const secretHash = await hashSecret(secret); + async (input) => + Database.transaction(async (tx) => { + if (input.teamId) { + // Held until the machine is written, so two registrations + // at the same instant cannot both see room for one. + await tx + .select({ id: TeamTable.id }) + .from(TeamTable) + .where(eq(TeamTable.id, input.teamId)) + .for('update'); + await assertTeamHasRoom(input.teamId); + } - // The name space holds tens of millions, so a collision is rare - // enough that retrying is cheaper than checking first -- and a - // check-then-insert would be wrong as well as slower, because two - // registrations in the same instant both read "free" and both write. - // The unique index is the thing that actually decides. - for (let attempt = 0; attempt < SLUG_ATTEMPTS; attempt++) { - const slug = Slug.generate(); - try { - await Database.use(async (tx) => { - await tx.insert(MachineTable).values({ - id: input.id, - ownerUserId: input.ownerUserId, - teamId: input.teamId, - organisationId: input.organisationId ?? null, - label: input.label, - slug, - secretHash, - lastSeen: null + const secret = generateSecret(); + const secretHash = await hashSecret(secret); + + // The name space holds tens of millions, so a collision is rare + // enough that retrying is cheaper than checking first -- and a + // check-then-insert would be wrong as well as slower, because two + // registrations in the same instant both read "free" and both write. + // The unique index is the thing that actually decides. + for (let attempt = 0; attempt < SLUG_ATTEMPTS; attempt++) { + const slug = Slug.generate(); + try { + await Database.use(async (tx) => { + await tx.insert(MachineTable).values({ + id: input.id, + ownerUserId: input.ownerUserId, + teamId: input.teamId, + organisationId: input.organisationId ?? null, + label: input.label, + slug, + secretHash, + lastSeen: null + }); }); - }); - return { id: input.id, secret, slug }; - } catch (err) { - if (!isUniqueViolation(err)) { - throw err; - } - // Only a name collision is worth another go. A duplicate id - // or secret means something is wrong that a new name cannot - // fix, and retrying would bury it. - if (!isSlugViolation(err)) { - throw err; + return { id: input.id, secret, slug }; + } catch (err) { + if (!isUniqueViolation(err)) { + throw err; + } + // Only a name collision is worth another go. A duplicate id + // or secret means something is wrong that a new name cannot + // fix, and retrying would bury it. + if (!isSlugViolation(err)) { + throw err; + } } } - } - throw new VisibleError( - 'internal', - ErrorCodes.Server.INTERNAL_ERROR, - 'Could not mint an unused hostname for this machine' - ); - } + throw new VisibleError( + 'internal', + ErrorCodes.Server.INTERNAL_ERROR, + 'Could not mint an unused hostname for this machine' + ); + }) ); /** How many names to try before giving up. See `register`. */ diff --git a/packages/core/src/machine/install-token.test.ts b/packages/core/src/machine/install-token.test.ts index eb8b7abb..74df5270 100644 --- a/packages/core/src/machine/install-token.test.ts +++ b/packages/core/src/machine/install-token.test.ts @@ -3,6 +3,7 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { Fixtures } from '../db/fixtures.js'; import { testDb } from '../db/test.js'; import { VisibleError } from '../error.js'; +import { Machine } from './index.js'; import { InstallToken } from './install-token.js'; const sql = testDb(); @@ -120,4 +121,32 @@ describe('Install tokens', () => { const issued = await InstallToken.create({ teamId: quiet.teamId, userId: quiet.userId }); expect(issued.token).toStartWith('nit_'); }); + + test('a team with no room for a host is not handed a token for one', async () => { + const owner = await newOwner('nit-cap-mint'); + for (let i = 0; i < Machine.TEAM_MACHINE_LIMIT; i++) await Fixtures.machine(owner, `box-${i}`); + const refused = await InstallToken.create({ teamId: owner.teamId, userId: owner.userId }).catch( + (e) => e + ); + expect(refused).toBeInstanceOf(VisibleError); + expect(refused.code).toBe('quota_exceeded'); + expect(refused.message).toBe('Your team already has 10 machines. Remove one to add another.'); + }); + + test('a token minted while there was room is refused once there is none, and stays unspent', async () => { + const owner = await newOwner('nit-cap-redeem'); + for (let i = 0; i < Machine.TEAM_MACHINE_LIMIT - 1; i++) { + await Fixtures.machine(owner, `box-${i}`); + } + const { token } = await InstallToken.create({ teamId: owner.teamId, userId: owner.userId }); + await Fixtures.machine(owner, 'the-last-place'); + + const refused = await InstallToken.redeem({ token, label: 'late' }).catch((e) => e); + expect(refused).toBeInstanceOf(VisibleError); + expect(refused.code).toBe('quota_exceeded'); + + const rows = + await sql`select redeemed_at from install_token where created_by_user_id = ${owner.userId}`; + expect(rows[0]!.redeemed_at).toBeNull(); + }); }); diff --git a/packages/core/src/machine/install-token.ts b/packages/core/src/machine/install-token.ts index 52796878..6d4000e6 100644 --- a/packages/core/src/machine/install-token.ts +++ b/packages/core/src/machine/install-token.ts @@ -47,7 +47,10 @@ export namespace InstallToken { * already checked membership of whichever it names. * * Refused once the person has hit {@link HOURLY_LIMIT} or - * {@link OUTSTANDING_LIMIT}, with a message a terminal can print as it is. + * {@link OUTSTANDING_LIMIT}, or the team already owns as many machines as + * it may, with a message a terminal can print as it is. The team limit is + * held again when the token is spent; checking here as well means nobody + * is handed a command that cannot work. */ export const create = fn( z @@ -71,6 +74,7 @@ export namespace InstallToken { .from(UserTable) .where(eq(UserTable.id, input.userId)) .for('update'); + if (input.teamId) await Machine.assertTeamHasRoom(input.teamId); const [usage] = await tx .select({ lastHour: sql`(count(*) filter (where ${InstallTokenTable.timeCreated} > now() - interval '1 hour'))::int`, diff --git a/packages/core/src/machine/machine.test.ts b/packages/core/src/machine/machine.test.ts index b7a45501..9e061d17 100644 --- a/packages/core/src/machine/machine.test.ts +++ b/packages/core/src/machine/machine.test.ts @@ -2,6 +2,7 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { Fixtures } from '../db/fixtures.js'; import { testDb } from '../db/test.js'; +import { VisibleError } from '../error.js'; import { Identifier } from '../id.js'; import { Machine } from './index.js'; @@ -167,3 +168,54 @@ describe('Machine heartbeat', () => { expect(Machine.isOnline(wellPast)).toBe(false); }); }); + +describe('How many machines a team may own', () => { + function register(owner: { userId: string; teamId: string }, label: string) { + return Machine.register({ + id: Identifier.ascending('machine'), + ownerUserId: owner.userId, + teamId: owner.teamId, + label + }); + } + + test('ten, and the eleventh is refused with a message to act on', async () => { + const owner = await newOwner('mch-cap'); + for (let i = 0; i < Machine.TEAM_MACHINE_LIMIT; i++) await register(owner, `box-${i}`); + + const refused = await register(owner, 'one-too-many').catch((e) => e); + expect(refused).toBeInstanceOf(VisibleError); + expect(refused.type).toBe('rate_limit'); + expect(refused.code).toBe('quota_exceeded'); + expect(refused.message).toBe('Your team already has 10 machines. Remove one to add another.'); + + const rows = await sql`select id from machine where team_id = ${owner.teamId}`; + expect(rows).toHaveLength(Machine.TEAM_MACHINE_LIMIT); + }); + + test('a removed machine frees its place', async () => { + const owner = await newOwner('mch-cap-removed'); + for (let i = 0; i < Machine.TEAM_MACHINE_LIMIT; i++) await register(owner, `box-${i}`); + await sql`update machine set time_deleted = now() + where id = (select id from machine where team_id = ${owner.teamId} limit 1)`; + expect((await register(owner, 'replacement')).secret).toStartWith('msk_'); + }); + + test('registrations racing for the last place do not both get it', async () => { + const owner = await newOwner('mch-cap-race'); + for (let i = 0; i < Machine.TEAM_MACHINE_LIMIT - 1; i++) await register(owner, `box-${i}`); + const results = await Promise.allSettled( + Array.from({ length: 4 }, (_, i) => register(owner, `racer-${i}`)) + ); + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1); + const rows = await sql`select id from machine where team_id = ${owner.teamId}`; + expect(rows).toHaveLength(Machine.TEAM_MACHINE_LIMIT); + }); + + test('hardware an organisation owns is not counted', async () => { + const operator = await newOwner('mch-cap-fleet'); + const fleet = await Fixtures.fleet(operator, Machine.TEAM_MACHINE_LIMIT + 1); + expect(fleet.machines).toHaveLength(Machine.TEAM_MACHINE_LIMIT + 1); + expect((await register(operator, 'own-box')).secret).toStartWith('msk_'); + }); +});