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
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,16 @@ jest.mock('@console/shared/src/hooks/useUserPreference', () => ({

jest.mock('@console/shared/src/hooks/useUser', () => ({
useUser: jest.fn(() => ({
user: {},
userResource: {},
user: {
username: 'shadowman',
},
userResource: {
metadata: {
annotations: {
'toolchain.dev.openshift.com/sso-user-id': 'sandbox-user-id-123',
},
},
},
userResourceLoaded: true,
userResourceError: null,
username: 'testuser',
Expand All @@ -30,22 +38,15 @@ jest.mock('@console/shared/src/hooks/useUser', () => ({
})),
}));

const mockUserResource = {};

const exampleReturnValue = {
accountMail: undefined,
accountMailDomain: '',
clusterId: undefined,
clusterType: undefined,
consoleVersion: undefined,
organizationId: undefined,
path: undefined,
userResource: mockUserResource,
};

jest.mock('@console/internal/components/utils/k8s-get-hook', () => ({
useK8sGet: () => [mockUserResource, true],
}));

const mockUserPreference = useUserPreference as jest.Mock;

const useResolvedExtensionsMock = useResolvedExtensions as jest.Mock;
Expand Down Expand Up @@ -220,6 +221,7 @@ describe('useTelemetry', () => {
...exampleReturnValue,
clusterType: 'DEVSANDBOX',
consoleVersion: 'x.y.z',
sandboxUserId: 'sandbox-user-id-123',
});
});

Expand Down Expand Up @@ -346,4 +348,52 @@ describe('useTelemetry', () => {
fireTelemetryEvent('test 11');
expect(listener).toHaveBeenCalledTimes(1);
});

it('anonymizes email to only return the domain', () => {
const email = 'shadowman@redhat.com';
const expectedDomain = 'redhat.com';

window.SERVER_FLAGS = {
...originServerFlags,
telemetry: {
ACCOUNT_MAIL: email,
},
};
updateClusterPropertiesFromTests();
const { result } = renderHook(() => useTelemetry());
const fireTelemetryEvent = result.current;
fireTelemetryEvent('test 12');
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith('test 12', {
...exampleReturnValue,
accountMailDomain: expectedDomain,
});

// assert PII is not sent
const callArgs = listener.mock.calls[0][1];
expect(callArgs.user).toBeUndefined();
expect(callArgs.userResource).toBeUndefined();
expect(callArgs.accountMail).toBeUndefined();
expect(callArgs.sandboxUserId).toBeUndefined();
});

it.each(['invalid-email', 'shadowman@', 'red@hat@redhat.com', '@@', ''])(
'should not extract domains from invalid emails (%s)',
(email) => {
window.SERVER_FLAGS = {
...originServerFlags,
telemetry: {
ACCOUNT_MAIL: email,
},
};
updateClusterPropertiesFromTests();
const { result } = renderHook(() => useTelemetry());
const fireTelemetryEvent = result.current;
fireTelemetryEvent('test 12');
expect(listener).toHaveBeenCalledWith('test 12', {
...exampleReturnValue,
accountMailDomain: '',
});
},
);
});
36 changes: 31 additions & 5 deletions frontend/packages/console-shared/src/hooks/useTelemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ export interface ClusterProperties {
clusterType?: string;
consoleVersion?: string;
organizationId?: string;
accountMail?: string;
accountMailDomain?: string;
}

export type TelemetryEventProperties = {
user?: UserInfo;
userResource?: UserKind;
/** Only sent if in a sandbox cluster */
sandboxUserId?: string;
} & ClusterProperties &
Record<string, any>;

Expand All @@ -35,6 +36,11 @@ export interface TelemetryEvent {

let telemetryEvents: TelemetryEvent[] = [];

const getEmailDomain = (email: string = ''): string => {
const emailParts = email.split('@');
return emailParts.length === 2 ? emailParts[1] : '';
};

export const getClusterProperties = () => {
const clusterProperties: ClusterProperties = {};
clusterProperties.clusterId = window.SERVER_FLAGS.telemetry?.CLUSTER_ID;
Expand All @@ -46,7 +52,7 @@ export const getClusterProperties = () => {
clusterProperties.consoleVersion =
window.SERVER_FLAGS.releaseVersion || window.SERVER_FLAGS.consoleVersion;
clusterProperties.organizationId = window.SERVER_FLAGS.telemetry?.ORGANIZATION_ID;
clusterProperties.accountMail = window.SERVER_FLAGS.telemetry?.ACCOUNT_MAIL;
clusterProperties.accountMailDomain = getEmailDomain(window.SERVER_FLAGS.telemetry?.ACCOUNT_MAIL);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't we use some email parser to avoid processing strings which are not proper email addresses?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'd like to avoid introducing new dependencies for this given the need for a backport. This is also already good enough for non-emails, e.g., redhat.com or matt@hicks@redhat.com this would return an empty string

return clusterProperties;
};

Expand All @@ -66,6 +72,20 @@ let clusterProperties = getClusterProperties();

export const updateClusterPropertiesFromTests = () => (clusterProperties = getClusterProperties());

const injectSandboxProperties = (
properties: TelemetryEventProperties,
userResource: UserKind,
): TelemetryEventProperties => {
if (clusterProperties.clusterType === 'DEVSANDBOX') {
return {
...properties,
sandboxUserId:
userResource?.metadata?.annotations?.['toolchain.dev.openshift.com/sso-user-id'],
};
}
return properties;
};

export const useTelemetry = () => {
// TODO use usePluginInfo() hook to tell whether all dynamic plugins have been processed
// to avoid firing telemetry events multiple times whenever a dynamic plugin loads asynchronously
Expand All @@ -89,7 +109,10 @@ export const useTelemetry = () => {
userResourceIsLoaded
) {
telemetryEvents.forEach(({ eventType, event }) => {
extensions.forEach((e) => e.properties.listener(eventType, { ...event, userResource }));
// Sends the telemetry event to all the listeners
extensions.forEach((e) =>
e.properties.listener(eventType, injectSandboxProperties(event, userResource)),
);
});
telemetryEvents = [];
}
Expand Down Expand Up @@ -120,7 +143,10 @@ export const useTelemetry = () => {
return;
}

extensions.forEach((e) => e.properties.listener(eventType, { ...event, userResource }));
// Sends the telemetry event to all the listeners
extensions.forEach((e) =>
e.properties.listener(eventType, injectSandboxProperties(event, userResource)),
);
},
[extensions, currentUserPreferenceTelemetryValue, userResource, userResourceIsLoaded],
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const eventListener: TelemetryEventListener = async (
switch (eventType) {
case 'identify':
{
const { user, userResource, ...otherProperties }: TelemetryEventProperties = properties;
const { user, sandboxUserId, ...otherProperties }: TelemetryEventProperties = properties;
const clusterId = otherProperties?.clusterId;
const organizationId = otherProperties?.organizationId;
const username = user?.username;
Expand All @@ -65,8 +65,7 @@ export const eventListener: TelemetryEventListener = async (

// anonymize user ID if cluster is not a DEVSANDBOX cluster
if (getClusterProperties().clusterType === 'DEVSANDBOX') {
processedUserId =
userResource?.metadata?.annotations?.['toolchain.dev.openshift.com/sso-user-id'];
processedUserId = sandboxUserId;
} else {
processedUserId = await anonymizeId(userId);
}
Comment on lines 67 to 71
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add fallback when sandbox ID is missing in DEVSANDBOX identify path.

At Line 68, processedUserId is set directly from optional sandboxUserId. If the annotation is absent, analytics.identify (Line 81) receives an invalid identifier. Fall back to anonymized userId when sandboxUserId is empty.

Suggested fix
-          if (getClusterProperties().clusterType === 'DEVSANDBOX') {
-            processedUserId = sandboxUserId;
-          } else {
-            processedUserId = await anonymizeId(userId);
-          }
+          if (getClusterProperties().clusterType === 'DEVSANDBOX' && sandboxUserId) {
+            processedUserId = sandboxUserId;
+          } else {
+            processedUserId = await anonymizeId(userId);
+          }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (getClusterProperties().clusterType === 'DEVSANDBOX') {
processedUserId =
userResource?.metadata?.annotations?.['toolchain.dev.openshift.com/sso-user-id'];
processedUserId = sandboxUserId;
} else {
processedUserId = await anonymizeId(userId);
}
if (getClusterProperties().clusterType === 'DEVSANDBOX' && sandboxUserId) {
processedUserId = sandboxUserId;
} else {
processedUserId = await anonymizeId(userId);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/packages/console-telemetry-plugin/src/listeners/segment.ts` around
lines 67 - 71, The DEVSANDBOX branch sets processedUserId directly to the
optional sandboxUserId which can be empty; update the branch so processedUserId
uses sandboxUserId when present otherwise falls back to the anonymized user id
by calling anonymizeId(userId). Locate the logic around getClusterProperties(),
processedUserId, and sandboxUserId and ensure analytics.identify receives a
non-empty id by defaulting to await anonymizeId(userId) when sandboxUserId is
falsy.

Expand Down