Skip to content

Commit 6e9740d

Browse files
authored
Use client logger in more places (crypto code) (#4900)
* Use client logger for `RustBackupManager` * use client logger in `CrossSigningIdentity` * use client logger in `OutgoingRequestProcessor` * RoomEncryptor: use correct logger for logDuration use the logger for this specific event, rather than the more general one for the room * Use client logger in `RoomEncryptor`
1 parent 70257e0 commit 6e9740d

10 files changed

+107
-89
lines changed

spec/unit/rust-crypto/CrossSigningIdentity.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
2020
import { CrossSigningIdentity } from "../../../src/rust-crypto/CrossSigningIdentity";
2121
import { type OutgoingRequestProcessor } from "../../../src/rust-crypto/OutgoingRequestProcessor";
2222
import { type ServerSideSecretStorage } from "../../../src/secret-storage";
23+
import { logger } from "../../../src/logger.ts";
2324

2425
describe("CrossSigningIdentity", () => {
2526
describe("bootstrapCrossSigning", () => {
@@ -55,7 +56,7 @@ describe("CrossSigningIdentity", () => {
5556
store: jest.fn(),
5657
} as unknown as Mocked<ServerSideSecretStorage>;
5758

58-
crossSigning = new CrossSigningIdentity(olmMachine, outgoingRequestProcessor, secretStorage);
59+
crossSigning = new CrossSigningIdentity(logger, olmMachine, outgoingRequestProcessor, secretStorage);
5960
});
6061

6162
it("should do nothing if keys are present on-device and in secret storage", async () => {

spec/unit/rust-crypto/KeyClaimManager.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ describe("KeyClaimManager", () => {
5353
markRequestAsSent: jest.fn(),
5454
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
5555

56-
const outgoingRequestProcessor = new OutgoingRequestProcessor(olmMachine, httpApi);
56+
const outgoingRequestProcessor = new OutgoingRequestProcessor(logger, olmMachine, httpApi);
5757

5858
keyClaimManager = new KeyClaimManager(olmMachine, outgoingRequestProcessor);
5959
});

spec/unit/rust-crypto/OutgoingRequestProcessor.spec.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
type UIAuthCallback,
4141
} from "../../../src";
4242
import { OutgoingRequestProcessor } from "../../../src/rust-crypto/OutgoingRequestProcessor";
43+
import { logger } from "../../../src/logger.ts";
4344

4445
describe("OutgoingRequestProcessor", () => {
4546
/** the OutgoingRequestProcessor implementation under test */
@@ -76,7 +77,7 @@ describe("OutgoingRequestProcessor", () => {
7677
markRequestAsSent: jest.fn(),
7778
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
7879

79-
processor = new OutgoingRequestProcessor(olmMachine, httpApi);
80+
processor = new OutgoingRequestProcessor(logger, olmMachine, httpApi);
8081
});
8182

8283
/* simple requests that map directly to the request body */
@@ -293,7 +294,7 @@ describe("OutgoingRequestProcessor", () => {
293294
return await authRequestResultResolvers.promise;
294295
},
295296
} as unknown as Mocked<MatrixHttpApi<IHttpOpts & { onlyData: true }>>;
296-
processor = new OutgoingRequestProcessor(olmMachine, mockHttpApi);
297+
processor = new OutgoingRequestProcessor(logger, olmMachine, mockHttpApi);
297298
});
298299

299300
// build a request
@@ -325,7 +326,7 @@ describe("OutgoingRequestProcessor", () => {
325326
onlyData: true,
326327
});
327328

328-
processor = new OutgoingRequestProcessor(olmMachine, httpApi);
329+
processor = new OutgoingRequestProcessor(logger, olmMachine, httpApi);
329330
});
330331

331332
afterEach(() => {

spec/unit/rust-crypto/RoomEncryptor.spec.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
AllDevicesIsolationMode,
3737
OnlySignedDevicesIsolationMode,
3838
} from "../../../src/crypto-api";
39+
import { logger } from "../../../src/logger.ts";
3940

4041
describe("RoomEncryptor", () => {
4142
describe("History Visibility", () => {
@@ -108,6 +109,7 @@ describe("RoomEncryptor", () => {
108109
} as unknown as Mocked<Room>;
109110

110111
roomEncryptor = new RoomEncryptor(
112+
logger,
111113
mockOlmMachine,
112114
mockKeyClaimManager,
113115
mockOutgoingRequestManager,

spec/unit/rust-crypto/backup.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { type OutgoingRequestProcessor } from "../../../src/rust-crypto/Outgoing
88
import * as testData from "../../test-utils/test-data";
99
import * as TestData from "../../test-utils/test-data";
1010
import { RustBackupManager, type KeyBackup } from "../../../src/rust-crypto/backup";
11+
import { logger } from "../../../src/logger.ts";
1112

1213
describe("Upload keys to backup", () => {
1314
/** The backup manager under test */
@@ -63,7 +64,7 @@ describe("Upload keys to backup", () => {
6364
makeOutgoingRequest: jest.fn(),
6465
} as unknown as Mocked<OutgoingRequestProcessor>;
6566

66-
rustBackupManager = new RustBackupManager(mockOlmMachine, httpAPi, outgoingRequestProcessor);
67+
rustBackupManager = new RustBackupManager(logger, mockOlmMachine, httpAPi, outgoingRequestProcessor);
6768

6869
fetchMock.get("path:/_matrix/client/v3/room_keys/version", testData.SIGNED_BACKUP_DATA);
6970
});

src/rust-crypto/CrossSigningIdentity.ts

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import {
2222

2323
import type * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
2424
import { type BootstrapCrossSigningOpts } from "../crypto-api/index.ts";
25-
import { logger } from "../logger.ts";
25+
import { type Logger } from "../logger.ts";
2626
import { type OutgoingRequestProcessor } from "./OutgoingRequestProcessor.ts";
2727
import { type UIAuthCallback } from "../interactive-auth.ts";
2828
import { type ServerSideSecretStorage } from "../secret-storage.ts";
@@ -33,6 +33,7 @@ import { type ServerSideSecretStorage } from "../secret-storage.ts";
3333
*/
3434
export class CrossSigningIdentity {
3535
public constructor(
36+
private readonly logger: Logger,
3637
private readonly olmMachine: OlmMachine,
3738
private readonly outgoingRequestProcessor: OutgoingRequestProcessor,
3839
private readonly secretStorage: ServerSideSecretStorage,
@@ -61,7 +62,7 @@ export class CrossSigningIdentity {
6162
olmDeviceStatus.hasMaster && olmDeviceStatus.hasUserSigning && olmDeviceStatus.hasSelfSigning;
6263

6364
// Log all relevant state for easier parsing of debug logs.
64-
logger.log("bootstrapCrossSigning: starting", {
65+
this.logger.debug("bootstrapCrossSigning: starting", {
6566
setupNewCrossSigning: opts.setupNewCrossSigning,
6667
olmDeviceHasMaster: olmDeviceStatus.hasMaster,
6768
olmDeviceHasUserSigning: olmDeviceStatus.hasUserSigning,
@@ -71,23 +72,23 @@ export class CrossSigningIdentity {
7172

7273
if (olmDeviceHasKeys) {
7374
if (!(await this.secretStorage.hasKey())) {
74-
logger.warn(
75+
this.logger.warn(
7576
"bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.",
7677
);
7778
// the keys should get uploaded to 4S once that is set up.
7879
} else if (!privateKeysInSecretStorage) {
7980
// the device has the keys but they are not in 4S, so update it
80-
logger.log("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage");
81+
this.logger.debug("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage");
8182
await this.exportCrossSigningKeysToStorage();
8283
} else {
83-
logger.log(
84+
this.logger.debug(
8485
"bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing",
8586
);
8687
}
8788
} /* (!olmDeviceHasKeys) */ else {
8889
if (privateKeysInSecretStorage) {
8990
// they are in 4S, so import from there
90-
logger.log(
91+
this.logger.debug(
9192
"bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available " +
9293
"in secret storage, reading storage and caching locally",
9394
);
@@ -116,7 +117,7 @@ export class CrossSigningIdentity {
116117
device.free();
117118
}
118119
} else {
119-
logger.log(
120+
this.logger.debug(
120121
"bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys",
121122
);
122123
await this.resetCrossSigning(opts.authUploadDeviceSigningKeys);
@@ -125,7 +126,7 @@ export class CrossSigningIdentity {
125126

126127
// TODO: we might previously have bootstrapped cross-signing but not completed uploading the keys to the
127128
// server -- in which case we should call OlmDevice.bootstrap_cross_signing. How do we know?
128-
logger.log("bootstrapCrossSigning: complete");
129+
this.logger.debug("bootstrapCrossSigning: complete");
129130
}
130131

131132
/** Reset our cross-signing keys
@@ -142,19 +143,19 @@ export class CrossSigningIdentity {
142143

143144
// If 4S is configured we need to update it.
144145
if (!(await this.secretStorage.hasKey())) {
145-
logger.warn(
146+
this.logger.warn(
146147
"resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet.",
147148
);
148149
// the keys should get uploaded to 4S once that is set up.
149150
} else {
150151
// Update 4S before uploading cross-signing keys, to stay consistent with legacy that asks
151152
// 4S passphrase before asking for account password.
152153
// Ultimately should be made atomic and resistant to forgotten password/passphrase.
153-
logger.log("resetCrossSigning: exporting private keys to secret storage");
154+
this.logger.debug("resetCrossSigning: exporting private keys to secret storage");
154155
await this.exportCrossSigningKeysToStorage();
155156
}
156157

157-
logger.log("resetCrossSigning: publishing public keys to server");
158+
this.logger.debug("resetCrossSigning: publishing public keys to server");
158159
for (const req of [
159160
outgoingRequests.uploadKeysRequest,
160161
outgoingRequests.uploadSigningKeysRequest,
@@ -178,17 +179,17 @@ export class CrossSigningIdentity {
178179
if (exported?.masterKey) {
179180
await this.secretStorage.store("m.cross_signing.master", exported.masterKey);
180181
} else {
181-
logger.error(`Cannot export MSK to secret storage, private key unknown`);
182+
this.logger.error(`Cannot export MSK to secret storage, private key unknown`);
182183
}
183184
if (exported?.self_signing_key) {
184185
await this.secretStorage.store("m.cross_signing.self_signing", exported.self_signing_key);
185186
} else {
186-
logger.error(`Cannot export SSK to secret storage, private key unknown`);
187+
this.logger.error(`Cannot export SSK to secret storage, private key unknown`);
187188
}
188189
if (exported?.userSigningKey) {
189190
await this.secretStorage.store("m.cross_signing.user_signing", exported.userSigningKey);
190191
} else {
191-
logger.error(`Cannot export USK to secret storage, private key unknown`);
192+
this.logger.error(`Cannot export USK to secret storage, private key unknown`);
192193
}
193194
}
194195
}

src/rust-crypto/OutgoingRequestProcessor.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import {
2828
UploadSigningKeysRequest,
2929
} from "@matrix-org/matrix-sdk-crypto-wasm";
3030

31-
import { logger } from "../logger.ts";
31+
import { type Logger } from "../logger.ts";
3232
import { calculateRetryBackoff, type IHttpOpts, type MatrixHttpApi, Method } from "../http-api/index.ts";
3333
import { logDuration, type QueryDict, sleep } from "../utils.ts";
3434
import { type AuthDict, type UIAuthCallback } from "../interactive-auth.ts";
@@ -49,6 +49,7 @@ import { UnstablePrefix as DehydrationUnstablePrefix } from "./DehydratedDeviceM
4949
*/
5050
export class OutgoingRequestProcessor {
5151
public constructor(
52+
private readonly logger: Logger,
5253
private readonly olmMachine: OlmMachine,
5354
private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,
5455
) {}
@@ -100,13 +101,13 @@ export class OutgoingRequestProcessor {
100101
// PutDehydratedDeviceRequest does not implement OutgoingRequest and does not need to be marked as sent.
101102
return;
102103
} else {
103-
logger.warn("Unsupported outgoing message", Object.getPrototypeOf(msg));
104+
this.logger.warn("Unsupported outgoing message", Object.getPrototypeOf(msg));
104105
resp = "";
105106
}
106107

107108
if (msg.id) {
108109
try {
109-
await logDuration(logger, `Mark Request as sent ${msg.type}`, async () => {
110+
await logDuration(this.logger, `Mark Request as sent ${msg.type}`, async () => {
110111
await this.olmMachine.markRequestAsSent(msg.id!, msg.type, resp);
111112
});
112113
} catch (e) {
@@ -116,13 +117,13 @@ export class OutgoingRequestProcessor {
116117
e instanceof Error &&
117118
(e.message === "Attempt to use a moved value" || e.message === "null pointer passed to rust")
118119
) {
119-
logger.log(`Ignoring error '${e.message}': client is likely shutting down`);
120+
this.logger.debug(`Ignoring error '${e.message}': client is likely shutting down`);
120121
} else {
121122
throw e;
122123
}
123124
}
124125
} else {
125-
logger.trace(`Outgoing request type:${msg.type} does not have an ID`);
126+
this.logger.trace(`Outgoing request type:${msg.type} does not have an ID`);
126127
}
127128
}
128129

@@ -143,7 +144,7 @@ export class OutgoingRequestProcessor {
143144
}
144145
}
145146

146-
logger.info(
147+
this.logger.info(
147148
`Sending batch of to-device messages. type=${request.event_type} txnid=${request.txn_id}`,
148149
messageList,
149150
);

src/rust-crypto/RoomEncryptor.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
import { EventType } from "../@types/event.ts";
3030
import { type IContent, type MatrixEvent } from "../models/event.ts";
3131
import { type Room } from "../models/room.ts";
32-
import { type Logger, logger, LogSpan } from "../logger.ts";
32+
import { type Logger, LogSpan } from "../logger.ts";
3333
import { type KeyClaimManager } from "./KeyClaimManager.ts";
3434
import { type RoomMember } from "../models/room-member.ts";
3535
import { HistoryVisibility } from "../@types/partials.ts";
@@ -44,8 +44,6 @@ import { type DeviceIsolationMode, DeviceIsolationModeKind } from "../crypto-api
4444
* @internal
4545
*/
4646
export class RoomEncryptor {
47-
private readonly prefixedLogger: Logger;
48-
4947
/** whether the room members have been loaded and tracked for the first time */
5048
private lazyLoadedMembersResolved = false;
5149

@@ -57,21 +55,21 @@ export class RoomEncryptor {
5755
private currentEncryptionPromise: Promise<void> = Promise.resolve();
5856

5957
/**
58+
* @param prefixedLogger - A logger to use for log messages.
6059
* @param olmMachine - The rust-sdk's OlmMachine
6160
* @param keyClaimManager - Our KeyClaimManager, which manages the queue of one-time-key claim requests
6261
* @param outgoingRequestManager - The OutgoingRequestManager, which manages the queue of outgoing requests.
6362
* @param room - The room we want to encrypt for
6463
* @param encryptionSettings - body of the m.room.encryption event currently in force in this room
6564
*/
6665
public constructor(
66+
private readonly prefixedLogger: Logger,
6767
private readonly olmMachine: OlmMachine,
6868
private readonly keyClaimManager: KeyClaimManager,
6969
private readonly outgoingRequestManager: OutgoingRequestsManager,
7070
private readonly room: Room,
7171
private encryptionSettings: IContent,
7272
) {
73-
this.prefixedLogger = logger.getChild(`[${room.roomId} encryption]`);
74-
7573
// start tracking devices for any users already known to be in this room.
7674
// Do not load members here, would defeat lazy loading.
7775
const members = room.getJoinedMembers();
@@ -212,7 +210,7 @@ export class RoomEncryptor {
212210
// This could end up being racy (if two calls to ensureEncryptionSession happen at the same time), but that's
213211
// not a particular problem, since `OlmMachine.updateTrackedUsers` just adds any users that weren't already tracked.
214212
if (!this.lazyLoadedMembersResolved) {
215-
await logDuration(this.prefixedLogger, "loadMembersIfNeeded: updateTrackedUsers", async () => {
213+
await logDuration(logger, "loadMembersIfNeeded: updateTrackedUsers", async () => {
216214
await this.olmMachine.updateTrackedUsers(members.map((u) => new RustSdkCryptoJs.UserId(u.userId)));
217215
});
218216
logger.debug(`Updated tracked users`);
@@ -229,7 +227,7 @@ export class RoomEncryptor {
229227
// XXX future improvement process only KeysQueryRequests for the users that have never been queried.
230228
logger.debug(`Processing outgoing requests`);
231229

232-
await logDuration(this.prefixedLogger, "doProcessOutgoingRequests", async () => {
230+
await logDuration(logger, "doProcessOutgoingRequests", async () => {
233231
await this.outgoingRequestManager.doProcessOutgoingRequests();
234232
});
235233
} else {
@@ -250,7 +248,7 @@ export class RoomEncryptor {
250248

251249
const userList = members.map((u) => new UserId(u.userId));
252250

253-
await logDuration(this.prefixedLogger, "ensureSessionsForUsers", async () => {
251+
await logDuration(logger, "ensureSessionsForUsers", async () => {
254252
await this.keyClaimManager.ensureSessionsForUsers(logger, userList);
255253
});
256254

@@ -289,7 +287,7 @@ export class RoomEncryptor {
289287
break;
290288
}
291289

292-
await logDuration(this.prefixedLogger, "shareRoomKey", async () => {
290+
await logDuration(logger, "shareRoomKey", async () => {
293291
const shareMessages: ToDeviceRequest[] = await this.olmMachine.shareRoomKey(
294292
new RoomId(this.room.roomId),
295293
// safe to pass without cloning, as it's not reused here (before or after)

0 commit comments

Comments
 (0)