Skip to content

fix(tracing): Baggage parsing fails when input is not of type string #5276

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

Merged
merged 5 commits into from
Jun 21, 2022
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
2 changes: 1 addition & 1 deletion packages/node/src/integrations/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function _createWrappedRequestMethodFactory(
`[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to ${requestUrl}: `,
);

const headerBaggageString = requestOptions.headers && (requestOptions.headers.baggage as string);
const headerBaggageString = requestOptions.headers && requestOptions.headers.baggage;

requestOptions.headers = {
...requestOptions.headers,
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type {} from './globals';
export type { Hub } from './hub';
export type { Integration, IntegrationClass } from './integration';
export type { Mechanism } from './mechanism';
export type { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';
export type { ExtractedNodeRequestData, HttpHeaderValue, Primitive, WorkerLocation } from './misc';
export type { ClientOptions, Options } from './options';
export type { Package } from './package';
export type { PolymorphicEvent } from './polymorphics';
Expand Down
2 changes: 2 additions & 0 deletions packages/types/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@ export interface WorkerLocation {
}

export type Primitive = number | string | boolean | bigint | symbol | null | undefined;

export type HttpHeaderValue = string | string[] | number | null;
42 changes: 32 additions & 10 deletions packages/utils/src/baggage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Baggage, BaggageObj, TraceparentData } from '@sentry/types';
import { HttpHeaderValue } from '@sentry/types';

import { isString } from './is';
import { logger } from './logger';

export const BAGGAGE_HEADER_NAME = 'baggage';
Expand Down Expand Up @@ -89,9 +91,28 @@ export function serializeBaggage(baggage: Baggage): string {
}, baggage[1]);
}

/** Parse a baggage header from a string and return a Baggage object */
export function parseBaggageString(inputBaggageString: string): Baggage {
return inputBaggageString.split(',').reduce(
/** Parse a baggage header from a string or a string array and return a Baggage object */
export function parseBaggageHeader(inputBaggageValue: HttpHeaderValue): Baggage {
// Adding this check here because we got reports of this function failing due to the input value
// not being a string. This debug log might help us determine what's going on here.
if ((!Array.isArray(inputBaggageValue) && !isString(inputBaggageValue)) || typeof inputBaggageValue === 'number') {
__DEBUG_BUILD__ &&
logger.warn(
'[parseBaggageHeader] Received input value of incompatible type: ',
typeof inputBaggageValue,
inputBaggageValue,
);

// Gonna early-return an empty baggage object so that we don't fail later on
return createBaggage({}, '');
}

const baggageEntries = (isString(inputBaggageValue) ? inputBaggageValue : inputBaggageValue.join(','))
.split(',')
.map(entry => entry.trim())
.filter(entry => entry !== '');
Comment on lines +110 to +113
Copy link
Contributor

Choose a reason for hiding this comment

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

I find this somehow very satisfying. :)


return baggageEntries.reduce(
([baggageObj, baggageString], curr) => {
const [key, val] = curr.split('=');
if (SENTRY_BAGGAGE_KEY_PREFIX_REGEX.test(key)) {
Expand Down Expand Up @@ -122,16 +143,17 @@ export function parseBaggageString(inputBaggageString: string): Baggage {
* it would only affect parts of the sentry baggage (@see Baggage interface).
*
* @param incomingBaggage the baggage header of the incoming request that might contain sentry entries
* @param headerBaggageString possibly existing baggage header string added from a third party to request headers
* @param thirdPartyBaggageHeader possibly existing baggage header string or string[] added from a third
* party to the request headers
*
* @return a merged and serialized baggage string to be propagated with the outgoing request
*/
export function mergeAndSerializeBaggage(incomingBaggage?: Baggage, headerBaggageString?: string): string {
if (!incomingBaggage && !headerBaggageString) {
export function mergeAndSerializeBaggage(incomingBaggage?: Baggage, thirdPartyBaggageHeader?: HttpHeaderValue): string {
if (!incomingBaggage && !thirdPartyBaggageHeader) {
return '';
}

const headerBaggage = (headerBaggageString && parseBaggageString(headerBaggageString)) || undefined;
const headerBaggage = (thirdPartyBaggageHeader && parseBaggageHeader(thirdPartyBaggageHeader)) || undefined;
const thirdPartyHeaderBaggage = headerBaggage && getThirdPartyBaggage(headerBaggage);

const finalBaggage = createBaggage(
Expand All @@ -150,14 +172,14 @@ export function mergeAndSerializeBaggage(incomingBaggage?: Baggage, headerBaggag
*
* Extracted this logic to a function because it's duplicated in a lot of places.
*
* @param rawBaggageString
* @param rawBaggageValue
* @param sentryTraceHeader
*/
export function parseBaggageSetMutability(
rawBaggageString: string | false | undefined | null,
rawBaggageValue: HttpHeaderValue | false | undefined,
sentryTraceHeader: TraceparentData | string | false | undefined | null,
): Baggage {
const baggage = parseBaggageString(rawBaggageString || '');
const baggage = parseBaggageHeader(rawBaggageValue || '');
if (!isSentryBaggageEmpty(baggage) || (sentryTraceHeader && isSentryBaggageEmpty(baggage))) {
setBaggageImmutable(baggage);
}
Expand Down
33 changes: 29 additions & 4 deletions packages/utils/test/baggage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
isBaggageMutable,
isSentryBaggageEmpty,
mergeAndSerializeBaggage,
parseBaggageHeader,
parseBaggageSetMutability,
parseBaggageString,
serializeBaggage,
setBaggageImmutable,
setBaggageValue,
Expand Down Expand Up @@ -97,9 +97,10 @@ describe('Baggage', () => {
});
});

describe('parseBaggageString', () => {
describe('parseBaggageHeader', () => {
it.each([
['parses an empty string', '', createBaggage({})],
['parses a blank string', ' ', createBaggage({})],
[
'parses sentry values into baggage',
'sentry-environment=production,sentry-release=10.0.2',
Expand All @@ -113,8 +114,32 @@ describe('Baggage', () => {
'userId=alice,serverNode=DF%2028,isProduction=false',
),
],
])('%s', (_: string, baggageString, baggage) => {
expect(parseBaggageString(baggageString)).toEqual(baggage);
[
'parses arbitrary baggage headers from string with empty and blank entries',
'userId=alice, serverNode=DF%2028 , isProduction=false, ,,sentry-environment=production,,sentry-release=10.0.2',
createBaggage(
{ environment: 'production', release: '10.0.2' },
'userId=alice,serverNode=DF%2028,isProduction=false',
),
],
[
'parses a string array',
['userId=alice', 'sentry-environment=production', 'foo=bar'],
createBaggage({ environment: 'production' }, 'userId=alice,foo=bar'),
],
[
'parses a string array with items containing multiple entries',
['userId=alice, userName=bob', 'sentry-environment=production,sentry-release=1.0.1', 'foo=bar'],
createBaggage({ environment: 'production', release: '1.0.1' }, 'userId=alice,userName=bob,foo=bar'),
],
[
'parses a string array with empty/blank entries',
['', 'sentry-environment=production,sentry-release=1.0.1', ' ', 'foo=bar'],
createBaggage({ environment: 'production', release: '1.0.1' }, 'foo=bar'),
],
['ignorese other input types than string and string[]', 42, createBaggage({}, '')],
])('%s', (_: string, baggageValue, baggage) => {
expect(parseBaggageHeader(baggageValue)).toEqual(baggage);
});
});

Expand Down