Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Device manager - record device client information on app start (PSG-633) #9314

Merged
merged 8 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from 7 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
19 changes: 19 additions & 0 deletions src/DeviceListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ import { isSecureBackupRequired } from './utils/WellKnownUtils';
import { ActionPayload } from "./dispatcher/payloads";
import { Action } from "./dispatcher/actions";
import { isLoggedIn } from "./utils/login";
import SdkConfig from "./SdkConfig";
import PlatformPeg from "./PlatformPeg";
import { recordClientInformation } from "./utils/device/clientInformation";

const KEY_BACKUP_POLL_INTERVAL = 5 * 60 * 1000;

Expand Down Expand Up @@ -78,6 +81,7 @@ export default class DeviceListener {
MatrixClientPeg.get().on(RoomStateEvent.Events, this.onRoomStateEvents);
this.dispatcherRef = dis.register(this.onAction);
this.recheck();
this.recordClientInformation();
}

public stop() {
Expand Down Expand Up @@ -200,6 +204,7 @@ export default class DeviceListener {
private onAction = ({ action }: ActionPayload) => {
if (action !== Action.OnLoggedIn) return;
this.recheck();
this.recordClientInformation();
};

// The server doesn't tell us when key backup is set up, so we poll
Expand Down Expand Up @@ -343,4 +348,18 @@ export default class DeviceListener {
dis.dispatch({ action: Action.ReportKeyBackupNotEnabled });
}
};

private recordClientInformation = async () => {
try {
await recordClientInformation(
MatrixClientPeg.get(),
SdkConfig.get(),
PlatformPeg.get(),
);
} catch (error) {
// this is a best effort operation
// log the error without rethrowing
logger.error('Failed to record client information', error);
}
};
}
60 changes: 60 additions & 0 deletions src/utils/device/clientInformation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { MatrixClient } from "matrix-js-sdk/src/client";

import BasePlatform from "../../BasePlatform";
import { IConfigOptions } from "../../IConfigOptions";

const formatUrl = (): string | undefined => {
// don't record url for electron clients
if (window.electron) {
return undefined;
}

// strip query-string and fragment from uri
const url = new URL(window.location.href);

return [
url.host,
url.pathname.replace(/\/$/, ""), // Remove trailing slash if present
].join("");
};

const getClientInformationEventType = (deviceId: string): string =>
`io.element.matrix_client_information.${deviceId}`;

/**
* Record extra client information for the current device
* https://github.com/vector-im/element-meta/blob/develop/spec/matrix_client_information.md
t3chguy marked this conversation as resolved.
Show resolved Hide resolved
*/
export const recordClientInformation = async (
matrixClient: MatrixClient,
sdkConfig: IConfigOptions,
platform: BasePlatform,
): Promise<void> => {
const deviceId = matrixClient.getDeviceId();
const { brand } = sdkConfig;
const version = await platform.getAppVersion();
const type = getClientInformationEventType(deviceId);
const url = formatUrl();

await matrixClient.setAccountData(type, {
name: brand,
version,
url,
});
};
50 changes: 50 additions & 0 deletions test/DeviceListener-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ limitations under the License.
import { EventEmitter } from "events";
import { mocked } from "jest-mock";
import { Room } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";

import DeviceListener from "../src/DeviceListener";
import { MatrixClientPeg } from "../src/MatrixClientPeg";
Expand All @@ -27,6 +28,7 @@ import * as BulkUnverifiedSessionsToast from "../src/toasts/BulkUnverifiedSessio
import { isSecretStorageBeingAccessed } from "../src/SecurityManager";
import dis from "../src/dispatcher/dispatcher";
import { Action } from "../src/dispatcher/actions";
import { mockPlatformPeg } from "./test-utils";

// don't litter test console with logs
jest.mock("matrix-js-sdk/src/logger");
Expand All @@ -40,6 +42,8 @@ jest.mock("../src/SecurityManager", () => ({
isSecretStorageBeingAccessed: jest.fn(), accessSecretStorage: jest.fn(),
}));

