@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
230 lines (229 loc) • 9.66 kB
JavaScript
import { DEBUG_BUILD } from "../debug-build.js";
import { parseCookieHeader } from "./cookie.js";
import { debug } from "./debug-logger.js";
import { FILTERED_VALUE, SENSITIVE_COOKIE_NAME_SNIPPETS } from "./data-collection/filtering-snippets.js";
import { shouldFilterDataKey } from "./data-collection/filterKeyValueData.js";
import { safeUnref } from "./timer.js";
import { getUrlQuery } from "./url.js";
// src/utils/request.ts
/** Hard cap on captured body size, even when `maxRequestBodySize` is `'always'`. */
const MAX_BODY_BYTE_LENGTH = 1048576;
/** Content types that are safe to capture as text. */
const TEXT_CONTENT_TYPES = [
"text/",
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"application/graphql"
];
/**
* Convert a `maxRequestBodySize` setting to a maximum byte length.
*/
function getMaxBodyByteLength(maxRequestBodySize) {
if (maxRequestBodySize === "small") return 1e3;
if (maxRequestBodySize === "medium") return 1e4;
return MAX_BODY_BYTE_LENGTH;
}
/**
* Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.
* The header keys will be lower case: e.g. A "Content-Type" header will be stored as "content-type".
*/
function winterCGHeadersToDict(winterCGHeaders) {
const headers = {};
try {
winterCGHeaders.forEach((value, key) => {
if (typeof value === "string") headers[key] = value;
});
} catch {}
return headers;
}
/**
* Convert common request headers to a simple dictionary.
*/
function headersToDict(reqHeaders) {
const headers = Object.create(null);
try {
Object.entries(reqHeaders).forEach(([key, value]) => {
if (key.startsWith(":")) return;
if (typeof value === "string") headers[key] = value;
else if (typeof value === "number") headers[key] = String(value);
});
} catch {}
return headers;
}
/**
* The `host` header, or the HTTP/2 `:authority` pseudo-header that replaces it.
*/
function getHostFromHeaders(headers) {
const host = headers.host ?? headers[":authority"];
return typeof host === "string" ? host : void 0;
}
/**
* Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.
*/
function winterCGRequestToRequestData(req) {
const headers = winterCGHeadersToDict(req.headers);
return {
method: req.method,
url: req.url,
query_string: extractQueryParamsFromUrl(req.url),
headers
};
}
/**
* Checks if the content type is textual and safe to capture.
*/
function isTextualContentType(contentType) {
if (!contentType) return false;
const lowerContentType = contentType.toLowerCase();
return TEXT_CONTENT_TYPES.some((type) => lowerContentType.includes(type));
}
/**
* Captures the body from a Web Fetch API Request and adds it to the isolation scope.
*
* This function clones the request to read the body without affecting the original.
* Only textual content types are captured - binary data is skipped.
*
* This is used by WinterCG-compatible runtimes (Cloudflare Workers, Deno, Bun, Vercel Edge, etc.)
* that use the Web Fetch API Request object.
*
* @param request - The incoming Web Fetch API Request
* @param isolationScope - The isolation scope to add the body to
* @param maxRequestBodySize - The maximum size of the request body to capture ('small' = 1KB, 'medium' = 10KB, 'always' = 1MB)
*/
async function captureBodyFromWinterCGRequest(request, isolationScope, maxRequestBodySize) {
try {
const contentType = request.headers.get("content-type");
if (!isTextualContentType(contentType)) {
DEBUG_BUILD && debug.log("Skipping body capture for non-textual content type:", contentType);
return;
}
if (!request.body) return;
const contentLength = request.headers.get("content-length");
const maxBodySize = getMaxBodyByteLength(maxRequestBodySize);
if (contentLength) {
const length = parseInt(contentLength, 10);
if (!isNaN(length) && length > 1048576) {
DEBUG_BUILD && debug.log("Skipping body capture: body too large", length);
return;
}
}
const bodyPromise = request.clone().text();
const timeoutPromise = new Promise((resolve) => {
safeUnref(setTimeout(() => resolve(null), 2e3));
});
const body = await Promise.race([bodyPromise, timeoutPromise]);
if (body === null) {
DEBUG_BUILD && debug.log("Timeout reading request body");
return;
}
if (!body) return;
const bytes = new TextEncoder().encode(body);
const bodyByteLength = bytes.length;
let truncatedBody;
if (bodyByteLength > maxBodySize) truncatedBody = `${new TextDecoder().decode(bytes.slice(0, maxBodySize - 3))}...`;
else truncatedBody = body;
isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: truncatedBody } });
DEBUG_BUILD && debug.log("Captured request body:", bodyByteLength, "bytes");
} catch (error) {
DEBUG_BUILD && debug.error("Error capturing request body:", error);
}
}
/**
* Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.
* Instead of allowing `PolymorphicRequest` to be passed,
* we want to be more specific and generally require a http.IncomingMessage-like object.
*/
function httpRequestToRequestData(request) {
const headers = request.headers || {};
const host = (typeof headers["x-forwarded-host"] === "string" ? headers["x-forwarded-host"] : void 0) || getHostFromHeaders(headers);
const protocol = (typeof headers["x-forwarded-proto"] === "string" ? headers["x-forwarded-proto"] : void 0) || request.protocol || (request.socket?.encrypted ? "https" : "http");
const url = request.url || "";
const absoluteUrl = getAbsoluteUrl({
url,
host,
protocol
});
const data = request.body || void 0;
const cookies = request.cookies;
return {
url: absoluteUrl,
method: request.method,
query_string: extractQueryParamsFromUrl(url),
headers: headersToDict(headers),
cookies,
data
};
}
function getAbsoluteUrl({ url, protocol, host }) {
if (url?.startsWith("http")) return url;
if (url && host) return `${protocol}://${host}${url}`;
}
/**
* Converts incoming HTTP request or response headers to OpenTelemetry span attributes following semantic conventions.
* Header names are converted to the format: http.<request|response>.header.<key>
* where <key> is the header name in lowercase. Header values are always emitted as a string array.
*
* @param lifecycle - The lifecycle of the headers, either 'request' or 'response'
*
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-response-header
*
* @see https://conventions.sentry.dev/attributes/http/#http-request-header-key
* @see https://conventions.sentry.dev/attributes/http/#http-response-header-key
*/
function httpHeadersToSpanAttributes(headers, dataCollection, lifecycle = "request") {
const headerBehavior = lifecycle === "request" ? dataCollection.httpHeaders.request : dataCollection.httpHeaders.response;
const cookieBehavior = dataCollection.cookies;
const prefix = `http.${lifecycle}.header.`;
const spanAttributes = {};
try {
const regularHeaders = {};
for (const [key, value] of Object.entries(headers)) {
if (value == null) continue;
const lowerKey = key.toLowerCase();
if (lowerKey === "cookie" || lowerKey === "set-cookie") {
if (cookieBehavior === false) continue;
const cookies = parseCookieHeader(value, lowerKey);
spanAttributes[`${prefix}${lowerKey}`] = cookies.length ? filterCookiePairs(cookies, cookieBehavior) : [FILTERED_VALUE];
} else {
if (headerBehavior === false) continue;
if (Array.isArray(value)) regularHeaders[lowerKey] = value.filter((v) => v != null).map((v) => String(v));
else if (typeof value === "string") regularHeaders[lowerKey] = [value];
}
}
if (headerBehavior !== false) for (const [headerKey, headerValues] of Object.entries(regularHeaders)) spanAttributes[`${prefix}${headerKey}`] = shouldFilterDataKey(headerKey, headerBehavior) ? [FILTERED_VALUE] : headerValues;
} catch {}
return spanAttributes;
}
/** Formats cookie pairs as `name=value` span attribute values, with sensitive values replaced. */
function filterCookiePairs(cookies, cookieBehavior) {
return cookies.map(([cookieKey, cookieValue]) => {
if (cookieKey === "") return FILTERED_VALUE;
return shouldFilterDataKey(cookieKey, cookieBehavior, SENSITIVE_COOKIE_NAME_SNIPPETS) ? `${cookieKey}=${FILTERED_VALUE}` : `${cookieKey}=${cookieValue}`;
});
}
/** Extract the query params from an URL. */
function extractQueryParamsFromUrl(url) {
if (!url) return;
try {
return getUrlQuery(new URL(url, "http://s.io").search);
} catch {
return;
}
}
/**
* Read the `content-length` header as a number, if it holds a valid one.
*
* `content-length` is the encoded (on-the-wire) body size whether or not a `content-encoding` is
* applied, so it maps to `http.request.body.size` / `http.response.body.size`. The decoded body size
* cannot be derived from it.
*/
function getContentLengthFromHeaders(headers) {
const contentLength = headers["content-length"];
if (typeof contentLength !== "string") return;
const length = parseInt(contentLength, 10);
return length >= 0 ? length : void 0;
}
export { MAX_BODY_BYTE_LENGTH, captureBodyFromWinterCGRequest, extractQueryParamsFromUrl, filterCookiePairs, getContentLengthFromHeaders, getHostFromHeaders, getMaxBodyByteLength, headersToDict, httpHeadersToSpanAttributes, httpRequestToRequestData, winterCGHeadersToDict, winterCGRequestToRequestData };
//# sourceMappingURL=request.js.map