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
scout/forge:scout/973-per-account-limits-on-repositories-and-a → main 5 commits fork
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. | ||
| 1095 | 1095 | | `FORGE_APPS_CONCURRENCY` | `2` | deploys running their heavy steps at once | |
| 1096 | 1096 | | `FORGE_PREVIEW_IDLE_DAYS` | `3` | days a pull may sit untouched before its preview sleeps; `0` = never | |
| 1097 | 1097 | | `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`) | | |
| 1098 | 1099 | | `FORGE_CHECKS_CONCURRENCY` | `1` | checks at once (live: Settings → Capacity) | |
| 1099 | 1100 | | `FORGE_CHECKS_PLACEMENT` | `process` | `job` runs a check's commands as a cluster Job (see Placement above) | |
| 1100 | 1101 | | `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[] = [ | ||
| 147 | 147 | "test/decide.test.ts", |
| 148 | 148 | "test/ledger.test.ts", |
| 149 | 149 | "test/capacity.test.ts", |
| 150 | "test/quotas.test.ts", | |
| 151 | ||
| 150 | 152 | "test/access-log.test.ts", |
| 151 | 153 | "test/flow-pipeline.test.ts", |
| 152 | 154 | "test/flow-throughput.test.ts", |
src/actions/apps.ts +11 −2
| @@ -59,6 +59,7 @@ import { | ||
| 59 | 59 | requireWriter, |
| 60 | 60 | type AccessError, |
| 61 | 61 | } from "./access.ts"; |
| 62 | import { overQuota, type QuotaError } from "../core/quotas.ts"; | |
| 62 | 63 | import { assignIssue, openIssue } from "./issues.ts"; |
| 63 | 64 | import { |
| 64 | 65 | commitToBranch, |
| @@ -79,11 +80,13 @@ export function enableApp( | ||
| 79 | 80 | actor: User | undefined, |
| 80 | 81 | repo: Repo, |
| 81 | 82 | input: AppSettingsInput = {}, |
| 82 | ): Result<AppRecord, "not_found" | CreateAppError | "unverified"> { | |
| 83 | ): Result<AppRecord, "not_found" | CreateAppError | "unverified" | QuotaError> { | |
| 83 | 84 | const admin = requireRepoAdmin(app, actor, repo); |
| 84 | 85 | if (!admin.ok) return admin; |
| 85 | 86 | const proven = requireVerified(app, admin.value); |
| 86 | 87 | if (!proven.ok) return proven; |
| 88 | const over = overQuota(app.db, admin.value, "apps"); | |
| 89 | if (over) return err(over); | |
| 87 | 90 | const created = insertApp(app.db, { |
| 88 | 91 | repoId: repo.id, |
| 89 | 92 | slug: input.slug ?? slugFor(repo.name), |
| @@ -271,7 +274,8 @@ export type NewAppError = | ||
| 271 | 274 | | CreateRepoActionError |
| 272 | 275 | | CreateAppError |
| 273 | 276 | | "scaffold_failed" |
| 274 | | "no_such_agent"; | |
| 277 | | "no_such_agent" | |
| 278 | | QuotaError; | |
| 275 | 279 | |
| 276 | 280 | /** |
| 277 | 281 | * The golden path's first step, as one call: a repository with a working |
| @@ -292,6 +296,11 @@ export async function newApp( | ||
| 292 | 296 | ? undefined |
| 293 | 297 | : getAgentByName(app.db, input.agent); |
| 294 | 298 | 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); | |
| 295 | 304 | |
| 296 | 305 | // Refuse a taken slug before anything exists to take back. |
| 297 | 306 | // 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 { | ||
| 40 | 40 | } from "../core/repos.ts"; |
| 41 | 41 | import { isActive, type User } from "../core/users.ts"; |
| 42 | 42 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 43 | import { overQuota, quotaMessage } from "../core/quotas.ts"; | |
| 43 | 44 | import { enableApp } from "./apps.ts"; |
| 44 | 45 | import { FORKS_PER_DAY, forkRepo } from "./repos.ts"; |
| 45 | 46 | |
| @@ -68,7 +69,9 @@ export type MakeItYoursError = | ||
| 68 | 69 | | { readonly kind: "own" } |
| 69 | 70 | /** Today's copies are made; another may be made from `resetsAt`. */ |
| 70 | 71 | | { 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 }; | |
| 72 | 75 | |
| 73 | 76 | export const COPIED = ["the code", "its history"] as const; |
| 74 | 77 | export const NOT_COPIED = [ |
| @@ -182,6 +185,8 @@ export async function makeItYours( | ||
| 182 | 185 | if (!enabled.ok) |
| 183 | 186 | return enabled.error === "unverified" |
| 184 | 187 | ? err({ kind: "unverified" }) |
| 188 | : enabled.error === "quota_apps" | |
| 189 | ? err({ kind: "quota", message: quotaMessage(app.db, actor, enabled.error) }) | |
| 185 | 190 | : err({ |
| 186 | 191 | kind: "invalid", |
| 187 | 192 | message: `the app could not be registered: ${enabled.error}`, |
| @@ -203,6 +208,8 @@ export async function makeItYours( | ||
| 203 | 208 | if (dryRun) return ok(plan); |
| 204 | 209 | if (copiesLeft === 0) |
| 205 | 210 | 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) }); | |
| 206 | 213 | // Born with the chosen visibility: the copy never exists as public first. |
| 207 | 214 | const forked = await forkRepo(app, actor, source, name, { visibility, now }); |
| 208 | 215 | if (!forked.ok) { |
| @@ -220,6 +227,9 @@ export async function makeItYours( | ||
| 220 | 227 | }); |
| 221 | 228 | case "limit": |
| 222 | 229 | 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) }); | |
| 223 | 233 | default: |
| 224 | 234 | return err({ |
| 225 | 235 | kind: "invalid", |
src/actions/migrate.ts +3
| @@ -196,6 +196,9 @@ export function migrateMessage(error: MigrateError): string { | ||
| 196 | 196 | return "Verify your email first: follow the link we sent, or ask for another under Settings."; |
| 197 | 197 | case "refused": |
| 198 | 198 | 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."; | |
| 199 | 202 | } |
| 200 | 203 | } |
| 201 | 204 |
src/actions/repos.ts +10 −2
| @@ -9,6 +9,7 @@ import type { App } from "../app.ts"; | ||
| 9 | 9 | import { canSeeSealed } from "../core/sealed.ts"; |
| 10 | 10 | import { capacityValue } from "../core/capacity.ts"; |
| 11 | 11 | import { NEW_FOR_MS } from "./accounts.ts"; |
| 12 | import { overQuota, type QuotaError } from "../core/quotas.ts"; | |
| 12 | 13 | import { |
| 13 | 14 | createLabel as insertLabel, |
| 14 | 15 | deleteLabel as removeLabel, |
| @@ -69,7 +70,8 @@ export type CreateRepoActionError = | ||
| 69 | 70 | | CreateRepoError |
| 70 | 71 | | "unauthorized" |
| 71 | 72 | | "forbidden_owner" |
| 72 | | "refused"; | |
| 73 | | "refused" | |
| 74 | | QuotaError; | |
| 73 | 75 | |
| 74 | 76 | /** |
| 75 | 77 | * The new-account guard (`guard_new_accounts`): when it is on, an account |
| @@ -117,6 +119,10 @@ export async function createRepo( | ||
| 117 | 119 | if (!guarded.ok) return guarded; |
| 118 | 120 | const ownerId = resolveOwner(app, user.value, input.owner ?? ""); |
| 119 | 121 | 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 | } | |
| 120 | 126 | const created = await initRepo(app.db, app.reposRoot, { |
| 121 | 127 | ownerId, |
| 122 | 128 | name: input.name, |
| @@ -148,13 +154,15 @@ export async function forkRepo( | ||
| 148 | 154 | parent: Repo, |
| 149 | 155 | name?: string, |
| 150 | 156 | 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>> { | |
| 152 | 158 | const user = requireParticipant(app, actor, parent); |
| 153 | 159 | if (!user.ok) return user; |
| 154 | 160 | const proven = requireVerified(app, user.value); |
| 155 | 161 | if (!proven.ok) return proven; |
| 156 | 162 | const guarded = requireNewAccountGuard(app, user.value); |
| 157 | 163 | if (!guarded.ok) return guarded; |
| 164 | const over = overQuota(app.db, user.value, "repos"); | |
| 165 | if (over) return err(over); | |
| 158 | 166 | const forked = await cloneRepo( |
| 159 | 167 | app.db, |
| 160 | 168 | app.reposRoot, |
src/core/capacity.ts +17 −1
| @@ -21,7 +21,9 @@ export type CapacityKey = | ||
| 21 | 21 | | "checks.shards" |
| 22 | 22 | | "children.max" |
| 23 | 23 | | "cells.egress" |
| 24 | | "guard_new_accounts"; | |
| 24 | | "guard_new_accounts" | |
| 25 | | "quota.repos" | |
| 26 | | "quota.apps"; | |
| 25 | 27 | |
| 26 | 28 | interface Definition { |
| 27 | 29 | /** What the settings page and the API call it. */ |
| @@ -80,6 +82,20 @@ export const CAPACITY: Record<CapacityKey, Definition> = { | ||
| 80 | 82 | fallback: "off", |
| 81 | 83 | 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.", |
| 82 | 84 | }, |
| 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 | }, | |
| 83 | 99 | }; |
| 84 | 100 | |
| 85 | 101 | 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"; | ||
| 21 | 21 | import { askCheck } from "../checks/again.ts"; |
| 22 | 22 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 23 | 23 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 24 | import { isCapacityKey, validCapacity } from "../core/capacity.ts"; | |
| 25 | ||
| 24 | 26 | import { changeLimit, listLimits } from "../actions/limits.ts"; |
| 25 | 27 | import { |
| 26 | 28 | accountSignIns, |
| @@ -349,6 +351,7 @@ import { | ||
| 349 | 351 | requireAccount, |
| 350 | 352 | requireScope, |
| 351 | 353 | respondAccess, |
| 354 | respondRefusal, | |
| 352 | 355 | str, |
| 353 | 356 | unauthorized, |
| 354 | 357 | } from "./respond.ts"; |
| @@ -1406,6 +1409,30 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1406 | 1409 | ); |
| 1407 | 1410 | }); |
| 1408 | 1411 | |
| 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 | ||
| 1409 | 1436 | // The forge's limits (`settings/limits.ts`): the same door as capacity. |
| 1410 | 1437 | router.add("GET", "/api/v1/admin/limits", (ctx) => { |
| 1411 | 1438 | const denied = accountAdmin(ctx, "ro"); |
| @@ -1801,7 +1828,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1801 | 1828 | if (!created.ok) { |
| 1802 | 1829 | if (created.error === "forbidden_owner") |
| 1803 | 1830 | return json({ error: "forbidden_owner" }, 403); |
| 1804 | return respondAccess(created.error, 422); | |
| 1831 | return respondRefusal(ctx.app, ctx.auth.user, created.error, 422); | |
| 1805 | 1832 | } |
| 1806 | 1833 | return json(created.value, 201); |
| 1807 | 1834 | }); |
| @@ -1904,7 +1931,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1904 | 1931 | if (!forked.ok) |
| 1905 | 1932 | return forked.error === "limit" |
| 1906 | 1933 | ? 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); | |
| 1908 | 1935 | return json(forked.value, 201); |
| 1909 | 1936 | }); |
| 1910 | 1937 | |
| @@ -4185,6 +4212,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4185 | 4212 | }, |
| 4186 | 4213 | 429, |
| 4187 | 4214 | ) |
| 4215 | : made.error.kind === "quota" | |
| 4216 | ? apiError("quota", 403, made.error.message) | |
| 4188 | 4217 | : made.error.kind === "invalid" |
| 4189 | 4218 | ? apiError("invalid", 422, made.error.message) |
| 4190 | 4219 | : made.error.kind === "own" |
| @@ -4313,7 +4342,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4313 | 4342 | : {}), |
| 4314 | 4343 | ...(typeof input.agent === "string" ? { agent: input.agent } : {}), |
| 4315 | 4344 | }); |
| 4316 | if (!made.ok) return respondAccess(made.error, 422); | |
| 4345 | if (!made.ok) return respondRefusal(ctx.app, ctx.auth.user, made.error, 422); | |
| 4317 | 4346 | return json( |
| 4318 | 4347 | { |
| 4319 | 4348 | repo: repoJson(ctx, made.value.repo), |
| @@ -4423,7 +4452,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4423 | 4452 | if (!repo) return notFound(); |
| 4424 | 4453 | const input = await body(ctx.request); |
| 4425 | 4454 | 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); | |
| 4427 | 4456 | return json( |
| 4428 | 4457 | appJson(ctx, enabled.value, repo, appsRuntime(ctx.app)), |
| 4429 | 4458 | 201, |
src/http/mcp.ts +1 −1
| @@ -2015,7 +2015,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 2015 | 2015 | properties: { |
| 2016 | 2016 | key: { |
| 2017 | 2017 | 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"], | |
| 2019 | 2019 | }, |
| 2020 | 2020 | value: { type: "string", maxLength: 16 }, |
| 2021 | 2021 | dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." }, |
src/http/respond.ts +17
| @@ -7,6 +7,8 @@ | ||
| 7 | 7 | import { bodyCapFor, readBounded } from "./limits.ts"; |
| 8 | 8 | import { scopeAllows, type TokenScope } from "../core/tokens.ts"; |
| 9 | 9 | import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts"; |
| 10 | import { isQuotaError, quotaMessage } from "../core/quotas.ts"; | |
| 11 | import type { App } from "../app.ts"; | |
| 10 | 12 | import type { User } from "../core/users.ts"; |
| 11 | 13 | import { crossOrigin, type Ctx } from "./context.ts"; |
| 12 | 14 | |
| @@ -159,6 +161,21 @@ export function respondAccess(error: string, status: number): Response { | ||
| 159 | 161 | return json({ error }, status); |
| 160 | 162 | } |
| 161 | 163 | |
| 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 | ||
| 162 | 179 | /** Bytes as a JSON object, or `{}` for anything else — malformed input is not a 500. */ |
| 163 | 180 | function asObject(bytes: Uint8Array): Record<string, unknown> { |
| 164 | 181 | let value: unknown; |
src/web/pages/apps.ts +4 −1
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | * 404 for everyone. |
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | import { quotaMessage } from "../../core/quotas.ts"; | |
| 15 | 16 | import { |
| 16 | 17 | appView, |
| 17 | 18 | newApp, |
| @@ -413,7 +414,9 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> { | ||
| 413 | 414 | body: newAppForm( |
| 414 | 415 | ctx, |
| 415 | 416 | 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."), | |
| 417 | 420 | ), |
| 418 | 421 | scriptJs: appNameJs, |
| 419 | 422 | }, |
src/web/pages/repo.ts +3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * path segment and can never smuggle a path of its own. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { quotaMessage } from "../../core/quotas.ts"; | |
| 11 | 12 | import { canRead, listForks, type Repo } from "../../core/repos.ts"; |
| 12 | 13 | import { FORKS_PER_DAY, forkRepo } from "../../actions/repos.ts"; |
| 13 | 14 | import { forkDrift, takeUpdates, type ForkDrift } from "../../actions/forks.ts"; |
| @@ -195,6 +196,8 @@ export async function forkSubmit(ctx: Ctx): Promise<Response> { | ||
| 195 | 196 | const reason = |
| 196 | 197 | forked.error === "name_taken" |
| 197 | 198 | ? "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)}.` | |
| 198 | 201 | : forked.error === "limit" |
| 199 | 202 | ? `That is today's forks made (${FORKS_PER_DAY} a day). Try again tomorrow.` |
| 200 | 203 | : "That fork could not be created."; |
src/web/pages/settings.ts +4 −1
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * same-origin POST and every one of them says what happened. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { quotaMessage } from "../../core/quotas.ts"; | |
| 11 | 12 | import { |
| 12 | 13 | deleteAppEnvVar, |
| 13 | 14 | disableApp, |
| @@ -829,7 +830,9 @@ export async function appSettingsUpdate(ctx: Ctx): Promise<Response> { | ||
| 829 | 830 | repo, |
| 830 | 831 | record, |
| 831 | 832 | 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."), | |
| 833 | 836 | ), |
| 834 | 837 | undefined, |
| 835 | 838 | 422, |
src/web/pages/site.ts +4
| @@ -8,6 +8,9 @@ | ||
| 8 | 8 | * typed still in it. A dead end that loses input is a bug, not a message. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { quotaMessage } from "../../core/quotas.ts"; | |
| 12 | import { mayView } from "../../core/sealed.ts"; | |
| 13 | ||
| 11 | 14 | import { limitValue } from "../../settings/limits.ts"; |
| 12 | 15 | import { signOutHere } from "../../actions/signins.ts"; |
| 13 | 16 | import { clientAddress } from "../../http/peer.ts"; |
| @@ -689,6 +692,7 @@ export async function newRepoSubmit(ctx: Ctx): Promise<Response> { | ||
| 689 | 692 | if (created.error === "forbidden_owner" || created.error === "unauthorized") |
| 690 | 693 | return new Response("forbidden", { status: 403 }); |
| 691 | 694 | const messages: Record<string, string> = { |
| 695 | quota_repos: quotaMessage(ctx.app.db, ctx.auth.user, "quota_repos"), | |
| 692 | 696 | name_taken: "That owner already has a repository by that name.", |
| 693 | 697 | invalid_name: "Names start with a letter or digit; no spaces, no .git.", |
| 694 | 698 | 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> { | ||
| 128 | 128 | const message = !made.ok |
| 129 | 129 | ? made.error.kind === "invalid" |
| 130 | 130 | ? made.error.message |
| 131 | : made.error.kind === "quota" | |
| 132 | ? `${made.error.message}.` | |
| 131 | 133 | : made.error.kind === "own" |
| 132 | 134 | ? "This app is already yours." |
| 133 | 135 | : 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"; | ||
| 12 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 13 | 13 | import { enableApp } from "../src/actions/apps.ts"; |
| 14 | 14 | import { getAppByRepo } from "../src/core/apps.ts"; |
| 15 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 15 | 16 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; |
| 16 | 17 | import { |
| 17 | 18 | assignIssue, |
| @@ -1183,6 +1184,8 @@ describe("the studio, continued", () => { | ||
| 1183 | 1184 | }); |
| 1184 | 1185 | if (!made.ok) throw new Error(made.error); |
| 1185 | 1186 | 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); | |
| 1186 | 1189 | const appOf = async (name: string) => { |
| 1187 | 1190 | const created = await createRepo(app2, pia, { |
| 1188 | 1191 | name, |
new above
offline