OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
auth: bound every input that decides how much work the server does
Carl-Gerhard Lindesvärd14960acdaf97
diff --git a/packages/core/src/modules/auth/auth.constants.test.ts b/packages/core/src/modules/auth/auth.constants.test.tsnew file mode 100644index 000000000..6e41b853f--- /dev/null+++ b/packages/core/src/modules/auth/auth.constants.test.ts@@ -0,0 +1,105 @@+// The ceilings exist so an input cannot choose how much work the server does:+// a password reaches argon2, a recovery code reaches it ten times, and an+// inviteId is written into a Set-Cookie header. These assert the bound fires+// and, just as importantly, that an ordinary value still passes.++import { describe, expect, test } from 'bun:test';+import { MAX_PASSWORD, MAX_TOKEN } from '../../shared/limits.constants';+import {+ zPassword,+ zRequestResetPassword,+ zResetPassword,+ zSignInEmail,+ zSignInShare,+ zSignUpEmail,+ zTotpCode,+ zTotpOrRecoveryCode,+} from './auth.constants';++const long = (n: number) => 'a'.repeat(n);++describe('passwords are bounded before argon2 sees them', () => {+ test('an ordinary password passes', () => {+ expect(zPassword.safeParse('correct horse battery').success).toBe(true);+ });++ test('exactly the maximum passes, one over does not', () => {+ expect(zPassword.safeParse(long(MAX_PASSWORD)).success).toBe(true);+ expect(zPassword.safeParse(long(MAX_PASSWORD + 1)).success).toBe(false);+ });++ test('the minimum still applies', () => {+ expect(zPassword.safeParse('short').success).toBe(false);+ });++ test('sign-in, sign-up, reset and share all carry the bound', () => {+ const huge = long(200_000);+ expect(+ zSignInEmail.safeParse({ email: '[email protected]', password: huge }).success+ ).toBe(false);+ expect(+ zSignUpEmail.safeParse({+ firstName: 'A',+ lastName: 'B',+ email: '[email protected]',+ password: huge,+ confirmPassword: huge,+ }).success+ ).toBe(false);+ expect(+ zResetPassword.safeParse({ token: 't', password: huge }).success+ ).toBe(false);+ expect(+ zSignInShare.safeParse({ password: huge, shareId: 's' }).success+ ).toBe(false);+ });+});++describe('the TOTP inputs are bounded', () => {+ test('a six-digit code still passes, with spaces stripped', () => {+ expect(zTotpCode.parse('123 456')).toBe('123456');+ });++ // This one decides ten sequential argon2 verifies in consumeRecoveryCode.+ test('a recovery code is capped', () => {+ expect(zTotpOrRecoveryCode.safeParse('abcd-efgh').success).toBe(true);+ expect(zTotpOrRecoveryCode.safeParse(long(MAX_TOKEN + 1)).success).toBe(+ false+ );+ });++ test('a huge TOTP code is refused before the regex runs over it', () => {+ expect(zTotpCode.safeParse(long(MAX_TOKEN + 1)).success).toBe(false);+ });+});++describe('emails and names', () => {+ test('a normal address passes and an over-long one does not', () => {+ expect(+ zRequestResetPassword.safeParse({ email: '[email protected]' }).success+ ).toBe(true);+ expect(+ zRequestResetPassword.safeParse({ email: `${long(300)}@example.com` })+ .success+ ).toBe(false);+ });++ test('a whitespace-only name is refused, and a real one is trimmed', () => {+ const base = {+ email: '[email protected]',+ password: 'longenough',+ confirmPassword: 'longenough',+ };+ expect(+ zSignUpEmail.safeParse({ ...base, firstName: ' ', lastName: 'B' })+ .success+ ).toBe(false);+ const ok = zSignUpEmail.safeParse({+ ...base,+ firstName: ' Ada ',+ lastName: 'Lovelace',+ });+ expect(ok.success).toBe(true);+ expect(ok.success && ok.data.firstName).toBe('Ada');+ });+});diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.tsindex 5a00d8253..8538f4a4d 100644--- a/packages/core/src/modules/auth/auth.constants.ts+++ b/packages/core/src/modules/auth/auth.constants.ts@@ -1,24 +1,46 @@import { z } from 'zod';+import {+ MAX_EMAIL,+ MAX_ID,+ MAX_NAME,+ MAX_PASSWORD,+ MAX_TOKEN,+} from '../../shared/limits.constants';export const zProvider = z.enum(['email', 'google', 'github']);-export const zPassword = z.string().min(8);+/**+ * `hashPassword` hands this straight to argon2, so the ceiling is what stops a+ * caller choosing how much work the server does. 128 is far above any password+ * a person types; anyone who set a longer one before this existed resets by+ * email, which asks only for an address.+ */+export const zPassword = z.string().min(8).max(MAX_PASSWORD);++/** Length first, so a huge string fails before the address is parsed. */+const zEmail = z.string().max(MAX_EMAIL).email();++/** An id we generated or a provider handed back. `inviteId` reaches a cookie. */+const zShortId = z.string().max(MAX_ID);++/** Trimmed first, so a whitespace-only name fails `min(1)` rather than storing. */+const zPersonName = z.string().trim().min(1).max(MAX_NAME);export const zSignInEmail = z.object({- email: z.string().email().min(1),+ email: zEmail.min(1),password: zPassword,- inviteId: z.string().nullish(),+ inviteId: zShortId.nullish(),});export type ISignInEmail = z.infer<typeof zSignInEmail>;export const zSignUpEmail = z.object({- firstName: z.string().min(1),- lastName: z.string().min(1),- email: z.string().email(),+ firstName: zPersonName,+ lastName: zPersonName,+ email: zEmail,password: zPassword,confirmPassword: zPassword,- inviteId: z.string().nullish(),+ inviteId: zShortId.nullish(),}).refine((data) => data.password === data.confirmPassword, {path: ['confirmPassword'],@@ -27,31 +49,37 @@ export const zSignUpEmail = zexport type ISignUpEmail = z.infer<typeof zSignUpEmail>;export const zResetPassword = z.object({- token: z.string(),- password: z.string().min(8),+ token: z.string().max(MAX_TOKEN),+ password: zPassword,});export type IResetPassword = z.infer<typeof zResetPassword>;export const zRequestResetPassword = z.object({- email: z.string().email(),+ email: zEmail,});export type IRequestResetPassword = z.infer<typeof zRequestResetPassword>;+// Bounded before the transform: the strip and the regex below both run over+// whatever arrives.export const zTotpCode = z.string()+ .max(MAX_TOKEN).transform((v) => v.replace(/\s+/g, '')).refine((v) => /^\d{6}$/.test(v), { message: 'Enter a 6-digit code' });export type ITotpCode = z.infer<typeof zTotpCode>;+// A recovery code is checked against all ten stored hashes in turn, so this one+// input decides ten argon2 verifies.export const zTotpOrRecoveryCode = z.string().min(1)+ .max(MAX_TOKEN).transform((v) => v.trim());export type ITotpOrRecoveryCode = z.infer<typeof zTotpOrRecoveryCode>;export const zSignInShare = z.object({- password: z.string().min(1),- shareId: z.string().min(1),+ password: z.string().min(1).max(MAX_PASSWORD),+ shareId: zShortId.min(1),shareType: z.enum(['overview', 'dashboard', 'report']).optional()diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.tsindex 98afd95c8..4f6381ecc 100644--- a/packages/core/src/modules/auth/auth.routes.ts+++ b/packages/core/src/modules/auth/auth.routes.ts@@ -9,6 +9,7 @@import { redirect } from 'elysia';import { z } from 'zod';import { defineRoutes } from '../../http/define';+import { MAX_TOKEN } from '../../shared/limits.constants';import {assertOAuthState,completeOAuthCallback,@@ -17,9 +18,11 @@ import {OAuthCallbackError,} from './auth.service';+// Both come from the provider's redirect, so they are attacker-supplied in+// the sense that anyone can call this URL directly.const callbackQuery = z.object({- code: z.string(),- state: z.string(),+ code: z.string().max(MAX_TOKEN),+ state: z.string().max(MAX_TOKEN),});/** Only used to make the URL parseable when DASHBOARD_URL is not set. */diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.tsindex 03c893aa0..31f7c29b3 100644--- a/packages/core/src/modules/organization/organization.constants.ts+++ b/packages/core/src/modules/organization/organization.constants.ts@@ -5,6 +5,7 @@// the schema — it is not a consumer.import { z } from 'zod';+import { MAX_EMAIL, MAX_ID, MAX_NAME } from '../../shared/limits.constants';/*** A per-project grant. `read` means exactly that: the member can look at the@@ -19,8 +20,8 @@ export const zProjectAccessGrant = z.object({export type IProjectAccessGrant = z.infer<typeof zProjectAccessGrant>;export const zInviteUser = z.object({- email: z.string().email(),- organizationId: z.string(),+ email: z.string().max(MAX_EMAIL).email(),+ organizationId: z.string().max(MAX_ID),role: z.enum(['org:admin', 'org:member']),access: z.array(zProjectAccessGrant),});@@ -59,7 +60,7 @@ export const zTimezone = z.transform(canonicalTimezone);export const zEditOrganization = z.object({- id: z.string().min(2),- name: z.string().min(2),+ id: z.string().min(2).max(MAX_ID),+ name: z.string().trim().min(2).max(MAX_NAME),timezone: zTimezone,});diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.tsindex 1f0e89240..e06c2f5ea 100644--- a/packages/core/src/modules/user/user.rpc.ts+++ b/packages/core/src/modules/user/user.rpc.ts@@ -10,6 +10,7 @@import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';+import { MAX_NAME } from '../../shared/limits.constants';export const userRouter = createTRPCRouter({deletionBlockers: protectedProcedure.query(async ({ ctx }) => {@@ -27,8 +28,8 @@ export const userRouter = createTRPCRouter({update: protectedProcedure.input(z.object({- firstName: z.string(),- lastName: z.string(),+ firstName: z.string().trim().min(1).max(MAX_NAME),+ lastName: z.string().trim().min(1).max(MAX_NAME),})).mutation(async ({ input, ctx }) => {diff --git a/packages/core/src/shared/limits.constants.ts b/packages/core/src/shared/limits.constants.tsnew file mode 100644index 000000000..b1f3c33e7--- /dev/null+++ b/packages/core/src/shared/limits.constants.ts@@ -0,0 +1,29 @@+// Upper bounds for user-supplied strings, shared so modules stop inventing a+// literal each.+//+// Named `*.constants.ts` deliberately: `constants-stay-isomorphic` lets a+// constants file import zod, another constants file, or nothing, so this is the+// only shape the rule allows a shared limit to take.+//+// These are ceilings, not product rules. A ceiling exists so an input cannot+// reach work that scales with its length — argon2 in `auth/src/password.ts`,+// a `Set-Cookie` write, a database column — and is set far above any honest+// value so it never fires for a real user.++/** Argon2 hashes this; 128 is well past any password a person types. */+export const MAX_PASSWORD = 128;++/** RFC 5321's limit on a whole address. */+export const MAX_EMAIL = 254;++/** A person's name, an organization's, a project's. */+export const MAX_NAME = 100;++/** Reset tokens, TOTP recovery codes, OAuth `code`/`state`. */+export const MAX_TOKEN = 512;++/** An id we generate or a provider hands us: invite, share, organization. */+export const MAX_ID = 128;++/** Free text that is stored but never parsed. */+export const MAX_DESCRIPTION = 1000;