const deviceId = 'my-device-id';

class MockClient extends EventEmitter {
getUserId = jest.fn();
getKeyBackupVersion = jest.fn().mockResolvedValue(undefined);
Expand All @@ -57,6 +61,8 @@ class MockClient extends EventEmitter {
downloadKeys = jest.fn();
isRoomEncrypted = jest.fn();
getClientWellKnown = jest.fn();
getDeviceId = jest.fn().mockReturnValue(deviceId);
setAccountData = jest.fn();
}
const mockDispatcher = mocked(dis);
const flushPromises = async () => await new Promise(process.nextTick);
Expand All @@ -75,6 +81,9 @@ describe('DeviceListener', () => {

beforeEach(() => {
jest.resetAllMocks();
mockPlatformPeg({
getAppVersion: jest.fn().mockResolvedValue('1.2.3'),
});
mockClient = new MockClient();
jest.spyOn(MatrixClientPeg, 'get').mockReturnValue(mockClient);
});
Expand All @@ -86,6 +95,47 @@ describe('DeviceListener', () => {
return instance;
};

describe('client information', () => {
it('saves client information on start', async () => {
await createAndStart();

expect(mockClient.setAccountData).toHaveBeenCalledWith(
`io.element.matrix_client_information.${deviceId}`,
{ name: 'Element', url: 'localhost', version: '1.2.3' },
);
});

it('catches error and logs when saving client information fails', async () => {
const errorLogSpy = jest.spyOn(logger, 'error');
const error = new Error('oups');
mockClient.setAccountData.mockRejectedValue(error);

// doesn't throw
await createAndStart();

expect(errorLogSpy).toHaveBeenCalledWith(
'Failed to record client information',
error,
);
});

it('saves client information on logged in action', async () => {
const instance = await createAndStart();

mockClient.setAccountData.mockClear();

// @ts-ignore calling private function
instance.onAction({ action: Action.OnLoggedIn });

await flushPromises();

expect(mockClient.setAccountData).toHaveBeenCalledWith(
`io.element.matrix_client_information.${deviceId}`,
{ name: 'Element', url: 'localhost', version: '1.2.3' },
);
});
});

describe('recheck', () => {
it('does nothing when cross signing feature is not supported', async () => {
mockClient.doesServerSupportUnstableFeature.mockResolvedValue(false);
Expand Down
86 changes: 86 additions & 0 deletions test/utils/device/clientInformation-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import BasePlatform from "../../../src/BasePlatform";
import { IConfigOptions } from "../../../src/IConfigOptions";
import { recordClientInformation } from "../../../src/utils/device/clientInformation";
import { getMockClientWithEventEmitter } from "../../test-utils";

describe('recordClientInformation()', () => {
const deviceId = 'my-device-id';
const version = '1.2.3';
const isElectron = window.electron;

const mockClient = getMockClientWithEventEmitter({
getDeviceId: jest.fn().mockReturnValue(deviceId),
setAccountData: jest.fn(),
});

const sdkConfig: IConfigOptions = {
brand: 'Test Brand',
element_call: { url: '', use_exclusively: false },
};

const platform = {
getAppVersion: jest.fn().mockResolvedValue(version),
} as unknown as BasePlatform;

beforeEach(() => {
jest.clearAllMocks();
window.electron = false;
});

afterAll(() => {
// restore global
window.electron = isElectron;
});

it('saves client information without url for electron clients', async () => {
window.electron = true;

await recordClientInformation(
mockClient,
sdkConfig,
platform,
);

expect(mockClient.setAccountData).toHaveBeenCalledWith(
`io.element.matrix_client_information.${deviceId}`,
{
name: sdkConfig.brand,
version,
url: undefined,
},
);
});

it('saves client information with url for non-electron clients', async () => {
await recordClientInformation(
mockClient,
sdkConfig,
platform,
);

expect(mockClient.setAccountData).toHaveBeenCalledWith(
`io.element.matrix_client_information.${deviceId}`,
{
name: sdkConfig.brand,
version,
url: 'localhost',
},
);
});
});