mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
`getBearerToken` in the Stripe Sync API handler parsed the
`Authorization` header with `/^Bearer\s+(.+)$/i`. Both `\s+` and `(.+)`
can match whitespace, so a header made of `Bearer` and a long run of
whitespace backtracks in quadratic time (CodeQL `js/polynomial-redos`).
The token is now parsed with `slice`, a case-insensitive scheme check
and `trim`.
**Changed:**
- `apps/studio/lib/api/apiHelpers.ts` – new shared
`getBearerToken(authorization)` that parses in linear time. It returns
`null` for a missing, array-valued, non-Bearer or empty/whitespace-only
header. Previously a whitespace-only token returned `''` instead of
`null`, which still got a 401.
- `apps/studio/pages/api/integrations/stripe-sync.ts` – drops the local
regex helper and uses the shared one.
`apps/studio/routes/api/integrations/stripe-sync.ts` re-exports this
handler on `master`, so both routes get the fix.
**Added:**
- `apps/studio/lib/api/apiHelpers.test.ts` – `getBearerToken` cases: a
valid token, lowercase `bearer`, extra whitespace,
missing/array/wrong-scheme/empty headers, and a 100k-whitespace header
that has to return in under 100 ms (the old regex takes about 4 s).
No other API handlers in `apps/studio` or `packages/` use this regex.
The remaining `Authorization` parsing in `lib/api/apiAuthenticate.ts`
and `lib/gotrue.ts` uses `replace(/bearer /i, '')`, which runs in linear
time.
## To test
- [ ] On a project, install the Stripe Sync integration from Studio
(Integrations → Stripe Sync). Installation starts and finishes.
- [ ] Uninstall it again. Uninstallation starts and finishes.
- [ ] `curl -i -X POST <studio-url>/api/integrations/stripe-sync -H
'Authorization: Basic abc' -H 'Content-Type: application/json' -d '{}'`
returns 401. Do the same with `Authorization: Bearer` followed only by
spaces, and with no `Authorization` header: both return 401.
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
151 lines
4.2 KiB
TypeScript
151 lines
4.2 KiB
TypeScript
import type { IncomingHttpHeaders } from 'node:http'
|
|
import { snakeCase } from 'lodash'
|
|
import z from 'zod'
|
|
|
|
import { IS_PLATFORM } from '@/lib/constants'
|
|
|
|
/**
|
|
* Construct headers for api request.
|
|
* For platform, it will include apiKey into the provided headers.
|
|
*
|
|
* To prevent relay frontend request headers like useragent, referrer... into the middleware requests.
|
|
* We will only keep the header keys that are in this list: Accept, Authorization, Content-Type, x-connection-encrypted
|
|
*/
|
|
export function constructHeaders(headers: { [prop: string]: any }) {
|
|
if (headers) {
|
|
const cleansedHeaders = {
|
|
Accept: headers.Accept,
|
|
Authorization: headers.Authorization,
|
|
cookie: headers.cookie,
|
|
'Content-Type': headers['Content-Type'],
|
|
'x-connection-encrypted': headers['x-connection-encrypted'],
|
|
} as any
|
|
// clean up key with underfined value
|
|
Object.keys(cleansedHeaders).forEach((key) =>
|
|
cleansedHeaders[key] === undefined ? delete cleansedHeaders[key] : {}
|
|
)
|
|
return {
|
|
...cleansedHeaders,
|
|
// [Joshen] JFYI both Alaister and I checked on this and realised this might not be used actually
|
|
// Could be safe to remove but leaving it here for now
|
|
...(!IS_PLATFORM && { apiKey: `${process.env.SUPABASE_SERVICE_KEY}` }),
|
|
}
|
|
} else {
|
|
return {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
}
|
|
}
|
|
}
|
|
|
|
// Typically for HTTP payloads
|
|
// @ts-ignore
|
|
export const toSnakeCase = (object) => {
|
|
const snakeCaseObject = {}
|
|
const snakeCaseArray = []
|
|
|
|
if (!object) return null
|
|
|
|
if (Array.isArray(object)) {
|
|
for (const item of object) {
|
|
if (typeof item === 'object') {
|
|
snakeCaseArray.push(toSnakeCase(item))
|
|
} else {
|
|
snakeCaseArray.push(item)
|
|
}
|
|
}
|
|
return snakeCaseArray
|
|
} else if (typeof object === 'object') {
|
|
for (const key of Object.keys(object)) {
|
|
if (typeof object[key] === 'object') {
|
|
// @ts-ignore
|
|
snakeCaseObject[snakeCase(key)] = toSnakeCase(object[key])
|
|
} else {
|
|
// @ts-ignore
|
|
snakeCaseObject[snakeCase(key)] = object[key]
|
|
}
|
|
}
|
|
return snakeCaseObject
|
|
} else {
|
|
return object
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Converts Node.js `IncomingHttpHeaders` to Fetch API `Headers`.
|
|
*/
|
|
export function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {
|
|
const headers = new Headers()
|
|
for (const [key, value] of Object.entries(nodeHeaders)) {
|
|
if (Array.isArray(value)) {
|
|
value.forEach((v) => headers.append(key, v))
|
|
} else if (value !== undefined) {
|
|
headers.append(key, value)
|
|
}
|
|
}
|
|
return headers
|
|
}
|
|
|
|
/**
|
|
* Zod transformer to parse boolean values from strings.
|
|
*
|
|
* Use when accepting a boolean value in a query parameter.
|
|
*/
|
|
export function zBooleanString(errorMsg?: string) {
|
|
return z.string().transform((value, ctx) => {
|
|
if (value === 'true') {
|
|
return true
|
|
}
|
|
|
|
if (value === 'false') {
|
|
return false
|
|
}
|
|
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: errorMsg || 'must be a boolean string',
|
|
})
|
|
return z.NEVER
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Transform a comma-separated string into an array of strings.
|
|
*
|
|
* Use when accepting a list of values in a query parameter.
|
|
*/
|
|
export function commaSeparatedStringIntoArray(value: string): string[] {
|
|
return value
|
|
.split(',')
|
|
.map((v) => v.trim())
|
|
.filter(Boolean)
|
|
}
|
|
|
|
const BEARER_SCHEME = 'bearer'
|
|
|
|
/**
|
|
* Extract the token from a `Bearer <token>` Authorization header (scheme is case-insensitive).
|
|
*
|
|
* Returns `null` for a missing, array-valued, non-Bearer or empty header. Parsed without a regex
|
|
* over the token so untrusted input can't trigger backtracking.
|
|
*/
|
|
export function getBearerToken(authorization: string | string[] | undefined | null) {
|
|
if (typeof authorization !== 'string') return null
|
|
|
|
const scheme = authorization.slice(0, BEARER_SCHEME.length)
|
|
const rest = authorization.slice(BEARER_SCHEME.length)
|
|
if (scheme.toLowerCase() !== BEARER_SCHEME || !/^\s/.test(rest)) return null
|
|
|
|
return rest.trim() || null
|
|
}
|
|
|
|
export class InternalServerError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public details?: Record<string, unknown>
|
|
) {
|
|
super(message)
|
|
this.name = 'InternalServerError'
|
|
}
|
|
}
|