Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JWT string validator #3887

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deno/lib/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export type StringValidation =
| "duration"
| "ip"
| "base64"
| "jwt"
| { includes: string; position?: number }
| { startsWith: string }
| { endsWith: string };
Expand Down
32 changes: 29 additions & 3 deletions deno/lib/__tests__/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,38 @@ test("base64 validations", () => {
];

for (const str of invalidBase64Strings) {
expect(str + z.string().base64().safeParse(str).success).toBe(
str + "false"
);
expect(str + z.string().base64().safeParse(str).success).toBe(str + "false");
}
});

test("jwt validations", () => {
const jwt = z.string().jwt();
const jwtWithAlg = z.string().jwt({ alg: "HS256" });

// Valid JWTs
const validHeader = btoa(JSON.stringify({ typ: "JWT", alg: "HS256" }));
const validPayload = btoa(JSON.stringify({ sub: "1234" }));
const validSignature = btoa("signature");
const validJWT = `${validHeader}.${validPayload}.${validSignature}`;

expect(jwt.safeParse(validJWT).success).toBe(true);
expect(jwtWithAlg.safeParse(validJWT).success).toBe(true);

// Different algorithm
const headerWithDiffAlg = btoa(JSON.stringify({ typ: "JWT", alg: "RS256" }));
const jwtWithDiffAlg = `${headerWithDiffAlg}.${validPayload}.${validSignature}`;
expect(jwt.safeParse(jwtWithDiffAlg).success).toBe(true);
expect(jwtWithAlg.safeParse(jwtWithDiffAlg).success).toBe(false);

// Invalid cases
expect(jwt.safeParse("not.a.jwt").success).toBe(false);
expect(jwt.safeParse("not.enough.parts.here").success).toBe(false);
expect(jwt.safeParse("invalid!base64.parts.here").success).toBe(false);
expect(jwt.safeParse(`${btoa("invalid json")}.${validPayload}.${validSignature}`).success).toBe(false);
expect(jwt.safeParse(`${btoa(JSON.stringify({ alg: "HS256" }))}.${validPayload}.${validSignature}`).success).toBe(false);
expect(jwt.safeParse(`${btoa(JSON.stringify({ typ: "JWT" }))}.${validPayload}.${validSignature}`).success).toBe(false);
});

