Skip to content
Merged
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
43 changes: 18 additions & 25 deletions src/runtime/api/csrf_jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use bun_boringssl_sys as boring;
use bun_core::Utf8Bytes;
use bun_csrf as csrf;
use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult};
use bun_jsc::{CallFrame, IntegerRange, JSGlobalObject, JSValue, JsResult};

use crate::api::crypto::evp::Algorithm as EvpAlgorithm;
use crate::crypto::evp;
Expand All @@ -21,31 +21,24 @@ fn algorithm_from_js_case_insensitive(
Ok(evp::lookup_ignore_case(slice.slice()))
}

/// Validates an optional integer property in `[0, MAX_SAFE_INTEGER]`.
/// Differs from `JSValue::get_optional_int::<u64>` in rejecting NaN and in
/// the error message wording expected by existing tests.
fn get_optional_int_u64(
/// `expiresIn` / `maxAge`. NaN maps to the default, and `0` would mean "no expiry".
fn get_optional_duration_ms(
target: JSValue,
global: &JSGlobalObject,
property: &'static str,
field_name: &'static [u8],
) -> JsResult<Option<u64>> {
let Some(value) = target.get(global, property)? else {
let Some(value) = target.get(global, field_name)? else {
return Ok(None);
};
if value.is_undefined() || value.is_empty() {
return Ok(Some(0));
}
if !value.is_number() {
return Err(global.throw_invalid_argument_type_value(property, "number", value));
}
let num: f64 = value.as_number();
const MAX_SAFE_INTEGER: f64 = 9007199254740991.0;
if num.fract() != 0.0 || num < 0.0 || num > MAX_SAFE_INTEGER {
return Err(global.throw_invalid_arguments(format_args!(
"{property} must be an integer between 0 and {MAX_SAFE_INTEGER}"
)));
}
Ok(Some(num as u64))
Ok(Some(global.validate_integer_range::<u64>(
value,
csrf::DEFAULT_EXPIRATION_MS,
IntegerRange {
min: 0,
field_name,
..Default::default()
},
)?))
}

/// Reads the optional `encoding` property. Parsed as a Buffer encoding name
Expand Down Expand Up @@ -105,8 +98,8 @@ pub(crate) fn csrf__generate(global: &JSGlobalObject, frame: &CallFrame) -> JsRe
let options_value = args[1];

// Extract expiresIn (optional)
if let Some(expires_in_js) = get_optional_int_u64(options_value, global, "expiresIn")? {
expires_in = expires_in_js;
if let Some(ms) = get_optional_duration_ms(options_value, global, b"expiresIn")? {
expires_in = ms;
}

// Extract sessionId (optional)
Expand Down Expand Up @@ -247,8 +240,8 @@ pub(crate) fn csrf__verify(global: &JSGlobalObject, frame: &CallFrame) -> JsResu
}

// Extract maxAge (optional)
if let Some(max_age_js) = get_optional_int_u64(options_value, global, "maxAge")? {
max_age = max_age_js;
if let Some(ms) = get_optional_duration_ms(options_value, global, b"maxAge")? {
max_age = ms;
}

// Extract encoding (optional)
Expand Down
59 changes: 59 additions & 0 deletions test/js/bun/util/csrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,65 @@ describe("Bun.CSRF", () => {
expect(() => CSRF.verify(token, { secret, sessionId: 123 })).toThrow();
});

describe.each([
["expiresIn", (value: unknown) => CSRF.generate(secret, { expiresIn: value as number })],
["maxAge", (value: unknown) => CSRF.verify(CSRF.generate(secret), { secret, maxAge: value as number })],
])("%s option validation", (field, call) => {
function thrown(value: unknown) {
try {
call(value);
} catch (error: any) {
return { constructor: error.constructor, code: error.code, message: error.message };
}
throw new Error(`expected ${field}: ${String(value)} to throw`);
}

test("NaN is treated as an absent option", () => {
expect(() => call(NaN)).not.toThrow();
expect(CSRF.verify(CSRF.generate(secret, { expiresIn: NaN }), { secret, maxAge: NaN })).toBe(true);

// The token embeds expiresIn as a big-endian u64 at bytes 24..32, after
// the timestamp and the nonce. 0 there means the token never expires.
const embeddedExpiresIn = (options?: { expiresIn: number }) =>
Buffer.from(CSRF.generate(secret, options), "base64url").readBigUInt64BE(24);
expect(embeddedExpiresIn({ expiresIn: 0 })).toBe(0n);
expect(embeddedExpiresIn({ expiresIn: NaN })).toBe(embeddedExpiresIn());
expect(embeddedExpiresIn({ expiresIn: NaN })).toBe(BigInt(24 * 60 * 60 * 1000));
});

test("out-of-range values throw RangeError [ERR_OUT_OF_RANGE]", () => {
const prefix = `The value of "${field}" is out of range. It must be >= 0 and <= 9007199254740991.`;
expect(thrown(-1)).toEqual({
constructor: RangeError,
code: "ERR_OUT_OF_RANGE",
message: `${prefix} Received -1`,
});
expect(thrown(2 ** 53)).toEqual({
constructor: RangeError,
code: "ERR_OUT_OF_RANGE",
message: `${prefix} Received 9007199254740992`,
});
expect(thrown(Infinity)).toEqual({
constructor: RangeError,
code: "ERR_OUT_OF_RANGE",
message: `${prefix} Received Infinity`,
});
});

test("non-integer and non-number values throw TypeError [ERR_INVALID_ARG_TYPE]", () => {
expect(thrown(1.5)).toEqual({
constructor: TypeError,
code: "ERR_INVALID_ARG_TYPE",
message: `The "${field}" property must be of type integer. Received number`,
});
expect(thrown("100")).toEqual({
constructor: TypeError,
code: "ERR_INVALID_ARG_TYPE",
message: `The "${field}" property must be of type number. Received string`,
});
});
});

test("rejects encodings that are not token formats", () => {
const token = CSRF.generate(secret);
const message = "Invalid format: must be 'base64', 'base64url', or 'hex'";
Expand Down
Loading