mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-26 07:37:54 +00:00
feat(workers): cap rented units per plan and refuse only new ones
This commit is contained in:
1 parent
4f46469780
commit
bf488e5b8a
4 files changed
+235
-33
No files matched your search
@@ -301,6 +301,13 @@ export const EVENTS_WORKER_DEPLOYS_PER_HOUR = 30;
|
||||
/** Deploys one user scope may trigger per hour. */
|
||||
export const EVENTS_USER_WORKER_DEPLOYS_PER_HOUR = 10;
|
||||
|
||||
/**
|
||||
* Units one user may rent at once: ordinary workers, user scopes, and the
|
||||
* events workers of apps they own. Only creating a unit is refused; holdings
|
||||
* over the cap are kept.
|
||||
*/
|
||||
export const RENTED_UNITS_PER_USER = tiered(100, 16, 16);
|
||||
|
||||
/**
|
||||
* Handlers one `publishAll` may carry. A build step publishes its whole set in
|
||||
* one call, and the set is capped by what an app may hold anyway.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// however the interactions with the Puter API are
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
import { Actor, makeActor as resolveActor } from '../../core/actor.js';
|
||||
import { runWithContext } from '../../core/context.js';
|
||||
import { PuterServer } from '../../server.js';
|
||||
import { DEFAULT_FREE_SUBSCRIPTION } from '../../services/metering/consts.js';
|
||||
import {
|
||||
setupPuterTestEnv,
|
||||
setupTestServer,
|
||||
@@ -797,6 +799,135 @@ describe('WorkerDriver', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('rented-unit cap', () => {
|
||||
const FREE_CAP = 16;
|
||||
const PAID_CAP = 100;
|
||||
|
||||
// The cap sits after the Cloudflare-config gate, so the driver needs
|
||||
// credentials to reach it; a create under the cap then fails on the
|
||||
// missing source file, which is what tells it past the cap check.
|
||||
let originalWorkersConfig: unknown;
|
||||
beforeAll(() => {
|
||||
const driverConfig = (
|
||||
target as unknown as { config: Record<string, unknown> }
|
||||
).config;
|
||||
originalWorkersConfig = driverConfig.workers;
|
||||
driverConfig.workers = {
|
||||
XAUTHKEY: 'test-key',
|
||||
ACCOUNTID: 'test-account',
|
||||
};
|
||||
});
|
||||
afterAll(() => {
|
||||
(
|
||||
target as unknown as { config: Record<string, unknown> }
|
||||
).config.workers = originalWorkersConfig;
|
||||
});
|
||||
|
||||
const holding = (
|
||||
plan: string,
|
||||
held: { workers?: number; scopes?: number; owned?: number },
|
||||
) => {
|
||||
vi.spyOn(
|
||||
server.services.metering,
|
||||
'getActorSubscription',
|
||||
).mockResolvedValue({ id: plan } as never);
|
||||
vi.spyOn(
|
||||
server.stores.subdomain,
|
||||
'countByUserIdAndPrefix',
|
||||
).mockResolvedValue(held.workers ?? 0);
|
||||
vi.spyOn(
|
||||
server.stores.eventHandler,
|
||||
'countUserScopesWithHandlersForUser',
|
||||
).mockResolvedValue(held.scopes ?? 0);
|
||||
vi.spyOn(
|
||||
server.stores.eventHandler,
|
||||
'countAppsWithHandlersForOwner',
|
||||
).mockResolvedValue(held.owned ?? 0);
|
||||
};
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const createWorker = () =>
|
||||
inCtx(() =>
|
||||
target.create({
|
||||
appId: 'test-app',
|
||||
workerName: 'capped',
|
||||
filePath: '/test.js',
|
||||
}),
|
||||
);
|
||||
|
||||
it('refuses a free user one unit past the cap, across all three sources', async () => {
|
||||
for (const held of [
|
||||
{ workers: FREE_CAP },
|
||||
{ scopes: FREE_CAP },
|
||||
{ owned: FREE_CAP },
|
||||
{ workers: 10, scopes: 4, owned: 2 },
|
||||
]) {
|
||||
holding(DEFAULT_FREE_SUBSCRIPTION, held);
|
||||
await expect(createWorker()).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('lets a free user create up to the cap', async () => {
|
||||
holding(DEFAULT_FREE_SUBSCRIPTION, {
|
||||
workers: 10,
|
||||
scopes: 3,
|
||||
owned: 2,
|
||||
});
|
||||
await expect(createWorker()).rejects.not.toMatchObject({
|
||||
statusCode: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a paid user the unit after 100', async () => {
|
||||
holding('paid-plan', { workers: 90, scopes: 5, owned: 5 });
|
||||
await expect(createWorker()).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
});
|
||||
holding('paid-plan', { workers: 90, scopes: 5, owned: 4 });
|
||||
await expect(createWorker()).rejects.not.toMatchObject({
|
||||
statusCode: 403,
|
||||
});
|
||||
expect(PAID_CAP).toBe(100);
|
||||
});
|
||||
|
||||
it('keeps a free user over the cap, redeploys what they hold, and refuses a new one', async () => {
|
||||
holding(DEFAULT_FREE_SUBSCRIPTION, { workers: 20 });
|
||||
const user = actor.user;
|
||||
const exists = vi
|
||||
.spyOn(server.stores.subdomain, 'getBySubdomain')
|
||||
.mockImplementation(
|
||||
async (name: string) =>
|
||||
(name === 'workers.puter.capped'
|
||||
? { user_id: user.id, uuid: 'existing-uuid' }
|
||||
: null) as never,
|
||||
);
|
||||
const noApp = makeActor({ app: undefined });
|
||||
const create = (workerName: string) =>
|
||||
inCtx(
|
||||
() =>
|
||||
target.create({
|
||||
appId: '',
|
||||
workerName,
|
||||
filePath: '/test.js',
|
||||
}),
|
||||
noApp,
|
||||
);
|
||||
|
||||
await expect(create('capped')).rejects.not.toMatchObject({
|
||||
statusCode: 403,
|
||||
});
|
||||
await expect(create('another')).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
});
|
||||
exists.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('admission bypass', () => {
|
||||
const unverified = (): Actor =>
|
||||
makeActor({
|
||||
@@ -864,7 +995,7 @@ describe('WorkerDriver', () => {
|
||||
// with an account id also demands a built worker preamble, which
|
||||
// is not built for backend tests.
|
||||
const store = server.stores.subdomain;
|
||||
const originalList = store.listByUserIdAndPrefix.bind(store);
|
||||
const originalCount = store.countByUserIdAndPrefix.bind(store);
|
||||
const driverConfig = (
|
||||
target as unknown as { config: Record<string, unknown> }
|
||||
).config;
|
||||
@@ -873,13 +1004,11 @@ describe('WorkerDriver', () => {
|
||||
XAUTHKEY: 'test-key',
|
||||
ACCOUNTID: 'test-account',
|
||||
};
|
||||
let listCalls = 0;
|
||||
store.listByUserIdAndPrefix = (async () => {
|
||||
listCalls++;
|
||||
return Array.from({ length: 100 }, (_, i) => ({
|
||||
subdomain: `workers.puter.w${i}`,
|
||||
})) as never;
|
||||
}) as typeof store.listByUserIdAndPrefix;
|
||||
let countCalls = 0;
|
||||
store.countByUserIdAndPrefix = (async () => {
|
||||
countCalls++;
|
||||
return 100;
|
||||
}) as typeof store.countByUserIdAndPrefix;
|
||||
|
||||
try {
|
||||
await expect(
|
||||
@@ -891,7 +1020,7 @@ describe('WorkerDriver', () => {
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
expect(listCalls).toBe(1);
|
||||
expect(countCalls).toBe(1);
|
||||
|
||||
// With the bypass the limit is never even counted; the call
|
||||
// fails later, on the missing source file.
|
||||
@@ -905,9 +1034,9 @@ describe('WorkerDriver', () => {
|
||||
}),
|
||||
),
|
||||
).rejects.not.toMatchObject({ statusCode: 403 });
|
||||
expect(listCalls).toBe(1);
|
||||
expect(countCalls).toBe(1);
|
||||
} finally {
|
||||
store.listByUserIdAndPrefix = originalList;
|
||||
store.countByUserIdAndPrefix = originalCount;
|
||||
driverConfig.workers = originalWorkersConfig;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -43,6 +43,7 @@ import { PuterDriver } from '../types.js';
|
||||
import { BoundedTtlMap } from '../../util/boundedTtlMap.js';
|
||||
import { awaitLater } from '../../util/concurrency.js';
|
||||
import { isUniqueViolation } from '../../util/dbError.js';
|
||||
import { assertRentedUnitRoom } from '../../util/rentedUnits.js';
|
||||
import { loadFileInput } from '../util/fileInput.js';
|
||||
import {
|
||||
normalizeLimit,
|
||||
@@ -57,7 +58,6 @@ const CF_BASE_URL = 'https://api.cloudflare.com/client/v4/accounts';
|
||||
export const WORKER_COMPATIBILITY_DATE = '2025-07-15';
|
||||
export const WORKER_COMPATIBILITY_FLAGS = ['global_fetch_strictly_public'];
|
||||
const WORKER_NAME_REGEX = /^[a-zA-Z0-9_-]+$/;
|
||||
const MAX_WORKERS_PER_USER = 100;
|
||||
|
||||
/**
|
||||
* Opt-in key for `create()` that skips the admission checks a _new_ worker has
|
||||
@@ -188,8 +188,8 @@ export interface InternalDeployTarget {
|
||||
|
||||
const MAX_SOURCE_SIZE = 10 * 1024 * 1024; // 10 MB
|
||||
// How far to scan an app's child apps when resolving which workers it may
|
||||
// see. A user is capped at MAX_WORKERS_PER_USER workers, so only that many
|
||||
// child apps can actually own one; the ceiling is generous slack over that.
|
||||
// see. A user is capped at their plan's rented units, so only that many
|
||||
// child apps can actually own a worker; the ceiling is generous slack over that.
|
||||
const CHILD_APP_SCAN_LIMIT = 1000;
|
||||
|
||||
// -- Preamble --------------------------------------------------------
|
||||
@@ -457,25 +457,16 @@ export class WorkerDriver extends PuterDriver {
|
||||
|
||||
this.#requireCfConfig();
|
||||
|
||||
// Quota check — count existing workers.puter.* subdomains owned by user
|
||||
//
|
||||
// A deploy target creates no such row, so this count can neither see
|
||||
// its scripts nor be grown by them; running it would only make an
|
||||
// unrelated worker quota decide whether these deploy. Whatever bounds
|
||||
// them has to be counted where they actually live, and belongs to the
|
||||
// caller that owns their lifecycle.
|
||||
const existingWorkers =
|
||||
skipAdmission || deployTarget
|
||||
? []
|
||||
: await this.stores.subdomain.listByUserIdAndPrefix(
|
||||
actor.user.id,
|
||||
WORKER_SUBDOMAIN_PREFIX,
|
||||
);
|
||||
if (existingWorkers.length >= MAX_WORKERS_PER_USER) {
|
||||
throw new HttpError(
|
||||
403,
|
||||
`Worker limit reached (max ${MAX_WORKERS_PER_USER})`,
|
||||
{ legacyCode: 'forbidden' },
|
||||
// A new worker is one more rented unit. Deploy targets create no
|
||||
// worker row and are bounded by their own caller; redeploying an
|
||||
// existing worker is never refused.
|
||||
if (!skipAdmission && !deployTarget && !existingSub) {
|
||||
await assertRentedUnitRoom(
|
||||
{
|
||||
stores: this.stores,
|
||||
metering: this.services.metering,
|
||||
},
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type { Actor } from '../core/actor.js';
|
||||
import { HttpError } from '../core/http/HttpError.js';
|
||||
import {
|
||||
RENTED_UNITS_PER_USER,
|
||||
limitFor,
|
||||
} from '../controllers/events/limits.js';
|
||||
import {
|
||||
actorPlanId,
|
||||
type SubscriptionMetering,
|
||||
} from '../services/metering/enforcement.js';
|
||||
import type { EventHandlerStore } from '../stores/events/EventHandlerStore.js';
|
||||
import {
|
||||
WORKER_SUBDOMAIN_PREFIX,
|
||||
type SubdomainStore,
|
||||
} from '../stores/subdomain/SubdomainStore.js';
|
||||
|
||||
export interface RentedUnitDeps {
|
||||
stores: {
|
||||
subdomain: Pick<SubdomainStore, 'countByUserIdAndPrefix'>;
|
||||
eventHandler: Pick<
|
||||
EventHandlerStore,
|
||||
| 'countUserScopesWithHandlersForUser'
|
||||
| 'countAppsWithHandlersForOwner'
|
||||
>;
|
||||
};
|
||||
metering: SubscriptionMetering | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse creating one more rented unit for a user already holding their plan's
|
||||
* cap of them. Call only where a unit is created: a redeploy or a publish into
|
||||
* an existing unit must never reach it.
|
||||
*/
|
||||
export const assertRentedUnitRoom = async (
|
||||
deps: RentedUnitDeps,
|
||||
actor: Actor,
|
||||
): Promise<void> => {
|
||||
const userId = actor.user?.id;
|
||||
if (userId === undefined) return;
|
||||
const cap = limitFor(
|
||||
RENTED_UNITS_PER_USER,
|
||||
await actorPlanId(deps.metering, actor),
|
||||
);
|
||||
const [workers, scopes, owned] = await Promise.all([
|
||||
deps.stores.subdomain.countByUserIdAndPrefix(
|
||||
userId,
|
||||
WORKER_SUBDOMAIN_PREFIX,
|
||||
),
|
||||
deps.stores.eventHandler.countUserScopesWithHandlersForUser(userId),
|
||||
deps.stores.eventHandler.countAppsWithHandlersForOwner(userId),
|
||||
]);
|
||||
if (Number(workers) + scopes + owned >= cap)
|
||||
throw new HttpError(403, `Worker limit reached (max ${cap})`, {
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
};
|
||||
Reference in new issue
Block a user