test("url validations", () => {
const url = z.string().url();
url.parse("http://google.com");
Expand Down
65 changes: 65 additions & 0 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,25 @@ export abstract class ZodType<
/////////////////////////////////////////
/////////////////////////////////////////
export type IpVersion = "v4" | "v6";
export type JWTAlgorithm =
| "HS256"
| "HS384"
| "HS512"
| "RS256"
| "RS384"
| "RS512"
| "ES256"
| "ES384"
| "ES512"
| "PS256"
| "PS384"
| "PS512";

export interface JWTValidation {
alg?: JWTAlgorithm;
message?: string;
}

export type ZodStringCheck =
| { kind: "min"; value: number; message?: string }
| { kind: "max"; value: number; message?: string }
Expand All @@ -546,6 +565,7 @@ export type ZodStringCheck =
| { kind: "trim"; message?: string }
| { kind: "toLowerCase"; message?: string }
| { kind: "toUpperCase"; message?: string }
| { kind: "jwt"; options?: JWTValidation; message?: string }
| {
kind: "datetime";
offset: boolean;
Expand Down Expand Up @@ -671,6 +691,30 @@ function isValidIP(ip: string, version?: IpVersion) {
return false;
}

function isValidJWT(jwt: string, options?: JWTValidation): boolean {
try {
// Check three-part structure
const parts = jwt.split(".");
if (parts.length !== 3) return false;

// Validate all parts are base64
for (const part of parts) {
if (!base64Regex.test(part)) return false;
}

// Decode and validate header
const header = JSON.parse(atob(parts[0]));
if (!header.typ || !header.alg) return false;

// Validate algorithm if specified
if (options?.alg && header.alg !== options.alg) return false;

return true;
} catch {
return false;
}
}

export class ZodString extends ZodType<string, ZodStringDef, string> {
_parse(input: ParseInput): ParseReturnType<string> {
if (this._def.coerce) {
Expand Down Expand Up @@ -943,6 +987,16 @@ export class ZodString extends ZodType<string, ZodStringDef, string> {
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.options)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else {
util.assertNever(check);
}
Expand Down Expand Up @@ -1002,6 +1056,17 @@ export class ZodString extends ZodType<string, ZodStringDef, string> {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}

jwt(options?: JWTValidation | string) {
if (typeof options === "string") {
return this._addCheck({ kind: "jwt", message: options });
}
return this._addCheck({
kind: "jwt",
options,
...errorUtil.errToObj(options?.message),
});
}

ip(options?: string | { version?: IpVersion; message?: string }) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
Expand Down
1 change: 1 addition & 0 deletions src/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export type StringValidation =
| "duration"
| "ip"
| "base64"
| "jwt"
| { includes: string; position?: number }
| { startsWith: string }
| { endsWith: string };
Expand Down
32 changes: 29 additions & 3 deletions src/__tests__/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,38 @@ test("base64 validations", () => {
];

for (const str of invalidBase64Strings) {
expect(str + z.string().base64().safeParse(str).success).toBe(
str + "false"
);
expect(str + z.string().base64().safeParse(str).success).toBe(str + "false");
}
});

test("jwt validations", () => {
const jwt = z.string().jwt();
const jwtWithAlg = z.string().jwt({ alg: "HS256" });

// Valid JWTs
const validHeader = btoa(JSON.stringify({ typ: "JWT", alg: "HS256" }));
const validPayload = btoa(JSON.stringify({ sub: "1234" }));
const validSignature = btoa("signature");
const validJWT = `${validHeader}.${validPayload}.${validSignature}`;

expect(jwt.safeParse(validJWT).success).toBe(true);
expect(jwtWithAlg.safeParse(validJWT).success).toBe(true);

// Different algorithm
const headerWithDiffAlg = btoa(JSON.stringify({ typ: "JWT", alg: "RS256" }));
const jwtWithDiffAlg = `${headerWithDiffAlg}.${validPayload}.${validSignature}`;
expect(jwt.safeParse(jwtWithDiffAlg).success).toBe(true);
expect(jwtWithAlg.safeParse(jwtWithDiffAlg).success).toBe(false);

// Invalid cases
expect(jwt.safeParse("not.a.jwt").success).toBe(false);
expect(jwt.safeParse("not.enough.parts.here").success).toBe(false);
expect(jwt.safeParse("invalid!base64.parts.here").success).toBe(false);
expect(jwt.safeParse(`${btoa("invalid json")}.${validPayload}.${validSignature}`).success).toBe(false);
expect(jwt.safeParse(`${btoa(JSON.stringify({ alg: "HS256" }))}.${validPayload}.${validSignature}`).success).toBe(false);
expect(jwt.safeParse(`${btoa(JSON.stringify({ typ: "JWT" }))}.${validPayload}.${validSignature}`).success).toBe(false);
});

test("url validations", () => {
const url = z.string().url();
url.parse("http://google.com");
Expand Down
65 changes: 65 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,25 @@ export abstract class ZodType<
/////////////////////////////////////////
/////////////////////////////////////////
export type IpVersion = "v4" | "v6";
export type JWTAlgorithm =
| "HS256"
| "HS384"
| "HS512"
| "RS256"
| "RS384"
| "RS512"
| "ES256"
| "ES384"
| "ES512"
| "PS256"
| "PS384"
| "PS512";

export interface JWTValidation {
alg?: JWTAlgorithm;
message?: string;
}

export type ZodStringCheck =
| { kind: "min"; value: number; message?: string }
| { kind: "max"; value: number; message?: string }
Expand All @@ -546,6 +565,7 @@ export type ZodStringCheck =
| { kind: "trim"; message?: string }
| { kind: "toLowerCase"; message?: string }
| { kind: "toUpperCase"; message?: string }
| { kind: "jwt"; options?: JWTValidation; message?: string }
| {
kind: "datetime";
offset: boolean;
Expand Down Expand Up @@ -671,6 +691,30 @@ function isValidIP(ip: string, version?: IpVersion) {
return false;
}

function isValidJWT(jwt: string, options?: JWTValidation): boolean {
try {
// Check three-part structure
const parts = jwt.split(".");
if (parts.length !== 3) return false;

// Validate all parts are base64
for (const part of parts) {
if (!base64Regex.test(part)) return false;
}

// Decode and validate header
const header = JSON.parse(atob(parts[0]));
if (!header.typ || !header.alg) return false;

// Validate algorithm if specified
if (options?.alg && header.alg !== options.alg) return false;

return true;
} catch {
return false;
}
}

export class ZodString extends ZodType<string, ZodStringDef, string> {
_parse(input: ParseInput): ParseReturnType<string> {
if (this._def.coerce) {
Expand Down Expand Up @@ -943,6 +987,16 @@ export class ZodString extends ZodType<string, ZodStringDef, string> {
});
status.dirty();
}
} else if (check.kind === "jwt") {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try splitting the JWT validation into a standalone utility function

if (!isValidJWT(input.data, check.options)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

structure the code to avoid multiple calls to addIssueToContext for bundle size reasons

validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else {
util.assertNever(check);
}
Expand Down Expand Up @@ -1002,6 +1056,17 @@ export class ZodString extends ZodType<string, ZodStringDef, string> {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}

jwt(options?: JWTValidation | string) {
if (typeof options === "string") {
return this._addCheck({ kind: "jwt", message: options });
}
return this._addCheck({
kind: "jwt",
options,
...errorUtil.errToObj(options?.message),
});
}

ip(options?: string | { version?: IpVersion; message?: string }) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
Expand Down