Public: anyone can read this; the crew can change it.

Per-account limits on repositories and apps: the count is checked before creating, and the refusal names it #2086

Parked opened this
Closed without merging

scout/forge:scout/973-per-account-limits-on-repositories-and-a → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +336 −13
docs/APPS.md +1
@@ -1095,6 +1095,7 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does.
10951095 | `FORGE_APPS_CONCURRENCY` | `2` | deploys running their heavy steps at once |
10961096 | `FORGE_PREVIEW_IDLE_DAYS` | `3` | days a pull may sit untouched before its preview sleeps; `0` = never |
10971097 | `FORGE_CREW_CONCURRENCY` | `2` | agent runs at once (live: Settings → Capacity) |
1098 | `FORGE_QUOTA_REPOS` / `FORGE_QUOTA_APPS` | `10` / `10` | most repositories / apps one account owns; admins and agents are not limited (live: Settings → Capacity, `PATCH /api/v1/admin/settings`) |
10981099 | `FORGE_CHECKS_CONCURRENCY` | `1` | checks at once (live: Settings → Capacity) |
10991100 | `FORGE_CHECKS_PLACEMENT` | `process` | `job` runs a check's commands as a cluster Job (see Placement above) |
11001101 | `FORGE_CHECKS_DRAIN_S` | `300` | seconds a roll lets running checks finish first |
scripts/gate.ts +2
@@ -147,6 +147,8 @@ export const GATE: readonly string[] = [
147147 "test/decide.test.ts",
148148 "test/ledger.test.ts",
149149 "test/capacity.test.ts",
150 "test/quotas.test.ts",
151
150152 "test/access-log.test.ts",
151153 "test/flow-pipeline.test.ts",
152154 "test/flow-throughput.test.ts",
src/actions/apps.ts +11 −2
@@ -59,6 +59,7 @@ import {
5959 requireWriter,
6060 type AccessError,
6161 } from "./access.ts";
62 import { overQuota, type QuotaError } from "../core/quotas.ts";
6263 import { assignIssue, openIssue } from "./issues.ts";
6364 import {
6465 commitToBranch,
@@ -79,11 +80,13 @@ export function enableApp(
7980 actor: User | undefined,
8081 repo: Repo,
8182 input: AppSettingsInput = {},
82 ): Result<AppRecord, "not_found" | CreateAppError | "unverified"> {
83 ): Result<AppRecord, "not_found" | CreateAppError | "unverified" | QuotaError> {
8384 const admin = requireRepoAdmin(app, actor, repo);
8485 if (!admin.ok) return admin;
8586 const proven = requireVerified(app, admin.value);
8687 if (!proven.ok) return proven;
88 const over = overQuota(app.db, admin.value, "apps");
89 if (over) return err(over);
8790 const created = insertApp(app.db, {
8891 repoId: repo.id,
8992 slug: input.slug ?? slugFor(repo.name),
@@ -271,7 +274,8 @@ export type NewAppError =
271274 | CreateRepoActionError
272275 | CreateAppError
273276 | "scaffold_failed"
274 | "no_such_agent";
277 | "no_such_agent"
278 | QuotaError;
275279
276280 /**
277281 * The golden path's first step, as one call: a repository with a working
@@ -292,6 +296,11 @@ export async function newApp(
292296 ? undefined
293297 : getAgentByName(app.db, input.agent);
294298 if (input.agent && !agent) return err("no_such_agent");
299 // Both counts first, so nothing exists to take back when one is full.
300 const full =
301 overQuota(app.db, user.value, "apps") ??
302 (input.owner ? undefined : overQuota(app.db, user.value, "repos"));
303 if (full) return err(full);
295304
296305 // Refuse a taken slug before anything exists to take back.
297306 // A name the owner already has stays `name_taken`, which createRepo says.
src/actions/make_it_yours.ts +11 −1
@@ -40,6 +40,7 @@ import {
4040 } from "../core/repos.ts";
4141 import { isActive, type User } from "../core/users.ts";
4242 import { err, ok, type Result } from "../kernel/result.ts";
43 import { overQuota, quotaMessage } from "../core/quotas.ts";
4344 import { enableApp } from "./apps.ts";
4445 import { FORKS_PER_DAY, forkRepo } from "./repos.ts";
4546
@@ -68,7 +69,9 @@ export type MakeItYoursError =
6869 | { readonly kind: "own" }
6970 /** Today's copies are made; another may be made from `resetsAt`. */
7071 | { readonly kind: "limit"; readonly resetsAt: string }
71 | { readonly kind: "invalid"; readonly message: string };
72 | { readonly kind: "invalid"; readonly message: string }
73 /** An account quota is full; `message` names the limit and the count. */
74 | { readonly kind: "quota"; readonly message: string };
7275
7376 export const COPIED = ["the code", "its history"] as const;
7477 export const NOT_COPIED = [
@@ -182,6 +185,8 @@ export async function makeItYours(
182185 if (!enabled.ok)
183186 return enabled.error === "unverified"
184187 ? err({ kind: "unverified" })
188 : enabled.error === "quota_apps"
189 ? err({ kind: "quota", message: quotaMessage(app.db, actor, enabled.error) })
185190 : err({
186191 kind: "invalid",
187192 message: `the app could not be registered: ${enabled.error}`,
@@ -203,6 +208,8 @@ export async function makeItYours(
203208 if (dryRun) return ok(plan);
204209 if (copiesLeft === 0)
205210 return err({ kind: "limit", resetsAt: resetsAt(app, actor.id, now) });
211 const full = overQuota(app.db, actor, "repos") ?? overQuota(app.db, actor, "apps");
212 if (full) return err({ kind: "quota", message: quotaMessage(app.db, actor, full) });
206213 // Born with the chosen visibility: the copy never exists as public first.
207214 const forked = await forkRepo(app, actor, source, name, { visibility, now });
208215 if (!forked.ok) {
@@ -220,6 +227,9 @@ export async function makeItYours(
220227 });
221228 case "limit":
222229 return err({ kind: "limit", resetsAt: resetsAt(app, actor.id, now) });
230 case "quota_repos":
231 case "quota_apps":
232 return err({ kind: "quota", message: quotaMessage(app.db, actor, forked.error) });
223233 default:
224234 return err({
225235 kind: "invalid",
src/actions/migrate.ts +3
@@ -196,6 +196,9 @@ export function migrateMessage(error: MigrateError): string {
196196 return "Verify your email first: follow the link we sent, or ask for another under Settings.";
197197 case "refused":
198198 return "New accounts cannot create repositories yet.";
199 case "quota_repos":
200 case "quota_apps":
201 return "You have reached the most repositories one account may own: delete one or ask the owner to raise the limit.";
199202 }
200203 }
201204
src/actions/repos.ts +10 −2
@@ -9,6 +9,7 @@ import type { App } from "../app.ts";
99 import { canSeeSealed } from "../core/sealed.ts";
1010 import { capacityValue } from "../core/capacity.ts";
1111 import { NEW_FOR_MS } from "./accounts.ts";
12 import { overQuota, type QuotaError } from "../core/quotas.ts";
1213 import {
1314 createLabel as insertLabel,
1415 deleteLabel as removeLabel,
@@ -69,7 +70,8 @@ export type CreateRepoActionError =
6970 | CreateRepoError
7071 | "unauthorized"
7172 | "forbidden_owner"
72 | "refused";
73 | "refused"
74 | QuotaError;
7375
7476 /**
7577 * The new-account guard (`guard_new_accounts`): when it is on, an account
@@ -117,6 +119,10 @@ export async function createRepo(
117119 if (!guarded.ok) return guarded;
118120 const ownerId = resolveOwner(app, user.value, input.owner ?? "");
119121 if (ownerId === undefined) return err("forbidden_owner");
122 if (ownerId === user.value.id) {
123 const over = overQuota(app.db, user.value, "repos");
124 if (over) return err(over);
125 }
120126 const created = await initRepo(app.db, app.reposRoot, {
121127 ownerId,
122128 name: input.name,
@@ -148,13 +154,15 @@ export async function forkRepo(
148154 parent: Repo,
149155 name?: string,
150156 options: { visibility?: "public" | "private"; now?: number } = {},
151 ): Promise<Result<Repo, ForkRepoError | "not_found" | "unauthorized" | "unverified" | "refused">> {
157 ): Promise<Result<Repo, ForkRepoError | "not_found" | "unauthorized" | "unverified" | "refused" | QuotaError>> {
152158 const user = requireParticipant(app, actor, parent);
153159 if (!user.ok) return user;
154160 const proven = requireVerified(app, user.value);
155161 if (!proven.ok) return proven;
156162 const guarded = requireNewAccountGuard(app, user.value);
157163 if (!guarded.ok) return guarded;
164 const over = overQuota(app.db, user.value, "repos");
165 if (over) return err(over);
158166 const forked = await cloneRepo(
159167 app.db,
160168 app.reposRoot,
src/core/capacity.ts +17 −1
@@ -21,7 +21,9 @@ export type CapacityKey =
2121 | "checks.shards"
2222 | "children.max"
2323 | "cells.egress"
24 | "guard_new_accounts";
24 | "guard_new_accounts"
25 | "quota.repos"
26 | "quota.apps";
2527
2628 interface Definition {
2729 /** What the settings page and the API call it. */
@@ -80,6 +82,20 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
8082 fallback: "off",
8183 help: "on refuses repository creation and forks for accounts younger than 7 days (agents and admins are exempt); off leaves it to the usual permissions. Takes effect immediately. Replaces the hand-installed database trigger that used to do this with no toggle.",
8284 },
85 "quota.repos": {
86 label: "Repositories per account",
87 env: "FORGE_QUOTA_REPOS",
88 kind: { type: "count", min: 1, max: 100000 },
89 fallback: "10",
90 help: "Most repositories (forks and copies included) one account may own. Admins and agents are not limited. Checked before each is created.",
91 },
92 "quota.apps": {
93 label: "Apps per account",
94 env: "FORGE_QUOTA_APPS",
95 kind: { type: "count", min: 1, max: 100000 },
96 fallback: "10",
97 help: "Most apps one account may own. Admins and agents are not limited. Checked before each is created.",
98 },
8399 };
84100
85101 export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[];
src/core/quotas.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Per-account quotas: how many repositories and apps one account may own.
3 * The limits are capacity settings (`core/capacity.ts`), so the owner changes
4 * them live from Settings → Capacity or `PATCH /api/v1/admin/settings`, and
5 * every change is kept in the same audit. #918 (previews, runs, checks) and
6 * #919 (storage) add their keys to `QUOTAS` and call `overQuota` the same way.
7 *
8 * Counts are read at the moment of creating, never cached. Forge admins and
9 * agents are not limited: admins run the forge, and an agent owns nothing it
10 * was not given. Pure data; the actions call it before they create anything.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { bootDefault, capacityCount, type CapacityKey } from "./capacity.ts";
15 import type { User } from "./users.ts";
16
17 export type QuotaKind = "repos" | "apps";
18
19 interface Quota {
20 readonly key: CapacityKey;
21 readonly noun: string;
22 readonly fallback: number;
23 }
24
25 export const QUOTAS: Record<QuotaKind, Quota> = {
26 repos: { key: "quota.repos", noun: "repositories", fallback: 10 },
27 apps: { key: "quota.apps", noun: "apps", fallback: 10 },
28 };
29
30 /** The error codes an action returns when a quota stops it. */
31 export type QuotaError = "quota_repos" | "quota_apps";
32
33 export const isQuotaError = (e: unknown): e is QuotaError =>
34 e === "quota_repos" || e === "quota_apps";
35
36 /** What `kind` is now for everyone: an admin's setting, else the default. */
37 export function quotaLimit(db: Database, kind: QuotaKind): number {
38 const { key, fallback } = QUOTAS[kind];
39 return capacityCount(db, key, Number(bootDefault(db, key)) || fallback);
40 }
41
42 /** How many of `kind` the account owns now. Sealed work copies are not its own. */
43 export function quotaUsed(db: Database, userId: string, kind: QuotaKind): number {
44 const sql =
45 kind === "repos"
46 ? `SELECT COUNT(*) AS n FROM repo WHERE owner_id = ?1 AND sealed_for IS NULL`
47 : `SELECT COUNT(*) AS n FROM app a JOIN repo r ON r.id = a.repo_id WHERE r.owner_id = ?1`;
48 return db.query<{ n: number }, [string]>(sql).get(userId)?.n ?? 0;
49 }
50
51 /** Whether the account is held to quotas at all. */
52 export const quotaApplies = (user: User): boolean =>
53 !user.isAdmin && user.kind !== "agent";
54
55 /** The error to refuse with when creating one more `kind` would pass the limit. */
56 export function overQuota(
57 db: Database,
58 user: User,
59 kind: QuotaKind,
60 ): QuotaError | undefined {
61 if (!quotaApplies(user)) return undefined;
62 return quotaUsed(db, user.id, kind) >= quotaLimit(db, kind)
63 ? (`quota_${kind}` as QuotaError)
64 : undefined;
65 }
66
67 /** The plain sentence that names the limit and the count: "10 of 10 repositories". */
68 export function quotaMessage(db: Database, user: User, error: QuotaError): string {
69 const kind: QuotaKind = error === "quota_repos" ? "repos" : "apps";
70 const limit = quotaLimit(db, kind);
71 return `you have ${Math.min(quotaUsed(db, user.id, kind), limit)} of ${limit} ${QUOTAS[kind].noun}, the most one account may have: delete one or ask the owner to raise the limit`;
72 }
src/http/api.ts +33 −4
@@ -21,6 +21,8 @@ import { bodyCapFor, readBounded } from "./limits.ts";
2121 import { askCheck } from "../checks/again.ts";
2222 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2323 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
24 import { isCapacityKey, validCapacity } from "../core/capacity.ts";
25
2426 import { changeLimit, listLimits } from "../actions/limits.ts";
2527 import {
2628 accountSignIns,
@@ -349,6 +351,7 @@ import {
349351 requireAccount,
350352 requireScope,
351353 respondAccess,
354 respondRefusal,
352355 str,
353356 unauthorized,
354357 } from "./respond.ts";
@@ -1406,6 +1409,30 @@ export function apiRoutes(router: Router<Handler>): void {
14061409 );
14071410 });
14081411
1412 // The same settings in one call: `{ "quota.repos": "20", … }`. Every key is
1413 // checked before any is stored, so a bad one changes nothing.
1414 router.add("PATCH", "/api/v1/admin/settings", async (ctx) => {
1415 const denied = accountAdmin(ctx, "admin");
1416 if (denied) return denied;
1417 const input = await body(ctx.request);
1418 const entries = Object.entries(input);
1419 if (entries.length === 0 || entries.length > 20)
1420 return apiError("invalid_value", 422, "send between one and twenty settings");
1421 for (const [key, raw] of entries) {
1422 const value = raw === null ? "" : typeof raw === "number" ? String(raw) : raw;
1423 if (!isCapacityKey(key))
1424 return apiError("no_such_setting", 422, `no such setting: ${key}`);
1425 if (typeof value !== "string" || (value.trim() !== "" && !validCapacity(key, value.trim())))
1426 return apiError("invalid_value", 422, `that value is outside what ${key} takes`);
1427 }
1428 const changes = entries.map(([key, raw]) => {
1429 const value = raw === null ? null : String(raw);
1430 const done = changeCapacity(ctx.app, ctx.auth.user, key, value);
1431 return done.ok ? done.value : undefined;
1432 });
1433 return json({ changes: changes.filter((c) => c !== undefined) });
1434 });
1435
14091436 // The forge's limits (`settings/limits.ts`): the same door as capacity.
14101437 router.add("GET", "/api/v1/admin/limits", (ctx) => {
14111438 const denied = accountAdmin(ctx, "ro");
@@ -1801,7 +1828,7 @@ export function apiRoutes(router: Router<Handler>): void {
18011828 if (!created.ok) {
18021829 if (created.error === "forbidden_owner")
18031830 return json({ error: "forbidden_owner" }, 403);
1804 return respondAccess(created.error, 422);
1831 return respondRefusal(ctx.app, ctx.auth.user, created.error, 422);
18051832 }
18061833 return json(created.value, 201);
18071834 });
@@ -1904,7 +1931,7 @@ export function apiRoutes(router: Router<Handler>): void {
19041931 if (!forked.ok)
19051932 return forked.error === "limit"
19061933 ? apiError("limit", 429, `at most ${FORKS_PER_DAY} forks a day: try again tomorrow`)
1907 : respondAccess(forked.error, 422);
1934 : respondRefusal(ctx.app, ctx.auth.user, forked.error, 422);
19081935 return json(forked.value, 201);
19091936 });
19101937
@@ -4185,6 +4212,8 @@ export function apiRoutes(router: Router<Handler>): void {
41854212 },
41864213 429,
41874214 )
4215 : made.error.kind === "quota"
4216 ? apiError("quota", 403, made.error.message)
41884217 : made.error.kind === "invalid"
41894218 ? apiError("invalid", 422, made.error.message)
41904219 : made.error.kind === "own"
@@ -4313,7 +4342,7 @@ export function apiRoutes(router: Router<Handler>): void {
43134342 : {}),
43144343 ...(typeof input.agent === "string" ? { agent: input.agent } : {}),
43154344 });
4316 if (!made.ok) return respondAccess(made.error, 422);
4345 if (!made.ok) return respondRefusal(ctx.app, ctx.auth.user, made.error, 422);
43174346 return json(
43184347 {
43194348 repo: repoJson(ctx, made.value.repo),
@@ -4423,7 +4452,7 @@ export function apiRoutes(router: Router<Handler>): void {
44234452 if (!repo) return notFound();
44244453 const input = await body(ctx.request);
44254454 const enabled = enableApp(ctx.app, ctx.auth.user, repo, appPatch(input));
4426 if (!enabled.ok) return respondAccess(enabled.error, 422);
4455 if (!enabled.ok) return respondRefusal(ctx.app, ctx.auth.user, enabled.error, 422);
44274456 return json(
44284457 appJson(ctx, enabled.value, repo, appsRuntime(ctx.app)),
44294458 201,
src/http/mcp.ts +1 −1
@@ -2015,7 +2015,7 @@ const TOOLS: readonly Tool[] = [
20152015 properties: {
20162016 key: {
20172017 type: "string",
2018 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
2018 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts", "quota.repos", "quota.apps"],
20192019 },
20202020 value: { type: "string", maxLength: 16 },
20212021 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
src/http/respond.ts +17
@@ -7,6 +7,8 @@
77 import { bodyCapFor, readBounded } from "./limits.ts";
88 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
99 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts";
10 import { isQuotaError, quotaMessage } from "../core/quotas.ts";
11 import type { App } from "../app.ts";
1012 import type { User } from "../core/users.ts";
1113 import { crossOrigin, type Ctx } from "./context.ts";
1214
@@ -159,6 +161,21 @@ export function respondAccess(error: string, status: number): Response {
159161 return json({ error }, status);
160162 }
161163
164 /**
165 * `respondAccess`, with an account quota refused in its own words: 403, the
166 * limit and the count ("10 of 10 repositories"), for the API and MCP alike.
167 */
168 export function respondRefusal(
169 app: App,
170 actor: User | undefined,
171 error: string,
172 status: number,
173 ): Response {
174 if (actor && isQuotaError(error))
175 return json({ error: "quota", message: quotaMessage(app.db, actor, error) }, 403);
176 return respondAccess(error, status);
177 }
178
162179 /** Bytes as a JSON object, or `{}` for anything else — malformed input is not a 500. */
163180 function asObject(bytes: Uint8Array): Record<string, unknown> {
164181 let value: unknown;
src/web/pages/apps.ts +4 −1
@@ -12,6 +12,7 @@
1212 * 404 for everyone.
1313 */
1414
15 import { quotaMessage } from "../../core/quotas.ts";
1516 import {
1617 appView,
1718 newApp,
@@ -413,7 +414,9 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
413414 body: newAppForm(
414415 ctx,
415416 values,
416 NEW_APP_ERRORS[made.error] ?? "That app could not be created.",
417 made.error === "quota_apps" || made.error === "quota_repos"
418 ? `${quotaMessage(ctx.app.db, ctx.auth.user, made.error)}.`
419 : (NEW_APP_ERRORS[made.error] ?? "That app could not be created."),
417420 ),
418421 scriptJs: appNameJs,
419422 },
src/web/pages/repo.ts +3
@@ -8,6 +8,7 @@
88 * path segment and can never smuggle a path of its own.
99 */
1010
11 import { quotaMessage } from "../../core/quotas.ts";
1112 import { canRead, listForks, type Repo } from "../../core/repos.ts";
1213 import { FORKS_PER_DAY, forkRepo } from "../../actions/repos.ts";
1314 import { forkDrift, takeUpdates, type ForkDrift } from "../../actions/forks.ts";
@@ -195,6 +196,8 @@ export async function forkSubmit(ctx: Ctx): Promise<Response> {
195196 const reason =
196197 forked.error === "name_taken"
197198 ? "You already have a repository by that name."
199 : forked.error === "quota_repos"
200 ? `Not forked: ${quotaMessage(ctx.app.db, ctx.auth.user!, forked.error)}.`
198201 : forked.error === "limit"
199202 ? `That is today's forks made (${FORKS_PER_DAY} a day). Try again tomorrow.`
200203 : "That fork could not be created.";
src/web/pages/settings.ts +4 −1
@@ -8,6 +8,7 @@
88 * same-origin POST and every one of them says what happened.
99 */
1010
11 import { quotaMessage } from "../../core/quotas.ts";
1112 import {
1213 deleteAppEnvVar,
1314 disableApp,
@@ -829,7 +830,9 @@ export async function appSettingsUpdate(ctx: Ctx): Promise<Response> {
829830 repo,
830831 record,
831832 values,
832 APP_ERRORS[saved.error] ?? "Those settings could not be saved.",
833 saved.error === "quota_apps"
834 ? `${quotaMessage(ctx.app.db, ctx.auth.user!, saved.error)}.`
835 : (APP_ERRORS[saved.error] ?? "Those settings could not be saved."),
833836 ),
834837 undefined,
835838 422,
src/web/pages/site.ts +4
@@ -8,6 +8,9 @@
88 * typed still in it. A dead end that loses input is a bug, not a message.
99 */
1010
11 import { quotaMessage } from "../../core/quotas.ts";
12 import { mayView } from "../../core/sealed.ts";
13
1114 import { limitValue } from "../../settings/limits.ts";
1215 import { signOutHere } from "../../actions/signins.ts";
1316 import { clientAddress } from "../../http/peer.ts";
@@ -689,6 +692,7 @@ export async function newRepoSubmit(ctx: Ctx): Promise<Response> {
689692 if (created.error === "forbidden_owner" || created.error === "unauthorized")
690693 return new Response("forbidden", { status: 403 });
691694 const messages: Record<string, string> = {
695 quota_repos: quotaMessage(ctx.app.db, ctx.auth.user, "quota_repos"),
692696 name_taken: "That owner already has a repository by that name.",
693697 invalid_name: "Names start with a letter or digit; no spaces, no .git.",
694698 git_init_failed: "The repository could not be initialised on disk.",
src/web/studio/make_it_yours.ts +2
@@ -128,6 +128,8 @@ export async function makeItYoursSubmit(ctx: Ctx): Promise<Response> {
128128 const message = !made.ok
129129 ? made.error.kind === "invalid"
130130 ? made.error.message
131 : made.error.kind === "quota"
132 ? `${made.error.message}.`
131133 : made.error.kind === "own"
132134 ? "This app is already yours."
133135 : made.error.kind === "unverified"
test/quotas.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * Per-account quotas on repositories and apps (#973): the count is checked
3 * before anything is created and the refusal names the limit and the count.
4 * A fresh account is refused past the limit — by repository, fork, copy and
5 * app, and on the API — while a forge admin is not; the owner changes the
6 * limits live, and each change is audited.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { enableApp, newApp } from "../src/actions/apps.ts";
15 import { createRepo, forkRepo } from "../src/actions/repos.ts";
16 import { capacityChanges } from "../src/core/capacity.ts";
17 import { quotaMessage, quotaUsed } from "../src/core/quotas.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21
22 describe("quotas: repositories and apps per account", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let owner: User;
27 let fresh: User;
28 let ownerToken: string;
29 let freshToken: string;
30
31 const api = (token: string, method: string, path: string, body?: unknown) =>
32 fetch(`${servers.url}/api/v1${path}`, {
33 method,
34 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
35 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
36 });
37 const setLimits = (repos: string, apps: string) =>
38 api(ownerToken, "PATCH", "/admin/settings", { "quota.repos": repos, "quota.apps": apps });
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-quotas-"));
42 app = createApp({ dataDir, port: 0 });
43 servers = await serve(app);
44 const o = await createUser(app.db, {
45 trusted: true, username: "boss", email: "[email protected]",
46 password: "a-good-passphrase", adminIfFirst: true,
47 });
48 if (!o.ok) throw new Error(o.error);
49 owner = o.value;
50 const f = await createUser(app.db, {
51 trusted: true, username: "fresh", email: "[email protected]",
52 password: "a-good-passphrase",
53 });
54 if (!f.ok) throw new Error(f.error);
55 fresh = f.value;
56 ownerToken = createToken(app.db, owner.id, "t", "admin").token;
57 freshToken = createToken(app.db, fresh.id, "t", "rw").token;
58 });
59
60 afterAll(async () => {
61 servers.stop();
62 app.close();
63 await rm(dataDir, { recursive: true, force: true });
64 });
65
66 test("a fresh account is refused past the repository limit; the owner is not", async () => {
67 expect((await setLimits("2", "1")).status).toBe(200);
68 for (const name of ["one", "two"])
69 expect((await createRepo(app, fresh, { name })).ok).toBe(true);
70 const refused = await createRepo(app, fresh, { name: "three" });
71 expect(refused).toEqual({ ok: false, error: "quota_repos" });
72 expect(quotaMessage(app.db, fresh, "quota_repos")).toContain("2 of 2 repositories");
73 expect(quotaUsed(app.db, fresh.id, "repos")).toBe(2);
74
75 const res = await api(freshToken, "POST", "/repos", { name: "three" });
76 expect(res.status).toBe(403);
77 const body = (await res.json()) as { error: string; message: string };
78 expect(body.error).toBe("quota");
79 expect(body.message).toContain("2 of 2 repositories");
80
81 for (const name of ["a", "b", "c"])
82 expect((await createRepo(app, owner, { name })).ok).toBe(true);
83 });
84
85 test("a fork counts as a repository", async () => {
86 const parent = await createRepo(app, owner, { name: "parent", visibility: "public" });
87 if (!parent.ok) throw new Error(parent.error);
88 const forked = await forkRepo(app, fresh, parent.value);
89 expect(forked).toEqual({ ok: false, error: "quota_repos" });
90 const res = await api(freshToken, "POST", "/repos/boss/parent/forks", {});
91 expect(res.status).toBe(403);
92 expect(((await res.json()) as { message: string }).message).toContain("2 of 2 repositories");
93 });
94
95 test("a fresh account is refused past the app limit; the owner is not", async () => {
96 await setLimits("10", "1");
97 const one = await newApp(app, fresh, { name: "first-app" });
98 expect(one.ok).toBe(true);
99 const refused = await newApp(app, fresh, { name: "second-app" });
100 expect(refused).toEqual({ ok: false, error: "quota_apps" });
101 // Nothing was made to take back.
102 expect(quotaUsed(app.db, fresh.id, "repos")).toBe(3);
103
104 const spare = await createRepo(app, fresh, { name: "spare" });
105 if (!spare.ok) throw new Error(spare.error);
106 const enabled = enableApp(app, fresh, spare.value);
107 expect(enabled).toEqual({ ok: false, error: "quota_apps" });
108 expect(quotaMessage(app.db, fresh, "quota_apps")).toContain("1 of 1 apps");
109
110 const res = await api(freshToken, "POST", "/apps", { name: "third-app" });
111 expect(res.status).toBe(403);
112 expect(((await res.json()) as { message: string }).message).toContain("1 of 1 apps");
113
114 expect((await newApp(app, owner, { name: "owner-one" })).ok).toBe(true);
115 expect((await newApp(app, owner, { name: "owner-two" })).ok).toBe(true);
116 }, 30_000);
117
118 test("raising the limit makes room, and each change is audited", async () => {
119 expect((await setLimits("10", "5")).status).toBe(200);
120 expect((await newApp(app, fresh, { name: "second-app" })).ok).toBe(true);
121 const keys = capacityChanges(app.db).map((c) => c.key);
122 expect(keys).toContain("quota.repos");
123 expect(keys).toContain("quota.apps");
124 }, 30_000);
125
126 test("only the owner changes limits, and a bad value changes nothing", async () => {
127 expect((await api(freshToken, "PATCH", "/admin/settings", { "quota.repos": "99" })).status).toBe(404);
128 const bad = await api(ownerToken, "PATCH", "/admin/settings", {
129 "quota.apps": "7",
130 "quota.repos": "zero",
131 });
132 expect(bad.status).toBe(422);
133 const nope = await api(ownerToken, "PATCH", "/admin/settings", { "quota.nothing": "1" });
134 expect(nope.status).toBe(422);
135 const after = await newApp(app, fresh, { name: "third-app" });
136 expect(after.ok).toBe(true);
137 }, 30_000);
138 });
test/studio-changes.test.ts +3
@@ -12,6 +12,7 @@ import { dirname, join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { enableApp } from "../src/actions/apps.ts";
1414 import { getAppByRepo } from "../src/core/apps.ts";
15 import { setCapacity } from "../src/core/capacity.ts";
1516 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1617 import {
1718 assignIssue,
@@ -1183,6 +1184,8 @@ describe("the studio, continued", () => {
11831184 });
11841185 if (!made.ok) throw new Error(made.error);
11851186 const pia = made.value;
1187 // This test is about the door, not the per-account repository limit.
1188 setCapacity(app2.db, "quota.repos", "100", pia.id);
11861189 const appOf = async (name: string) => {
11871190 const created = await createRepo(app2, pia, {
11881191 name,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs